# Prism developer documentation Prism developer documentation, all pages. Each page starts with a line of `=====`, its title, its address and the files it is derived from. ===== Page: Start here Address: https://prism.am/dev/start/ Derived from: crates/modding/src/events.rs, crates/modding/src/manifest.rs, crates/modding/src/lib.rs, crates/themes/src/api.rs, content/mods/sdk/modding.d.ts, apps/desktop/src/app/paths.rs # Start here What you can build for Prism, what each kind needs, the versions to match, where the SDK is, and which page to read for what. Prism is extended by plain files that the game reads from disk. Delete the file or folder and the extension is gone. There is nothing to compile, no account and no key. ## What you can build {#what-you-can-build} | You build | It is | What it does | Start with | | --- | --- | --- | --- | | A **mod** | A folder with a `main.ts`. | Adds to the game: HUD elements, judgement sets, difficulty ratings, library filters, selection tabs, gameplay modifiers, download sources, native effects. | [A first mod](https://prism.am/dev/md/first-mod.md) | | A **skin** | A folder with a `skin.ts` and images. | Sets how the playfield looks: lanes, notes, receptors, lights, and where the HUD elements stand. | [A first skin](https://prism.am/dev/md/first-skin.md) | | A **map script** | A `script.ts` next to a chart. | Animates the playfield of that map while it plays, like an ITG modchart. | [A first map script](https://prism.am/dev/md/first-map-script.md) | | An **editor mod** | A `main.ts` in a folder named `editor-…`. | Adds panels and tools to the map editor. The game itself never loads it. | [Editor mods](https://prism.am/dev/md/guides/editor-mod.md) | | A **theme** | A folder with `theme.json`, `tokens.css`, and optionally `theme.css` and `theme.ts`. | Changes the look and the layout of the menus. It is data: it never runs code while the game draws. | [Themes](https://prism.am/dev/md/themes.md) | | A **client of the online API** | Any program that sends HTTP requests. | Reads charts, boards, ratings and the catalogue from prism.am. Reads need no account. | [The online API](https://prism.am/dev/md/online/api.md) | A mod, a skin and a map script share one API, one engine and one set of limits. What differs is when each one runs and what it may call: see [Concepts](https://prism.am/dev/md/concepts.md#kinds). ## What you need {#requirements} - **A text editor and the game.** Mods, skins and map scripts are TypeScript files that the game runs itself. It transpiles them when it loads them, in an embedded JavaScript engine (QuickJS). You need no Node, no bundler and no build step. - **No manifest file.** A mod, a skin or a map script declares itself in code: `defineMod({ … })`, `defineSkin({ … })` or `defineChart({ … })`, called once at the top level of the entry file. No JSON describes them. (A theme is the exception: its `theme.json` names it.) - **The same `apiVersion` as the game.** Each declaration carries `apiVersion`, and it must be equal to the API version of the game, not lower and not higher. A script that is off by one is refused with a clear message. - **TypeScript, optionally.** The game does not check types. To have your editor and `tsc` catch mistakes, give them the [SDK](#sdk). Install TypeScript with `npm install --global typescript` or run it with `bunx tsc`. See [Tooling](https://prism.am/dev/md/tooling.md#type-check). - **Imports stay inside the folder.** A script can import relative modules of its own folder. It never reaches outside it, and `import()` written as a call is refused. ## Versions {#versions} | What | Version now | Where you write it | What happens on a mismatch | | --- | --- | --- | --- | | Mod, skin and map-script API | **2** | `apiVersion: 2` in `defineMod`, `defineSkin`, `defineChart` | The script does not load: `` `my-mod` requires modding API version 1; this game provides version 2 `` | | Theme contract | **1** | `themeApi` in `theme.json`; absent means 1 | A theme that asks for a newer one is refused with a message | | Package files (`.pvmod`, skin `.zip`) | none | | The declaration inside the package carries the API version | The first line of the SDK file states the version it describes (`// Modding API version 2.`). ## The SDK {#sdk} The SDK is one TypeScript declaration file, generated from the Rust contracts of the game. It types every global (`hud`, `game`, `ctx`, `playfield`…), every event payload and every option. - [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts) is the file to download. It declares 64 functions and 25 events. In the repository it is `content/mods/sdk/modding.d.ts`. - `content/mods/sdk/modding.ts` is an optional module of listening shortcuts and typed models. No example needs it. - [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts) types `theme.ts` of a theme. - The [SDK reference](https://prism.am/dev/md/reference/sdk.md) lists every function and event with its signature and a short note, generated from the same file. A script uses the SDK without importing it: the functions are globals. For `tsc` and your editor, a one-line comment is enough, and it has no effect at run time: ```ts fragment /// log.info("typed"); ``` ## Where your files go {#folders} The data folder of the player is `%LOCALAPPDATA%\Prism\PrismNG\data` (`PrismNG-PBE` on the PBE channel). The environment variable `PRISM_DATA_DIR` replaces it as a whole. | Kind | Folder | Replaced by | | --- | --- | --- | | Mods | `data\mods\\main.ts` | `PRISM_MODS_DIR` | | Skins | `data\skins\\skin.ts` | `PRISM_SKINS_DIR` | | Themes | `data\themes\\theme.json` | `PRISM_THEMES_DIR` | | Map scripts | next to the chart, in the map folder | | The game ships its own mods, skins and themes in folders next to `prism.exe`. Yours are read after them, and never replace them. See [Tooling](https://prism.am/dev/md/tooling.md#environment) for every variable. ## Four ways to test {#testing} | Way | What it checks | Opens the game | Where | | --- | --- | --- | --- | | **Type-check with `tsc`** | Types, typos, wrong option names. | No | [Tooling](https://prism.am/dev/md/tooling.md#type-check) | | **Reload and play** | Everything, with the real game: copy the folder, press **Reload** on the Mods page, play a map. Messages and errors appear under the mod. | Yes | [A first mod](https://prism.am/dev/md/first-mod.md#mods-page) | | **A Rust test over the real engine** | That the script loads and does what you expect, without a window. It starts the same `ModHost` as the game and sends it events. | No | [Tooling](https://prism.am/dev/md/tooling.md#rust-tests) | | **A diagnostic run of the game** | The skin and the map script of one map, as at a real launch: `prism.exe --smoke-test` prints their problems. | Yes | [Tooling](https://prism.am/dev/md/tooling.md#cli) | Themes have their own check: `cargo run -p modding --example check_theme`. See [Tooling](https://prism.am/dev/md/tooling.md#tools). ## I want to… {#decision-table} | I want to… | Read | | --- | --- | | Show a number, a bar or a label during a play | [HUD elements](https://prism.am/dev/md/guides/hud-element.md) | | Draw effects over the playfield, in the native renderer | [Stage drawing](https://prism.am/dev/md/guides/stage-drawing.md) | | Give the player options, keep data between sessions | [Elements, settings and storage](https://prism.am/dev/md/guides/elements-settings-storage.md) | | Change how notes, lanes and lights look | [A first skin](https://prism.am/dev/md/first-skin.md), then [Skins](https://prism.am/dev/md/guides/skin.md) | | Know every skin field and its bounds | [Skin fields](https://prism.am/dev/md/reference/skin-fields.md) | | Convert an osu! skin | [Skin import](https://prism.am/dev/md/guides/skin-import.md) | | Move the playfield with the music | [A first map script](https://prism.am/dev/md/first-map-script.md), then [Map scripts](https://prism.am/dev/md/guides/map-scripts.md) | | Add a judgement system (windows, tiers) | [Judgement sets](https://prism.am/dev/md/guides/judgement-set.md) | | Add a difficulty or performance rating | [Ratings](https://prism.am/dev/md/guides/rating.md) | | Add a filter to the song library | [Library filters](https://prism.am/dev/md/guides/library-filters.md) | | Add a selection tab or read the local leaderboard | [Tabs and leaderboard](https://prism.am/dev/md/guides/tabs-leaderboard.md) | | Add a gameplay modifier | [Gameplay modifiers](https://prism.am/dev/md/guides/gameplay-modifiers.md) | | Rewrite the notes of a chart before it plays | [Chart transform](https://prism.am/dev/md/guides/chart-transform.md) | | Add a place to download maps from | [Download sources](https://prism.am/dev/md/guides/download-source.md) | | Add a tool to the map editor | [Editor mods](https://prism.am/dev/md/guides/editor-mod.md) | | Change the look of the menus | [Themes](https://prism.am/dev/md/themes.md) | | Understand lifecycle, budgets, permissions, errors | [Concepts](https://prism.am/dev/md/concepts.md) | | Look up a function, an event or a type | [SDK reference](https://prism.am/dev/md/reference/sdk.md) | | Install, export, run, or use a command-line flag | [Tooling](https://prism.am/dev/md/tooling.md) | | Open or write a game file (`.pvmod`, `.pvreplay`, `.pvplaylist`…) | [`.pvmod`](https://prism.am/dev/md/formats/pvmod.md), [skin package](https://prism.am/dev/md/formats/skin-package.md), [`.pvreplay`](https://prism.am/dev/md/formats/pvreplay.md) | | Read charts, scores or the catalogue over HTTP | [The online API](https://prism.am/dev/md/online/api.md) | | Publish a mod or a skin to the catalogue | [Submit to the catalogue](https://prism.am/dev/md/online/submit.md) | | Fix an error message | [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md), [Limits](https://prism.am/dev/md/help/limits.md) | | Give all of this to an AI assistant | [Feed an AI assistant](https://prism.am/dev/md/llm.md) | ===== Page: A first mod Address: https://prism.am/dev/first-mod/ Derived from: content/examples/mods/hello-hud/main.ts, crates/modding/src/manifest.rs, crates/modding/src/package.rs, apps/desktop/src/app/mods.rs, crates/modding/tests/docs_examples_start.rs # A first mod A working HUD mod in five minutes: the file, the folder, where to put it, the Mods page, type checking, exporting, and what an error looks like. This mod draws the combo in big type on the right of the screen, and the accuracy under it. It is short on purpose: every line is something you will write in your own mods. ## The mod {#the-mod} Create a folder `hello-hud` with one file, `main.ts`: ```ts /// // Hello HUD: the combo in big type on the right of the screen, the accuracy below it. // Nothing here runs per judgement: `bind` makes the overlay refresh the values itself. export default defineMod({ id: "hello-hud", // a-z, 0-9, ., -, _ ; 1 to 64 characters ; stable name: "Hello HUD", version: "1.0.0", // semantic version apiVersion: 2, // must equal the game's API version author: "Me", description: "The combo in big type, and the accuracy below it.", setup() { ctx.on("game.songStart", () => { hud.group({ id: "panel", flow: { direction: "column", align: "end", gap: 0.004 }, layout: { x: 0.98, y: 0.5, anchor: "topRight" }, }); hud.text({ id: "combo", parent: "panel", text: "", bind: { kind: "combo" }, style: { size: 0.06 } }); hud.text({ id: "acc", parent: "panel", text: "", bind: { kind: "accuracy", decimals: 2 }, style: { size: 0.03 } }); }); ctx.on("game.songEnd", () => hud.clear()); log.info("Hello HUD loaded"); }, }); ``` What each part does: - `export default defineMod({ … })` is the whole declaration. It must be called once, at the top level of the file. `id`, `name`, `version` and `apiVersion` are required. - `id` names the mod for the game and for other mods. It is not the folder name. Use lowercase letters, digits, `.`, `-` and `_`, 1 to 64 characters, starting and ending with a letter or digit. Keep it stable: the player's settings and the mod's storage are filed under it. - `version` is a semantic version (`1.0.0`, `2.0.0-beta.1`). The game compares versions when a package replaces an installed mod. - `apiVersion` must equal the API version of the game, which is [2](https://prism.am/dev/md/start.md#versions). - `setup()` runs once, after the declaration is valid. Everything beyond declaring and logging happens there or in a handler. - `ctx.on("game.songStart", …)` registers a handler for an event. This one builds the HUD each time a map starts. `game.songEnd` clears it. - `hud.group` and `hud.text` describe nodes. The overlay draws them; the script never draws a pixel. - `bind: { kind: "combo" }` makes the overlay refresh the text itself on every judgement. Nothing in the script runs per judgement. - Lengths such as `size` and `gap` are fractions of the screen **height**. `layout.x` and `layout.y` are fractions of the parent (the screen at the top level). With `x: 0.98` and `anchor: "topRight"` the group's top-right corner sits at 98 % of the width. - `log.info(…)` writes a line that appears under the mod on the Mods page. ## The folder {#folder} A mod is a folder. The entry file is `main.ts`, or `index.ts` if there is no `main.ts`. ```text hello-hud/ main.ts the entry point, required lib/format.ts modules that main.ts imports with a relative path fonts/Title.ttf fonts named in `fonts` (.ttf, .otf) images/star.png PNG images that hud.image or stage.sprite show ``` - The folder name is free. It is not the id. - A folder whose name starts with `.` is ignored. So is a folder without an entry file (`content/mods/sdk` is one). - A folder whose name starts with `editor-` is never loaded by the game, in any root: those are editor mods. Do not name your mod folder that way. - Imports must stay inside the folder. A script cannot read any other file, and cannot reach the network. - If two folders declare the same `id`, the first one loaded keeps it. The other fails with ``another mod already uses the id `hello-hud`: the folder `…` loaded first and keeps it``. ## Where to put it {#where} The game reads two roots, in this order: | Order | Root | Use it for | | --- | --- | --- | | 1 | `mods\` next to `prism.exe` (in a source checkout, `content/mods/`) | The mods that ship with the game. Leave it alone. | | 2 | `%LOCALAPPDATA%\Prism\PrismNG\data\mods` | Your mods, and the ones the player installs. | The second root is `data\mods` inside the data folder. The game creates it at start. Two variables move things: - `PRISM_MODS_DIR` replaces the second root only. The mods next to `prism.exe` stay where they are. - `PRISM_DATA_DIR` replaces the whole data folder, and `mods` with it. Copy your folder in: ```powershell Copy-Item -Recurse hello-hud "$env:LOCALAPPDATA\Prism\PrismNG\data\mods\" ``` Within a root, mods load in folder-name order. Then the game sorts them by dependencies, then by `loadOrder` (an optional number from 0 to 10000, default 1000) and `id`. That order is also the order in which events reach the mods and the order in which their HUD layers stack. ## The Mods page {#mods-page} Open **Mods** from the menu. The page lists every mod with its state (`Active`, `Failed` or `Disabled`), its name, version and author, and its messages. | Control | What it does | | --- | --- | | **Open folder** | Opens the player's mods root in Explorer. | | **Reload** | Starts the mod host again: it re-reads every folder and runs every mod's load and `setup` again. There is no automatic reload and no file watcher: press it after every edit. | | **Install…** | Picks a `.pvmod` file and installs it. You can also drop a `.pvmod` file on the window. | | **Export** | Writes the mod as `-.pvmod` in a folder you choose. See [Export a .pvmod](#export). | | **Uninstall** | Deletes the mod's folder. The mod's storage file is kept, so a reinstall finds its data. | | The switch of each mod | Turns it on or off. The choice is kept, and the mod stays installed. A change made during a play waits for the return to the menu. | Install, export, uninstall and reload are refused during a play: `Mods cannot be reloaded during a play`. A mod that declares the `stage` permission also gets a switch that lets the player forbid its native drawing. [Concepts](https://prism.am/dev/md/concepts.md#permissions) explains the three permissions. ## Type checking {#type-check} The game transpiles your TypeScript without checking types. A wrong option name only shows up when the call runs. Let `tsc` find it first. 1. Put [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts) next to `main.ts`. 2. Start `main.ts` with `/// `. In the repository the examples point at `../../../mods/sdk/modding.d.ts` instead. 3. Add a `tsconfig.json`: ```json { "compilerOptions": { "strict": true, "noEmit": true, "target": "es2022", "lib": ["es2022"], "module": "esnext", "moduleResolution": "bundler", "types": [] }, "include": ["main.ts", "lib"] } ``` 4. Run `tsc` in the folder (`npx tsc`, or `bunx tsc`). A typo is caught before the game ever runs it: ```ts fragment error=TS2551 hud.txt({ id: "combo", text: "" }); ``` The `error=TS2551` marks this block as a documented mistake: it fails with exactly that code, and `tsc` suggests `text`. ## Export a .pvmod {#export} **Export** on the Mods page writes a ZIP archive named `-.pvmod`. Give that file to a player: they press **Install…** or drop it on the game window. Installing a mod with the same `id` replaces the installed one, so the same file updates, reinstalls or rolls back. The archive holds `main.ts` or `index.ts` and the files the mod uses. Only `.ts`, `.ttf`, `.otf`, `.png`, `.json`, `.md` and `.txt` files are allowed, and hidden entries and `node_modules` are left out. Limits: 64 MiB, 1024 entries, 256 files. [The `.pvmod` format](https://prism.am/dev/md/formats/pvmod.md) lists the rules and every refusal. ## When something is wrong {#errors} Errors do not crash the game. They show on the Mods page, under the mod, with the level `error`, and the mod's state changes. | When | State | What you see | | --- | --- | --- | | The declaration is wrong, or the file throws while loading | `Failed` | The reason, once. The other mods load normally. | | `setup` throws | `Failed` | The exception. | | A handler throws, or runs longer than 30 ms | `Active` | One error line per failure. | | Three failures in a row, or three overruns in all | `Disabled` | `disabled: failed 3 times in a row; last error: …` or `disabled: exceeded the 30ms execution budget 3 times`. The mod stays off until the mod host starts again (**Reload**, or a restart of the game). | The messages you will meet first, quoted as the game writes them: ```text `hello-hud` requires modding API version 1; this game provides version 2 `version` must be a semantic version such as 1.0.0, got "1.0" (…) unknown field `descripton`, expected one of id, name, version, … `main.ts` must declare the mod with `export default defineMod({ … })` at its top level defineMod must be called exactly once `hud.text` is not available while the mod loads: call it from `setup` or an event handler ``` The last one is the most common first mistake: at load time only `defineMod`, `log.*` and `ctx.on` work. Put everything else in `setup` or in a handler. [Concepts](https://prism.am/dev/md/concepts.md#errors) explains what is disabled when, and [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md) lists more messages. ## Next {#next} - Place and style elements: [HUD elements](https://prism.am/dev/md/guides/hud-element.md). - Every function and event: [SDK reference](https://prism.am/dev/md/reference/sdk.md). - What a script may and may not do: [Concepts](https://prism.am/dev/md/concepts.md). - Install, reload, command line: [Tooling](https://prism.am/dev/md/tooling.md). ===== Page: A first skin Address: https://prism.am/dev/first-skin/ Derived from: content/examples/skins/first-skin/skin.ts, crates/skin/src/library.rs, crates/skin/src/prepare.rs, crates/skin/src/spec.rs, crates/modding/src/manifest.rs, apps/desktop/src/app/skins.rs, crates/modding/tests/docs_examples_start.rs # A first skin A working skin in five minutes: skin.ts, one image, where skins live, the Skins page, the skin editor, and what an error looks like. A skin sets how the playfield looks: the lanes, the notes, the receptors, the lights. It is a folder with one script, `skin.ts`, and the images the script names. The game runs the script at the start of every map, so the skin can react to the number of keys, the screen size or the song. ## The skin {#the-skin} Create a folder `first-skin` with this `skin.ts`, and a 64 by 64 pixel PNG at `notes/gem.png` (white, on a transparent background: a rounded gem; any white PNG works): ```ts /// // First skin: dark lanes, pink gems, a pale frame around the stage. A skin is a folder // with this file; its images are named by paths relative to the folder. // // Sizes are fractions of the screen height; `x` and `y` are fractions of the screen. export default defineSkin({ id: "first-skin", // 1 to 64 of a-z, 0-9, ., -, _ ; shares its namespace with mods name: "First Skin", version: "1.0.0", apiVersion: 2, // must equal the game's API version author: "Me", description: "Pink gems on dark lanes.", // `play` describes this launch: the skin runs again for every map. setup(play: PlayContext) { // Narrower lanes for the wide layouts, so that 9K still fits on the screen. const laneWidth = play.columns <= 6 ? 0.09 : 0.07; playfield.set({ x: 0.5, y: 0.5, anchor: "center", laneWidth, laneGap: 0.004, laneHeight: 0.9, receptorY: 0.85, // the line where notes are hit, from the top scroll: "down", laneColor: "#10131ccc", borderWidth: 0.002, borderColor: "#f3d7e8aa", noteColor: "#ff4d94", // tints the image of the note noteSize: { width: laneWidth, height: laneWidth }, note: "notes/gem.png", receptorColor: "#f3d7e8", pressedColor: "#ffffff", }); // One lane of its own: the first column's notes are mint. lanes.set({ column: 0, lane: { noteColor: "#66e6bf" } }); log.info(`First Skin: ${play.columns} columns, lanes ${laneWidth} wide`); }, }); ``` What each part does: - `export default defineSkin({ … })` declares the skin. `id`, `name`, `version` and `apiVersion` are required. `id` follows the rules of a mod id and shares its namespace with the mods: a mod and a skin cannot use the same one. `apiVersion` must equal the API version of the game ([2](https://prism.am/dev/md/start.md#versions)). `author`, `description`, `homepage`, `fonts` and `images` are optional. - `setup(play)` runs at every map launch, on a fresh copy of the script. Nothing is kept from one map to the next. `play` tells you what is about to be played: `mode`, `layout`, `columns` (the number of keys), `screenWidth` and `screenHeight` in pixels, `song` and `judgements`. Name the parameter `play`, not `ctx`, which would hide the global `ctx`. - `playfield.set({ … })` merges a description of the whole playfield. A field you do not give keeps the engine's default, so a skin that sets nothing draws the standard playfield. - `lanes.set({ column, lane })` merges a description into one column, counted from 0. The first column's notes are tinted mint here; the others keep `noteColor`. - `note: "notes/gem.png"` names an image of the skin folder. Images are always paths relative to the folder. `noteColor` tints the image: a white image takes the colour exactly. - `mine: "notes/mine.png"` names the image of a mine, drawn at the note size with its own proportions; `mineColor` tints it. A skin without one draws the default skin's mine, so a skin never has to bring it. - Positions are fractions of the screen: `x` of its width, `y` of its height, from the top-left corner. Sizes and widths are fractions of the screen **height**, so the playfield keeps its proportions at every resolution. Colours are `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. ## The folder {#folder} ```text first-skin/ skin.ts required, one file, at most 1 MiB notes/gem.png images, always PNG fx/flash-1.png frames of an animation, named with the {n} token preview.png the picture the Skins page shows (else left.png) ``` - `skin.ts` is a single script. It cannot import another file: loading `import { W } from "./util"` fails with `Error resolving module './util'`. - A folder without `skin.ts` is not a skin. The Skins page lists it as a problem. - Images are PNG files of at most 4 MiB and 2048 pixels per side. The game shrinks them to 640 pixels in its texture atlas, and a map loads at most 256 images for one layer. - An image used only inside a handler during the play must be loaded before the play starts: name it in `setup`, or list it in `defineSkin({ images: [ … ] })` (64 at most). - Fonts (`.ttf`, `.otf`, 8 MiB at most each) are named in `defineSkin({ fonts })`. Key sounds (`.wav`, `.ogg`, `.flac`, `.mp3`, 1 MiB each) are named by `hitSound`. ## Where skins live {#where} | Root | Folder | Notes | | --- | --- | --- | | The game's | `skins\` next to `prism.exe` (in a source checkout, `content/skins/`) | `default` and `default-circle`, shipped with the game. | | The player's | `%LOCALAPPDATA%\Prism\PrismNG\data\skins\\` | Yours. `PRISM_SKINS_DIR` replaces this root only. | The game's skins are listed first, then the player's. The folder name is the skin's name on this machine: 1 to 64 characters, valid as a Windows file name, not starting with `.`. If two folders carry the same name, the first one wins and a message says so. Copy your folder in: ```powershell Copy-Item -Recurse first-skin "$env:LOCALAPPDATA\Prism\PrismNG\data\skins\" ``` Since `skin.ts` is read again at every map launch, you edit it, save, and start a map: no restart. `prism.exe --skin ` picks a skin for a diagnostic run. See [Tooling](https://prism.am/dev/md/tooling.md#cli). ## The Skins page {#skins-page} Open **Skins** from the menu. It lists the interface themes, then one card per skin with its preview, name, version, author and problems. | Control | What it does | | --- | --- | | **Use** | Makes the skin the one for the next map. The setting is `skin`. A change restarts the mod host, so it waits for the menu. | | **Customize skin** | On the card of the skin in use. Opens the skin editor on a demo chart. | | **Export** | Writes `.zip`. Hidden files are left out. | | **Import…** | Installs a `.zip` as a new folder. It never replaces an existing skin: a taken name becomes `-2`, `-3`… | | **Open folder**, **Reload** | Open the player's root, and read the list again. | | Actions menu | Converts an osu! skin ([Skin import](https://prism.am/dev/md/guides/skin-import.md)), and assigns a skin per number of keys. | Only the player's skins can be deleted from the page, never the game's, and never the one in use. ## The skin editor {#editor} **Customize skin** opens a frozen demo chart under the interface. Click the playfield, a column or a HUD widget to select it: the inspector shows what can be changed there. The editor draws its fields from the same catalogue as the [skin fields reference](https://prism.am/dev/md/reference/skin-fields.md), with the same bounds. What the player edits is a separate layer stored in the settings (`skinConfig`), not in your files. The layers stack, and the highest wins, value by value: 1. your skin, 2. the map's script, if any, 3. the player's own configuration. So an edit never changes `skin.ts`, and **Reset customizations** brings the skin back as you wrote it. ## When something is wrong {#errors} A skin that fails never stops the game. The game reports the problem and plays with the engine's own defaults, or with the default value of the one field at fault. | What is wrong | What happens | Message | | --- | --- | --- | | `skin.ts` throws, does not declare itself, or has a wrong `apiVersion` | The skin does not run: plain rectangles, no images. | `` `skin.ts` must declare the skin with `export default defineSkin({ … })` at its top level `` | | A number is out of its bounds | It is moved into the bounds. | `laneWidth: 3 is outside [0.005, 0.5]; 0.5 is used` | | A colour is not a colour | The default colour is used. | `noteColor: "pink" is not a color (#rgb, #rgba, #rrggbb or #rrggbbaa); the default color is used` | | An image is missing or is not a PNG | That image is not drawn. | The file name and the reason | | A handler changes a field outside a play | The call throws. | `` the playfield only changes while a chart plays: call it from a handler between `game.songStart` and `game.songEnd` `` | | A lane that does not exist | The call throws. | `lane 40 does not exist: there are at most 32 lanes` | | No skin at all | The engine's defaults. | `No skin found: put a skin folder in skins/` | Like a mod, a skin that fails three times in a row, or overruns its 30 ms budget three times, is stopped. Unlike a mod, it comes back at the next map launch. [Concepts](https://prism.am/dev/md/concepts.md#errors) explains the difference. ## Next {#next} - Every playfield field, with its bounds and defaults: [Skin fields](https://prism.am/dev/md/reference/skin-fields.md). - Animations, lights, per-key skins, the player layer, the HUD elements a skin places: [Skins](https://prism.am/dev/md/guides/skin.md). - Change the playfield during a play: [`playfield.update`](https://prism.am/dev/md/reference/sdk/game.md#playfield-update), and [Map scripts](https://prism.am/dev/md/guides/map-scripts.md) for a script that belongs to one map. - Start from an existing skin: copy `content/skins/default` and change values. - Convert an osu! skin: [Skin import](https://prism.am/dev/md/guides/skin-import.md). ===== Page: A first map script Address: https://prism.am/dev/first-map-script/ Derived from: content/examples/map-scripts/first-light/script.ts, crates/modding/src/chart.rs, crates/modding/src/manifest.rs, crates/modding/src/api.rs, crates/modding/src/host.rs, apps/desktop/src/app/skins.rs, apps/desktop/src/app/playback.rs, crates/modding/tests/docs_examples_start.rs # A first map script A map script that animates the playfield with the music: where the file goes next to a chart, what it may change, its budgets, and how replays treat it. A map script belongs to one map. It moves the playfield while the map plays: it sways, rotates, zooms, shifts columns and changes colours with the music, like an ITG modchart. Judging and scoring never depend on it. A map without a script plays with the skin's playfield. ## The script {#the-script} `first-light` makes the playfield sway from side to side, leaning into each swing, one swing every two measures. The lanes glow on every beat, brightest on the downbeat. ```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" }); }); }, }); ``` How it works: - `export default defineChart({ apiVersion: 2, setup })` declares the script. A map script has no `id` and no name: it is identified by its map. `apiVersion` must equal the game's ([2](https://prism.am/dev/md/start.md#versions)). - `setup(play)` receives the same `PlayContext` as a skin: `columns`, `song` (with `song.timing`, the tempo points), the screen size, the judgement tiers. It runs at every launch of the map, on a fresh copy. - `playfield.set` and `playfield.update` change the playfield. `update` takes a `patch` and can animate it: `transitionMs` and `easing`. - The handler runs **once per beat**, not per frame. It only starts transitions: the renderer animates every value on its own from the song clock, so the motion stays smooth whatever the script's pace. - Two `playfield.update` calls in one handler with different transitions stay separate and apply in order: a glow at once, then a fade back by the next beat. ## Where it goes {#where} Next to the chart, in the map's folder, beside the audio: | File | Serves | | --- | --- | | `script.ts` | Every difficulty of the folder. | | `.script.ts` | That difficulty only. It wins over `script.ts`. | For `Artist - Title [Hard].osu`, the specific script is `Artist - Title [Hard].script.ts`. The file is read again at every launch of the map: edit, save, start the map. No restart of the game. It must be UTF-8 text of at most 1 MiB. Images it shows are PNG files of its own folder, named in `setup` or listed in `defineChart({ images: [ … ] })` (64 at most), and decoded before the play starts. The player can switch every map script off with **Settings → Game → Allow map scripts** (setting `allowMapScripts`, on by default). The safe mode switches them off too. ## What it may change {#may-change} | It may | It may not | | --- | --- | | Call `playfield.set`, `playfield.update` and `lanes.set`: every playfield field, and per lane, with the same bounds as a skin. | Call `hud.*` or `storage.*`: they throw. | | Read the game: `game.song()`, `game.notes()`, `game.player()`, `game.judgements()`, `game.playfield()`, `game.settings()`. | Register anything: judgement sets, ratings, tabs, modifiers… Only mods do. | | Listen to `game.songStart`, `game.beat`, `game.tick`, `game.judgement`, `game.pause`, `game.resume`, `game.songEnd`, `game.playfieldChange`, `game.settingsChange`. | Reach the network, or read a file other than the images of its folder. | | Draw natively with `stage.*`, if it declares `permissions: ["stage"]`. | Change the notes, the judgement or the score. | The script describes a **layer** over the skin's. Each value it gives wins over the skin's while it gives it. The player's own configuration wins over both. For a lane, the order is: the script's lane, the script's common values, the skin's lane, the skin's common values, the engine's default. Time is in microseconds in events (`beat.timeUs`) and in milliseconds in transitions (`transitionMs`, 0 to 10000). `game.beat` fires at the exact time of each beat on the song clock and stops during a pause. `game.tick` fires 30 times a second. ## Budgets {#budgets} A map script is treated like a downloaded mod: | Budget | Value | | --- | --- | | Run time of one call (load, `setup`, each handler) | 30 ms | | Memory | 16 MiB | | Stop | 3 timeouts, or 3 errors in a row | | Wait at launch for the `setup` of the skin and the script | 1000 ms, then the map plays with the engine's defaults and without the script | | Source file | 1 MiB | | Tempo points in `song.timing` | 1024 | A script that is stopped during the play loses its layer: the skin's playfield stays. It comes back at the next launch. ## Replays {#replays} A replay records `mapScript`: the BLAKE3 hash (hexadecimal) of the source of the script that drew the play. It is `null` without a script, or when the script could not start. Judging does not depend on the script, so a replay plays back identically with or without it. Changing one character of the script changes the hash. ## Try it {#try} 1. Copy `script.ts` next to a chart of a map in your library. 2. Start the map from the game. The playfield sways. 3. Or run a diagnostic play that skips the menus. Use a throwaway data folder so your own data is untouched: ```powershell $env:PRISM_DATA_DIR = "$env:TEMP\prism-scratch" prism.exe --bench-gameplay 10 --map "C:\path\to\Artist - Title [Hard].osu" ``` It plays the map as a real launch would and prints a line `PRISM_BENCH map script: …` with the path, the state (`running` or `not running`), the hash and the problems. `--smoke-test` prints the same under `PRISM_SMOKE` for the map selected at start. See [Tooling](https://prism.am/dev/md/tooling.md#cli). ## When something is wrong {#errors} The play always goes on, with the skin alone. The error is reported in a notice at launch and in the mods' log. | What is wrong | Message | | --- | --- | | Wrong `apiVersion` | `the map script requires modding API version 1; this game provides version 2` | | No declaration | `` the map script must declare itself with `export default defineChart({ … })` at its top level `` | | Declared twice | `defineChart must be called exactly once` | | A mod's call in a map script | `` `hud.text` is not available to map scripts: they only change the playfield `` | | Too big, or not text | ` exceeds 1048576 bytes`, ` is not UTF-8 text` | | A playfield change outside a play | `` the playfield only changes while a chart plays: call it from a handler between `game.songStart` and `game.songEnd` `` | | A declared image is missing or is not a PNG | The script does not start. | [Concepts](https://prism.am/dev/md/concepts.md#errors) explains when a script is stopped and for how long. ## Next {#next} - Every rule, every field, transitions and images: [Map scripts](https://prism.am/dev/md/guides/map-scripts.md). - The playfield fields and their bounds: [Skin fields](https://prism.am/dev/md/reference/skin-fields.md). - `playfield.update`, `lanes.set` and the `game.*` reads: [SDK reference](https://prism.am/dev/md/reference/sdk/game.md). ===== Page: Concepts Address: https://prism.am/dev/concepts/ Derived from: crates/modding/src/api.rs, crates/modding/src/host.rs, crates/modding/src/runtime.rs, crates/modding/src/manifest.rs, crates/modding/src/events.rs, crates/modding/src/judgement.rs, crates/skin/src/color.rs, content/mods/sdk/modding.d.ts # Concepts How scripts run in Prism: the three kinds, the lifecycle, threads and budgets, events, permissions, errors, determinism, units, ids and what is forbidden. Read this page once before you write more than a toy. It explains the rules that every other page assumes. ## The three kinds of script {#kinds} Mods, skins and map scripts run on the same engine with the same budgets. They differ in who owns them, when they run and what they may call. | | Mod | Skin | Map script | | --- | --- | --- | --- | | Entry file | `main.ts` or `index.ts` in a folder of a mods root | `skin.ts` in a skin folder | `script.ts` or `.script.ts` next to a chart | | Declares itself with | `defineMod` | `defineSkin` | `defineChart` | | Has an id | Yes | Yes (same namespace as mods) | No: it belongs to its map | | Runs | Loaded when the mod host starts, then lives until it stops | At every map launch, on a fresh copy | At every map launch, after the skin, on a fresh copy | | Listens to events (`ctx.on`) | Yes | Yes | Yes | | Reads the game (`game.*`) | Yes | Yes | Yes | | `playfield.*`, `lanes.set` | No: `` `playfield.set` is only available to skins and map scripts `` | Yes, in `setup` and during a play | Yes, in `setup` and during a play | | `playfield.setNoteMask` | Yes, inside the `playfield.noteMask` handler of a `noteMask` modifier, once per play | No | No | | `hud.*`, `storage.*` | Yes | Yes | No: `` `hud.text` is not available to map scripts: they only change the playfield `` | | Provides and configures HUD elements (`provides`, `uses`, `ctx.element`) | Yes | Yes | No: `ctx.has` is always false, and `configure` throws | | `*.register` (judgements, scroll speed, ratings, library filters, tabs, key actions, gameplay modifiers, download sources and bridges, tables) | Yes, in `setup` only | No | No | | `leaderboard.*`, `ratings.backfill`, `metron.performance`, `ui.popup`, `skinImport.*` | Yes | No | No | | `stage.*` | With `permissions: ["stage"]` | With `permissions: ["stage"]` | With `permissions: ["stage"]` | | When it fails for good | Off until the mod host starts again | Off until the next map launch | Off until the next map launch | The rule behind the table: a **mod** adds to the game for every play. A **skin** describes the look of the playfield for every map. A **map script** describes one map, and only changes the playfield. ## Lifecycle {#lifecycle} A mod goes through these steps. 1. **Discovery.** The mod host starts once the interface has sent the saved settings, and loads in the background: the game does not wait for it. It reads the game's `mods` folder first, then the player's, each in folder-name order. A folder is a mod if it holds `main.ts` or `index.ts` and its name does not start with `.`. Folders named `editor-…` are never loaded. 2. **Load.** The top-level code of the entry file (and of what it imports) runs. Only `defineMod`, `log.*` and `ctx.on` work. Anything else throws `` `X` is not available while the mod loads: call it from `setup` or an event handler ``. That includes `storage.*` and `game.*`. This is also how installing a `.pvmod` reads its declaration: nothing else runs. 3. **Declaration.** `defineMod` must be called exactly once, at the top level. The game validates the id, the version, the API version, the texts, the fonts and the dependencies. An invalid declaration, a taken id or a second call fails the mod, even when the exception is caught. 4. **Setup.** `setup` runs once, after the `setup` of every package the mod `uses`. This is the only place for `*.register` calls: they throw `` `X.register` is only available in a mod's setup `` anywhere else, and the registries close once every mod has set up. 5. **Events.** From then on the mod receives events, and may call everything except `defineMod`. 6. **Stop.** The mod stops when the host restarts (**Reload**, a skin change, a restart of the game), when the player turns it off, or when the game disables it after repeated failures. The order of mods is: providers before the mods that `use` them, otherwise `loadOrder` (0 to 10000, default 1000), then `id`. That order is also the order of event delivery and of the stacking of HUD layers. A skin and a map script have two steps instead of six. At every map launch the game loads `skin.ts` fresh, runs `setup(play)`, then loads the map script fresh and runs its `setup(play)`. Then it validates and decodes everything the two described (`playfield.set`, `lanes.set`, images). `playfield.*` and `lanes.set` work in `setup`, and in handlers between `game.songStart` and `game.songEnd`. Everywhere else they throw `` the playfield only changes while a chart plays: call it from a handler between `game.songStart` and `game.songEnd` ``. The game waits at most 1000 ms for the two `setup`s. After that the map plays with the engine's defaults and without the script, and says so. ## Threads and budgets {#budgets} All script code runs on one thread, named `mods`, never on the input, render, audio or window thread. By default the thread is pinned to the last logical core. It has an 8 MiB stack. Game threads never wait for it: they push events into a bounded queue. The shipped mods share one engine, because the game's author wrote them. Every mod the player installs gets an **engine of its own**, so one cannot starve another. Each script keeps its own globals either way. | Limit | Value | | --- | --- | | Run time of one load, `setup`, event or tick | 30 ms | | Memory per script | 16 MiB | | Stack per script | 1 MiB | | Failures in a row that disable a script | 3 (an exception or a timeout) | | Timeouts in all that disable a script | 3 | | HUD nodes per mod | 384 | | Characters in one HUD text | 256 | | Storage per mod | 256 KiB | | Event queue | 1024 events | | Message queue (what the Mods page shows) | 256 messages | | Length of a log line | 1024 characters, cut with `…` | | `game.tick` | 30 per second, during a play | [Limits](https://prism.am/dev/md/help/limits.md) has the full table, down to every per-call bound. The budget is wall-clock time, not CPU time. A handler that needs 25 ms on a quiet machine will fail on a busy one: keep handlers short. ## Events {#events} An event is a message from the game. A script listens with `ctx.on("", handler)` and stops with `ctx.off`. Handlers run in registration order. There are 25 events in four families: | Family | Events | | --- | --- | | The play | `game.songStart`, `game.songEnd`, `game.judgement`, `game.pause`, `game.resume`, `game.tick`, `game.beat`, `game.pauseMenu`, `game.lobbyLive`, `game.playfieldChange`, `game.settingsChange` | | For something you registered or provide | `chart.transform`, `controls.action`, `elements.configure` | | Answers to a request you made | `leaderboard.result`, `metron.performanceResult`, `ratings.progress`, `ui.action`, `skinImport.action`, `skinImport.created`, `skinImport.opened`, `skinImport.staged` | | The library | `library.ready`, `library.chartAdd`, `library.chartsAdded` | [Events](https://prism.am/dev/md/reference/sdk/events.md) has the payload of each. Delivery is built so that the game never waits for a script: - The game puts each event into a bounded queue of 1024. If the queue is full, **the new event is dropped** and counted. Nothing blocks. - A script that falls behind therefore loses events instead of slowing the play. Do not write a handler that assumes it saw every event. - Payloads carry running totals for that reason. `game.judgement` has `combo`, `counts` and `accuracy` after that note, so a script **resynchronises** on the next one. `game.tick` carries `hitCount`, counted natively and independent of delivery. - Histories are read on demand, not accumulated from events: `game.hits(…)` and `game.keys(…)` return what happened, bounded. - `game.tick` arrives 30 times a second, only while a chart plays and is not paused. A late tick is skipped. `game.beat` arrives at the exact time of each beat on the song clock, without waiting for a tick. - The entities of a play (song, chart, judgements, playfield) are built before the play starts and shared read-only, so they are readable from `game.songStart` on. - Events reach scripts in the order skin, map script, mods. ## Permissions {#permissions} Three permissions exist. A script names them in `permissions: [ … ]` of its declaration. | Permission | What it allows | Who may declare it | How the player removes it | | --- | --- | --- | --- | | `stage` | `stage.*`: native drawing over the playfield, from typed elements, with no shader. | Mods, skins, map scripts | A switch on the mod's row in the Mods page. Without it the calls throw `` `X` needs the `stage` permission: declare `permissions: ["stage"]` ``, and when the player removed it `` `X`: the player turned off native drawing for `id` ``. | | `network` | `downloads.register` and `downloads.registerBridge`: declare where maps can be downloaded from. The game makes every request. | Mods | A switch on the mod's row. The sources it declared leave the list at once. | | `skinImport` | `skinImport.*`: converting a skin the player picks. | Mods | Turning the mod off. Without the permission: `` `skinImport` needs the `skinImport` permission: declare `permissions: ["skinImport"]` ``. | A mod installed from the catalogue starts turned off, so the player sees what it asks before it runs. Nothing else needs a permission: HUD nodes, storage, reading the game, registering sets are always allowed to a mod. ## Errors {#errors} A script error never crashes the game. What happens depends on when it happens and on the kind. | When | A mod | A skin or a map script | | --- | --- | --- | | The declaration is invalid, or the top-level code throws | The mod does not load. State `Failed`, with the reason. Other mods load. | The script does not run. The skin falls back to the engine's defaults; the play goes on with the skin alone for a map script. | | `setup` throws, or overruns 30 ms | The mod does not load. | Same. | | A handler throws, or overruns 30 ms | An error message. The script stays on. | Same. | | 3 failures in a row, or 3 timeouts in all | **Disabled** for the rest of the session: the HUD is removed, its judgement sets, ratings, actions and modifiers are withdrawn, its storage is written. It comes back after **Reload** or a restart. | **Disabled** until the **next map launch**: the HUD, or the map script's layer, goes away and the playfield stays as the others describe it. | The messages are `exceeded the 30ms execution budget N times` and `failed 3 times in a row; last error: …`. A mod that declares itself wrongly keeps its first error even if the script catches the exception. Messages show on the Mods page under the id of the script, and a notice at launch reports a skin or a map script that did not run. What a host call throws is a normal JavaScript exception. You may catch it: `try { … } catch (error) { log.warn(String(error)); }`. A caught exception is not counted as a failure. Only an exception that leaves the handler is. ## Determinism {#determinism} - **The result of a play is native.** Judging, scoring and replays are computed by the game from the inputs. A script influences them only through declarations the game validates: a judgement set, a gameplay modifier, a chart transform. A map script cannot change a result at all. - **A replay does not run scripts.** It records the hash of the map script that drew the play (`mapScript`). It replays identically with or without the script. - **Scripts are not deterministic.** `Date`, `performance.now()` and `Math.random()` exist and are not seeded. Do not draw anything that must be the same twice with them. - **A transform is seeded.** `chart.getNotes()` returns a `seed`, derived from the play, and the editor's `input.random()` is seeded too: use those when a pattern must repeat. [Chart transform](https://prism.am/dev/md/guides/chart-transform.md) explains. ## Units {#units} | What | Unit | | --- | --- | | Times in events and entities (`timeUs`, `offsetUs`, `durationUs`, `startUs`) | **Microseconds** of song time. Negative during a pre-roll. | | Durations of animations and transitions (`transitionMs`, `durationMs`, `…FadeMs`), settings (`scrollTimeMs`, `audioOffsetMs`) | **Milliseconds.** The name ends in `Ms`. | | Lengths: sizes, widths, gaps, radii, font sizes | **Fractions of the screen height.** At 1080p, `0.05` is 54 pixels. The shape of a node therefore does not depend on the aspect ratio. | | Positions `x`, `y` (HUD `layout`, playfield) | **Fractions of the parent**: the width for `x`, the height for `y`. The screen at the top level. | | Angles | Degrees, clockwise. | | Colours | Hex text: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`. Colour options of an element also accept `theme:`, which follows the player's theme. | A name tells you the unit: `Us`, `Ms`. An option that is neither is a fraction. ## Ids {#ids} There are several ids, with different rules. | What | Rule | | --- | --- | | Mod id, skin id | 1 to 64 characters among `a-z`, `0-9`, `.`, `-`, `_`. Starts and ends with a letter or a digit. No `..`. Usable as a Windows file name. Shared by mods and the skin: the first one loaded keeps it, the next fails with `` another mod already uses the id `X`: the folder `Y` loaded first and keeps it ``. No prefix is reserved: the shipped mods use `pvng.`. | | Skin folder name | 1 to 64 characters, a valid Windows file name, not starting with `.`. It is the name of the skin on this machine. | | What a mod registers: judgement set, tier, scroll speed system, rating, library filter, tab, key action, gameplay modifier | **Stricter**: 1 to 32 characters among `a-z`, `0-9` and `-`. Other packages name it `/`. | | HUD element name (`provides`) | 1 to 32 characters among `a-z`, `0-9`, `-`, starting with a letter. Others configure it as `"/"`. | | HUD node id | 1 to 64 characters, no control characters. Unique inside the mod. | | Storage key | 1 to 128 characters. | A judgement set id and the id of one of its tiers are in the strict group, so `com.example.set` is a valid mod id but not a valid set id. ## What is forbidden {#forbidden} A script runs in a sandbox. It is meant to be safe to install from a stranger. - **No DOM, no web view.** A script never touches the interface's page, its JavaScript or its IPC. It describes typed nodes; the overlay draws them as text and shapes. No HTML, no raw CSS, no script. - **No network.** `fetch` and sockets do not exist. A mod with the `network` permission only declares *data* (hosts, URL templates, JSON paths) and the game makes the requests, on hosts it shows to the player. - **No files.** A script reads only the files of its own folder (fonts, PNG images), served by the game after validation, and its own storage. It cannot read or write anywhere else. - **No timers.** `setTimeout` and `setInterval` exist as imports of `manivelle:env`, but the host never runs them: their callbacks never fire. Use `game.tick`, `game.beat` or any event. `async` handlers are allowed, but nothing makes them wait. - **No imports from outside the folder**, no `import()` call (`dynamic import() is not supported; use a static import`), and a skin imports nothing at all. - **No `console`.** It writes to the game's standard error, not to the Mods page. Use `log.info` and `log.warn`. - **No hot reload.** `ctx.hot` is declared in the SDK, but the game does not call it: **Reload** restarts everything. See [Tooling](https://prism.am/dev/md/tooling.md#hot-reload). - **No shaders and no free drawing.** Native effects are typed elements with bounded properties (`stage.*`). These limits are the point of the design: they are what lets the game run code a player downloaded. ===== Page: Tooling Address: https://prism.am/dev/tooling/ Derived from: apps/desktop/src/app/startup.rs, apps/desktop/src/app/open_with.rs, apps/desktop/src/app/paths.rs, apps/desktop/src/app/mods.rs, apps/desktop/src/app/safe_mode.rs, apps/desktop/src/gpu_backend.rs, apps/desktop/src/bench.rs, crates/modding/src/package.rs, crates/modding/examples/write_sdk.rs, crates/modding/examples/check_theme.rs, crates/modding/examples/script_bench.rs, tools/ # Tooling Type checking, installing, reloading, the log, exporting, the command-line flags and environment variables of the game, the TypeScript packages, and the tools of the repository. ## Type checking {#type-check} The game transpiles TypeScript without checking it. `tsc` is the only type check, and it runs on your machine. From a mod, skin or map-script folder that holds a copy of [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts): ```text npx tsc --noEmit --strict --target es2022 --lib es2022 --module esnext --moduleResolution bundler main.ts ``` Use `skin.ts` or `script.ts` instead of `main.ts` for a skin or a map script. A `tsconfig.json` with the same options does the same, and lets your editor use them: see [A first mod](https://prism.am/dev/md/first-mod.md#type-check). Inside the repository you do not copy anything. The file `content/mods/sdk/modding.d.ts` is the SDK, and examples point at it with `/// `. The repository's own TypeScript runs the check: ```text node apps/web/node_modules/typescript/bin/tsc --noEmit --strict --target es2022 --lib es2022 --module esnext --moduleResolution bundler content/examples/mods/hello-hud/main.ts ``` `cargo test -p modding --test sdk` runs `examples_type_check`, which checks every mod of `content/mods/` and every example mod against the committed SDK. It is skipped without Node and `apps/web/node_modules`, unless `PVNG_REQUIRE_TSC` is set. The reference line has no effect at run time: the game ignores it. Types describe the API but do not enforce it. The game's own checks, in Rust, are the real ones: out-of-range values, unknown fields, budgets. ## Installing {#installing} | How | For | Notes | | --- | --- | --- | | **Copy the folder** | A mod, a skin | Into `data\mods` or `data\skins`. Then **Reload** on the Mods page (a mod), or start a map (a skin). | | **Install…** on the Mods page, or drop a `.pvmod` on the window | A mod | Reads a package, checks it, installs it into `data\mods\`. | | **Import…** on the Skins page | A skin | Installs a `.zip` as a new folder. It never replaces a skin. | | Open a `.pvmod` with the game | A mod | The file association starts the game or hands the file to the running one. The mod is installed **switched off**, because it is code: the player turns it on from the Mods page. | | The catalogue | A mod, a skin | A new mod from the catalogue also starts switched off. See [Submit to the catalogue](https://prism.am/dev/md/online/submit.md). | Installing a `.pvmod` runs the mod's top-level code once, in a throwaway engine with the usual budgets, only to read the declaration. Nothing else runs. The mod is refused, with a message that begins `invalid mod package:` or `the mod does not load:`, in these cases: - the package breaks a rule of the format ([`.pvmod`](https://prism.am/dev/md/formats/pvmod.md)); - the game's own mods folder already holds that id: `the game's own folder X already holds the mod `id`; uninstall or edit it instead`; - the folder `data\mods\` holds another mod: `the folder X holds another mod (`id`); rename it first`. Installing a mod with an id that is already installed replaces it. Uninstalling moves the folder aside (`.trash--…`) and deletes it. The mod's storage file stays. Install, uninstall and reload are refused during a play. ## Reload and hot reload {#hot-reload} **There is no hot reload.** The SDK declares `ctx.hot` (`data`, `save`, `dispose`) and `ctx.off`, and the engine supports hot reloading, but the game never asks it to reload a changed file, and it runs no file watcher. Do not build on `ctx.hot`: nothing calls its callbacks. What you have instead: | Kind | Edit loop | | --- | --- | | Mod | Edit, press **Reload** on the Mods page, play. Reload restarts the mod host: every mod loads again. Transpiled scripts are cached in `data\mod-cache`. | | Skin | Edit, save, start a map. `skin.ts` is read again at every map launch. Use **Customize skin** to see it on a demo chart. | | Map script | Edit, save, start the map. It is read again at every launch. | A mod keeps no state across a reload except its storage file. Save what must survive with `storage.set`. ## The log {#log} | Where you write | Where it appears | | --- | --- | | `log.info(text)`, `log.warn(text)` | The **Messages** list under the mod on the Mods page, with the level `info` or `warning`. Lines are cut at 1024 characters; the queue holds 256 messages and drops the rest. | | An exception, a refusal, a budget overrun | The same list, with the level `error`. | | `console.log` and its siblings | The game's standard error. A normal launch has no console, so you see nothing. Use `log.*`. | | A crash of the game | `prism-crash.log` in the data folder, plus a report there. | A diagnostic run (see [the command line](#cli)) keeps its console and prints what the game would show. Run it from a terminal. ## Exporting {#exporting} | Of | How | Result | | --- | --- | --- | | A mod | **Export** on the Mods page | `-.pvmod` in a folder you choose. See [A first mod](https://prism.am/dev/md/first-mod.md#export) and [`.pvmod`](https://prism.am/dev/md/formats/pvmod.md). | | A skin | **Export** on the Skins page | `.zip`. See [Skin package](https://prism.am/dev/md/formats/skin-package.md). | | A theme | Zip the folder | See [Themes](https://prism.am/dev/md/themes/sharing.md). | Hidden entries are left out. A mod export also leaves out `node_modules`. ## Tests over the real engine {#rust-tests} With a checkout of the repository you can load a script through the real engine, with no window, and assert what it does. The pages of this documentation do it for their own examples (`crates/modding/tests/docs_examples_start.rs`); `crates/modding/tests/host.rs` and the files beside it are larger models. ```rust let mut options = ModHostOptions::new(&mods_dir); // a folder holding your mod folders options.pinning = CorePinning::Disabled; // do not pin a core in a test let host = ModHost::start(options)?; assert!(host.wait_ready(Duration::from_secs(10))); // every mod loaded let status = host.status(); // state, name, version of each mod assert_eq!(status.get("hello-hud").unwrap().state, ModState::Active); host.send(GameEvent::SongStart(song_start)); // what the game sends host.wait_idle(Duration::from_secs(10)); // the queue is handled let scene = host.scene(); // what the mods drew assert!(scene.node("hello-hud", "combo").is_some()); ``` For a skin set `options.skin` to a `skin::Package` and call `host.prepare_play(context, patches, chart)`, which returns the playfield the skin and the map script described, as the game would draw it. Run one file with `cargo test -p modding --test docs_examples_start`. ## The command line {#cli} The game is `prism.exe`. A normal launch takes no argument. Files given to it are opened as a double-click would: `.osr`, `.pvreplay`, `.pvmod`, `.osk`, `.osz`, `.qp` and `.pvplaylist`, and links of the form `prism://map/`. | Flag | What it does | | --- | --- | | `--safe-mode` | Starts with only the game's own mods, the default skin and theme, and no map script. Nothing is saved. Holding Shift while the game starts does the same, and the game offers it after two starts that never reached the menus. Use it to tell your mod from the game. | | `--skin ` | The skin a diagnostic run draws. `` must be a valid skin folder name: `--skin X is not a skin folder name`. | | `--gpu-backend ` | Chooses the graphics API. It beats `PRISM_GPU_BACKEND`, which beats the saved choice. A value that does not parse is reported and the next source is tried. | | `--smoke-test` | A diagnostic run: starts the game, runs the skin and the map script of the selected map as at a real launch, checks the native draw and the overlay, and exits. It prints `PRISM_SMOKE skin: | N problem(s)`, `PRISM_SMOKE map script: …`, then `PRISM_SMOKE_OK` or `SMOKE FAILED: …`. | | `--smoke-edit`, `--smoke-auto`, `--smoke-training`, `--smoke-watch` | Other diagnostic runs, one per feature: editing, Auto, training and watching a replay. | | `--bench-gameplay ` | A benchmark of a play of 1 to 3600 seconds (more than 0). It runs the skin and the map script like a launch and prints `PRISM_BENCH skin: …` and `PRISM_BENCH map script: …`. | | `--map `, `--start ` | With `--bench-gameplay`: the chart to play (`demo` is the built-in one), and where to start in it. | | `--bench-repeat `, `--bench-pause ` | An endurance run around the benchmark: several plays in a row, with a pause between. `--bench-repeat` needs `--bench-gameplay`. | | `--bench-key-sounds`, `--bench-fullscreen` | With `--bench-gameplay`: play key sounds, and borderless fullscreen. | | `--check-library`, `--scan-library [args]` | Diagnostics of the song library of the data folder: a check, and a scan. | | `--write-ts-packages [dir]` | Writes the TypeScript packages and exits. See [the packages](#ts-packages). | | `--crash-test ` | Hidden: dies the way a native crash does, to check crash reports. | | `--after-update ` | Internal: the game restarts itself with it after an update. Never pass it. | **Every diagnostic run opens the data folder of the player's game unless you tell it otherwise.** Always set `PRISM_DATA_DIR` to an empty, absolute, writable folder first: ```powershell $env:PRISM_DATA_DIR = "$env:TEMP\prism-scratch" prism.exe --smoke-test --skin first-skin ``` Diagnostic runs print to the terminal, never open a message box, take no single-instance lock and use a throwaway web view profile. They end with an error code when a check failed. ## Environment variables {#environment} | Variable | Effect | | --- | --- | | `PRISM_DATA_DIR` | The whole data folder. Must be an absolute path, not a drive root, writable; it is created if missing. A bad value refuses to start: it never falls back to the real data. A line `data dir: … (PRISM_DATA_DIR)` is printed. While it is set, the data folder cannot be moved from Settings. | | `PRISM_MODS_DIR` | The player's mods root, instead of `data\mods`. | | `PRISM_SKINS_DIR` | The player's skins root, instead of `data\skins`. | | `PRISM_THEMES_DIR` | The player's themes root, instead of `data\themes`. | | `PRISM_FONTS_DIR` | The fonts folder, instead of `data\fonts`. | | `PRISM_GPU_BACKEND` | `auto`, `dx12`, `vulkan` or `gl`. Beaten by `--gpu-backend`. | | `PRISM_CATALOG` | The address of the catalogue. `https` only, except for localhost; this variable also lets you name a plain `http` server. | | `PRISM_UPDATE_FEED` | The address of the release list. It beats the player's setting. `https` only (`http` for the local machine). | | `PRISM_ONLINE` | The game server's WebSocket address, instead of `wss://prism.am/play`. It beats the setting. | | `PRISM_ACCOUNTS` | The accounts site, instead of `https://prism.am`. It beats the setting. | | `PRISM_SCAN_THREADS` | The number of threads of a library scan: a positive integer, capped at 32. Other values are ignored. | | `PRISM_DEV_URL` | For work on the game's interface: load its pages from this development server. | | `PRISM_INTERFACE_DIR` | For work on the game's interface: load another built interface from this folder. | An empty address variable means the default. ## The TypeScript packages {#ts-packages} `prism.exe --write-ts-packages [dir]` writes one TypeScript package per area of the game under `dir`, as `@pvng/`: `package.json` and `index.d.ts`. They hold the wire types between the game and its interface (`@pvng/online` and `@pvng/desktop` among them), generated from the Rust types. With no `dir` the default is `apps/web/packages` of the sources, so pass a folder when you run an installed game. The command needs no data folder. They are not the mod SDK: mods use [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts). Use the packages if you write an interface for the game's protocol. ## Tools of the repository {#tools} | Tool | What it is for | | --- | --- | | `cargo run -p modding --example write_sdk` | Regenerates `content/mods/sdk/modding.d.ts`, `modding.ts` and `theme.d.ts` from the Rust contracts. The test `committed_sdk_matches_the_rust_contracts` fails when they are stale. | | `prism.exe --check-theme []` | The installed game's own theme check (no window, no data written): the game's themes and `` (a folder of theme folders, or one theme folder; absent: the player's themes folder), one line per problem, exit code 1 on any. The game also writes the problems of its last listing to `/themes/problems.txt`. | | `cargo run -p modding --example check_theme [-- ]` | Checks theme folders the way the game does, and prints one line per problem: `"": : : `. Exit code 1 on any problem. With no argument it checks `content/themes`. | | `cargo run --release -p modding --example script_bench -- --out ` | Times the script engine: loading, events, host calls, memory. `--compare a.json b.json` compares two files. Options: `--reps`, `--events`, `--calls`, `--pin core\|last\|off`, `--isolated`, `--quick`. | | `tools/build.ps1 [-Release]` | Builds the game: `cargo build --locked -p desktop`. | | `tools/launch.ps1` | Runs `target/release/prism.exe`, building it first if it is missing. | | `tools/bench-realistic.mjs --exe ` | Realistic benchmarks (dense charts, key sounds, the shipped HUD mods) in a fresh data folder each run. | | `tools/osu-replay-dump.mjs` | Downloads the online replays of one osu! profile through the osu! API v2, with your credentials. | | `tools/check-changelog.mjs` | Checks the player-facing changelogs. | | `tools/package.ps1`, `promote.ps1`, `sign-release.ps1`, `build-installer.ps1`, `test-installer.ps1` | Release work: zip, promotion to stable, signing, installer. Of no use to a mod author. | ## Next {#next} - Every rule behind the messages you will see: [Concepts](https://prism.am/dev/md/concepts.md). - Limits as one table: [Limits](https://prism.am/dev/md/help/limits.md). - A message you do not understand: [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md). ===== Page: Feed an AI assistant Address: https://prism.am/dev/llm/ Derived from: services/website/scripts/devdocs.mjs, services/website/content/dev-src/llm/themes.en.md, crates/modding/examples/check_theme.rs # Feed an AI assistant The llms files and raw Markdown pages of this site, their stable addresses, and how an agent should use them. This site is written for people and for language models. Every page exists as rendered HTML and as raw Markdown, and a few plain-text files gather the pages so an assistant can read them in one go. Nothing here is maintained by hand: the files are rebuilt from the documentation and from the code on every build. See [Never stale](https://prism.am/dev/md/llm.md#generated). ## Which file for which job {#files} | File | What it holds | Use it when | | --- | --- | --- | | [llms.txt](https://prism.am/dev/llms.txt) | The index: one line per page, each pointing to the raw Markdown of that page. | The agent can fetch URLs and should read only what it needs. | | [llms-full.txt](https://prism.am/dev/llms-full.txt) | Every page in one plain-text file. | You paste the whole documentation into an assistant that cannot fetch. | | [llms-themes.txt](https://prism.am/dev/llms-themes.txt) | One self-contained document for writing a theme: the rules, the workflow, a complete example, the common errors, and compact lists of the tokens, contracts, nodes and CSS properties. | You want an agent to write or fix a **theme**. It needs nothing else. | | [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts) | The TypeScript types of `theme.ts`. | The agent can read types, or an editor checks the theme as you type. | | [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts) | The TypeScript types of the mod, skin and map-script API. | The agent writes a **mod**, a skin script or a map script. | Each text file exists in English and in French. The French files carry the same content; identifiers, file names and error messages stay in English in both. ## Stable addresses {#addresses} These addresses do not change from one release to the next. Link to them from your own tools. ```text /dev/llms.txt index (English) /dev/llms.fr.txt index (French) /dev/llms-full.txt every page (English) /dev/llms-full.fr.txt every page (French) /dev/llms-themes.txt the theme document (English) /dev/llms-themes.fr.txt the theme document (French) /dev/sdk/theme.d.ts types of theme.ts /dev/sdk/modding.d.ts types of the mod API ``` On the main site the prefix is `https://prism.am`; on the developer site the same files are served without the `/dev` prefix, for example `https://dev.prism.am/llms.txt`. ## Raw pages {#raw-pages} Every page of the documentation is also served as the Markdown it was built from, with its front matter and its code blocks, without the site's navigation. ```text /dev/md/.md English, for example /dev/md/themes/quick-start.md /fr/dev/md/.md French ``` `` is the path of the page after `/dev/`. The index [llms.txt](https://prism.am/dev/llms.txt) lists them all, so an agent never has to guess one. ## How an agent should use them {#using} 1. Start from the task. For a theme, give the agent [llms-themes.txt](https://prism.am/dev/llms-themes.txt) and nothing else: it is complete on purpose. For anything else, give it [llms.txt](https://prism.am/dev/llms.txt) and let it fetch the pages it needs. 2. Tell the agent to use only what is in the files. The game refuses every name, property and value that is not in its closed lists; an invented one is a rejected theme, not a warning. 3. Ask for a folder, not a snippet: a theme is a folder with a manifest, tokens and optional files. 4. Run the checker on what the agent wrote and give it the output. Each message names the file, the place and the reason, and is written to be acted on; see [Reading an error](https://prism.am/dev/md/themes/errors.md#reading-errors). 5. Repeat until the checker prints no problem. Then look at the theme in the game. The checker is the same code the game runs: ```bash cargo run -p modding --example check_theme -- path/to/themes ``` It exits with code 1 when there is any problem. A theme that passes it is valid; whether it is good-looking is for you to judge in the game. ## Never stale {#generated} The files are produced by the site's build, never edited and never committed. Three kinds of content go into them. - **Authored pages**, the ones people read, written in both languages with the same structure. - **Reference pages generated from the code**: the [tokens](https://prism.am/dev/md/themes/tokens.md), the [nodes](https://prism.am/dev/md/themes/nodes.md), the [contracts](https://prism.am/dev/md/themes/contracts.md) and the [CSS allow-list](https://prism.am/dev/md/themes/css-allowlist.md). They are read from the contract files the game validates against, so a token, a screen or a property added to the game appears in them at the next build, without anyone editing a page. - **Compact blocks** of the same data, embedded in [llms-themes.txt](https://prism.am/dev/llms-themes.txt) at the places marked for them. The theme examples that the pages show are real folders, checked against the real validator by the test suite. An example that stops being valid fails the tests instead of staying in the documentation. > [!NOTE] > A page states a fact from the code only when it is stable (a limit, a rule) and names the source file. Everything that can change with the contract is generated or linked. ## Pages for a theme author {#theme-pages} If the agent can fetch pages, these are the ones to give it for a theme. - [Themes](https://prism.am/dev/md/themes.md): the map of the section. - [Quick start](https://prism.am/dev/md/themes/quick-start.md): a first theme in a few minutes. - [Concepts](https://prism.am/dev/md/themes/concepts.md): what a theme is made of. - [Errors](https://prism.am/dev/md/themes/errors.md): how to read a message, and the catalogue of the common ones. - [Cookbook](https://prism.am/dev/md/themes/cookbook.md): small complete themes to start from. ===== Page: SDK reference Address: https://prism.am/dev/reference/sdk/ Derived from: content/mods/sdk/modding.d.ts # SDK reference The typed SDK of mods, skins and map scripts, generated from the game: every function, event and type. Everything on these pages is read from [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts), the declarations the game generates from its Rust contracts (Modding API version 2). Signatures and types cannot drift from the game; the descriptions come from notes that are checked for coverage in both languages. ## Pages {#pages} - [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md): defineMod, defineSkin, defineChart, defineEditorMod, the manifest types, permissions and the ctx global. - [Events](https://prism.am/dev/md/reference/sdk/events.md): Every event a script can subscribe to with ctx.on, and its payload type. - [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md): game.*, playfield.*, lanes.*, log.*, ui.*, storage.* and controls.*. - [HUD](https://prism.am/dev/md/reference/sdk/hud.md): hud.*: the on-screen elements a mod or a skin adds. - [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md): stage.*: sprites, shapes and animations drawn by the renderer (permission stage). - [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md): judgements.*, gameplay.*, scrollSpeed.* and chart.*. - [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md): ratings.*, tables.*, metron.* and library.*. - [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md): tabs.* and leaderboard.*. - [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md): downloads.* (mirrors, sources, bridges) and skinImport.*. - [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md): defineEditorMod and the interfaces of the map editor's API: panels, tools, patterns, validations. ## Where is each type? {#types-index} Every type of the SDK is defined once, on the first page that uses it. | Type | Page | | --- | --- | | `Anchor` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `Animate` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `AnimateKind` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `AnimateOn` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `AuthKind` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `AuthScope` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BackfillRequest` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `Beat` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `Border` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `BoxNode` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `BpmRange` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `BridgeAction` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeActionResult` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeDefinition` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeDownload` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeExpect` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeFormat` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeMethod` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeOnResponse` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeRequest` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeResponse` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeResult` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeSearch` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `BridgeStep` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `CalculatorRequest` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `ChartAdded` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ChartDefinition` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ChartManifest` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ChartMetric` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `ChartNotes` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `ChartSetup` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ChartTransformEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ChartsAdded` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ColumnDefinition` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `ColumnKind` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `Dependency` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `DependencySpec` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `DifficultySpec` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `DownloadAuth` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `DownloadDeclaration` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `DownloadKind` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `DownloadSpec` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `DownloadTarget` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `Easing` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `EditorApi` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorCommandDef` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorIcon` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorIssue` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorListAction` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorListItem` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorModContext` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorModDefinition` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorModStorage` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorNotePreview` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorPanelDef` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorParamDef` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorPatternDef` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorPlacementStep` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorPointer` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorStateApi` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorTempo` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorTempoPoint` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorTool` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorToolDef` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorValidationDef` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `EditorViewNode` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `ElementConfigure` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ElementDeclaration` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ElementOption` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ExtendableTab` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `Fill` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `Flow` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `FlowAlign` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `FlowDirection` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `FlowJustify` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `GameplayModifierDeclaration` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `GameplayModifierKind` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `Gradient` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `GradientStop` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `GroupNode` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `Hit` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `HitLightOn` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `HitList` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `HitQuery` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `HoldMissedStyle` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `HostEventContext` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `HostEventHandler` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `HostEventReply` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `HostEvents` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `HostHotContext` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `HostReplies` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `HudAction` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `HudElement` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `HudLabel` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `ImageBox` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ImageFit` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `ImageNode` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `ImageOp` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ImageSize` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ImportPanelDefinition` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ImporterDeclaration` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ImporterText` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `IniEntry` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `IniGeneral` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `IniSection` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ItemSpec` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `JudgementConfig` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `JudgementEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `JudgementLineAt` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `JudgementParam` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `JudgementSetDefinition` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `JudgementTier` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `JudgementTiers` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `KeyLane` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `KeyPress` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `KeyQuery` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `KeyState` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `Lane` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `LaneSpec` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `LaneUpdate` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `Layout` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `LeaderboardBestQuery` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `LeaderboardEntry` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `LeaderboardPerformance` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `LeaderboardQuery` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `LeaderboardResult` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `LeaderboardStat` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `LibraryFilterDeclaration` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `LibraryReady` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `LobbyCoopLive` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `LobbyLiveEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `LobbyRival` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ManiaColumn` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ManiaSection` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `MapMarker` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `MapNote` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `MapPluginApi` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `MapSection` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `MapTimingPoint` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `MeasureLineLength` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `MetronCalculator` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `MetronCatalog` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `MineRule` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `ModActionDeclaration` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `ModActionEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ModDefinition` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ModManifest` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ModParamDeclaration` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `ModSettings` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ModSetup` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `NativeBytes` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `NodePatch` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `Note` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteLevel` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `NoteMask` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteMaskCover` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteMaskEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `NotePage` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteQuery` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteSnapEnd` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteSnapMax` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteSnapTintMode` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `NoteSubmission` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `OffsetSide` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `OnlySpec` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `OptionKind` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PagingKind` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PagingSpec` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelAction` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelBadge` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelMeter` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelNote` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelPart` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelRow` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelSection` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelStatus` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelTile` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PanelTone` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `PatternRandomness` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `PatternStep` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `PatternStepsInput` | [Editor mods (editor.*)](https://prism.am/dev/md/reference/sdk/editor.md#types) | | `PauseMenuRow` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PauseMenuState` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PerformanceRequest` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `PerformanceResult` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `Permission` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PixelBox` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PlayContext` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PlayerState` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `Playfield` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PlayfieldAnchor` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `PlayfieldSide` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PlayfieldSpec` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `PlayfieldUpdate` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `PopupAction` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `PopupActionEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `PopupDefinition` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `Provides` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `RatingColorStop` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingColors` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingDeclaration` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingField` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingFieldSource` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingPanel` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingPattern` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingProgress` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `RatingSeries` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `RatingSeriesSource` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `Report` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `ResponseFormat` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ResponseSpec` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ResultAction` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ResultDetail` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `ScrollDirection` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `ScrollSpeedContext` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `ScrollSpeedDefinition` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `ScrollSpeedParam` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `ScrollSpeedToMs` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `SearchSpec` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `SetAccuracy` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `SetHolds` | [Judgements, modifiers, scroll speeds and chart transforms](https://prism.am/dev/md/reference/sdk/gameplay.md#types) | | `Shadow` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `ShowWhen` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `SkinDefinition` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinDescription` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `SkinHud` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `SkinImportAction` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinImportCreate` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `SkinImportCreated` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinImportOpened` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinImportStaged` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinIni` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinLayout` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `SkinManifest` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinSetup` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SkinSource` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `Song` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SongEndEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SongStartEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SongTime` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SourceFile` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SourceImage` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SourceKind` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `SpriteSize` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `StageAlign` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageAnimation` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageColumn` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageCue` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageEmitter` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageEvent` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageJudgementFilter` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageLayer` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StagePoint` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageProps` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageRect` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageRequest` | [Download sources and skin import](https://prism.am/dev/md/reference/sdk/downloads.md#types) | | `StageSize` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageSpace` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageSprite` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageText` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StageTrigger` | [Native drawing (stage)](https://prism.am/dev/md/reference/sdk/stage.md#types) | | `StagedFile` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `StorageEntry` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `Style` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `TabDeclaration` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `TabExtensionDeclaration` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `TabField` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `TabFieldSource` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `TabPanel` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `TabSlot` | [Tabs and the local leaderboard](https://prism.am/dev/md/reference/sdk/tabs.md#types) | | `TableDefinition` | [Ratings, tables, calculators and library filters](https://prism.am/dev/md/reference/sdk/ratings.md#types) | | `TextAlign` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `TextBinding` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `TextNode` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `TextureFilter` | [Game state, storage, logging and keys](https://prism.am/dev/md/reference/sdk/game.md#types) | | `TickEvent` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `TierCount` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `TierInfo` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `TierRef` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `TimingPoint` | [Declarations and ctx](https://prism.am/dev/md/reference/sdk/declarations.md#types) | | `Transform` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | | `VersusMetric` | [HUD](https://prism.am/dev/md/reference/sdk/hud.md#types) | ===== Page: Declarations and ctx Address: https://prism.am/dev/reference/sdk/declarations/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Declarations and ctx defineMod, defineSkin, defineChart, defineEditorMod, the manifest types, permissions and the ctx global. ## Conventions {#conventions} Song times are in microseconds (`timeUs`) except where a field says milliseconds (`Hit.offsetMs`, judgement windows). Layout and style lengths are fractions of the screen height; `x`, `y` are fractions of the parent. An out-of-range value throws in the script. The permissions are `stage`, `skinImport` and `network`, declared in `defineMod`. ## Functions {#functions} ### `defineChart` {#definechart} ```dts function defineChart(input: ChartDefinition): ChartManifest; ``` Declares a map script, a script that ships with one map and only reshapes its playfield. Call it once at the top level and export the result. The declaration has no id: only `apiVersion` (2: "the map script requires modding API version 1; this game provides version 2"), `permissions` and `images`. Errors: "defineChart must be called exactly once", "defineChart declares a map script: this mod declares itself with defineMod", "defineChart can only be called at the top level of the map script"; without it, "the map script must declare itself with `export default defineChart({ … })`". `setup(play)` receives the `PlayContext`. A map script may call `playfield.*`, `lanes.*`, `game.*`, `log.*` and `ctx.on`; `hud.*` and `storage.*` throw "`X` is not available to map scripts: they only change the playfield". It has no `uses`, so `ctx.has` is always false for it. ```ts export default defineChart({ apiVersion: 2, setup(play) { playfield.set({ scroll: play.columns > 4 ? "up" : "down" }); }, }); ``` ### `defineMod` {#definemod} ```dts function defineMod(input: ModDefinition): ModManifest; ``` Declares the mod. Call it exactly once, at the top level of `main.ts` (or `index.ts`), and export the result as the default export. `setup(mod)` runs once the declaration is accepted, with the validated manifest. Anything else is refused: "defineMod can only be called at the top level of the mod's entry file", "defineMod must be called exactly once" (the first error is kept even when the script catches it), "defineMod declares a mod: this skin declares itself with defineSkin". Without a declaration the host reports "`main.ts` must declare the mod with `export default defineMod({ … })` at its top level". Checks: `id` is 1 to 64 characters from `a-z 0-9 . - _`, starts and ends with a letter or digit, no `..`; `name` and `author` at most 64 characters, `description` at most 1024, `homepage` an http(s) URL of at most 256 characters; `version` is a semantic version ("`version` must be a semantic version such as 1.0.0, got "1.0""); `apiVersion` must be the game's (2): "`my-mod` requires modding API version 1; this game provides version 2"; `loadOrder` 0 to 10000 (1000 by default); `images` at most 64 `.png` paths. An unknown field is refused ("unknown field `x`, expected one of …"). Ids are shared with the skin and every other mod: "another mod already uses the id `X`: the folder `Y` loaded first and keeps it". Only `stage`, `skinImport` and `network` exist as permissions. At load time only `defineMod`, `log.*` and `ctx.on` work; every other call throws "`X` is not available while the mod loads: call it from `setup` or an event handler". ```ts export default defineMod({ id: "hello", name: "Hello", version: "1.0.0", apiVersion: 2, setup(mod) { log.info(`${mod.name} ${mod.version} is ready`); }, }); ``` ### `defineSkin` {#defineskin} ```dts function defineSkin(input: SkinDefinition): SkinManifest; ``` Declares the skin script (`skin.ts` of a skin package). Same rules, limits and messages as `defineMod` (identity checks, `apiVersion` 2, one call at the top level, shared id space), with `defineSkin` in the text: a mod that calls it gets "defineSkin declares a skin: this mod declares itself with defineMod". There is no `loadOrder`. `setup(play)` receives the `PlayContext` of the map being launched: mode, layout, column count, screen size, the song and the judgement tiers. It is where a skin calls `playfield.set` and `lanes.set`; the host waits for it at most 1000 ms. A skin may use `hud.*` and `storage.*` (its storage file is `mod-storage/skins/.json`) but never `register` functions. If the skin script fails three times in a row or times out three times, it is disabled until the next map launch (a mod stays disabled until the game restarts). ```ts export default defineSkin({ id: "wide-lanes", name: "Wide lanes", version: "1.0.0", apiVersion: 2, setup(play) { log.info(`${play.song.title}: ${play.columns} columns`); playfield.set({ scroll: "down" }); }, }); ``` ### `translate` {#translate} ```dts function translate(key: string, values?: Record): string; ``` Returns the game's translated text for an interface key, in the language the player uses, filling `{name}` placeholders from `values`. It exists only in editor mods (`defineEditorMod`), which run in the map editor of the web interface, never in the game. The language is the editor's (English, French, Chinese or Korean); a `{name}` in the text is replaced by the matching entry of `values`, or stays as written when `values` has none. A key the catalogue does not know throws. Prefer it to hard-coded English for every label an editor mod shows. ```ts fragment const title: string = translate("editor.mod_markers_title"); ``` ## The ctx global {#ctx} ```dts on(event: K, handler: HostEventHandler): void; off(event: K, handler: HostEventHandler): void; has(id: string): boolean; element(id: string): { configure(options: Record): void }; ``` The script's own context. Every script (mod, skin, map script) has it as a global. - `ctx.on(event, handler)` registers a handler for one of the 25 events; handlers of an event run in registration order, an `async` handler is awaited. Register at the top level or in `setup`. `ctx.off(event, handler)` removes the first registration of that function; a delivery already in progress still runs it. - `ctx.has(id)` is true when a package named in `uses` is present, version-compatible and running. `ctx.element("pkg/element").configure(options)` hands options to an element another package provides: the options are checked against the provider's declaration ("unknown option `x`, expected one of …"), it throws "add `pkg` to `uses` to configure its elements" when `pkg` is not in `uses`, and does nothing when the provider is absent. Both exist once the script has declared itself, and a map script has no `uses`. - `ctx.hot` (`data`, `save`, `dispose`) and the timers are declared but inert today: Prism never reloads a script in place, so `save` and `dispose` callbacks never run, and `setTimeout` / `setInterval` callbacks never fire. Do not build on them; use `game.tick` and `game.beat` for time. - `import { ctx, console, setTimeout, setInterval, clearTimeout, clearInterval } from "manivelle:env"` reaches the same objects as a module import. `console.*` writes to the process error output, not to the Mods page: use `log.info` and `log.warn`. A dynamic `import()` is refused ("dynamic import() is not supported; use a static import"). - Every handler runs under the mod's budget: 30 ms per call, 16 MiB of heap; 3 consecutive errors or 3 timeouts disable the script, with the message "exceeded the 30ms execution budget N times" or "failed 3 times in a row; last error: …". ```ts fragment ctx.on("game.songEnd", (end) => { log.info(`finished at ${end.accuracy.toFixed(2)}%`); }); ``` ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type Permission = "stage" | "skinImport" | "network"; type ChartDefinition = { apiVersion: number; permissions?: Permission[]; images?: string[]; setup?: ChartSetup; }; type ChartSetup = (play: PlayContext) => void | Promise; type PlayContext = { mode: string; layout: string; layoutSkin: string; columns: number; screenWidth: number; screenHeight: number; song: Song; judgements: JudgementConfig; }; type Song = { title: string; artist: string; creator: string; difficulty: string; mode: string; layout: string; keys: number; durationUs: number; noteCount: number; ratings: Record; holdCount: number; bpm?: BpmRange | null; timing: TimingPoint[]; }; type BpmRange = { min: number; max: number; main: number; }; type TimingPoint = { timeUs: number; bpm: number; beatUs: number; meter: number; }; type JudgementConfig = { preset: string; tiers: TierInfo[]; }; type TierInfo = { index: number; id: string; name: string; symbol?: string | null; color: string; gradient?: string[] | null; earlyMs?: number | null; lateMs?: number | null; weight?: number | null; breaksCombo: boolean; }; type ChartManifest = { apiVersion: number; permissions?: Permission[]; images?: string[]; }; type ModDefinition = { id: string; name: string; version: string; apiVersion: number; author?: string | null; description?: string | null; homepage?: string | null; fonts?: Record; uses?: Record; provides?: Provides; permissions?: Permission[]; images?: string[]; loadOrder?: number; setup?: ModSetup; }; type Dependency = string | DependencySpec; type DependencySpec = { version: string; required?: boolean; feature?: string | null; }; type Provides = { elements?: Record; }; type ElementDeclaration = { root?: string | null; options?: Record; }; type ElementOption = { type: OptionKind; min?: number | null; max?: number | null; values?: string[]; maxLength?: number | null; default?: unknown | null; label?: string | null; player?: boolean; }; type OptionKind = "number" | "integer" | "boolean" | "string" | "color" | "enum" | "colors"; type ModSetup = (mod: ModManifest) => void | Promise; type ModManifest = { id: string; name: string; version: string; apiVersion: number; author?: string | null; description?: string | null; homepage?: string | null; fonts?: Record; uses?: Record; provides?: Provides; permissions?: Permission[]; images?: string[]; loadOrder?: number; }; type SkinDefinition = { id: string; name: string; version: string; apiVersion: number; author?: string | null; description?: string | null; homepage?: string | null; fonts?: Record; uses?: Record; provides?: Provides; permissions?: Permission[]; images?: string[]; setup?: SkinSetup; }; type SkinSetup = (play: PlayContext) => void | Promise; type SkinManifest = { id: string; name: string; version: string; apiVersion: number; author?: string | null; description?: string | null; homepage?: string | null; fonts?: Record; uses?: Record; provides?: Provides; permissions?: Permission[]; images?: string[]; }; type HostEventContext = { on(event: K, handler: HostEventHandler): void; off(event: K, handler: HostEventHandler): void; has(id: string): boolean; element(id: string): { configure(options: Record): void }; }; type HostEvents = { "chart.transform": ChartTransformEvent; "controls.action": ModActionEvent; "elements.configure": ElementConfigure; "game.beat": Beat; "game.judgement": JudgementEvent; "game.lobbyLive": LobbyLiveEvent; "game.pause": SongTime; "game.pauseMenu": PauseMenuState; "game.playfieldChange": Playfield; "game.resume": SongTime; "game.settingsChange": ModSettings; "game.songEnd": SongEndEvent; "game.songStart": SongStartEvent; "game.tick": TickEvent; "leaderboard.result": LeaderboardResult; "library.chartAdd": ChartAdded; "library.chartsAdded": ChartsAdded; "library.ready": LibraryReady; "metron.performanceResult": PerformanceResult; "playfield.noteMask": NoteMaskEvent; "ratings.progress": RatingProgress; "skinImport.action": SkinImportAction; "skinImport.created": SkinImportCreated; "skinImport.opened": SkinImportOpened; "skinImport.staged": SkinImportStaged; "ui.action": PopupActionEvent; }; type ChartTransformEvent = { id: string; }; type ModActionEvent = { id: string; pressed: boolean; timeUs: number; }; type ElementConfigure = { element: string; from: string; options: unknown; }; type Beat = { index: number; timeUs: number; bpm: number; meterBeat: number; }; type JudgementEvent = { column: number; timeUs: number; offsetUs: number; tier: TierRef; combo: number; counts: number[]; accuracy: number; }; type TierRef = { index: number; id: string; name: string; color: string; }; type LobbyLiveEvent = { rank: number; players: number; accuracy: number; rival?: LobbyRival | null; coop?: LobbyCoopLive | null; }; type LobbyRival = { name: string; accuracy: number; rank: number; gap: number; chosen: boolean; }; type LobbyCoopLive = { partner: string; partnerAccuracy: number; pairAccuracy?: number | null; }; type SongTime = { timeUs: number; }; type PauseMenuState = { rows: PauseMenuRow[]; selection: number; volume: number; rate: number; }; type PauseMenuRow = "continue" | "restart" | "quit" | "volume" | "swap" | "seekBack" | "seekForward" | "speed"; type Playfield = { keys: number; lanes: Lane[]; sides: PlayfieldSide[]; hitY: number; spawnY: number; scrollTimeUs: number; }; type Lane = { column: number; x: number; width: number; }; type PlayfieldSide = { x: number; y: number; width: number; height: number; zoom: number; aspect: number; }; type ModSettings = { volume: number; showFps: boolean; scrollTimeMs: number; audioOffsetMs: number; ratingSystem: string; }; type SongEndEvent = { counts: number[]; maxCombo: number; accuracy: number; aborted: boolean; }; type SongStartEvent = { song: Song; judgements: JudgementConfig; versusCentre: number; playfield: Playfield; timeUs: number; }; type TickEvent = { timeUs: number; hitCount: number; }; type LeaderboardResult = { requestId: number; chartId: number; offset: number; total: number; entries: LeaderboardEntry[]; judgement: string; performance?: LeaderboardPerformance | null; unavailableReplays: number; error?: string | null; }; type LeaderboardEntry = { rank: number; replayId: string; playerName?: string | null; received: boolean; accuracy: number; performance?: number | null; performanceNonstandard: boolean; maxCombo: number; misses: number; tiers: TierCount[]; rate: number; modified: boolean; playedAtMs: number; }; type TierCount = { name: string; count: number; }; type LeaderboardPerformance = { calculator: string; unit: string; }; type ChartAdded = { chartId: number; }; type ChartsAdded = { chartIds: number[]; truncated: boolean; }; type LibraryReady = {}; type PerformanceResult = { requestId: number; calculator: string; value?: number | null; unit: string; error?: string | null; }; type NoteMaskEvent = { id: string; params: Record; }; type RatingProgress = { requestId: number; id: string; done: number; total: number; failed: number; finished: boolean; error?: string | null; ahead: number; }; type SkinImportAction = { id: string; }; type SkinImportCreated = { requestId: number; id?: string | null; error?: string | null; }; type SkinImportOpened = { importerId: string; locale: string; source?: SkinSource | null; error?: string | null; }; type SkinSource = { sourceId: number; label: string; kind: SourceKind; ini?: SkinIni | null; images: SourceImage[]; sections: IniSection[]; files: SourceFile[]; truncated: boolean; totalBytes: number; problems: string[]; }; type SourceKind = "folder" | "archive"; type SkinIni = { general: IniGeneral; mania: ManiaSection[]; fontsUsed: boolean; problems: string[]; }; type IniGeneral = { name?: string | null; author?: string | null; version?: string | null; }; type ManiaSection = { keys: number; columnStart?: number | null; columnWidth: number[]; columnSpacing: number[]; columnLineWidth: number[]; hitPosition?: number | null; lightPosition?: number | null; scorePosition?: number | null; comboPosition?: number | null; judgementLine?: boolean | null; upsideDown?: boolean | null; noteBodyStyle?: number | null; lightFramePerSecond?: number | null; barlineHeight?: number | null; widthForNoteHeightScale?: number | null; specialStyle?: number | null; keysUnderNotes?: boolean | null; colourColumnLine?: string | null; colourBarline?: string | null; colourJudgementLine?: string | null; colourHold?: string | null; stageLeft?: string | null; stageRight?: string | null; stageBottom?: string | null; stageHint?: string | null; stageLight?: string | null; lightingN?: string | null; lightingL?: string | null; columns: ManiaColumn[]; ignored: string[]; }; type ManiaColumn = { noteImage?: string | null; noteImageH?: string | null; noteImageL?: string | null; noteImageT?: string | null; keyImage?: string | null; keyImageD?: string | null; noteBodyStyle?: number | null; colour?: string | null; colourLight?: string | null; }; type SourceImage = { name: string; frames: number; hasStill: boolean; scale: number; width: number; height: number; bytes: number; blank?: boolean | null; bounds?: PixelBox | null; peakColor?: string | null; peakWidth?: number | null; }; type PixelBox = { left: number; top: number; width: number; height: number; }; type IniSection = { name: string; entries: IniEntry[]; }; type IniEntry = { key: string; value: string; }; type SourceFile = { path: string; width: number; height: number; bytes: number; }; type SkinImportStaged = { requestId: number; stageId?: number | null; report?: Report | null; error?: string | null; }; type Report = { files: StagedFile[]; totalBytes: number; budgetBytes: number; overBudget: boolean; problems: string[]; }; type StagedFile = { path: string; bytes: number; width: number; height: number; }; type PopupActionEvent = { id: string; }; type HostEventHandler = ( payload: HostEvents[K], ) => HostEventReply; type HostEventReply = K extends keyof HostReplies ? HostReplies[K] | Promise : void | Promise; type HostReplies = {}; type HostHotContext = { readonly data: unknown; save(snapshot: () => unknown): void; dispose(cleanup: () => void): void; }; ``` ===== Page: Events Address: https://prism.am/dev/reference/sdk/events/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Events Every event a script can subscribe to with ctx.on, and its payload type. ## Events {#events} ### `chart.transform` {#event-chart-transform} Payload: `ChartTransformEvent` Asks your mod to transform the chart of a play that is about to start. The payload is `{ id }`: the `id` of the `chartTransform` modifier (declared by `gameplay.register`) that the player switched on. It is delivered during play preparation, never during the play, and only to the mod that owns the modifier, once per switched-on modifier, in load order; the notes a handler leaves are the ones the next modifier is offered. Inside the handler, and only there, `chart.getNotes` and `chart.setNotes` work. A mod that has no handler for the event, whose handler throws, runs too long or runs out of memory has its modification dropped with a notice; the other modifiers and the map are untouched. A handler that never calls `chart.setNotes` changes nothing. Check `request.id` when the mod declares several modifiers. ```ts fragment ctx.on("chart.transform", (request) => { if (request.id !== "rotate") return; const notes = chart.getNotes(); chart.setNotes({ startUs: notes.startUs, endUs: notes.endUs, column: notes.column.map((value) => (value + 1) % notes.keys), kind: notes.kind }); }); ``` See [Transforming the chart](https://prism.am/dev/md/guides/chart-transform.md). ### `controls.action` {#event-controls-action} Payload: `ModActionEvent` A key the player bound to one of the mod's `controls.register` actions was pressed (`pressed: true`) or released, with its song time. Delivered only to the mod that registered the action, only while a play runs (never in the map editor), and an action the mod withdrew is ignored. `id` is the action's own id, not the namespaced binding. ```ts fragment ctx.on("controls.action", ({ id, pressed, timeUs }) => { if (id === "mark" && pressed) storage.set({ key: "mark", value: timeUs }); }); ``` ### `elements.configure` {#event-elements-configure} Payload: `ElementConfigure` Delivered to the provider of an element, when another package or the player sets options on it. A package declares an element in `provides.elements`; a package that lists the provider in `uses` calls `ctx.element("/").configure(options)`; the host checks the options against the declaration and hands the result to the provider as this event. Only the provider receives it, never the caller. Payload: `element` is the element's name in the provider's `provides.elements` (without the provider prefix), `from` the id of the package that configured it, or `player` when the player's own values from the game's settings apply, and `options` every declared option: the value set, else the player's, else the declared default (an option with none of these is left out). The player's values win over a package's, and the latest package wins over earlier ones; options the player set that the declaration refuses are ignored. It fires after each `configure` call and when the player's values change, and once after the provider's `setup` for options set before it ran, so register the handler in `setup` and build the element from the payload. It also fires when a configuring skin is replaced at a map launch, with the options the other packages and the player leave. Without a configuration, the provider receives no event: use the declared defaults until one arrives. If the provider is absent, `configure` does nothing and the event never fires. ```ts fragment ctx.on("elements.configure", (configure) => { if (configure.element === "accuracy") log.info(`options from ${configure.from}: ${JSON.stringify(configure.options)}`); }); ``` ### `game.beat` {#event-game-beat} Payload: `Beat` The song clock reached a beat of the chart's timing points. `index` counts beats from the first timing point across tempo changes (negative before it), `timeUs` is the beat's song time, `bpm` the tempo of its timing point and `meterBeat` its position in the measure (0 on the downbeat; measures restart at each timing point). One event per beat, delivered when the clock reaches it; a late mod thread skips beats rather than delivering a burst. Nothing fires while paused or for a chart without timing points. Delivered to every running script. ```ts fragment ctx.on("game.beat", (beat) => { if (beat.meterBeat === 0) log.info(`downbeat ${beat.index} at ${beat.bpm} BPM`); }); ``` ### `game.judgement` {#event-game-judgement} Payload: `JudgementEvent` One note was judged. `column` is the lane, `timeUs` the song time of the judgement, `offsetUs` the input time minus the note time (the hold end for a release; 0 for a miss), `tier` a reference to the tier (`index`, `id`, `name`, `color`), and `combo`, `counts` (per tier, miss last) and `accuracy` (percent) are the totals after this judgement. Fires for every judgement of the play, so keep the handler short (30 ms budget). The queue between the game and scripts holds 1024 events and drops the newest when it is full: a script that must not lose anything reads `game.hits` or `game.player` instead. Delivered to every running script. ```ts fragment ctx.on("game.judgement", (judgement) => { if (judgement.tier.index === 0) log.info(`perfect on lane ${judgement.column}, ${judgement.offsetUs / 1000} ms`); }); ``` ### `game.lobbyLive` {#event-game-lobbylive} Payload: `LobbyLiveEvent` The player's live standing in a multiplayer lobby round, sent only while a lobby play runs and only when the figures changed. `rank` is the place by live accuracy (1 leads, a tie shares the better place), `players` the number of players of the round, `accuracy` the player's own (percent) and `rival` the player they are compared with, or `null` when nobody else plays: `name` (24 characters at most), `accuracy`, `rank`, `gap` (the player's accuracy minus theirs, in points: positive when ahead) and `chosen` (picked on the lobby page, otherwise the default rival). Everything but the player's own accuracy is declared by the other games, so it never ranks anything. Read-only host data, never a network read from the script. ```ts fragment ctx.on("game.lobbyLive", (live) => { log.info(`#${live.rank}/${live.players}${live.rival ? `, gap ${live.rival.gap.toFixed(2)}` : ""}`); }); ``` ### `game.pause` {#event-game-pause} Payload: `SongTime` The play was paused. Payload `timeUs`, the song time. The song clock stops with it, so `game.tick` and `game.beat` stop too. Delivered to every running script. ```ts fragment ctx.on("game.pause", ({ timeUs }) => log.info(`paused at ${timeUs} µs`)); ``` ### `game.pauseMenu` {#event-game-pausemenu} Payload: `PauseMenuState` The pause menu changed: it opened, the selection moved or a value changed. `rows` lists the rows shown (`continue`, `restart`, `quit`, `volume`, and in a watched replay `swap`, `seekBack`, `seekForward`, `speed`), `selection` is the index of the highlighted one, `volume` the music volume (0 to 1) and `rate` the replay speed (0.25 to 2; 1 outside a watched replay). A mod that draws the pause menu rebuilds its nodes on each event; row labels come from `hud.text` label bindings, translated by the game. ```ts fragment ctx.on("game.pauseMenu", (menu) => { log.info(`row ${menu.selection}: ${menu.rows[menu.selection]}`); }); ``` ### `game.playfieldChange` {#event-game-playfieldchange} Payload: `Playfield` The playfield moved or resized (window resize, layout change). The payload is the new `Playfield`, as `game.playfield()` returns it. Redraw anything you positioned from `lanes`, `sides` or `hitY`. Delivered to every running script. ```ts fragment ctx.on("game.playfieldChange", (field) => { log.info(`${field.keys} lanes, hit line at ${field.hitY}`); }); ``` ### `game.resume` {#event-game-resume} Payload: `SongTime` The play resumed, or the pause menu closed (a closed menu is announced as a resume, not as a `game.pauseMenu`). Payload `timeUs`, the song time. The clock, ticks and beats start again. ```ts fragment ctx.on("game.resume", ({ timeUs }) => log.info(`resumed at ${timeUs} µs`)); ``` ### `game.settingsChange` {#event-game-settingschange} Payload: `ModSettings` The player changed a setting scripts can read: the payload is the full `ModSettings` (`volume`, `showFps`, `scrollTimeMs`, `audioOffsetMs`, `ratingSystem`). It is also sent once at startup, before any play. Delivered to every running script. ```ts fragment ctx.on("game.settingsChange", (settings) => { log.info(`scroll time ${settings.scrollTimeMs} ms`); }); ``` ### `game.songEnd` {#event-game-songend} Payload: `SongEndEvent` The play finished or the player left it. `counts` per tier (miss last), `maxCombo` and `accuracy` (percent) are the replay's result when the chart finished, the live totals when `aborted` is true. Delivered once per play to every running script; `game.player().playing` is false afterwards. ```ts fragment ctx.on("game.songEnd", (end) => { if (!end.aborted) storage.set({ key: "last", value: end.accuracy }); }); ``` ### `game.songStart` {#event-game-songstart} Payload: `SongStartEvent` A chart starts playing. Payload: the `song`, the `judgements` (also `game.judgements()`), the `playfield` of this play, `versusCentre` (the width, in screen heights, a side-by-side comparison keeps free between its two playfields; unused in solo) and `timeUs`, the song time playback begins at (negative during a lead-in). Delivered once per play to every running script: the skin, the map script and the mods. From then on `game.notes`, `game.playfield`, `game.judgements` and the `playfield.*` live calls work. Drop the state of the previous play here (counters, nodes you built per play). ```ts fragment ctx.on("game.songStart", (start) => { log.info(`${start.song.title}: ${start.judgements.tiers.length} tiers, starts at ${start.timeUs} µs`); }); ``` ### `game.tick` {#event-game-tick} Payload: `TickEvent` A heartbeat while the song clock runs: 30 per second by default. Payload `timeUs` (song time) and `hitCount`, the number of real, non-miss hits of the play read from the native history (so it is exact even when `game.judgement` events were dropped). Use it to poll `game.hits`, `game.keys` or `game.player` only when `hitCount` changed. Ticks stop while paused, a tick that is late is skipped rather than delivered in a burst, and a handler that is slower than the interval just gets later ticks. Offline video exports deliver one tick per frame. ```ts fragment let seen = 0; ctx.on("game.tick", ({ hitCount }) => { if (hitCount === seen) return; seen = hitCount; const last = game.hits({ limit: 1 })[0]; if (last) log.info(`last hit ${last.offsetMs.toFixed(1)} ms`); }); ``` ### `leaderboard.result` {#event-leaderboard-result} Payload: `LeaderboardResult` The answer to `leaderboard.query` or `leaderboard.best`. `requestId` is the number the function returned; match it, because a mod may have two requests outstanding. The payload carries the page (`chartId`, `offset`, `total` of the whole ranking, `entries`), the `judgement` name the ranking was evaluated under, the `performance` calculator and unit when the ranking has one, `unavailableReplays` (recorded plays whose replay could not be read or judged again; they are not in `total`) and `error`, an English message when no ranking could be built (`total` is then 0 and `entries` empty). It is delivered only to the mod that asked, from the mods thread, under the mod's usual budget. It arrives once per accepted request, in no guaranteed order against other requests. A mod that was disabled or unloaded meanwhile, or a host that was replaced, never receives it: the request is forgotten. ```ts fragment ctx.on("leaderboard.result", (result) => { if (result.error) log.warn(result.error); else log.info(`${result.total} plays, ${result.entries.length} listed under ${result.judgement}`); }); ``` Triggered by [leaderboard.query](https://prism.am/dev/md/reference/sdk/tabs.md#leaderboard-query) and [leaderboard.best](https://prism.am/dev/md/reference/sdk/tabs.md#leaderboard-best). ### `library.chartAdd` {#event-library-chartadd} Payload: `ChartAdded` A chart was added to the library by an explicit scan (a pack was installed, the player scanned a folder). The payload is `{ chartId }`, a library chart id as used by `leaderboard.query`, `ratings.backfill` and your tables. It is delivered after the scan's transaction committed, once per added chart, to every running script that subscribed. An explicit scan that adds thousands of charts sends thousands of events: prefer `library.chartsAdded` for batch work. It is sent after `library.chartsAdded` of the same scan. ```ts fragment ctx.on("library.chartAdd", (added) => log.info(`chart ${added.chartId} added`)); ``` ### `library.chartsAdded` {#event-library-chartsadded} Payload: `ChartsAdded` The charts one scan added, in a single event. `chartIds` holds up to 8192 ids; `truncated` is `true` when the scan added more, in which case `chartIds` has only the first 8192 and a mod that wants every chart asks for a whole-library `ratings.backfill` (without `charts`). It is delivered after the scan's transaction committed, to every running script that subscribed, before the per-chart `library.chartAdd` events of the same scan. An empty scan sends nothing. ```ts fragment ctx.on("library.chartsAdded", (added) => { ratings.backfill(added.truncated ? { id: "prismcalc-1" } : { id: "prismcalc-1", charts: added.chartIds }); }); ``` The ids can be passed straight to `charts` of [ratings.backfill](https://prism.am/dev/md/reference/sdk/ratings.md#ratings-backfill). ### `library.ready` {#event-library-ready} Payload: `LibraryReady` Asks the mods to run their whole-library check: the menu has loaded and the library can be queried. The payload is empty (`{}`). It is delivered to every running script that subscribed, and more than once per session: when the interface (re)loads, after a global library scan, when the mods restart, and when the player presses "Recalculate ratings". A handler must therefore be idempotent. It is the usual moment for a whole-library `ratings.backfill`, which only calculates the charts that lack a current row. ```ts fragment ctx.on("library.ready", () => { ratings.backfill({ id: "prismcalc-1" }); }); ``` ### `metron.performanceResult` {#event-metron-performanceresult} Payload: `PerformanceResult` The answer to `metron.performance`. `requestId` is the number the function returned. `calculator` is the id asked for, `value` the performance (`null` when it failed), `unit` is `pp`, or `SSR` for `etterna-515`, and `error` is the English reason when `value` is `null`. It is delivered only to the mod that asked. The result is bound to the play it was asked in: if the song changed before the calculation finished, the result is dropped and no event arrives. Do not wait for it forever; ask again in the next play. ```ts fragment ctx.on("metron.performanceResult", (result) => { if (result.error) log.warn(result.error); else log.info(`${result.calculator}: ${result.value} ${result.unit}`); }); ``` Triggered by [metron.performance](https://prism.am/dev/md/reference/sdk/ratings.md#metron-performance). ### `playfield.noteMask` {#event-playfield-notemask} Payload: `NoteMaskEvent` Asks your mod for the covers and the lift of a play that is about to start. The payload is `{ id, params }`: the `id` of the `noteMask` modifier (declared by `gameplay.register`) the player switched on, and the value of every parameter that modifier declared in `params`, by id: the player's saved value clamped to the declared `min` and `max`, or the declared `default` when the player never changed it. An id the mod did not declare never appears. It is delivered during play preparation, never during the play, and only to the mod that owns the modifier, once per switched-on modifier, in load order. Inside the handler, and only there, `playfield.setNoteMask` works. A mod that has no handler for the event, whose handler throws, runs too long or runs out of memory has its modification dropped with a notice; the other modifiers and the play are untouched. A handler that never calls `playfield.setNoteMask` changes nothing. Check `request.id` when the mod declares several modifiers. ```ts fragment ctx.on("playfield.noteMask", (request) => { if (request.id !== "lift") return; playfield.setNoteMask({ lift: request.params.liftHeight }); }); ``` See [Setting the playfield mask](https://prism.am/dev/md/guides/gameplay-modifiers.md#note-mask). ### `ratings.progress` {#event-ratings-progress} Payload: `RatingProgress` A progress report of a `ratings.backfill` request, delivered only to the mod that made it. `requestId` is the number the function returned and `id` the rating's id. `done` charts were calculated of `total` (the charts that lacked a current row when the request started), `failed` of them unavailable. `finished` is `true` on the last report, after which no more arrive for that request; `error` is set when the whole request failed. `ahead` is the number of calculations waiting before this request in the library's one queue (0 once it runs); `done` and `total` stay 0 until it starts. Several reports arrive per request, so check `finished` before starting the next backfill. A report that arrives after the request was closed (the mod was stopped) is not delivered. The game shows the same progress in its processing window without any code from the mod. ```ts fragment ctx.on("ratings.progress", (progress) => { if (progress.finished) log.info(`${progress.id}: ${progress.done}/${progress.total}, ${progress.failed} failed`); }); ``` Triggered by [ratings.backfill](https://prism.am/dev/md/reference/sdk/ratings.md#ratings-backfill). ### `skinImport.action` {#event-skinimport-action} Payload: `SkinImportAction` The player pressed a button of your import panel. The payload is `{ id }`, the `id` of the action you declared in `skinImport.panel`. It is delivered only to the mod that owns the panel. `dismiss` is the game's own button: the game closes the panel itself and the event is not delivered for it. Actions that carry `editSkin` open that skin in the editor and are not delivered either. Everything else reaches you, in the order the player presses them. ```ts fragment ctx.on("skinImport.action", (action) => { if (action.id === "retry") skinImport.panel({ title: "Retrying", status: "working" }); }); ``` ### `skinImport.created` {#event-skinimport-created} Payload: `SkinImportCreated` The answer to `skinImport.create`. `requestId` is the number the function returned; `id` is the folder name of the new skin, which may differ from the id you asked for (a suffix such as `-2` is added when the name was taken), and `error` is the reason when the folder could not be written or failed the inspection a skin goes through. It is delivered only to the mod that asked, and only if the player has not closed the panel or picked another source meanwhile: a stale answer is dropped. ```ts fragment ctx.on("skinImport.created", (created) => { if (created.error) skinImport.panel({ title: "Failed", status: "error", detail: created.error }); }); ``` Triggered by [skinImport.create](https://prism.am/dev/md/reference/sdk/downloads.md#skinimport-create). ### `skinImport.opened` {#event-skinimport-opened} Payload: `SkinImportOpened` The player picked a source for one of your importers and the native worker read it. The payload is `importerId` (which of your importers), `locale` (the interface language, `en`, `fr`, `zh` or `ko`, for the panel's texts), and `source` or `error`. `source` describes what was read: `sourceId` (give it to `skinImport.stage`), `label`, `kind` (`folder` or `archive`), the parsed `ini` (general fields, mania sections), the `images` with their sizes and frames, `truncated`, `totalBytes` and `problems`. `error` is set instead when the source could not be read. It is delivered only to the mod that owns the importer, once per pick. A new pick replaces the previous source and preparation; an answer that arrives after the panel was closed is dropped. The game opens the dialog: the mod never sees a path. ```ts fragment ctx.on("skinImport.opened", (opened) => { if (opened.error || !opened.source) return; log.info(`${opened.source.images.length} pictures in ${opened.source.label}`); }); ``` ### `skinImport.staged` {#event-skinimport-staged} Payload: `SkinImportStaged` The answer to `skinImport.stage`. `requestId` is the number the function returned. On success `stageId` names the preparation for `skinImport.create` and `report` lists the generated files, `totalBytes`, `budgetBytes` (900 KiB), `overBudget` and `problems`; otherwise `error` says why. It is delivered only to the mod that asked, and a stale answer (panel closed, another source picked) is dropped. Only the latest preparation can be created. ```ts fragment ctx.on("skinImport.staged", (staged) => { if (staged.report?.overBudget) log.warn(`${staged.report.totalBytes} bytes, over the budget`); }); ``` Triggered by [skinImport.stage](https://prism.am/dev/md/reference/sdk/downloads.md#skinimport-stage). ### `ui.action` {#event-ui-action} Payload: `PopupActionEvent` A button of the mod's `ui.popup` was clicked. `id` is the action's `id`, or `dismiss` when the player closed the popup with its own button (the popup is already removed then). Delivered only to the mod that owns the popup. ```ts fragment ctx.on("ui.action", ({ id }) => { if (id === "cancel") ui.dismiss(); }); ``` ### Defined elsewhere {#elsewhere} `ChartTransformEvent` (declarations), `ModActionEvent` (declarations), `ElementConfigure` (declarations), `Beat` (declarations), `JudgementEvent` (declarations), `TierRef` (declarations), `LobbyLiveEvent` (declarations), `LobbyRival` (declarations), `LobbyCoopLive` (declarations), `SongTime` (declarations), `PauseMenuState` (declarations), `PauseMenuRow` (declarations), `Playfield` (declarations), `Lane` (declarations), `PlayfieldSide` (declarations), `ModSettings` (declarations), `SongEndEvent` (declarations), `SongStartEvent` (declarations), `Song` (declarations), `BpmRange` (declarations), `TimingPoint` (declarations), `JudgementConfig` (declarations), `TierInfo` (declarations), `TickEvent` (declarations), `LeaderboardResult` (declarations), `LeaderboardEntry` (declarations), `TierCount` (declarations), `LeaderboardPerformance` (declarations), `ChartAdded` (declarations), `ChartsAdded` (declarations), `LibraryReady` (declarations), `PerformanceResult` (declarations), `NoteMaskEvent` (declarations), `RatingProgress` (declarations), `SkinImportAction` (declarations), `SkinImportCreated` (declarations), `SkinImportOpened` (declarations), `SkinSource` (declarations), `SourceKind` (declarations), `SkinIni` (declarations), `IniGeneral` (declarations), `ManiaSection` (declarations), `ManiaColumn` (declarations), `SourceImage` (declarations), `PixelBox` (declarations), `IniSection` (declarations), `IniEntry` (declarations), `SourceFile` (declarations), `SkinImportStaged` (declarations), `Report` (declarations), `StagedFile` (declarations), `PopupActionEvent` (declarations) ===== Page: Game state, storage, logging and keys Address: https://prism.am/dev/reference/sdk/game/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Game state, storage, logging and keys game.*, playfield.*, lanes.*, log.*, ui.*, storage.* and controls.*. ## Functions {#functions} ### `controls.register` {#controls-register} ```dts function controls.register(input: ModActionDeclaration): void; ``` Declares a key action that appears in the game's Controls screen under the mod's name. Mods only, from `setup` (otherwise "controls.register is only available in a mod's setup"). `id` follows the usual id rule (`a-z 0-9 -`, at most 32 characters; "action id is registered twice"), `name` at most 64 characters, `defaultKey` a physical key code of the game's key list such as `KeyK` or `Space` ("action defaultKey must be an accepted physical key code, got …"). A mod registers at most 32 actions. The player may rebind it; the binding is stored under `/`. Presses arrive as the `controls.action` event. ```ts fragment controls.register({ id: "mark", name: "Mark this moment", defaultKey: "KeyM" }); ``` ### `game.hits` {#game-hits} ```dts function game.hits(input: HitQuery): HitList; ``` The latest real hits (judgements that are not misses), oldest first: `offsetMs` is input minus target in milliseconds (negative early, positive late) and `tier` an index into `game.judgements().tiers`. `limit` is 1 to 256 (50 by default). `player` is 0 (the left side, the watched play) or 1 (the right side of a side-by-side replay), otherwise "player must be 0 (left side) or 1 (right side), got N". The history is native and never lost, unlike the `game.judgement` event; `game.tick` carries `hitCount` so a script only queries when it changed. Hold heads and releases are separate hits. ```ts fragment const recent = game.hits({ limit: 20 }); const mean = recent.reduce((sum, hit) => sum + hit.offsetMs, 0) / Math.max(1, recent.length); ``` ### `game.judgements` {#game-judgements} ```dts function game.judgements(input: void): JudgementConfig | null; ``` The judgement configuration of the play: preset name and `tiers` (index, id, name, colour, early/late windows in ms when the set has them, `breaksCombo`). Returns `null` outside a play. Tier indexes in `game.judgement`, `game.hits` and `counts` arrays refer to this list; the last tier is the miss. ```ts fragment const config = game.judgements(); const names = config?.tiers.map((tier) => tier.name) ?? []; ``` ### `game.keys` {#game-keys} ```dts function game.keys(input: KeyQuery): KeyState; ``` The state of the keys of the play: per lane whether it is held, how many presses it counted, and the key (`KeyD`) and gamepad input (`pad:a`) it is bound to (`null` when unbound), plus the latest presses with their song time. `limit` is 0 to 256 (64 by default; 0 returns only the lanes). `player` as in `game.hits`. Only lanes 0 to 15 are recorded. `play` identifies the history: a new one starts with each play, seek or section restart, so a script that sees it change restarts its own counts. `total` changes with every press. Read-only and native, independent of the event queue: it needs no permission. ```ts fragment const keys = game.keys({ limit: 0 }); const held = keys.lanes.filter((lane) => lane.pressed).length; ``` ### `game.notes` {#game-notes} ```dts function game.notes(input: NoteQuery): NotePage; ``` Reads the chart in pages: notes whose time is in `[fromUs, toUs)`, optionally of one `column`, sorted by time. `limit` is 1 to 256 (64 by default; "limit must be in [1, 256], got N"). When more notes remain, `next` is a cursor to pass as `cursor` for the following page. Times are song time in microseconds, hold ends in `endUs`. Readable from `game.songStart` on. ```ts fragment let cursor: number | null | undefined; let total = 0; do { const page = game.notes({ fromUs: 0, toUs: 10_000_000, column: 0, cursor }); total += page.notes.length; cursor = page.next; } while (cursor != null); log.info(`${total} notes in column 0 during the first 10 s`); ``` ### `game.player` {#game-player} ```dts function game.player(input: void): PlayerState; ``` A snapshot of the player's progress in the current play: `playing`, `paused`, the song time (extrapolated from the last clock event), `combo`, `maxCombo`, `counts` per tier of `game.judgements()` (miss last), `judged` (their sum) and `accuracy` in percent (100 before the first judgement). Cheap enough for a `game.tick` handler. Outside a play it reports `playing: false`. ```ts fragment ctx.on("game.tick", () => { const player = game.player(); if (player.combo > 0 && player.combo % 100 === 0) log.info(`combo ${player.combo}`); }); ``` ### `game.playfield` {#game-playfield} ```dts function game.playfield(input: void): Playfield | null; ``` Where the playfield is on screen, or `null` before the first play: `keys`, one `lanes` entry per column (`x` of the centre as a fraction of the screen width, `width` as a fraction of the screen height), `sides` (the box of each playfield: one in solo, two in a side-by-side comparison; place per-side elements from it), `hitY` and `spawnY` (fractions of the screen height) and `scrollTimeUs`, the time a note takes from spawn to hit line. It changes with the window and the layout: listen to `game.playfieldChange` instead of caching it. ```ts fragment const field = game.playfield(); const firstLane = field?.lanes[0]; ``` ### `game.settings` {#game-settings} ```dts function game.settings(input: void): ModSettings | null; ``` The player's settings a script may read, or `null` before the game sent them (it sends them once at startup): `volume` 0 to 1, `showFps`, `scrollTimeMs`, `audioOffsetMs`, and `ratingSystem`, the difficulty scale selected in the library (not the active judgement set). Read-only. `game.settingsChange` fires when one changes. ```ts fragment const settings = game.settings(); if (settings?.showFps) log.info("FPS display is on"); ``` ### `game.song` {#game-song} ```dts function game.song(input: void): Song | null; ``` Returns the `Song` being played (title, artist, difficulty, keys, duration, ratings, BPM range, `timing` of at most 1024 points), or `null` before the first play. Available to every kind of script from `setup` on; at load it throws "`game.song` is not available while the mod loads". It is set by `game.songStart`. ```ts fragment const song = game.song(); if (song) log.info(`${song.artist} - ${song.title} (${song.keys}K)`); ``` ### `lanes.set` {#lanes-set} ```dts function lanes.set(input: LaneUpdate): void; ``` Sets the look of one lane: `column` (from 0) and `lane`, the per-lane fields (sprites, offsets, key and stage lights…), merged over earlier calls for that column. In `setup` it is part of the starting state; during a play colours and offsets move to the new value over `transitionMs` (0 to 10000; instant when absent) with `easing`. Same availability and errors as `playfield.update` (skins and map scripts, `setup` or a handler during a play). ```ts fragment lanes.set({ column: 0, lane: { noteOffsetY: 0.01 }, transitionMs: 200 }); ``` ### `log.info` {#log-info} ```dts function log.info(input: string): void; ``` Writes an informational line to the Mods page under the script's id. Works in every phase, including while the file loads, and for every kind of script. Text over 1024 characters is cut and ends with `…`. The message queue holds 256 lines; further lines are dropped. Use it instead of `console.log`, which does not reach the Mods page. ```ts fragment log.info(`loaded ${mod.id}`); ``` ### `log.warn` {#log-warn} ```dts function log.warn(input: string): void; ``` Same as `log.info` with the level of a warning, shown highlighted on the Mods page. Use it for a recoverable problem the player should notice, not for progress notes. ```ts fragment log.warn("the chart has no timing point; beat effects are off"); ``` ### `playfield.set` {#playfield-set} ```dts function playfield.set(input: PlayfieldSpec): void; ``` Sets playfield properties for a skin or a map script (mods get "`playfield.set` is only available to skins and map scripts"). Call it in `setup`: fields are merged over what earlier calls set, so calls can be split. During a play it applies at once, with no transition (use `playfield.update` to animate); outside `setup` and a play it throws "`playfield.set` only works in the skin's `setup` and in its handlers during a play". Values are validated against the field bounds (`x`, `y` in 0 to 1 of the screen, `lanes` at most 32 entries…); an invalid value throws with the field name. A live image must be one the package loaded at launch (declared in `images`). ```ts fragment playfield.set({ x: 0.5, scroll: "up", zoom: 1.1 }); ``` ### `playfield.setNoteMask` {#playfield-setnotemask} ```dts function playfield.setNoteMask(input: NoteMask): void; ``` Sets how the playfield is drawn for the play that is about to start: a cover on the spawn side of the notes' region (`sudden`), a cover on the receptor side of every lane (`hidden`) and a lift of the receptor line (`lift`), all in percent of the height of the lanes' box. Only the mods that declared a `noteMask` modifier call it, and only inside their `playfield.noteMask` handler; elsewhere it throws ``playfield.setNoteMask is only available inside a `playfield.noteMask` handler``. Every part is optional, and an absent part is drawn as the skin draws it. `sudden` and `hidden` are `{ size, feather }`: `size` from 10 to 100, `feather` from 0 to 50 (the part of the cover's far edge that fades out). `lift` goes from 0 (not raised) to 50 and never carries the receptor line past the spawn edge. Numbers are rounded to the nearest whole percent. A number outside its range, `NaN` or infinite, an unknown field or a wrong type throws in your script with the reason; the first refusal drops the whole modification of that mod even when the script catches the exception, and the play is drawn without it with a notice. With several calls in one handler the last valid one wins. Two mods of one play cannot set the same part: the later one in load order is dropped with a notice. The numbers are copied once, when the play starts, into what the renderer draws and the replay records (`chartMods.visual`); nothing of your script runs while the play is drawn, and a mask never changes the notes or the judging, so the play stays ranked. ```ts fragment ctx.on("playfield.noteMask", (request) => { if (request.id !== "curtain") return; playfield.setNoteMask({ sudden: { size: request.params.height, feather: 10 } }); }); ``` See [Setting the playfield mask](https://prism.am/dev/md/guides/gameplay-modifiers.md#note-mask). ### `playfield.update` {#playfield-update} ```dts function playfield.update(input: PlayfieldUpdate): void; ``` Changes the playfield during a play: `patch` fields replace the current ones; numbers and colours move there over `transitionMs` (0 to 10000, instant when absent) with `easing` (`linear` by default, `easeIn`, `easeOut`, `easeInOut`); images switch at once, and each must be one the skin loaded at launch. Skins and map scripts only, from a handler between `game.songStart` and `game.songEnd`: otherwise "the playfield only changes while a chart plays: call it from a handler between `game.songStart` and `game.songEnd`". In `setup` it merges like `playfield.set`. Changes are queued and applied at the end of the step. ```ts fragment ctx.on("game.beat", (beat) => { if (beat.meterBeat === 0) { playfield.update({ patch: { zoom: 1.05 }, transitionMs: 120, easing: "easeOut" }); } }); ``` ### `storage.clear` {#storage-clear} ```dts function storage.clear(input: void): void; ``` Deletes every key of this script's storage. Same availability as `storage.get`. It cannot be undone. ```ts fragment storage.clear(); ``` ### `storage.get` {#storage-get} ```dts function storage.get(input: string): unknown | null; ``` Reads a value saved by this script, or `null` when the key is absent. Mods and skins only, after load (a map script gets "`storage.get` is not available to map scripts: they only change the playfield"). The file is `mod-storage/.json` (skins: `mod-storage/skins/.json`); it survives restarts and uninstalling the mod keeps it. A corrupt or oversized file makes `setup` fail with "storage : …". ```ts fragment const best = storage.get("best"); const bestScore = typeof best === "number" ? best : 0; ``` ### `storage.keys` {#storage-keys} ```dts function storage.keys(input: void): string[]; ``` Lists the saved keys in alphabetical order. Same availability as `storage.get`. ```ts fragment const saved: string[] = storage.keys(); ``` ### `storage.remove` {#storage-remove} ```dts function storage.remove(input: string): void; ``` Deletes a key. Removing an absent key does nothing. Same availability as `storage.get`. ```ts fragment storage.remove("history"); ``` ### `storage.set` {#storage-set} ```dts function storage.set(input: StorageEntry): void; ``` Saves a JSON `value` under a `key` (one argument: `{ key, value }`). Keys have 1 to 128 characters ("storage keys must have 1 to 128 characters"); at most 256 keys ("the storage holds at most 256 keys"); at most 262144 bytes (256 KiB) of key bytes plus JSON text ("the storage holds at most 262144 bytes; this value would bring it to N"). Replacing a key counts only the difference. Writes reach the disk at most once per second and when the mod stops. Same availability as `storage.get`. ```ts fragment storage.set({ key: "best", value: 98.4 }); storage.set({ key: "history", value: [{ at: 1, accuracy: 98.4 }] }); ``` ### `ui.dismiss` {#ui-dismiss} ```dts function ui.dismiss(input: void): void; ``` Closes the mod's own popup. Does nothing when none is open. Mods only ("only mods dismiss menu popups"). ```ts fragment ui.dismiss(); ``` ### `ui.popup` {#ui-popup} ```dts function ui.popup(input: PopupDefinition): void; ``` Shows (or updates) the mod's popup on the game's menu screens: a title, a detail line, a progress bar (`done` of `total`) and up to four action buttons. A mod has one popup; calling again with other content replaces it, and the same content does nothing. Mods only ("only mods display menu popups"); at most eight mods may have a popup open at once ("at most eight mod popups may be open"). Bounds: `title` 1 to 96 characters, `detail` at most 512, `done` ≤ `total` ≤ 10 000 000, at most 4 actions, each with an `id` of 1 to 32 characters from `a-z 0-9 _` (not `dismiss`, which is the player's own close button) and a `label` of 1 to 64 characters. Breaking them throws "popup title, detail, progress or actions exceed their bounds" or "invalid or duplicate popup action". A click arrives as `ui.action`. ```ts fragment ui.popup({ title: "Rating backfill", detail: "Computing ratings", done: 120, total: 800, actions: [{ id: "cancel", label: "Cancel" }], }); ``` ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type ModActionDeclaration = { id: string; name: string; defaultKey: string; }; type HitQuery = { limit?: number | null; player?: number | null; }; type HitList = Hit[]; type Hit = { offsetMs: number; tier: number; }; type KeyQuery = { limit?: number | null; player?: number | null; }; type KeyState = { play: number; total: number; lanes: KeyLane[]; presses: KeyPress[]; }; type KeyLane = { column: number; pressed: boolean; count: number; key?: string | null; pad?: string | null; }; type KeyPress = { column: number; timeUs: number; }; type NoteQuery = { fromUs: number; toUs: number; column?: number | null; cursor?: number | null; limit?: number | null; }; type NotePage = { notes: Note[]; next?: number | null; }; type Note = { index: number; column: number; timeUs: number; endUs?: number | null; }; type PlayerState = { playing: boolean; paused: boolean; timeUs: number; combo: number; maxCombo: number; counts: number[]; judged: number; accuracy: number; }; type LaneUpdate = { column: number; lane: LaneSpec; transitionMs?: number | null; easing?: Easing | null; }; type LaneSpec = { note?: string | null; receptor?: string | null; receptorPressed?: string | null; holdBody?: string | null; holdEnd?: string | null; stageLight?: string | null; stageLightColor?: string | null; stageLightSize?: SpriteSize | null; stageLightOffsetY?: number | null; stageLightOn?: boolean | null; stageLightOpacity?: number | null; stageLightScale?: number | null; stageLightFadeMs?: number | null; keyLightOn?: boolean | null; keyLightOpacity?: number | null; keyLightScale?: number | null; keyLightFadeMs?: number | null; noteOffsetY?: number | null; receptorOffsetX?: number | null; receptorOffsetY?: number | null; holdEndOffset?: number | null; holdMatchNoteWidth?: boolean | null; holdWidthScale?: number | null; holdEndSize?: SpriteSize | null; holdEndScale?: number | null; holdEndFlip?: boolean | null; holdEndRound?: boolean | null; holdEndFade?: number | null; holdEndFadeStart?: number | null; holdEndFadeMs?: number | null; holdEndHiddenMs?: number | null; noteTintStrength?: number | null; receptorTintStrength?: number | null; laneTintStrength?: number | null; lightTintStrength?: number | null; holdMissedStyle?: HoldMissedStyle | null; holdMissedColor?: string | null; holdMissedOpacity?: number | null; laneImage?: string | null; laneColor?: string | null; noteColor?: string | null; receptorColor?: string | null; pressedColor?: string | null; holdBodyColor?: string | null; holdEndColor?: string | null; offsetX?: number | null; offsetY?: number | null; width?: number | null; noteSize?: SpriteSize | null; receptorSize?: SpriteSize | null; hitSound?: string | null; }; type SpriteSize = { width: number; height: number; }; type HoldMissedStyle = "hide" | "tint"; type Easing = "linear" | "easeIn" | "easeOut" | "easeInOut" | "easeInCubic" | "easeOutCubic" | "easeInOutCubic" | "easeOutExpo" | "easeOutBounce"; type PlayfieldSpec = { x?: number | null; y?: number | null; anchor?: PlayfieldAnchor | null; rotation?: number | null; zoom?: number | null; laneWidth?: number | null; width?: number | null; laneGap?: number | null; laneHeight?: number | null; receptorY?: number | null; scroll?: ScrollDirection | null; noteSize?: SpriteSize | null; receptorSize?: SpriteSize | null; holdWidth?: number | null; holdEndSize?: SpriteSize | null; holdEndOffset?: number | null; holdMatchNoteWidth?: boolean | null; holdWidthScale?: number | null; holdEndScale?: number | null; holdEndFlip?: boolean | null; holdEndRound?: boolean | null; holdEndFade?: number | null; holdEndFadeStart?: number | null; holdEndFadeMs?: number | null; holdEndHiddenMs?: number | null; noteOffsetY?: number | null; receptorOffsetX?: number | null; receptorOffsetY?: number | null; stageLightSize?: SpriteSize | null; stageLightOffsetY?: number | null; hitLight?: string | null; hitLightOn?: HitLightOn | null; hitLightFollowJudgement?: boolean | null; stageLightOn?: boolean | null; stageLightOpacity?: number | null; stageLightScale?: number | null; stageLightFadeMs?: number | null; keyLightOn?: boolean | null; keyLightOpacity?: number | null; keyLightScale?: number | null; keyLightFadeMs?: number | null; hitLightOpacity?: number | null; hitLightScale?: number | null; holdLightOpacity?: number | null; holdLightScale?: number | null; hitLightFrames?: number | null; hitLightFps?: number | null; hitLightSize?: SpriteSize | null; hitLightOffsetY?: number | null; hitLightColor?: string | null; holdLight?: string | null; holdLightFrames?: number | null; holdLightFps?: number | null; holdLightSize?: SpriteSize | null; holdLightOffsetY?: number | null; holdLightColor?: string | null; mineLight?: string | null; mineLightFrames?: number | null; mineLightFps?: number | null; mineLightSize?: SpriteSize | null; mineLightOffsetY?: number | null; mineLightColor?: string | null; mineLightOpacity?: number | null; mineLightScale?: number | null; textureFilter?: TextureFilter | null; noteTintStrength?: number | null; receptorTintStrength?: number | null; laneTintStrength?: number | null; lightTintStrength?: number | null; holdMissedStyle?: HoldMissedStyle | null; holdMissedColor?: string | null; holdMissedOpacity?: number | null; laneCover?: boolean | null; laneCoverColor?: string | null; laneCoverOpacity?: number | null; laneCoverSize?: number | null; laneCoverFeather?: number | null; noteSnapColors?: boolean | null; noteSnapMax?: NoteSnapMax | null; noteSnapStrength?: number | null; noteSnapTintMode?: NoteSnapTintMode | null; noteSnapEnd?: NoteSnapEnd | null; noteSnapColor1?: string | null; noteSnapColor2?: string | null; noteSnapColor3?: string | null; noteSnapColor4?: string | null; noteSnapColor6?: string | null; noteSnapColor8?: string | null; noteSnapColor12?: string | null; noteSnapColor16?: string | null; noteSnapColor24?: string | null; noteSnapColor32?: string | null; noteSnapOther?: string | null; measureLines?: boolean | null; measureLineColor?: string | null; measureLineOpacity?: number | null; measureLineThickness?: number | null; measureLineLength?: MeasureLineLength | null; measureLineOvershoot?: number | null; measureLineEvery?: number | null; beatLines?: boolean | null; beatLineColor?: string | null; beatLineOpacity?: number | null; beatLineThickness?: number | null; borderWidth?: number | null; borderColor?: string | null; judgementLine?: boolean | null; judgementLineColor?: string | null; judgementLineThickness?: number | null; judgementLineOffsetY?: number | null; judgementLineAt?: JudgementLineAt | null; judgementWindowThickness?: number | null; judgementWindowOpacity?: number | null; judgementWindowDashed?: boolean | null; backgroundColor?: string | null; backgroundImage?: string | null; backgroundTint?: string | null; mine?: string | null; mineColor?: string | null; laneColor?: string | null; noteColor?: string | null; receptorColor?: string | null; pressedColor?: string | null; holdBodyColor?: string | null; holdEndColor?: string | null; note?: string | null; receptor?: string | null; receptorPressed?: string | null; holdBody?: string | null; holdEnd?: string | null; laneImage?: string | null; stageLight?: string | null; stageLightColor?: string | null; hitSound?: string | null; lanes?: LaneSpec[] | null; }; type PlayfieldAnchor = "topLeft" | "top" | "topRight" | "left" | "center" | "right" | "bottomLeft" | "bottom" | "bottomRight"; type ScrollDirection = "down" | "up"; type HitLightOn = "all" | "off"; type TextureFilter = "linear" | "nearest"; type NoteSnapMax = "1/1" | "1/2" | "1/3" | "1/4" | "1/6" | "1/8" | "1/12" | "1/16" | "1/24" | "1/32"; type NoteSnapTintMode = "multiply" | "replace"; type NoteSnapEnd = "head" | "own" | "off"; type MeasureLineLength = "playfield" | "lanes"; type JudgementLineAt = "center" | "top" | "bottom"; type NoteMask = { sudden?: NoteMaskCover | null; hidden?: NoteMaskCover | null; lift?: number | null; }; type NoteMaskCover = { size: number; feather: number; }; type PlayfieldUpdate = { patch: PlayfieldSpec; transitionMs?: number | null; easing?: Easing | null; }; type StorageEntry = { key: string; value: unknown; }; type PopupDefinition = { title: string; detail: string; done: number; total: number; actions?: PopupAction[]; }; type PopupAction = { id: string; label: string; }; ``` ### Defined elsewhere {#elsewhere} `JudgementConfig` (declarations), `TierInfo` (declarations), `Playfield` (declarations), `Lane` (declarations), `PlayfieldSide` (declarations), `ModSettings` (declarations), `Song` (declarations), `BpmRange` (declarations), `TimingPoint` (declarations) ===== Page: HUD Address: https://prism.am/dev/reference/sdk/hud/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # HUD hud.*: the on-screen elements a mod or a skin adds. ## Functions {#functions} ### `hud.box` {#hud-box} ```dts function hud.box(input: BoxNode): string; ``` Adds a rectangle (background, gradient, border, radius, shadow) and returns its `id`. Same caller, timing and node rules as `hud.text`. `fill` cuts the box horizontally at a fraction, from the left, and the overlay keeps it up to date: `songProgress` (follows the clock every frame), `accuracy`, `tierShare { tier }` (share of the judgements of that tier), `playerAccuracy { player }` (0 or 1, side-by-side replays). Every node (box, text, image, group) also takes these fields: - `visible`: hides the node; it adds to `showWhen`. - `showWhen`: `paused`, `running`, `showFps` (the player's setting), `judged` (after the first judgement), `ghost` (a ghost is racing), `versus` (side-by-side replay), `solo` (no comparison). - `animate { on, kind, durationMs }`: `on` is `judgement`, `miss` or `hit`; `kind` is `pop`, `popFade`, `popOut` or `flash`; `durationMs` 1 to 5000. It restarts at each occurrence and scales around the centre of the box. `popOut` goes from 1.25 to 1 in 140 ms while the opacity falls to 0 over the whole duration, then the node stays hidden. - `element`: ties the node to one HUD element the player can restyle: `fps`, `accuracy`, `hits`, `misses`, `combo`, `timer`, `remaining`, `status`, `judgement`, `judgementCounts`. The font the player chose for it replaces the node's. - `layout { x, y, width, height, anchor }`: `x`, `y` are fractions of the parent's width and height (the screen at the first level) in [-10, 10], ignored inside a `flow` group; `width` and `height` are in [0, 4] as fractions of the screen height; `anchor` is the point of the node placed at `(x, y)`: `topLeft` (default), `top`, `topRight`, `left`, `center`, `right`, `bottomLeft`, `bottom`, `bottomRight`. - `style`: every length is a fraction of the screen **height** (0.05 is 54 px at 1080p). Colours are `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` or `theme:`. `radius`, `padding`, `opacity`, `border.width`: [0, 1]; `size`: (0, 1], 0.04 by default; `weight`: 100 to 900 in steps of 100; `gradient`: `angle` and 2 to 8 stops (`at` in [0, 1]); `shadow`: `x`, `y` in [-1, 1], `blur` in [0, 1]; `transform`: `x`, `y` in [-4, 4], `scale` in [0, 10], `rotate` in [-3600, 3600] degrees; `transitionMs` up to 10000; `align`: `start`, `center`, `end`; `italic`. `shape` is `plate`, `control` or `panel` and wins over `radius`; `face` is a theme font token (`display`, `body`, `num`, `label`, `mono`…) and `font` wins over it; `label: true` applies the theme's label look. A value outside its range throws with the reason (for example "style.size must be in (0, 1], got 2"). ```ts fragment hud.box({ id: "bar", fill: { kind: "songProgress" }, layout: { x: 0.5, y: 0.98, width: 1.2, height: 0.006, anchor: "bottom" }, style: { background: "#66b3ff" }, }); ``` ### `hud.clear` {#hud-clear} ```dts function hud.clear(input: void): void; ``` Removes every node of the calling mod (or skin). Call it at `game.songStart` before rebuilding a HUD that depends on the song. ### `hud.group` {#hud-group} ```dts function hud.group(input: GroupNode): string; ``` Adds a container and returns its `id`; other nodes join it through their `parent`. Without `flow` the children are placed by their own `layout`. With `flow { direction, gap?, align?, justify? }` they are laid out in a `row` or a `column`: `gap` in [0, 1] (fraction of the screen height), `align` `start`, `center`, `end` or `stretch`, `justify` `start`, `center`, `end` or `spaceBetween`. Give the group a `width` and `height` if its children use fractions. Groups nest at most 8 levels ("groups nest at most 8 levels deep"); a parent must exist and be a group ("parent `x` does not exist", "parent `x` is not a group"); a node cannot be its own parent, and an `id` already used under another parent is refused ("node `x` already exists under another parent; remove it to move it"). Children keep their creation order. ```ts fragment hud.group({ id: "row", flow: { direction: "row", gap: 0.01 }, layout: { x: 0.02, y: 0.02 } }); hud.text({ id: "row-hits", parent: "row", text: "0", bind: { kind: "hits" } }); hud.text({ id: "row-misses", parent: "row", text: "0", bind: { kind: "misses" } }); ``` ### `hud.image` {#hud-image} ```dts function hud.image(input: ImageNode): string; ``` Adds a PNG and returns its `id`. `src` is a relative path to a `.png` file inside the mod's folder, at most 8 MiB, checked at the call (relative path, real file, PNG signature). `fit` is `contain` (default), `cover` or `fill`. Same caller, timing, node and style rules as `hud.box`; the 384-node limit counts it. ```ts fragment hud.image({ id: "logo", src: "logo.png", fit: "contain", layout: { x: 0.02, y: 0.02, width: 0.2, height: 0.1 } }); ``` ### `hud.remove` {#hud-remove} ```dts function hud.remove(input: string): void; ``` Removes the node and all its descendants. Does nothing if the node does not exist. Mods and skins only, from `setup` or an event handler. ### `hud.text` {#hud-text} ```dts function hud.text(input: TextNode): string; ``` Adds a text node and returns its `id`. Mods and skins only: a map script gets "`hud.text` is not available to map scripts: they only change the playfield". Call it from `setup` or an event handler, never while the file loads. Each mod owns a retained tree: a node stays until `hud.remove`, `hud.clear` or the mod is disabled. Reusing an `id` replaces the node in place (the parent must be the same). Limits per mod: 384 nodes ("the HUD node limit is 384 per mod"), `id` of 1 to 64 characters, `text` of at most 256 characters with no control character except `\n` and `\t`. `text` is shown outside a play; during a play `bind` replaces it with a value the overlay updates by itself, without a round trip through the script. Kinds of `bind`: - Counters: `combo`, `maxCombo`, `hits` (judged notes that are not misses), `misses`, `judged`, `remaining`. - `accuracy`, `ghostAccuracy`, `ghostDelta`, `playerAccuracy`, `versusGap`: `decimals` 0 to 4, 2 by default. - `tierCount { tier, digits?, padColor? }` and `tierName { tier }`: `tier` is an index from 0 to 32. `digits` (1 to 6) pads the count with zeros (`0284`); `padColor` is the colour of those leading zeros (of the whole count while it is 0). - `lastJudgement { colors? }`: the name of the last tier, coloured with its tier colour or with `colors` (keys are tier ids or indexes, 64 entries at most). - `lastOffset { decimals?, tinted?, colors?, side? }`: signed timing of the last judgement (`−12 ms`, `+8 ms`), `decimals` 0 to 3, `side` `early` or `late`; empty for a miss. - `pavg`: hits of the hardest tier over all judged notes. `tierRatio { rank }`: the `1:X` ratio, `rank` 0 (hardest tier) or 1. - Ghost: `ghostCombo`, `ghostName` (empty without a ghost). - Side-by-side replays (empty outside a comparison): `playerAccuracy`, `playerCombo`, `playerHits`, `playerMisses`, `playerTierCount { tier }`, `playerName`, `playerRate`, `playerLastJudgement`, all with `player` 0 (left) or 1 (right) (otherwise "must be 0 (left side) or 1 (right side)"); `versusGap { metric, decimals? }` with `metric` `accuracy`, `combo` or `misses` (left minus right). The single-play bindings describe the left side only: mark a solo element `showWhen: "solo"`. - Time: `elapsed`, `total` (`m:ss`), `timer` (`elapsed / total`), `fps`. - `label { label }`: a translated word, one of `hits`, `misses`, `combo`, `accuracy`, `paused`, `remaining`, `fps`, `early`, `late`, `ghost`, `difference`, `pauseMenuTitle`, `pauseMenuContinue`, `pauseMenuRestart`, `pauseMenuQuit`, `pauseMenuVolume`, `pauseMenuSpeed`, `kps`, `kpsMax`, `gap`. - `action { action }`: a native button shown only while the host allows it, one of 18 values: `skipIntro`; `pauseResume`, `pauseRestart`, `pauseQuit`, `pauseVolumeDown`, `pauseVolumeUp`, `pauseSwap`, `pauseSeekBack`, `pauseSeekForward`, `pauseSpeedDown`, `pauseSpeedUp`; `watchPlayPause`, `watchSeekBack`, `watchSeekForward`, `watchSpeedDown`, `watchSpeedUp`, `watchSwap`, `watchScrub`. ```ts fragment hud.text({ id: "combo", text: "0", bind: { kind: "combo" }, element: "combo", animate: { on: "hit", kind: "pop", durationMs: 150 }, layout: { x: 0.5, y: 0.3, anchor: "center" }, style: { size: 0.06, align: "center" }, }); ``` ### `hud.update` {#hud-update} ```dts function hud.update(input: NodePatch): void; ``` Changes an existing node without recreating it; returns nothing. The node must exist ("node `x` does not exist"). The given `layout` and `style` fields replace those of the node and the others stay. `text`/`bind`, `src`/`fit`, `flow` and `fill` only exist for their node type: on another type the call throws "node `x` is a box and has no `text`". It takes the same values and limits as the creation functions. Use it to toggle `visible` or to change a label from an event handler; values that follow the game (`bind`, `fill`) need no update. ```ts fragment hud.update({ id: "combo", visible: false }); ``` ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type BoxNode = { id: string; parent?: string | null; fill?: Fill | null; visible?: boolean | null; layout?: Layout | null; style?: Style | null; showWhen?: ShowWhen | null; animate?: Animate | null; element?: HudElement | null; }; type Fill = { kind: "songProgress"; } | { kind: "accuracy"; } | { kind: "tierShare"; tier: number; } | { kind: "playerAccuracy"; player: number; }; type Layout = { x?: number | null; y?: number | null; width?: number | null; height?: number | null; anchor?: Anchor | null; }; type Anchor = "topLeft" | "top" | "topRight" | "left" | "center" | "right" | "bottomLeft" | "bottom" | "bottomRight"; type Style = { color?: string | null; background?: string | null; gradient?: Gradient | null; border?: Border | null; radius?: number | null; padding?: number | null; opacity?: number | null; font?: string | null; face?: string | null; shape?: string | null; label?: boolean | null; size?: number | null; weight?: number | null; italic?: boolean | null; align?: TextAlign | null; shadow?: Shadow | null; transform?: Transform | null; transitionMs?: number | null; easing?: Easing | null; }; type Gradient = { angle: number; stops: GradientStop[]; }; type GradientStop = { color: string; at: number; }; type Border = { width: number; color: string; }; type TextAlign = "start" | "center" | "end"; type Shadow = { x: number; y: number; blur: number; color: string; }; type Transform = { x?: number | null; y?: number | null; scale?: number | null; rotate?: number | null; }; type ShowWhen = "paused" | "running" | "showFps" | "judged" | "ghost" | "versus" | "solo"; type Animate = { on: AnimateOn; kind: AnimateKind; durationMs: number; }; type AnimateOn = "judgement" | "miss" | "hit"; type AnimateKind = "pop" | "popFade" | "popOut" | "flash"; type HudElement = "fps" | "accuracy" | "hits" | "misses" | "combo" | "timer" | "remaining" | "status" | "judgement" | "judgementCounts"; type GroupNode = { id: string; parent?: string | null; flow?: Flow | null; visible?: boolean | null; layout?: Layout | null; style?: Style | null; showWhen?: ShowWhen | null; animate?: Animate | null; element?: HudElement | null; }; type Flow = { direction: FlowDirection; gap?: number | null; align?: FlowAlign | null; justify?: FlowJustify | null; }; type FlowDirection = "row" | "column"; type FlowAlign = "start" | "center" | "end" | "stretch"; type FlowJustify = "start" | "center" | "end" | "spaceBetween"; type ImageNode = { id: string; parent?: string | null; src: string; fit?: ImageFit | null; visible?: boolean | null; layout?: Layout | null; style?: Style | null; showWhen?: ShowWhen | null; animate?: Animate | null; element?: HudElement | null; }; type ImageFit = "contain" | "cover" | "fill"; type TextNode = { id: string; parent?: string | null; text: string; bind?: TextBinding | null; visible?: boolean | null; layout?: Layout | null; style?: Style | null; showWhen?: ShowWhen | null; animate?: Animate | null; element?: HudElement | null; }; type TextBinding = { kind: "combo"; } | { kind: "maxCombo"; } | { kind: "hits"; } | { kind: "misses"; } | { kind: "judged"; } | { kind: "remaining"; } | { kind: "accuracy"; decimals?: number | null; } | { kind: "ghostAccuracy"; decimals?: number | null; } | { kind: "ghostDelta"; decimals?: number | null; } | { kind: "ghostCombo"; } | { kind: "ghostName"; } | { kind: "playerAccuracy"; player: number; decimals?: number | null; } | { kind: "playerCombo"; player: number; } | { kind: "playerHits"; player: number; } | { kind: "playerMisses"; player: number; } | { kind: "playerTierCount"; player: number; tier: number; } | { kind: "playerName"; player: number; } | { kind: "playerRate"; player: number; } | { kind: "playerLastJudgement"; player: number; } | { kind: "versusGap"; metric: VersusMetric; decimals?: number | null; } | { kind: "tierCount"; tier: number; digits?: number | null; padColor?: string | null; roll?: boolean | null; } | { kind: "tierName"; tier: number; } | { kind: "pavg"; } | { kind: "tierRatio"; rank: number; } | { kind: "lastJudgement"; colors?: Record; } | { kind: "lastOffset"; decimals?: number | null; tinted?: boolean | null; colors?: Record; side?: OffsetSide | null; } | { kind: "elapsed"; } | { kind: "total"; } | { kind: "timer"; } | { kind: "fps"; } | { kind: "label"; label: HudLabel; } | { kind: "action"; action: HudAction; }; type VersusMetric = "accuracy" | "combo" | "misses"; type OffsetSide = "early" | "late"; type HudLabel = "hits" | "misses" | "combo" | "accuracy" | "paused" | "remaining" | "fps" | "early" | "late" | "ghost" | "difference" | "pauseMenuTitle" | "pauseMenuContinue" | "pauseMenuRestart" | "pauseMenuQuit" | "pauseMenuVolume" | "pauseMenuSpeed" | "kps" | "kpsMax" | "nps" | "gap"; type HudAction = "skipIntro" | "pauseResume" | "pauseRestart" | "pauseQuit" | "pauseVolumeDown" | "pauseVolumeUp" | "pauseSwap" | "pauseSeekBack" | "pauseSeekForward" | "pauseSpeedDown" | "pauseSpeedUp" | "watchPlayPause" | "watchSeekBack" | "watchSeekForward" | "watchSpeedDown" | "watchSpeedUp" | "watchSwap" | "watchScrub"; type NodePatch = { id: string; text?: string | null; bind?: TextBinding | null; fill?: Fill | null; src?: string | null; fit?: ImageFit | null; flow?: Flow | null; visible?: boolean | null; layout?: Layout | null; style?: Style | null; showWhen?: ShowWhen | null; animate?: Animate | null; element?: HudElement | null; }; ``` ### Defined elsewhere {#elsewhere} `Easing` (game) ===== Page: Native drawing (stage) Address: https://prism.am/dev/reference/sdk/stage/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Native drawing (stage) stage.*: sprites, shapes and animations drawn by the renderer (permission stage). ## Functions {#functions} ### `stage.clear` {#stage-clear} ```dts function stage.clear(input: void): void; ``` Removes every element, emitter and trigger of the calling script. Call it at `game.songStart` before rebuilding the scene. Same permission rules as `stage.sprite`; the player removing the permission clears the scene at once. ### `stage.emitter` {#stage-emitter} ```dts function stage.emitter(input: StageEmitter): string; ``` Creates a particle emitter and returns its `id`. Same permission, timing, `at`, `layer` and budget rules as `stage.sprite`. `size` is the particle size, `lifetimeMs` its life (at most 5000 ms), `maxParticles` the cap of live particles (at most 512 per emitter; the sum over the script is capped at 1024). `burst` particles come out each time the emitter receives the `burst` cue (at most 256), `rate` per second continuously. `speed`, `speedJitter`, `direction`, `spread` (degrees), `gravity` (within ±16) shape the motion; `color` fades to `endColor`; `fade` and `shrink` end the life smoothly; `image` draws a declared PNG instead of a square. An emitter on a `lane` or `receptor` position with no `column` projects its particles onto the column of the event that triggers it. When full, the oldest particle is replaced. ```ts fragment stage.emitter({ id: "sparks", at: { space: "receptor" }, size: 0.008, color: "#ffd24a", lifetimeMs: 380, speed: 0.55, spread: 150, gravity: 1.6, burst: 14, maxParticles: 120, }); stage.trigger({ id: "hit", on: { judgement: { tier: 0 } }, target: "sparks", play: "burst" }); ``` ### `stage.play` {#stage-play} ```dts function stage.play(input: StageCue): void; ``` Starts an animation of an element (`target`, `animation`) from the next frame, for example from an event handler. Same permission and timing rules as `stage.sprite`. Throws if the element does not exist or lacks that animation. At most 64 cues are queued; past that the oldest is dropped. ```ts fragment stage.play({ target: "glow", animation: "flash" }); ``` ### `stage.rect` {#stage-rect} ```dts function stage.rect(input: StageRect): string; ``` Draws a filled rectangle and returns its `id`. Same permission, timing, `at`, `layer`, animation and budget rules as `stage.sprite`; no image is needed. `radius` rounds the corners in screen heights (half the short side makes a circle or a pill). ```ts fragment stage.rect({ id: "bar", at: { space: "screen", x: 0.5, y: 0.9 }, size: { width: 0.4, height: 0.01 }, color: "#66b3ff", radius: 0.005 }); ``` ### `stage.remove` {#stage-remove} ```dts function stage.remove(input: string): boolean; ``` Removes the element or trigger with that `id` and returns `true` if there was one, `false` otherwise. Same permission and timing rules as `stage.sprite`. ### `stage.sprite` {#stage-sprite} ```dts function stage.sprite(input: StageSprite): string; ``` Draws a PNG image in the game's native renderer, in the same frame as the notes, and returns its `id`. It needs `permissions: ["stage"]` in `defineMod`, `defineSkin` or `defineChart` (map scripts may draw too): without it the call throws "`stage.sprite` needs the `stage` permission: declare `permissions: [\"stage\"]`", and if the player turned native drawing off for the mod: "`stage.sprite`: the player turned off native drawing for ``". `image` must be one of the `images` the script declared (64 at most): "image \"x\" is not declared in `images`: only declared images are loaded". Call it from `setup` or an event handler; a scene built in `setup` comes back after a reload, one built at `game.songStart` at the next play. Every stage element has an `id` (1 to 64 characters; recreating it replaces it in place, keeping running animations and particles) and these shared fields: - `at { space?, column?, x?, y? }`: `screen` (default; origin top left, `x` and `y` are fractions of the width and height), or `playfield` (centre of the columns' box), `lane` (centre of `column`), `receptor` (receptor of `column`), where `x` and `y` are screen heights, right and down. `lane` and `receptor` need a `column` (below 32). Every space other than `screen` follows the playfield when a map script moves it. - `layer`: `below` (behind the playfield), `lanes` (over the columns, under the notes), `above` (default, over the notes). All sit under the HUD. - `size { width, height }` from 0 to 4 screen heights; `opacity` 0 to 1; `scale` 0 to 16; `rotation` in degrees; `color` `#rgb` to `#rrggbbaa`; offsets within ±4. - `animations`: up to 8 named animations `{ durationMs, easing?, repeat?, from?, to? }`, each at most 10 s; `from` and `to` set `x`, `y` (screen-height offsets), `scale`, `rotation`, `opacity`, `color`. Missing values stay the element's own and return when the animation ends. `burst` is a reserved name. Run them with `stage.trigger`, `stage.play` or `stage.stop`. Budgets per script: 128 elements, 16 emitters, 1024 live particles, 64 triggers; past them the call throws, for example "the stage holds 128 elements, its limit". Out-of-range values throw "name: value is outside [min, max]". ```ts fragment stage.sprite({ id: "glow", image: "glow.png", at: { space: "receptor", column: 0 }, size: { width: 0.12, height: 0.12 }, opacity: 0, animations: { flash: { durationMs: 200, from: { opacity: 1 }, to: { opacity: 0 } } }, }); ``` ### `stage.stop` {#stage-stop} ```dts function stage.stop(input: StageCue): void; ``` Stops a running animation of an element (`target`, `animation`); the element returns to its own values. Same rules and errors as `stage.play`; this is how a `repeat` animation ends. ### `stage.text` {#stage-text} ```dts function stage.text(input: StageText): string; ``` Draws one line of text in the game's font and returns its `id`. Same permission, timing and rules as `stage.sprite`. `text` holds at most 128 characters ("text: longer than 128 characters"); `size` is the line height in screen heights (> 0); `align` is `start`, `center` or `end`. ```ts fragment stage.text({ id: "title", at: { space: "screen", x: 0.5, y: 0.1 }, text: "Go!", size: 0.05, align: "center" }); ``` ### `stage.trigger` {#stage-trigger} ```dts function stage.trigger(input: StageTrigger): string; ``` Registers a rule evaluated by the renderer every frame (nothing runs in the script). `on` has exactly one field: `judgement { tier?, column?, miss? }`, `press { column? }`, `release { column? }`, `holdStart { column? }` or `holdEnd { column? }`; absent filters match everything ("`on` needs exactly one of judgement, press, release, holdStart and holdEnd"). Give exactly one of `play` or `stop` (an animation name, or `burst` for an emitter): "a trigger needs exactly one of `play` and `stop`". `target` must be an existing element with that animation ("element `x` does not exist", "element `x` has no animation `y`"). Same permission and timing rules as `stage.sprite`. Limit: 64 triggers per script; the same `id` replaces. The shot fires in the very frame the note is judged. ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type StageEmitter = { id: string; layer?: StageLayer | null; at: StagePoint; image?: string | null; size: number; color?: string | null; endColor?: string | null; lifetimeMs: number; speed?: number | null; speedJitter?: number | null; direction?: number | null; spread?: number | null; gravity?: number | null; burst?: number | null; rate?: number | null; maxParticles: number; fade?: boolean | null; shrink?: boolean | null; }; type StageLayer = "below" | "lanes" | "above"; type StagePoint = { space?: StageSpace | null; column?: number | null; x?: number | null; y?: number | null; }; type StageSpace = "screen" | "playfield" | "lane" | "receptor"; type StageCue = { target: string; animation: string; }; type StageRect = { id: string; layer?: StageLayer | null; at: StagePoint; size: StageSize; color?: string | null; radius?: number | null; opacity?: number | null; rotation?: number | null; scale?: number | null; animations?: Record | null; }; type StageSize = { width: number; height: number; }; type StageAnimation = { durationMs: number; easing?: Easing | null; repeat?: boolean | null; from?: StageProps; to?: StageProps; }; type StageProps = { x?: number | null; y?: number | null; scale?: number | null; rotation?: number | null; opacity?: number | null; color?: string | null; }; type StageSprite = { id: string; layer?: StageLayer | null; at: StagePoint; image: string; size: StageSize; color?: string | null; opacity?: number | null; rotation?: number | null; scale?: number | null; animations?: Record | null; }; type StageText = { id: string; layer?: StageLayer | null; at: StagePoint; text: string; size: number; color?: string | null; align?: StageAlign | null; opacity?: number | null; rotation?: number | null; scale?: number | null; animations?: Record | null; }; type StageAlign = "start" | "center" | "end"; type StageTrigger = { id: string; on: StageEvent; target: string; play?: string | null; stop?: string | null; }; type StageEvent = { judgement?: StageJudgementFilter | null; press?: StageColumn | null; release?: StageColumn | null; holdStart?: StageColumn | null; holdEnd?: StageColumn | null; }; type StageJudgementFilter = { tier?: number | null; column?: number | null; miss?: boolean | null; }; type StageColumn = { column?: number | null; }; ``` ### Defined elsewhere {#elsewhere} `Easing` (game) ===== Page: Judgements, modifiers, scroll speeds and chart transforms Address: https://prism.am/dev/reference/sdk/gameplay/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Judgements, modifiers, scroll speeds and chart transforms judgements.*, gameplay.*, scrollSpeed.* and chart.*. ## Functions {#functions} ### `chart.getNotes` {#chart-getnotes} ```dts function chart.getNotes(input: void): ChartNotes; ``` Returns the notes of the chart about to be played, as four typed arrays plus a few numbers. It works only inside a `chart.transform` handler, and only in the mod the event was delivered to. Elsewhere it throws ``chart.getNotes is only available inside a `chart.transform` handler``. The notes are the 1x chart, before the music rate, after the transformations that ran earlier. `count` entries per array: `startUs` and `endUs` are little-endian `Float64` values (read them with `new Float64Array(notes.startUs.buffer, notes.startUs.byteOffset, notes.count)`), `column` is one byte per note from 0, `kind` is one byte per note: 0 tap, 1 hold, 2 burst, 3 mine. `endUs` is 0 for a tap and a mine. `keys` is the column count, `durationUs` the end of the map, `seed` a random number drawn for this play and this mod, the seed of a reproducible shuffle. Times are microseconds. ```ts fragment ctx.on("chart.transform", (request) => { if (request.id !== "stats") return; const notes = chart.getNotes(); const holds = notes.kind.filter((kind) => kind === 1).length; log.info(`${holds} holds in ${notes.count} notes on ${notes.keys} keys`); }); ``` A handler that never calls `chart.setNotes` leaves the chart untouched. See [Transforming the chart](https://prism.am/dev/md/guides/chart-transform.md). ### `chart.setNotes` {#chart-setnotes} ```dts function chart.setNotes(input: NoteSubmission): void; ``` Hands the game the full replacement for the chart. It works only inside the `chart.transform` handler of the mod that received the event, and the game delivers that event only for a modifier of kind `chartTransform` that the player switched on. Elsewhere it throws ``chart.setNotes is only available inside a `chart.transform` handler``. Give the same four arrays as `chart.getNotes` (`Uint8Array`, an `ArrayBuffer` or an array of bytes), with any note count up to 100000; notes may be in any order, the game sorts them by start time. The game validates the buffers and refuses the whole modification of the mod on the first problem, even when the script catches the exception and submits another buffer: the notes stay as they were and a notice is shown, the map is never corrupted. A run that is too slow or out of memory is dropped the same way. A play whose notes ended up different is unranked. ```ts fragment ctx.on("chart.transform", (request) => { if (request.id !== "rotate") return; const notes = chart.getNotes(); const column = notes.column.map((value) => (value + 1) % notes.keys); chart.setNotes({ startUs: notes.startUs, endUs: notes.endUs, column, kind: notes.kind }); }); ``` Errors you will see: `100001 notes exceed the limit of 100000`, `` `column` holds 10 bytes, 12 expected for 12 notes``, ``note 3: a tap or a mine has no end time, `endUs` must be 0 (got 500)``, `note 3: kind 7 is not 0 (tap), 1 (hold), 2 (burst) or 3 (mine)`, `note 3: column 5 is outside the 4 columns`, `note 3: two notes at 1000 us in column 1`, `note 3: starts at 900 us in column 1 before the note before it ends (1500 us)`, and `note 3: … us is outside the map (… us)`. ### `gameplay.register` {#gameplay-register} ```dts function gameplay.register(input: GameplayModifierDeclaration): void; ``` Declares a modifier the player switches on from the Mods tab. Only mods call it, and only from `setup`. The modifier is published as `/`. `kind` says what the game does when it is on: `auto`, `ghost`, `fullLn` and `noPause` are native behaviors; `chartTransform` hands the chart to your script through the `chart.transform` event (see `chart.getNotes` and `chart.setNotes`); `noteMask` hands the drawing of the playfield (covers on the notes' region, a lift of the receptor line) to your script through the `playfield.noteMask` event (see `playfield.setNoteMask`). `mirror`, `noLn` and `rankedFullLn` are built into Prism and a mod cannot declare them; the old `sudden`, `hidden` and `lift` kinds are gone, those modifiers are `noteMask` mods. `group` is one of `assist`, `layout`, `longNotes`, `timing`, `difficulty`, `other`; when absent the kind's own group applies. `icon` is one of 28 lucide names (`MODIFIER_ICONS` in `modifiers.rs`); when absent the kind's icon applies. `conflictsWith` lists up to 8 keys written `/`: the Mods tab refuses to switch both on. A `noteMask` modifier declares its own sliders in `params` (at most 8; the other kinds take none, the game declares those of `fullLn`): each is `{ id, label, description, section, min, max, step, default, unit? }` with an `id` of letters and digits starting with a letter, integer bounds within ±1000000, `min < max`, a `step` from 1 to `max - min`, a `default` inside the bounds and a `unit` of `%` or `ms`. A play whose notes a `chartTransform` script changed is unranked; a `noteMask` modifier only changes what is drawn and never unranks; the other native kinds keep their own rules. | Limit | Value | | --- | --- | | Modifiers per mod | 8 | | `id` | `a-z`, `0-9`, `-`, 1 to 32 characters | | `name` | 1 to 32 characters | | `description` | 1 to 200 characters | | `conflictsWith` | at most 8 keys | ```ts fragment gameplay.register({ id: "steady", name: "Steady", description: "The pause key and a lost window focus do nothing during the play.", kind: "noPause", group: "other", icon: "shield", }); ``` Errors you will see: `Mirror is built into Prism: a mod cannot declare it` (also `No long notes is built into Prism: …` and `Full long notes is built into Prism: …`), `modifier id is registered twice`, `a mod registers at most 8 gameplay modifiers`, `modifier group "x" is not one of assist, layout, longNotes, timing, difficulty, other`, `modifier icon "x" is not an allowed icon`, `conflict "x" is not a / key`. See [Gameplay modifiers](https://prism.am/dev/md/guides/gameplay-modifiers.md). ### `judgements.register` {#judgements-register} ```dts function judgements.register(input: JudgementSetDefinition): void; ``` Adds a judgement set the player can pick in the settings: a list of tiers (Perfect, Great, …, then the Miss) with their timing windows and weights. Only mods call it, and only from `setup`. The set is published as `/`, at most 97 characters. `tiers` is a pure function from the set's parameter values to the tiers. The host calls it for every combination of parameters while the mods load (up to 4096 combinations per set and 1 second for all sets together); a set with more combinations resolves the rest on first use. A tier takes `windowMs` for both sides, or `earlyMs` and `lateMs`; all times are milliseconds. `accuracy` and `holds` pick the native scoring: see the guide. | Limit | Value | | --- | --- | | Sets per mod | 8 | | Set id, tier id | `a-z`, `0-9`, `-`, 1 to 32 characters | | Set name | 1 to 64 characters | | Parameters | at most 8, name `[A-Za-z][A-Za-z0-9]*` up to 32, `label` up to 32, `short` up to 8 | | Tiers returned | 2 to 33 (up to 32 hit tiers, then the Miss) | | Tier name | 1 to 32 characters; `color` up to 9 characters; `gradient` 2 to 8 hex colors | ```ts fragment judgements.register({ id: "strict", name: "Strict", params: { scale: { label: "Window scale", short: "Scale", min: 0.5, max: 1.5, step: 0.1, default: 1 } }, accuracy: "weights", holds: "head", tiers: ({ scale }) => [ { id: "perfect", name: "Perfect", color: "#7df9ff", windowMs: 20 * scale, weight: 1 }, { id: "good", name: "Good", color: "#6bd36b", windowMs: 60 * scale, weight: 0.6 }, { id: "miss", name: "Miss", color: "#ff5c5c", windowMs: 120 * scale, weight: 0, breaksCombo: true }, ], }); ``` Errors you will see: ``judgement set id must be 1 to 32 characters among a-z, 0-9 and `-`, got "Strict"``, `a mod registers at most 8 judgement sets`, ``judgement set `x` is registered twice``, `tiers must return 2 to 33 tiers (hit tiers, then the miss), got 1`, ``tier `good` needs windowMs, or earlyMs and lateMs``, and ``param `scale` needs finite min < max, 0 < step <= max - min and min <= default <= max``. The weights are checked by the game before the set is used: `Wife3` tiers take no weight, `continuous` weights must not increase. See [Writing a judgement set](https://prism.am/dev/md/guides/judgement-set.md). ### `scrollSpeed.register` {#scrollspeed-register} ```dts function scrollSpeed.register(input: ScrollSpeedDefinition): void; ``` Adds a scroll speed system to the settings, such as osu!mania's speed or Etterna's C-mod. The player moves a slider over `param`; `toMs` turns the chosen value into the native scroll time, the milliseconds a note takes from where it appears to the receptors. Only mods call it, and only from `setup`. The system is published as `/`. `toMs(value, { travel })` must be a pure function returning a positive finite number of milliseconds. `travel` is the distance a note covers, in screen heights (0.8 for the native playfield). The host converts the whole slider grid (`min` to `max` by `step`, at most 4096 values) after the mods load, and converts a typed value on demand. A value whose call throws or returns a non-number is dropped from the grid. | Limit | Value | | --- | --- | | Systems per mod | 8 | | `id` | `a-z`, `0-9`, `-`, 1 to 32 characters | | `name` | 1 to 64 characters | | `param` | `label` up to 32, `short` up to 8; finite `min < max`, `0 < step <= max - min`, `min <= default <= max` | | Slider values | at most 4096 | ```ts fragment scrollSpeed.register({ id: "c-mod", name: "C-mod", param: { label: "C-mod", short: "C", min: 120, max: 1800, step: 5, default: 200 }, toMs: (cmod, { travel }) => ((travel * 480) / ((64 * cmod) / 60)) * 1000, }); ``` Errors you will see: `param takes 5000 values from min to max by step; the limit is 4096`, `a mod registers at most 8 scroll speed systems`, ``scroll speed system `x` is registered twice``, `toMs(120) threw …`, `toMs(120) returned string`, `no value converts to a scroll time: …`. ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type ChartNotes = { keys: number; count: number; seed: number; durationUs: number; startUs: NativeBytes; endUs: NativeBytes; column: NativeBytes; kind: NativeBytes; }; type NativeBytes = Uint8Array; type NoteSubmission = { startUs: NativeBytes; endUs: NativeBytes; column: NativeBytes; kind: NativeBytes; }; type GameplayModifierDeclaration = { id: string; name: string; description: string; kind: GameplayModifierKind; group?: string | null; icon?: string | null; conflictsWith?: string[]; params?: ModParamDeclaration[]; }; type GameplayModifierKind = "auto" | "ghost" | "fullLn" | "chartTransform" | "noteMask" | "noPause" | "mirror" | "noLn" | "rankedFullLn" | "noMines"; type ModParamDeclaration = { id: string; label: string; description: string; section: string; min: number; max: number; step: number; default: number; unit?: string | null; }; type JudgementSetDefinition = { id: string; name: string; params?: Record; accuracy: SetAccuracy; holds: SetHolds; mine?: MineRule | null; tiers: JudgementTiers; }; type JudgementParam = { label: string; min: number; max: number; step: number; default: number; short?: string | null; }; type SetAccuracy = "osuScoreV1" | "wife3" | "weights" | "continuous"; type SetHolds = "osuCombined" | "etterna" | "head" | "separate"; type MineRule = { weight?: number | null; windowMs?: number | null; }; type JudgementTiers = (params: Record) => JudgementTier[]; type JudgementTier = { id: string; name: string; color: string; gradient?: string[] | null; windowMs?: number | null; earlyMs?: number | null; lateMs?: number | null; weight?: number | null; breaksCombo?: boolean; releaseWindowMs?: number | null; releaseEarlyMs?: number | null; releaseLateMs?: number | null; }; type ScrollSpeedDefinition = { id: string; name: string; param: ScrollSpeedParam; toMs: ScrollSpeedToMs; }; type ScrollSpeedParam = { label: string; min: number; max: number; step: number; default: number; short?: string | null; unit?: string | null; }; type ScrollSpeedToMs = (value: number, context: ScrollSpeedContext) => number; type ScrollSpeedContext = { travel: number; }; ``` ===== Page: Ratings, tables, calculators and library filters Address: https://prism.am/dev/reference/sdk/ratings/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Ratings, tables, calculators and library filters ratings.*, tables.*, metron.* and library.*. ## Functions {#functions} ### `library.filters.register` {#library-filters-register} ```dts function library.filters.register(input: LibraryFilterDeclaration): void; ``` Adds a filter to the library's filter bar, driven by a column of one of your tables. Only mods call it, only from `setup`, and the table must be one your mod registered. The filter is published as `/`; the kind of the column (`number` or `text`) is the kind of the filter. A chart takes part only if its row has the given `version` (at least 1): an older row is stale and ignored. `name` is the label, 1 to 64 characters; `unit` is a suffix of at most 16 characters. A mod registers at most 32 filters. The mod id `host` is reserved for the game's own filters. ```ts fragment tables.register({ id: "my_rating", columns: [{ name: "overall", kind: "number", indexed: true }] }); library.filters.register({ id: "overall", name: "My rating", table: "my_rating", column: "overall", version: 1, unit: "MSD" }); ``` Errors you will see: `filter must reference a registered column of its mod`, `filter table is not registered by this mod`, `filter version must be positive`, `filter id is registered twice`, `a mod registers at most 32 library filters`, `host is reserved for neutral library filters`, `filter unit must have at most 16 characters and no control characters`. See [Library filters](https://prism.am/dev/md/guides/library-filters.md). ### `metron.catalog` {#metron-catalog} ```dts function metron.catalog(input: void): MetronCatalog; ``` Lists the native calculators Metron offers: 10 entries today (`osu-2016`, `osu-2018`, `osu-current`, `etterna-515`, `quaver-2025`, `interlude-2025`, `daniel-2026`, `sunnyxxy-2024`, `prism`, `prismcalc-1`). Each has its `id`, its `version` and `performance`, which is `true` when `metron.performance` can compute a performance for it (`osu-2018`, `etterna-515` and `prism`). It reads no state and returns at once, from `setup` or an event handler, never at the top level of the file. Read the version from here when you register a rating: it changes when a calculator's behavior changes. ```ts fragment for (const calculator of metron.catalog().calculators) { log.info(`${calculator.id} v${calculator.version}${calculator.performance ? " (performance)" : ""}`); } ``` ### `metron.difficulty` {#metron-difficulty} ```dts function metron.difficulty(input: CalculatorRequest): number | null; ``` Returns the difficulty of the chart being played under one calculator, or `null` when the chart has no rating for it or no chart is playing. It reads the ratings the library already computed (the same values as `game.song().ratings`), so it is instant and costs nothing. `calculator` is an id of `metron.catalog()`; an unknown id throws `unknown Metron calculator "x"`. The unit depends on the calculator: stars for the osu! family, MSD for the MinaCalc ones. ```ts fragment const stars = metron.difficulty({ calculator: "osu-2018" }); if (stars !== null) log.info(`osu! 2018: ${stars.toFixed(2)}`); ``` ### `metron.performance` {#metron-performance} ```dts function metron.performance(input: PerformanceRequest): number | null; ``` Starts the calculation of the performance (the pp or SSR) of the chart being played at a given accuracy. Only mods call it, from an event handler once a chart plays. It returns a request number, or `null` when the workers are busy (2 outstanding requests per mod, 64 in total). The answer comes as a `metron.performanceResult` event with the same `requestId`: `value` (or `error`) and `unit`, `pp` for `osu-2018` and `prism`, `SSR` for `etterna-515`. `accuracy` is a fraction from 0 to 1, not a percentage. Only the calculators whose `performance` flag is `true` in `metron.catalog()` work. The result is meaningful when the accuracy comes from the calculator's own judgement; the game labels other mixes nonstandard. ```ts fragment ctx.on("game.songStart", () => { metron.performance({ calculator: "prism", accuracy: 0.98 }); }); ctx.on("metron.performanceResult", (result) => { if (result.value != null) log.info(`98%: ${result.value.toFixed(1)} ${result.unit}`); }); ``` Errors you will see: `Metron has no performance calculator for osu-2016`, `accuracy must be a fraction from 0 to 1`, `no decoded chart is playing`, `only mods request Metron performance`, `native score workers are unavailable`. ### `ratings.backfill` {#ratings-backfill} ```dts function ratings.backfill(input: BackfillRequest): number | null; ``` Asks the host to calculate a registered rating for the charts that lack a current row. Without `charts` it looks at the whole library; with `charts` (at most 8192 library chart ids, for example from `library.chartsAdded`) it looks only at those charts. Only mods call it, from `setup` or an event handler (`library.ready` is the usual place). It returns a request number, or `null` when the workers are busy: a mod may keep 16 backfills outstanding and all mods together 64, so call it again at the next check. The work runs on the library's workers, never on the mods thread. Progress comes back to your mod as `ratings.progress` events carrying the same `requestId` (`done`, `total`, `failed`, `finished`, `error`, `ahead`); the game also shows the request in its processing window. ```ts fragment ctx.on("library.ready", () => { if (ratings.backfill({ id: "prismcalc-1" }) === null) log.warn("the rating workers are busy"); }); ctx.on("ratings.progress", (progress) => { if (progress.finished) log.info(`${progress.done}/${progress.total} rated, ${progress.failed} failed`); }); ``` Errors you will see: `unknown registered rating` (the `id` names a rating of this mod, not a calculator), `too many charts in one scoped backfill`, `invalid chart id`, `rating table is unavailable`, `library workers are unavailable`, `only mods calculate library ratings`. ### `ratings.register` {#ratings-register} ```dts function ratings.register(input: RatingDeclaration): void; ``` Declares a rating: a Metron calculator whose result is stored in a column of one of your tables and shown in the library and the chart panel. Only mods call it, only from `setup`, and the table must have been registered before by `tables.register` in the same mod. The rating is published as `/`. The host computes the values (see `ratings.backfill`); your script never writes a row. `calculator` is an id from `metron.catalog()` (10 of them today, among them `osu-2018`, `etterna-515`, `prism`, `prismcalc-1`). `version` must equal the calculator's version from the same catalog: a mismatch is refused, and a stored row with an older version is stale. `column` must be a numeric column. `panels` (at most 4) draw the chart panel: `metrics`, `bars` and `radar` take fields (1 to 16, 3 to 12 for a radar) that read a numeric column or a neutral chart metric, `timeline` takes 1 or 2 series (`density`, `bpm`). `patterns` (at most 12) name numeric columns that score one pattern each; `short` is 1 to 5 characters and `color` is `#rgb`, `#rrggbb` or a theme role. `colors` gives a color scale with up to 16 increasing stops; an invalid scale is dropped with a warning and the rating still registers. | Limit | Value | | --- | --- | | Ratings per mod | 16 | | `id` | `a-z`, `0-9`, `-`, 1 to 32 characters | | `name` | 1 to 64 characters; `unit` 1 to 16 characters | | Panels | at most 4; title 1 to 64 characters; field `decimals` 0 to 3; `max` in (0, 1000000] | | Patterns | at most 12; `label` up to 32 characters | ```ts fragment tables.register({ id: "prism_rating", columns: [{ name: "overall", kind: "number", indexed: true }] }); const calculator = metron.catalog().calculators.find((entry) => entry.id === "prismcalc-1"); if (calculator) { ratings.register({ id: "prismcalc-1", name: "PrismCalc", calculator: calculator.id, unit: "MSD", table: "prism_rating", column: "overall", version: calculator.version, }); } ``` Errors you will see: `rating table is not registered`, `rating must reference a registered numeric column of its mod`, `rating version must match the native calculator version`, `unknown Metron calculator "x"`, `a mod registers at most 16 ratings`, ``rating `x` is registered twice``, `a rating has at most 4 panels`, `panel must have 3 to 12 fields`, `a rating declares at most 12 patterns`. See [Writing a rating](https://prism.am/dev/md/guides/rating.md). ### `tables.register` {#tables-register} ```dts function tables.register(input: TableDefinition): void; ``` Declares a table the host keeps in the library database, one row per chart, owned by your mod. Only mods call it, only from `setup`. It is the storage behind `ratings.register` and `library.filters.register`; no function writes rows from a script, the host fills the rating column when `ratings.backfill` runs. The table survives restarts, and registering it again with the same columns is harmless. `id` and every column `name` match `^[a-z][a-z0-9_]{0,31}$`. A column is `number` or `text`; `indexed: true` adds an index (set it on the columns you filter on). A table has 1 to 32 columns. The names `chart_id`, `calc_version`, `chart_stamp`, `chart_size` and `error` are reserved: the host adds them to every table. A mod keeps at most 16 tables, and a table id is unique per mod. Changing the type of a column that already exists is refused. ```ts fragment tables.register({ id: "my_rating", columns: [ { name: "overall", kind: "number", indexed: true }, { name: "label", kind: "text" }, ], }); ``` Errors you will see: `table and column ids must use lowercase ASCII letters, digits and underscores (1–32 characters)`, `a mod table has 1–32 columns`, `duplicate or reserved mod column`, `a mod registers at most 16 uniquely named tables`, and, as a mod message, `chart table registration failed: cannot change an existing column type`. ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type LibraryFilterDeclaration = { id: string; name: string; table: string; column: string; version: number; unit?: string; }; type MetronCatalog = { calculators: MetronCalculator[]; }; type MetronCalculator = { id: string; performance: boolean; version: number; }; type CalculatorRequest = { calculator: string; }; type PerformanceRequest = { calculator: string; accuracy: number; }; type BackfillRequest = { id: string; charts?: number[] | null; }; type RatingDeclaration = { id: string; name: string; calculator: string; unit: string; table: string; column: string; version: number; panels?: RatingPanel[]; colors?: RatingColors | null; patterns?: RatingPattern[]; }; type RatingPanel = { kind: "metrics"; title: string; fields: RatingField[]; } | { kind: "bars"; title: string; fields: RatingField[]; max?: number | null; } | { kind: "radar"; title: string; fields: RatingField[]; max?: number | null; } | { kind: "timeline"; title: string; series: RatingSeries[]; }; type RatingField = { label: string; source: RatingFieldSource; unit?: string; decimals?: number; }; type RatingFieldSource = { kind: "column"; column: string; } | { kind: "chart"; metric: ChartMetric; }; type ChartMetric = "notes" | "holds" | "holdPercent" | "averageNps" | "peakNps" | "bpmMin" | "bpmMax" | "duration"; type RatingSeries = { label: string; source: RatingSeriesSource; unit: string; }; type RatingSeriesSource = "density" | "bpm"; type RatingColors = { scale?: number | null; stops: RatingColorStop[]; }; type RatingColorStop = { at: number; color: string; }; type RatingPattern = { column: string; label: string; short: string; color?: string | null; }; type TableDefinition = { id: string; columns: ColumnDefinition[]; }; type ColumnDefinition = { name: string; kind: ColumnKind; indexed?: boolean; }; type ColumnKind = "number" | "text"; ``` ===== Page: Tabs and the local leaderboard Address: https://prism.am/dev/reference/sdk/tabs/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Tabs and the local leaderboard tabs.* and leaderboard.*. ## Functions {#functions} ### `leaderboard.best` {#leaderboard-best} ```dts function leaderboard.best(input: LeaderboardBestQuery): number | null; ``` The first entry of a chart's local leaderboard: the same as `leaderboard.query` with `limit` 1. It takes an object, `{ chartId }`, not a bare number. It returns a request number or `null` under the same limits as `leaderboard.query` (the two share the 2 and 16 outstanding requests), and the answer arrives as a `leaderboard.result` event whose `entries` hold at most one play. ```ts fragment leaderboard.best({ chartId: 12 }); ctx.on("leaderboard.result", (result) => { const best = result.entries[0]; if (best) log.info(`best: ${best.accuracy.toFixed(2)}% by ${best.playerName ?? "unknown"}`); }); ``` The errors are those of `leaderboard.query`. ### `leaderboard.query` {#leaderboard-query} ```dts function leaderboard.query(input: LeaderboardQuery): number | null; ``` Reads the local leaderboard of a chart: the plays of this computer, each replay judged again with the player's current judgement and ranked like the Leaderboard tab. Only mods call it, from `setup` or an event handler. It returns a request number, or `null` when the limit is reached (2 requests outstanding per mod, 16 in total). It never blocks: the answer arrives as a `leaderboard.result` event with the same `requestId`, only in the mod that asked. `chartId` is the library's chart id (as in `library.chartAdd`, `library.chartsAdded` and the chart tables), a positive integer; a mod has no file path. `limit` is 1 to 100 (20 by default) and `offset` 0 to 100000 (0 by default). The result carries `total`, `entries` (rank, player name, accuracy in percent, performance, combo, misses, tier counts, rate, whether the play was modified, date in milliseconds), the `judgement` used, the calculator's `performance` unit, and `error` when it failed. ```ts fragment const requestId = leaderboard.query({ chartId: 12, limit: 10 }); ctx.on("leaderboard.result", (result) => { if (result.requestId !== requestId || result.error) return; for (const entry of result.entries) log.info(`#${entry.rank} ${entry.accuracy.toFixed(2)}%`); }); ``` Errors you will see: `chartId must be a library chart id (a positive integer)`, `limit must be between 1 and 100`, `offset must be at most 100000`, `only mods read the local leaderboard`, `local scores are unavailable`. ### `tabs.extend` {#tabs-extend} ```dts function tabs.extend(input: TabExtensionDeclaration): void; ``` Adds sections to one of the host's tabs without replacing what it shows: `tab` is `info`, `leaderboard` or `mods` (Training and the editor stay closed), `slot` puts your panels before (`top`) or after (`bottom`) the host's content. Only mods call it, only from `setup`. Panels are the same as for `tabs.register`, but 1 to 4 per extension. `order` (0 to 1000) sorts the sections of the same tab and slot; equal orders sort by mod id. A mod extends the host's tabs at most 4 times, and all mods together at most 24 extensions are shown (extras are dropped). ```ts fragment tabs.extend({ tab: "info", slot: "bottom", order: 0, panels: [{ kind: "text", title: "Note", text: "Rated by my calculator." }], }); ``` Errors you will see: `tabs.extend is only available in a mod's setup`, `a mod extends the host's tabs at most 4 times`, `panels must hold 1 to 4 panels`, `panel text must not contain control characters`. ### `tabs.register` {#tabs-register} ```dts function tabs.register(input: TabDeclaration): void; ``` Adds a tab next to Info, Leaderboard and Mods in the panel of the selected chart in song select. Only mods call it, only from `setup`. The tab is published as `/`. A tab is a list of declarative panels (1 to 8): `metrics`, `bars`, `radar`, `timeline`, `leaderboard` (the best plays of the chart) and `text`. The game draws them; there is no script code in the interface. A field reads a numeric column of a rating of your mod (`{ kind: "column", rating, column }`, the rating registered before in the same mod), a neutral chart metric, or a leaderboard statistic (`plays`, `bestPerformance`, `bestAccuracy`). Tabs sort by `order` (0 to 1000), then by key, after the host's own tabs. | Limit | Value | | --- | --- | | Tabs per mod / all mods | 4 / 12 (extras are dropped) | | `id` | `a-z`, `0-9`, `-`, 1 to 32 characters | | `title` | 1 to 24 characters | | `icon` | one of 16: `layers` (default), `info`, `trophy`, `star`, `gauge`, `activity`, `chart-bar`, `list`, `flame`, `music`, `clock`, `target`, `sparkles`, `bookmark`, `heart`, `users` | | Panels | 1 to 8; title up to 64 characters; `text` up to 280; a `leaderboard` panel lists 1 to 10 plays | ```ts fragment tabs.register({ id: "stats", title: "Stats", icon: "chart-bar", order: 10, panels: [ { kind: "metrics", title: "Chart", fields: [ { label: "Notes", source: { kind: "chart", metric: "notes" } }, { label: "Plays", source: { kind: "leaderboard", stat: "plays" } }, ] }, { kind: "leaderboard", title: "Top plays", limit: 5 }, ], }); ``` Errors you will see: `tabs.register is only available in a mod's setup`, ``tab `x` is registered twice``, `a mod registers at most 4 tabs`, `tab icon "x" is not an allowed icon`, `panels must hold 1 to 8 panels`, `a leaderboard panel lists 1 to 10 plays`, `order must be between 0 and 1000`, ``field `Overall` reads column `overall` of rating `r`: register that rating first (`ratings.register`, same mod) and name one of its numeric columns``. See [Tabs and the local leaderboard](https://prism.am/dev/md/guides/tabs-leaderboard.md). ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type LeaderboardBestQuery = { chartId: number; }; type LeaderboardQuery = { chartId: number; limit?: number | null; offset?: number | null; }; type TabExtensionDeclaration = { tab: ExtendableTab; slot: TabSlot; order?: number; panels: TabPanel[]; }; type ExtendableTab = "info" | "leaderboard" | "mods"; type TabSlot = "top" | "bottom"; type TabPanel = { kind: "metrics"; title: string; fields: TabField[]; } | { kind: "bars"; title: string; fields: TabField[]; max?: number | null; } | { kind: "radar"; title: string; fields: TabField[]; max?: number | null; } | { kind: "timeline"; title: string; series: RatingSeries[]; } | { kind: "leaderboard"; title: string; limit: number; } | { kind: "text"; title?: string | null; text: string; }; type TabField = { label: string; source: TabFieldSource; unit?: string; decimals?: number; }; type TabFieldSource = { kind: "column"; rating: string; column: string; } | { kind: "chart"; metric: ChartMetric; } | { kind: "leaderboard"; stat: LeaderboardStat; }; type LeaderboardStat = "plays" | "bestPerformance" | "bestAccuracy"; type TabDeclaration = { id: string; title: string; icon?: string | null; order?: number; panels: TabPanel[]; }; ``` ### Defined elsewhere {#elsewhere} `ChartMetric` (ratings), `RatingSeries` (ratings), `RatingSeriesSource` (ratings) ===== Page: Download sources and skin import Address: https://prism.am/dev/reference/sdk/downloads/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Download sources and skin import downloads.* (mirrors, sources, bridges) and skinImport.*. ## Functions {#functions} ### `downloads.register` {#downloads-register} ```dts function downloads.register(input: DownloadDeclaration): void; ``` Declares a download mirror or source as data: the game makes every request itself, only to the hosts you list, and your script never touches the network or the player's token. Only mods call it, only from `setup`, and the mod must declare `permissions: ["network"]`; the player can take that permission away from the Mods page, which withdraws the declaration at once. `kind: "mirror"` serves osu! beatmapsets (`target: "osu"`): it must page by `offset` or `page`, `download.url` must contain `{id}` and nothing else, and its results have a numeric id. `kind: "source"` has a tab of its own: it needs `search` and either `download.url` (with `{id}`) or `download.urlField` (a path in the listed result, with the `mapped` response format). `search.params` are templates over 18 variables (`{query}`, `{status}`, `{sort}`, `{offset}`, `{page}`, `{limit}`, `{cursor}`, `{keysMin}`, `{keysMax}`, `{starsMin}`, `{starsMax}`, `{bpmMin}`, `{bpmMax}`, `{lengthMin}`, `{lengthMax}`, `{genre}`, `{language}`, `{id}`); a group in brackets is written only when every variable inside has a value, and `\` escapes `\ [ ] { }`. `auth: { kind: "token" }` makes the game ask the player for a token and send it itself. `header` is `Authorization` (default), `X-API-Key` or `X-Auth-Token`; `scheme` is up to 16 letters (`Bearer` for `Authorization` by default, `""` sends the token alone); `scope` is `all` (default: search and download) or `download` (the file requests only). The token is 8 to 4096 visible characters. | Limit | Value | | --- | --- | | Declarations per mod / all mods | 4 / 64 | | `id` | `a-z`, `0-9`, `-`, 1 to 32 characters | | `name` / `description` | up to 32 / up to 200 characters | | `hosts` | 1 to 8 lowercase DNS names with at least two labels; no IP address, no port, no `local`, `localhost`, `internal`, `lan`, `intranet`, `home`, `corp`, `*.home.arpa` | | URLs and templates | `https` only, plain ASCII, up to 256 characters, on a declared host | | `rateLimit` | 1 to 120 requests per minute (30 by default) | | `search.paging.size` | 1 to 100; `search.params` up to 16 entries | | JSON paths | up to 128 characters and 8 steps; a key is up to 48 characters | ```ts fragment downloads.register({ id: "mirror", name: "Example mirror", kind: "mirror", target: "osu", hosts: ["mirror.example.org"], search: { url: "https://mirror.example.org/api/search", params: { query: "{query}", amount: "{limit}", offset: "{offset}" }, paging: { kind: "offset", size: 20 }, response: { format: "osu" }, }, download: { url: "https://mirror.example.org/d/{id}" }, }); ``` Errors you will see: `` `downloads.register` needs the `network` permission: declare `permissions: ["network"]` ``, `a mod registers at most 4 downloads`, `download id is registered twice`, `host "x": local names are never allowed`, `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``, `rateLimit is 1 to 120 requests per minute`, `auth.header is one of Authorization, X-API-Key, X-Auth-Token`. See [Adding a download source](https://prism.am/dev/md/guides/download-source.md). ### `downloads.registerBridge` {#downloads-registerbridge} ```dts function downloads.registerBridge(input: BridgeDefinition): void; ``` Adapts a site whose API does not fit `downloads.register`: you write pure functions that compute the next step, the host does every request. Only mods call it, only from `setup`, with the `network` permission; the header fields (`id`, `name`, `description`, `site`, `hosts`, `rateLimit`, `auth`) follow the rules of `downloads.register`. A bridge is always a source with its own tab. `search(query, page, state)` starts a search (`page` is 1 for the first page). `onResponse(response, state)` receives each answer as text; `action(result, actionId, state)` runs when the player presses one of a result's buttons. Each returns a step with exactly one of `request`, `results`, `download` and `error`. `request` makes the host perform it and call `onResponse`; `results` ends a search (`nextPage`, a string or a number of up to 128 characters, asks for another page); `download` ends an action with the file to fetch (`format` is `zip`, `osz` or `qp`, `filename` up to 128 characters); `error` shows a message of up to 200 characters. `state` is any JSON up to 8 KiB, handed back to the next function. A request takes `method` (`GET` or `POST`), `headers`, and one of `body` (a string), `form` or `json`, plus `expect` (`json`, `text`, `xml`, `html`) for how the answer is checked. Answers arrive as text: parse XML and HTML with strings and regular expressions. A `BridgeResult` carries `id`, `title`, `artist`, optional `creator`, `coverUrl`, `tags`, `size`, `keyCount`, `details`, up to 4 `actions`, and `data`, a string of up to 1024 characters the game hands back to `action` as `result.data`. | Bound | Value | | --- | --- | | Requests per search or action | 6, within 60 seconds | | Answer text handed to the script | 2 MiB (a larger one is an error, never cut) | | Request body | 64 KiB; URL up to 2048 bytes; up to 12 headers | | One step as JSON | 256 KiB; results per step up to 100 | | Header names a script may set | `accept`, `accept-language`, `content-type`, `referer`, `origin`, `x-requested-with`, `x-api-key`, `x-auth-token`, `authorization`, `if-none-match` | The token is added by the host and never given to your functions; an answer that repeats it is scrubbed. Failures show up as ``a step has exactly one of `request`, `results`, `download` and `error` ``, `needed more than 6 requests`, `` `state` is at most 8 KiB of JSON ``, `` `nextPage` goes with `results` ``, `returned results where a download was expected`. The complete example `content/examples/mods/download-bridge/main.ts` is the reference; see [Adding a download source](https://prism.am/dev/md/guides/download-source.md). ### `skinImport.close` {#skinimport-close} ```dts function skinImport.close(input: void): void; ``` Closes your panel and drops the picked source and the preparation, like the player's `dismiss`. Skins your importer already created stay (and stay valid targets of `editSkin`). It needs the `skinImport` permission; call it from an event handler when the job is over or abandoned. It takes no argument and returns nothing. ```ts fragment ctx.on("skinImport.action", (action) => { if (action.id === "cancel") skinImport.close(); }); ``` ### `skinImport.create` {#skinimport-create} ```dts function skinImport.create(input: SkinImportCreate): number | null; ``` Writes the staged skin as a new folder of the player's skins directory; it never replaces a skin that exists. `stageId` is the one `skinImport.staged` gave and must still be the current preparation. It returns a request number, or `null` while another job runs. The result arrives as a `skinImport.created` event with the new skin's `id`, or an `error`; the new folder goes through the same inspection as an installed skin first. ```ts fragment ctx.on("skinImport.staged", (staged) => { if (staged.stageId != null && staged.report && !staged.report.overBudget) skinImport.create({ stageId: staged.stageId }); }); ctx.on("skinImport.created", (created) => { if (created.id) skinImport.panel({ title: "Done", status: "done", actions: [{ id: "open", label: "Edit", primary: true, editSkin: created.id }] }); }); ``` Errors you will see: `nothing was prepared`, `this preparation is not the current one`. ### `skinImport.panel` {#skinimport-panel} ```dts function skinImport.panel(input: ImportPanelDefinition): void; ``` Shows or updates the progress panel of your importer on the Skins page: a declarative description, never HTML. Call it from an event handler (`skinImport.opened`, `skinImport.staged`, `skinImport.created`) after an importer is registered; calling it again replaces the panel and re-draws only if it changed. `status` is `working`, `ready`, `done` or `error`. | Limit | Value | | --- | --- | | `title` | 1 to 96 characters | | Sections / rows per section / parts per row | 6 / 24 / 8 | | Notes / actions | 48 / 4 | | Badges / tiles | 16 / 6 | | `icon` | one of 30 names (`palette`, `image`, `images`, `package`, `ruler`, `gauge`, `circle-check`, `triangle-alert`, …) | | Action `id` | `a-z`, `0-9`, `_`, 1 to 32 characters, unique; `dismiss` is the game's | An action with `editSkin` opens that skin in the editor; it must name a skin this importer created. When the player presses an action, you get a `skinImport.action` event with its `id`; `dismiss` closes the panel itself. ```ts fragment skinImport.panel({ title: "Converting", status: "working", detail: "Reading the pictures", badges: [{ text: "osu!", tone: "info" }], actions: [{ id: "cancel", label: "Cancel" }], }); ``` Errors you will see: ``register an importer in `setup` before showing a panel``, `a panel has at most 6 sections, 48 notes and 4 actions`, `a panel has at most 16 badges and 6 tiles`, `a section has at most 24 rows`, `a row has at most 8 parts`, ``a tile meter needs a finite `value` of 0 or more and a `max` above 0``, `` `editSkin` names "x", which this importer did not create ``. ### `skinImport.register` {#skinimport-register} ```dts function skinImport.register(input: ImporterDeclaration): void; ``` Registers a skin importer, the entry the player sees in the Skins page to convert a skin of another game into a Prism skin. It needs the `skinImport` permission in `defineMod` and works only from `setup`. The player picks the folder or archive (the game opens the dialog, never the mod); a native worker reads it, and your script only receives the parsed data (`skinImport.opened`) and answers with values. `id` is 1 to 32 characters among `a-z`, `0-9`, `-`, `_`, and starts with a letter or a digit. `name` is 1 to 64 characters, `description` up to 256. `sources` lists `folder`, `archive` or both, once each. `localized` gives `name` and `description` for `en`, `fr`, `zh` and `ko`. A mod registers at most 4 importers, with distinct ids. ```ts fragment skinImport.register({ id: "my-converter", name: "My converter", description: "Converts a skin folder or archive.", localized: { fr: { name: "Mon convertisseur" } }, sources: ["folder", "archive"], }); ``` Errors you will see: `` `skinImport` needs the `skinImport` permission: declare `permissions: ["skinImport"]` ``, `` `skinImport.register` is only available in a mod's setup ``, ``importer id "X" must be 1 to 32 characters among a-z, 0-9, `-`, `_` ``, ``an importer lists `folder`, `archive` or both, once each``, `a mod registers at most 4 importers, with distinct ids`. See [Importing a skin](https://prism.am/dev/md/guides/skin-import.md). ### `skinImport.stage` {#skinimport-stage} ```dts function skinImport.stage(input: StageRequest): number | null; ``` Prepares the conversion: you give a `SkinDescription` (the skin's id, name, layouts, lanes and HUD values) and a list of picture operations (`source`, `dest` as a `.png` path, optional `animation`, `frame`, `crop`, `fit`, `stretch`); the native worker builds the pictures and measures them. It returns a request number, or `null` when a job is already running. The result arrives as a `skinImport.staged` event: `report` lists every file, `totalBytes`, `budgetBytes` (900 KiB) and `overBudget`, plus `problems`, and `stageId` for `skinImport.create`. `sourceId` must be the one `skinImport.opened` gave. The skin may name at most 8 layouts and every picture it references must be produced by an operation; `fit` and `stretch` exclude each other, and a picture over the side or byte limit needs one of them. A job allows up to 256 pictures. ```ts fragment ctx.on("skinImport.opened", (opened) => { if (!opened.source) return; skinImport.stage({ sourceId: opened.source.sourceId, skin: { id: "converted", name: "Converted", layouts: [{ keys: 4, lanes: [{}, {}, {}, {}] }] }, images: [], }); }); ``` Errors you will see: `no source was picked`, `this source is not the one the player picked`, `a skin describes 1 to 8 layouts, not 9`, `300 pictures requested; the limit is 256`, `two images write x.png`, `` `fit` and `stretch` are exclusive ``, ``x.png would weigh … bytes; the limit is …: add `fit` ``. ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts type DownloadDeclaration = { id: string; name: string; description?: string | null; site?: string | null; kind: DownloadKind; target?: DownloadTarget | null; hosts: string[]; rateLimit?: number | null; auth?: DownloadAuth | null; search?: SearchSpec | null; download: DownloadSpec; }; type DownloadKind = "mirror" | "source"; type DownloadTarget = "osu"; type DownloadAuth = { kind: AuthKind; header?: string | null; scheme?: string | null; scope?: AuthScope | null; }; type AuthKind = "none" | "token"; type AuthScope = "download" | "all"; type SearchSpec = { url: string; params?: Record; sorts?: Record; statuses?: Record; paging?: PagingSpec | null; response: ResponseSpec; }; type PagingSpec = { kind: PagingKind; size: number; first?: number | null; }; type PagingKind = "offset" | "page" | "cursor"; type ResponseSpec = { format: ResponseFormat; results?: string | null; total?: string | null; nextCursor?: string | null; item?: ItemSpec | null; }; type ResponseFormat = "osu" | "mapped"; type ItemSpec = { id: string; title: string; artist?: string | null; creator?: string | null; status?: string | null; bpm?: string | null; playCount?: string | null; favourites?: string | null; cover?: string | null; difficulties?: DifficultySpec | null; }; type DifficultySpec = { path: string; name?: string | null; keys: string; stars?: string | null; length?: string | null; only?: OnlySpec | null; }; type OnlySpec = { path: string; equals: string; }; type DownloadSpec = { url?: string | null; urlField?: string | null; }; type BridgeDefinition = { id: string; name: string; description?: string | null; site?: string | null; hosts: string[]; rateLimit?: number | null; auth?: DownloadAuth | null; search: BridgeSearch; onResponse?: BridgeOnResponse; action?: BridgeAction; }; type BridgeSearch = (query: string, page: unknown, state: unknown) => BridgeStep; type BridgeStep = { request?: BridgeRequest | null; results?: BridgeResult[] | null; download?: BridgeDownload | null; error?: string | null; nextPage?: unknown | null; state?: unknown | null; }; type BridgeRequest = { url: string; method?: BridgeMethod | null; headers?: Record | null; body?: string | null; form?: Record | null; json?: unknown | null; expect?: BridgeExpect | null; }; type BridgeMethod = "GET" | "POST"; type BridgeExpect = "json" | "text" | "xml" | "html"; type BridgeResult = { id: unknown; title: string; artist: string; creator?: string | null; coverUrl?: string | null; tags?: string[] | null; size?: string | null; keyCount?: number | null; details?: ResultDetail[] | null; actions?: ResultAction[] | null; data?: string | null; }; type ResultDetail = { label: string; value: string; }; type ResultAction = { id: string; label: string; }; type BridgeDownload = { url: string; method?: BridgeMethod | null; headers?: Record | null; body?: string | null; form?: Record | null; json?: unknown | null; filename?: string | null; format: BridgeFormat; }; type BridgeFormat = "zip" | "osz" | "qp"; type BridgeOnResponse = (response: BridgeResponse, state: unknown) => BridgeStep; type BridgeResponse = { status: number; headers: Record; text: string; }; type BridgeAction = (result: BridgeActionResult, actionId: string, state: unknown) => BridgeStep; type BridgeActionResult = { id: string; title: string; artist: string; data?: string | null; }; type SkinImportCreate = { stageId: number; }; type ImportPanelDefinition = { title: string; status: PanelStatus; detail?: string | null; icon?: string | null; badges?: PanelBadge[]; tiles?: PanelTile[]; sections?: PanelSection[]; notes?: PanelNote[]; actions?: PanelAction[]; }; type PanelStatus = "working" | "ready" | "done" | "error"; type PanelBadge = { text: string; tone: PanelTone; icon?: string | null; }; type PanelTone = "ok" | "warn" | "info" | "bad"; type PanelTile = { label: string; value: string; icon?: string | null; tone?: PanelTone | null; meter?: PanelMeter | null; hint?: string | null; }; type PanelMeter = { value: number; max: number; }; type PanelSection = { heading: string; rows: PanelRow[]; }; type PanelRow = { label: string; value: string; icon?: string | null; tone?: PanelTone | null; parts?: PanelPart[] | null; }; type PanelPart = { text: string; icon?: string | null; }; type PanelNote = { level: NoteLevel; text: string; icon?: string | null; }; type NoteLevel = "info" | "warning" | "error"; type PanelAction = { id: string; label: string; primary?: boolean | null; editSkin?: string | null; }; type ImporterDeclaration = { id: string; name: string; description?: string | null; localized?: Record; sources: SourceKind[]; }; type ImporterText = { name: string; description?: string | null; }; type StageRequest = { sourceId: number; skin: SkinDescription; images: ImageOp[]; }; type SkinDescription = { id: string; name: string; version?: string | null; author?: string | null; description?: string | null; playfield?: PlayfieldSpec; layouts: SkinLayout[]; hud?: SkinHud; }; type SkinLayout = { keys: number; playfield?: PlayfieldSpec; lanes: LaneSpec[]; }; type SkinHud = { judgementY?: number | null; comboY?: number | null; }; type ImageOp = { source: string; dest: string; animation?: boolean; frame?: number | null; crop?: PixelBox | null; fit?: ImageBox | null; stretch?: ImageSize | null; additive?: boolean; file?: string | null; turn?: number | null; }; type ImageBox = { maxWidth: number; maxHeight: number; }; type ImageSize = { width: number; height: number; }; ``` ### Defined elsewhere {#elsewhere} `SourceKind` (declarations), `PlayfieldSpec` (game), `PlayfieldAnchor` (game), `ScrollDirection` (game), `SpriteSize` (game), `HitLightOn` (game), `TextureFilter` (game), `HoldMissedStyle` (game), `NoteSnapMax` (game), `NoteSnapTintMode` (game), `NoteSnapEnd` (game), `MeasureLineLength` (game), `JudgementLineAt` (game), `LaneSpec` (game), `PixelBox` (declarations) ===== Page: Editor mods (editor.*) Address: https://prism.am/dev/reference/sdk/editor/ Derived from: content/mods/sdk/modding.d.ts, content/dev-src/notes/sdk/ # Editor mods (editor.*) defineEditorMod and the interfaces of the map editor's API: panels, tools, patterns, validations. ## Functions {#functions} ### `defineEditorMod` {#defineeditormod} ```dts function defineEditorMod(def: EditorModDefinition): EditorModDefinition; ``` Declares a mod for the map editor of the web app, not for the game: the file is `content/mods/editor-/main.ts`, exports `defineEditorMod({...})` as its default, and the game's own mod scan skips every `editor-*` folder. The editor loads these files at build time, sorts them by `loadOrder` then `id`, and calls `setup(editor)` once. A mod that is invalid or whose `setup` throws is left out (its panels and tools are rolled back) and the error is written to the browser console. | Field | Rule | | --- | --- | | `id` | `^[a-z0-9._-]{1,64}$` | | `name` | up to 80 characters | | `version` | `major.minor.patch` digits | | `apiVersion` | `1`; another value is refused | | `loadOrder` | integer 0 to 10000, default 1000 | | `permissions` | `map:read`, `map:write`, each once | `editor.panel`, `editor.command`, `editor.tool`, `editor.pattern` and `editor.validation` register what the mod adds. Panel ids are `^[a-z0-9-]{1,32}$`; command, tool, pattern and validation ids are `^[a-z0-9._-]{1,64}$`; titles and labels are up to 120 characters. Ids are unique for each kind across all editor mods, not per mod. A panel has exactly one of `view` or `component` (the five components belong to the built-in mods). A pattern needs a `#rrggbb` `color`, at most 8 `params` of kind `number`, `select`, `toggle` or `sequence` (a list of whole numbers 1 to 99 such as `"4 2 3 2 4"`, `maxLength` 1 to 32, 16 by default), and a pure `steps` function that draws from `input.random()`, never `Math.random`. Param names match `^[a-z][a-zA-Z0-9]{0,31}$`. ```ts editor export default defineEditorMod({ id: "example.editor-jack", name: "Jack pattern", version: "1.0.0", apiVersion: 1, permissions: ["map:read", "map:write"], setup(editor) { editor.pattern({ id: "jack-run", title: "Jack run", color: "#ff5c5c", steps: ({ stepCount, columns }) => Array.from({ length: stepCount }, () => [columns[0]]), }); }, }); ``` Errors you will see in the console: `Invalid mod id: X`, `Mod x targets editor API 2; host runs 1`, `Mod x loadOrder must be an integer 0-10000`, `Mod x repeats permission map:read`, `Editor pattern id "jack-run" is already registered by pvng.editor-patterns`, `Pattern jack-run needs a colour like #4d8dff: it is how the pattern is told apart in the picker`, `Panel x needs exactly one of view or component`. ## Types {#types} Definitions read from the SDK. A type used here that is defined on another page is listed under *Defined elsewhere*. ```dts interface EditorModDefinition { id: string; name: string; version: string; apiVersion: 1; author?: string; description?: string; loadOrder?: number; permissions?: ("map:read" | "map:write")[]; setup(editor: EditorApi): void; } interface EditorApi { readonly apiVersion: 1; panel(def: EditorPanelDef): void; command(def: EditorCommandDef): void; tool(def: EditorToolDef): void; pattern(def: EditorPatternDef): void; validation(def: EditorValidationDef): void; } interface EditorPanelDef { id: string; title: string; icon: EditorIcon; rail: "main" | "bottom"; view?: (ctx: EditorModContext) => EditorViewNode; component?: "timing" | "sections" | "markers" | "settings" | "issues"; } type EditorIcon = "timer" | "layers" | "flag" | "settings" | "wand" | "bookmark" | "music" | "wrench" | "plus" | "trash" | "play"; interface EditorModContext { /** The map's data and its commands (`map:write` to change it). */ readonly map: MapPluginApi; /** What the editor is doing right now: cursor, pointer, selection, tool, grid, tempo. Read-only and live. */ readonly editor: EditorStateApi; /** Small data the mod keeps between sessions, private to it. */ readonly storage: EditorModStorage; } interface MapPluginApi { readonly version: 1; readonly map: { readonly id: bigint | null; readonly keyCount: number; }; readonly vectors: { readonly notes: ReadonlyArray; readonly timingPoints: ReadonlyArray; readonly sections: ReadonlyArray; readonly markers: ReadonlyArray; }; readonly cursor: { readonly timeUs: number; }; readonly selection: { readonly noteIds: ReadonlySet; readonly count: number; }; readonly commands: { addNote(timeUs: bigint, column: number): Promise; addHold(timeUs: bigint, column: number, durationUs: bigint): unknown; deleteRange(startUs: number, endUs: number): Promise; seek(timeUs: number): void; clearSelection(): void; setSelection(noteIds: bigint[]): void; addToSelection(noteIds: bigint[]): void; /** * Arms a pattern: the editor shows it under the pointer and the next click on the playfield places it, as one step (Shift * puts it in random lanes, Escape or a right click drops it). `null` drops it. Needs `map:write`. At most 256 notes. */ armPlacement(steps: ReadonlyArray | null): void; /** Places a pattern at `timeUs` at once, as one undoable step (the tempo there sets its times). Needs `map:write`. At most 256 notes. */ placePattern(steps: ReadonlyArray, timeUs: number): Promise; }; } interface MapNote { readonly id: bigint; readonly timeUs: bigint; readonly column: number; readonly noteType: number; readonly durationUs: bigint; } interface MapTimingPoint { readonly id: bigint; readonly timeUs: bigint; readonly pointType: number; readonly bpm: number | undefined; readonly scrollSpeed: number | undefined; readonly signature: number; } interface MapSection { readonly id: bigint; readonly name: string | undefined; readonly startTimeUs: bigint; readonly endTimeUs: bigint; } interface MapMarker { readonly id: string | bigint; readonly timeUs: number; readonly name: string; readonly color: string; readonly createdBy?: bigint; } interface EditorPlacementStep { readonly beat: number; readonly column: number; readonly holdBeats?: number; } interface EditorStateApi { readonly mapId: bigint | null; readonly keyCount: number; /** Every note, by time then lane. */ readonly notes: ReadonlyArray; /** Every timing point (tempo and scroll speed), as the map holds them. */ readonly timingPoints: ReadonlyArray; /** A pattern is armed (`ctx.map.commands.armPlacement`): the next click on the playfield places it. */ readonly placing: boolean; readonly markers: { readonly all: ReadonlyArray; readonly activeId: string | bigint | null; readonly loopEnabled: boolean; readonly loopRange: { readonly startUs: number; readonly endUs: number } | null; }; readonly time: { /** The playhead: the audio position while playing, else the cursor. */ readonly cursorUs: number; readonly playing: boolean; /** The length of the audio, 0 without any. */ readonly durationUs: number; /** The mouse over the playfield, `null` when it is elsewhere. */ readonly pointer: EditorPointer | null; }; readonly view: { readonly tool: EditorTool; readonly beatDivisor: number; readonly snapToGrid: boolean; readonly snapScroll: boolean; readonly zoom: number; readonly metronome: boolean; /** The stretch of the map on screen. */ readonly visibleStartUs: number; readonly visibleEndUs: number; }; readonly selection: { readonly count: number; readonly noteIds: ReadonlySet; /** The selected notes, by time then lane. */ readonly notes: ReadonlyArray; /** The span of the selection, holds included; `null` when nothing is selected. */ readonly startUs: number | null; readonly endUs: number | null; /** The lanes the selection uses, ascending. */ readonly columns: ReadonlyArray; }; readonly timing: { /** The tempo changes, by time. */ readonly tempos: ReadonlyArray; /** The tempo in force at a time. */ tempoAt(timeUs: number): EditorTempo; /** The time moved to the nearest grid line (`divisor` defaults to the editor's). */ snap(timeUs: number, divisor?: number): number; /** The notes that start in [startUs, endUs). */ notesIn(startUs: number, endUs: number): ReadonlyArray; }; } interface EditorPointer { /** The time under the mouse. */ readonly timeUs: number; /** The same time moved to the nearest line of the grid in use. */ readonly snappedUs: number; /** The lane under the mouse, or `null` between lanes. */ readonly column: number | null; } type EditorTool = "select" | "note" | "hold"; interface EditorTempoPoint { readonly timeUs: number; readonly bpm: number; readonly signature: number; } interface EditorTempo { readonly bpm: number; readonly beatUs: number; /** Where the tempo starts: the origin of its grid. */ readonly originUs: number; /** Beats per measure. */ readonly signature: number; } interface EditorModStorage { get(key: string): T | undefined; /** Throws when the value is not JSON or the limits (32 keys, 64 KiB a value, 256 KiB in all) would be passed. */ set(key: string, value: unknown): void; remove(key: string): void; keys(): string[]; } type EditorViewNode = | { kind: "stack"; children: EditorViewNode[] } /** A titled group, the editor's own: the same header and surface as its built-in panels. `hint` is one short sentence in a bubble. */ | { kind: "section"; title: string; hint?: string; children: EditorViewNode[] } /** The pattern generator: every registered pattern, its settings and the button that writes the notes. At most one per panel. */ | { kind: "patterns" } | { kind: "text"; text: string } | { kind: "button"; label: string; onClick: () => void; disabled?: boolean } | { kind: "number"; label: string; value: number; min?: number; max?: number; step?: number; onChange: (v: number) => void } | { kind: "select"; label: string; value: string; options: { value: string; label: string }[]; onChange: (v: string) => void } | { kind: "toggle"; label: string; value: boolean; onChange: (v: boolean) => void } /** A text field that keeps its own text: Enter or the button calls `onSubmit` with it, then the field empties. Labels are unique in a panel. */ | { kind: "input"; label: string; placeholder?: string; maxLength?: number; submitLabel?: string; onSubmit: (text: string) => void } /** Rows with their own buttons: a title, a detail line and up to three actions each. */ | { kind: "list"; empty: string; items: EditorListItem[] }; interface EditorListItem { id: string; title: string; detail?: string; /** A colour dot before the title (`#rrggbb`). */ color?: string; /** A small picture of a pattern before the title. */ preview?: EditorNotePreview; /** Clicking the row itself. */ onClick?: () => void; actions: EditorListAction[]; } interface EditorNotePreview { columns: number; length: number; notes: { at: number; column: number; length?: number }[]; } interface EditorListAction { label: string; icon: EditorIcon; onClick: () => void; danger?: boolean; disabled?: boolean; } interface EditorCommandDef { id: string; title: string; run: (ctx: EditorModContext) => void | Promise; } interface EditorToolDef { id: string; title: string; icon: EditorIcon; run: (ctx: EditorModContext) => void | Promise; } interface EditorPatternDef { id: string; title: string; /** The colour of the pattern, `#rrggbb`. Required, so every pattern can be told apart at a glance. */ color: string; /** One short sentence, shown in a bubble. */ description?: string; /** The pattern's own settings, after the shared ones. */ params?: EditorParamDef[]; /** The columns pressed at each step: one list per step, `[]` for a rest. Pure: use `input.random`, never `Math.random`. */ steps: (input: PatternStepsInput) => number[][]; } type EditorParamDef = | { kind: "number"; name: string; label: string; default: number; min: number; max: number; step?: number } | { kind: "select"; name: string; label: string; default: string; options: { value: string; label: string }[] } | { kind: "toggle"; name: string; label: string; default: boolean } /** * A list of whole numbers the player builds by clicking (a size per entry, from 1 to the map's key count), kept as text such * as "4 2 3 2 4". It cannot be empty and holds at most `maxLength` entries (16 when it does not say, 32 at most). */ | { kind: "sequence"; name: string; label: string; default: string; maxLength?: number }; interface PatternStepsInput { /** How many steps to give. */ readonly stepCount: number; /** The grid: one entry per step, with its time, measure and beat. */ readonly grid: ReadonlyArray; readonly stepsPerBeat: number; readonly stepsPerMeasure: number; /** The range, from the measure line of the cursor to the end of the last measure. */ readonly startUs: number; readonly endUs: number; /** The tempo in force at the start of the range. */ readonly bpm: number; /** The columns the player allows, ascending, never empty: use only these. */ readonly columns: ReadonlyArray; /** The map's number of columns: the allowed ones are a part of them. */ readonly keyCount: number; /** What the editor shows right now (notes, selection, tempo…), read-only: a pattern may read the map to adapt. */ readonly editor: EditorStateApi; readonly randomness: PatternRandomness; /** Seeded random numbers in [0, 1): the same seed gives the same pattern. */ random(): number; /** The values of the pattern's own `params`. */ readonly values: Readonly>; } interface PatternStep { /** Where the step falls. */ readonly timeUs: number; /** How long the step lasts: it differs between two measures of different tempos. */ readonly stepUs: number; /** The measure it belongs to, counted from 0 in the range. */ readonly measure: number; /** Its place in the measure, from 0. */ readonly inMeasure: number; /** The beat of the measure it falls on, from 0. */ readonly beat: number; } type PatternRandomness = "fixed" | "varied" | "random"; interface EditorValidationDef { id: string; title: string; check: (ctx: EditorModContext) => EditorIssue[]; } interface EditorIssue { severity: "info" | "warning" | "error"; message: string; } ``` ===== Page: Skin fields Address: https://prism.am/dev/reference/skin-fields/ Derived from: apps/web/src/mock/skin-fields.json, crates/skin/src/fields.rs, crates/skin/src/spec.rs, crates/skin/src/player.rs, content/dev-src/notes/skin-fields.en.md # Skin fields Every value of a playfield a skin, a map script or the player can set: kind, bounds, scope and a note for each. The catalogue of the 131 values of a playfield that the in-game skin editor lists, in 11 groups and 23 sections. It is the host's own list (`field_catalog()` of `crates/skin`): each field can be given by a skin (`playfield.set`), by a map script (`playfield.update`) and by the player in the skin editor. See [Writing a skin](https://prism.am/dev/md/guides/skin.md) for how the three layers combine. ## Reading this page {#reading} **Units.** Positions are fractions of the screen: `x` of its width, `y` of its height. Every size and offset is a fraction of the screen **height**, so the playfield keeps its proportions at any resolution. A note travels 0.8 screen heights during the scroll time the player sets. **Values.** Colours are written `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`; a tint multiplies its image. An image is a `.png` path relative to the skin folder; the player may also use an image they imported (`player:`). A size is `{ width, height }`. **Names.** A field is named the same in `playfield.set({ … })` and in the player's configuration (`skinConfig[skinId].playfield`). On one lane it goes in `lanes.set({ column, lane: { … } })` and in `skinConfig[skinId].playfield.lanes[column]`, under the same name unless the entry says *lane key*. A lane's value wins over the playfield's value of the same layer. **Bounds.** The ranges below are the **player's**: the catalogue is the player's configuration. A script is checked against its own bounds, which differ for `x`, `y`, `zoom` and `rotation` (see the table below and the [skin guide](https://prism.am/dev/md/guides/skin.md#layers)). In `setup`, a number outside its bounds is brought back inside and reported; in a handler during the play, the call throws. **Simple mode.** The skin editor lists only the fields marked *simple mode* until the player switches to advanced mode. | Field | Script (skin, map script) | Player | | --- | --- | --- | | `x` | 0 to 1 | −1 to 2 | | `y` | 0 to 1 | −1 to 2 | | `zoom` | 0 to 4 | 0.25 to 4 | | `rotation` | −3600 to 3600 | −180 to 180 | ## The groups {#groups} Each group is a tab of the skin editor; inside it, the fields are listed by section. | Group | Sections | Fields | | --- | --- | --- | | [Placement](https://prism.am/dev/md/reference/skin-fields.md#group-placement) | Position, Free placement, Scroll | 9 | | [Size](https://prism.am/dev/md/reference/skin-fields.md#group-size) | Size and spacing, Notes, Receptors, Long notes, Background | 11 | | [Color](https://prism.am/dev/md/reference/skin-fields.md#group-color) | Color and image, Notes, Receptors, Long notes, Missed long notes, Note snap colors, Background | 28 | | [Image](https://prism.am/dev/md/reference/skin-fields.md#group-image) | Notes, Receptors, Long notes, Color and image, Background | 5 | | [Judgement line](https://prism.am/dev/md/reference/skin-fields.md#group-judgement-line) | Judgement line | 8 | | [Lane cover](https://prism.am/dev/md/reference/skin-fields.md#group-lane-cover) | Lane cover | 5 | | [Hold end](https://prism.am/dev/md/reference/skin-fields.md#group-hold-end) | Hold end | 11 | | [Measure lines](https://prism.am/dev/md/reference/skin-fields.md#group-measure) | Measure lines, Beat lines | 11 | | [Lighting](https://prism.am/dev/md/reference/skin-fields.md#group-lighting) | Key light, Stage light, Hit light, Hold light, Mine light | 41 | | [Sound](https://prism.am/dev/md/reference/skin-fields.md#group-sound) | Key sound | 1 | | [Rendering](https://prism.am/dev/md/reference/skin-fields.md#group-rendering) | Rendering | 1 | ## Placement {#group-placement} Where the playfield and its lanes sit and which way the notes scroll. ### Position {#section-placement-position} #### `x` {#x} **Position X** · number · −1 to 2, step 0.005 · playfield · simple mode Horizontal position of the anchor point of the lanes box, as a fraction of the screen width. Default 0.5. A script may give 0 to 1, the player −1 to 2. #### `y` {#y} **Position Y** · number · −1 to 2, step 0.005 · playfield · simple mode Vertical position of the same point, as a fraction of the screen height. Default 0.5. A script may give 0 to 1, the player −1 to 2. #### `zoom` {#zoom} **Zoom** · number · 0.25 to 4, step 0.01 · playfield · simple mode Scale of the whole playfield around the centre of the lanes box. Default 1. A script may give 0 to 4, the player 0.25 to 4. Purely visual. #### `rotation` {#rotation} **Rotation** · number · −180 to 180, step 1 · playfield Rotation of the whole playfield around the same centre, in degrees, clockwise. Default 0. The notes follow their lanes. A script may give −3600 to 3600, the player −180 to 180. Purely visual. ### Free placement {#section-placement-lane-placement} #### `offsetX` {#offsetx} **Offset X** · number · −2 to 2, step 0.005 · lane only Lane only. Moves the whole lane (background, receptor, notes, holds) to the right, in screen heights. Default 0, script and player both −2 to 2. Never changes judging. #### `offsetY` {#offsety} **Offset Y** · number · −2 to 2, step 0.005 · lane only Lane only. Moves the whole lane down, in screen heights. Default 0, script and player both −2 to 2. Never changes judging. ### Scroll {#section-placement-scroll} #### `scroll` {#scroll} **Scroll direction** · choice · `down`, `up` · playfield · simple mode `down`: the notes fall towards the receptors. `up`: they rise. Default `down`. With `up`, the default `receptorY` becomes `1 − 0.85`. #### `receptorY` {#receptory} **Receptor position** · number · 0 to 1, step 0.005 · playfield · simple mode Position of the receptor line, from the top of the screen, as a fraction of the screen height. Default 0.85 when notes scroll down, 0.15 when they scroll up. #### `noteOffsetY` {#noteoffsety} **Note offset (along scroll)** · number · −0.5 to 0.5, step 0.001 · playfield and lane Moves the notes and the heads of holds along the scroll, positive in the direction the notes move. Default 0. The hold body starts from the moved head, so no gap opens. Purely visual: judging, hold timing, score and replays are untouched. ## Size {#group-size} Sizes of lanes, notes, receptors and holds. ### Size and spacing {#section-size-lane-size} #### `laneWidth` {#lanewidth} **Lane width** · number · 0.005 to 0.5, step 0.001 · playfield and lane, lane key `width` · simple mode Width of one lane. Default 0.085. On a lane the key is `width`. A script can also give `width` (the total width of the playfield, script only), which wins over `laneWidth` of the same layer. #### `laneGap` {#lanegap} **Lane gap** · number · 0 to 0.1, step 0.001 · playfield · simple mode Space between two lanes: they are `laneWidth + laneGap` apart, the gap never narrows a lane. Default 0.003. #### `laneHeight` {#laneheight} **Lane height** · number · 0 to 1, step 0.005 · playfield Height of the lanes box. Default 0.9. ### Notes {#section-size-notes} #### `noteSize` {#notesize} **Note size** · size · 0 to 2 per side · playfield and lane · simple mode Size of a note, width and height, each 0 to 2 screen heights. Default 0.0725 × 0.0725. A lane may have its own. ### Receptors {#section-size-receptors} #### `receptorSize` {#receptorsize} **Receptor size** · size · 0 to 2 per side · playfield and lane · simple mode Size of a receptor, width and height, each 0 to 2. Default 0.0775 × 0.0775. #### `receptorOffsetX` {#receptoroffsetx} **Receptor offset X** · number · −0.5 to 0.5, step 0.001 · playfield and lane Where the centre of the receptor image is, horizontally, from the middle of the lane on the receptor line, in screen heights (right is positive). Default 0. Use it when the image is cropped to its visible part and is no longer centred on the line. #### `receptorOffsetY` {#receptoroffsety} **Receptor offset Y** · number · −0.5 to 0.5, step 0.001 · playfield and lane Same, vertically (down is positive). Default 0. ### Long notes {#section-size-holds} #### `holdWidth` {#holdwidth} **Hold width** · number · 0 to 2, step 0.001 · playfield Width of the body of a hold. Default 0.02975. Ignored when `holdMatchNoteWidth` is on. #### `holdMatchNoteWidth` {#holdmatchnotewidth} **Match hold width to notes** · yes/no · playfield and lane The hold body takes the width of the note of its lane (its resolved `noteSize`) times `holdWidthScale`, and the end image takes the width of the body. `holdWidth` and the width of `holdEndSize` are then ignored. Default false; the two shipped skins turn it on. #### `holdWidthScale` {#holdwidthscale} **Hold width scale** · number · 0.25 to 3, step 0.01 · playfield and lane Factor applied to the note width when `holdMatchNoteWidth` is on. Default 1. ### Background {#section-size-background} #### `borderWidth` {#borderwidth} **Border width** · number · 0 to 0.1, step 0.001 · playfield Thickness of a frame around the lanes box. Default 0: no frame. ## Color {#group-color} Tints and colours, including the note snap colours and the look of missed holds. ### Color and image {#section-color-lane-look} #### `laneColor` {#lanecolor} **Lane color** · colour · playfield and lane · simple mode Background colour of each lane. It also tints `laneImage`. Default `#454d61`. #### `laneTintStrength` {#lanetintstrength} **Lane color strength** · number · 0 to 1, step 0.01 · playfield and lane How `laneColor` applies to `laneImage`, with the same rule as `noteTintStrength`. A column without an image is filled with its colour either way. Also per column. Default absent. ### Notes {#section-color-notes} #### `noteColor` {#notecolor} **Note color** · colour · playfield and lane · simple mode Tint multiplied with the note image (heads of holds included). Default white. See `noteTintStrength` to blend instead of multiplying. #### `noteTintStrength` {#notetintstrength} **Tint strength** · number · 0 to 1, step 0.01 · playfield and lane · simple mode How `noteColor`, `holdBodyColor` and `holdEndColor` apply to the note head, the hold body and the hold end (never to receptors or lane backgrounds). Absent: the colour multiplies the image. A value from 0 to 1: 0 shows the image as it is, 1 draws the lights and shadows of the image in the colour, so white at 1 on a cyan note gives a white-grey note with its highlights. Default absent. ### Receptors {#section-color-receptors} #### `receptorColor` {#receptorcolor} **Receptor color** · colour · playfield and lane · simple mode Tint multiplied with the receptor image. Default white. #### `receptorTintStrength` {#receptortintstrength} **Receptor color strength** · number · 0 to 1, step 0.01 · playfield and lane How `receptorColor` and `pressedColor` apply to the receptor images, with the same rule as `noteTintStrength`. Absent: the colour multiplies the image. From 0 (the image as it is) to 1 (its lights and shadows drawn in the colour). Also per column. Default absent. ### Long notes {#section-color-holds} #### `holdBodyColor` {#holdbodycolor} **Hold body color** · colour · playfield and lane · simple mode Tint multiplied with the hold body image. Default white. ### Missed long notes {#section-color-hold-missed} #### `holdMissedStyle` {#holdmissedstyle} **Missed long note look** · choice · `tint`, `hide` · playfield and lane What a hold looks like once it is missed (head never hit, or released too early): `tint` keeps it on screen dimmed until it leaves (even if the player presses again), `hide` removes it. Default `tint`. Visual only. #### `holdMissedColor` {#holdmissedcolor} **Missed long note tint** · colour · playfield and lane Tint multiplied with the head, body and end of a missed hold. Colours multiply in linear light, so the default `#808080` keeps about a fifth of the brightness. #### `holdMissedOpacity` {#holdmissedopacity} **Missed long note opacity** · number · 0 to 1, step 0.01 · playfield and lane Multiplies the alpha of a missed hold. Default 1. ### Note snap colors {#section-color-note-snap} #### `noteSnapColors` {#notesnapcolors} **Color notes by snap** · yes/no · playfield Turns the snap colors on: each note takes the color of the division of the beat it sits on (1/1 on the beat, 1/2, 1/3, 1/4, 1/6, 1/8, 1/12, 1/16, 1/24, 1/32, like osu!'s beat snap), computed from the final notes (chart modifiers included) and independent of the rate. Default false. Purely visual; playfield only, never per lane. #### `noteSnapStrength` {#notesnapstrength} **Snap color strength** · number · 0 to 1, step 0.01 · playfield How strongly the snap color is laid on the note image, from 0 to 1: 0 leaves the image as it is, 1 shows the color whatever the image (its shading is kept). Default 1. #### `noteSnapMax` {#notesnapmax} **Finest snap colored** · choice · `1/1`, `1/2`, `1/3`, `1/4`, `1/6`, `1/8`, `1/12`, `1/16`, `1/24`, `1/32` · playfield The finest snap that has its own color. A finer note, or one off the grid, takes `noteSnapOther`. Default `1/32`. #### `noteSnapColor1` {#notesnapcolor1} **1/1 (on the beat)** · colour · playfield Color of the 1/1 notes (on the beat). Default `#ff4d4d`. #### `noteSnapColor2` {#notesnapcolor2} **1/2 (half beat)** · colour · playfield Color of the 1/2 notes (half a beat). Default `#4d8dff`. #### `noteSnapColor3` {#notesnapcolor3} **1/3 (triplets)** · colour · playfield Color of the 1/3 notes (triplets). Default `#b565ff`. #### `noteSnapColor4` {#notesnapcolor4} **1/4** · colour · playfield Color of the 1/4 notes (a quarter of a beat). Default `#ffd84d`. #### `noteSnapColor6` {#notesnapcolor6} **1/6** · colour · playfield Color of the 1/6 notes. Default `#ff7ac8`. #### `noteSnapColor8` {#notesnapcolor8} **1/8** · colour · playfield Color of the 1/8 notes. Default `#ff9f40`. #### `noteSnapColor12` {#notesnapcolor12} **1/12** · colour · playfield Color of the 1/12 notes. Default `#2ec4b6`. #### `noteSnapColor16` {#notesnapcolor16} **1/16** · colour · playfield Color of the 1/16 notes. Default `#5bd75b`. #### `noteSnapColor24` {#notesnapcolor24} **1/24** · colour · playfield Color of the 1/24 notes. Default `#f2f2f2`. #### `noteSnapColor32` {#notesnapcolor32} **1/32** · colour · playfield Color of the 1/32 notes. Default `#c08a5a`. #### `noteSnapOther` {#notesnapother} **Other (off the grid or finer)** · colour · playfield Color of the notes off the grid, finer than 1/32 or than `noteSnapMax`. Default `#a0a0a0`. #### `noteSnapEnd` {#notesnapend} **Long note end** · choice · `head`, `own`, `off` · playfield Colour of the end of a hold: `head` uses the colour of the head, `own` the colour of the snap of the tail, `off` keeps `holdEndColor`. The body always keeps `holdBodyColor`. Default `head`. ### Background {#section-color-background} #### `borderColor` {#bordercolor} **Border color** · colour · playfield Colour of the frame set by `borderWidth`. Default white. #### `backgroundColor` {#backgroundcolor} **Background color** · colour · playfield · simple mode Background of the lanes box, visible between the lanes. It also tints `backgroundImage`. Default transparent. #### `backgroundTint` {#backgroundtint} **Map background tint** · colour · playfield · simple mode Multiplies the background image of the map. The default `#818181` is the historical 22 % dimming. ## Image {#group-image} Images of notes, receptors, hold bodies, lanes and the background. ### Notes {#section-image-notes} #### `note` {#note} **Note image** · image · playfield and lane · simple mode Image of the notes (a `.png` path in the skin folder). Default: a white rectangle. ### Receptors {#section-image-receptors} #### `receptor` {#receptor} **Receptor image** · image · playfield and lane · simple mode Image of the receptors. Default: a white rectangle. ### Long notes {#section-image-holds} #### `holdBody` {#holdbody} **Hold body image** · image · playfield and lane Image of the hold body. Default: a white rectangle. ### Color and image {#section-image-lane-look} #### `laneImage` {#laneimage} **Lane image** · image · playfield and lane Image stretched over each lane. Default none. ### Background {#section-image-background} #### `backgroundImage` {#backgroundimage} **Background image** · image · playfield · simple mode Image stretched over the lanes box. Default none. ## Judgement line {#group-judgement-line} The line drawn on each lane at the receptor line, and the judgement window lines. ### Judgement line {#section-judgement-line-line} #### `judgementLine` {#judgementline} **Draw judgement line** · yes/no · playfield Draws a line on every lane at the judgement line (the receptor line): one segment per lane, as wide as the lane, above the lane background and under the receptors. Default false. Never changes judging. #### `judgementLineColor` {#judgementlinecolor} **Judgement line color** · colour · playfield Colour of the judgement line. Default white. #### `judgementLineAt` {#judgementlineat} **Judgement line position** · choice · `center`, `top`, `bottom` · playfield Where the line sits on the receptors: `center`, `top` (their top edge) or `bottom`, as the screen shows them. Default `center`. #### `judgementLineThickness` {#judgementlinethickness} **Judgement line thickness** · number · 0.0005 to 0.02, step 0.0005 · playfield Thickness of the judgement line, in screen heights. Default 0.003. #### `judgementLineOffsetY` {#judgementlineoffsety} **Judgement line offset (along scroll)** · number · −0.5 to 0.5, step 0.001 · playfield Moves the judgement line along the scroll from where `judgementLineAt` puts it (positive: the direction of the notes). Default 0. #### `judgementWindowThickness` {#judgementwindowthickness} **Judgement window line thickness** · number · 0.0005 to 0.02, step 0.0005 · playfield Thickness of the judgement window lines, in screen heights. They only show when tiers are ticked in Settings, Game. Default 0.002. #### `judgementWindowOpacity` {#judgementwindowopacity} **Judgement window line opacity** · number · 0 to 1, step 0.01 · playfield Multiplies the alpha of the judgement window lines. Default 0.7. #### `judgementWindowDashed` {#judgementwindowdashed} **Dashed judgement window lines** · yes/no · playfield Judgement window lines dashed instead of solid. Default false. ## Lane cover {#group-lane-cover} A block of colour over the lanes where the notes appear. ### Lane cover {#section-lane-cover-lane-cover} #### `laneCover` {#lanecover} **Draw lane cover** · yes/no · playfield A block of colour over the whole width of the lanes, drawn above the notes on the side where they appear, never past the receptor edge. Default false. Visual only. The Sudden and Hidden modifiers draw this same cover. #### `laneCoverColor` {#lanecovercolor} **Lane cover color** · colour · playfield Colour of the cover. Default `#000000`. #### `laneCoverOpacity` {#lanecoveropacity} **Lane cover opacity** · number · 0 to 1, step 0.01 · playfield Multiplies the alpha of the cover colour. Default 1. At 0 it also turns off Sudden and Hidden. #### `laneCoverSize` {#lanecoversize} **Lane cover size** · number · 0 to 1, step 0.005 · playfield How far the cover reaches from the edge where the notes appear, as a fraction of the lanes box height. Default 0.3. #### `laneCoverFeather` {#lanecoverfeather} **Lane cover soft edge** · number · 0 to 0.2, step 0.005 · playfield Soft edge: the end of the cover fades out over this length (a fraction of the lanes box height, never more than the cover). Default 0: a sharp edge. ## Hold end {#group-hold-end} The image at the tail of a hold. ### Hold end {#section-hold-end-hold-end} #### `holdEnd` {#holdend} **Hold end image** · image · playfield and lane Image of the end of a hold. It is written like a note: its tip (the bottom of the image) aims at the receptors when notes fall; the game flips it so it points away from the receptors in the playfield's frame. Default: a white rectangle. #### `holdEndColor` {#holdendcolor} **Hold end color** · colour · playfield and lane Tint multiplied with the hold end image. Default white. #### `holdEndSize` {#holdendsize} **Hold end size** · size · 0 to 2 per side · playfield and lane Size of the hold end. Default 0.0725 × 0.015. A height of 0 draws no end. With `holdMatchNoteWidth` only its height counts. #### `holdEndScale` {#holdendscale} **Hold end scale** · number · 0.1 to 3, step 0.01 · playfield and lane Multiplies the resolved size of the hold end; the position of the end does not move. Default 1. #### `holdEndOffset` {#holdendoffset} **Hold end offset (toward receptor)** · number · −0.5 to 0.5, step 0.001 · playfield and lane Moves the hold end image along the scroll, positive towards the receptor ("30 px before the end" is positive). Default 0. An end whose time is off the drawn area is not drawn. #### `holdEndFlip` {#holdendflip} **Turn hold end over** · yes/no · playfield and lane Flips the hold end image relative to the automatic orientation. Default false. #### `holdEndRound` {#holdendround} **Round hold end** · yes/no · playfield and lane Rounds the end of the hold: the body itself narrows to the hold's end (moved by `holdEndOffset`), with the body's image, color and fade, as deep as half its width times `holdEndScale`. The end image is not drawn. Default false. Visual only. #### `holdEndFade` {#holdendfade} **Hold end fade length** · number · 0 to 10, step 0.005 · playfield and lane Length of a fade at the far end of the hold (the end it comes from), in screen heights: the body and the end image go from `holdEndFadeStart` to full opacity over this distance, towards the receptors. Default 0: no fade. Visual only. #### `holdEndFadeStart` {#holdendfadestart} **Hold end opacity (at the very end)** · number · 0 to 1, step 0.01 · playfield and lane Opacity at the very end of the hold when a fade is on (`holdEndFade` or `holdEndFadeMs`), 0 to 1. Default 0: invisible. #### `holdEndFadeMs` {#holdendfadems} **Hold end fade start (ms before the end)** · number · 0 to 2000, step 1 · playfield and lane Where the end fade starts, in milliseconds before the hold's end, 0 to 2000: the body and the end image go from full opacity to `holdEndFadeStart` between that moment and `holdEndHiddenMs`, whatever the scroll speed. Default 0: off (`holdEndFade` then applies). Visual only. #### `holdEndHiddenMs` {#holdendhiddenms} **Hold end invisible from (ms before the end)** · number · 0 to 2000, step 1 · playfield and lane From this many milliseconds before the end (0 to `holdEndFadeMs`), the hold stays at `holdEndFadeStart` to its end. For example `holdEndFadeMs` 100 and `holdEndHiddenMs` 50: the fade starts 100 ms before the end and the hold is invisible over the last 50. Default 0: the fade runs to the very end. ## Measure lines {#group-measure} The lines at each measure and each beat, scrolling with the notes. ### Measure lines {#section-measure-measure} #### `measureLines` {#measurelines} **Draw measure lines** · yes/no · playfield A line across the playfield at the start of every measure, scrolling like the notes, drawn under the receptors and the notes and above the lane backgrounds. Default false. Native, no mod needed. It follows the tempo changes and the rate, and shows in play, replay, visualizer, preview and the skin editor, not in the map editor. #### `measureLineColor` {#measurelinecolor} **Measure line color** · colour · playfield Colour of the measure lines. Default white. #### `measureLineOpacity` {#measurelineopacity} **Measure line opacity** · number · 0 to 1, step 0.01 · playfield Multiplies the alpha of the measure line colour. Default 0.35. #### `measureLineThickness` {#measurelinethickness} **Measure line thickness** · number · 0.0005 to 0.02, step 0.0005 · playfield Thickness of the measure lines, in screen heights. Default 0.003. #### `measureLineLength` {#measurelinelength} **Measure line length** · choice · `playfield`, `lanes` · playfield `playfield`: one continuous line across the playfield. `lanes`: one segment per lane, on the receptor line of that lane. Default `playfield`. #### `measureLineOvershoot` {#measurelineovershoot} **Overshoot past the lanes** · number · 0 to 0.5, step 0.005 · playfield How far a line reaches past the outer lanes, in screen heights (`playfield` length only). Default 0. #### `measureLineEvery` {#measurelineevery} **Emphasise every N measures** · number · 1 to 16, step 1 · playfield One measure in N is emphasised (twice as thick, full alpha of the colour), counting from the first measure. 1: none. Default 1. ### Beat lines {#section-measure-beat} #### `beatLines` {#beatlines} **Draw beat lines** · yes/no · playfield A dimmer line at each of the other beats of the measure, under the measure lines. Default false. #### `beatLineColor` {#beatlinecolor} **Beat line color** · colour · playfield Colour of the beat lines. Default white. #### `beatLineOpacity` {#beatlineopacity} **Beat line opacity** · number · 0 to 1, step 0.01 · playfield Multiplies the alpha of the beat line colour. Default 0.12. #### `beatLineThickness` {#beatlinethickness} **Beat line thickness** · number · 0.0005 to 0.02, step 0.0005 · playfield Thickness of the beat lines, in screen heights. Default 0.002. ## Lighting {#group-lighting} The key light, the stage light, the hit light and the hold light. ### Key light {#section-lighting-key-light} #### `keyLightOn` {#keylighton} **Show the key light** · yes/no · playfield and lane · simple mode The receptor reacts to its key, even on a lane with no note. `false`: it does not react (the `receptor` image stays). Default true. #### `receptorPressed` {#receptorpressed} **Key light image** · image · playfield and lane Image of the receptor while its key is held. Default: the `receptor` image. #### `pressedColor` {#pressedcolor} **Key light color** · colour · playfield and lane Tint of the key light. Default white. #### `keyLightOpacity` {#keylightopacity} **Key light opacity** · number · 0 to 1, step 0.01 · playfield and lane Multiplies the alpha of the key light colour. Default 1. #### `keyLightScale` {#keylightscale} **Key light scale** · number · 0.25 to 3, step 0.01 · playfield and lane Scale of the pressed receptor around its centre. Default 1 (its size). #### `keyLightFadeMs` {#keylightfadems} **Key light fade (ms)** · number · 0 to 500, step 5 · playfield and lane Fade in and out of the key light, in milliseconds. Default 0: instant. The normal receptor stays drawn under the pressed one during the fade. ### Stage light {#section-lighting-stage-light} #### `stageLightOn` {#stagelighton} **Show the stage light** · yes/no · playfield and lane · simple mode Switches the stage light off without touching its image, colour or animations. Default true. #### `stageLight` {#stagelight} **Stage light image** · image · playfield and lane Image drawn over a lane while its key is held, above the receptor and under the notes, its near edge on the receptor line, spreading to where the notes come from. Default none: nothing is drawn. #### `stageLightColor` {#stagelightcolor} **Stage light color** · colour · playfield and lane Tint of `stageLight`. Default white. #### `lightTintStrength` {#lighttintstrength} **Light color strength** · number · 0 to 1, step 0.01 · playfield and lane How the light colours (`stageLightColor`, `hitLightColor` or the judgement's colour, `holdLightColor`, `mineLightColor`) apply to the light images, with the same rule as `noteTintStrength`. Also per column. Default absent. #### `stageLightOpacity` {#stagelightopacity} **Stage light opacity** · number · 0 to 1, step 0.01 · playfield and lane Multiplies the alpha of the stage light. Default 1. #### `stageLightSize` {#stagelightsize} **Stage light size** · size · 0 to 2 per side · playfield and lane Size of the stage light. A width of 0 means the lane width, a height of 0 follows the image. Default 0 × 0. #### `stageLightScale` {#stagelightscale} **Stage light scale** · number · 0.1 to 3, step 0.01 · playfield and lane Factor applied to the resolved size. The edge near the receptors stays on their line. Default 1. #### `stageLightOffsetY` {#stagelightoffsety} **Stage light offset (along scroll)** · number · −0.5 to 0.5, step 0.001 · playfield and lane Moves the stage light along the scroll (positive: the direction of the notes). Default 0. #### `stageLightFadeMs` {#stagelightfadems} **Stage light fade (ms)** · number · 0 to 500, step 5 · playfield and lane Fade in and out of the stage light, in milliseconds, in real frame time. Default 100; 0 is instant. ### Hit light {#section-lighting-hit-light} #### `hitLight` {#hitlight} **Hit light image** · text · playfield Pattern of the images of the hit light, a path with the token `{n}` that each frame number replaces (`fx/spark-{n}.png`, frames 0, 1, 2…). Played once at the receptors on every non-miss judgement of the lane (note, hold head, judged hold release) and restarted by the next one. A single image needs no token. Default none. #### `hitLightOn` {#hitlighton} **Show the hit light on** · choice · `all`, `off` · playfield · simple mode `all`: the hit light plays on every hit. `off`: never, whatever the skin. The hold light and the stage light have their own fields. Default `all`. #### `hitLightFollowJudgement` {#hitlightfollowjudgement} **Hit light follows the judgement** · yes/no · playfield The hit light takes the colour of the judgement tier that was hit instead of `hitLightColor`. The opacity still applies. Default false. #### `hitLightFrames` {#hitlightframes} **Hit light frame count** · number · 1 to 32, step 1 · playfield Number of frames of the hit light, 1 to 32. Default 1. #### `hitLightFps` {#hitlightfps} **Hit light frame rate** · number · 1 to 240, step 1 · playfield Frames per second of the hit light, in real time. Default 60. #### `hitLightColor` {#hitlightcolor} **Hit light color** · colour · playfield Tint of the hit light. Default white. #### `hitLightOpacity` {#hitlightopacity} **Hit light opacity** · number · 0 to 1, step 0.01 · playfield Multiplies the alpha of the hit light. Default 1. #### `hitLightSize` {#hitlightsize} **Hit light size** · size · 0 to 2 per side · playfield Size of the hit light. A width of 0 means twice the lane width, a height of 0 follows the image. Default 0 × 0. #### `hitLightScale` {#hitlightscale} **Hit light scale** · number · 0.1 to 3, step 0.01 · playfield Factor applied to the resolved size, around the centre of the image. Default 1. #### `hitLightOffsetY` {#hitlightoffsety} **Hit light offset (along scroll)** · number · −0.5 to 0.5, step 0.001 · playfield Moves the hit light along the scroll (positive: the direction of the notes). Default 0. ### Hold light {#section-lighting-hold-light} #### `holdLight` {#holdlight} **Hold light image** · text · playfield Pattern of the images of the hold light, same `{n}` rule as `hitLight`. It loops while a hold of the lane is held (from its judged head, not a miss, to its release or end). Default none. #### `holdLightFrames` {#holdlightframes} **Hold light frame count** · number · 1 to 32, step 1 · playfield Number of frames of the hold light, 1 to 32. Default 1. #### `holdLightFps` {#holdlightfps} **Hold light frame rate** · number · 1 to 240, step 1 · playfield Frames per second of the hold light. Default 60. #### `holdLightColor` {#holdlightcolor} **Hold light color** · colour · playfield Tint of the hold light. Default white. #### `holdLightOpacity` {#holdlightopacity} **Hold light opacity** · number · 0 to 1, step 0.01 · playfield Multiplies the alpha of the hold light. Default 1. #### `holdLightSize` {#holdlightsize} **Hold light size** · size · 0 to 2 per side · playfield Size of the hold light. A width of 0 means twice the lane width, a height of 0 follows the image. Default 0 × 0. #### `holdLightScale` {#holdlightscale} **Hold light scale** · number · 0.1 to 3, step 0.01 · playfield Factor applied to the resolved size. Default 1. #### `holdLightOffsetY` {#holdlightoffsety} **Hold light offset (along scroll)** · number · −0.5 to 0.5, step 0.001 · playfield Moves the hold light along the scroll (positive: the direction of the notes). Default 0. ### Mine light {#section-lighting-mine-light} #### `mineLight` {#minelight} **Mine light image** · text · playfield Pattern of the images of the mine light, same `{n}` rule as `hitLight`. It plays once on the receptor of a lane when one of its mines goes off. Without it the game draws its own flash: the mine grows and fades. Default none. #### `mineLightFrames` {#minelightframes} **Mine light frame count** · number · 1 to 32, step 1 · playfield Number of frames of the mine light, 1 to 32. Default 1. #### `mineLightFps` {#minelightfps} **Mine light frame rate** · number · 1 to 240, step 1 · playfield Frames per second of the mine light. Default 60. #### `mineLightColor` {#minelightcolor} **Mine light color** · colour · playfield Tint of the mine light. Default white. #### `mineLightOpacity` {#minelightopacity} **Mine light opacity** · number · 0 to 1, step 0.01 · playfield Multiplies the alpha of the mine light. Default 1. #### `mineLightSize` {#minelightsize} **Mine light size** · size · 0 to 2 per side · playfield Size of the mine light. A width of 0 means twice the lane width, a height of 0 follows the image. Default 0 × 0. #### `mineLightScale` {#minelightscale} **Mine light scale** · number · 0.1 to 3, step 0.01 · playfield Factor applied to the resolved size. Default 1. #### `mineLightOffsetY` {#minelightoffsety} **Mine light offset (along scroll)** · number · −0.5 to 0.5, step 0.001 · playfield Moves the mine light along the scroll (positive: the direction of the notes). Default 0. ## Sound {#group-sound} The key sound of a lane. ### Key sound {#section-sound-hit-sound} #### `hitSound` {#hitsound} **Key sound file** · text · playfield and lane A sound file of the skin (`.wav`, `.ogg`, `.flac` or `.mp3`) played when the key of the lane is pressed, if Settings, Audio, key sounds is on. Only its first second is used. It is read once at launch: a `playfield.update` does not change it during a play. Default: the game's own sound. ## Rendering {#group-rendering} How the textures are sampled. ### Rendering {#section-rendering-texture} #### `textureFilter` {#texturefilter} **Image smoothing** · choice · `linear`, `nearest` · playfield `linear` samples bilinearly, so scaled sprites stay smooth. `nearest` keeps sharp pixels (pixel art). Default `linear`. ===== Page: Build a HUD element Address: https://prism.am/dev/guides/hud-element/ Derived from: crates/modding/src/scene.rs, crates/modding/src/api.rs, crates/modding/src/fonts.rs, crates/modding/src/assets.rs, content/examples/mods/hud-combo-panel/main.ts, content/mods/combo/main.ts, content/mods/progress-bar/main.ts, content/mods/judgement-display/main.ts, content/mods/sdk/modding.d.ts # Build a HUD element Draw text, boxes and images over the game with hud.*: bindings, layout, style, show conditions, animation, images and fonts, with a complete working mod. The HUD is a tree of nodes that your mod keeps and the game draws in its overlay, above everything else. You describe the nodes once; the overlay updates them. A value that changes at every judgement or every frame (the combo, the accuracy, the song progress) is never written by your script: a **binding** names it and the overlay fills it in, with no round trip to the mods thread. Use `hud.*` for anything that is text, a box or a PNG. If you need effects locked to the frame of the notes (sparks at a hit, a lane glow), use the [native stage](https://prism.am/dev/md/guides/stage-drawing.md) instead. A skin builds the game's HUD with the same `hud.*` calls; this page applies to mods and skins alike. It assumes you have made [a first mod](https://prism.am/dev/md/first-mod.md). ## A complete element {#complete-example} This mod draws a panel in the bottom-left corner: a badge and the combo, the accuracy, the last judgement with its timing, a count per hit tier, and a progress bar. The folder also holds `badge.png`. Nothing in it runs per judgement. ```ts /// // A panel in the bottom-left corner: a badge and the combo, the accuracy, the last // judgement with its offset, a count per hit tier, and a song progress bar. Everything // the panel shows changes through bindings: the overlay updates the texts and the bar // itself, so no script runs per judgement. The mod only places the nodes, once per play. // // Install it by copying this folder into the mods folder (Mods page → Open folder). /** Screen height fractions: every length of a layout or a style is one. */ const PANEL_WIDTH = 0.42; const BAR_HEIGHT = 0.008; const SHADOW = { x: 0, y: 0.002, blur: 0.004, color: "#000000b3" }; function build(tiers: TierInfo[]) { hud.clear(); // The panel: a column group. Its children are placed one under the other, in creation // order, so they carry no `x` or `y`. It sits at the bottom-left corner of the screen. hud.group({ id: "panel", flow: { direction: "column", gap: 0.006, align: "start" }, layout: { x: 0.015, y: 0.985, anchor: "bottomLeft" }, style: { background: "#000000a6", radius: 0.012, padding: 0.012 }, }); // A row: the badge (a PNG of the mod's folder) and the combo. hud.group({ id: "head", parent: "panel", flow: { direction: "row", gap: 0.01, align: "center" } }); hud.image({ id: "badge", parent: "head", src: "badge.png", layout: { width: 0.05, height: 0.05 } }); hud.group({ id: "combo-box", parent: "head", flow: { direction: "column", align: "start" } }); hud.text({ id: "combo-label", parent: "combo-box", text: "COMBO", bind: { kind: "label", label: "combo" }, style: { size: 0.014, color: "theme:text-2", label: true }, }); hud.text({ id: "combo", parent: "combo-box", text: "0", bind: { kind: "combo" }, // The text is replayed at every hit: a short pop, centered on the node. animate: { on: "hit", kind: "pop", durationMs: 140 }, style: { size: 0.05, weight: 700, color: "theme:text", face: "num", shadow: SHADOW }, }); hud.text({ id: "accuracy", parent: "panel", text: "100.00%", bind: { kind: "accuracy", decimals: 2 }, style: { size: 0.026, color: "theme:accent", face: "num", shadow: SHADOW }, }); // The last judgement takes the color of its tier; it appears after the first one. hud.group({ id: "last", parent: "panel", flow: { direction: "row", gap: 0.008, align: "center" }, showWhen: "judged" }); hud.text({ id: "judgement", parent: "last", text: "", bind: { kind: "lastJudgement" }, animate: { on: "judgement", kind: "popOut", durationMs: 700 }, style: { size: 0.03, weight: 700, shadow: SHADOW }, }); hud.text({ id: "offset", parent: "last", text: "", bind: { kind: "lastOffset", decimals: 0 }, style: { size: 0.018, face: "num", shadow: SHADOW }, }); // One row per hit tier (it has a window; the Miss tier has none), at most four: its // translated name and its count, in the tier's color. const hitTiers = tiers.filter((tier) => tier.lateMs !== null && tier.lateMs !== undefined).slice(0, 4); for (const tier of hitTiers) { hud.group({ id: `tier-${tier.index}`, parent: "panel", flow: { direction: "row", gap: 0.008 } }); hud.text({ id: `tier-${tier.index}-name`, parent: `tier-${tier.index}`, text: tier.name, bind: { kind: "tierName", tier: tier.index }, style: { size: 0.016, color: tier.color }, }); hud.text({ id: `tier-${tier.index}-count`, parent: `tier-${tier.index}`, text: "0", bind: { kind: "tierCount", tier: tier.index }, style: { size: 0.016, color: tier.color, face: "num" }, }); } // The bar: a track and a fill that the overlay clips from the song clock. hud.group({ id: "bar", parent: "panel", layout: { width: PANEL_WIDTH, height: BAR_HEIGHT } }); hud.box({ id: "track", parent: "bar", layout: { x: 0, y: 0, width: PANEL_WIDTH, height: BAR_HEIGHT }, style: { background: "#ffffff2e", radius: BAR_HEIGHT / 2 }, }); hud.box({ id: "fill", parent: "bar", fill: { kind: "songProgress" }, layout: { x: 0, y: 0, width: PANEL_WIDTH, height: BAR_HEIGHT }, style: { background: "theme:accent", gradient: { angle: 90, stops: [{ color: "theme:accent", at: 0 }, { color: "#ffffff", at: 1 }] }, radius: BAR_HEIGHT / 2, }, }); // Shown while the game is paused only. hud.text({ id: "paused", text: "PAUSED", bind: { kind: "label", label: "paused" }, showWhen: "paused", layout: { x: 0.5, y: 0.45, anchor: "center" }, style: { size: 0.06, weight: 700, color: "#ffffff", shadow: SHADOW }, }); } export default defineMod({ id: "example.combo-panel", name: "Combo panel", version: "1.0.0", apiVersion: 2, author: "Prism", description: "A bottom-left panel: combo, accuracy, last judgement, tier counts and song progress.", setup() { ctx.on("game.songStart", (start: SongStartEvent) => build(start.judgements.tiers)); ctx.on("game.songEnd", () => hud.clear()); }, }); ``` Copy the folder `hud-combo-panel` into your mods folder (Mods page, *Open folder*) and start a map. The rest of this page explains each part. The mod builds its tree at `game.songStart` and clears it at `game.songEnd`. That is the convention for a HUD mod: no nodes outside a play, a fresh tree for each play, built from the judgement tiers of the map that starts. ## The node tree {#node-tree} A mod owns one tree. Its nodes stay on screen until `hud.remove`, `hud.clear` or the mod being disabled. The trees of all mods stack above the skin's tree, in load order. | Function | Creates | Specific fields | |---|---|---| | `hud.text` | a text | `text` (required), `bind` | | `hud.box` | a rectangle: background, gradient, border, radius, shadow | `fill` (partly filled from the left) | | `hud.image` | a PNG of the mod's folder | `src` (required), `fit`: `contain` (default), `cover`, `fill` | | `hud.group` | a container | `flow` (lays children in a row or a column) | Every node also takes `id` (required), `parent`, `visible`, `showWhen`, `animate`, `element`, `layout` and `style`. The creation functions return the `id`. ### Ids and groups {#ids-groups} An `id` is 1 to 64 characters without control characters, unique inside your mod. Only a group can be a `parent`, and groups nest at most 8 levels deep. Children are drawn in creation order. A node's `x` and `y` are fractions of its parent (of the screen at the first level). Creating a node with an existing `id` replaces it where it is. The parent must be the same: to move a node, remove it and create it again. Creating an identical node changes nothing, so a rebuild that produces the same tree costs nothing. ### Changing and removing nodes {#update-remove} `hud.update` changes a node you already made. The `layout` and `style` fields you give replace those of the node and the others stay. `text` and `bind` exist only on a text, `src` and `fit` on an image, `flow` on a group, `fill` on a box; any other combination throws. ```ts fragment hud.update({ id: "combo", style: { color: "#ffd27a" } }); hud.update({ id: "panel", visible: false }); hud.remove("last"); hud.clear(); ``` `hud.remove` deletes the node and all its descendants and ignores an unknown `id`. `hud.update` of an unknown `id` throws. Rebuilding the whole element when its options change (`hud.remove` of the root, then the creation calls) is the simplest approach and what the shipped mods do. It is cheap: unchanged nodes publish nothing. ## Text and bindings {#bindings} `text` is shown outside a play and while no binding gives a value. During a play a `bind` replaces it. The overlay resolves and formats every binding itself, on the frame the value changes. ### Bindings for one play {#bindings-play} | `bind.kind` | Shows | |---|---| | `combo`, `maxCombo` | the combo, the highest combo of the play | | `hits` | judged notes that are not misses | | `misses` | the count of the Miss tier (the last tier) | | `judged`, `remaining` | notes judged so far, notes not judged yet | | `accuracy` | the accuracy as a localized percentage; `decimals` 0 to 4, 2 by default | | `tierCount {tier, digits?, padColor?}`, `tierName {tier}` | the count and the translated name of the tier at index `tier` (0 to 32). `digits` (1 to 6) pads the count with zeros, like `0284`; `padColor` colors those leading zeros (the whole count while it is 0) | | `lastJudgement {colors?}` | the name of the last tier judged, in that tier's color, or in the color `colors` gives its id or its index (`{ "perfect": "#fff", "3": "#4fc3f7" }`, 64 entries at most) | | `lastOffset {decimals?, tinted?, colors?, side?}` | the signed timing of the last judgement, like `-12 ms` (early) or `+8 ms` (late). `decimals` 0 to 3, 0 by default. Empty before the first judgement and for a miss. The node takes the tier's color unless `tinted` is `false`. `side` shows only the `early` or only the `late` timings, so two nodes put the timing on the side of its sign | | `elapsed`, `total`, `timer` | the song time `m:ss`, the duration, `elapsed / total` | | `fps` | the game's frames per second | | `pavg`, `tierRatio {rank}` | PAvg, and the ratio `1:X` of the hardest (`rank` 0) or second hardest (`rank` 1) hit tier | | `label {label}` | a word translated into the player's language: `hits`, `misses`, `combo`, `accuracy`, `paused`, `remaining`, `fps`, `early`, `late`, `ghost`, `difference`, `kps`, `kpsMax`, `gap`, and the pause menu words `pauseMenuTitle`, `pauseMenuContinue`, `pauseMenuRestart`, `pauseMenuQuit`, `pauseMenuVolume`, `pauseMenuSpeed` | | `action {action}` | a native button, visible only while the game allows its action (`skipIntro`, the `pause*` and `watch*` actions). You choose the look; the game does the action | ```ts fragment hud.text({ id: "acc", text: "", bind: { kind: "accuracy", decimals: 1 } }); hud.text({ id: "early", text: "", bind: { kind: "lastOffset", side: "early" } }); hud.text({ id: "late", text: "", bind: { kind: "lastOffset", side: "late" } }); ``` ### Comparison and ghost bindings {#bindings-versus} Two modes give a play extra data. In a side-by-side comparison of two replays, the single-play bindings above describe the left side only. The `player*` bindings take a `player` (0 left, 1 right): `playerAccuracy`, `playerCombo`, `playerHits`, `playerMisses`, `playerName`, `playerRate`, `playerLastJudgement` and `playerTierCount` (with `tier`). `versusGap {metric, decimals?}` shows how far the left side is ahead (`accuracy`, `combo` or `misses`). They are empty outside a comparison. Against a ghost, `ghostAccuracy`, `ghostDelta` (your accuracy minus the ghost's, in points), `ghostCombo` and `ghostName` show the ghost; they are empty without one. Use `showWhen` to show or hide what depends on the mode (see [Showing and hiding](#show-conditions)). ### Fill of a box {#fill} `fill` cuts a box horizontally at a fraction, from its left edge, following a game value: `{ kind: "songProgress" }` (the song clock, every frame), `{ kind: "accuracy" }`, `{ kind: "tierShare", tier }` (the share of judgements in that tier) and `{ kind: "playerAccuracy", player }` in a comparison. A bar growing from the right is the same box rotated by half a turn with `style.transform: { rotate: 180 }`. ## Layout, anchors and units {#layout} `layout` is `{ x?, y?, width?, height?, anchor? }`. | Field | Meaning | Range | |---|---|---| | `x`, `y` | position as a fraction of the parent's width and height; `(0, 0)` is the top left. Ignored inside a `flow` group | -10 to 10 | | `width`, `height` | size, as a fraction of the screen **height** | 0 to 4 | | `anchor` | the point of the node placed at `(x, y)`: `topLeft` (default), `top`, `topRight`, `left`, `center`, `right`, `bottomLeft`, `bottom`, `bottomRight` | | Every length in `layout` sizes and in `style` is a fraction of the screen height, so an element keeps its proportions in any aspect ratio. At 1920x1080, `0.05` is 54 px; a bar across a 16:9 screen is about 1.73 wide. Without `width` and `height` a node takes the size of its content. Give a size to a group whose children are placed with fractions. A `flow` group lays its children out one after another: `{ direction: "row" | "column", gap?, align?, justify? }`. `gap` is 0 to 1; `align` (across) is `start`, `center`, `end` or `stretch`; `justify` (along) is `start`, `center`, `end` or `spaceBetween`. An invalid layout value throws in your script: ```ts fragment error=TS2322 hud.text({ id: "title", text: "Hello", layout: { x: 0.5, y: 0.1, anchor: "middle" } }); ``` ## Style {#style} `style` maps each property to one CSS property of the overlay. Every field is optional. | Property | Values | Effect | |---|---|---| | `color` | a color | text color; white by default | | `background` | a color | fill of a box or group | | `gradient` | `{ angle, stops: [{ color, at }] }`; 2 to 8 stops, `at` 0 to 1; `angle` in degrees, 0 up and 90 to the right | linear gradient over `background` | | `border` | `{ width, color }`; `width` 0 to 1 | solid border | | `radius`, `padding` | 0 to 1 | corner radius, inner spacing | | `shape` | `plate`, `control`, `panel` | the theme's shape (its clipped corners, the smaller clip of its buttons, its panel radius); wins over `radius` | | `opacity` | 0 to 1 | opacity | | `font` | a font name | see [Fonts](#fonts) | | `face` | a theme font face: `display`, `body`, `num`, `label`, `mono` | the active theme's font; `font` wins if both are set | | `size` | above 0, up to 1; 0.04 by default | font size (line height) | | `weight` | 100 to 900 by steps of 100 | font weight | | `label` | boolean | the theme's label look: its letter case and spacing, and its label weight unless `weight` is set | | `italic` | boolean | italic | | `align` | `start`, `center`, `end` | text alignment | | `shadow` | `{ x, y, blur, color }`; `x`, `y` in -1 to 1, `blur` 0 to 1 | text shadow on a text, box shadow otherwise | | `transform` | `{ x?, y?, scale?, rotate? }`; translation -4 to 4, `scale` 0 to 10, `rotate` in degrees -3600 to 3600 | applied after layout, around the anchor | | `transitionMs` | 0 to 10000 | duration of the transition between two values | ### Colors and the theme {#colors} A color is `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` (sRGB, straight alpha), or `theme:`. A role is a colour token of the active interface theme: `theme:text`, `theme:text-2`, `theme:plate`, `theme:accent`, `theme:line`, `theme:ok`, `theme:danger`, and so on. A role follows the theme when the player changes it, so prefer roles to hex values for the text and surfaces of an element. A name that is not a colour token is refused. ```ts fragment hud.text({ id: "score", text: "0", style: { color: "theme:text", face: "num", shadow: { x: 0, y: 0.002, blur: 0.004, color: "#000000b3" } }, }); ``` `face` is checked as a theme font token (`font-`), so it is not limited to five names. An explicit `font` wins. ## Showing and hiding {#show-conditions} A node is drawn when `visible` is not `false` **and** its `showWhen` holds. Change `visible` with `hud.update`; use `showWhen` for what depends on the state of the play, with no script call. | `showWhen` | The node is drawn | |---|---| | `running` | while the play runs, not paused | | `paused` | while the play is paused | | `judged` | after the first judgement of the play | | `showFps` | when the player's "show FPS" setting is on | | `ghost` | while the play has a ghost | | `versus` | during a side-by-side comparison of two replays | | `solo` | outside a comparison; use it on elements built for one play, since a comparison gives each side its own `player*` bindings | ## Animation {#animation} `animate: { on, kind, durationMs }` restarts an animation on the node each time `on` happens: `judgement` (every judgement), `hit` (a judgement in a hit tier) or `miss` (a judgement in the Miss tier). `durationMs` is 1 to 5000. | `kind` | Effect | |---|---| | `pop` | the scale goes from 1.35 to 1 and the opacity from 0.4 to 1, then the node is back at rest | | `popFade` | the same pop in the first fifth, then the opacity falls to 0.35 over the end of the duration and stays there | | `popOut` | the scale goes from 1.25 to 1 in 140 ms, whatever the duration, while the opacity falls linearly from 1 to 0 over the whole duration; then the node stays hidden | | `flash` | the opacity goes from 0 to 1 and back to 0 | The scale turns around the center of the node, whatever its anchor, and adds to the node's own `transform`. With the system's "reduce motion" preference the overlay keeps the fades and drops the scaling. ## Images and fonts {#images-fonts} ### Images {#images} `hud.image({ src })` takes the path of a `.png` inside the mod's folder: relative, a real file in the folder (links and junctions are followed and must stay inside it), with a PNG signature, at most 8 MiB. The path is checked at the call. The overlay asks the game for the file, which checks it again before serving it. `fit` is `contain` (default), `cover` or `fill`. ### Fonts {#fonts} Declare the fonts of the mod in `defineMod`, then use their names in `style.font`. ```ts /// export default defineMod({ id: "example.big-score", name: "Big score", version: "1.0.0", apiVersion: 2, fonts: { title: "fonts/Title-Bold.ttf" }, setup() { ctx.on("game.songStart", () => { hud.text({ id: "title", text: "0", bind: { kind: "combo" }, layout: { x: 0.5, y: 0.1, anchor: "top" }, style: { font: "title", size: 0.08 }, }); }); ctx.on("game.songEnd", () => hud.clear()); }, }); ``` - A font is a `.ttf` or `.otf` file inside the mod's folder, with a TrueType or OpenType signature, at most 8 MiB. A mod declares at most 8. - The name is 1 to 64 characters among ASCII letters and digits, space, `-`, `_` and `.`, with no space at either end. - An invalid font stops the mod from loading: ``font `title`: …``. - `style.font` with a declared name selects the mod's font; it is published as the family `/` and shadows a global font of the same name for this mod only. `"/"` names a font another package provides, passed through as is: an [element that others configure](https://prism.am/dev/md/guides/elements-settings-storage.md) can take its user's font this way. Any other name is global (`"default"` is the game's font, or a font the player installed). - The overlay uses the game's font for a family it does not have. ## An element others can configure {#configurable} A mod can expose its HUD as an element: it declares options in `provides.elements`, and a skin, another mod or the player places and colors it without a line of your code being called. This is how every widget of the default HUD is built. The pattern, the option kinds and the layers of configuration are in [Configurable elements, settings and storage](https://prism.am/dev/md/guides/elements-settings-storage.md). Give each node of such an element the `element` field when it is one of the game's known elements: `fps`, `accuracy`, `hits`, `misses`, `combo`, `timer`, `remaining`, `status`, `judgement` or `judgementCounts`. The font the player chose for that element (the `hudFonts` setting) then replaces the font of the node and of its descendants. ## Limits {#limits} | What | Limit | |---|---| | Nodes per mod | 384 | | Text length | 256 characters; no control character other than `\n` and `\t` | | `id` length | 1 to 64 characters, no control character | | Group depth | 8 levels | | `layout.x`, `layout.y` | -10 to 10 | | `layout.width`, `layout.height` | 0 to 4 | | `style.size` | above 0, up to 1 | | `radius`, `padding`, `border.width`, `flow.gap` | 0 to 1 | | `shadow` offsets / blur | -1 to 1 / 0 to 1 | | `transform` translation / scale / rotate | -4 to 4 / 0 to 10 / -3600 to 3600 | | `transitionMs` | 0 to 10000 | | Gradient stops | 2 to 8 | | `animate.durationMs` | 1 to 5000 | | `decimals` | 0 to 4 (0 to 3 for `lastOffset`) | | Tier index | 0 to 32 | | `colors` of a binding | 64 entries, keys of 1 to 32 characters | | PNG | 8 MiB | | Fonts | 8 per mod, 8 MiB each | A map script cannot use `hud.*` at all. ## Errors you will see {#errors} A value out of bounds, an unknown field or an unreadable color throws a `TypeError` with the reason in your script. You can catch it. An error that escapes a handler is logged on the Mods page; three in a row, or three calls over the 30 ms budget, disable the mod until the game restarts. ```ts fragment try { hud.update({ id: "combo", style: { size: 2 } }); } catch (error) { log.warn(`HUD: ${error}`); } ``` | Message | Cause | |---|---| | ``style.size must be in (0, 1], got 2`` | a number out of its range (the name is the field's path) | | ``style.color must be #rgb, #rgba, #rrggbb, #rrggbbaa or a colour theme role, got "red"`` | a color that is not hex or a theme role | | ``style.color must name a colour theme role as theme:, got "theme:nope"`` | an unknown role | | ``style.shape must be plate, control or panel, got "round"`` | an unknown shape | | ``the HUD node limit is 384 per mod`` | too many nodes: rebuild instead of piling up | | ``node `x` already exists under another parent; remove it to move it`` | same `id`, new `parent` | | ``parent `p` does not exist`` / ``parent `p` is not a group`` | the parent must exist first and be a group | | ``groups nest at most 8 levels deep`` | a tree too deep | | ``node id must have 1 to 64 characters, without control characters`` | an invalid `id` | | ``text has 300 characters, the limit is 256`` | a text too long | | `` node `x` is a text and has no `src` `` | a `hud.update` field that does not fit the node's kind | | ``node `x` does not exist`` | `hud.update` of an unknown `id` | | ``bind.tier must be a tier index from 0 to 32, got 40`` | a tier index out of range | | ``"badge.png" is not a PNG image`` / ``"badge.png" must be a .png file`` | `src` does not name a real PNG | | `` `hud.text` is not available while the mod loads: call it from `setup` or an event handler `` | a `hud.*` call at the top level of `main.ts` | | `` `hud.text` is not available to map scripts: they only change the playfield `` | `hud.*` in a map script | ## Pitfalls {#pitfalls} - Do not update a binding's value yourself. A `hud.update({ text })` per judgement costs a round trip through the mods thread and lags behind; bind it. - Build in `game.songStart`, not at load. The tiers, the keys and the playfield are those of the map that starts; a skin or a map can change them between plays. - Clear in `game.songEnd`, or the nodes stay on the result screen. - `visible: false` hides a node but keeps it counted in the 384. Remove what you do not need. - A length written as a pixel count is wrong: a size is a fraction of the screen height. `size: 54` throws. - A `hud.update` of `layout` or `style` merges field by field. To drop a field, rebuild the node. - `x` and `y` do nothing for a child of a `flow` group. Move the group. - Colors in hex do not follow the theme. Use `theme:` for text and surfaces. - Time and randomness are not deterministic in a mod. Take every value from events and bindings. ## See also {#see-also} - [hud.* reference](https://prism.am/dev/md/reference/sdk/hud.md) and [`hud.text`](https://prism.am/dev/md/reference/sdk/hud.md#hud-text) for the exact signatures. - [Native rendering with stage.*](https://prism.am/dev/md/guides/stage-drawing.md) for effects drawn by the renderer. - [Configurable elements, settings and storage](https://prism.am/dev/md/guides/elements-settings-storage.md) to let skins and players move your element. - [Write a skin](https://prism.am/dev/md/guides/skin.md), which builds the game's HUD with the same calls. - [Limits](https://prism.am/dev/md/help/limits.md) and [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md). ===== Page: Native rendering with stage.* Address: https://prism.am/dev/guides/stage-drawing/ Derived from: crates/modding/src/stage.rs, crates/stage/src/element.rs, crates/stage/src/scene.rs, crates/stage/src/spec.rs, content/examples/mods/stage-burst/main.ts, content/examples/mods/hit-bursts/main.ts, content/mods/sdk/modding.d.ts # Native rendering with stage.* Draw sprites, shapes, text and particles in the game's own renderer, in the same frame as the notes, with animations and triggers that run without your script. A mod can draw in two ways. `hud.*` places nodes in the web overlay, above everything. `stage.*` places elements in the game's native renderer (wgpu), in the same frame as the notes: sparks at the receptor of a hit note, a glow on a held lane, a sprite that follows the playfield when a map script moves it. Use `stage.*` when an effect must be exact to the frame or must move with the playfield; use [`hud.*`](https://prism.am/dev/md/guides/hud-element.md) for text and panels. You do not draw frame by frame. You **declare** elements, animations and triggers once, and the renderer plays them from the song clock. Skins and [map scripts](https://prism.am/dev/md/guides/map-scripts.md) can use `stage.*` as well. ## A complete example {#complete-example} This mod throws sparks at the receptor of every hit, in the color of the judgement tier, pulses a lane when its key goes down, and makes a "MISS" rise and fade on every miss. The folder holds `spark.png`. ```ts /// // Native drawing (`stage.*`): sparks at the receptor of every hit, in the color of the // judgement tier; a pulse on a lane when its key goes down; a "MISS" that rises and fades // on every miss. The stage is declared once per play. The game's renderer plays it from // the song clock, in the frame that shows the judgement: no script runs per frame, and // the elements follow the playfield wherever the skin or a map script moves it. // // Install it by copying this folder into the mods folder (Mods page → Open folder). /** Sparks one emitter keeps alive; the stage allows 1024 particles in all. */ const SPARKS_PER_TIER = 100; function build(start: SongStartEvent) { // Start from an empty stage: the previous play's elements are gone. stage.clear(); // One emitter per hit tier (a hit tier has a window), at most seven. An emitter // placed on a receptor without `column` bursts at the column of the judgement that // plays it. const hitTiers = start.judgements.tiers.filter((tier) => tier.lateMs !== null && tier.lateMs !== undefined).slice(0, 7); for (const tier of hitTiers) { stage.emitter({ id: `sparks-${tier.index}`, layer: "above", at: { space: "receptor" }, image: "spark.png", size: 0.02, color: tier.color, endColor: "#ffffff00", lifetimeMs: 420, speed: 0.7, speedJitter: 0.5, direction: 0, spread: 150, gravity: 1.6, burst: 12, maxParticles: SPARKS_PER_TIER, shrink: true, }); stage.trigger({ id: `hit-${tier.index}`, on: { judgement: { tier: tier.index, miss: false } }, target: `sparks-${tier.index}`, play: "burst", }); } // A sprite on each receptor, invisible at rest, that swells and fades when the // lane's key goes down. `from`/`to` only name what changes; the rest keeps the // element's values, which come back when the animation ends. for (const lane of start.playfield.lanes) { stage.sprite({ id: `pulse-${lane.column}`, layer: "lanes", at: { space: "receptor", column: lane.column }, image: "spark.png", size: { width: lane.width * 1.4, height: lane.width * 1.4 }, color: "#8fd3ff", opacity: 0, animations: { press: { durationMs: 160, easing: "easeOut", from: { opacity: 0.8, scale: 0.7 }, to: { opacity: 0, scale: 1.3 } }, }, }); stage.trigger({ id: `press-${lane.column}`, on: { press: { column: lane.column } }, target: `pulse-${lane.column}`, play: "press" }); } // Text is drawn with the game's font, on one line of at most 128 characters. stage.text({ id: "miss", layer: "above", at: { space: "playfield", y: 0.1 }, text: "MISS", size: 0.05, color: "#ff5a5a", align: "center", opacity: 0, animations: { rise: { durationMs: 700, easing: "easeOut", from: { opacity: 1, y: 0 }, to: { opacity: 0, y: -0.08 } }, }, }); stage.trigger({ id: "missed", on: { judgement: { miss: true } }, target: "miss", play: "rise" }); } export default defineMod({ id: "example.stage-burst", name: "Stage burst", version: "1.0.0", apiVersion: 2, author: "Prism", description: "Sparks on every hit, a pulse on each pressed lane and a rising MISS, drawn by the game's renderer.", // Without this permission every `stage.*` call throws; the player can withdraw it from the Mods page. permissions: ["stage"], // Only the PNGs listed here are decoded and usable by `stage.sprite` and `stage.emitter`. images: ["spark.png"], setup() { ctx.on("game.songStart", build); }, }); ``` Copy the folder `stage-burst` into your mods folder (Mods page, *Open folder*) and start a map. A second, smaller example is `content/examples/mods/hit-bursts`. ## Permission {#permission} Declare `permissions: ["stage"]` in `defineMod` (the same in `defineSkin` and `defineChart`). Without it every `stage.*` call throws. The Mods page marks such a mod ("Draws in the native renderer"), and the player can withdraw the permission mod by mod. When it is withdrawn, every `stage.*` call throws and the mod's stage is cleared at once. A mod that builds its stage in `setup` gets it back when the mods reload; one that builds it at `game.songStart` gets it back at the next play. ## Elements {#elements} Every element belongs to the script that created it and has an `id` of 1 to 64 characters. Creating an element with an existing `id` replaces it in place, keeping its running animations and particles. | Function | Element | |---|---| | `stage.sprite({ id, at, image, size, color?, opacity?, rotation?, scale?, layer?, animations? })` | a PNG of the package, declared in `images` | | `stage.rect({ id, at, size, color?, radius?, opacity?, rotation?, scale?, layer?, animations? })` | a filled rectangle; `radius` rounds the corners (a circle or a pill when it reaches half the short side) | | `stage.text({ id, at, text, size, color?, align?, opacity?, rotation?, scale?, layer?, animations? })` | one line of at most 128 characters, in the game's font; `size` is in screen heights | | `stage.emitter({ id, at, size, lifetimeMs, maxParticles, ... })` | a particle emitter (see [Emitters](#emitters)) | | `stage.trigger({ id, on, target, play? \| stop? })` | a trigger (see [Triggers](#triggers)) | | `stage.play({ target, animation })`, `stage.stop({ target, animation })` | starts or stops an animation from a handler | | `stage.remove(id)`, `stage.clear()` | removes an element or a trigger, or everything | `color` is `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. `size` of a sprite or a rectangle is `{ width, height }` in screen heights, each 0 to 4. `opacity` is 0 to 1, `scale` 0 to 16, `rotation` in degrees clockwise (-3600 to 3600). The images a mod can use are those of `defineMod({ images: [...] })`: PNG files of the folder, 64 at most. All of them are decoded when a map launches, with the same limits as skin images, and packed in the playfield's atlas. A skin or a map script uses its own `images`. A sprite or an emitter that names an image that is not declared throws. ### Positions {#positions} `at` is `{ space?, column?, x?, y? }`. `x` and `y` move the point of `space`. | `space` | Origin | `x`, `y` | |---|---|---| | `screen` (default) | the top-left corner of the screen | fractions of the width and of the height | | `playfield` | the center of the box of the columns | screen heights, to the right and down | | `lane` | the center of column `column` | the same | | `receptor` | the receptor of column `column` | the same | Every position but `screen` follows the playfield: it moves, turns and scales with it, including when a map script moves it (`rotation`, `zoom`, `offsetX` of the columns). `x` and `y` are within -4 to 4. `column` is below 32; `lane` and `receptor` need a `column`, except on an emitter. An emitter without a `column` on `lane` or `receptor` throws its particles from the column of the event that triggers it. ### Layers {#layers} `layer` is `below` (behind the playfield, over the map's background), `lanes` (over the columns and receptors, under the notes) or `above` (the default, over the notes). All of them are under the HUD overlay. Within a layer, elements are drawn in the order of their scripts, then of their creation. ### Emitters {#emitters} An emitter throws particles: `burst` of them when a trigger plays its `burst`, and `rate` per second continuously. | Field | Meaning | Bounds | |---|---|---| | `size` | size of a particle, in screen heights | above 0, up to 0.5 | | `image` | a declared PNG; a plain square without it | | | `color`, `endColor` | color at birth and at death; `endColor` is `color` by default | | | `lifetimeMs` | life of a particle | above 0, up to 5000 | | `speed`, `speedJitter` | speed in screen heights per second; `speedJitter` varies it by a fraction | 0 to 8; 0 to 1 | | `direction`, `spread` | center of the cone in degrees clockwise from up (0 is up); width of the cone (360 is every direction, the default) | -3600 to 3600; 0 to 360 | | `gravity` | acceleration in screen heights per second squared, positive downward | -16 to 16 | | `burst` | particles per `burst` | 0 to 256 | | `rate` | particles per second | 0 to 1000 | | `maxParticles` | particles alive at once; the oldest is replaced when it is full | 1 to 512 | | `fade`, `shrink` | opacity fades out, size shrinks to 0 over the life; `fade` is on by default, `shrink` off | | ## Animations and triggers {#animations-triggers} ### Animations {#animations} Nothing runs in your script per frame. An element declares its animations once: `animations: { name: { durationMs, easing?, repeat?, from, to } }`. `from` and `to` give `x`, `y` (an offset in screen heights, -4 to 4), `scale`, `rotation`, `opacity` and `color`. A value you leave out stays the element's own, and returns to it when the animation ends. With `repeat` the animation starts again until it is stopped. `durationMs` is above 0, up to 10000. `easing` is `linear` (default), `easeIn`, `easeOut` or `easeInOut`. An element has 8 animations at most, and `burst` is a name kept for emitters. An emitter plays only `burst`. ### Triggers {#triggers} A trigger starts (`play`) or stops (`stop`) an animation of its `target` element when `on` happens. For an emitter, `play: "burst"` throws `burst` particles. `on` holds exactly one field: | `on` | Happens when | |---|---| | `{ judgement: { tier?, column?, miss? } }` | a note is judged; a filter you leave out matches everything | | `{ press: { column? } }`, `{ release: { column? } }` | a lane key goes down, comes up | | `{ holdStart: { column? } }`, `{ holdEnd: { column? } }` | a lane starts, stops holding a long note | ### Cues from a handler {#cues} `stage.play` and `stage.stop` do the same as a trigger from a script handler, for an event no trigger covers. They take effect from the next frame, but they go through the mods thread: they are not frame-exact like a trigger. ```ts fragment ctx.on("game.judgement", (judgement) => { if (judgement.combo > 0 && judgement.combo % 100 === 0) { stage.play({ target: "milestone", animation: "pulse" }); } }); ``` ## When it runs {#timing} The render thread evaluates animations, particles and triggers at each frame, from the song clock (a pause freezes them) and from the judgements the frame shows. A judgement made by the input thread is queued, without a lock or a wait, before the game state shows it, so a burst starts in the very frame the note disappears. The renderer reads your published stage without waiting for your script, which cannot make a frame late. Everything is drawn in the playfield's single instance batch, with the game's shader (no custom shader): a sprite, a rectangle or a particle is one quad, a text is one quad per glyph. A frame without a change of scene allocates nothing; a dead particle frees its place. ## Budgets and limits {#limits} | What | Limit | |---|---| | Elements per script (emitters included) | 128 | | Emitters per script | 16 | | Live particles per script | 1024 in all: the sum of the `maxParticles`, 512 at most per emitter, 256 per `burst` | | Triggers per script | 64 | | Cues queued by `stage.play`/`stage.stop` | 64; the oldest is dropped when it is full | | Animations per element | 8, each up to 10 s | | Text | 128 characters | | `id` (element, trigger, animation) | 1 to 64 characters | | `at.x`, `at.y`, animation offsets | -4 to 4 | | `size` (width, height) | 0 to 4 | | `column` | below 32 | | `images` | 64 PNG per script | ## Errors you will see {#errors} A value out of bounds throws with the field's name in the script. Catch it with `try`, as for `hud.*`. | Message | Cause | |---|---| | `` `stage.sprite` needs the `stage` permission: declare `permissions: ["stage"]` `` | the permission is missing from the declaration | | `` `stage.sprite`: the player turned off native drawing for `example.stage-burst` `` | the player withdrew the permission | | ``image "spark.png" is not declared in `images`: only declared images are loaded`` | a sprite or an emitter names an image missing from `images` | | ``size.width: 5 is outside [0, 4]`` | a number out of bounds (the name is the field's path) | | ``lifetimeMs: 9000 is outside (0, 5000]`` | a value that must be above 0 and at most its maximum | | ``at.column: a `lane` or `receptor` position needs a column`` | `lane`/`receptor` without `column` on a sprite, rectangle or text | | ``column 40 does not exist: there are at most 32 lanes`` | a column out of range | | ``the stage holds 128 elements, its limit`` | too many elements | | ``the stage holds 16 emitters, its limit`` | too many emitters | | ``the stage's emitters would keep 1100 particles alive; the limit is 1024`` | the sum of the `maxParticles` is too high | | ``the stage holds 64 triggers, its limit`` | too many triggers | | `` a trigger needs exactly one of `play` and `stop` `` | a trigger with both or neither | | `` `on` needs exactly one of judgement, press, release, holdStart and holdEnd `` | an `on` with none or several events | | ``element `miss` does not exist`` / ``element `miss` has no animation `rise` `` | `stage.play`/`stage.stop` with an unknown target or animation | | ``animation name `burst` is kept for emitters`` | an animation named `burst` on a sprite, rectangle or text | | ``animations: 9 animations; the limit is 8`` | too many animations on one element | ## Pitfalls {#pitfalls} - Call `stage.clear()` first when you rebuild at `game.songStart`. The stage of the previous play is still there until you clear or replace it. - Declare the PNG in `images`. Putting a file in the folder is not enough: only the listed images are decoded. - An element's `opacity` is its resting value. Give a trigger-driven element `opacity: 0` and animate it in, as the example does for the lane pulse and the MISS text. - Share the particle budget: 7 emitters of 150 particles are already 1050. Size `maxParticles` for the burst you need, not for the maximum. - A `receptor` sprite per column needs the number of columns of the map: read it from `start.playfield.lanes` at `game.songStart`, not from a constant. - `stage.text` draws one line of at most 128 characters, in the game's font: it has no wrapping and no `font` option. Write text that fits. - Text and panels that carry information belong to `hud.*`; the stage is for effects. ## See also {#see-also} - [stage.* reference](https://prism.am/dev/md/reference/sdk/stage.md), for example [`stage.emitter`](https://prism.am/dev/md/reference/sdk/stage.md#stage-emitter). - [Build a HUD element](https://prism.am/dev/md/guides/hud-element.md) for text, boxes and bindings. - [Write a map script](https://prism.am/dev/md/guides/map-scripts.md), which moves the playfield your stage follows. - [Limits](https://prism.am/dev/md/help/limits.md). ===== Page: Configurable elements, settings and storage Address: https://prism.am/dev/guides/elements-settings-storage/ Derived from: crates/modding/src/dependencies.rs, crates/modding/src/elements.rs, crates/modding/src/api.rs, crates/modding/src/storage.rs, crates/modding/src/manifest.rs, crates/modding/src/runtime.rs, content/examples/mods/configurable-counter/main.ts, content/examples/mods/counter-placer/main.ts, content/mods/combo/main.ts, content/mods/accuracy/main.ts, content/mods/judgement-display/main.ts, content/mods/sdk/modding.d.ts # Configurable elements, settings and storage Expose an element that skins, other mods and the player configure, depend on other packages, keep data between sessions, and know what survives a reload. Mods and skins do not call each other. A package that wants to be placed, resized or recolored by others declares an **element** with typed **options**; another package, or the player, sets those options, and the host delivers them to the provider, which redraws. Each package keeps its own engine and its own budget. This is how the whole default HUD works: the default skin builds no `hud.*` node, it only places the elements of the HUD mods. This page covers the provider side, the user side, the dependencies between packages, the persistent `storage.*`, and what a reload keeps. You should know [how to build a HUD element](https://prism.am/dev/md/guides/hud-element.md) first. ## A complete provider {#complete-example} This mod, `example.counter`, provides the element `counter`: a combo counter with a label, the accuracy, the last judgement and the best combo ever reached, which it keeps in its storage. It declares ten options and redraws from them. ```ts /// // A combo counter that others configure. The mod PROVIDES an element, `counter`, with // declared options; a skin, another mod or the player places and colors it without any // script calling another. It receives the options in `elements.configure` and draws the // element from them. The best combo is kept in the mod's storage, so it survives the // game being closed. `counter-placer` is a mod that configures this element. // // Install it by copying this folder into the mods folder (Mods page → Open folder). /** Everything the element accepts: `configure` refuses an unknown option or a value out of bounds. */ const OPTIONS = { x: { type: "number", min: 0, max: 1, default: 0.5, label: "Horizontal position" }, y: { type: "number", min: 0, max: 1, default: 0.08, label: "Vertical position" }, anchor: { type: "enum", values: ["topLeft", "top", "topRight", "left", "center", "right", "bottomLeft", "bottom", "bottomRight"], default: "top", label: "Anchor" }, size: { type: "number", min: 0.01, max: 0.3, default: 0.06, label: "Size" }, visible: { type: "boolean", default: true, label: "Show the counter" }, textColor: { type: "color", default: "theme:text", label: "Combo color" }, label: { type: "string", maxLength: 24, default: "Combo", label: "Label" }, showBest: { type: "boolean", default: true, label: "Show the best combo" }, decimals: { type: "integer", min: 0, max: 4, default: 0, label: "Accuracy decimals", player: true }, judgementColors: { type: "colors", default: {}, label: "Judgement colors by tier" }, } satisfies Record; type Options = { x: number; y: number; anchor: Anchor; size: number; visible: boolean; textColor: string; label: string; showBest: boolean; decimals: number; judgementColors: Record; }; /** The declared defaults, until someone configures the element. */ const declared: Record = OPTIONS; let options = Object.fromEntries(Object.entries(declared).map(([name, option]) => [name, option.default])) as Options; let playing = false; let best = 0; function build() { hud.remove("counter"); if (!playing || !options.visible) return; hud.group({ id: "counter", flow: { direction: "column", align: "center" }, layout: { x: options.x, y: options.y, anchor: options.anchor }, }); hud.text({ id: "counter-label", parent: "counter", text: options.label, style: { size: options.size / 3, color: options.textColor, label: true }, }); hud.text({ id: "counter-value", parent: "counter", text: "0", bind: { kind: "combo" }, animate: { on: "hit", kind: "pop", durationMs: 120 }, style: { size: options.size, weight: 700, color: options.textColor, face: "num" }, }); hud.text({ id: "counter-accuracy", parent: "counter", text: "", bind: { kind: "accuracy", decimals: options.decimals }, style: { size: options.size / 3, color: options.textColor, face: "num" }, }); hud.text({ id: "counter-judgement", parent: "counter", text: "", bind: { kind: "lastJudgement", colors: options.judgementColors }, animate: { on: "judgement", kind: "popOut", durationMs: 500 }, style: { size: options.size / 2.5, weight: 600 }, }); if (options.showBest) { hud.text({ id: "counter-best", parent: "counter", text: `Best ${best}`, style: { size: options.size / 3, color: options.textColor, opacity: 0.7 }, }); } } export default defineMod({ id: "example.counter", name: "Configurable counter", version: "1.0.0", apiVersion: 2, author: "Prism", description: "A combo counter whose position, size and colors other packages and the player set.", // `root` names the HUD node the skin editor finds on screen; only the id is checked. provides: { elements: { counter: { root: "counter", options: OPTIONS } } }, setup() { // Storage is read in `setup` or in a handler, never while the file loads. const saved = storage.get("best-combo"); best = typeof saved === "number" ? saved : 0; ctx.on("elements.configure", (configure) => { if (configure.element === "counter") { options = configure.options as Options; build(); } }); ctx.on("game.songStart", () => { playing = true; build(); }); ctx.on("game.songEnd", (end: SongEndEvent) => { playing = false; hud.clear(); if (!end.aborted && end.maxCombo > best) { best = end.maxCombo; storage.set({ key: "best-combo", value: best }); } }); }, }); ``` Until someone configures the element, the mod works with the declared defaults: that is why it starts from them. After that, every change reaches `elements.configure` with all the options, so the handler only has to replace its options and rebuild. ### The mod that configures it {#placer} A user declares the provider in `uses`, checks it is there with `ctx.has`, and configures the element. It draws nothing itself. ```ts /// // Places and colors the `counter` element of `example.counter` (the folder // `configurable-counter`), without a single `hud.*` call. It declares the package in // `uses`; if the player removed or disabled it, `ctx.has` is false and nothing happens. // // Install both folders by copying them into the mods folder (Mods page → Open folder). export default defineMod({ id: "example.counter-placer", name: "Counter placer", version: "1.0.0", apiVersion: 2, author: "Prism", description: "Moves the configurable counter to the right and colors it.", // Optional by default: without the package this mod still loads. uses: { "example.counter": "^1" }, setup() { if (ctx.has("example.counter")) { // The options are checked against the provider's declaration: an unknown option, // a wrong type or a value out of bounds throws here, in this script. ctx.element("example.counter/counter").configure({ x: 0.98, y: 0.4, anchor: "topRight", size: 0.07, textColor: "#ffd27a", label: "Streak", judgementColors: { "0": "#66ccff", "1": "#88ff88" }, }); } }, }); ``` Copy both folders (`configurable-counter` and `counter-placer`) into your mods folder (Mods page, *Open folder*). The counter appears on the right. Remove `counter-placer` and it goes back to the middle of the top: those are the defaults. ## Declaring an element {#provides} `provides: { elements: { : { root?, options } } }` in `defineMod` or `defineSkin`. - `root` is the `id` of the root node of the element in your HUD tree. The skin editor uses it to find the element on screen. Only the id is checked: the node does not have to exist when you declare. - `options` maps option names to declarations. A declaration is `{ type, min?, max?, values?, maxLength?, default?, label?, player? }`. The key of an element is `"/"`: `example.counter/counter`. Players' settings and `ctx.element` use it. ### Option kinds {#option-kinds} | `type` | Accepts | Declaration fields | |---|---|---| | `number` | a finite number | `min`, `max` | | `integer` | a whole number | `min`, `max` | | `boolean` | `true` or `false` | | | `string` | text without control characters, 256 characters at most | `maxLength` (1 to 256) | | `color` | `#rgb`, `#rrggbb`, `#rrggbbaa`, or `theme:` (a colour token of the active theme: `theme:text`, `theme:accent`...) | | | `enum` | one of `values` | `values` (1 to 32 entries of at most 32 characters, no duplicate) | | `colors` | an object of colors by key (a tier id, an index...), 64 entries at most, keys of at most 32 characters | | `default` is the value you receive when nobody sets one; it must satisfy the declaration. An option with no default and no value is left out of the options you receive: read it as optional. `label` (64 characters at most) is the name shown in the skin editor and in settings. `min` and `max` only exist for numbers, `values` only for an enum, `maxLength` only for a string. A hex color does not follow the theme; `theme:` does. ### Names and limits {#declaration-limits} | What | Rule | |---|---| | Element name | 1 to 32 characters among `a-z`, `0-9` and `-`, starting with a letter | | Option name | 1 to 32 ASCII letters and digits, starting with a letter (`textColor`, not `text-color`) | | Elements per package | 16 | | Options per element | 32 | | `label` | 64 characters | | `feature` of a dependency | 64 characters | An invalid declaration stops the package from loading, with the reason on the Mods page. ## Three layers of configuration {#layers} The options you receive are always the full set, resolved from three layers. **Defaults, then the skin, then the player: the last one wins, and nothing global overrides the player.** 1. **Defaults.** The `default` of each option. 2. **A package.** A skin or a mod calls `ctx.element("/").configure({ ... })`. The options are checked against your declaration (unknown option, type, bounds: an exception in the calling script), completed with the defaults, and delivered to you after the calling script has run. If several packages configure the same element, the latest wins. A skin's configuration is dropped when the skin is replaced: the element goes back to what the other packages and the player left. 3. **The player.** In the skin editor, per skin, the player sets any option of an element it can place, and the host overlays those values on the options of layer 2. ### Receiving the options {#receiving} ```ts fragment ctx.on("elements.configure", (configure) => { // configure.element: the element's name in your provides.elements // configure.from: the id of the package that configured it, or "player" // configure.options: every declared option (the user's value or the default) log.info(`${configure.element} configured by ${configure.from}`); }); ``` `from` is `"player"` when the player's values apply, otherwise the id of the package. The provider always gets every option, never a partial set. A restarting provider (a skin at every map launch, or every mod when the mods reload) receives the last configuration of each user again; you do not have to remember it. A value of the player that your declaration refuses (an unknown option, a wrong type, out of bounds, an enum value you removed) is ignored and reported in your messages: ``example.counter/counter: the player's option `size` is ignored: expected a number in [0.01, 0.3], got 5``. Values of a provider that is absent or disabled are kept and applied when it runs again. ### What the player can change {#player-options} The skin editor edits **every** option of an element that has numeric `x` and `y` options (a *placeable* element: positions, sizes, visibility, fonts, colors, decimals...). The `player: true` flag matters for an element **without** a place, which the editor cannot place: its `player` options are listed in Settings, Game, Mods, and stored in the global setting `elementOptions`, under the skin's configuration. The shipped mods flag the options a player is likely to want (`length` and `mode` of `hit-bar`, `always` of `fps`, `decimals` of `accuracy`); since those elements have `x` and `y`, the skin editor edits them anyway. ```ts fragment const options: Record = { length: { type: "integer", min: 1, max: 256, default: 50, label: "Hits shown", player: true }, mode: { type: "enum", values: ["last", "all"], default: "all", label: "Hits drawn", player: true }, }; ``` Give every option a `label`: it is the only text the player sees. Give an element with a `font` option the `element` field on its nodes so that the player's `hudFonts` choice applies (see [Build a HUD element](https://prism.am/dev/md/guides/hud-element.md#configurable)). ## Using another package {#uses} `uses: { "": "" }` in `defineMod` or `defineSkin`: the id of the package and a range (`"^1"`, `">=1.2, <2"`). The long form is `{ version, required?, feature? }`. At most 16 packages, and a package cannot use itself. ### Optional and required {#optional-required} A dependency is **optional** by default. When the package is absent, installed in another version, or failed to load, your package still loads, `ctx.has("")` is `false`, and the Mods page reads ``feature "Combo styling" disabled: package pvng.combo missing`` (`feature` names what stops working; without it the text reads ``features using pvng.combo disabled: package pvng.combo missing``). The other reasons are ``package pvng.combo 2.0.0 does not match ^1`` and ``package pvng.combo is not active`` (disabled or failed). `required: true` makes it mandatory: without it your package does not load, and the Mods page reads ``requires pvng.combo ^1: package pvng.combo missing``. ```ts /// export default defineMod({ id: "example.combo-skin", name: "Combo styling", version: "1.0.0", apiVersion: 2, uses: { "pvng.combo": { version: "^1", required: false, feature: "Combo styling" }, "pvng.accuracy": "^1", }, setup() { if (ctx.has("pvng.combo")) { ctx.element("pvng.combo/combo").configure({ x: 0.5, y: 0.2, anchor: "top", showLabel: false }); } }, }); ``` ### ctx.has and ctx.element {#ctx-has} `ctx.has(id)` is true when the package is in your `uses`, compatible and running. `ctx.element("/").configure(options)` needs the package in `uses` (``add `pvng.combo` to `uses` to configure its elements``) and checks `options` against the provider's declaration. If the provider is missing, `configure` does nothing and does not throw: the feature is off. Guard with `ctx.has` anyway when the call depends on it, as the default skin does. `ctx.has` and `ctx.element` exist in map scripts too, but a map script has no `uses`: `has` is always false and `configure` throws ``declare the package before configuring elements``. ### Order and cycles {#order} Packages set up after the ones they use; otherwise in load order (see below). A dependency cycle refuses every package of the cycle: ``dependency cycle: a → b → a``. A skin resolves its dependencies at every map launch, against the active mods. ## Storage {#storage} `storage` keeps JSON values between sessions, for mods and skins (not map scripts). | Function | Does | |---|---| | `storage.get(key)` | the stored JSON value, or `null` | | `storage.set({ key, value })` | stores a JSON value | | `storage.remove(key)` | removes a key | | `storage.keys()` | the keys, sorted | | `storage.clear()` | empties the storage | ```ts fragment const saved = storage.get("best-combo"); const best = typeof saved === "number" ? saved : 0; storage.set({ key: "best-combo", value: Math.max(best, 120) }); ``` - A mod's storage is the file `mod-storage/.json` of the game's data folder, chosen by the host from the validated id: a mod cannot read another's. A skin's is `mod-storage/skins/.json`. - Keys are 1 to 128 characters; a mod holds at most **256 keys**. The whole storage (key bytes plus the JSON text of each value) is at most **256 KiB**. A value has no limit of its own beyond that total. - Writes are batched: the file is written at most once per second, through a temporary file renamed over the old one, and once more when the host stops. Uninstalling a mod keeps its storage. - `storage.*` is not available while the file loads: use it in `setup` or in a handler. - An unreadable or over-sized file makes `setup` fail with ``storage : …``. - Anything that must survive a restart goes there: `let` variables are lost. ## Load order, fonts and images {#manifest-fields} These manifest fields shape a package that provides elements. | Field | Meaning | |---|---| | `loadOrder` | 0 to 10000, 1000 by default. Mods set up by `(loadOrder, id)` after the packages they use. The game's own `mods/` load before the player's. HUD layers stack in that order: a later mod draws above an earlier one. The shipped HUD widgets use 300 to 400 | | `fonts` | up to 8 fonts the package bundles: `{ name: "fonts/File.ttf" }`; used by `style.font` as `/`, which another package can name too (see [Fonts](https://prism.am/dev/md/guides/hud-element.md#fonts)) | | `images` | up to 64 `.png` paths decoded for the native stage (see [Native rendering](https://prism.am/dev/md/guides/stage-drawing.md)); the PNGs of `hud.image` do not need to be listed | ## Reloads and state {#reload} The Reload button of the Mods page **restarts the whole mods host**: every package runs its top level and its `setup` again, and module variables are lost. It is refused during a play ("Mods cannot be reloaded during a play"). What you get back after a restart: the configurations that users set on your elements (re-delivered as `elements.configure`), and your `storage`. What you do not: your own variables. Rebuild from `elements.configure` and from `storage.get` in `setup`. `ctx.hot` (`data`, `save`, `dispose`), `ctx.off`, and the `setTimeout` and `setInterval` of `manivelle:env` are in the SDK because it declares the engine's whole context. Do not rely on them: the game does not reload one script in place, so `ctx.hot` has nothing to carry, and nothing advances the timers, so a callback given to `setTimeout` never runs. Drive time from events (`game.tick`, `game.beat`). ## Errors you will see {#errors} | Message | Cause | |---|---| | `` add `example.counter` to `uses` to configure its elements `` | `ctx.element` of a package missing from `uses` | | `` `example.counter` provides no element `bar` `` | an element name the provider does not declare | | ``example.counter/counter: unknown option `colour`, expected one of anchor, decimals, ...`` | an option name that is not declared | | ``example.counter/counter: option `size`: expected a number in [0.01, 0.3], got 5`` | a value out of the declaration (type, bounds, enum) | | ``elements are named "/", got "counter"`` | `ctx.element` without the package prefix | | ``` `uses` names 17 packages; the limit is 16 ``` | too many dependencies | | ``a package cannot use itself`` | `uses` names its own id | | ``dependency cycle: a → b → a`` | packages that use each other | | ``` `uses.x`: "one" is not a semver range: … ``` | an invalid version range | | ``feature "X" disabled: package Y missing`` | an optional dependency is absent (a notice, the package runs) | | ``package Y 2.0.0 does not match ^1`` / ``package Y is not active`` | the other reasons of that notice | | ``requires Y ^1: package Y missing`` | a required dependency is absent (the package does not load) | | `` `provides.elements` declares 17 elements; the limit is 16 `` | too many elements | | ``element `counter` declares 33 options; the limit is 32`` | too many options | | ``element name "Counter" must be 1 to 32 characters starting with a letter`` | an invalid element name | | `` `min` and `max` only apply to numbers `` | `min` or `max` on a non-number | | ``an enum needs 1 to 32 values`` | an empty or oversized enum | | ``element `counter`, option `size`: default: expected a number in [0.01, 0.3], got 5`` | a default that breaks its own declaration | | ``storage keys must have 1 to 128 characters`` | an empty or too long key | | ``the storage holds at most 256 keys`` | a 257th key | | ``the storage holds at most 262144 bytes; this value would bring it to 270000`` | the total is over 256 KiB | | `` `storage.get` is not available while the mod loads: call it from `setup` or an event handler `` | `storage.*` at the top level of `main.ts` | ## Pitfalls {#pitfalls} - Start from the declared defaults. An element nobody configures receives no `elements.configure` and would otherwise show nothing. - Build the nodes only during a play, and clear them at `game.songEnd`, as the shipped HUD mods do. The skin editor still finds the element through `root`. - Option names are alphanumeric: `textColor`, never `text-color`. Element names are the other way round: `hits-row`, never `hitsRow`. - A color option set to hex does not follow the theme; the default `theme:text` does. Defaults should be roles for text and surfaces. - Do not store anything the player must not lose in a variable: use `storage.set`. And do not write on every frame: the file is written once per second at most, and your script pays for each call. - A `player: true` option on a placeable element is edited in the skin editor anyway; the flag only adds a place in Settings for an element without one. - A `required` dependency makes your package disappear when the other is removed. Keep dependencies optional unless the package is useless without it. - Do not read another package's storage or call its functions: there is no such API. Use an element. ## See also {#see-also} - [Build a HUD element](https://prism.am/dev/md/guides/hud-element.md) for the nodes you draw from the options. - [Write a skin](https://prism.am/dev/md/guides/skin.md), which configures the elements of the HUD mods. - [storage.* and ctx reference](https://prism.am/dev/md/reference/sdk/game.md) and the event [`elements.configure`](https://prism.am/dev/md/reference/sdk/events.md#event-elements-configure). - [Mod package format](https://prism.am/dev/md/formats/pvmod.md) for `fonts`, `images` and the limits of a package. - [Limits](https://prism.am/dev/md/help/limits.md) and [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md). ===== Page: Writing a skin Address: https://prism.am/dev/guides/skin/ Derived from: docs/skins.md, crates/skin/src/spec.rs, crates/skin/src/prepare.rs, crates/skin/src/player.rs, crates/skin/src/package.rs, crates/skin/src/paths.rs, crates/modding/src/manifest.rs, crates/modding/src/api.rs, crates/modding/src/play.rs, content/skins/default/skin.ts # Writing a skin How a skin is built, from its folder and defineSkin to the three layers of the playfield, images, sounds, live changes and the errors you will see. A skin is a folder with a TypeScript script, `skin.ts`, and the images, sounds and fonts it names. The game runs the script at every map launch. `setup(play)` describes the native playfield (where the lanes sit, how big the notes are, colors, images, lights) and places the HUD elements that mods provide. Handlers registered in `setup` can change the playfield while the map plays. The playfield is drawn by the game itself, at the speed of the notes. A skin never draws frames; it only gives values. For the HUD, see [HUD elements](https://prism.am/dev/md/guides/hud-element.md). If you want a first working skin in a few minutes, start with [your first skin](https://prism.am/dev/md/first-skin.md) and come back for the rules. ## A complete skin {#example} This skin uses colors only: no image to ship. ```ts // Ember: a warm skin made of colors only, no image. Copy this folder into your skins folder, // change `id` and `name`, and press Reload on the Skins page. // // A skin is one script. The game runs it at every map launch: `setup` describes the playfield // (sizes are fractions of the screen height) and places the HUD elements of the mods. Handlers // registered in `setup` may change the playfield during the play. /** Share of the screen height all the lanes together fill, whatever the number of keys. */ const FIELD = 0.42; const FLASH = "#ffb36b"; export default defineSkin({ id: "ember", name: "Ember", version: "1.0.0", apiVersion: 2, author: "Prism docs", description: "A warm skin made of colors only.", uses: { "pvng.combo": "^1" }, setup(play: PlayContext) { // Narrower lanes when there are more keys: the field keeps about the same width. const laneWidth = Math.min(0.1, FIELD / play.columns); playfield.set({ laneWidth, laneGap: 0.004, receptorY: 0.86, scroll: "down", laneColor: "#241616c8", noteColor: "#ff8a3d", receptorColor: "#ffd2a8", pressedColor: "#fff2e0", holdBodyColor: "#c2531b", holdEndColor: "#ff8a3d", holdMatchNoteWidth: true, keyLightFadeMs: 80, judgementLine: true, judgementLineColor: FLASH, judgementLineThickness: 0.002, measureLines: true, measureLineOpacity: 0.2, borderWidth: 0.004, borderColor: "#ffb36b00", }); // The two outer lanes a little lighter than the others. for (const column of [0, play.columns - 1]) { lanes.set({ column, lane: { laneColor: "#3a2020d0" } }); } // The HUD is made of mods: the skin only places their elements. if (ctx.has("pvng.combo")) { ctx.element("pvng.combo/combo").configure({ x: 0.5, y: 0.2, anchor: "top", size: 0.05 }); } // Every 100 combo the frame around the lanes lights up, then fades over 600 ms. ctx.on("game.judgement", (judgement: JudgementEvent) => { if (judgement.combo === 0 || judgement.combo % 100 !== 0) return; playfield.update({ patch: { borderColor: FLASH } }); playfield.update({ patch: { borderColor: "#ffb36b00" }, transitionMs: 600, easing: "easeOut" }); }); }, }); ``` - `defineSkin` is the only thing the script exports. It is called once, at the top level. - `setup(play)` runs at every launch. `play.columns` is the number of keys, so the same script fits 4K to 16K. - `playfield.set` gives values for the whole playfield. `lanes.set` gives values for one lane. - `ctx.on("game.judgement", …)` registers a handler. During the play, `playfield.update` changes values, here with a transition. - The two `uses` and `ctx.has` lines place the combo counter, which is a mod. The second example below adds images. Every value that can be set is in the [field reference](https://prism.am/dev/md/reference/skin-fields.md). ## Folder and package {#package} A skin is a folder. The folder name is the skin's id on this machine: 1 to 64 characters, valid as a Windows folder name, not starting with a dot. | Where | Folder | | --- | --- | | Skins of the game | `skins\` next to `prism.exe` (`content/skins/` in the repository). Read from disk like any other skin: none is built into the binary. | | Skins of the player | `%LOCALAPPDATA%\Prism\PrismNG\data\skins\\`, or the folder named by the `PRISM_SKINS_DIR` environment variable (it only replaces this player folder). | The list takes the skins of the game first, then the player's. When two folders have the same id, the first one wins and a message says so. A folder without `skin.ts` is not a skin; the Skins page reports it. With no skin at all, the engine plays with its own values (white rectangles, no image) and shows one notice: `No skin found: put a skin folder in skins/`. Inside the folder, every file is named by a path relative to it: `notes/red.png`. A path uses `/`, has no `..`, is at most 200 characters and 8 levels deep, and is not a Windows reserved name. A symbolic link or a junction that leaves the folder is refused. | File | Rule | | --- | --- | | `skin.ts` | Required, a single script without `import`, at most 1 MiB. | | `.png` images | At most 4 MiB and 2048 px per side. | | `.ttf`, `.otf` fonts | At most 8 MiB each. | | `.wav`, `.ogg`, `.flac`, `.mp3` sounds | At most 1 MiB; only the first second is used. | | `preview.png` | Optional. The picture of the skin on the Skins page (the list falls back to `left.png`). | To share a skin as a `.zip` and the limits an archive is checked against, see the [skin package format](https://prism.am/dev/md/formats/skin-package.md). ## defineSkin {#define-skin} ```dts declare function defineSkin(input: SkinDefinition): SkinManifest; ``` Every field is checked when the script loads. An unknown field is refused (`unknown field …, expected one of …`). | Field | Rule | | --- | --- | | `id` | Required. 1 to 64 characters among `a-z 0-9 . - _`, starting and ending with a letter or digit. Keep it equal to the folder name. It must not be the id of a mod. | | `name` | Required. 1 to 64 characters. Shown on the Skins page. | | `version` | Required. A semantic version, `1.0.0`. | | `apiVersion` | Required. Must be the game's, `2`. | | `author` | Optional, 1 to 64 characters. | | `description` | Optional, at most 1024 characters. | | `homepage` | Optional. An `http://` or `https://` address, at most 256 characters. | | `fonts` | Optional. Fonts the skin bundles: name to `.ttf` or `.otf` path. See [fonts](#fonts). | | `uses` | Optional. The mods whose elements the skin places, like a mod's `uses`. | | `provides` | Optional. Elements other packages may configure, like a mod's `provides`. | | `permissions` | Optional. `["stage"]` for [native drawing](#stage). | | `images` | Optional. PNG files that handlers put on the playfield or the stage during the play, at most 64. See [images](#images). | | `setup` | Optional function, `setup(play: PlayContext)`. | `setup` receives the context of the launch. Name the parameter `play`, not `ctx`: `ctx` is the global that holds `ctx.on`. | `play.` | Content | | --- | --- | | `mode`, `layout` | The mode and the layout of the map (an entry of the mode catalogue). | | `layoutSkin` | How the layout looks, for example `4k`. | | `columns` | The number of lanes. | | `screenWidth`, `screenHeight` | The window in pixels. | | `song` | The map: title, artist, difficulty, `timing` (tempo points) and more. | | `judgements` | The judgement tiers of the play. | The script is loaded fresh at every launch: nothing carries over from one play to the next, and you can edit it between two plays without restarting the game. `playfield.set` and `lanes.set` work in `setup`; elsewhere they work only in handlers during a play, see [changing the playfield during a play](#during-play). ## The playfield values {#playfield} `playfield.set(spec)` merges `spec` into the description of the playfield: the fields you give replace those of earlier calls, the others stay. `lanes.set({ column, lane })` merges a lane description into lane `column` (from 0, at most 32 lanes). A value you never give keeps the engine's default look, so a skin with no `playfield.set` draws the historical playfield. Two rules explain most of the numbers: - Positions are fractions of the screen (`x` of its width, `y` of its height). Sizes and offsets are fractions of the screen **height**, so the playfield keeps its proportions at any resolution. - A note travels 0.8 screen heights during the scroll time the player chooses. The [field reference](https://prism.am/dev/md/reference/skin-fields.md) lists all 116 fields with kind, bounds and a note each. The defaults most skins start from: | Value | Default | | --- | --- | | `x`, `y`, `anchor` | `0.5`, `0.5`, `center` | | `laneWidth`, `laneGap`, `laneHeight` | `0.085`, `0.003`, `0.9` | | `receptorY` | `0.85` (notes scrolling down), `0.15` (up) | | `noteSize`, `receptorSize` | `0.0725 × 0.0725`, `0.0775 × 0.0775` | | `laneColor` | `#454d61` | | `backgroundTint` | `#818181` (the map background at 22 %) | Without values, the lanes take in turn the arrows `left`, `down`, `up`, `right` of the `default` skin, with its key, hold body and hold end images. Those key images are 198 × 566 px, so give a `receptorSize` 2.86 times taller than wide if you rely on them, as `content/skins/default/skin.ts` does. A few things the reference does not repeat: - **Hold ends.** `holdEnd` is written like a note: its tip, the bottom of the image, aims at the receptors when notes fall. The game flips it so it points away from the receptors, whatever the zoom and rotation. `holdMatchNoteWidth` makes the body as wide as the note and the end as wide as the body, so a bigger note grows them together. - **Visual offsets.** `noteOffsetY`, `holdEndOffset`, `receptorOffsetX/Y` and the other offsets move images along the scroll without touching judging, hold timing, score or replays. - **Lane cover, measure lines, beat lines and note snap colors** are native and off by default, including in the `default` skin. A skin turns them on with `laneCover: true`, `measureLines: true`, `noteSnapColors: true`; a map script can too, and the player in the editor. They are visual only. - **Missed holds** (`holdMissedStyle`) are dimmed, not hidden, unless you ask for `hide`. - **Hit light.** `hitLightOn` is `all` or `off`. There is no mode for long notes only. - **Key light, stage light, hit light, hold light** are four separate mechanisms with their own fields; the [reference](https://prism.am/dev/md/reference/skin-fields.md#group-lighting) lists them. - **Colors** are `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. A tint multiplies its image in the shader; a color without an image tints a white rectangle. ## The three layers {#layers} A value is resolved in three layers. The highest layer that gives the value wins, value by value: 1. the skin (`setup` of `skin.ts`, and its handlers), 2. the [map script](https://prism.am/dev/md/guides/map-scripts.md) of the map being played, if any, 3. the player's configuration for this skin (`skinConfig[skinId]`, set in the in-game skin editor). Inside one layer, a lane's value beats the playfield value: `lanes[column]`, then the playfield's, then the engine's default. The player's layer also beats a `playfield.update` in progress, live. The layers do not check the same bounds: | Value | Skin and map script | Player | | --- | --- | --- | | `x`, `y` | 0 to 1 | −1 to 2 | | `zoom` | 0 to 4 | 0.25 to 4 | | `rotation` (degrees, clockwise) | −3600 to 3600 | −180 to 180 | Other bounds are the same for all layers: `laneWidth` 0.005 to 0.5, `laneGap` 0 to 0.1, sizes 0 to 2, visual offsets −0.5 to 0.5, lane `offsetX/Y` −2 to 2, `transitionMs` 0 to 10000. A few fields are for scripts only and not in the player's editor: `anchor`, `width` (the total width, which wins over `laneWidth` of the same layer) and `lanes` itself. ## Images and frames {#images} An image is a `.png` file of the skin folder, named by its relative path. The name must end in `.png` and the content must really be a PNG: anything else is an error. - **Limits.** 4 MiB and 2048 px per side at most. Images are reduced to 640 px on their longest side and packed into one atlas of 2048 × 4096 px, with at most 256 images per layer. An image that does not fit is ignored and a white rectangle is drawn. No mipmaps: bilinear sampling is fine down to about half size. - **Filtering.** `textureFilter: "linear"` (default) keeps scaled sprites smooth; `"nearest"` keeps pixels sharp, for pixel art. - **Loaded before the play.** Every image is decoded at launch; nothing is decoded while playing. The images are those `setup` names in `playfield.set` and `lanes.set`, plus those `defineSkin({ images: [...] })` declares (64 at most). A handler that names any other image throws ``[...] were not loaded when the play started: name them in `setup` or declare them in `images` ``. - **Animations.** `hitLight` and `holdLight` take a pattern with the token `{n}`, replaced by 0, 1, 2… for each frame (`fx/spark-{n}.png`), and `hitLightFrames` / `holdLightFrames` give the count, 1 to 32. The default rate is 60 frames per second (`…Fps`, 1 to 240), in real time. A pattern needs `{n}` when it has more than one frame; a single frame needs no token. A missing frame is reported and the animation is shorter. - **Player images.** The player may import PNG, JPEG or WebP files (4 MiB, 2048 px, 64 per skin) and name them `player:` in the editor. Your skin never has to handle them. A complete skin with images: ```ts // Sparks: a skin with images. The notes are blue gems, every hit plays a four-frame ring // (`fx/spark-0.png` to `fx/spark-3.png`) on its lane in the color of the judgement, and the // notes turn gold during the first 25 combo of every 100. // // An image a handler puts on the playfield during the play must be loaded before it starts: // `images` declares `notes/gold.png`, which `setup` itself never names. const GOLD = "notes/gold.png"; const BLUE = "notes/note.png"; export default defineSkin({ id: "sparks", name: "Sparks", version: "1.0.0", apiVersion: 2, author: "Prism docs", description: "Blue gems and a ring of light on every hit.", images: [GOLD], setup(play: PlayContext) { const laneWidth = Math.min(0.09, 0.4 / play.columns); playfield.set({ laneWidth, laneGap: 0.002, noteSize: { width: laneWidth, height: laneWidth }, receptorSize: { width: laneWidth, height: laneWidth }, note: BLUE, laneColor: "#10182ac8", // `{n}` is replaced by 0, 1, 2, 3: one file per frame, 30 frames per second. No size is // given: the ring is twice the width of the lane and its height follows the image. hitLight: "fx/spark-{n}.png", hitLightFrames: 4, hitLightFps: 30, hitLightFollowJudgement: true, keyLightFadeMs: 60, textureFilter: "linear", }); let gold = false; ctx.on("game.judgement", (judgement: JudgementEvent) => { const now = judgement.combo >= 100 && judgement.combo % 100 < 25; if (now === gold) return; gold = now; playfield.update({ patch: { note: gold ? GOLD : BLUE } }); }); }, }); ``` `notes/gold.png` appears only in a handler, so `images` declares it. The ring frames are named in `setup`, so they need no declaration. ## Sounds {#sounds} `hitSound` names a sound file of the skin: `.wav`, `.ogg` (Vorbis), `.flac` or `.mp3`. It plays when the player presses the key of the lane, if Settings, Audio, key sounds is on (off by default). Set it for the whole playfield or per lane: ```ts fragment playfield.set({ hitSound: "sounds/tap.wav" }); lanes.set({ column: 2, lane: { hitSound: "sounds/kick.wav" } }); ``` The path follows the rules of images. A file over 1 MiB, unreadable or missing plays the game's sound instead and writes a line in the log. An unknown extension is reported at launch: `"" must be a .wav, .ogg, .flac or .mp3 sound`. Only the first second is used, ended by a short fade, decoded before the play. The sound is read once at launch: a `playfield.update` does not change it during the play. A skin without `hitSound` imposes none. ## Fonts {#fonts} `fonts` maps a name to a `.ttf` or `.otf` file of the folder: `fonts: { title: "fonts/title.ttf" }`. Names have 1 to 64 characters among letters, digits, space, `-`, `_` and `.`, at most 8 fonts, 8 MiB each: the game loads at most that, and a larger font, although the import accepts it, does not load. As with a mod, the font is published as the family `/`, and a font option of an element takes that full name (`font: "demo-fonts/cantarell"`); a bare name is read in the fonts of the mod that owns the element. The native playfield does not draw text: fonts are for the HUD. The example `content/skins/demo-fonts` uses Cantarell (SIL Open Font License 1.1), whose licence text is in a comment at the end of `skin.ts`. ## One skin for each key count {#key-counts} There are two things that go by this name. **Inside one skin**, read `play.columns` (4 to 9, and 10, 12, 14 or 16 for a double play) and give each layout its own values, as the `default` skin does: columns of 62 px at 4K and 58, 54, 50, 46 and 42 px for 5K to 9K on a virtual screen of 480, different key images for the odd layouts. In `ember`, the lane width is computed from `play.columns`. **Across skins**, the player may pick a skin for each key count: Skins page, Actions menu, *Skin per key count*, one card per layout of the game (4K to 16K). Each launch loads the skin assigned to its key count, and the global skin serves the counts with no choice. A skin that is no longer installed falls back to the first available one, with a warning. The choice is not exported with the settings. It is off in safe mode and when the game is started with `--skin`. The element options in Settings and the skin editor follow the global skin. ## The default skins {#default-skins} The game ships two skins, in `content/skins/`. They are plain folders: copy one under another name to start your own. | Skin | What it is | | --- | --- | | `default` ("Prism Default") | The default. The osu! skin "PRISM // arrow (cap ends)" by april, converted by hand for 4K to 9K: columns of 62 px at 4K and 58, 54, 50, 46, 42 px for 5K to 9K on a 480 px screen, dark columns `#07090f96`, arrows and lit keys, hold bodies and caps, stage light and hit and hold light animations (`fx/explosion-{n}.png`, `fx/holdlight-{n}.png`). About 518 KiB in 40 files. | | `default-circle` ("Default Circle") | The 4K layout of the osu! skin by tekkito2, extended to 5K to 9K: round notes (an outer circle on the edge columns, an inner one elsewhere), columns of 72 px (66 px at 8K, 58 px at 9K), the judgement line on, a lighter scratch column at 8K. 7 files, about 33 KiB. | Both turn on `holdMatchNoteWidth`, place the HUD with `ctx.element(…).configure({ … })`, and keep their HUD code in a separate section of `skin.ts`. The folder of a shipped skin stays under 900 KiB. ## The player's configuration and the skin editor {#player-config} Every skin has its own player configuration, `Settings.skinConfig[skinId]` (64 skins at most): a `playfield` part and the options of the HUD `elements` the skin places. It never edits the skin's files; it is a separate layer on top. The player reaches it from the Skins page: **Customize skin** on the card of the skin in use. The editor runs a frozen demo under the overlay; clicking the playfield, a lane, a hold end or a HUD element selects it and shows its values. The panel lists the catalogue of the [field reference](https://prism.am/dev/md/reference/skin-fields.md): a *Simple / Advanced* switch (simple lists the marked fields only), tabs, collapsible sections, a *Modified* filter and a search over the whole catalogue. Per lane, `offsetX` and `offsetY` place each lane freely. A customized skin shows a badge on the Skins page, and *Reset customizations* removes its configuration. The catalogue comes from the game, not from the skin: every skin, even a minimal one, gets the lane cover, measure lines and the other native groups, off by default. **Live preview.** The top bar of the editor has *Live preview*: a real map from the library, by default the selected one, plays in Auto behind the editor with the real clock, lights and HUD. It has no effect on score, replays, profile or settings. The sound is off by default and the map loops. A lab at the bottom offers an imperfect autobot (Human, Chaos) to see every judgement tier on your skin, slow motion, freezing on an event and a table of the windows. The protocol and its limits are not part of what a skin author needs. ## Changing the playfield during a play {#during-play} From a handler (`game.judgement`, `game.tick`, `game.beat`, `game.pause`…) a skin can change any field of the playfield, colors and images included: ```ts fragment ctx.on("game.judgement", (judgement: JudgementEvent) => { lanes.set({ column: judgement.column, lane: { receptorColor: judgement.tier.color }, transitionMs: 0 }); if (judgement.combo % 100 === 0) { playfield.update({ patch: { note: "notes/gold.png", laneWidth: 0.09 }, transitionMs: 300, easing: "easeOut" }); } }); ``` - `playfield.update({ patch, transitionMs?, easing? })`: `patch` is a partial `PlayfieldSpec` (`lanes` included). `lanes.set({ column, lane, transitionMs?, easing? })` does the same for one lane. - `transitionMs` is 0 to 10000 (absent or 0: at once). `easing` is `linear` (default), `easeIn`, `easeOut` or `easeInOut`. - Numbers and colors animate from the displayed value to the new one. Images, the anchor and the scroll direction change at once. Each value has its own transition: a change only interrupts the transitions of the values it changes. The transition follows the song clock, so a pause freezes it. - These calls only work in `setup` and, in a handler, between `game.songStart` and `game.songEnd`. Anywhere else they throw ``the playfield only changes while a chart plays: call it from a handler between `game.songStart` and `game.songEnd` ``. - Each call is checked (bounds, colors, paths, lane under 32) and throws in your script on a mistake. The number of lanes does not change, and judging is untouched: these changes are visual. - Changes of one step of the mod thread with the same transition are merged into one (the last values win); those with different transitions stay apart, in order, at most 8 per step. They go through a queue of 64 that the mod thread fills without ever waiting; when it is full they are kept for the next step. Light the lane, then bring it back in one handler: two calls with two transitions. - The `game.playfield()` entity of mods stays the layout of the launch. Because every handler runs on the mod thread with a budget (30 ms per call, see [budgets](https://prism.am/dev/md/help/limits.md)), start transitions on beats or judgements and let the renderer animate; do not move things frame by frame. ## Native drawing with stage {#stage} A skin that declares `permissions: ["stage"]` can also draw in the native renderer with `stage.*`: sprites, rectangles, text, particle emitters and triggers, in step with the notes. Without the permission every `stage.*` call throws. A sprite or an emitter can only name an image declared in `defineSkin({ images })`; those images are decoded with the playfield's, in the same atlas. Like the rest of the script, the skin's stage elements start from zero at every launch. The functions and their limits are in [native drawing](https://prism.am/dev/md/guides/stage-drawing.md). ## Loading without slowing the game {#loading} ```text map launch (main thread) └─ helper thread one queue of playfield changes per layer (skin, map script) prepare_play ──> mod thread: skin.ts loaded fresh, setup(play), then the map script, loaded fresh, setup(play) waits for the two PlayfieldSpec and the image lists (1 s at most) skin::prepare: validation, PNG decoding, one atlas └─ main thread: the prepared playfield, then the start render thread: one texture upload before the first frame; each frame: pending changes, transitions, drawing ``` The render thread never reads a file or decodes an image. A frame with no change and no transition reads one slot of a queue and allocates nothing. If the mod thread does not answer in 1 second, the play starts with the engine's default look. ## Errors you will see {#errors} Nothing invalid stops the play. Each problem is reported in the mods log during `setup`, as a banner at launch, and on the Skins page, where the skin in use lists the problems of its last launch. | What went wrong | What the game does | | --- | --- | | Number out of bounds in `setup`, `playfield.set` | The value is brought into the bounds: `laneWidth: 0.9 is outside [0.005, 0.5]; 0.5 is used`. Not finite: the default is used. | | Invalid color or path | The next value of the chain (lane, playfield, default) is used. | | Image missing, unreadable, not a PNG, over 4 MiB or over 2048 px | A white rectangle: `"" is 4096×4096 pixels; the limit is 2048×2048`. | | Too many lanes | `lanes: 40 lanes; the limit is 32`, the extra ones are ignored. | | More than 256 images used in a layer | `N images are used; the limit is 256, for the others a white rectangle is used`. | | `defineSkin` invalid, `skin.ts` throws, `setup` over budget | The play uses the engine's plain defaults, and the error is reported. | | The chosen skin folder is missing | The first available skin is played, and the loss is reported. | | Nothing from the mod thread in 1 s | The play starts with the engine's look. | In a handler during the play, the same mistakes are not corrected: the call throws, in your script, with these messages. | Message | Cause | | --- | --- | | `: is outside [min, max]`, ` is not a finite number` | A number out of bounds or not finite. | | `lane N does not exist: there are at most 32 lanes` | A `column` of 32 or more. | | `Frames: N is outside [1, 32]` | A frame count out of range. | | `"" needs the {n} token that each frame number replaces` | A multi-frame light pattern with no `{n}`. | | `"" must be a .png image` | An image that is not a `.png` path. | | `transitionMs: …` | A transition outside 0 to 10000. | | ``[...] were not loaded when the play started: name them in `setup` or declare them in `images` `` | An image the play did not load. | | `` `playfield.set` is only available to skins and map scripts `` | The call is made from a mod. | | `` `` 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}>([^<]*)`).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(/([\s\S]*?)<\/map>/g)].map((block) => ({ id: block[1], title: text(block[2], "title"), artist: text(block[2], "artist"), mapper: text(block[2], "mapper"), keys: Number(text(block[2], "keys")), mb: text(block[2], "mb"), })); /** What this mod carries from one call to the next (the game hands `state` back; it is JSON, 8 KiB at most). */ interface State { page?: number; detailOf?: string; } export default defineMod({ id: "example.download-bridge", name: "Example download bridge", version: "1.0.0", apiVersion: 2, author: "PVNG", description: "Adapts a fictional site (POST + XML, then a detail request) for the Download tab. Fictional hosts.", permissions: ["network"], setup() { downloads.registerBridge({ id: "maps", name: "Example maps", description: "A fictional site with a form search answered in XML.", site: "https://maps.example.org", hosts: ["maps.example.org", "files.example.org"], rateLimit: 30, // The player's token, kept by the game: sent in this header on downloads only, never given to the functions below. auth: { kind: "token", header: "Authorization", scope: "download" }, // First page: `page` is 1. Whatever `nextPage` a `results` step names comes back here. search(query, page, _state): BridgeStep { return { request: { url: "https://maps.example.org/cgi/find", method: "POST", form: { terms: query, page: String(page) }, expect: "xml" }, state: { page: Number(page) }, }; }, // The game calls this with the answer to the request of the previous step. onResponse(response, state): BridgeStep { const carried = (state ?? {}) as State; if (response.status !== 200) return { error: `the site answered ${response.status}` }; if (carried.detailOf !== undefined) { // The detail request answered with JSON: it names the file. const detail = JSON.parse(response.text) as { file?: string }; if (!detail.file) return { error: "this map has no file" }; return { download: { url: `https://files.example.org${detail.file}`, format: "osz" } }; } const found = rows(response.text); return { results: found.map((row) => ({ id: row.id, title: row.title, artist: row.artist, creator: row.mapper, keyCount: row.keys, size: `${row.mb} MB`, tags: ["example"], details: [{ label: "Site id", value: row.id }], // Each button comes back to `action` with its id. actions: [{ id: "download", label: "Download" }], })), nextPage: found.length >= 2 ? (carried.page ?? 1) + 1 : undefined, state: carried, }; }, // A button was pressed: ask for the detail page, then `onResponse` names the file. action(result, _actionId, _state): BridgeStep { return { request: { url: `https://maps.example.org/maps/${result.id}.json`, expect: "json" }, state: { detailOf: result.id } }; }, }); }, }); ``` ### Requests {#bridge-request} `request` is `{ url, method?, headers?, body? | form? | json?, expect? }`. | Field | Rule | |---|---| | `url` | `https` on a declared host, 2048 bytes at most. `{token}` may stand in the tail (never in the host). | | `method` | `GET` (the default) or `POST` | | `headers` | at most 12, each value 512 characters at most, only these names: `Accept`, `Accept-Language`, `Content-Type`, `Referer`, `Origin`, `X-Requested-With`, `X-API-Key`, `X-Auth-Token`, `Authorization`, `If-None-Match`. No `Host`, no `Cookie`. A `Referer` or `Origin` must also be on a declared host. | | `body`, `form`, `json` | at most **one** of them, **POST only**, 64 KiB: text, URL-encoded fields, or JSON. The game adds the `Content-Type`. | | `expect` | `json`, `text`, `xml` or `html`: only changes the `Accept` header the game sends | The answer reaches `onResponse` as `{ status, headers, text }`: the status, a few headers in lowercase (`content-type`, `content-length`, `retry-after`, `x-total-count`, `etag`, `last-modified`, `content-disposition`) and the body **as text**, 2 MiB at most. A bigger answer is an error, never a silent cut. XML and HTML arrive as text too: there is no DOM and no XML parser; use `JSON.parse`, regular expressions and string methods. A 4xx or 5xx status is handed to your script so it can decide; 429 (rate limited) and a 401 or 403 when a token is saved are translated by the game itself. ### Results {#bridge-results} `results` holds at most 100 cards per page. Rust bounds and cleans every text; the page draws all the cards the same way in the eight themes (labels, size, details, buttons), so you choose *what* is shown and never the markup. | Field | Rule | |---|---| | `id` | a string of 1 to 128 characters or an integer; required. A repeated id is shown once. | | `title`, `artist` | required (a card with no title is an error); cleaned of control characters | | `creator` | optional, 64 characters | | `coverUrl` | optional; on a declared host, else ignored without an error; fetched through the game's cover route | | `tags` | at most 8, 24 characters each | | `size` | shown as written, 24 characters, such as `12.4 MB` | | `keyCount` | 1 to 18, shown like a difficulty chip | | `details` | at most 8 lines `{ label, value }` (32 and 200 characters) | | `actions` | at most 4 buttons `{ id, label }` (id 1 to 32 of `a-z0-9-`, label 32 characters). With none, the card gets one plain download button, action `download`. | | `data` | up to 1024 characters the game hands back to `action` with the result, as `result.data`; use it for what the next call needs (a slug, a path) | The card the game keeps for `action` is the **validated** one, never what the script wrote, and at most 8 KiB of JSON. A press on a button calls `action(result, actionId, null)` at download time; it must end with a `download` step. ### Downloads {#bridge-download} `download` is `{ url, method?, headers?, body? | form? | json?, filename?, format }`, with the rules of a request. `format` is `zip`, `osz` or `qp` (all zip containers); `rar`, `7z` and single files are refused. `filename` is informative (128 characters at most): the game names the folder. The game downloads with its size cap, extracts safely, and requires at least one chart it can read. ### Limits of a bridge {#bridge-limits} | Limit | Value | |---|---| | requests per search or per action | 6 (`needed more than 6 requests`) | | time per search or per action, scripts included | 60 s (`took more than 60 s`) | | text of one answer | 2 MiB | | body of a request | 64 KiB | | JSON returned by one function | 256 KiB | | `state` | 8 KiB of JSON | | results per page | 100 | | headers per request | 12 | The requests of a bridge count in the source's rate (searches, steps and downloads). ### The token in a bridge {#bridge-token} With `auth` declared, the game injects the token itself: in the declared header (every request for `scope: "all"`, downloads only for `"download"`), and in place of `{token}` wherever a request names it: the URL's tail, a header, a body, a form or JSON field. `{token}` without `auth` is refused, and it is never accepted in the host name. The script never sees it: an answer that repeats it reaches `onResponse` with `[token]` in its place. There are no cookies and no OAuth. A 401 or 403 with a saved token tells the player to save a valid one. ### When a bridge is switched off {#bridge-off} - Your function **throws**, returns something JSON cannot write, or goes over the execution budget: the bridge is **switched off for the session**. Its source leaves the Download page, the mod's log says why, and the other mods and sources continue. - A step that breaks the schema (an unknown field, `format: "rar"`, an undeclared host, a forbidden header, two of `request` and `results`…) is an **error shown to the player**, not a switch-off: the declaration is wrong, not the run. ```text Example maps: needed more than 6 requests Example maps: the header "Cookie" is not allowed (allowed: accept, accept-language, content-type, referer, origin, x-requested-with, x-api-key, x-auth-token, authorization, if-none-match) Example maps: search: a step has exactly one of `request`, `results`, `download` and `error` Example maps: search: `state` is at most 8 KiB of JSON Example maps: returned 101 results, at most 100 a page ``` ## What neither form can do {#cannot} OAuth or form sign-in, cookies, writing network code in the script (never), archives the game cannot import (`rar`, `7z`, a loose file), packs with their content unfolded (a mod source lists *sets*: one zip, one folder) and native DOM or XML parsing. A declaration also cannot read JSON keys that contain a dot or a character outside `A-Za-z0-9_-`, nor serve as a mirror for anything but osu!. For anything beyond, the source belongs in `crates/downloader`. ## Pitfalls {#pitfalls} - Listing every host the site uses: the API, the file server and the cover CDN. A cover or file URL on an undeclared host is ignored or refused. - Using `example.org` in a mod you publish. It serves nothing. - Registering after `setup`: `downloads.register` and `downloads.registerBridge` are only available in the mod's `setup`. - Putting the query in `search.url`. Use `params`. - Reading XML with `JSON.parse`. XML and HTML are text. - Carrying more than 8 KiB in `state`. Put a small id in `state` or in the result's `data`, and fetch the rest again. ## Reference {#reference} - [`downloads.register`](https://prism.am/dev/md/reference/sdk/downloads.md#downloads-register) and [`downloads.registerBridge`](https://prism.am/dev/md/reference/sdk/downloads.md#downloads-registerbridge), with every type. - [Permissions and limits](https://prism.am/dev/md/help/limits.md), and the `network` permission in [Concepts](https://prism.am/dev/md/concepts.md). ===== Page: Editor mods Address: https://prism.am/dev/guides/editor-mod/ Derived from: apps/web/src/mapeditor/lib/mods/api.ts, apps/web/src/mapeditor/lib/mods/registry.svelte.ts, apps/web/src/mapeditor/lib/mods/load.ts, apps/web/src/mapeditor/lib/mods/pattern-engine.ts, apps/web/src/mapeditor/lib/mods/storage.svelte.ts, apps/web/src/mapeditor/lib/map/plugin-api.ts, content/mods/sdk/modding.d.ts, content/mods/editor-sections/main.ts, content/mods/editor-patterns/main.ts, content/mods/editor-snippets/main.ts, content/examples/mods/editor-stairs/main.ts, crates/modding/src/manifest.rs # Editor mods Add panels, commands, tools, note patterns and checks to the map editor with defineEditorMod, and know exactly what loads today and what the registry refuses. An **editor mod** adds to the map editor (`apps/web/src/mapeditor`) panels, commands, toolbar tools, note patterns and consistency checks. It is written in TypeScript against the same SDK file as game mods ([modding.d.ts](https://prism.am/dev/sdk/modding.d.ts)), but it is declared with `defineEditorMod` and it **never runs in the game**. ## What loads today {#state} Only the editor mods **shipped with the editor** are loaded: the folders `content/mods/editor-*` of the repository, bundled when the editor is built. Loading an editor mod from the player's mods folder, or from a `.pvmod` package, is **not implemented**. A panel also cannot be a free Svelte component: only the declarative `view` is open to everyone. So writing an editor mod today means one of two things: contributing a new `editor-` folder to the repository (it is picked up at build time), or using this page as the specification of the API. Everything below is how the registry behaves for the shipped mods now. ## The folder and the declaration {#folder} An editor mod is a folder `content/mods/editor-/` with a `main.ts`. The prefix `editor-` is reserved: the game host skips every folder named `editor-*`, in the shipped mods folder and in the player's, so the game never tries to run `defineEditorMod`. The smallest editor mod registers one panel. This is the shipped *Section editor*: its panel body is a first-party component, so the mod only declares it. ```ts /// // The section editor panel. The panel body is the first-party sections component, so this mod only // registers the panel; the editor keeps the sections through the map API. export default defineEditorMod({ id: "pvng.editor-sections", name: "Section editor", version: "1.0.0", apiVersion: 1, author: "PVNG", description: "The layers panel: named sections of the map and their time ranges.", permissions: ["map:read"], setup(editor) { editor.panel({ id: "sections", title: translate("editor.mod_sections_title"), icon: "layers", rail: "main", component: "sections", }); }, }); ``` `defineEditorMod` is an identity function in the editor: it only types the declaration. The registry then validates it. ## A complete example {#example} The example registers one of each of the five registries. It is type-checked, and its declarations pass the editor's real validators (`api.ts`). It is not in `content/mods`, so the editor does not load it: it is the model to copy into an `editor-` folder. ```ts /// // An editor mod: it adds to the map editor a pattern, a tool, a command, a check and a panel. It is written with `defineEditorMod` // (not `defineMod`) and never runs in the game, which skips every folder named `editor-*`. Declarations are made in `setup`, once. // Plain texts here: `translate` reads the editor's own catalogue, a mod has none. export default defineEditorMod({ id: "example.editor-stairs", name: "Stairs", version: "1.0.0", apiVersion: 1, author: "PVNG", description: "A stairs pattern, a tool that selects what is on screen, a command and a check.", // `map:write` is needed by every call that changes the map or the selection (`ctx.map.commands`). Reading, patterns and checks need none. permissions: ["map:read", "map:write"], setup(editor) { // A pattern only says which columns are pressed at each step of the grid. The editor places the notes and gives the pattern its // shared settings (measures, divisor, allowed columns, randomness and seed, long notes). `color` is required: `#rrggbb`. editor.pattern({ id: "stairs", title: "Stairs", color: "#2ec4b6", description: "One note per step, walking across the allowed columns.", params: [ { kind: "select", name: "way", label: "Direction", default: "up", options: [ { value: "up", label: "Left to right" }, { value: "down", label: "Right to left" }, ], }, { kind: "number", name: "repeat", label: "Steps per column", default: 1, min: 1, max: 4, step: 1 }, ], // Pure: the same input gives the same notes. Use `input.random()`, never `Math.random()`. steps: (input) => { const repeat = Number(input.values.repeat); return Array.from({ length: input.stepCount }, (_, step) => { if (input.randomness === "random") return [input.columns[Math.floor(input.random() * input.columns.length)]]; const at = Math.floor(step / repeat) % input.columns.length; return [input.columns[input.values.way === "down" ? input.columns.length - 1 - at : at]]; }); }, }); // A tool is a button of the toolbar's Tools group: it runs an action and does not change the active tool. editor.tool({ id: "select-visible", title: "Select the notes on screen", icon: "wrench", run: (ctx) => { const { visibleStartUs, visibleEndUs } = ctx.editor.view; ctx.map.commands.setSelection(ctx.editor.timing.notesIn(visibleStartUs, visibleEndUs).map((note) => note.id)); // Private data of the mod: JSON, 32 keys, 64 KiB a value, 256 KiB in all. ctx.storage.set("uses", (ctx.storage.get("uses") ?? 0) + 1); }, }); // A command is listed in the editor's command palette. editor.command({ id: "note-at-cursor", title: "Add a note in the first column at the cursor", run: async (ctx) => { // Times in `ctx.map.commands` are bigint microseconds; the grid line nearest the cursor comes from `timing.snap`. await ctx.map.commands.addNote(BigInt(Math.round(ctx.editor.timing.snap(ctx.editor.time.cursorUs))), 0); }, }); // A check: the Issues panel lists what it returns when the player runs the checks. editor.validation({ id: "dense-chords", title: "Chords of four notes or more", check: (ctx) => { const sizes = new Map(); for (const note of ctx.editor.notes) sizes.set(note.timeUs, (sizes.get(note.timeUs) ?? 0) + 1); const issues: EditorIssue[] = []; for (const [timeUs, size] of sizes) { if (size >= 4) issues.push({ severity: "info", message: `${size} notes at ${Number(timeUs) / 1000} ms` }); } return issues.slice(0, 20); }, }); // A panel is a declarative tree the editor draws: the mod styles nothing. A `view` that reads `ctx.editor` or `ctx.storage` is // built again when the value changes. editor.panel({ id: "stairs", title: "Stairs", icon: "wand", rail: "main", view: (ctx) => ({ kind: "section", title: "Stairs", hint: "Pick the Stairs pattern in the pattern generator.", children: [ { kind: "text", text: `${ctx.editor.selection.count} notes selected, the tool was used ${ctx.storage.get("uses") ?? 0} times.` }, { kind: "button", label: "Note at the cursor", onClick: () => void ctx.map.commands.addNote(BigInt(Math.round(ctx.editor.timing.snap(ctx.editor.time.cursorUs))), 0) }, ], }), }); }, }); ``` Plain texts are used here because `translate(key, values?)` only reads **the editor's own message catalogue**: a mod has no catalogue of its own, and its titles are translated when the mod loads, not live. ## The definition {#definition} | Field | Rule | |---|---| | `id` | `^[a-z0-9._-]{1,64}$`, unique among the loaded editor mods | | `name` | 1 to 80 characters | | `version` | `major.minor.patch`, three whole numbers | | `apiVersion` | `1`. Another value is refused. | | `author`, `description` | optional strings | | `loadOrder` | optional integer from 0 to 10 000, 1000 by default. Mods load in `loadOrder`, then by `id`. | | `permissions` | optional list of `"map:read"` and `"map:write"`, no repeat. `map:read` is the default. | | `setup(editor)` | required; makes the registrations with the `editor` object | `setup` runs once at load. A mod whose `setup` throws is **deactivated** with everything it registered, the error is logged and the editor keeps running. ## The five registries {#registries} `editor` has five methods: `panel`, `command`, `tool`, `pattern` and `validation`. Every item has an `id` and, except for the panel, the same id rule: `^[a-z0-9._-]{1,64}$`. A title is 1 to 120 characters. Ids are **unique per kind across all mods**, not just within your mod. ### Panels {#panels} A panel is a button in a rail and the panel it opens. | Field | Rule | |---|---| | `id` | `^[a-z0-9-]{1,32}$` | | `title` | 1 to 120 characters | | `icon` | one of `timer`, `layers`, `flag`, `settings`, `wand`, `bookmark`, `music`, `wrench`, `plus`, `trash`, `play` | | `rail` | `"main"` (left, with the other content panels) or `"bottom"` (the settings rail) | | `view` | `(ctx) => EditorViewNode`, a declarative tree the editor draws | | `component` | `"timing"`, `"sections"`, `"markers"`, `"settings"` or `"issues"`: an internal component. **Shipped mods only.** | Give **exactly one** of `view` and `component`. A third-party mod that names a `component` is refused. A `view` that reads `ctx.editor` or `ctx.storage` is built again when the value changes. A callback that throws, or a promise that rejects, becomes an error toast and never an uncaught error. The editor draws every control in a column of the same width, with the game's own components: a mod styles nothing. ### View nodes {#view-nodes} | `kind` | Fields | What it draws | |---|---|---| | `stack` | `children` | the children one after the other | | `section` | `title`, `hint?`, `children` | a titled group with the header and surface of the built-in panels; `hint` is one short sentence in a bubble | | `text` | `text` | a paragraph | | `button` | `label`, `onClick`, `disabled?` | a button | | `number` | `label`, `value`, `min?`, `max?`, `step?`, `onChange` | a number field | | `select` | `label`, `value`, `options: { value, label }[]`, `onChange` | a drop-down list | | `toggle` | `label`, `value`, `onChange` | a switch | | `input` | `label`, `placeholder?`, `maxLength?`, `submitLabel?`, `onSubmit` | a text field that keeps its own text; Enter or the button calls `onSubmit(text)`, then the field empties. Labels are unique in a panel. | | `list` | `empty`, `items` | rows, see below | | `patterns` | none | the pattern generator: every registered pattern, its settings and the button that writes the notes. At most one per panel. | A list item is `{ id, title, detail?, color?, preview?, onClick?, actions }`: `color` is a `#rrggbb` dot before the title, `preview` a miniature of a pattern `{ columns, length, notes: [{ at, column, length? }] }` (lanes across, time upward, in the unit of `length`), `onClick` is the click on the row, and `actions` are up to three buttons `{ label, icon, onClick, danger?, disabled? }`. ### Commands and tools {#commands-tools} - A **command** `{ id, title, run(ctx) }` is listed in the editor's command palette. - A **tool** `{ id, title, icon, run(ctx) }` is a button in the *Tools* group of the toolbar. It runs an action and does not change the active tool. `run` may be asynchronous. Both receive the mod's context, [`ctx`](#context). ### Patterns {#patterns} A pattern is a shape of notes the player can generate. Your mod only says **which columns are pressed at each step** of the grid; the editor places the notes, and gives every pattern the same settings: measures or a time range, the beat divisor, the allowed columns, the randomness and the seed, and the long notes (with the rules of Full long notes). A pattern never writes to the map itself, so it needs no permission. ```text steps(input) → number[][] // one list of columns per step, [] for a rest ``` | Field | Rule | |---|---| | `id`, `title` | as above | | `color` | **required**, `#rrggbb` (six hex digits): the badge of the pattern in the picker. A pattern without a valid colour is refused. | | `description` | optional, 1 to 120 characters, shown in a bubble | | `params` | optional, at most 8 settings of its own, after the shared ones | | `steps` | a function, see below | `steps` receives: | Field | Meaning | |---|---| | `stepCount` | how many steps to give | | `grid` | one entry per step: `{ timeUs, stepUs, measure, inMeasure, beat }`. `stepUs` differs between two measures of different tempos. | | `stepsPerBeat`, `stepsPerMeasure` | the grid's resolution | | `startUs`, `endUs` | the range, from the measure line of the cursor to the end of the last measure | | `bpm` | the tempo in force at the start of the range | | `columns` | the columns the player allows, ascending, never empty: use only these | | `keyCount` | the map's number of columns | | `editor` | the editor's state, read-only: a pattern may read the map to adapt | | `randomness` | `"fixed"` (the textbook shape), `"varied"` (the same shape, changed now and then) or `"random"` (columns drawn at each step) | | `random()` | seeded numbers in [0, 1): the same seed gives the same pattern. **Never use `Math.random()`.** | | `values` | the values of the pattern's own `params` | The engine keeps from your answer only integer columns that are allowed, with no repeat in a step, at most 8 per step; steps beyond `stepCount` are ignored, and a grid has at most 20 000 steps. Anything else is dropped. A function that does not return a list throws `A pattern must return one list of columns per step`. The seed is the one the player sets (0 draws a different one each time); the long notes the player asks for are added by the engine after your function. ### Pattern parameters {#pattern-params} Each parameter has a `name` (`^[a-z][a-zA-Z0-9]{0,31}$`, unique in the pattern), a `label` (1 to 120 characters) and a `kind`. | `kind` | Fields | Rule | |---|---|---| | `number` | `default`, `min`, `max`, `step?` | finite, `min <= max`, `default` inside the range, `step > 0` | | `select` | `default`, `options: { value, label }[]` | at least one option, no duplicate value, `default` is one of them | | `toggle` | `default` | a boolean | | `sequence` | `default`, `maxLength?` | a list of whole numbers from 1 to 99 separated by spaces (`"4 2 3 2 4"`), the player builds it by clicking, never empty, at most `maxLength` entries (1 to 32, 16 by default) | Before it calls `steps`, the editor checks the values against the declaration (type, bounds, a listed option, a well-formed sequence): a missing or unknown value is refused. In `steps` read them from `input.values`; a `number` is a number and a `sequence` is the text, which you split on spaces. ### Checks {#validations} A check `{ id, title, check(ctx) }` returns a list of `{ severity, message }` with `severity` one of `"info"`, `"warning"`, `"error"`. The *Issues* panel lists the result of every registered check when the player presses **Run checks**. A check that throws is reported with its error and does not stop the others; a result that is not a list of well-formed issues is an error too. No shipped mod registers a check yet: until one does, the panel says "No checks are registered. Editor mods add checks here." ## The context: `ctx` {#context} Every callback receives `{ map, editor, storage }`. ### `ctx.map` {#map-api} The map and the commands that edit it. | Part | What it has | |---|---| | `map` | `id` (`bigint` or `null`), `keyCount` | | `vectors` | `notes`, `timingPoints`, `sections`, `markers`, read-only | | `cursor` | `timeUs` | | `selection` | `noteIds` (a `ReadonlySet`), `count` | | `commands` | `addNote(timeUs, column)`, `addHold(timeUs, column, durationUs)`, `deleteRange(startUs, endUs)`, `seek(timeUs)`, `clearSelection()`, `setSelection(ids)`, `addToSelection(ids)`, `armPlacement(steps \| null)`, `placePattern(steps, timeUs)` | Times of notes (`MapNote.timeUs`, `durationUs`) and the arguments of `addNote`, `addHold` are `bigint` microseconds; `deleteRange`, `seek` and `placePattern` take `number` microseconds. `armPlacement` and `placePattern` take steps `{ beat, column, holdBeats? }` measured in beats from the start of the pattern, at most 256 notes; the tempo where they land sets their times. `armPlacement` shows the pattern under the pointer and the next click on the playfield places it as one undoable step (Shift: random lanes, Escape or a right click: drop it); `placePattern` places it at once. ### `ctx.editor`: the editor's live state {#editor-state} Read-only, always current, with no permission. A `view` that reads it is rebuilt when it changes. Times are microseconds. | Field | Content | |---|---| | `mapId`, `keyCount` | the open map and its number of columns | | `placing` | a pattern is armed: the next click on the playfield places it | | `notes` | every note, by time then column | | `timingPoints` | every timing point (tempo and scroll speed) | | `markers` | `all`, `activeId`, `loopEnabled`, `loopRange` | | `time` | `cursorUs` (the playhead while playing, else the cursor), `playing`, `durationUs`, `pointer` | | `time.pointer` | the mouse over the playfield: `timeUs`, `snappedUs` (on the grid in use), `column`; `null` elsewhere | | `view` | `tool`, `beatDivisor`, `snapToGrid`, `snapScroll`, `zoom`, `metronome`, `visibleStartUs`, `visibleEndUs` | | `selection` | `count`, `noteIds`, `notes` (resolved, by time), `startUs` and `endUs` (the span, holds included, `null` if empty), `columns` | | `timing` | `tempos`, `tempoAt(t)` (`bpm`, `beatUs`, `originUs`, `signature`), `snap(t, divisor?)`, `notesIn(start, end)` | ### `ctx.storage` {#storage} Private data of the mod: JSON values by key, with `get(key)`, `set(key, value)`, `remove(key)` and `keys()`. Each mod has its own space, kept in the editor page's own storage; values are read back as written (nothing is ever executed), and reading in a `view` makes the view follow it. The limits are **32 keys, 64 KiB a value and 256 KiB in all**; `set` throws past them (`storage: "x" is over 65536 bytes`, `storage: more than 32 keys`, `storage: over 262144 bytes in all`) and when the value is not JSON. ## Permissions {#permissions} | Permission | Effect | |---|---| | `map:read` (the default) | reading the map, the cursor, the selection and `ctx.editor`. Reads are not blocked for a mod that does not list it. | | `map:write` | in addition, every command of `ctx.map.commands`: adding, deleting and moving notes, timing points and sections, `seek`, the selection, `armPlacement` and `placePattern` | A mod without `map:write` still gets the commands, but each one rejects with `Plugin is missing the map:write permission`. Patterns, checks and `ctx.editor` need no permission. ## What the registry refuses {#registry-rules} The editor never trusts a value that comes from a mod. The first problem throws and the item (or the mod) is not registered: ```text Invalid mod id: My Mod Mod example.x has an invalid version Mod example.x targets editor API 2; host runs 1 Mod example.x loadOrder must be an integer 0-10000 Mod example.x repeats permission map:write Editor mod "example.x" is already loaded Invalid panel id: Stairs Panel stairs needs exactly one of view or component Panel stairs uses a first-party component but its mod is not first-party Panel stairs has an unknown icon: star Editor pattern id "stairs" is already registered by example.other Pattern stairs needs a colour like #4d8dff: it is how the pattern is told apart in the picker Pattern stairs params must be a list of at most 8 Pattern stairs repeats parameter way Parameter repeat default is out of range Parameter way default is not one of its options Parameter queue default must be 1 to 16 whole numbers from 1 to 99 separated by spaces ``` ## The shipped editor mods {#shipped} | Mod (`id`) | Folder | Panel | Rail | What it is | |---|---|---|---|---| | `pvng.editor-timing` | `editor-timing` | `timing` | main | `component: "timing"` | | `pvng.editor-sections` | `editor-sections` | `sections` | main | `component: "sections"` | | `pvng.editor-markers` | `editor-markers` | `markers` | main | `component: "markers"` | | `pvng.editor-patterns` | `editor-patterns` | `patterns` | main | a `{ kind: "patterns" }` view and eight patterns, no permission | | `pvng.editor-snippets` | `editor-snippets` | `snippets` | main | a `view` and `map:read`, `map:write` | The panels `notes`, `audio` and `waveform` are in the editor itself, with no mod. The settings rail (`settings`) and the *Issues* panel (`issues`) belong to the core mod `pvng.editor-core`. `editor-patterns` registers eight patterns, each with its colour: `stream`, `trill`, `jack`, `chordfill`, `jumpstream`, `handstream`, `quadstream` and `chordjack`. They show the three kinds of parameter in use: `stream` has a `select` and two `toggle`s, `trill` a `number`, `chordjack` a `sequence` (a list of chord sizes such as `4 3` repeated over the range) and a `select` for anchors. Their panel is just `view: () => ({ kind: "patterns" })`: it lists **every registered pattern**, whichever mod added it, so a pattern from your mod appears there without a panel of your own. `editor-snippets` places short patterns with `placePattern` on the grid line nearest the cursor (`ctx.editor.timing.snap`), saves the player's own from the selected notes (`ctx.editor.selection.notes`) in `ctx.storage` (24 at most) and shows them as a `list` with previews and actions. ## Pitfalls {#pitfalls} - **Not loaded from the player's folder.** Do not tell players to drop an editor mod in their mods folder: it will be ignored, as every `editor-*` folder is. - **`bigint` against `number`.** `ctx.editor.notes` and `ctx.map.vectors.notes` carry `bigint` times; `ctx.editor.time.cursorUs` is a `number`. Convert with `BigInt(Math.round(x))` and `Number(x)`. - **A command without `map:write`** rejects at run time, not at load time: declare the permission. - **`Math.random()` in a pattern.** It breaks the player's seed: use `input.random()`. - **A `view` with a side effect.** It is built again whenever what it reads changes: keep it a pure description and put actions in `onClick`. - **Two `input` nodes with the same label in a panel.** Labels are unique in a panel. - **An id used by another mod.** Pattern, command, tool, panel and check ids are unique across mods per kind: prefix yours (`example.stairs`) if collision is likely. ## Reference {#reference} - Every editor type, with the SDK's own comments: [Editor mods (reference)](https://prism.am/dev/md/reference/sdk/editor.md). - The game's own modding side: [Concepts](https://prism.am/dev/md/concepts.md) and [Your first mod](https://prism.am/dev/md/first-mod.md). ===== Page: The .pvmod package Address: https://prism.am/dev/formats/pvmod/ Derived from: crates/modding/src/package.rs, crates/skin/src/archive.rs, crates/modding/src/manifest.rs, services/api/src/catalog/archive.rs, services/api/src/catalog/validate.rs, crates/downloader/src/repository.rs, apps/web/src/locales/en.json # The .pvmod package The ZIP format that carries a mod between players, its entry file, allowed files, limits, install and replace rules, and the errors you can see. A `.pvmod` file is how a mod travels: one ZIP of the mod folder, named `-.pvmod`. Plain folders keep working for development; the package is only the exchange format. The game checks the whole archive before it writes anything, and a failed install leaves your mods folder as it was. ## What is in a package {#layout} A package holds the files of the mod folder, nothing else. The only declaration of a mod is `defineMod` in its entry file. JSON in a package is data the mod may import, never a manifest. ```text sparks-1.2.0.pvmod ├── main.ts entry file (or index.ts) ├── lib/shapes.ts ├── fonts/Display.ttf └── images/spark.png ``` The entry file is `main.ts`, or `index.ts` when there is no `main.ts`. It sits at the root of the ZIP. A ZIP whose files all live in one top folder (`sparks/main.ts`) is accepted too: that folder is stripped on install. | Allowed extension | Used for | |---|---| | `ts` | Sources (`.d.ts` counts as `.ts`) | | `ttf`, `otf` | Fonts (a mod font is at most 8 MiB) | | `png` | Images | | `json`, `md`, `txt` | Data and notes | Any other extension makes the whole package invalid. Folder entries are fine. The id declared by `defineMod` is 1 to 64 characters among `a-z`, `0-9`, `.`, `-`, `_`. It starts and ends with a letter or a digit and has no `..`. The version is a semantic version (`1.2.0`, a pre-release suffix is allowed). See [Concepts](https://prism.am/dev/md/concepts.md) for the manifest. ## Limits {#limits} These limits are checked before extraction and again while extracting. | Limit | Value | |---|---| | Package file | 64 MiB | | Entries (files and folders) | 1024 | | Files | 256 | | One file, uncompressed | 16 MiB | | All files, uncompressed | 64 MiB | Entries must have a safe relative path (no `..`, no absolute path). Symbolic links and encrypted entries are refused. Two entries whose names differ only by case are refused (`Foo.ts` and `foo.ts`), because Windows and macOS would merge them. Only the stored and deflate compression methods are read. The catalogue is stricter than the game: it caps a mod at 2 MiB and a skin at 8 MiB, and has its own file-type and count rules. Read [Catalogue](https://prism.am/dev/md/online/catalog.md) before publishing. The table of every limit in one place is in [Limits](https://prism.am/dev/md/help/limits.md). ## Export a mod {#export} On the **Mods** page, the **Export** action of an installed mod asks for a folder and writes `-.pvmod` there. The id and version come from the mod's `defineMod`. Export skips hidden entries (names that start with `.`) and `node_modules`. Every other file must be allowed: a `.psd` or a `.mp3` in the folder makes the export fail with the error described below, so move it out first. Symbolic links in the folder fail the export too. The file is written to a temporary name and renamed, so a failed export leaves no half file. ## Install a mod {#install} You can install a package three ways: the **Install…** button of the Mods page, dropping a `.pvmod` on the game window, or double-clicking it in Windows (see [Share strings and file associations](https://prism.am/dev/md/formats/share-strings.md#file-associations)). A mod that arrives by double-click is installed **disabled**: enable it from the Mods page after reading its permissions. Updating an installed mod keeps its enabled or disabled state. The game then: 1. Checks the whole ZIP (paths, links, extensions, sizes, counts, entry file). 2. Extracts it into a hidden staging folder of your mods folder. 3. Loads the mod once in a throwaway engine, under the mod budgets, to read its `defineMod`. 4. Swaps the folder into place as `/` with renames. The mod is installed under its **id**, not under the package's file name. ### Replace rules {#replace} An install replaces an installed mod with the same id, whatever its version. The game reports which case applied: | Case | Message shown | |---|---| | No folder with this id | `Installed {name} {version}.` | | Newer version | `Updated {name} from {from} to {version}.` | | Same version | `Reinstalled {name} {version}.` | | Older version | `Downgraded {name} from {from} to {version}.` | | Existing folder could not be read | `Replaced an unreadable mod folder with {name} {version}.` | Uninstalling a mod keeps its storage, so a reinstall finds its data again. The game's own mods (shipped next to `prism.exe`) are searched first; you cannot shadow one with a package. The running mod host does not see the change until it restarts. ### Errors {#errors} A refused package gives one of two message shapes: - `invalid mod package: ` — the archive is not acceptable. - `the mod does not load: ` — the archive is fine, but `defineMod` is missing or invalid, the API version does not match, or a script or font fails. The `` for an invalid package is one of: | Reason | Cause | |---|---| | `not a ZIP archive (…)` | The file is not a ZIP | | `the package weighs N bytes; the limit is M` | Over 64 MiB | | `the package has N entries; the limit is M` | Over 1024 entries | | `"X" is a symbolic link` | A link entry (also on export) | | `"X" is encrypted` | A password-protected entry | | `"X" appears twice` | Two entries with the same name, ignoring case | | `"X" weighs N bytes; the limit is M` | A file over 16 MiB | | `the files weigh more than N bytes` | Over 64 MiB unpacked | | `the package holds more than N files` | Over 256 files | | `"X" uses an unsupported compression (…)` | Not stored or deflate | | `"X" cannot be in a package: allowed files are .ts, .ttf, .otf, .png, .json, .md, .txt` | Disallowed extension | | `no main.ts or index.ts at the root of the package` | No entry file | | `unsafe entry: …` | A path that escapes the folder | | ``the game's own folder already holds the mod ``; uninstall or edit it instead`` | The id belongs to a mod shipped with the game | | ``the folder holds another mod (``); rename it first`` | A folder named like your id declares a different mod | For `the mod does not load`, the reason is the same text you see when a mod in a plain folder fails: see [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md). ## Pitfalls {#pitfalls} - Count your files: 256 is a hard cap in the game. The catalogue server counts up to 512, so a catalogue mod with 257 to 512 files passes the server and then fails the install. - The catalogue accepts fewer bytes than the game (2 MiB against 64 MiB). A mod with a large font installs from a file and is still refused by the catalogue. - Keep build output, screenshots and source art out of the folder: any file with an extension outside the list fails the export and the install. ===== Page: The skin package Address: https://prism.am/dev/formats/skin-package/ Derived from: crates/skin/src/package.rs, crates/skin/src/archive.rs, crates/skin/src/library.rs, services/api/src/catalog/archive.rs, services/api/src/catalog/validate.rs, crates/downloader/src/repository.rs, crates/skin_import/src/source.rs # The skin package The .zip that carries a skin, its entry file skin.ts, allowed files, limits, the import rule that never replaces, and how it differs from the catalogue and from .osk. A skin package is a ZIP of a skin folder, named `.zip`. It has no version field and no manifest: the skin is its `skin.ts`. See [Writing a skin](https://prism.am/dev/md/guides/skin.md) for what goes inside. ## What is in a package {#layout} ```text my-skin.zip ├── skin.ts entry file (required) ├── preview.png shown on the Skins page ├── fonts/Title.ttf ├── images/note.png └── sounds/kick.wav ``` The entry file is `skin.ts`, at the root of the ZIP or inside the one top folder that holds every file (that folder is stripped on import). | Allowed extension | Used for | |---|---| | `ts` | Sources | | `png` | Images (`preview.png` is the picture of the Skins page) | | `ttf`, `otf` | Fonts | | `wav`, `ogg`, `flac`, `mp3` | Key sounds | Any other extension makes the package invalid. ## Limits {#limits} | Limit | Value | |---|---| | Package file | 64 MiB | | Entries (files and folders) | 1024 | | Files | 512 | | One file, uncompressed | 32 MiB | | All files, uncompressed | 64 MiB | The archive rules are the same as for [mod packages](https://prism.am/dev/md/formats/pvmod.md#limits): safe relative paths only, no symbolic links, no encrypted entries, no two names that differ only by case, stored or deflate compression only. All limits are in [Limits](https://prism.am/dev/md/help/limits.md). ## Export and import {#export-import} On the **Skins** page, **Export** writes `.zip` into a folder you choose and replaces a file of that name if there is one. Hidden files (names that start with `.`) are left out. Any other file must have an allowed extension, and a symbolic link fails the export. **Import…** reads a package and installs it as a new folder of your skins folder. An import **never replaces** an existing skin. The folder name is the ZIP's top folder name when it has one, else the file name without `.zip`. Characters a file name cannot hold are replaced by `-`, leading and trailing dots and spaces are dropped, the name is cut to leave room for a suffix, and a name that is still not valid becomes `skin`. If that folder already exists (in your folder or in the skins shipped with the game), the game appends `-2`, `-3`… until it is free. The new skin then appears in the list; you choose it as usual. Like a mod, the archive is checked in full before anything is written, extracted into a hidden staging folder, then renamed into place, so a failed import leaves your skins unchanged. ### Errors {#errors} Every refusal starts with `invalid skin package:`. The reasons are the archive messages of the [mod package table](https://prism.am/dev/md/formats/pvmod.md#errors) with one difference: the allowed-files message names a skin package and the skin list. ```text invalid skin package: "sounds/boom.aiff" cannot be in a skin package: allowed files are .ts, .png, .ttf, .otf, .wav, .ogg, .flac, .mp3 invalid skin package: no skin.ts at the root of the package invalid skin package: the package has 1500 entries; the limit is 1024 ``` ## The catalogue allows less {#catalogue} A skin you export with key sounds imports fine, but the catalogue server accepts only `ts png ttf otf` and a package of at most 8 MiB. Remove the `wav`, `ogg`, `flac` and `mp3` files before publishing. A person may publish at most 2 distinct skin ids. See [Catalogue](https://prism.am/dev/md/online/catalog.md). ## Importing an osu! skin {#osk} An `.osk` is an osu! skin, a different ZIP with its own limits. The converter reads it and builds a Prism skin from it; it never writes a `.osk`. The limits and the conversion are in [Importing an osu! skin](https://prism.am/dev/md/guides/skin-import.md). ## Pitfalls {#pitfalls} - Two ZIPs of the same skin never overwrite each other: import twice and you get two folders. Delete the old one from the Skins page. - A package with `skin.ts` one level too deep (two nested folders) fails with `no skin.ts at the root of the package`. - A skin id is a folder name: it cannot start with `.` and must be a valid file name. ===== Page: The .pvreplay file Address: https://prism.am/dev/formats/pvreplay/ Derived from: crates/replay/src/formats/replay_file.rs, crates/replay/src/formats/share.rs, crates/replay/src/formats/replay.rs, crates/core/src/chart_identity.rs, crates/core/src/rate.rs, crates/note_hash/src/lib.rs # The .pvreplay file The binary container of a recorded play: magic, version, zstd frame, rkyv archive, limits, field order, metadata JSON, how chart_hash is computed, and the errors. A `.pvreplay` stores the physical inputs of one play and enough information to find the exact chart it was played on. Prism replays it by re-judging the inputs, so the file carries no scores. The container is binary and strict: nothing is half-read. ## Container layout {#container} | Bytes | Content | |---|---| | 0 to 3 | Magic `PVRZ` (`50 56 52 5A`) | | 4 | Format version, one byte. This build writes and reads `1`. Version `0` is damaged; a higher one is refused as newer | | 5 to end | One zstd frame (level 9 when written) holding an rkyv archive | The archive is validated with `bytecheck` before any field is read. The game also requires the decompressed archive to fit its limit, so a small file cannot expand without bound. ## Limits {#limits} | Limit | Value | |---|---| | File size (compressed) | 8 MiB | | Decompressed archive | 32 MiB | | Inputs | 2,000,000 | | Pause marks | 1024 | | Metadata JSON | 1 MiB | | Input time | within 24 hours of the song's zero | | Columns | 255 at most; every input names a column of the chart | | Playback rate | 0.5 to 2 | | Texts of the chart identity (title, artist, difficulty, creator) | 256 characters, no control characters | | Player name, extension keys | 64 characters | | Extensions | 32 | | Keys of the chart | 1 to 64 | ## The archive {#archive} The archive holds these fields, in this order. | Field | Type | Meaning | |---|---|---| | `chart_hash` | 32 bytes | [Chart hash](https://prism.am/dev/md/formats/rox-and-hashes.md#chart-hash) of the chart as it was played | | `note_hash` | 32 bytes | [Note hash](https://prism.am/dev/md/formats/rox-and-hashes.md#note-hash), the key of the online boards | | `playback_rate` | f64 | The rate of the play, 0.5 to 2 | | `pauses` | optional list | `None` means not recorded (an old recording), never "no pause". `Some([])` means the play had no pause. Each mark has `at_us`, `duration_us` (`-1` when the length was not recorded) and `focus` (a pause caused by a lost window focus) | | `inputs` | list | Delta events: microseconds since the previous event, the column (one byte), and whether the key went down. The first delta is the signed time in the song | | `meta` | JSON text | A JSON object, see below | Hashes are 64 lowercase hexadecimal characters in text, 32 bytes in the file. ### The metadata {#meta} `meta` is a JSON object. Unknown fields are ignored, so a later version can add some. | Field | Type | Meaning | |---|---|---| | `chart` | object | `title`, `artist`, `difficulty`, `creator`, `keys`: human-readable fallbacks for the chart | | `rules` | string | Ruleset of the recording: 1 to 64 characters among letters, digits, `.`, `_`, `-` | | `playerName` | string, optional | Absent when the recording did not know who played; never invented | | `chartMods` | object, optional | The chart modifiers of the play (mirror, random with its seed, long notes). Absent for a play on the map as it is | | `judgement` | object, optional | The judgement the play was recorded with. It is metadata of the original result and never ranks | | `scrollTimeMs` | number, optional | The scroll time, above 0 and at most 60000 | | `playedAtMs` | integer, optional | When the play was made, in Unix milliseconds, when the file knows it. A receiver that ranks plays reads it as a claim | | `extensions` | object, optional | Optional data a later version may define | ```json { "chart": { "title": "Example Song", "artist": "Example Artist", "difficulty": "Hard", "creator": "mapper", "keys": 4 }, "rules": "prism", "playerName": "alice", "scrollTimeMs": 520.0, "playedAtMs": 1760000000000 } ``` ## Reading a replay {#identity} The `chart_hash` pins the exact chart, notes and timing, to the microsecond. The receiver rebuilds the chart it finds under that hash (with `chartMods` applied) and judges the inputs on it. If the chart is missing, the game says so; it does not guess. The game imports a `.pvreplay` by the replay import button, by dropping it on the window, or by double-clicking it ([file associations](https://prism.am/dev/md/formats/share-strings.md#file-associations)). Opening a replay never starts a play. The game server judges a play on the exact version of the chart the player used, named by this hash, and keeps the file it stored. See [Rox files and hashes](https://prism.am/dev/md/formats/rox-and-hashes.md#which-api) for which identity each API takes. ## How chart_hash is computed {#chart-hash} The hash is BLAKE3 in key-derivation mode with the context string `pvng chart content v1` (hash version `1`). It is fed, in this order: 1. The key count, one byte. 2. The number of notes, as a little-endian `u64`. 3. Every note, sorted by `(time_us, column, kind, duration_us)`: time as a little-endian `i64`, then the column byte and the kind byte, then the duration as a little-endian `i64`. The kind is `0` for a tap, `1` for a hold, `2` for a burst and `3` for a mine. The duration is `0` for a tap and a mine. 4. The number of timing points, as a little-endian `u64`. 5. Every timing point, sorted by `(time_us, kind, value bits, signature)`: time, then a byte `0` (BPM) or `1` (scroll velocity) and the signature byte (`0` for a scroll velocity), then the `f32` bits of the BPM or the scroll speed as little-endian `u32`. Times are exact microseconds and no global offset is removed. Mines, bursts and timing points count. Metadata, audio and hitsounds do not. A stored hash of another hash version is recomputed rather than trusted. ## Errors {#errors} These are the messages when you import a file. | Message | Cause | |---|---| | `The replay file is too large (N bytes, at most 8388608)` | Over 8 MiB | | `The file is not a Prism replay` | The first four bytes are not `PVRZ` | | `The replay was made by a newer version of the game (format version N, this build reads up to 1)` | Version byte above 1 | | `Invalid replay file: ` | Damaged or invalid content | The reason after `Invalid replay file:` is one of the following: | Reason | Cause | |---|---| | `the replay file is damaged: the compressed frame: …` | The zstd frame is broken, or inflates past 32 MiB | | `the replay file is damaged: the archive: …` | The archive fails validation | | `the replay file is damaged: the metadata is not an object` | `meta` is not a JSON object | | `the replay file is damaged: too many pauses` | More than 1024 pause marks | | `the chart hash is not 64 lowercase hexadecimal digits` | Bad chart hash in `chart` | | `the note hash is not 64 lowercase hexadecimal digits` | Bad note hash | | `N keys is not a chart size` | `keys` outside 1 to 64 | | `the chart title is too long or has control characters` | Same for `artist`, `difficulty`, `creator` | | `the player name is empty, too long or has control characters` | Bad `playerName` | | `the rules name is not a plain identifier` | Bad `rules` | | `the scroll time is out of range` | `scrollTimeMs` outside 0 to 60000 | | `too many extensions, or an extension with an invalid name` | More than 32, or a key over 64 characters | When the game reads the inputs against the chart, an input beyond 24 hours from the song's zero is refused with `Replay input N is outside the song's time range`. The lower-level messages `this is not a Prism replay file`, `the replay file is too large` and `this replay was saved by a newer version of the game (format N)` come from the container reader and appear in logs. ## Pitfalls {#pitfalls} - The file holds no score. Two machines judge the same inputs the same way only if they have the same chart, hence the exact `chart_hash`. - `note_hash` is not `chart_hash`. The note hash ignores a global offset and timing; the chart hash does not. A map that exists under two offsets has one note hash and two chart hashes. - Do not edit a replay with a JSON tool. It is a binary archive, and the sizes are checked. ===== Page: The .pvplaylist file and its share code Address: https://prism.am/dev/formats/pvplaylist/ Derived from: crates/core/src/playlist_share.rs, crates/core/src/playlist.rs, crates/core/src/chart_identity.rs, crates/core/src/rate.rs, services/api/src/catalog/playlist.rs # The .pvplaylist file and its share code The JSON schema of a shared playlist (pvng-playlist v1), the rates extension, limits, errors, and the one-line share code. A `.pvplaylist` is a JSON file that names an ordered list of maps by their chart hash. The same content travels as a text share code. It holds identities only, no chart and no audio. Importing a playlist creates it, adds the maps you own and reports how many are missing; it never starts a play. ## The file {#file} The file is UTF-8 JSON. Keys are camelCase. Unknown top-level fields are ignored. | Field | Type | Rule | |---|---|---| | `format` | string | Exactly `"pvng-playlist"` | | `version` | integer | `1`. Zero or missing is invalid; above `1` is refused as newer | | `name` | string | 1 to 64 characters, no control characters, no leading or trailing space | | `entries` | array | The maps in playlist order. At most 200 | | `extensions` | object, optional | Optional data. At most 32 keys, each at most 64 characters | Each entry is a chart identity: | Field | Type | Rule | |---|---|---| | `hash` | string | The [chart hash](https://prism.am/dev/md/formats/rox-and-hashes.md#chart-hash): 64 lowercase hexadecimal characters | | `title`, `artist`, `difficulty`, `creator` | string | Each at most 256 characters, no control characters. They are fallbacks for display when the map is missing | | `keys` | integer | 1 to 64 | Maps are matched by `hash`. The other fields only name a map you do not have. ```json { "format": "pvng-playlist", "version": 1, "name": "Warm-up", "entries": [ { "hash": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "title": "Example Song", "artist": "Example Artist", "difficulty": "Easy", "creator": "mapper", "keys": 4 }, { "hash": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210", "title": "Another Song", "artist": "Another Artist", "difficulty": "Hard", "creator": "mapper", "keys": 7 } ], "extensions": { "rates": [1.0, 1.25] } } ``` ### The rates extension {#rates} `extensions.rates` gives each map its playback rate. It is an array of numbers, one per entry, in order, each from 0.5 to 2. The game leaves it out when every map plays at 1. A reader that does not know the extension plays every map at 1. When the key is present and the array does not have exactly one valid rate per map, the whole file is invalid. ## Limits {#limits} | Limit | Value | |---|---| | File | 1 MiB, checked before parsing | | Maps | 200 | | Name | 64 characters | | Extensions | 32, keys of at most 64 characters | | Texts of an entry | 256 characters | | Share code | 512 Ki characters (524288) | The catalogue accepts a `.pvplaylist` of at most 1 MiB, runs the same validation on the server, and lists it as a third kind next to mods and skins. See [Catalogue](https://prism.am/dev/md/online/catalog.md). ## The share code {#share-code} A share code is the file as one line of text, for a message: ```text pvng-playlist-1:. ``` - `pvng-playlist-1:` is the prefix; the `1` is the code version. A code of another version is refused by its prefix. - `` is the file's bytes compressed with zstd (level 19), then encoded in base64url without padding. - `` is the CRC-32 of the uncompressed file bytes, as 8 lowercase hexadecimal digits. When a code is pasted, whitespace is ignored. A code longer than 524288 characters is refused before it is decoded. The decoded bytes then go through the same validation as a file. ## Errors {#errors} For a file: | Message | Cause | |---|---| | `The playlist file is too large (N bytes, at most 1048576)` | Over 1 MiB | | `The file is not a playlist: ` | Not JSON | | `The file is not a Prism playlist (format is not "pvng-playlist")` | Wrong `format`, or not an object | | `The playlist was made by a newer version of the game (format version N, this build reads up to 1)` | `version` above 1 | | `Invalid playlist file: missing or invalid format version` | `version` absent or `0` | | `Invalid playlist file: the playlist name needs 1 to 64 characters, without control characters or surrounding spaces` | Bad `name` | | `Invalid playlist file: a playlist holds at most 200 maps, this one has N` | Too many entries | | `Invalid playlist file: map K: ` | Entry K (counted from 1) is invalid. The reason is `the chart hash is not 64 lowercase hexadecimal digits`, `the chart title is too long or has control characters` (or `artist`, `difficulty`, `creator`), or `N keys is not a chart size` | | `Invalid playlist file: too many extensions, or an extension with an invalid name` | More than 32 extensions, or a bad key | | `Invalid playlist file: the "rates" extension needs one rate between 0.5 and 2 for each of the N maps` | Bad `rates` | For a code: | Message | Cause | |---|---| | `This is not a Prism playlist code (it starts with "pvng-playlist-1:")` | Wrong prefix | | `The playlist code is too long (N characters, at most 524288)` | Too long | | `The playlist code is damaged: copy it again, whole` | Bad base64, bad zstd frame, or a CRC mismatch | | `The playlist is too large to share as a code` | Writing side: the code would exceed the limit | If a file or a code is valid, the game reports how many maps were added and how many are missing. ## Pitfalls {#pitfalls} - A hash is the chart hash, not the note hash. A playlist from another player finds your map only if your copy has the same notes and timing. - Edit the JSON by hand only if you keep `entries` and `rates` the same length. The error names the count it wanted. - A playlist file you send by chat is easier as a code, but a very long playlist can exceed the code limit while its file still fits. - Marathons are another format: see [The .pvmarathon file](https://prism.am/dev/md/formats/pvmarathon.md). ===== Page: The .pvmarathon file Address: https://prism.am/dev/formats/pvmarathon/ Derived from: crates/core/src/marathon.rs, crates/core/src/playlist.rs, crates/core/src/rate.rs # The .pvmarathon file The JSON recipe of a marathon (pvng-marathon v1), its fields, limits, the constants that shape the composed chart, and the errors. A marathon is a map composed on demand from several maps. The `.pvmarathon` file is the recipe: it lists the maps in order with their hashes and rates, and nothing else. No chart or audio file is generated. Prism lays the maps end to end on one clock, so one play judges the whole run, with one combo and one accuracy. A `.pvmarathon` is not opened by double-click. The library scan reads the recipes in your library, and the marathon then behaves like a map. ## The file {#file} The file is plain JSON. Keys are camelCase. Unknown fields are ignored. | Field | Type | Rule | |---|---|---| | `format` | string | Exactly `"pvng-marathon"` | | `version` | integer | `1`. A higher version is refused rather than half read | | `title` | string | Name of the marathon | | `artist` | string | Always `"Marathon"` | | `creator` | string, optional | Who wrote the recipe. At most 64 characters, no control characters, trimmed. Absent when there was no name; never made up. It is never part of the marathon's identity | | `maps` | array | 1 to 200 entries, in play order | Each entry of `maps`: | Field | Type | Rule | |---|---|---| | `chartHash` | string | [Chart hash](https://prism.am/dev/md/formats/rox-and-hashes.md#chart-hash) of the map as the game plays it, 64 lowercase hexadecimal characters | | `noteHash` | string | [Note hash](https://prism.am/dev/md/formats/rox-and-hashes.md#note-hash) of the same chart, 64 lowercase hexadecimal characters | | `rate` | number | The rate this map is played at in the marathon, 0.5 to 2 | | `title` | string, optional | A hint for naming the map. Default empty | | `path` | string, optional | Where the map was when the recipe was written. It is tried first, then the library is searched by hash | | `variant` | integer | Which chart of the file at `path` (a file can hold several). Default `0` | A map is named by its hashes. `path` and `title` are only hints: a file found at `path` must still match both hashes, or the game says `its notes are not the ones the marathon was made with`. ```json { "format": "pvng-marathon", "version": 1, "title": "Endurance", "artist": "Marathon", "creator": "alice", "maps": [ { "chartHash": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "noteHash": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210", "rate": 1.0, "title": "Example Song", "variant": 0 }, { "chartHash": "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff", "noteHash": "ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100", "rate": 1.2, "title": "Another Song", "path": "Songs/another/another.osu", "variant": 0 } ] } ``` ## Limits {#limits} | Limit | Value | |---|---| | File | 256 KiB | | Maps | 200 (the playlist limit) | | Rate of a map | 0.5 to 2 | | Creator | 64 characters | All maps of a marathon must have the same number of keys, and every map must have notes. ## How maps are laid out {#layout} Each map gets a slot: a lead-in, the map from its first note to its last, then a tail. These constants are part of the marathon's note hash, since they move the composed notes. Changing one changes the hash of every marathon. | Constant | Value | Meaning | |---|---|---| | `LEAD_US` | 2.5 s | The longest lead-in. A map whose audio has more than this before its first note is cut to it | | `MIN_LEAD_US` | 1.5 s | The shortest lead-in. A map whose audio starts later is padded with silence | | `TAIL_US` | 1 s | Time kept after the last note before the next slot | The music ramps up into each map (a raised cosine ending on the first note). Each map plays its own audio file at its own rate; each chart is prepared for its own rate first, and the composed chart is played at rate 1. A composed marathon is cached for 10 seconds. The composed chart is read like any other chart: the scan gives it its own chart hash and note hash, and a play records an ordinary [replay](https://prism.am/dev/md/formats/pvreplay.md). ## Errors {#errors} | Message | Cause | |---|---| | `A marathon file is at most 256 KiB` | File too large | | `Not a marathon file` | Not JSON, or `format` is not `pvng-marathon` | | `A marathon file of version N needs a newer Prism` | `version` is 0 or above 1 | | `A marathon holds 1 to 200 maps` | Empty list or too many | | `A marathon map is named by its hashes` | A hash is not 64 lowercase hexadecimal characters | | `A marathon needs at least one map` | Composing an empty list | | `A marathon needs maps with the same number of keys` | Mixed key counts | | `A marathon cannot hold a map without notes` | A map with no note | | `Marathon map "": its notes are not the ones the marathon was made with` | The chart found does not match `noteHash` | A rate outside 0.5 to 2 is refused with the message of the rate check. When a map cannot be found, the reason ends in one of: `it is missing or has changed`, `its audio file is missing`, `its audio is not rendered yet (Settings, Audio: the keysounded charts are prepared in the background)`, or `it has no audio file of its own and the rendering of chart audio is off (Settings, Audio)`. ## Pitfalls {#pitfalls} - Both hashes are required, and both must be right. Editing a recipe by hand to point to another difficulty fails the check. - Playing a map at another rate in a marathon gives another marathon: the rate is part of the recipe. - Changing `creator` does not change the marathon: its folder and its identity ignore it. ===== Page: Share strings, config files and file associations Address: https://prism.am/dev/formats/share-strings/ Derived from: apps/desktop/src/app/settings_transfer.rs, apps/desktop/src/app/open_with.rs, apps/desktop/src/app/map_link.rs, apps/web/src/lib/judgement.ts, apps/web/src/lib/control-share.ts, deploy/installer/prism.iss # Share strings, config files and file associations The settings and skin-config export files, the judgement and controls share strings, the prism://map link, and the seven file types a double-click opens. Prism shares configuration as small files or one-line strings. Each has a `format` or a prefix, a version, size limits and a validator that refuses what it does not understand. Nothing is applied before you review it. ## Settings file {#settings} `.pvsettings.json` carries your settings. The game exports an allow-list of keys (audio, display, scroll speed, judgement, offsets and similar). It never exports paths, credentials, your player name, the skin choice, the list of disabled mods or the machine-specific values. Key bindings (`controlProfiles`, `controlProfileActive`) are exported only when you ask. An import is shown as a review (`current → new`, with what was ignored and why) before you choose what to apply. | Field | Type | Rule | |---|---|---| | `format` | string | Exactly `"pvng-settings"` | | `version` | integer | `1`; above is refused as newer; missing or `0` is invalid | | `settings` | object | At most 128 keys | ```json { "format": "pvng-settings", "version": 1, "settings": { "showFps": true, "vsync": true } } ``` A key the game does not know is ignored as unknown. A key that stays on its machine (a path, your name, installed content) is ignored as private. A value of the wrong type is ignored as invalid. Each is listed in the review. ## Skin configuration file {#skin-config} `.pvskin-config.json` carries the configuration of one skin: the `playfield` and `elements` values you changed, and nothing from the player's own images. | Field | Type | Rule | |---|---|---| | `format` | string | Exactly `"pvng-skin-config"` | | `version` | integer | `1` | | `skin` | string | The id of the skin it was exported from. Only a valid skin id is kept | | `config` | object | Only `playfield` and `elements` are read. At most 4096 leaf values | ```json { "format": "pvng-skin-config", "version": 1, "skin": "my-skin", "config": { "playfield": { "zoom": 1.2, "receptor": "fx/r.png", "lanes": { "1": { "noteColor": "#ff0000" } } }, "elements": { "pvng.combo/combo": { "size": 40 } } } } ``` Every value is validated with the rules the skin configuration loads with. See [Skin fields](https://prism.am/dev/md/reference/skin-fields.md). ### Import limits and errors {#config-limits} Both files share the same reader. | Limit | Value | |---|---| | File | 512 KiB | | JSON nesting | 24 levels | | Settings keys | 128 | | Skin configuration leaves | 4096 | | Message | Cause | |---|---| | `The file is larger than 512 KB` | Over the size limit | | `The file nests deeper than 24 levels` | Over the depth limit | | `The file is not valid JSON: …` | Not JSON | | `The file is not a Prism configuration` | Not a JSON object | | `The file is not a Prism settings file` | Wrong `format` on a settings import | | `The file is not a Prism skin configuration file` | Wrong `format` on a skin import | | `The file was written by a newer Prism (format version N)` | `version` above 1 | | `The file has no valid format version` | `version` missing or `0` | | `The file holds no settings` | No `settings` object | | `The file holds no skin configuration` | No `config` object | | `The file names more than 128 settings` | Too many keys | | `The file names more than 4096 values` | Too many leaves | ## Judgement preset code {#judgement} A custom judgement preset (the windows, names, colours and weights of the tiers) shares as one line: ```text pvng-judgement-1:<base64url> ``` The body is the preset's JSON, UTF-8, in base64url without padding. There is no checksum. The game also accepts the raw JSON text. The preset is validated on import and the whole preset is refused on the first problem. The preset's fields are exact: unknown fields are rejected. ```json { "name": "Prism", "tiers": [ { "name": "Marvelous", "earlyMs": 16, "lateMs": 16, "color": "#00ffff", "weight": 6, "breaksCombo": false }, { "name": "Perfect", "earlyMs": 50, "lateMs": 50, "color": "#ffff00", "weight": 6, "breaksCombo": false }, { "name": "Great", "earlyMs": 65, "lateMs": 65, "color": "#00ff00", "weight": 4, "breaksCombo": false }, { "name": "Good", "earlyMs": 100, "lateMs": 100, "color": "#4fc3f7", "weight": 2, "breaksCombo": false }, { "name": "Bad", "earlyMs": 150, "lateMs": 150, "color": "#ff69b5", "weight": 1, "breaksCombo": false } ], "miss": { "name": "Miss", "color": "#ff0000", "weight": 0 } } ``` The limits are 32 tiers per preset, 1000 ms for a window and 64 saved presets. Judgement sets written in TypeScript are another thing: see [Judgement sets](https://prism.am/dev/md/guides/judgement-set.md). ## Controls code {#controls} A control profile (key bindings, pad bindings, mod actions) shares as one line: ```text pvng-controls-1:<base64url>.<crc32> ``` The body is a JSON object of the control fields that differ from the shipped controls, in UTF-8, base64url without padding. `<crc32>` is the CRC-32 of those JSON bytes, as 8 lowercase hexadecimal digits. A code is at most 98304 characters. A profile name, a path or any field outside the known control fields is ignored. A pasted code is checked against its sum and against the rules of the load path, and two actions on one key where the rules forbid it refuse the **whole** code: nothing is half applied. The version number in the prefix is `1`; another version is refused with its own reason. ## Map link {#map-link} ```text prism://map/<64 hexadecimal digits> ``` The digits are the [note hash](https://prism.am/dev/md/formats/rox-and-hashes.md#note-hash) of the map. The accepted form is exactly `prism://map/` followed by 64 hexadecimal characters. A trailing `/` is tolerated (browsers add it) and the scheme and the word `map` are not case-sensitive. Anything else is refused: another action, a query, a fragment, a path, a shorter hash. A link never opens a file. When the link reaches the game, the map is selected in your library if you have it. If you do not, the game asks Prism's index (`GET /api/charts/<note hash>`, see [Charts API](https://prism.am/dev/md/online/charts.md)) and shows which osu! set or Etterna pack holds it, with a **Download** button. Only that click starts a download. In offline mode nothing is asked. ## File associations {#file-associations} A double-click on one of these files opens Prism and imports it. Nothing starts by itself: no play, no replay, a mod arrives disabled, a skin is only read. | Extension | What | Same path as | |---|---|---| | `.osr`, `.pvreplay` | osu!mania or Prism replay | The replay import button and drag and drop | | `.pvmod` | Mod ([package](https://prism.am/dev/md/formats/pvmod.md)) | The Mods page install; the mod arrives **disabled** | | `.osk` | osu! skin | The skin converter of the Skins page ([import](https://prism.am/dev/md/guides/skin-import.md)); you still click Create | | `.osz`, `.qp` | osu! or Quaver map pack | The map pack drag and drop (download queue) | | `.pvplaylist` | Playlist ([file](https://prism.am/dev/md/formats/pvplaylist.md)) | The playlist import | These are seven extensions. Any other extension is refused. `.zip` is deliberately not associated: it is too generic, and a Prism skin in a `.zip` installs from the Skins page. `.pvmarathon` is not openable: it is a recipe the library scan reads. How the game receives a file: - Windows runs `prism.exe "<file>"`. The game keeps only arguments without a leading dash whose extension is known, makes them absolute, and keeps at most 8 without duplicates. - Only one copy runs per channel. A second copy brings the first to the foreground, hands it the paths, and exits. Stable and preview each have their own window: a file goes to the copy of the same channel. - A received path is checked again: valid text, at most 4096 bytes, no control character, absolute, known extension, at most 8 paths and 32 KiB. One invalid path refuses the whole message. - The file itself goes through the normal importer, with its own validation. The file waits in a queue until the interface is ready and no play, training, viewer, replay or editor is on screen. At most 16 files wait. The Windows installer registers the associations per user, without administrator rights (the `fileassoc` task, ticked by default). Prism becomes the default program for an extension only when no other program owns it, so the osu! and Quaver extensions (`.osr`, `.osz`, `.qp`) are never taken from them; Prism then appears under "Open with". `.pvreplay`, `.pvmod` and `.pvplaylist` are taken. A copy unzipped from the archive has no association: choose `prism.exe` under "Open with" to get the same result. The `prism://` scheme follows the same task and the same per-user rule. ===== Page: Rox files and chart hashes Address: https://prism.am/dev/formats/rox-and-hashes/ Derived from: crates/core/src/lib.rs, crates/core/src/chart_identity.rs, crates/note_hash/src/lib.rs, vendor/rhythm-open-exchange/src/formats/rox_native/decoder.rs, services/api/src/controllers/charts.rs, Cargo.toml # Rox files and chart hashes The .rox chart container, how Prism reads it, and the three identities of a chart (note hash, chart hash, chart version) with the API that takes each. Prism talks about a chart in three ways. A `.rox` file holds it. Two hashes name it, and they are not interchangeable. This page tells you which one you hold and which API takes it. ## The .rox file {#rox} `.rox` is the native binary chart of the Rhythm Open Exchange model, the `rhythm-open-exchange` crate (version 0.8.1, built from the copy in `vendor/` for the game, the game server and the site alike). A file is the four magic bytes of the format, then a zstd frame holding an rkyv archive of the chart: key count, metadata, timing points (BPM and scroll velocity), notes (tap, hold, burst, mine), hitsounds. The definition of the layout is the crate's code. Prism never trusts a `.rox`. The decoder inflates the frame into a bounded buffer and validates the archive before reading it. | Limit of the decoder | Value | |---|---| | Decompressed archive | 64 MiB | | Notes | 4,000,000 | | Timing points | 1,000,000 | | Hitsounds | 1,000,000 | The game reads a chart file through one decoder picked from the file (`.osu`, `.qua`, `.sm`, `.rox` and the other formats the crate reads). For bytes it already holds, such as a chart fetched from the index, it decodes them as a `.rox`. `GET /api/charts/{hash}/rox` serves the `.rox` of a chart the index holds. It is content-addressed: `ETag` is the hash and `Cache-Control` is `immutable`. The `{hash}` is a note hash. See [Charts API](https://prism.am/dev/md/online/charts.md). ## The note hash {#note-hash} The note hash is the identity the index and the online boards know. It answers the question "is this the same notes pattern, wherever it was downloaded from". It is BLAKE3 in key-derivation mode with the context `pvng note hash v1` (version `1`). It is fed with: 1. The key count, one byte. 2. The number of notes, a little-endian `u64`. 3. The notes sorted by `(start, column, kind, end)`, each as little-endian `i64` start, the column byte, the kind byte (`0` tap, `1` hold) and the little-endian `i64` end. Before hashing, every time is rounded to the nearest millisecond (half up), and the time of the first note is subtracted from all of them. A chart shifted as a whole by a whole number of milliseconds therefore has the same note hash. Only taps and holds count. Mines, bursts, timing points, metadata and audio are left out. There is no tolerance: two charts whose notes round to different milliseconds have different hashes. The result is 64 lowercase hexadecimal characters. ## The chart hash {#chart-hash} The chart hash is the identity of the **exact** chart a play was made on. It is BLAKE3 over the notes and the timing points, to the microsecond, with no offset removed. The function counts mines and bursts when the chart it is given has them. The game hashes the chart as it plays it, from which it has removed mines and rolls. The full algorithm is in [The .pvreplay file](https://prism.am/dev/md/formats/pvreplay.md#chart-hash). It is 64 lowercase hexadecimal characters. Because the note hash forgets a global offset, one note hash can have several chart hashes. An osu! set and an Etterna pack that hold the same notes with a 13.7 ms difference give one note hash and two chart hashes. ## The chart version {#version} A **chart version** is one chart hash under a note hash. The index keeps every version it reads: the first one under the note hash, the others as separate files under their chart hash. The game names the version it played, and the game server judges a play on that exact version when the index holds it. When the index does not hold it yet, the server falls back to its own copy aligned on the start of the first note, and the result may differ by one point. ## Which API takes which {#which-api} | Where | Takes | |---|---| | `GET /api/charts/{hash}` and `/rox`, `/notes`, and the other chart reads | Note hash | | Online boards, rankings and marathon reads by hash | Note hash | | `prism://map/<hash>` | Note hash | | `scoreBegin` on the game server | Both: the note hash for the board, `chartHash` for the exact version played | | `.pvreplay` | Both, in the archive | | `.pvplaylist` entry `hash` | Chart hash | | `.pvmarathon` entry | Both: `chartHash` and `noteHash` | To import an osu! replay for a map you do not own, the game asks the site for the map by the MD5 of its `.osu` file and receives its note hash and the chart hash of that exact file. ## Which one do I hold {#which} - A 64-hex string in a `prism://map/` link, or in `GET /api/charts/<hash>`, is a note hash. - A 64-hex string inside a `.pvplaylist` or a `.pvreplay` named `chart` is a chart hash. - You cannot compute one from the other. To go from a chart hash to a note hash, decode the chart and hash it with the note hash rules. The crates `game_core::chart_identity::chart_hash` and `note_hash::note_hash` are the reference implementations. ## Pitfalls {#pitfalls} - Do not send a note hash where a chart hash is expected, or the reverse: both are 64 hexadecimal characters and nothing in the text tells them apart. A playlist entry is a chart hash; `GET /api/charts/<hash>` takes a note hash. - A conversion that changes notes gives another chart. The ROX encoder writes mines as taps and rolls as holds, so a converted file has another hash. ===== Page: releases.json and release signatures Address: https://prism.am/dev/formats/releases/ Derived from: services/api/types/src/lib.rs, crates/updater/src/feed.rs, crates/updater/src/signature.rs, crates/updater/src/net.rs, crates/updater/src/lib.rs # releases.json and release signatures The public contract of the downloads feed the game reads, how the client parses it, and how a release zip is verified with minisign. The game updates itself from one JSON document, `releases.json`, and checks every download with a minisign signature. This page is the public contract of both. How releases are produced and published is not part of it. ## Where to read it {#endpoints} | URL | Content | |---|---| | `https://prism.am/releases.json` | The feed. This is the default feed of the game | | `/download/<channel>/latest` | A stable redirect to the newest zip of a channel (the Windows package). With `?os=linux`, to the newest Linux package of the channel | | `/download/<channel>/installer` | A stable redirect to the newest Windows installer of a channel that has one | There are two channels: `stable` and `pbe` (the preview channel). Only active releases are listed, newest first within each channel. A withdrawn release disappears from the feed. ## The feed {#feed} The document has four top-level fields, and a fifth once a release has a Linux package. A reader must ignore unknown fields: the schema is never bumped for additions. | Field | Type | Meaning | |---|---|---| | `schema` | integer | `1` | | `generatedAt` | string | Date-time in UTC, ISO 8601 | | `channels` | array | One summary per channel | | `releases` | array | Every active release | | `linux` | array, optional | The releases that have a Linux package, see [one list per system](#systems) | A channel summary: | Field | Type | Meaning | |---|---|---| | `channel` | string | `stable` or `pbe` | | `latestSeq` | integer or `null` | `seq` of the newest active release; `null` when the channel has none | | `latestUrl` | string | The stable redirect to the newest zip | | `latestInstallerUrl` | string, optional | The redirect to the newest installer, absent when none has one | | `latestLinuxUrl` | string, optional | The redirect to the newest Linux package, absent when no release has one | A release: | Field | Type | Meaning | |---|---|---| | `channel` | string | `stable` or `pbe` | | `seq` | integer | Order within the channel, strictly increasing. The newest is the largest `seq` | | `build` | string | Free label shown to people, for example `PBE 0007`. It is never parsed and never orders releases | | `commit` | string, optional | Short git hash the build was made from | | `semver` | string, optional | A semantic version, on stable builds | | `builtFromBuild` | string, optional | The label of the build a stable build was promoted from | | `publishedAt` | string | Date-time in UTC | | `file` | string | The download file name, only `A-Z a-z 0-9 . _ -` | | `url` | string | The download URL, relative to the site unless the server sets a public base URL | | `sha256` | string | Lowercase hexadecimal SHA-256 of the file | | `size` | integer | Size of the file in bytes | | `notesMd` | string | Release notes in Markdown (French) | | `notesEnMd` | string, optional | English release notes in Markdown | | `installer` | object, optional | `file`, `url`, `sha256`, `size` of the Windows installer, a first-install file that the in-game updater never downloads | ```json { "schema": 1, "generatedAt": "2026-10-31T09:00:00Z", "channels": [ { "channel": "pbe", "latestSeq": 7, "latestUrl": "/download/pbe/latest" } ], "releases": [ { "channel": "pbe", "seq": 7, "build": "PBE 0007", "commit": "a1b2c3d", "publishedAt": "2026-10-31T08:30:00Z", "file": "prism-pbe-0007.zip", "url": "/files/pbe/prism-pbe-0007.zip", "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "size": 17000000, "notesMd": "Notes." } ] } ``` ### One list per system {#systems} `releases` holds the Windows packages. A release that also has a Linux package is written a second time in `linux`: the same `channel`, `seq`, `build`, dates and notes, with the Linux zip as its `file`, `url`, `sha256` and `size`, and no `installer`. Each game reads the list of its own system and nothing else: a Windows game reads `releases`, a Linux game reads `linux`. A release with no Linux package is simply not in `linux`, so the newest Linux release may be older than the newest Windows one. The Linux zip is signed like any release zip, with the trusted comment of its own entry. ## How the client reads it {#client} The client reads the feed tolerantly. A release that makes no sense is dropped on its own and the others still count. | Rule | Value | |---|---| | Feed size | At most 4 MiB. A larger feed is refused | | Required | `releases` is an array. Each entry needs `channel`, `seq`, `build`, `sha256`, `size` and `url` | | `channel` | `stable` or `pbe` | | `seq` | An integer above 0. For a duplicate `(channel, seq)`, the first is kept | | `build` | Control characters removed, cut to 64 characters; must not be empty | | `sha256` | 64 hexadecimal characters; lowercased | | `size` | From 1 to 1 GiB (1,073,741,824 bytes) | | `url` | Not empty, at most 1024 characters | | `notesMd`, `notesEnMd` | Cut to 16 Ki characters | | `commit` | Kept only when 7 to 40 hexadecimal characters; lowercased | | Withdrawn | An entry with `withdrawn: true` or `status: "withdrawn"` is never offered, and is not counted as dropped | The order of a channel is its `seq`, never its `build` label. The client also reads the plainer names `published_at` and `date` for `publishedAt`, `notes_md` and `notes` for `notesMd`, and `notes_en_md` and `notesEn` for `notesEnMd`. The signature is **not** a feed field. ### Network rules {#network} - The feed and every package URL must be `https`. Plain `http` is only allowed for a loopback host (`localhost`, `127.0.0.1`, `[::1]`), for tests. - Every URL, including each redirect, must have the same scheme, host and port as the feed URL. A feed cannot send the game to another server. - At most 3 redirects are followed. - A check sends nothing identifying: a plain `User-Agent`, no cookie, no query, no version, no identifier. - The game reads the feed automatically once a day at most, and installs only when you click. The default feed is `https://prism.am/releases.json`; `PRISM_UPDATE_FEED` overrides it. ## Signature {#signature} Each release zip has a detached minisign signature in a sidecar file: ```text <zip url>.minisig ``` The file is at most 4 KiB. The signature is made over the zip itself, in minisign's pre-hashed mode (BLAKE2b over the file). Its **trusted comment** names the release, in this form: ```text channel=pbe seq=7 build=PBE 0007 sha256=<hexadecimal SHA-256 of the zip> ``` The keys can come in any order. The build label may hold spaces. The global part of the signature covers the trusted comment, so the comment cannot be swapped. The game verifies after the download and before anything is unpacked: 1. The SHA-256 and size of the file match the feed. 2. The signature is valid, under one of the public keys embedded in the game, over the downloaded file. 3. The trusted comment says this very release: the channel, the `seq`, the SHA-256 of the file and the `build` label of the feed entry. A genuine signature of another release (an older `seq`, the other channel) cannot be replayed. The key the game trusts is the author's release key, `RWQsLoM1lFYu6qNoyW3uT2vS6gUZyMSqTvUNBjiTwREhRivuky4jwd/B` (key id `EA2E569435832E2C`). Several keys may be embedded: a new key can be added by a release signed with the old one. A build with at least one embedded key **refuses** an unsigned release. There is no quiet fallback. A refusal is one of: | Refusal | Cause | |---|---| | Missing | No `.minisig` next to the zip | | Invalid | The signature file is unreadable, was made by another key, or does not match the file | | Identity | A valid signature of another release: channel, `seq`, hash or build label differ | A fork built with no embedded key verifies nothing, and the interface says "unsigned". ## Pitfalls {#pitfalls} - Changing `build` after signing breaks the signature: the label is in the trusted comment. - A relative `url` is resolved against the feed's own host. An absolute URL on another host is refused. - A `size` of 0 or above 1 GiB makes the client drop that release from its list. - Do not rely on `build` to order releases. Use `seq`. ===== Page: Online API Address: https://prism.am/dev/online/api/ Derived from: services/api/src/openapi.rs, services/api/src/controllers/openapi.rs, services/api/src/controllers/catalog.rs, services/api/src/controllers/charts.rs, services/api/src/controllers/auth.rs, services/api/src/app.rs, services/api/src/accounts/settings.rs, services/api/types/openapi.json, services/api/config/production.yaml, crates/online_protocol/src/lib.rs, deploy/Caddyfile, services/website/package.json # Online API Where the Prism web API is described, how to sign in, what needs no account, the real rate limits, and how to generate a typed client. The Prism site and the game talk to one backend (`services/api`, a Loco.rs application) over HTTPS and JSON. This page is the pointer: where the exhaustive reference is, how to authenticate, what you can read without an account, the limits, and how to get a typed client. The pages that follow explain the groups of endpoints that matter to tool makers: [map index and boards](https://prism.am/dev/md/online/charts.md), [catalogue](https://prism.am/dev/md/online/catalog.md), [submission](https://prism.am/dev/md/online/submit.md) and [game updates](https://prism.am/dev/md/online/updates.md). ## Where the reference lives {#reference} The API describes itself. The description is generated from the Rust code (the controller attributes), so it cannot drift from the server. | What | Address | Content | |---|---|---| | Interactive reference | `https://prism.am/api/docs` | A [Scalar](https://scalar.com) page. Its script is served by the API itself (no third-party host), under a policy that allows scripts from the page's own origin only. The backend serves the same page at `GET /`. | | Public description | `https://prism.am/api/openapi.json` | OpenAPI 3.1. It hides the `ops` and `admin` tags. | | Committed copy | `services/api/types/openapi.json` | The full description (the public one plus the `ops` operations: health, the description, the public keys; and the staff API), as a file of the repository. It is not served. | The staff API (`/api/admin/*`) is not reachable on the public host: the reverse proxy answers `404` there, and only the admin site relays it. It appears in the committed full description for the people who maintain it. Do not build on it. The committed file is regenerated from the code, never edited by hand. From `services/api`: ```bash cargo openapi ``` `cargo openapi` is an alias of `cargo run -p prism_backend --bin openapi --`. It writes `types/openapi.json` and opens no database. A test fails when the committed file is out of date. The public description lists 110 operations: 61 need no token (the sign-in calls included) and 49 require a signed-in account (`bearer`). The map index, the boards, the players, the rankings, the marathon reads, the catalogue and the releases are all in the first group. ## Authentication {#authentication} Public reads need nothing: no key, no header. Everything that acts for a player (profile, friends, clans, presets, sending a marathon) needs an access token. - The token is a JWT signed with EdDSA (Ed25519). Send it as `Authorization: Bearer <accessToken>`. - The only security scheme of the description is `bearer`. There are no API keys, no personal tokens and no OAuth application. - `POST /api/auth/login` takes `{ "login": "<username or e-mail>", "password": "…", "device": "…" }` (`device` is optional) and answers `accessToken`, `refreshToken`, `expiresIn` and `user`. - The access token lives **600 seconds** (`expiresIn`). The refresh token lives **30 days** and **rotates**: `POST /api/auth/refresh` with `{ "refreshToken": "…" }` answers a new pair, and the old refresh token is dead. Presenting an old one again ends the whole session, so a client that refreshes from two places at once logs itself out. - `POST /api/auth/logout` ends one session, `POST /api/auth/logout-all` ends every session of the account. - Registration asks for a proof of work first (`GET /api/auth/pow`) and an e-mail confirmation. An account that is banned cannot sign in (`403 account_banned`, with `reason` and `bannedUntil`). - The public keys that verify the tokens are served at `/.well-known/prism-keys.json` (the current key and, during a rotation, the previous ones). The game server reads them; an ordinary client never needs them. A `401` with `invalid_token` means the access token is missing, expired or not accepted: refresh it and retry once. ## What is public {#public} All of these answer without an account, as JSON unless said otherwise: - the **map index**: chart identity and sources, the `.rox` file, notes, pp, ratings, chartsets and their filters, the crawl status; - the **boards**: the board of a chart, its rates, one player's entry, one play and its replay; - **players and rankings**: profiles, search, ranks, achievements, the global, achievement and clan rankings; - **marathons**: the list, a marathon, its recipe, its board; - the **catalogue** of mods, skins and playlists (`GET /api/catalog`); - **challenges**, **tournaments**, **titles**, filter **presets** (reads); - the **game builds**: `/releases.json`, `/download/{channel}/latest` and `/download/{channel}/installer`; - the **rating calculators** (`GET /api/ratings`) and the health of the service. The [map index and boards](https://prism.am/dev/md/online/charts.md) page documents the first four groups with their real parameters. Everything else is in the reference at `/api/docs`. ## Conventions {#conventions} - **JSON, camelCase.** Field names are camelCase. Dates are either an ISO 8601 string (`generatedAt`, `createdAt`) or a number of milliseconds since the Unix epoch in a field whose name ends in `Ms` (`playedAtMs`). - **Additive.** The documents only grow. Ignore the fields and the enum values you do not know. The catalogue has no v2 and the game protocol has none either. - **Errors.** An error answers its status code and a JSON body `{ "error": "<code>", "description": "<sentence>" }`. `error` is a stable snake_case code to branch on (`bad_request`, `invalid_token`, `rate_limited`, `invalid_credentials`…); `description` names what is wrong and is meant for people. A banned account's `403` carries `reason` and `bannedUntil` too. - **Identities.** A chart is a **note hash**: 64 lowercase hexadecimal characters ([what it hashes](https://prism.am/dev/md/formats/rox-and-hashes.md)). An account is a lowercase UUID. A play, a marathon and a chartset have an integer id (a chartset also has a `uuid`). - **Caching.** Most reads carry an `ETag`: send `If-None-Match` and a `304` costs nothing. Content-addressed files (`.rox`, notes) are `immutable`. - **Bodies.** The public host refuses a request body above 64 KB, except the profile picture (5 MiB) and the one-time osu! import's files (1 MiB). - **Courtesy.** Put a way to reach you in your `User-Agent`. Do not poll: ask again when an `ETag` or a `ttlMs` says the answer may have changed. ## Rate limits {#rate-limits} Limits are per client address and per minute, in a fixed window. A client that goes over is answered `429` with `{ "error": "rate_limited", … }` and a `Retry-After` header in seconds. The client address is the **first** value of the `X-Forwarded-For` header. The reverse proxy overwrites that header with the real peer, so it cannot be forged from outside. Without a proxy (development), every client is `direct`. The proxy applies no rate limit of its own. | Limiter | Default | Setting | Counts | |---|---|---|---| | Public reads | 240 per minute | `CHARTS_RATE_PER_MINUTE` | One counter per **bucket** (below) and per address: a client can use 240 per minute in each bucket. | | Catalogue | 120 per minute | `CATALOG_RATE_PER_MINUTE` | `GET /api/catalog`. | | Accounts | 60 per minute | none | Every `/api/auth/*` call, one counter per address (an IPv6 address counts by its /64). | | Performance reports | 4 per minute | none | `POST /api/perf-reports`. | The buckets of the public reads limiter are these thirteen. A request is counted in the bucket of its endpoint: | Bucket | Endpoints | |---|---| | `lookup` | `GET /api/charts/{hash}`, and `ratings` or `pp` of a chart already computed | | `rating-compute` | `ratings` or `pp` of a chart at a rate that must be computed first | | `rox` | `GET /api/charts/{hash}/rox` and `/notes` | | `scores` | boards, plays, players, rankings (global, achievements, clans), marathon boards, achievements | | `browse` | chartsets, one chartset, the crawl status, marathons (list, one, recipe, by hash) | | `suggest` | `GET /api/chartsets/suggest` | | `replay` | `GET /api/scores/{id}/replay` | | `challenges` | the weekly challenge reads | | `clans` | `GET /api/clans/{uuid}` | | `presets` | the filter preset reads | | `tournaments` | the tournament reads | | `titles` | `GET /api/titles` | | `link-preview` | the page previews that chat apps fetch | `GET /api/ratings` is not throttled. The limits are the server's defaults: a self-hosted server may set others. ## The game protocol {#game-protocol} Lobbies, chat, presence and score submission do not go through this API. The game opens a **WebSocket** on `wss://prism.am/play` to the game server and exchanges JSON text frames, one message per frame. Both sides use the same Rust types (`crates/online_protocol`), published as the TypeScript package `@pvng/online` (generated by `prism.exe --write-ts-packages [dir]`, committed at `apps/web/packages/@pvng/online`). - `PROTOCOL_VERSION` is `1` and there will be no v2: messages are enums tagged by `type`, a new message or field is additive, and a reader ignores what it does not know. The constant moves only if a message changes its meaning. - What both sides can do is negotiated by the `features` list of the handshake (`hello` from the game, `welcome` from the server): `presence`, `chat`, `lobbies`, `lobby-files`, `scores`, `lobby-open`, `lobby-late-join`, `chat-commands`, `titles`, `clan-chat`, `lobby-draft`. - The first message is `hello` with the `protocol`, the `clientVersion`, the `features` the client speaks and the account's access token (at most 2048 bytes). The server answers `welcome` with the features it offers and the minimum client version, or an error code. The protocol is for the game, not for third-party bots: a score only counts after the server has replayed it on its own copy of the chart. ## Generate a typed client {#typed-client} The website itself does this. From `services/website`, `bun run gen:api` runs: ```bash openapi-typescript ../api/types/openapi.json -o src/lib/api/schema.d.ts ``` For your own project, point the generator at the public description: ```bash bunx openapi-typescript https://prism.am/api/openapi.json -o prism-api.d.ts ``` The file exports `paths`, `components` and `operations`: a type for every path, parameter and response. The typed fetch wrapper `openapi-fetch` (`createClient<paths>({ baseUrl: "https://prism.am" })`) reads them directly. Any other OpenAPI 3.1 generator works as well, since the document is plain OpenAPI. > [!NOTE] > The description is generated from the code, but a field's meaning is in its text. When a typed client compiles and an answer still surprises you, read the operation's description in `/api/docs`: it states the sort order, what is hidden (banned accounts) and what an absent field means. ===== Page: Map index, boards and rankings Address: https://prism.am/dev/online/charts/ Derived from: services/api/types/openapi.json, services/api/docs/BROWSE.md, services/api/docs/SCORES.md, services/api/src/controllers/charts.rs, services/api/src/controllers/browse.rs, services/api/src/controllers/boards.rs, services/api/src/controllers/scores.rs, services/api/src/controllers/marathons.rs, services/api/src/controllers/achievements.rs, services/index/src/lib.rs, crates/note_hash/src/lib.rs # Map index, boards and rankings The public read API of the map index, the online boards, players, rankings and marathons: identities, parameters, answers and limits, with curl examples. The map index behind the Browse page, the online boards, the player pages and the marathons have a public, read-only JSON API. It needs no account. This page groups the endpoints by use and gives the parameters that matter. The exhaustive list, with every field of every answer, is the reference at [`/api/docs`](https://prism.am/api/docs); the conventions (errors, caching, rate limits) are on the [online API](https://prism.am/dev/md/online/api.md) page. All examples use `https://prism.am`. A chart in the examples is written `<hash>`: a note hash, described next. ## Chart identity: the note hash {#identity} A chart is identified by its **note hash**: 64 lowercase hexadecimal characters, a BLAKE3 digest of the key count and of the taps and holds (start time, column, kind, end time of a long note) in whole milliseconds, with the first note's time subtracted. The same notes give the same hash whether they come from an `.osu`, `.sm`, `.ssc` or `.qua` file and whatever the file is called. Mines, bursts and timing points do not count, and neither do the audio and the metadata. The hash version is returned as `noteHashVersion`. The index holds osu!mania and Etterna charts of **4 to 9 keys**. A key count outside that range matches nothing. The note hash is not the `chart_hash` stored in a replay: that one is stricter and exists to check a replay against a chart. The two are explained in [`.rox` files and hashes](https://prism.am/dev/md/formats/rox-and-hashes.md). Every endpoint below takes the note hash. A malformed hash answers `400`. ## Find a chart {#chart-lookup} ### Where to download it {#chart-sources} ```bash curl https://prism.am/api/charts/<hash> ``` `GET /api/charts/{hash}` says what is known about a chart and where it can be downloaded at its origin. A well-formed hash the index does not know answers `200` with `"status": "unknown"`, so that a client can ask without error handling. ```json { "chartHash": "9f2c…64 hex…", "status": "known", "sources": [ { "kind": "osuSet", "ref": "4001", "confidence": "verified", "checkedAtMs": 1791600000000 } ], "ttlMs": 300000, "chart": { "hash": "9f2c…", "noteHashVersion": 1, "keys": 7, "bpmMin": 120.0, "bpmMax": 180.0, "bpmMain": 180.0, "lengthMs": 144000, "notes": 1200, "lns": 40, "densityAvg": 8.3, "densityPeak": 14.0, "roxBytes": 5120, "title": "Song", "artist": "Artist", "creator": "Mapper", "difficulty": "7K Hard" } } ``` The `chart` object is abbreviated here: it also carries `uuid`, `setUuid` and the ratings when they are known. `kind` is an **open set** (`osuSet`, `etternaPack`, …): ignore kinds you do not know. `ref` is an identifier, never a URL: an osu! set id or an EtternaOnline pack id. The page of the source is `https://osu.ppy.sh/beatmapsets/<ref>` or `https://etternaonline.com/packs/<ref>`. The answer carries an `ETag` and `Cache-Control: public, max-age=300`. ### The chart file and its notes {#chart-files} | Endpoint | Answer | |---|---| | `GET /api/charts/{hash}/rox` | The chart in the compact ROX format, as an attachment (`application/octet-stream`). `404` if the chart is unknown or was removed. **Never audio, never images.** | | `GET /api/charts/{hash}/notes` | The notes at 1.0×, as JSON, for a preview playfield: `keys`, `lengthMs` and `notes`. Mines and rolls are left out, as the game drops them. The browser scales the times to another rate itself. | Both are content-addressed: `ETag` is the hash and `Cache-Control` is `immutable`. ### Ratings and pp {#ratings} ```bash curl "https://prism.am/api/charts/<hash>/ratings?rate=1.2&calc=minacalc" curl "https://prism.am/api/charts/<hash>/pp?rate=1.0" curl https://prism.am/api/ratings ``` | Endpoint | Parameters | Answer | |---|---|---| | `GET /api/charts/{hash}/ratings` | `rate`: 0.70 to 2.00 in steps of 0.05 (1.0 by default). `calc`: `minacalc`, `osu`, `quaver` or `sunny` (all by default) | The ratings of the chart at that rate: each calculator with its version, its `overall` and its skillsets. A rate other than 1.0 is computed on the first request. | | `GET /api/charts/{hash}/pp` | `rate`, as above | The Prism pp of the chart for every accuracy from 80.0 % to 100.0 % in steps of 0.1 (201 `points`), with `msd`, `stars` and the length factor. | | `GET /api/ratings` | none | The calculators the site computes, their versions and the rates that may be asked for. | An unknown chart answers `404` (for `pp`, also a chart MinaCalc cannot rate). When the calculation queue is full the answer is `503` with `Retry-After`. ## Boards {#boards} The online board of a chart lists each player once, with their best play. The game server verified every play and **replayed it on its own copy of the chart** before it wrote it to the site's database, and every play is read under the **Prism judgement**: accuracy, combo and misses are the Prism ones, never the player's claim. The judgement a player chose is only the record of what they played with; there is no judgement dimension on the boards. The order is: best rating first (the MinaCalc 527 rating the server computed; a play without one last), then Prism accuracy, then the highest combo, then the play recorded first. The plays of a banned account or of an account scheduled for deletion are not listed. ### A page of the board {#board-page} ```bash curl "https://prism.am/api/charts/<hash>/scores?limit=20&rate=1.0" curl "https://prism.am/api/charts/<hash>/scores?country=FR" ``` | Query parameter | Meaning | |---|---| | `rate` | Absent or `all`: THE board of the chart, each player once with their best play whatever its speed. An exact playback rate from 0.5 to 2.0: the same ranking over the plays of that speed, each player once too (`total` counts players). | | `limit`, `offset` | `limit` is 1 to 100 (default 50), `offset` at most 10000. | | `country` | Only the players of this country: an ISO 3166-1 alpha-2 code in **upper case** (`FR`). `rank` and `total` count among them. A lowercase or unknown code is a `400`. | | `friends` | `1`: the board of the accounts the caller follows plus the caller. Needs `Authorization: Bearer` (`401 invalid_token` without) and the answer is `Cache-Control: private, no-store`. Not with `country` (`400 conflicting_scope`). | There is no `judgement` parameter: an unknown parameter (an old client's `judgement=`) is ignored, not an error. ```json { "chartHash": "9f2c…64 hex…", "rate": 1.0, "total": 132, "offset": 0, "limit": 50, "items": [ { "id": 4821, "hasReplay": true, "rank": 1, "username": "Ada", "userId": "0190…uuid…", "accuracy": 99.12, "maxCombo": 842, "misses": 1, "counts": [610, 120, 60, 30, 12, 6, 3, 1], "rating": 24.5, "playedAtMs": 1791600000000, "playbackRate": 1.0 } ] } ``` An entry has more fields than shown (`pp`, `skillsets`, `country`, `avatar`, `title`, `clan`, `unstableRate`, pause counts…): see the reference. A chart nobody played is `total: 0` with no items, never an error. `rank` counts over the whole board, not the page. `playedAtMs` is the date the player's game claims. `userId` is the account's UUID: the game compares it to its own account to spot "my score". `counts` (the eight Prism tiers, the Miss last) and `rating` are absent from a play stored before the server kept them. ### Rates, one player, one play {#board-more} | Endpoint | Answer | |---|---| | `GET /api/charts/{hash}/boards` | The rates a chart has, for a rate picker: one `{ "rate", "plays" }` per playback rate with at least one visible play, by rate ascending (at most 200). A chart nobody played is an empty list. | | `GET /api/charts/{hash}/scores/players/{user_id}` | One player's entry on THE board: their best play and its rank over the whole board. `404` if they have none. | | `GET /api/charts/{hash}/attempts` | Where players miss and where they leave the chart, counted on the bins of the chart's profile (the same span and bins as its density curve). | | `GET /api/scores/{id}` | One play, with the board's figures, its position when it is the player's best, every judgement the server stored and the chartset that holds its chart. | | `GET /api/scores/{id}/replay` | The replay of the play, a [`.pvreplay`](https://prism.am/dev/md/formats/pvreplay.md) file (`application/octet-stream`, immutable), to watch and rejudge in the game. `404` when the play has no replay or its account is not active. | The `id` of a play is the `id` of a board entry; only an entry with `"hasReplay": true` has a replay. ## Chartsets (Browse) {#chartsets} A chartset is one song folder: an osu! set or an Etterna pack song. `GET /api/chartsets` lists them with filters; most are the filters of the Browse page. ```bash curl "https://prism.am/api/chartsets?keys=4,7&ratingMin=18&sort=rating&perPage=24" curl "https://prism.am/api/chartsets?q=%22blue%20zenith%22&bpmMin=170" ``` ### Text and source {#chartset-text} | Parameter | Meaning | |---|---| | `q` | Free words, 200 characters at most, ranked by relevance. A set matches when it holds most of the words in its title, artist, creator, difficulty names, pack or tags (case, accents and punctuation aside). Words in quotes are one phrase. `qMatch=all` asks for every word, spelled as typed. | | `title`, `artist`, `creator`, `difficulty`, `pack` | Part of the name. Add `titleMatch`, `artistMatch`, `creatorMatch`, `difficultyMatch` or `packMatch` with `exact` for an exact, case-insensitive match (`contains` is the default). | | `tags` | One or several tags, comma-separated: the set must hold all of them (8 tags and 200 characters at most). `tagsMatch=exact` asks for whole tags. | | `source`, `packId` | `osuSet` or `etternaPack`; the EtternaOnline id of a pack. | | `updatedFrom`, `updatedTo` | `YYYY-MM-DD` (UTC): the set was last updated at its origin in that range. Only osu! sets have that date. | ### Numbers {#chartset-numbers} Every pair `xMin` / `xMax` is an inclusive range, and a chart of the set must match all of them. | Parameter | Meaning | |---|---| | `keys` | Comma-separated key counts, e.g. `4,7`. | | `bpmMin`, `bpmMax`, `lengthMin`, `lengthMax` | BPM and length in seconds (overlap with the set's charts). | | `densityMin`, `densityMax`, `npsMin`, `npsMax` | Peak and average notes per second. | | `notesMin`, `notesMax`, `lnMin`, `lnMax` | Notes (a long note counts once) and percentage of long notes (0 to 100). | | `ratingCalc`, `ratingMin`, `ratingMax`, `rated` | Difficulty range by calculator: `minacalc` (default), `osu`, `quaver` or `sunny`. `rated=yes` keeps the charts that calculator rated, `no` the others. | | `rate` | The rate of the rating criteria: 0.70 to 2.00 in steps of 0.05, 1.0 by default. Every chart is rated at 1.0 only; another rate matches the charts a visitor already asked for. | | `pattern`, `streamMin`, `streamMax`, `jumpstreamMin`, … `technicalMax` | The dominant MinaCalc skillsets of a chart (`stream`, `jumpstream`, `handstream`, `stamina`, `jackspeed`, `chordjack`, `technical`) and a range for each. | ### Order and pages {#chartset-paging} | Parameter | Meaning | |---|---| | `sort` | `relevance` (the default when `q` has words), `updated` (the default otherwise), `title`, `artist`, `bpm`, `length`, `density`, `rating`, `date`, or a skillset name. `rating` reads the 1.0× aggregates: with another `rate` it is a `400`. | | `dir` | `asc` or `desc`; the natural direction of the sort when absent. | | `page`, `perPage` | `page` from 1, `perPage` 1 to 60 (24 by default). | The answer is `{ "items": [...], "total": n, "page": p, "perPage": n }`. `total` is exact when nothing restricts the list and exact up to 10 000 otherwise; past that it is `10000` and `totalCapped` is `true`. The order is total (every sort ends on the set's id), so a page never repeats or skips a set. An item carries `id`, `uuid`, `title`, `artist`, `creator`, `sourceKind`, `sourceRef`, `keys`, `bpmMin`, `bpmMax`, `lengthMinMs`, `lengthMaxMs`, `densityMax`, `chartCount`, `coverUrl`, `difficulties` and `downloadUrl` (`/go/chartset/<id>`, absent for a set with no public source). ### One chartset, suggestions, redirect {#chartset-more} | Endpoint | Answer | |---|---| | `GET /api/chartsets/{id}` | One chartset (its `uuid` or its numeric id): the fields above plus `tags`, `sources` and `charts`, each holding its `chart` object (with its note hash), its `difficulty` name in this set and, for osu!, its `osuBeatmapId`. | | `GET /api/chartsets/suggest` | The values a text filter can take, with the number of sets that hold each. `field` is `tag`, `creator`, `artist` or `pack` (required); `q` is what was typed (50 characters at most); `limit` is 1 to 20 (10 by default). Answer: `{ "field", "items": [{ "value", "count" }] }`. | | `GET /go/chartset/{id}` | A `302` redirect to the page of the original source, where the map is downloaded. `404` for a set without a public source. | | `GET /api/crawl/status` | Public progress counters of the index crawl: charts, chartsets, sources, and what the crawler reports about itself. | The index hosts none of the audio, images or archives of the maps. It only points to the original source, and creators are credited wherever a chart is shown. To have an entry removed, use the [Contact page](https://prism.am/contact/). ## Players and rankings {#players} ```bash curl https://prism.am/api/players/Ada curl "https://prism.am/api/players/search?q=ad" curl "https://prism.am/api/rankings?keys=7&sort=stream&country=FR&limit=20" ``` | Endpoint | Answer | |---|---| | `GET /api/players/{name}` | A player's public profile: best plays, latest plays, rating and best by main pattern. The name is case-insensitive. `403` when the player has not made their profile public, `404` when the name is unknown. | | `GET /api/players/id/{userId}` | A player's best plays by performance and their places in the global and per-key-count rankings, for any active account (the profile's privacy switch does not apply: it shows only the best play of each chart, which the public board already shows). | | `GET /api/players/id/{userId}/achievements` | The game's achievements evaluated over the player's online plays: every achievement with its tier, progress and the date of each tier. An achievement the server cannot tell is flagged `available: false`. | | `GET /api/players/search` | `q` is the start of a player name (2 to 20 characters of `A-Z a-z 0-9 _ -`). Active accounts whose name starts with it, any case. | | `GET /api/players/ranks` | `ids`: 1 to 100 account ids, comma-separated. The rank and total pp of those accounts, with their picture, country and title. | | `GET /api/rankings` | A page of the global ranking: active accounts by Prism performance total (the 50 best plays' pp, the best at full weight falling in a straight line to 1 % at the 50th). | | `GET /api/rankings/achievements` | A page of the achievement points ranking. | | `GET /api/rankings/clans` | The clans ranking: the sum (`totalPp`) and mean (`averagePp`) of the members' pp. `sort` is `total` (default), `average` or `members`. | | `GET /api/rankings/sctp` | The Single Charts Top Performance ranking (SCTP): the plays worth the most pp, one per chart (the best play of each chart, any player, any rate). Takes `keys` too. | The rankings take `limit` (1 to 100, 50 by default) and `offset` (at most 10000). `GET /api/rankings` also takes `keys` (4 for 4K, 7 for 7K…), `sort` (`global`, or a MinaCalc pattern: `stream`, `jumpstream`, `handstream`, `stamina`, `jackspeed`, `chordjack`, `technical`), `country` (upper-case alpha-2 code; the players are ranked again among themselves) and `q` (a username substring, any case, before paging; the place is kept). The achievements ranking takes `country` too. Equal totals share a place. A banned account is never listed. ## Marathons {#marathons} A marathon is a recipe of maps played one after the other, each at its own rate, with its own board. Its identity is its own **note hash**: the game composes the marathon and hashes the result. ```bash curl "https://prism.am/api/marathons?keys=4&mapsMin=3&sort=rating" curl https://prism.am/api/marathons/by-hash/<marathon-note-hash>/scores ``` | Endpoint | Answer | |---|---| | `GET /api/marathons` | The marathons, filtered and paged: `q` (name or creator), `keys`, `creator` (+ `creatorMatch`), `lengthMin`/`lengthMax` (seconds), `mapsMin`/`mapsMax`, `ratingMin`/`ratingMax` (the PrismCalc overall at 1.0×; `ratingCalc` is `minacalc` only), `sort` (`updated` default, `title`, `rating`, `length`, `maps`), `dir`, `page`, `perPage` (1 to 60, 24 by default). | | `GET /api/marathons/{id}` | One marathon: its card, its source link and its maps in play order. A map the index does not know is listed with `known: false`. | | `GET /api/marathons/{id}/recipe` | The game's marathon manifest as the site keeps it, with no local path. | | `GET /api/marathons/{id}/scores`, `GET /api/marathons/by-hash/{note_hash}/scores` | The board of the marathon: each player once with their best play, best rating first. `limit` 1 to 100 (50 by default), `offset` 0 to 10000. A marathon has no rate and no replay. | Sending a marathon (`POST /api/marathons`) needs an account and is done by the game: see [authentication](https://prism.am/dev/md/online/api.md#authentication). The format of the recipe is on the [`.pvmarathon`](https://prism.am/dev/md/formats/pvmarathon.md) page. ## Manners {#manners} - Requests are limited per address, in buckets of 240 per minute; beyond it the answer is `429` with `Retry-After`. The exact buckets are in [rate limits](https://prism.am/dev/md/online/api.md#rate-limits). - Use `ETag` / `If-None-Match`; do not poll. - Put a way to reach you in your `User-Agent`. - Cache what is immutable: a `.rox` or a notes answer never changes for a given hash. ===== Page: Catalogue API and package rules Address: https://prism.am/dev/online/catalog/ Derived from: services/api/docs/CATALOG.md, services/api/src/catalog/validate.rs, services/api/src/catalog/archive.rs, services/api/src/catalog/playlist.rs, services/api/src/catalog/documents.rs, services/api/src/catalog/store.rs, services/api/src/catalog/limiter.rs, services/api/src/controllers/catalog.rs, services/api/types/src/lib.rs, crates/downloader/src/repository.rs, apps/desktop/src/app/hosted.rs, crates/modding/src/package.rs, crates/skin/src/package.rs, docs/catalogue.md # Catalogue API and package rules The public catalogue of mods, skins and playlists: the GET /api/catalog contract, what the server accepts, what the game reads and installs, side by side. The catalogue is the list of **mods**, **skins** and **playlists** published for Prism: mods and playlists after the team approves them, skins as soon as they pass the checks. The Download page of the game (**Download → Mods / Skins / Playlists**) and the site pages `/extensions/` and `/playlists/` read it from one endpoint. This page is the contract between the server that publishes it and the game that installs from it, and the limits each side applies. To publish something, see [Submit](https://prism.am/dev/md/online/submit.md). Two programs apply rules to the same package, and they do not apply the same ones. The server checks a package **before publishing** it. The game checks it again **before installing** it, with the rules of its own importer. A package must pass both. The [limits table](https://prism.am/dev/md/help/limits.md) lists every number of the project in one place. ## The list: `GET /api/catalog` {#list} ```bash curl "https://prism.am/api/catalog?kind=mod" curl -H 'If-None-Match: "<etag>"' https://prism.am/api/catalog ``` No authentication. Limited to 120 requests per minute per address (`429` with `Retry-After`); see [rate limits](https://prism.am/dev/md/online/api.md#rate-limits). The answer has a strong `ETag` and `Cache-Control: no-cache`: send `If-None-Match` and an unchanged catalogue answers `304`. The body changes only when the content changes (`generatedAt` is the last change). The only parameter is `kind=mod|skin|playlist`. Absent, every kind is listed. Any other value is a `400`. (The OpenAPI text of this parameter still says "`mod` or `skin`": the server accepts `playlist` too.) ```json { "schema": 1, "generatedAt": "2026-10-11T09:00:00Z", "items": [ { "id": "better-hud", "kind": "mod", "name": "Better HUD", "version": "1.2.0", "seq": 7, "author": "Ada", "descriptionEn": "A cleaner HUD.", "descriptionFr": "Un HUD plus propre.", "permissions": ["stage"], "tags": ["hud", "minimal"], "sha256": "43451505e2c8fb5c986c7e1e19a132d333d1b96e6eb03aa576a276903a8738f2", "size": 18342, "filename": "better-hud-1.2.0.pvmod", "url": "/files/catalog/mod/better-hud-1.2.0.pvmod", "status": "approved", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": "2026-10-11T08:59:00Z", "screenshots": ["/files/catalog/mod/better-hud-7-1.png"], "versions": [ { "version": "1.2.0", "seq": 7, "publishedAt": "2026-10-11T08:59:00Z", "filename": "better-hud-1.2.0.pvmod", "url": "/files/catalog/mod/better-hud-1.2.0.pvmod", "sha256": "…", "size": 18342 }, { "version": "1.1.0", "seq": 3, "publishedAt": "2026-10-02T10:00:00Z", "filename": "better-hud-1.1.0.pvmod", "url": "/files/catalog/mod/better-hud-1.1.0.pvmod", "sha256": "…", "size": 17010 } ] } ] } ``` There is **one entry per id and kind**: its newest approved version. Items are sorted by kind (the order of the `kind` enum), then by name (case-insensitive), then by `id`. Only approved items are listed, and nothing else is ever public. | Field | Meaning | |---|---| | `id` | Stable id of the item (rules [below](#ids)), unique **per kind**. | | `kind` | `mod`, `skin` or `playlist`. | | `name` | Display name. | | `version` | **Free** label of the newest approved version. Never parse it or sort by it. | | `seq` | Integer that strictly increases **per kind**, in publication order. It is what orders versions and what the game compares to detect an update. | | `author` | Credited author (a display name, not an account). | | `descriptionEn` | Plain English text, always present. | | `descriptionFr` | Plain French text, **absent** when none was given. | | `permissions` | The permissions the mod declares (`stage`, `skinImport`, `network`…). Always `[]` for a skin and for a playlist. | | `tags` | Up to 8 short labels, shown as chips on the card. Absent when there are none. | | `sha256`, `size`, `filename` | Lowercase hexadecimal hash, byte size and file name of this version. | | `url` | Download address: relative to the site, or absolute when the server knows its public address. | | `status` | Always `approved` in public documents. | | `owner` | The owning account; **absent** until accounts own items. | | `createdAt`, `updatedAt` | First approved publication of the item, and last change of the current version. | | `screenshots` | Preview image URLs. **Absent** when there are none. | | `versions` | Every approved version, newest first. The first one is the version of the fields above. | > [!WARNING] > The server writes the English description as `descriptionEn`. The game's own reader looks for `description` (and `descriptionFr`) instead, so the game currently shows no description for a catalogue item. A client of your own should read `descriptionEn`. Readers must ignore the fields they do not know: the document only grows, and there will be no v2. ## The files {#files} Packages are served at `/files/catalog/<kind>/<filename>`, like the game's own zips: - `Content-Disposition: attachment`, `Cache-Control: public, max-age=31536000, immutable` (a file name is never rewritten), `Range` accepted, `X-Content-Type-Options: nosniff`; - previews (`.png`, `.jpg`, `.webp`) are served without `attachment`, also immutable; - a path with a hidden segment (`.held`, `.incoming`) answers `404`: a package that is waiting for review cannot be downloaded by guessing its name. Two documents are rewritten at every change: `/files/catalog/catalog.json` (every kind, the same shape as `GET /api/catalog`) and `/files/catalog/SHA256SUMS.txt` (`<sha256> <kind>/<file>` for each approved package, checkable with `sha256sum -c`). ## What each kind is {#kinds} | | Mod | Skin | Playlist | |---|---|---|---| | File | `.pvmod` | `.zip` | `.pvplaylist` | | Format page | [`.pvmod`](https://prism.am/dev/md/formats/pvmod.md) | [skin package](https://prism.am/dev/md/formats/skin-package.md) | [`.pvplaylist`](https://prism.am/dev/md/formats/pvplaylist.md) | | State at publication | `pending`: **invisible** until the author approves it | `approved`: public at once | `pending`: invisible until approved | | Limit per person | none | **2 skins** per author (see below) | none | | Permissions | those the mod declares | none | none | A row has a state: `pending` → `approved` ⇄ `withdrawn`. Only `approved` rows are public. One row exists per **version**, and the public version of an id is the newest approved one (highest `seq`). The per-person limit counts distinct skin ids by author, where the author key is the author name with spaces collapsed and lower-cased. A new *version* of a skin does not count as a third skin, and withdrawing a skin frees its place. ## Server and game, side by side {#limits} ### Package size {#limit-size} | | Server (publishing) | Game, reading the list | Game, importing | |---|---|---|---| | Mod package | 2 MiB | 64 MiB | 64 MiB | | Skin package | 8 MiB | 256 MiB | 64 MiB | | Playlist file | 1 MiB | 1 MiB | 1 MiB | The game drops a list item whose `size` is above its ceiling, then checks the size and the SHA-256 after downloading. The server's ceilings are what really bound the catalogue today; the game's are wider. ### What is inside a ZIP {#limit-archive} | | Server (mod and skin) | Game, mod import | Game, skin import | |---|---|---|---| | Entries | 1024 | 1024 | 1024 | | Files | 512 | **256** | 512 | | One file, uncompressed | 16 MiB | 16 MiB | 32 MiB | | All files, uncompressed | 64 MiB | 64 MiB | 64 MiB | | Entry file | `main.ts` or `index.ts` | `main.ts` or `index.ts` | `skin.ts` | | Allowed extensions | `ts ttf otf png json md txt` | the same | `ts png ttf otf wav ogg flac mp3` | Two consequences: - A **mod** with 257 to 512 files passes the server and fails to install in the game. - A **skin** that carries key sounds (`wav`, `ogg`, `flac`, `mp3`) can be imported in the game but **cannot be published**: the server accepts only `ts png ttf otf` for a skin. Both sides refuse an unsafe path (absolute, `..`, a drive letter, a backslash), a symbolic link, an encrypted entry, a name that appears twice with the case ignored, and any compression other than stored or deflate. The server also reads each entry for real, to be sure it holds the size it declares. The entry file sits at the root or in the single top folder. See the [`.pvmod`](https://prism.am/dev/md/formats/pvmod.md) and [skin package](https://prism.am/dev/md/formats/skin-package.md) pages for the exact errors. A playlist is not a ZIP. The server accepts it only when the game would read it: a JSON object with `"format": "pvng-playlist"`, `"version": 1` (a newer version is refused), a name of 1 to 64 characters without control characters or surrounding spaces, at most 200 maps and at most 32 extensions. See [`.pvplaylist`](https://prism.am/dev/md/formats/pvplaylist.md). ### Ids {#ids} The id of an item is checked three times, with three rules. | Where | Rule | |---|---| | Server (`id` of an item) | 1 to 64 characters among `a-z`, `0-9`, `-`, `_`, `.`; the first is a letter or a digit; no `..`. | | Game, reading the list | 1 to 64 characters among `A-Za-z0-9._-`; no leading `.` or `-`; no trailing `.`. An item with another id is dropped. | | Mod manifest (`defineMod`) | 1 to 64 characters among `a-z`, `0-9`, `.`, `-`, `_`; starts **and ends** with a letter or a digit; no `..`; usable as a Windows file name. | The server allows a trailing `.`, and the game silently ignores such an item. To satisfy all three: lowercase letters, digits and `-` `_` `.` inside, starting and ending with a letter or a digit, no `..`, 64 characters at most. Use the **same** id in the catalogue and in `defineMod`. ### Text {#limit-text} | Field | Server | Game | |---|---|---| | `name`, `author` | 64 characters | keeps 80 | | `version` | 32 characters | keeps 32 | | Description | 2000 characters | keeps 600 | | Permissions | 8, each up to 32 letters or digits starting lowercase | keeps 12 names of up to 32 characters among `A-Za-z0-9_-` | | Tags | 8, each 1 to 24 characters, lower-cased, no comma or control character | keeps 8 | | Screenshots | 3, each a real PNG, JPEG or WebP of at most 512 KiB | keeps 6 | | List | no limit | reads at most 1 MiB and 500 items | The server rejects a value that breaks its rule. The game truncates or drops what is over its own, and ignores an invalid item without breaking the list. ## What the game does with an item {#client} - The list is requested **when a section opens**, never before. The game sends no identifier (no cookie, no token, no machine or player id), only `Accept` and its user agent. The address is `https://prism.am` unless the player changed it: the environment variable `PRISM_CATALOG` wins, then **Settings → Library → Catalogue address**. - Every request stays on **one host**: the same scheme, host and port as the catalogue address. A redirect to another host is refused, at most 3 redirects are followed, and a public https catalogue refuses private or local addresses. An item whose `url` points elsewhere is dropped. - The file goes to a temporary folder, with progress and a cancel button. Its exact size and its SHA-256 are verified; any difference deletes the file and shows an error. - The checked file is handed to the **same importer** as a manual import: the game's mod installer for a `.pvmod`, the skin library for a `.zip`, the playlist import for a `.pvplaylist`. All the package rules above apply again. What happens when something already exists: | Kind | Behaviour | |---|---| | Mod | An installed mod with the same id is **replaced** (that is the update). A mod arriving from the catalogue is installed **disabled**: the player turns it on from the Mods page. An update keeps the mod's state. | | Skin | A skin never overwrites a skin. The import gives it a free folder name (`neon-2`), so an update sits next to the old one. | | Playlist | An install always adds a new playlist; nothing is replaced. | The game remembers which catalogue item each local one came from (`seq` and `version`). With that link, an item is an **update** when the catalogue's `seq` is greater. Without it (installed by hand), the versions are compared when both are dot-separated numbers, and otherwise the item counts as installed. This is why `seq`, not `version`, is the order. The permissions shown before installing are the ones the catalogue announces. What counts is the package's manifest: if the package declares one the catalogue did not announce, the game says so after installing. ## Maintaining the catalogue {#admin} The author adds items by hand with the `prism-admin` command on the server. This is not an API; it is listed so that the rules above have a visible origin. ```text catalog add --kind mod|skin|playlist --file <.pvmod|.zip|.pvplaylist> --id <slug> --name <name> --version <label> --author <name> --desc-en <text> [--desc-fr <text>] [--permissions stage,skinImport] [--owner <account>] [--screenshot <png|jpg|webp>]… [--tag <label>]… catalog list [--kind …] [--status pending|approved|withdrawn] catalog approve <id> [<version>] [--kind …] catalog withdraw <id> [<version>] [--kind …] [--reason …] catalog verify [--kind …] catalog regenerate ``` `add` refuses: a duplicate id plus version or file name, an id already held by another author, a third skin of one author, a file that is too large, not a ZIP or holding an unsafe entry, a permission declared on a skin or a playlist, and a preview that is not a real image (recognised by its content). `verify` re-hashes every file wherever its state puts it, and `regenerate` rewrites `catalog.json` and `SHA256SUMS.txt`. ===== Page: Submit to the verified catalogue Address: https://prism.am/dev/online/submit/ Derived from: services/api/docs/CATALOG.md, services/api/src/controllers/catalog.rs, services/api/src/catalog/validate.rs, services/api/src/catalog/archive.rs, services/api/src/catalog/playlist.rs, services/api/src/catalog/store.rs, services/api/src/catalog/documents.rs, crates/downloader/src/repository.rs, apps/desktop/src/app/hosted.rs # Submit to the verified catalogue Build a mod, skin or playlist package, what the server checks and what the team reviews, how to send it from the game, and how updates and versions work. The catalogue (the Mods, Skins and Playlists sections of the game's Download page, and the site pages `/extensions/` and `/playlists/`) lists what players and the Prism team publish. A mod or a skin is sent **from the game**, signed in to your Prism account with a confirmed e-mail address: **Publish to prism.am** on the Mods or the Skins page. A playlist is still sent through the Contact page and added by the team. This page is what to prepare and what to expect. The contract of the list that results is on [Catalogue API](https://prism.am/dev/md/online/catalog.md). | | Mod | Skin | Playlist | |---|---|---|---| | File | `<id>-<version>.pvmod` | `<id>.zip` | `<name>.pvplaylist` | | Largest file | 2 MiB | 8 MiB | 1 MiB | | Sent from | the game's Mods page | the game's Skins page | the Contact page | | Public | after the team approves it | as soon as the checks pass | after the team approves it | | Per account | 5 mods | 2 distinct skin ids | no limit | | Permissions | those the mod declares | none | none | ## 1. Prepare the package {#prepare} ### A mod {#prepare-mod} 1. Write the mod as a folder with a `main.ts` ([first mod](https://prism.am/dev/md/first-mod.md)) and try it in the game. 2. Export it from the **Mods** page. You get `<id>-<version>.pvmod`, a ZIP of the folder ([how export works](https://prism.am/dev/md/formats/pvmod.md#export)). 3. Keep it **within 2 MiB**, with at most 256 files (the game's installer refuses more than 256 even though the server would take 512). Allowed files: `.ts`, `.ttf`, `.otf`, `.png`, `.json`, `.md`, `.txt`. `main.ts` or `index.ts` sits at the root or in the single top folder. 4. Choose a stable `id` and use the **same one** in `defineMod`: lowercase letters, digits and `-` `_` `.` inside, starting and ending with a letter or a digit, no `..`, 64 characters at most. The id identifies your mod for ever and is unique among mods. 5. Declare **only the permissions you need** (`stage`, `skinImport`, `network`). Players see them before they install. 6. Make sure `apiVersion` matches the game's current API (`2` today): see [Changes](https://prism.am/dev/md/help/changes.md). ### A skin {#prepare-skin} 1. Build the skin folder with a `skin.ts` ([first skin](https://prism.am/dev/md/first-skin.md)) and export it from the **Skins** page: `<id>.zip` ([how export works](https://prism.am/dev/md/formats/skin-package.md#export-import)). 2. Keep it **within 8 MiB**. Allowed files: `.ts`, `.png`, `.ttf`, `.otf`. **Remove the key sounds** (`wav`, `ogg`, `flac`, `mp3`): the game imports them, the catalogue server refuses them. 3. A skin has no permissions: a skin declaring one in the catalogue entry is refused. 4. One person may publish at most **2 distinct skin ids**. New versions of those skins do not count again; withdrawing a skin frees its place. ### A playlist {#prepare-playlist} 1. Build the playlist in the game and export it from the **Playlists** page: `<name>.pvplaylist`. 2. Keep it **within 1 MiB**, with at most **200 maps** and a name of 1 to 64 characters (no control characters, no space at either end). The server reads the file the way the game does: a newer format version is refused. 3. A playlist holds map identities, not maps: each entry names a chart by its content hash (`chart_hash`, see [hashes](https://prism.am/dev/md/formats/rox-and-hashes.md)) with its title, artist, difficulty and creator, and players need the maps to play it. ## 2. What is checked {#review} Two checks, in this order. **The server checks the file**, with the rules of the game's own importer, before anything is published. A file that fails is refused and nothing is stored: - the size, and a real ZIP archive (mod and skin); - safe relative paths (no absolute path, no `..`, no drive letter, no `\`), no symbolic link, no encryption, no duplicate name once case is ignored, allowed file types only, at most 1024 entries, 512 files, 16 MiB per file and 64 MiB unpacked, every entry holding the size it declares (read for real, so a zip bomb is refused); - the entry file: `main.ts` or `index.ts` for a mod, `skin.ts` for a skin, at the root or in the single top folder; - for a playlist, the JSON header, the version, the name and the number of maps; - the entry's texts: id, name (64 characters), author (64), version label (32), description (2000), permissions (8), tags (8 of 24 characters), screenshots (3 real images of 512 KiB at most). The server does not run your code. The permissions of a mod's entry are the ones its `defineMod` declares, sent by the game with the package; the team checks them against what the code does. **The team reviews the item.** A mod and a playlist stay **invisible** (state `pending`) until the team approves them. Nothing is served to the public before that, not even by guessing the file name. A skin is published as soon as it passes the checks. An approved item can be withdrawn later, at your request or if a problem appears. Refusals you can meet: an `id` plus `version` that already exist, a file name already used, an id already held by **another author**, a third skin or a sixth mod of one account, a permission declared on a skin or a playlist, more than 5 sends in an hour (10 in a day). The game shows each one in words. ## 3. Send it {#send} **A mod or a skin**: in the game, on the **Mods** or **Skins** page, choose **Publish to prism.am** on one of your own items (the game's shipped items cannot be sent), write a short description in English and send. The game builds the package as its Export does; the author shown is your account name. Offline mode sends nothing. **A playlist**: send the file through the [Contact page](https://prism.am/contact/) with its name, the author name to credit and a short description in English (and in French if you wish), as plain text. ## 4. Updates and versions {#updates} To publish an update, raise the version in `main.ts` or `skin.ts` and send again: the **same `id`** with a **new version label**. The label is free text, but the same `id` plus `version` twice is refused, and so is a file name already used. A version label is never compared by the server or the game. What orders versions is `seq`: an integer that strictly increases per kind, in publication order. Each approved version has its own `seq`, and the entry players see is the one with the highest. - The catalogue keeps **every approved version** in `versions[]`, newest first. A new version does **not** replace the old one on the server; it becomes the public version. - A new version of a **mod** is `pending` like the first one. Until the team approves it, the previous approved version stays the public one. - A new version of a **skin** is public as soon as it passes the checks. - Withdrawing a version removes it from the list. When no approved version is left, the item is gone from `GET /api/catalog`. - In the game, an installed item is an **update** when the catalogue's `seq` is greater than the one it was installed with. A mod update replaces the installed mod and keeps its enabled or disabled state. A skin update lands next to the old skin under a free folder name (`neon-2`): the game never overwrites a skin. A catalogue playlist is never an update: installing it adds a new playlist. ## 5. After approval {#approved} The item appears in the catalogue, in the game's Download page and on the site, with a mod's permissions shown before installation. A mod from the catalogue is installed **disabled**: the player turns it on from the Mods page, after reading what it asks for. ===== Page: Game updates (the player's side) Address: https://prism.am/dev/online/updates/ Derived from: docs/mises-a-jour.md, crates/updater/src/lib.rs, crates/updater/src/feed.rs, crates/updater/src/signature.rs, crates/updater/src/apply.rs, crates/updater/src/identity.rs, crates/updater/src/manifest.rs, crates/updater/src/whats_new.rs, crates/updater/src/net.rs, apps/desktop/src/app/updates.rs, apps/desktop/src/app/whats_new.rs, apps/desktop/src/app/install.rs # Game updates (the player's side) How the game finds, downloads, verifies and installs an update: channels, the daily list read, install on click, signature check, rollback, repair and what's new. Prism updates itself from the project's site, never from a code host. This page describes what the game does and what a player sees, so that a tool maker or a self-hosting server knows what to expect. The public contract of the list the game reads (`releases.json`) is on [Release list](https://prism.am/dev/md/formats/releases.md); this page does not repeat it. ## Channels {#channels} A Prism install belongs to one of two channels: | | `stable` | `pbe` | |---|---|---| | What it is | The release most players run. | Test builds, before they become stable. | | `channel` file (next to `prism.exe`) | `stable`, or absent | `pbe` | | Data folder | `%LOCALAPPDATA%\Prism\PrismNG\data` | `%LOCALAPPDATA%\Prism\PrismNG-PBE\data` | | Window title | `Prism` | `Prism PBE`, and a "PBE" badge in the drawer | The two channels run side by side, each with its own library, replays, mods, skins and themes. The `channel` file is read once at startup; it holds one word, and an absent or unusable file means `stable`. The channel is never compiled into the executable, which is how the same executable can be promoted from PBE to stable. Within a channel, versions are ordered by `seq`, an integer the site assigns at publication. The build label (`pbe.21`, say) is free text and is never compared. A game never downgrades: when the newest entry is older than what is installed, nothing happens. The player can pick another channel in **Settings → System → Updates**; its newest version is then always offered, with a warning that the **data folder changes** (`PrismNG` and `PrismNG-PBE` are different folders). ## When the game looks {#checking} - **One list read.** The only automatic thing the game does is read the release list: one `GET` of `https://prism.am/releases.json`, with no identifier, no version, no cookie, and the user agent `Prism-updater`. The setting **Check for updates automatically** is **on by default** for that reason. - **When.** The first check of each run happens a few seconds after the interface is ready, whatever the interval. After that, at most **once a day**. An attempt counts even when it fails, so a site that is down is not asked every hour. The player can also press **Check for updates** at any time. - **Never during play.** Every step waits while a chart plays, previews, or replays. A download in progress stops when a play starts; the partial file is kept and resumed. - **A newer version found at launch** opens a prompt: **Update now** downloads, installs and restarts in one click, **Later** closes it until the next launch. - A site that is down or not reachable shows "Updates unavailable" and nothing else. The address is `https://prism.am/releases.json` unless the player sets the **Release list address** (the environment variable `PRISM_UPDATE_FEED` wins). It must be `https` (plain `http` only for `localhost` or `127.0.0.1`), and **every** address the game then follows (the package, a redirect) must have the same scheme, host and port as the list. At most 3 redirects are followed, by the game itself. The channel, list address and check settings are not exported with the other settings. ## Download and install happen on click {#install} 1. **Download** starts only when the player asks. It shows progress and resumes after an interruption (`Range`). The size and the SHA-256 of the zip are checked against the list; a wrong file is deleted. 2. **Verification of the signature** comes next, before anything is unpacked (see below). 3. **Install** happens only when the player clicks **Restart to update**. The game moves the files into place, keeping what it replaces, and restarts itself. **Nothing is installed at launch** and nothing installs by itself: a downloaded update waits for the click. The folder of `prism.exe` must accept a file being created, written, renamed and deleted (that is what installing does) and `prism.exe` must not be read-only. If not, the game says "The install folder is not writable" **before** downloading a byte. Install Prism in a folder you can write to, not under `Program Files`. An attempt that failed is remembered by its identity (channel, `seq`, SHA-256) with its reason, and not offered again for 24 hours. After a restart the game shows it as failed and retries nothing by itself. The **Retry** button clears the memory and tries again. A build the game cannot identify (a development build, or one missing from the list) **never downloads or installs**. It shows "Unrecognised build", the newest release of its channel and the address of the download page to copy. ## Signature verification {#signature} Every release is signed by the author with [minisign](https://jedisct1.github.io/minisign/). The signature covers the zip itself, and its **trusted comment** binds the identity of the release: `channel=pbe seq=1 build=v0.1.0-pbe.1 sha256=<SHA-256 of the zip>`. The signature file is published next to the zip, at `<zip url>.minisig` (4 KiB at most), under the same host and redirect rules. The game checks it **after the download and before unpacking anything**: - the signature must be valid under a key the game trusts (the Prism key, id `EA2E569435832E2C`, is embedded in the executable) on the downloaded file; - the trusted comment must say **this** release: the channel, the `seq`, the SHA-256 of the file and the build label of the list entry. A genuine signature of another version (an older `seq`, another channel) is refused, so an old release cannot be replayed; - an absent, unreadable, truncated, other-key, modified-file or wrong-identity signature means **refusal**: the zip is deleted, nothing reaches the staging folder, and the interface says why. With a key embedded there is **no fallback to "unsigned"**. Only a build of a fork with no trusted key says "Unsigned". Once verified, **Settings → System → Updates** shows "Signed by Prism key <id>". The package must contain `prism.exe` and a `channel` file equal to the announced channel. It is unpacked under the usual archive rules (no `..`, no absolute path, no link). ## What changes on disk {#files} Everything stays next to `prism.exe`, never in the data folder (apart from the time of the last check): ```text update-staging/ the downloaded zip, the unpacked package, a marker "complete" update-backup/ every file the update replaced, as it was (the two newest backups are kept) update-state.json the installed version, a launch counter, the last rollback ``` Rules for the shipped folders (`mods\`, `skins\`, `themes\`): a file of the package **replaces** the same path (shipped content follows the game), and the old one is backed up when it differs. Anything the package does not contain is **never touched or deleted**: your own mods, skins and themes stay. A shipped file that a version removes stays on disk. **Automatic rollback.** A freshly installed version counts its launches. If it starts twice without ever reaching the interface, the third start puts the previous files back (the faulty ones go to `update-backup/<seq>/failed/`), the old version restarts, and **Settings → System** says so. An installation interrupted by a power cut or a killed process is undone at the next launch. A new executable that cannot even load cannot roll itself back: restore `update-backup/<seq>/files/prism.exe` by hand. ## Verify and repair the installation {#repair} **Settings → System → Updates → Verify installation** compares the shipped files of your install with the signed file list of its release (`FILES.sha256`, inside the zip and so covered by the signature). It changes nothing: it reads, counts and shows the differences (missing, modified, unreadable). Your mods, skins, themes, the data folder and any file not in the list are never read, flagged or deleted. - An install that predates this feature, or a damaged list, has nothing to compare: the game says so and offers no repair. An update writes a fresh list. - **Repair** downloads the installed release from the site (same access check, hash and signature as an update), unpacks it aside and puts back only the files you want. A missing file is always restored. A modified file is restored only if you tick **Also restore the files I changed** (unticked every time). Replaced files go to `update-backup/repair-<ms>/`, not deleted. - Repair is refused during a play and for an unrecognised build. If `prism.exe` was replaced, the game asks you to restart. ## What's new after an update {#whats-new} After an update (or a first launch), the game shows **once** the notes of the versions the player has not seen, read from the changelog installed next to `prism.exe` (`CHANGELOG.md`, or `CHANGELOG.fr.md` in French). No network is used. - The changelog is newest first; the game shows the sections newer than the last version seen, in that order. A version missing from the changelog shows only the running version; a downgrade shows nothing. - A first launch shows nothing and only remembers the version (`whats-new.json` in the data folder). A version already seen is never shown again. - It never appears during a play, a preview, a replay, training or skin editing: the window waits until the state is free. The menu is never blocked. - After an automatic rollback, nothing is shown. - A zip copied over the install by hand, with no `update-state.json`, counts as a first launch, so it is silent. - **Show what's new after an update** is on by default. The "What's new" link shows the notes of the installed version at any time, without remembering anything. - English and French read their own changelog; the other interface languages show the English text. The same notes are on the [site's changelog page](https://prism.am/changelog/), read from the release list. ===== Page: Troubleshooting Address: https://prism.am/dev/help/troubleshooting/ Derived from: crates/modding/src/manifest.rs, crates/modding/src/api.rs, crates/modding/src/runtime.rs, crates/modding/src/scene.rs, crates/modding/src/storage.rs, crates/modding/src/stage.rs, crates/modding/src/downloads.rs, crates/modding/src/dependencies.rs, crates/modding/src/judgement.rs, crates/modding/src/popup.rs, crates/modding/src/transform.rs, crates/modding/src/package.rs, crates/skin/src/archive.rs, crates/skin/src/package.rs, crates/modding/tests/host.rs, apps/desktop/src/app/mods.rs, docs/map-scripts.md # Troubleshooting Problems by symptom with the real message, its cause and the fix: a mod that is not listed or is disabled, declaration errors, budgets, permissions, skins and map scripts, packages. Look for your symptom, read the message, apply the fix. Messages are quoted from the code exactly; the part that depends on your script (an id, a number) is written between `<` and `>` or as an ellipsis. The limits behind them are in [Limits](https://prism.am/dev/md/help/limits.md). ## Where the errors are {#where} - The **Mods** page lists every mod folder with its state: **active**, **failed** (not loaded: invalid declaration, an error at load or in `setup`) or **disabled** (turned off by the player, or stopped after repeated errors). A failed or disabled mod shows its reason, and a **Messages** list shows what the scripts logged (`log.*`) and every error. - **Reload** restarts the mods host and retries every mod that failed. The game does not watch your files: after an edit, press **Reload**. Reload, install and uninstall are refused during a play ("Mods cannot be reloaded during a play"). - The errors of a map script appear in a banner at the map launch and in the same message list; the map is then played with the skin alone. - `console.log` goes to the process's standard error, not to the Mods page. Use `log.info`, `log.warn`, `log.error`. ## The mod is not listed {#not-listed} | Symptom | Cause | Fix | |---|---|---| | No card at all | The game reads one **folder per mod** in its mods folder. A folder is a mod only if it contains `main.ts` or `index.ts` at its root. | Open the folder from the Mods page (**Open folder**) and check the layout: `mods/<your-mod>/main.ts`, not `mods/<your-mod>/<another-folder>/main.ts`. | | No card, the folder is right | A folder whose name starts with `.` is ignored (the installer's staging folders). A folder whose name starts with `editor-` is skipped by the game: it belongs to the map editor. | Rename the folder. | | The card shows after a restart only | Nothing reloads by itself. | Press **Reload** on the Mods page. | | A mod just installed does nothing | A mod that arrives from the catalogue or by double-click is installed **disabled**. | Enable it on the Mods page, after reading its permissions. | | `Mods cannot be reloaded during a play` | Reload, install and uninstall wait for the end of a play. | Leave the play, then retry. | | The same id twice | See [the id messages](#declaration). | | ## The mod failed to load {#declaration} A failed mod shows its reason on the Mods page. The errors of the declaration come first, because `defineMod` is validated before anything runs. | Message | Cause | Fix | |---|---|---| | `` `<id>` requires modding API version 1; this game provides version 2 `` | `apiVersion` is not the game's (it must be **equal**). | Set `apiVersion: 2`. See [apiVersion](#apiversion). | | `` `id` must be 1 to 64 characters among a-z, 0-9, `.`, `-`, `_`, starting and ending with a letter or digit (e.g. `score-counter` or `com.example.score`), got "<id>" `` | The id breaks the id rules: uppercase, a space, a leading or trailing `-` or `.`, `..`, more than 64 characters. | Use a lowercase id such as `score-counter`. | | `` `version` must be a semantic version such as 1.0.0, got "1.0" (…) `` | `version` is not semver. | Write three numbers: `1.0.0`; a suffix is allowed: `1.0.0-beta.1`. | | `` unknown field `<field>`, expected one of … `` | `defineMod` got a field it does not declare (a typo, or a field of another contract). | Remove it or fix its name; the message lists the valid ones. | | `id: missing field` (or `name`, `version`, `apiVersion`) | A required field is missing. | Add it: `id`, `name`, `version` and `apiVersion` are required. | | `setup must be a function` | `setup` is declared but is not a function. | Give a function, or remove the field. | | `` `main.ts` must declare the mod with `export default defineMod({ … })` at its top level `` | The file never calls `defineMod` at its top level (inside a function, a condition or a callback). | Move the call to the top level: `export default defineMod({ … })`. | | `defineMod can only be called at the top level of the mod's entry file` | `defineMod` was called from a function, or from a file that is not the entry file. | Call it once, at the top level of `main.ts`. | | `defineMod must be called exactly once` | Two calls. The first error is kept even if you catch it. | Keep one call. | | `defineMod declares a mod: this skin declares itself with defineSkin` | A skin folder calls `defineMod`. | Use `defineSkin` in `skin.ts`. | | `` another mod already uses the id `<id>`: the folder `<other>` loaded first and keeps it `` | Two folders declare the same id. The game's own folder loads first, then the player's, each in folder-name order. | Rename one id. Ids are shared by mods and skins: `` the skin already uses the id `<id>` ``. | | `load failed` or the thrown error | The top-level code threw. | Fix the error. At load only `defineMod`, `log.*` and `ctx.on` exist. | | `` `hud.text` is not available while the mod loads: call it from `setup` or an event handler `` | A host function (`hud.*`, `storage.*`, `game.*`, `stage.*`…) ran at the top level. | Move the call into `setup` or a handler. | | `setup failed: …` | `setup` threw. | Fix the error; the other mods load normally. | A mod that uses packages also meets the dependency messages: | Message | Meaning | |---|---| | `` `uses` names N packages; the limit is 16 `` | Too many packages in `uses`. | | `a package cannot use itself` | A mod lists its own id. | | `dependency cycle: a → b → a` | Packages depend on each other; every package of the cycle is refused. | | `package <p> is not active` | The package you use is missing, failed or disabled. | | `package <p> 2.0.0 does not match ^1` | The package is there but its version is outside the range you asked for. | | ``feature "<name>" disabled: package <p> missing`` | An optional dependency is absent: only that feature is off. | | `` unknown option `<x>`, expected one of … `` | You configure an element option the package does not provide. | ### The `apiVersion` surprise {#apiversion} `apiVersion: 1` type-checks. In `modding.d.ts` the field is a plain `number`, so TypeScript cannot know the game's version. The game compares it for **equality** and refuses the script when it differs. The same goes for a skin and for a map script (`the map script requires modding API version <n>; this game provides version 2`). See [Versions and changes](https://prism.am/dev/md/help/changes.md#mod-api). ## The mod was disabled {#disabled} | Message on the Mods page | Cause | Fix | |---|---|---| | `exceeded the 30ms execution budget <n> times` | The script spent more than 30 ms in a handler three times (the count is cumulative). | Do less per event: precompute in `setup`, do not loop over big arrays on every tick. See [budget](#budget). | | `failed 3 times in a row; last error: …` | A handler threw three times without a success in between. | Read the last error and fix it, or catch it. | | `interrupted after exceeding the 30ms execution budget (…)` | A single call hit the budget and was stopped. It is also what each of the three timeouts reports. | As above. | A disabled mod loses its HUD, judgement sets, scroll systems and ratings, and its storage is written once. A **mod** stays off until the host restarts (**Reload** or restarting the game). A **skin** or a **map script** stays off until the next map launch. ### Execution budget {#budget} Each script gets **30 ms** per load, `setup`, event handler or tick, **16 MiB** of memory and a 1 MiB stack. These are real-time limits: a slow machine hits them sooner. Time is counted per call, not per frame, but a `game.tick` handler runs 30 times a second. Keep handlers small, do the heavy work once in `setup`, and read at most what you need (`game.notes({ limit })`). The full list is in [Limits](https://prism.am/dev/md/help/limits.md#budgets). ## HUD, stage and storage limits {#limits-errors} | Message | Cause | Fix | |---|---|---| | `the HUD node limit is 384 per mod` | You created a 385th node. | Reuse nodes (update the same `id`), remove the ones you no longer show, or group. | | `node id must have 1 to 64 characters, without control characters` | A bad HUD node id. | Shorten it. | | `` node `<id>` already exists under another parent; remove it to move it `` | You re-created a node under a different parent. | Remove it first, or keep its parent. | | `groups nest at most 8 levels deep` | Groups are too deep. | Flatten. | | `storage keys must have 1 to 128 characters` | An empty or very long storage key. | Use short keys. | | `the storage holds at most 256 keys` | A 257th key. | Store one object under one key. | | `the storage holds at most 262144 bytes; this value would bring it to <n>` | The mod's 256 KiB of storage is full. | Store less; delete old keys. | | `storage <path>: …` | The mod's storage file is corrupt or too big, so `setup` fails. | Delete `mod-storage/<id>.json` in the data folder, or fix it. | | `popup title, detail, progress or actions exceed their bounds` | `ui.popup` called with too much. | Title 1 to 96 characters, detail up to 512, up to 4 actions, `done` at most `total`. | | `at most eight mod popups may be open` | Too many popups open at once. | Close some before opening more. | | `invalid or duplicate popup action` | An action id is empty, longer than 32, reserved (`dismiss`), repeated, or has characters other than `a-z 0-9 _`. | Fix the ids. | | `` limit must be in [1, 256], got <n> `` | `game.notes` or `game.hits` asked for a limit out of range. | Ask for 1 to 256. | ## Permissions {#permissions} A mod must declare what it uses in `permissions`, and the player can take `stage` and `network` away mod by mod. `skinImport` is removed by disabling the mod. | Message | Cause | Fix | |---|---|---| | `` `<function>` needs the `stage` permission: declare `permissions: ["stage"]` `` | You called `stage.*` without declaring it. | Add `permissions: ["stage"]`. | | `` `<function>`: the player turned off native drawing for `<id>` `` | The player took the permission away on the Mods page. | Nothing to fix in the code: handle the refusal, and tell the player what the mod needs. | | `` `skinImport` needs the `skinImport` permission: declare `permissions: ["skinImport"]` `` | `skinImport.*` without the permission. | Declare it. | | `` `<function>` needs the `network` permission: declare `permissions: ["network"]` `` | `downloads.register` without the permission. | Declare it. | ## Skins and map scripts {#skins-scripts} | Message | Cause | Fix | |---|---|---| | `` `skin.ts` must declare the skin with `export default defineSkin({ … })` at its top level `` | The skin's entry file has no top-level `defineSkin`. | Add it. A skin's entry file is `skin.ts`. | | ``the map script must declare itself with `export default defineChart({ … })` at its top level`` | The map script has no top-level `defineChart`. | Add it. | | `defineChart must be called exactly once` | Two calls. | Keep one. | | `` `<function>` is not available to map scripts: they only change the playfield `` | A map script called `hud.*` or `storage.*`. | A map script changes the playfield only: use `playfield.*`. | | `` `<function>` is only available to skins and map scripts `` | A mod called `playfield.*`. | Do that in a skin or a map script. | | ``the playfield only changes while a chart plays: call it from a handler between `game.songStart` and `game.songEnd` `` | `playfield.*` called in `setup` or outside a play. | Call it from a handler during a play. | | `` `<function>` is not available while the skin loads: call it from `setup` or an event handler `` | A host function at the top level of a skin. | Move it to `setup`. | | `declare the package before configuring elements` | `ctx.element(…).configure` in a map script: it has no `uses`, so it cannot configure elements. | Configure elements from a skin or a mod. | A map script lives next to its chart: `script.ts` for every difficulty of the folder, or `<chart file name>.script.ts` for one difficulty, 1 MiB at most. It is read again at every launch of the map. The player can turn all map scripts off (**Settings → Gameplay → Allow map scripts**, on by default). A map script that fails never stops the map: it plays with the skin alone. A skin's `setup` and the wait for `chart.transform` are capped at 1000 ms: past that the map plays unchanged ("…: the map plays unchanged"). For a `chart.transform` mod: | Message | Cause | |---|---| | `` chart.getNotes is only available inside a `chart.transform` handler `` (same for `setNotes`) | The call is outside the transform handler. | | `` chart.setNotes refused the buffer: … `` | The notes you returned break a rule: more than 100 000 notes, a column at or above the key count, a time outside the map, a hold ending before it starts, two notes starting together in a column. | ## TypeScript passes but the game refuses {#ts-passes} The SDK describes **shapes**. The game checks **values and moments**, and that is where a script that compiles can still be refused: - `apiVersion` is a `number`: `1` compiles and is refused ([above](#apiversion)). - Ids, names and texts are `string`: the id rules, the 1 to 32 or 64 character bounds and the closed lists (icons, groups) are checked at runtime. - Numbers are `number`: ranges (`layout.x` between ±10, a `size` in (0, 1], 2 to 8 gradient stops) are checked at runtime. - Phases: `hud.text(…)` type-checks at the top level and throws there. - Limits: 384 nodes, 256 storage keys, 30 ms per call: nothing in the types. - Closed sets: the game declares `mirror`, `noLn` and `rankedFullLn` in `GameplayModifierKind`, yet `gameplay.register` refuses them ("Mirror is built into Prism: a mod cannot declare it"). - Unknown fields: TypeScript (excess property check) usually catches them, but a spread or an `as` cast hides them from it, and the game refuses `` unknown field `<field>` ``. - Dynamic `import()` is not supported: use a static `import`. - `Date` and the rest of plain JavaScript are available, so a script is not deterministic. Only `chart.getNotes().seed` is seeded. Run `tsc --strict` against [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts) as a first filter, then try the mod in the game: the Mods page is the second check. ## Package import errors {#packages} A `.pvmod` or a skin `.zip` is checked entirely before it is written. A failed install leaves your folders as they were. The error comes with a prefix: `invalid mod package: …`, `invalid skin package: …`, or `the mod does not load: …` when the declaration inside is invalid. | Message | Cause | Fix | |---|---|---| | `not a ZIP archive (…)` | The file is not a ZIP (renamed, truncated). | Export it again. | | `the package weighs <n> bytes; the limit is <m>` | Over 64 MiB. | Remove what you do not need. | | `the package has <n> entries; the limit is <m>` | More than 1024 entries. | Remove files and folders. | | `the package holds more than 256 files` (mod) / `512 files` (skin) | Too many files. | Remove files. | | `` "<path>" weighs <n> bytes; the limit is <m> `` | One file is over 16 MiB (mod) or 32 MiB (skin). | Compress it or drop it. | | `the files weigh more than <n> bytes` | More than 64 MiB unpacked. | Remove files. | | `` "<path>" cannot be in a package: allowed files are .ts, .ttf, … `` | A forbidden file type (`.psd`, `.mp3` in a mod). | Remove it. A skin may carry sounds for the game; the catalogue may not. | | `` "<path>" is a symbolic link `` / `` is encrypted `` / `` appears twice `` | A link, an encrypted entry, or two names that differ only by case. | Remove the link, repackage without a password, rename. | | `unsafe entry: …` | An absolute path, `..`, a drive letter or a backslash. | Repackage from the folder itself. | | `no main.ts or index.ts at the root of the package` (skin: `no skin.ts …`) | The entry file is missing, or sits in a folder that is not the only top folder. | Put it at the root. | | `` the game's own folder <dir> already holds the mod `<id>`; uninstall or edit it instead `` | A mod of the same id is shipped with the game. | Pick another id. | | `` the folder <dir> holds another mod (`<id>`); rename it first `` | An `<id>` folder is already used by another mod. | Rename it. | | `` no installed mod has the id `<id>` `` | Uninstall or export of something not installed. | Reload the Mods page. | The rules and the formats are in [`.pvmod`](https://prism.am/dev/md/formats/pvmod.md) and [skin package](https://prism.am/dev/md/formats/skin-package.md). For what the catalogue refuses on top of that, see [Submit](https://prism.am/dev/md/online/submit.md) and [Catalogue API](https://prism.am/dev/md/online/catalog.md). ## Online and update symptoms {#online} | Symptom | Cause | Fix | |---|---|---| | HTTP `429` with `rate_limited` | You went over a bucket's 240 per minute (catalogue 120, accounts 60). | Wait `Retry-After` seconds; use `ETag`. See [rate limits](https://prism.am/dev/md/online/api.md#rate-limits). | | HTTP `401` with `invalid_token` | The access token (600 s) expired or is missing. | Refresh it with the refresh token, then retry once. | | HTTP `400` with `bad_request` | A malformed hash or parameter; `description` names it. | Fix the parameter. | | Catalogue item shows no description in the game | The server sends `descriptionEn`; the game reads `description`. | See the warning in [Catalogue API](https://prism.am/dev/md/online/catalog.md#list). | | "Updates unavailable" | The release list could not be read. | Retry later. See [Game updates](https://prism.am/dev/md/online/updates.md). | | An update is refused with a signature message | The `.minisig` is absent, invalid, or names another release. | Nothing on the player's side: the release must be re-published. | | "The install folder is not writable" | Prism sits in a folder the player cannot modify. | Move it to a user folder (not `Program Files`). | ===== Page: Limits and budgets Address: https://prism.am/dev/help/limits/ Derived from: crates/modding/src/host.rs, crates/modding/src/runtime.rs, crates/modding/src/api.rs, crates/modding/src/scene.rs, crates/modding/src/storage.rs, crates/modding/src/entities.rs, crates/modding/src/keys.rs, crates/modding/src/manifest.rs, crates/modding/src/dependencies.rs, crates/modding/src/judgement.rs, crates/modding/src/modifiers.rs, crates/modding/src/controls.rs, crates/modding/src/tabs.rs, crates/modding/src/ratings.rs, crates/modding/src/scroll_speed.rs, crates/modding/src/importers.rs, crates/modding/src/library.rs, crates/modding/src/leaderboard.rs, crates/modding/src/popup.rs, crates/modding/src/fonts.rs, crates/modding/src/assets.rs, crates/modding/src/package.rs, crates/stage/src/scene.rs, crates/stage/src/element.rs, crates/skin/src/package.rs, crates/skin/src/library.rs, crates/skin/src/paths.rs, crates/skin/src/spec.rs, crates/skin_import/src/source.rs, crates/downloader/src/declared.rs, crates/downloader/src/bridge.rs, crates/downloader/src/repository.rs, crates/replay/src/formats/replay_file.rs, crates/replay/src/formats/share.rs, crates/core/src/chart_identity.rs, crates/core/src/playlist.rs, crates/core/src/playlist_share.rs, crates/core/src/marathon.rs, crates/core/src/scripted_notes.rs, crates/db/src/playlist.rs, crates/updater/src/feed.rs, crates/updater/src/lib.rs, crates/updater/src/net.rs, crates/updater/src/signature.rs, crates/online_protocol/src/lib.rs, apps/desktop/src/app/skins.rs, apps/desktop/src/app/playback.rs, services/index/src/lib.rs, services/api/src/catalog/validate.rs, services/api/src/catalog/archive.rs, services/api/src/app.rs, services/api/src/controllers/perf.rs, services/api/src/accounts/settings.rs, deploy/Caddyfile # Limits and budgets Every limit and budget of the modding API, packages, replays, the catalogue and the online API, grouped, each with the source file that enforces it. The numbers below are read from the code. A limit is enforced by the file in the last column; when a number looks wrong to you, that file is the truth. Messages you see when you cross a limit are in [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md). Sizes use MiB (1024 × 1024 bytes) and KiB. In the last column, a path is relative to `crates/`, except `api/` (`services/api/src`), `index/` (`services/index/src`) and `desktop/` (`apps/desktop/src/app`). ## Script budgets {#budgets} A script is a mod, a skin or a map script. These budgets bind each script on the `mods` thread. | Limit | Value | Source | |---|---|---| | Execution time of one load, `setup`, event handler or tick | 30 ms | `modding/host.rs` (`ModLimits`) | | Memory of one script | 16 MiB (shipped mods share one engine whose reserve is 16 MiB × their number) | `modding/host.rs`, `runtime.rs` | | Stack | 1 MiB | `modding/host.rs` | | Disabled after | 3 failures in a row, **or** 3 timeouts in total | `modding/host.rs`, `runtime.rs` | | A disabled mod stays off | until the host restarts (a skin or map script: until the next map launch) | `modding/runtime.rs` | | Skin `setup` and the wait for `chart.transform` | 1000 ms each | `desktop/skins.rs`, `playback.rs` | | Event queue to the script thread | 1024 | `modding/host.rs` | | Message queue (log lines, errors) | 256; the rest is dropped and counted | `modding/host.rs` | | One log line | 1024 characters, then cut with `…` | `modding/api.rs` | | `game.tick` | 30 per second | `modding/host.rs` | | `chart.transform`: notes read or submitted | 100 000 | `core/scripted_notes.rs` | | `chart.transform`: mods transforming one play | 8 | `core/scripted_notes.rs` | | `ui.popup`: title / detail / actions | 96 / 512 characters / 4 | `modding/popup.rs` | | `ui.popup`: open at once per game | 8 | `modding/api.rs` | | `ui.popup`: `total` of a progress | 10 000 000 | `modding/popup.rs` | Timers and `ctx.hot` are declared by the SDK but are not driven by the game: callbacks of `setTimeout` and `setInterval` never run. Do not rely on them. ## HUD and native drawing {#hud-stage} | Limit | Value | Source | |---|---|---| | HUD nodes per mod | 384 | `modding/host.rs`, `scene.rs` | | Characters of one HUD text | 256 (control characters other than `\n` and `\t` are refused) | `modding/host.rs`, `scene.rs` | | Node id | 1 to 64 characters, no control character | `modding/scene.rs` | | Group depth | 8 | `modding/scene.rs` | | Gradient stops | 2 to 8 | `modding/scene.rs` | | `animate` duration | 1 to 5000 ms | `modding/scene.rs` | | `transitionMs` | 10 000 at most | `modding/scene.rs` | | Tier colors of a binding | 64 entries, keys of 32 characters | `modding/scene.rs` | | HUD image (`src`) | PNG, 8 MiB | `modding/assets.rs` | | Declared images (`images`) | 64 `.png` paths | `modding/manifest.rs` | | Fonts per mod | 8, 8 MiB each, name 64 characters | `modding/fonts.rs`, `assets.rs` | | Native elements per script (`stage.*`) | 128 | `stage/scene.rs` | | Emitters per script | 16 | `stage/scene.rs` | | Live particles per script | 1024 (512 per emitter, 256 per burst) | `stage/scene.rs`, `element.rs` | | Triggers / queued cues | 64 / 64 | `stage/scene.rs` | | Native element text | 128 characters | `stage/element.rs` | | Animations per element | 8, each up to 10 s | `stage/element.rs` | | Particle lifetime | 5 s | `stage/element.rs` | | Native element id | 64 characters | `stage/element.rs` | | Column of a native element | below 32 | `stage/element.rs`, `skin/spec.rs` | ## Storage and reads {#storage} | Limit | Value | Source | |---|---|---| | Storage key | 1 to 128 characters | `modding/storage.rs` | | Keys per mod | 256 | `modding/storage.rs` | | Storage of one mod (keys plus JSON text) | 256 KiB | `modding/host.rs` | | Storage writes | at most once per second, and when the host stops | `modding/storage.rs` | | `game.notes` `limit` | 1 to 256 (64 by default) | `modding/entities.rs` | | `game.hits` `limit` | 1 to 256 (50 by default) | `modding/entities.rs` | | `game.keys` `limit` | 0 to 256 (64 by default); only lanes 0 to 15 are recorded | `modding/keys.rs` | | Timing points of a `Song` | 1024 | `modding/entities.rs` | | `leaderboard` `limit` / `offset` | 1 to 100 (20 by default) / 0 to 100 000 | `modding/leaderboard.rs` | | Pending leaderboard queries | 2 per mod, 16 in total | `modding/leaderboard.rs` | | Charts scoped by `library.chartsAdded` | 8192 ids | `modding/library.rs` | | Pending rating backfills | 16 per mod, 64 in total | `modding/library.rs` | ## Ids and manifest {#ids} | Limit | Value | Source | |---|---|---| | Mod and skin `id` | 1 to 64 characters among `a-z 0-9 . - _`, starting and ending with a letter or digit, no `..`, valid as a Windows file name | `modding/manifest.rs` | | Strict ids (judgement sets and tiers, gameplay modifiers, control actions, ratings, tabs, download declarations) | 1 to 32 characters among `a-z 0-9 -` | `modding/judgement.rs` (`check_id`) | | Package element name | `[a-z0-9-]`, 1 to 32 characters, starting with a letter | `modding/dependencies.rs` | | `name`, `author` | 64 characters each | `modding/manifest.rs` | | `description` | 1024 characters (line breaks allowed) | `modding/manifest.rs` | | `homepage` | `http` or `https`, 256 characters, no whitespace | `modding/manifest.rs` | | `version` | a semantic version (`1.0.0`, `1.0.0-beta.1`) | `modding/manifest.rs` | | `loadOrder` | 0 to 10 000 (1000 by default) | `modding/manifest.rs` | | Permissions | `stage`, `skinImport`, `network` | `modding/manifest.rs` | | Packages in `uses` | 16 | `modding/dependencies.rs` | | Elements provided per package | 16, with 32 options each | `modding/dependencies.rs` | | Enum option values / string `maxLength` | 32 / 256 | `modding/dependencies.rs` | | Elements a player may override | 256 | `modding/dependencies.rs` | ## What a mod may register {#registries} Registrations happen in `setup` only and are capped per mod. Extra tabs and extensions beyond the global totals are dropped. | Registry | Per mod | Other bounds | Source | |---|---|---|---| | Judgement sets | 8 | 8 params; 32 tiers plus Miss; set name 64, id 32; at most 4096 combinations built eagerly | `modding/judgement.rs` | | Gameplay modifiers | 8 | name 32, description 200, 8 conflicts; a `noteMask` modifier declares 8 sliders (id 32 letters and digits, label 32, description 200, bounds within ±1000000) | `modding/modifiers.rs` | | Control actions | 32 | name 64 | `modding/controls.rs` | | Scroll speed systems | 8 | name 64, 4096 values | `modding/scroll_speed.rs` | | Tabs | 4 (12 in total) | title 24, 8 panels per tab, text 280, 10 leaderboard rows | `modding/tabs.rs` | | Tab extensions | 4 (24 in total) | 4 panels each | `modding/tabs.rs` | | Ratings | 16 | 4 panels, 16 fields, 12 patterns, 16 color stops | `modding/ratings.rs` | | Download declarations | 4 (64 in total) | 8 hosts, rate up to 120 per minute, page size up to 100, 16 params | `downloader/declared.rs` | | Download bridge | | 6 requests, 60 s, 2 MiB per answer, 64 KiB body, 256 KiB per step, 8 KiB state, 100 results, 12 headers | `downloader/bridge.rs` | | `skinImport` importers | 4 | panel of 6 sections × 24 rows, 48 notes, 16 badges, 6 tiles, 4 actions | `modding/importers.rs` | ## Packages {#packages} | Limit | `.pvmod` | Skin `.zip` | Source | |---|---|---|---| | Package file | 64 MiB | 64 MiB | `modding/package.rs`, `skin/package.rs` | | Entries | 1024 | 1024 | same | | Files | **256** | 512 | same | | One file, unpacked | 16 MiB | 32 MiB | same | | All files, unpacked | 64 MiB | 64 MiB | same | | Path | 200 characters, 8 levels | the same | `skin/paths.rs` | | Entry file | `main.ts` or `index.ts` | `skin.ts` (1 MiB) | `modding/package.rs`, `skin/library.rs` | | Allowed files | `ts ttf otf png json md txt` | `ts png ttf otf wav ogg flac mp3` | same | | In a skin: one PNG / one font | | 4 MiB / 8 MiB | `skin/library.rs`, `modding/assets.rs` | The osu! skin converter reads a `.osk` with its own bounds (`skin_import/source.rs`): archive 512 MiB, 8192 entries, 64 MiB per entry, 1 GiB in total, folders 6 levels deep, 4096 images, 64 frames; `skin.ini` 2 MiB, 64 mania blocks, 32 keys; 8 layouts. ## Replays, playlists, marathons {#replays} | Limit | Value | Source | |---|---|---| | `.pvreplay` file | 8 MiB; 32 MiB once decompressed | `replay/formats/replay_file.rs` | | Inputs in a replay | 2 000 000 | `replay/formats/replay_file.rs` | | Metadata JSON of a replay | 1 MiB | `replay/formats/replay_file.rs` | | Input time | within 24 h of the song's zero | `replay/formats/share.rs` | | Texts / names / extensions in a shared file | 256 / 64 / 32 | `core/chart_identity.rs`, `replay/formats/share.rs` | | Playback rate | 0.5 to 2 | `replay/formats/share.rs` | | `.pvplaylist` file | 1 MiB | `core/playlist_share.rs` | | Maps in a shared playlist | 200 | `core/playlist.rs` | | Maps in a playlist of the library | 10 000 | `db/playlist.rs` | | Playlist name | 1 to 64 characters | `core/playlist.rs` | | Playlists in a library | 256, plus one per pack | `db/playlist.rs` | | Playlist share code | 512 KiB of text | `core/playlist_share.rs` | | `.pvmarathon` file | 256 KiB | `core/marathon.rs` | | Maps in a marathon / creator | 200 / 64 characters | `core/marathon.rs` | ## Catalogue {#catalogue} The server and the game apply different limits to the same package; see the [side-by-side tables](https://prism.am/dev/md/online/catalog.md#limits). | Limit | Value | Source | |---|---|---| | Package published by the server | mod 2 MiB, skin 8 MiB, playlist 1 MiB | `api/catalog/validate.rs` | | Package the game accepts from the list | mod 64 MiB, skin 256 MiB, playlist 1 MiB | `downloader/repository.rs` | | Archive checked by the server | 1024 entries, 512 files, 16 MiB per file, 64 MiB unpacked | `api/catalog/archive.rs` | | Skins per author | 2 distinct ids | `api/catalog/validate.rs` | | Server text caps | id 64, name 64, author 64, version 32, description 2000 | `api/catalog/validate.rs` | | Permissions / tags / screenshots (server) | 8 / 8 of 24 characters / 3 of 512 KiB | `api/catalog/validate.rs` | | What the game keeps | name and author 80, version 32, description 600, 8 tags, 6 screenshots | `downloader/repository.rs` | | The list the game reads | 1 MiB, 500 items | `downloader/repository.rs` | ## Online API and updates {#online} | Limit | Value | Source | |---|---|---| | Public reads | 240 per minute per bucket and address | `api/app.rs`, config | | Catalogue | 120 per minute per address | `api/app.rs`, config | | Accounts (`/api/auth/*`) | 60 per minute per address | `api/app.rs` | | Performance reports | 4 per minute per address | `api/controllers/perf.rs` | | Request body on the public host | 64 KB; profile picture 5 MiB; osu! import file 1 MiB | `deploy/Caddyfile` | | Access token / refresh token | 600 s / 30 days | `api/accounts/settings.rs` | | Access token read by the game server | 2048 bytes | `online_protocol/lib.rs` | | Board and ranking pages | `limit` 1 to 100, `offset` up to 10 000 | OpenAPI | | Chartset and marathon lists | `perPage` 1 to 60 (24 by default) | OpenAPI | | Chart index key counts | 4 to 9 | `index/lib.rs` | | Release list read by the game | 4 MiB; package 1 byte to 1 GiB; notes cut at 16 KiB | `updater/feed.rs` | | Signature file | 4 KiB | `updater/signature.rs` | | Redirects followed | 3, same host | `updater/net.rs`, `downloader` | | Automatic update check | at most once a day (the first of each run is immediate) | `updater/lib.rs` | ===== Page: Versions and changes Address: https://prism.am/dev/help/changes/ Derived from: crates/modding/src/events.rs, crates/modding/src/manifest.rs, crates/themes/src/api.rs, crates/online_protocol/src/lib.rs, crates/replay/src/formats/replay_file.rs, crates/core/src/playlist_share.rs, crates/core/src/marathon.rs, services/api/types/src/lib.rs, docs/changelog/README.md, CHANGELOG.md, services/website/src/lib/pages/Changelog.svelte # Versions and changes Which version numbers exist in Prism, how the mod API and the theme API are versioned, what a mismatch does, what counts as breaking, and where the release notes live. Prism has several contracts, each with its own version number. This page lists them, says what each does when it does not match, and says where to read what changed. ## The version numbers {#numbers} | Contract | Where you write it | Today | When it does not match | |---|---|---|---| | **Mod API** (mods, skins, map scripts) | `apiVersion` in `defineMod`, `defineSkin`, `defineChart` | `2` | The script is **not loaded**. Equality, not a minimum. | | **Theme API** | `themeApi` in `theme.json` (optional) | `1` | A theme that asks for a **newer** version is refused; an older one loads; absent means 1. | | **Editor API** (map editor mods) | `apiVersion` in `defineEditorMod` | `1` | A separate number from the mod API; the editor declarations are their own block of `modding.d.ts`. | | **Game protocol** | `PROTOCOL_VERSION`, negotiated by `features` | `1` | There is no v2: messages are additive and features are negotiated. See [online API](https://prism.am/dev/md/online/api.md#game-protocol). | | **Catalogue** | `schema` of `GET /api/catalog` | `1` | No v2: readers ignore unknown fields. | | **Release list** | `schema` of `releases.json` | `1` | See [Release list](https://prism.am/dev/md/formats/releases.md). | | **Replay** (`.pvreplay`) | the byte after the `PVRZ` magic | `1` | A newer file: "The replay was made by a newer version of the game". | | **Playlist, marathon** | `version` of the JSON | `1` | A newer file is refused with "…made by a newer version of the game" (playlist) or "…needs a newer Prism" (marathon). | | **Hashes** | `noteHashVersion`, `HASH_VERSION` | `1` | A stored hash of another version is recomputed. | A package also has its own **semantic version** (`version: "1.2.0"`). That one is the author's: it orders the releases of one mod, and other packages can require a range of it with `uses` (see [Concepts](https://prism.am/dev/md/concepts.md)). ## The mod API: `apiVersion` {#mod-api} The game speaks one version of the mod API (`API_VERSION`, `2` today). A mod, a skin or a map script declares the version it was written for, and it must be **equal**: ```text `my-mod` requires modding API version 1; this game provides version 2 the map script requires modding API version 1; this game provides version 2 ``` The first message is what the Mods page shows for a mod or a skin written for another version; the second is for a map script. The script is not loaded and the rest of the game goes on. Nothing is run, so no half-working state exists. TypeScript cannot catch this: in `modding.d.ts` the field is a plain `number`, so `apiVersion: 1` type-checks and the game refuses it. See [Troubleshooting](https://prism.am/dev/md/help/troubleshooting.md#apiversion). The SDK file is generated from the Rust contracts of the game and its first line names the version it describes (`// Modding API version 2.`). The [SDK reference](https://prism.am/dev/md/reference/sdk.md) states the version of the page you are reading. To move a mod to a new version: 1. Download the `modding.d.ts` of the game version you target ([modding.d.ts](https://prism.am/dev/sdk/modding.d.ts)) and replace the one your project uses. 2. Run `tsc`: every function, event, field or type that changed or went away is now an error. 3. Fix those, then set `apiVersion` to the new number. 4. Try the mod in the game and read the Mods page for load errors. Declare `apiVersion` as the number written in the SDK header, not as a range: a mod cannot say "2 or later". ## The theme API: `themeApi` {#theme-api} A theme says which version of the theme contract it was written for with `"themeApi": 1` in `theme.json`. The game speaks one version, `THEME_API`, which is `1` today. - Absent, the field means 1: every theme written before it existed. - A value that is not a whole number from 1 is refused, and the message says what was found. - A theme that asks for a **newer** version than the game speaks is refused with one sentence: `themeApi N is newer than this game speaks (theme API M): update the game, or use a version of the theme written for API M`. - A theme that asks for an **older** version loads for as long as the game can still read it. A second version of the theme contract is planned: when the contract needs a change that would break themes, it becomes theme API 2, published **next to** API 1 for as long as the game can keep both. Until it ships, write `"themeApi": 1`. The rules are in [Interface themes](https://prism.am/dev/md/themes.md#versions) and the list of what needs a new version is in [what a new version means](https://prism.am/dev/md/themes.md#new-version). ## What counts as breaking {#breaking} For **themes** the contract is written down. These stay inside a version and never break a theme: adding an input path, an output, a node kind or a property, widening a limit, changing what a theme cannot see. These need a new version: removing or renaming a path, a part, a token, a node kind or a property, changing the type of a path, making an optional place required. For **mods, skins and map scripts**, the contract is the SDK file shipped with the game. What the game can do is compare `apiVersion`; everything else is checked while the script runs. So, for your script: - **Adding** to the SDK does not touch a script that does not use it: a new function, event, optional field or enum value. - **Removing, renaming or retyping** a function, event, field or value you use makes the script fail where you use it, with an error on the Mods page. If the API version changed, the script is refused at load instead. - **Tightening a limit** (a smaller budget, a shorter text) makes a script that sat close to the old limit fail with the usual validation error. The numbers are in [Limits](https://prism.am/dev/md/help/limits.md). Read the diff of `modding.d.ts` between two game versions: it is generated, so it is exact. ## Where the release notes are {#changelog} Release notes are written for players, in plain words, once per release, in English and in French. | Where | What | |---|---| | [`/changelog/`](https://prism.am/changelog/) (French: `/fr/changelog/`) | The notes of every release of each channel, read from the release list. | | In the game: **Settings → System → Updates → What's new** | The notes of the installed version, and the notes of what you have not seen after an update. | | `CHANGELOG.md` and `CHANGELOG.fr.md` | The full log, newest first, installed next to `prism.exe` and kept in the repository. | | `docs/changelog/v<version>.en.md`, `.fr.md` | The body of the notes of one version, as published. | A version of the log has sections **New**, **Improved**, **Changed**, **Fixed** and **Known limits**. The top section, `[Unreleased]`, is the work not shipped yet. The log is about what changes for a player and is written in player words (a check refuses developer jargon), so it rarely names an API call. For the developer side, the sources are the generated SDK (its header and its diff), the [SDK reference](https://prism.am/dev/md/reference/sdk.md), and these pages, which are generated from the code and the SDK. When a mod or a theme stops working after an update, check in this order: the Mods page (or the theme error shown with its file and reason), the `apiVersion` or `themeApi` number against this page, then the changelog entry of the version that updated. ===== Page: Interface themes Address: https://prism.am/dev/themes/ Derived from: docs/themes.md, crates/themes/src/library.rs, crates/themes/src/api.rs, crates/skin/src/shipped.rs, apps/desktop/src/app/interface_themes.rs, apps/web/src/theme/themes.ts # Interface themes What a theme is, what it can and cannot change, the files of a theme folder, where themes are found, and how the theme contract is versioned. An interface theme is the look and the layout of the game's menus: Stage, Classic, Cabinet, Carousel and the others are themes. A theme is a plain folder, read from disk like a mod or a skin. Delete the folder and the theme is gone. The player picks one in **Skins → Interface** (the setting `uiTheme`, whose value is the theme's id). This section is the reference for writing one. If you have never made a theme, start with the [quick start](https://prism.am/dev/md/themes/quick-start.md): a first theme takes ten minutes. ## What a theme is {#what-is-a-theme} A theme is **data**, never code that runs while the game draws. Scripts have no access to the DOM, the CSS or the JavaScript of the game's web view, and every value that enters the page is validated in Rust first. So a theme is made of: - a manifest (`theme.json`) that names it; - a token file (`tokens.css`): colours, fonts, shapes, durations and layout words, in a strict subset of CSS; - optionally a stylesheet (`theme.css`) for the theme's own classes, in a validated subset of CSS; - optionally a template script (`theme.ts`) that decides where the parts of a screen stand. It runs **once**, when the theme loads, and returns a tree of nodes from a closed list. That tree is data too, validated against the contract of the screen; - pictures. The `themes` crate (`crates/themes`) validates the folder and the host publishes only what passed to the page. A theme cannot execute or load anything. ## What a theme can change {#can-change} | Level | What you write | What it changes | | --- | --- | --- | | Tokens | `tokens.css` | Every colour, font, size, shape of plates and buttons, duration, easing, and the layout words (`--pv-layout-*`: which side the list is on, where the tabs go, how rows look). The full list is the [token reference](https://prism.am/dev/md/themes/tokens.md). | | Styles | `theme.css` | The look of the theme's own classes, and of the game's elements through their `data-*` marks. See [theme.css](https://prism.am/dev/md/themes/css.md). | | Templates | `theme.ts` | The structure of a templated screen: which places stand where, how they are wrapped, what extra facts are shown, and the inside of list cards (faces). See [templates](https://prism.am/dev/md/themes/templates.md). | | Pictures | `images/…` | Backgrounds, overlays, the preview of the picker card. | Which screens and components can be templated is the content of the [contracts reference](https://prism.am/dev/md/themes/contracts.md). Every screen that is not listed there keeps its structure; it still follows the tokens. ## What a theme cannot change {#cannot-change} These limits are the point of the design: whatever the theme says, the game stays usable. - **Nothing a screen needs can disappear.** A template must place every required place of its screen and must bind every required output of a component to a control. Play can move, never vanish. See [templates](https://prism.am/dev/md/themes/templates.md#places) and [concepts](https://prism.am/dev/md/themes/concepts.md#contracts). - **The keyboard and the accessibility tree stay the host's.** Shortcuts, the focus order (the order of the tree), the roles and accessible names of the game's own controls, the virtualised list and the actions of each row do not depend on the template. - **The map's picture stays visible.** A theme may tint, darken, blur or recolour it, never remove or bury it. The validator (`crates/themes/src/artwork.rs`) refuses a token set that lets less than 20 % of the picture through. See [tokens](https://prism.am/dev/md/themes/tokens.md). - **Icon buttons keep their geometry.** Their size and shape come from tokens; case, letter spacing and padding do not reach them. - **A theme runs no code while the game draws.** `theme.ts` runs once, at load, under budgets (500 ms, 16 MiB, 128 KiB of source, 4 000 nodes). See [templates](https://prism.am/dev/md/themes/templates.md#execution). - **Gameplay is not a theme.** The playfield and the in-game HUD are the business of skins and mods. ## The theme folder {#folder} The folder is named after the theme's id. ```text themes/<id>/ theme.json the manifest (required) tokens.css the tokens (required unless theme.json names another file) theme.css optional: styles of the theme's own classes theme.ts optional: the templates, defineTheme({ … }) preview.png optional: the picture of the picker card (named by "preview") images/… optional: pictures named by image tokens, templates and theme.css ``` Only these files are read. Anything else in the folder (a `theme.d.ts` for your editor, notes, source files) is ignored. ### theme.json {#theme-json} The manifest is at most 64 KiB. `name`, `description` and `author` are trimmed and may not contain control characters. | Field | Meaning | | --- | --- | | `id` | Required. Must be the folder name: lowercase letters, digits and hyphens, starting with a letter or a digit, 32 characters at most. The id `base` is reserved for the default templates: a theme with that id cannot have `theme.css` or `theme.ts`. | | `name` | Required. 1 to 48 characters. | | `description` | 0 to 240 characters. | | `version` | Your own version label: letters, digits and `. _ + -`, 32 characters at most. | | `author` | 0 to 64 characters. | | `order` | Position in the picker, 0 to 1000 (100 when absent); ties are broken by id. | | `themeApi` | The version of the theme contract the theme was written for: a whole number from 1. Absent means 1. The game speaks 2. A theme that asks for a newer version than the game speaks is refused with a sentence that says what to do. Write `2` to template the screens, faces and `"accent": "map"` that version 2 added. See [versions](https://prism.am/dev/md/themes.md#versions). | | `preview` | A picture of the folder shown on the picker card (`png`, `jpg`, `jpeg`, `webp`, `gif` or `svg`, 4 MiB at most). Without it the card is drawn from your tokens. | | `fonts` | Fonts the theme ships: `{ "Unbounded": "fonts/Unbounded.ttf" }`, a family name (1 to 48 ASCII letters, digits, spaces, `-` and `_`, starting with a letter; not a CSS generic such as `serif`) and a `.ttf`, `.otf`, `.woff` or `.woff2` file of the `fonts/` folder. At most 8 fonts, 4 MiB each, 12 MiB in all; a file must start like the font it claims to be. The game declares the `@font-face`; use the names in the `--pv-font-*` tokens and in `theme.css`. Ship only fonts whose licence allows it (OFL fonts do). | | `sounds` | Interface sounds: `{ "select": "sounds/select.ogg" }`, a moment (`select`: the selection settled on another map; `confirm`: Play or Enter; `back`: the menu drawer or Escape; `open`: another page; `toggle`: a gameplay modifier switched) and a `.wav`, `.ogg`, `.mp3` or `.flac` file of the `sounds/` folder that starts like a sound. 512 KiB each, 2 MiB in all; the first second plays. The game plays them on the player's device at the *Interface sounds* volume (Settings → Audio), never during a play. | | `options` | Options the player sets in Skins while the theme is worn, at most 12: `{ "id": "wave", "kind": "toggle", "label": "Font wave", "localized": { "fr": "Vague" }, "default": true }`; `kind` is `toggle` (default `true`/`false`), `choice` (2 to 8 `choices` of `{ "id", "label", "localized" }`, default one of their ids) or `color` (default `#rgb` or `#rrggbb`). `<body>` carries `data-opt-<id>` (a toggle that is on: present; a choice: its id) and `--opt-<id>` (a colour; a toggle: `1` or `0`): `[data-opt-wave] .title { animation: … }`, `color: var(--opt-glow, #3fd17a)`. | | `accent` | `"preference"` (default): the accent follows the player's *Accent colour* setting (*Theme default*, *Map artwork* or *Custom colour*; *Theme default* is your `--pv-accent`). `"fixed"`: the accent is always your `--pv-accent`, whatever the player chose (a signature colour). `"map"` (needs `"themeApi": 2`; with 1 the theme loads and follows the player's setting, with a notice): the accent is the selected map's own (the dominant hue of its artwork, or its difficulty colour), as if the player had chosen *Map artwork*; a *Custom colour* still wins, and your `--pv-accent` is what shows while no map is selected. The old word `"artwork"` is accepted and means `"preference"`. | | `tokens` | The name of the token file, a `.css` file of the folder. Default `tokens.css`. | | `localized` | The name and the description in other languages: `{ "fr": { "name": "…", "description": "…" } }`. At most 16 languages; a code is 2 to 8 letters or hyphens. The game has `en`, `fr`, `zh` and `ko`. A language that is missing falls back to `name` and `description`. | A minimal manifest: ```json { "id": "first-theme", "name": "First theme", "description": "The smallest useful theme: a manifest and a palette in tokens.css, nothing else. Teal on deep blue, rounded plates.", "version": "1.0.0", "author": "Prism docs", "themeApi": 2, "accent": "fixed", "tokens": "tokens.css", "localized": { "fr": { "name": "Premier thème", "description": "Le plus petit thème utile : un manifeste et une palette dans tokens.css, rien d'autre. Turquoise sur bleu profond, plaques arrondies." } } } ``` ### The other files {#files} - `tokens.css` holds one `:root { --pv-x: value; }` block and up to two `@media (max-width: <n>px)` blocks for narrow windows. Nothing else is allowed. 64 KiB, 200 declarations, 600 characters per value. A token you leave out keeps the game's neutral value, so a theme can be partial. See [concepts](https://prism.am/dev/md/themes/concepts.md#tokens) and the [token reference](https://prism.am/dev/md/themes/tokens.md). - `theme.css` is limited to 256 KiB, 2048 rules and 40 declarations per rule. See [theme.css](https://prism.am/dev/md/themes/css.md). - `theme.ts` is limited to 128 KiB. See [templates](https://prism.am/dev/md/themes/templates.md). - Pictures: `png`, `jpg`, `jpeg`, `webp`, `gif` or `svg`, 4 MiB each, up to 512 files under `images/` (four levels deep). Templates and styles may name only these files. The default templates every theme inherits live in the game's own folder `themes/_base/`. It is not a theme: a folder whose name starts with `_` is never listed, and `_base` is read only from the game's own `themes/` folder. See [concepts](https://prism.am/dev/md/themes/concepts.md#base). ## Where themes are looked up {#lookup} The game looks in two folders, in this order: 1. `themes/` next to `prism.exe`: the themes that ship with the game. In a development checkout this is the repository's `content/themes/`, found by walking up from the executable to the directory that holds `Cargo.lock`. 2. `<data>/themes`: the player's own themes. `PRISM_THEMES_DIR` points the game at another folder instead. On Windows `<data>` is `%LOCALAPPDATA%\Prism\PrismNG\data` (the preview channel uses `PrismNG-PBE`). *Open themes folder* in **Skins → Interface** opens it. If the same id is found twice, the first wins and the second is reported: you cannot replace a shipped theme by giving yours its id. At most 64 themes are loaded. After you change a folder, use *Reload themes* in the same place; the game lists the folders again and runs the scripts again. [Sharing](https://prism.am/dev/md/themes/sharing.md) covers installing and troubleshooting. ## The map of this section {#map} | Page | Read it to | | --- | --- | | [Quick start](https://prism.am/dev/md/themes/quick-start.md) | Make a first theme (tokens), then a first layout (`theme.ts`). | | [Concepts](https://prism.am/dev/md/themes/concepts.md) | Understand tokens, templates, screens, slots, contracts, faces, live data, motion, fallbacks. | | [Templates](https://prism.am/dev/md/themes/templates.md) | Write `theme.ts`: the execution model, bindings, conditions, events, slots, faces. | | [theme.css](https://prism.am/dev/md/themes/css.md) | Style your classes and reach the game's elements. | | [Cookbook](https://prism.am/dev/md/themes/cookbook.md) | Copy a recipe: banner, slanted cards, poster, terminal list, live bars, settings rail. | | [Reading errors](https://prism.am/dev/md/themes/errors.md) | Understand a message and fix it; the catalogue of errors. | | [Sharing](https://prism.am/dev/md/themes/sharing.md) | Install, share, check before you publish, troubleshoot. | | [Tokens](https://prism.am/dev/md/themes/tokens.md) | Generated: every `--pv-*` token with its type, range and role. | | [Nodes](https://prism.am/dev/md/themes/nodes.md) | Generated: every constructor of `theme.ts`, with its attributes. | | [Contracts](https://prism.am/dev/md/themes/contracts.md) | Generated: every screen and contract: input, outputs, places, parts, host classes, musts. | | [CSS allow-list](https://prism.am/dev/md/themes/css-allowlist.md) | Generated: selectors, at-rules and properties `theme.css` accepts. | For an AI assistant, see [llms-themes.txt](https://prism.am/dev/llms-themes.txt) and [Feed an AI assistant](https://prism.am/dev/md/llm.md): one self-contained document for writing a theme. The types of `theme.ts` are in [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts). ## Versions and stability {#versions} A theme is written against a **contract**: the paths of the input of every screen and component, the outputs, the places, the parts (`data-part`), the classes of the host, the node kinds and attributes, the properties of `theme.css`, the tokens. The contract has a version. ### THEME_API and themeApi {#theme-api} The game speaks one version, the constant `THEME_API` (`crates/themes/src/api.rs`); `check_theme` prints it (`theme API N`). A theme names the version it was written for with `"themeApi": N` in `theme.json`. Absent, it is 1: every theme written before the field existed. - A theme that asks for a **newer** version than the game speaks is refused in one sentence, instead of failing later on a node or a property that this game does not know: `theme.json: themeApi N is newer than this game speaks (theme API M): update the game, or use a version of the theme written for API M`. - A value that is not a whole number from 1 (`"1"`, `0`, `1.5`, `true`) is refused, and the message says what was found. - A theme that asks for an **older** version is loaded as long as the game can still read it. Write the number of the version you tested your theme against. The repository tool `check_theme` prints the version your copy of the game speaks. ### What changes in version 2 {#version-2} Theme API 2 only **adds**: no path, output, place, part, class, node kind, property or token of version 1 was removed or renamed, and no type changed. To move a theme to version 2, write `"themeApi": 2` in its `theme.json`; nothing else has to change. The shipped themes declare 2. What a theme that declares 1 (or nothing) **keeps**: everything it used. It loads, and its version 1 templates are validated and rendered as before. What it is **refused**, one notice per template or field, the theme still loading: - the template of a screen or a face added in version 2: `screen.chat`, `screen.clan`, `screen.download`, `screen.help`, `screen.lobby`, `screen.mods`, `screen.profile`, `screen.replay`, `screen.result`, `screen.settings`, `screen.skins`, and the faces `catalog.card`, `download.card`, `player.card` and `library.chartRow`. The theme keeps its tokens, its CSS and its other templates; the page takes the template of `_base`, then the game's own render. The notice names what to do: `requires themeApi 2: the screen "screen.settings" was added in theme API 2 and this theme declares themeApi 1; set "themeApi": 2 in theme.json once the theme is written for version 2` (see [the error](https://prism.am/dev/md/themes/errors.md#api-needs-version-2)); - `"accent": "map"`: the theme loads and its accent follows the player's setting, as `"preference"` does, with a notice that names it. One contract changed shape: `library.chartRow` was a component that drew its own button and became a **face** in version 2 (the game keeps the button, the keyboard and the menus, the theme draws the inside). A version 1 template of it is refused until the theme declares 2; no shipped theme had one, and it must be rewritten as a face, without a button. Every contract and screen the [contracts reference](https://prism.am/dev/md/themes/contracts.md) lists as *added in theme API 2* needs `"themeApi": 2`. ### What stays within a version {#within-a-version} The game may do all of this without changing `THEME_API`. None of it breaks a theme. - **Add**: an input path, an output, an optional place, a part, a host class, a state, a contract or a screen, a node kind or an attribute of a node, a CSS property, a value, a pseudo-element, a filter function, an `@media` condition, a `--pv-*` token (with a neutral value: a theme that ignores it keeps its look). - **Widen**: a limit (size, node count, budgets) may go up, a token range may widen, an enumeration may gain a value. A theme that compares a field with the values it knows stays correct. - **Change what a theme cannot see**: the DOM *inside* a host render (outside its `data-*` marks, its parts and its listed classes), the default renders, the templates of `_base`, the wording of error messages (read them, do not parse them), performance, and validation that gets more precise about something that was already wrong. ### What a new version means {#new-version} These need a new version of the contract, published next to the old one for as long as the game can: - removing or renaming a path, an output, a place, a part, a host class, a token, a node kind, a property or a value; - changing the type of a path, or the order or the type of the arguments of an output; - making a place or an output required when it was not; - giving an existing name another meaning; - lowering a limit below what a shipped theme uses. So an update of the game does not silently break your theme within a version. When a new version comes, your theme keeps asking for the version it was written for until you port it. The tests protect the promise: the embedded contracts (`apps/web/packages/@pvng/ui-contracts/contracts.json`) and the SDK (`content/mods/sdk/theme.d.ts`) are generated, and a test theme per version must keep passing `crates/modding/tests/theme_fixtures.rs`. ===== Page: Quick start Address: https://prism.am/dev/themes/quick-start/ Derived from: content/examples/themes/first-theme/theme.json, content/examples/themes/first-theme/tokens.css, content/examples/themes/first-layout/theme.ts, content/examples/themes/first-layout/theme.css, crates/modding/examples/check_theme.rs, crates/themes/src/library.rs, apps/web/src/components/ThemePicker.svelte # Quick start Make your first theme in ten minutes: a palette in tokens.css, then a first change of layout with theme.ts. You will make two themes. The first has two files and changes the look of the whole game: colours, shapes and fonts. The second adds a template and moves two things on the map selection screen. Each step takes a few minutes, and the example folders used here are tested: they pass the same validation as the game's own themes. ## Before you start {#before} You need a text editor and the game. Two tools are optional, and you can add them when you want them: - **`check_theme`**, the check that validates a folder exactly as the game does and prints the same messages. The installed game runs it: `prism.exe --check-theme <folder>` (no window, exit code 1 on a problem; with no folder, your themes folder). In a clone of the repository it is also `cargo run -p modding --example check_theme`. The game writes the problems of its last listing to `problems.txt` in your themes folder too: see [reading errors](https://prism.am/dev/md/themes/errors.md). - **TypeScript** (`npx tsc`) and [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts), for the second step: your editor completes the paths of the screen and a typo is a type error before the game runs the file. Themes are looked up in `themes/` next to `prism.exe` (the themes that ship with the game) and in your own `<data>/themes` folder. Your own folder is the one to use. In the game, open the **Skins** page: the *Interfaces* section has an *Actions* menu with *Open themes folder* and *Reload themes*. *Open themes folder* opens `<data>/themes` (it is created for you). See [where themes are looked up](https://prism.am/dev/md/themes.md#lookup). ## Your first theme: tokens only {#first-theme} A theme is a folder. The smallest useful one holds a manifest and a file of tokens. ### Start the folder {#first-theme-folder} Two ways to begin: - **From scratch.** Create the folder `first-theme` in your themes folder, with the two files below. - **From a shipped theme.** Copy a folder of the game's own `themes/` (for example `slant`) into your themes folder, rename it, and edit it. The id in `theme.json` **must be the folder's name**, so change both. A shipped theme also has a `theme.ts` and a `theme.css`: keep them to start from its layout, or delete them to keep only its palette. The name of the folder is the theme's id: lowercase letters, digits and hyphens, 32 characters at most. ### The manifest {#first-theme-manifest} `theme.json` names the theme and says how its accent behaves. It is the same file as in the tested example `first-theme`: ```json { "id": "first-theme", "name": "First theme", "description": "The smallest useful theme: a manifest and a palette in tokens.css, nothing else. Teal on deep blue, rounded plates.", "version": "1.0.0", "author": "Prism docs", "themeApi": 2, "accent": "fixed", "tokens": "tokens.css", "localized": { "fr": { "name": "Premier thème", "description": "Le plus petit thème utile : un manifeste et une palette dans tokens.css, rien d'autre. Turquoise sur bleu profond, plaques arrondies." } } } ``` `id` equals the folder name. `accent: "fixed"` means the accent is always the theme's own `--pv-accent`, whatever the player chose in the *Accent colour* setting; leave it out (or write `"preference"`) to let the player's choice win. `localized` gives the name and description in French; add the languages you can write. Every field is explained in [the theme folder](https://prism.am/dev/md/themes.md#theme-json). ### The tokens {#first-theme-tokens} `tokens.css` is a list of `--pv-*` values in one `:root` block. Every token is typed, and every token you leave out keeps the game's neutral value, so this file can be as short as you like. ```css /* * First theme: a palette, a shape and a font, nothing else. Every token that is missing keeps the game's neutral value, * so a theme can be as short as this one. Only `:root { --pv-x: value }` blocks are allowed in this file. */ :root { /* Native controls (scrollbars, inputs) follow the scheme of the palette. */ --pv-color-scheme: dark; /* Surfaces: a deep blue page and three steps of plate on it (rest, raised, hovered). */ --pv-bg: #0b1320; --pv-plate: rgb(18 30 48 / .86); --pv-plate-raised: rgb(27 44 68 / .92); --pv-plate-hover: rgb(38 60 90 / .96); --pv-plate-active: rgb(45 212 191 / .18); --pv-plate-active-hover: rgb(45 212 191 / .28); --pv-line: rgb(255 255 255 / .14); --pv-track: rgb(255 255 255 / .1); /* Text: three steps, and the ink drawn on top of an accent-coloured surface. */ --pv-text: #eef5fb; --pv-text-2: #b6c6d8; --pv-text-3: #8397ad; --pv-ink: #06201c; /* The accent. `"accent": "fixed"` in theme.json makes it the accent whatever the player chose. */ --pv-accent: #2dd4bf; --pv-accent-2: #f9a8d4; /* Shape: every plate is a rectangle with round corners. `--pv-clip-*` would cut other shapes (see the tokens reference). */ --pv-clip-lg: inset(0 round 14px); --pv-clip-md: inset(0 round 10px); --pv-clip-sm: inset(0 round 6px); --pv-radius-input: 8px; --pv-radius-panel: 14px; /* Type: one family for text, a heavier weight for titles. */ --pv-font-display: 'Segoe UI Variable Display', 'Segoe UI', system-ui, sans-serif; --pv-font-body: 'Segoe UI Variable Text', 'Segoe UI', system-ui, sans-serif; --pv-fw-display: 700; --pv-display-case: none; /* Layout words are tokens too: the tabs of the selected map as a rail, the Play strip at the bottom (the default). */ --pv-layout-tabs: rail; --pv-layout-play: bottom; } ``` What it does, from the top: - `--pv-color-scheme` tells the native controls (scrollbars, inputs) whether the palette is dark or light. - `--pv-bg`, `--pv-plate*`, `--pv-line` and `--pv-track` are the surfaces: the page, three steps of plate (rest, raised, hovered and selected), hairlines and the empty part of a gauge. Colours may carry transparency. - `--pv-text`, `--pv-text-2`, `--pv-text-3` are three steps of text; `--pv-ink` is the text drawn **on** an accent-coloured surface, so it must read against `--pv-accent`. - `--pv-accent` and `--pv-accent-2` are the accents. - `--pv-clip-*` and the radii set the shape of plates, buttons and badges. A clip can cut slanted shapes; here every plate is a rounded rectangle. - The fonts and weights set the type. Use a stack that ends with a generic family. - `--pv-layout-*` are **layout words**: a token that takes one word from a closed list. `--pv-layout-tabs: rail` turns the tabs of the selected map into a rail. The first word of each list is the game's current layout, and `bottom` is the first word of `--pv-layout-play`, so that line says what the game does anyway; try `--pv-layout-play: top` and `--pv-layout-list: left`. Every token, its type and its range are in the [token reference](https://prism.am/dev/md/themes/tokens.md). The ideas behind them are in [concepts](https://prism.am/dev/md/themes/concepts.md#tokens). ### Check it {#check} Put the folder in your themes folder and run the game's check on it (`prism.exe` is in the game's install folder): ```powershell & "$env:LOCALAPPDATA\Programs\Prism\prism.exe" --check-theme "$env:LOCALAPPDATA\Prism\PrismNG\data\themes" ``` From a clone of the repository, the same check is `check_theme` on the folder that **holds** your theme folders: ```powershell cargo run -p modding --example check_theme -- "$env:LOCALAPPDATA\Prism\PrismNG\data\themes" ``` A folder with no problem prints one line for the folder and one line per theme, and the exit code is 0: ```text <your themes folder>: 1 theme(s) loaded (theme API 1) first-theme 0 template(s), 0 byte(s) of theme.css ``` A problem prints one line per problem, in the form `"<theme>": <file>: <where>: <reason>`, and the exit code is 1. These two are real, from a copy of this theme with a mistake in the accent line: ```text problem: "first-theme": tokens.css: line 26: --pv-acent is not a theme token problem: "first-theme": tokens.css: line 26: --pv-accent: "teal-ish" is not a colour ``` The file, the line, the token and the reason are all there. A problem in `theme.json`, `tokens.css` or `theme.css` takes the theme out of the game's list, so fix it before you look for the theme. ### Pick it in the game {#pick} 1. Open the **Skins** page. The *Interfaces* section lists every theme as a card, drawn with that theme's tokens. 2. If the game was already running when you added the folder, open the *Actions* menu and choose *Reload themes*. 3. Click the card of your theme. The menus change at once. ![The map selection wearing the first theme](https://prism.am/dev/img/themes/first-theme.png) If the card is missing, the list below the cards (*Theme folders that cannot be used*) says why. The game writes the same lines to its standard error as `Themes: …`. ### Change a token and reload {#reload} Open `tokens.css`, change `--pv-accent` to another colour, save, and choose *Reload themes*. The game lists the folders again and applies the new values to the theme in use. This edit, check, reload loop is the whole workflow. When a theme grows, keep running `check_theme`: it gives the same notices as the game. ## Your first layout: theme.ts {#first-layout} Tokens restyle the game. To **move** things, a theme adds a template. You will rearrange the map selection screen: the list of maps on the left, and the selected map on the right with its Play strip (rating, judgement and the Play button) **above** the heading. The tested example is `first-layout`: the same palette idea plus a `theme.ts` and a `theme.css`. ![The map selection of the first-layout theme: the list on the left, the Play strip on top of the selected map](https://prism.am/dev/img/themes/first-layout.png) ### Add the files {#layout-start} Copy your `first-theme` folder to `first-layout`, change `id` and `name` in `theme.json`, and add two files next to `tokens.css`: `theme.ts` (the template) and `theme.css` (the styles of the classes the template creates). Any theme can have these files, with or without tokens. `theme.ts` is TypeScript that the game runs **once**, when the theme loads. It does not draw anything. It returns a tree of nodes, plain data, which Rust checks against the contract of the screen. If the tree is valid, the game draws it with its own components. ### The entry point {#layout-entry} ```ts theme // First layout: the library (the list) on the left, the selected map on the right with the Play strip ABOVE its heading. // // theme.ts runs ONCE, when the theme loads, and returns data: a tree of nodes that Rust checks against the contract of `screen.library`. // The validator refuses a template that drops a place the screen requires, so every place is still placed here: only their order and their wrappers change. // The file declares names of its own (functions), so it is a module. export {}; // The `c` of the library screen: its input paths, its places and its classes are typed by theme.d.ts. type Screen = ThemeContext<'screen.library'>; // The entry point: one template for the screen `screen.library`. defineTheme({ screens: { library: libraryScreen } }); ``` - The first lines are comments. The theme API has no `import`: `defineTheme` and the builders (`box`, `row`, `text`…) are already there. - `export {};` makes the file a module, so that the names it declares (the functions below) are its own. - `type Screen = ThemeContext<'screen.library'>` is the type of the **context** `c` for the map selection screen. From the declarations in `theme.d.ts`, your editor knows every path of the screen's input, every place and every class of the screen. - `defineTheme({ screens: { library: libraryScreen } })` registers one template, for the screen `screen.library`. A template is a function that receives `c` and returns a node. Everything else in the file is helpers that build that tree. ### The screen {#layout-screen} ```ts theme // The screen: two columns side by side, the list first. `pv-screen` is a class of the screen (the game styles it), `screen` is this theme's, defined in theme.css. // `--selection-color` is a variable of the screen: the colour of the selected row, read from the input. function libraryScreen(c: Screen): ThemeNode { return c.row( { class: ['screen', 'pv-screen'], vars: { '--selection-color': c.bind('browser.color') } }, library(c), selectedMap(c), ); } ``` `c.row` lays its children side by side. The attributes come first, then the children. `class` names two classes: `pv-screen` belongs to the screen (the game styles it) and `screen` is yours, defined in `theme.css`. `vars` hands a variable of the screen to the stylesheet; its value is read from the input with `c.bind('browser.color')`. The children are the library first, then the selected map: that order puts the list on the left. ### The selected map and the Play strip {#layout-map} ```ts theme // The selected map: the Play strip first (the `footer` place: rating, judgement, Play), then the heading, the tabs and their panels. // While nothing is selected, `when` draws the heading alone: it is the invitation to pick a map. function selectedMap(c: Screen): ThemeNode { return c.column( { as: 'section', class: 'map', aria: { label: c.t('ui.selected_map'), busy: c.bind('selection.busy') }, vars: { '--difficulty-color': c.bind('browser.color') } }, c.when( c.field('selection.shown').truthy(), [c.box({ class: 'play' }, c.slot('footer')), c.box({ class: 'details' }, c.slot('header'), c.slot('tabs'), c.slot('panels'))], c.slot('header'), ), ); } ``` `c.slot('footer')` is a **place**: the game draws its own Play strip there, and your template only says where it stands and what wraps it. The strip is placed **before** the heading, the tabs and the panels, inside a `box` with the class `play`. `c.when(condition, then, otherwise)` draws `then` while a map is selected; with nothing selected, the heading alone is the invitation to pick one. The validator refuses a template that does not place every required place of its screen, so you cannot delete Play or the list. You can only move them. See [places](https://prism.am/dev/md/themes/templates.md#places). ### The library {#layout-library} ```ts theme // The library: the toolbar, the search and the list. The playlists and the visualizer cover the list, so they are placed next to it // (`browser-body`, `browser-list` and `browser-playlists` are classes of the screen: the game stacks the lists with them). function library(c: Screen): ThemeNode { const covered = c.field('browser.covered').truthy(); return c.column( { as: 'section', class: 'library', aria: { label: c.t('ui.available_beatmapsets') } }, c.slot('intent'), c.slot('toolbar'), c.box( { class: 'browser-body' }, c.box({ class: 'browser-list', classWhen: { covered }, inert: covered }, c.slot('search'), c.slot('list')), c.when(c.field('browser.view').eq('playlists'), c.box({ class: 'browser-playlists', focusable: true }, c.slot('playlistSearch'), c.slot('playlists'))), c.when(c.field('browser.visualizer').truthy(), c.slot('visualizer')), ), ); } ``` The toolbar, the search and the list, as the game draws them by default. The playlists and the visualizer cover the list, so they are placed next to it. `browser-body`, `browser-list` and `browser-playlists` are classes of the screen: the game uses them to stack the lists, so keep them. `classWhen` adds `covered` while a condition holds, and `inert` makes the list unreachable by keyboard while it is covered. ### The stylesheet {#layout-css} Every class the template uses must be defined in `theme.css` or be a class of the screen. Here `screen`, `map`, `library`, `details` and `play` are the theme's own: ```css /* The classes of theme.ts: two columns, the library first, the selected map second. */ .screen { display: flex; flex-direction: row; align-items: stretch; gap: var(--pv-s6); height: 100%; min-height: 0; } .map { display: flex; flex-direction: column; flex: 1 1 0; min-width: 0; min-height: 0; } .library { display: flex; flex-direction: column; flex: 1 1 0; min-width: 0; min-height: 0; } .map > .details { display: flex; flex-direction: column; flex: 1 1 0; min-height: 0; overflow: hidden; } /* The Play strip stays pinned above the heading; a hairline under it separates it from the map. */ .map > .play { border-bottom: 1px solid var(--pv-line); padding-bottom: var(--pv-s3); } ``` Colours and gaps come from tokens (`var(--pv-line)`, `var(--pv-s6)`), never from literals. The rules of `theme.css` are in [theme.css](https://prism.am/dev/md/themes/css.md). ### Type checking with theme.d.ts {#types} The game refuses a template with a wrong path, but you can catch it in your editor first. Copy [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts) next to `theme.ts` (the game's own copy is `mods/sdk/theme.d.ts`), and put this as the first line of `theme.ts`: ```text /// <reference path="theme.d.ts" /> ``` Then check the file with TypeScript: ```powershell npx tsc --noEmit --strict --target es2022 --skipLibCheck theme.ts ``` A typo in a path is an error, with the list of valid paths in your editor's completion. This is what `tsc` says for `c.bind('browser.colour')`: ```text theme.ts(20,75): error TS2345: Argument of type '"browser.colour"' is not assignable to parameter of type 'ThemeBindable<ThemeScope_screen_library>'. ``` The comment line and the extra `theme.d.ts` are ignored by the game (only `theme.json`, `tokens.css`, `theme.css`, `theme.ts` and pictures are read). Leave both out of a theme you share. The `ThemeContext` types are explained in [templates](https://prism.am/dev/md/themes/templates.md#typed-context). ### Reload, and read the errors {#layout-reload} Choose *Reload themes*, then pick `first-layout`. The game runs `theme.ts` again, validates the tree and, if it is valid, draws it. If it is not, the theme still loads **without its template** (tokens and CSS stay) and a notice names the file, the node and the reason. This is the same typo as above, as the game or `check_theme` prints it: ```text problem: "first-layout": theme.ts: screen.library › row.screen (vars › --selection-color › bind): the path "browser.colour" is not in the screen: no field "colour" in "browser" (fields: view, covered, visualizer, color) [at vars/--selection-color/bind] ``` Read it from left to right: the template (`screen.library`), the chain of nodes down to the one at fault (`row.screen`: a `row` whose first class is `screen`), the attribute in parentheses, the reason, and the raw path in brackets. [Reading errors](https://prism.am/dev/md/themes/errors.md) explains every part and lists the errors you are likely to meet. ## Where to go next {#next} - Change how the game's own parts are laid out with layout words and tokens: the [token reference](https://prism.am/dev/md/themes/tokens.md). - Learn the language of `theme.ts`: [templates](https://prism.am/dev/md/themes/templates.md). - Copy a recipe (a hero banner, slanted cards, a poster layout, a terminal list, live bars, a settings rail): the [cookbook](https://prism.am/dev/md/themes/cookbook.md). - Understand screens, contracts, faces and the fallbacks: [concepts](https://prism.am/dev/md/themes/concepts.md). - Check, share and troubleshoot: [sharing](https://prism.am/dev/md/themes/sharing.md). ===== Page: Theme concepts Address: https://prism.am/dev/themes/concepts/ Derived from: docs/themes.md, crates/themes/src/library.rs, crates/themes/src/contracts.rs, crates/themes/src/template/validate.rs, crates/themes/src/stylesheet.rs, crates/modding/src/theme.rs, apps/web/src/template/store.ts, apps/web/src/template/eval.ts, apps/web/src/theme/themes.ts # Theme concepts The ideas behind a theme: tokens, styles, templates, screens and places, contracts and faces, live data, motion, localisation, accent and fallbacks. Each section below is short and ends with a pointer to the page that holds the exhaustive list. The pointers matter: the lists of tokens, nodes and contracts are generated from the code, so they are always right, and this page never repeats them. ## Tokens {#tokens} A **token** is a CSS custom property named `--pv-<name>`, set in `tokens.css`. The game's own stylesheets read tokens and nothing else, so tokens are how a theme restyles the whole interface without markup or script. - **Typed.** Every token has a type (a colour, a length, a font stack, a duration, a clip shape, a list of gradient layers, a choice among words…), and often a range. A value that does not fit is refused with the line, the token and the reason. - **Closed.** A name outside the contract is refused. The contract is `crates/themes/tokens.json`; the [token reference](https://prism.am/dev/md/themes/tokens.md) is generated from it. - **Partial is fine.** A token you leave out keeps the game's neutral value. The component tokens (`--pv-card-*`, `--pv-button-*`, `--pv-input-*`, `--pv-tab-*`, `--pv-tooltip-*`, `--pv-list-row-*`) default to references to the base tokens (`--pv-card-bg` is `--pv-surface-2`, which is `--pv-plate-raised`), so setting the base palette already restyles the components. - **Layout words.** A token of type *choice* takes one word from a closed list. The page turns each valid choice into a `data-layout-<name>` attribute on `<html>` and the game's stylesheets react to it: `--pv-layout-list: left` puts the list on the left, `--pv-layout-tabs: rail` makes the tabs a rail. The first word of each list is the current layout: a theme that says nothing changes nothing. - **Narrow windows.** Up to two `@media (max-width: <n>px)` blocks, each holding one `:root`, override tokens for narrow windows (`n` from 320 to 4000). Image tokens stay in the main block. - **Two guard rails.** The map's picture must stay visible (at least 20 % of its light reaches the screen: `crates/themes/src/artwork.rs`). The three curves of the replay graph must stay distinguishable (their hues differ by at least 30°: `crates/themes/src/curves.rs`). A theme that breaks one is refused whole, with the names of the tokens at fault. - **A shared backdrop.** On every page except the song selection (Download, Multiplayer, Profile, Clan, Skins, Mods, Help, a score's analysis), the map's picture sits behind a veil so a bright cover never reaches the page's titles and tabs. `--pv-page-scrim` is that veil (by default the page background at 78 %; the guard rail above caps it at 90 %, so the picture stays visible) and `--pv-page-art-blur` blurs the picture behind it (0 keeps it sharp). A theme tunes both in `tokens.css`. The song selection is not affected: it keeps `--pv-shade` alone. A light theme sets `--pv-color-scheme: light` and redefines the tokens that default to dark-surface colours (the offset, tier and rating tokens: see the [token reference](https://prism.am/dev/md/themes/tokens.md)). Reference: [tokens](https://prism.am/dev/md/themes/tokens.md). Practice: [quick start](https://prism.am/dev/md/themes/quick-start.md#first-theme). ## theme.css {#theme-css} `theme.css` styles the **classes your template creates**. It is a validated subset of CSS: Rust parses it, refuses anything outside the subset, and rewrites it before the page sees it. Every class `.name` becomes `.tpl-<id>-name` and every selector is placed under `[data-direction="<id>"]`, so a theme cannot touch the rest of the game or another theme. It reaches the game's own elements through their `data-*` marks, never through their classes. Reference and rules: [theme.css](https://prism.am/dev/md/themes/css.md) and the generated [CSS allow-list](https://prism.am/dev/md/themes/css-allowlist.md). ## Templates {#templates} A template redraws the **structure** of a screen. `theme.ts` calls `defineTheme({ screens, components })`; each entry is a function that receives a typed context `c` and returns a node. The script runs **once**, when the theme loads, in a throwaway engine with no game API, and returns a tree of nodes from a closed list (`box`, `row`, `text`, `slot`, `when`, `each`…). Nothing of the script survives its run: only the tree, which Rust validates against the contract before the page draws a node of it. The page draws every tree with one generic renderer. So a template cannot compute at draw time. It declares what to show (`bind`), when (`when`), repeated how (`each`) and what a control asks for (`on.press`). The game does the rest. Full guide: [templates](https://prism.am/dev/md/themes/templates.md). Every node and attribute: [nodes](https://prism.am/dev/md/themes/nodes.md). ## Screens, places and slots {#screens} A **screen** is a whole page of the game that a theme may template. The templatable screens are: `screen.library` (map selection), `screen.settings` (the Settings window), `screen.download` (the Download page, with the `download.card` face for its results), `screen.help`, `screen.result` (the summary shown for ten seconds after a play), `screen.lobby` (the multiplayer room, with the `player.card` face for each player), `screen.chat` (the chat sheet), `screen.profile`, `screen.clan`, `screen.replay` (score analysis), `screen.mods` and `screen.skins` (with the `catalog.card` face). The [contracts reference](https://prism.am/dev/md/themes/contracts.md) is generated from the game and always holds the current list. Their places, inputs and outputs are in the [contracts reference](https://prism.am/dev/md/themes/contracts.md). The rest of this section uses the map selection as the example. Its template (`screens: { library: … }`, for the contract named `screen.library`) composes it from **places** (also called slots). A place is a named position that the game fills with one of its own components: in the map selection screen they include `list`, `search`, `header`, `tabs`, `panels` and `footer`. The host builds the input of every place and mounts it where the template says `c.slot('footer')`. The template decides **where** each place stands and **how it is wrapped**: wrappers, order, extra decoration, extra facts around it. It does not decide what the place contains. A place marked *required* must appear at least once (inside a `when` it counts); that is how Play and the list cannot be removed, only moved. The screens and their places are in the [contracts reference](https://prism.am/dev/md/themes/contracts.md). Practice: [first layout](https://prism.am/dev/md/themes/quick-start.md#first-layout). ## Components and contracts {#contracts} Every templatable piece of the game has a **contract**: the written agreement between the game and a theme. A contract states: - the **input**: the facts a renderer receives, one state at a time (for example `play.label` for the Play footer); - the **outputs**: what a renderer may ask for, each one an action of the game, with typed arguments (`confirm` starts the map); - the **places** (`slots`) the contract leaves free for a template to fill; - the **parts** (`data-part`) of the default render, which a node may carry and a stylesheet may target; - the **host classes** and **CSS variables** the game's stylesheet gives that a template may use; - the **musts**: what every render of the contract must keep (for example that Play is a button, reachable and focusable). The game's own tests (`apps/web/tests/contracts.spec.ts`) check the default render against them. At load the validator enforces the part a template can break: required places and required outputs. A **screen** has the same shape (input, outputs, places, host classes, variables) plus the list of components a template may mount inside it. A **component** template (`components: { 'library.footer': … }`) replaces only that piece. A theme can write the screen, any components, or both. The validator checks a template against its contract before the theme is used: every path exists in the input, every operator fits the type of the field, every output exists with its arguments, every class is the theme's own or one the contract lists, every part exists, every required place is placed and every required output is bound to a control. A template that fails is refused alone, with a message that says where. Reference: [contracts](https://prism.am/dev/md/themes/contracts.md). Messages: [reading errors](https://prism.am/dev/md/themes/errors.md). ## Faces {#faces} A list row cannot be replaced like a footer: it is virtualised (hundreds of rows recycled while you scroll), and it has a context menu, a hover popover, Ctrl+click, keyboard focus and buttons beside it. So some contracts are **faces** (`face: true` in the contracts table): the set card of the song list, the difficulty row, the score card of the leaderboard and the result card of the Download page (`download.card`), the player card of the lobby and the chat (`player.card`) and the catalogue card (`catalog.card`) are faces, and the contracts reference marks every one. For a face, the split is strict: | The game keeps | The theme draws | | --- | --- | | The root of the card (the button or plate, its edge, accessible name, `aria-expanded`, `data-active`), the keyboard (Enter, Space, Menu, Shift+F10), the context menu, the popovers, the virtualised row that carries it, the buttons beside a score and their tooltips. | The **inside** of the root: layout, text, icons, pictures, gauges, repeated lists (`box`, `row`, `column`, `text`, `icon`, `image`, `meter`, `each`, `when`), classes, `vars` and `part`. | What the validator refuses in a face: a `button`, `toggle` or `dropdown` (a face adds no tab stop and no action), a `slot` that mounts another contract, and any call to an output. The message reads `a button is not allowed in library.setCard: the host draws and owns the card's own button, keyboard, menus and actions…`. A face still places the game's own small widgets where it wants (for example the goal mark or the tier counts) with `c.slot('goal')`, `c.slot('tiers')`. The exact list is on each contract in the [contracts reference](https://prism.am/dev/md/themes/contracts.md). A face that leaves out a part such as `artist` only loses the gesture that part carries (Ctrl+click filters by it). A face reads the host's variables with `var()` in `theme.css` (`--set-color`, `--edge`, `--difficulty-color`) and the **row distance** `--row-distance`: the number of rows between a row and the centre of the list. A theme can shape a carousel with it. Cookbook: [slanted cards](https://prism.am/dev/md/themes/cookbook.md). ## Inputs, outputs and bindings {#io} - **Input.** The data a template can read. It is a tree of typed fields. `c.bind('map.bpm')` reads one field as text, a number or a boolean. A path that does not exist is a type error in your editor and an error from Rust at load. At run time, a path that has nothing behind it shows nothing and makes a condition false; it never throws. - **Outputs.** The actions a control may call. `c.on.press('confirm')` makes a `button` call the output `confirm` with its arguments in order and with the right types; a toggle or dropdown appends its new value as the last argument. A node may call only outputs of its own screen or contract. A theme can never invent an action. - **Bindings.** A binding links a node to a path: `text(c.bind('play.label'))`. A list of values is written one after the other. `$alias.field` reads the current item inside an `each`; `[]` is allowed only in the `from` of a `slot`. - **Conditions.** `c.field('path')` compared with `.eq`, `.gt`… or tested with `.truthy()`; combined with `.and`, `.or`, `.not`. A condition decides `when`, `classWhen`, `hidden`, `inert`, `disabled`, `pressed`. Guide: [templates](https://prism.am/dev/md/themes/templates.md#bindings). ## Formatting {#formatting} The game shows numbers a certain way, and a theme should not reinvent it. `c.fmt` formats a numeric path as the game does: | Call | Result | | --- | --- | | `c.fmt.rate(path, digits?)` | A playback rate, `1.25` (no `x`). | | `c.fmt.count(path, digits?)` | A compact count, floored: `12k`. | | `c.fmt.percent(path, digits?)` | A number that is **already** a percentage (`97.4` gives `97.40%`); 2 digits by default. | | `c.fmt.duration(path, digits?)` | A duration in **seconds** as `m:ss` or `h:mm:ss`. | | `c.fmt.fixed(path, digits?)` | A fixed number of decimals (2 by default). | A bare `c.bind` of a number shows it with at most two decimals, trailing zeros dropped (`27.361499` reads `27.36`, `3` reads `3`). A path that is not a number formats to empty text. `c.t('key', { name: value })` is the game's translated text for a key. ## Live bars {#live-bars} Each bar of `map.equalizer` has two heights from 4 to 100: `level`, the note density of the map, and `live`, the **same bar as the menu music plays it now** (the game's spectrum folded into the same bars). `map.listening` is true while the music drives the bars. - **Opt in by binding.** A template that binds `live` (or `listening`) makes the screen ask the game for the spectrum, only while a map is shown and the player has not asked for less animation. A theme that does not bind it costs nothing: no request, no analysis, no message. - **Smoothing is the page's.** A bar rises fast (attack about 45 ms) and falls slowly (release about 190 ms). Take each frame as it comes: **no `transition` on the bars** (measured: it makes every bar recompute its style on each frame for nothing visible). Set the height with `transform: scaleY(calc(var(--tpl-live) / 100))`, not `height`: a bar moves about thirty times a second and must not trigger layout. - **Fallback.** With no music (menu music off, loading, paused for the settings or during a play, or nothing received for a third of a second), `live` equals `level`, and the bars ease to the density in about half a second. With *reduce motion* on, the page never asks for the spectrum: `live` is `level` and the bars are still. - **Cost.** One update of the screen input per spectrum frame (about 30 a second, around 2.5 ms of script measured in the development browser), only while music plays. At rest nothing runs. The recipe is in the [cookbook](https://prism.am/dev/md/themes/cookbook.md); the fields are in the [contracts reference](https://prism.am/dev/md/themes/contracts.md). ## The animation rule {#animation-rule} **No infinite animation on a screen at rest.** An animation that loops forever (`infinite`) repaints its area on every frame even when nothing else moves. It was measured in the game's web view: fifteen equalizer bars and two infinite glows cost about three CPU cores on a menu left alone (about 6 % once the music is paused). So decorative motion plays **once per selection**. - Hang the animation on `[data-entering]`, which the game sets for about 0.9 s after the selection settles (250 ms after the last change, and only when the new map is in another set). Put `data: { entering: c.bind('selection.entering') }` on the node so that it carries the attribute. - Or hang it on `:hover` or `:focus-visible`, with a finite `animation-iteration-count`. - Put every moving animation in `@media (prefers-reduced-motion: no-preference)`. - Never start an entrance below 0.8 opacity. The selected map's heading, figures and panels already show the new map when their entrance plays, so they only *settle*: the game's shared keyframes `pv-slide-settle` and `pv-rise-settle` run from `opacity: .8`, never from 0, and a theme's own entrance keyframes do the same. Starting from 0 makes the panel blink out and back every time the arrow keys move the selection. The validator does not check this; the game's spec `tests/selection-update-in-place.spec.ts` walks every shipped theme and fails when a panel dips. The validator does not forbid `infinite` (a theme that used it stays valid) but **warns**: `"<id>": theme.css: warning: line N: an infinite animation repaints the page every frame, even on an idle screen; play it a few times (a finite animation-iteration-count), or once per selection under [data-entering]`. The warning shows in the list under the picker, in the game's log and in `check_theme`. Treat it as an error. ## Reduced motion {#reduced-motion} When the player asks for less animation (`prefers-reduced-motion: reduce`), the **game's own** motion collapses whatever the theme says: the durations its components read (`--pv-dur-*`) drop to almost zero, and the travel of entrance animations (`--pv-shift-base`) and the stagger drop to zero. `--pv-motion-intensity` (0 to 1) scales that travel and stagger for a calm theme; the game multiplies it by 0 under reduced motion. The `data-entering` entrance never plays. What the game cannot do is stop **your** animations: a rule in `theme.css` plays as written. So the theme stops itself: put every animation and every moving transition in `@media (prefers-reduced-motion: no-preference)`. Live bars are still under reduced motion, as above. ## Localisation {#localization} `theme.json` carries the name and the description of the theme in other languages under `localized`, keyed by language code (the game has `en`, `fr`, `zh` and `ko`). The picker shows the entry that matches the game's language and falls back to the manifest's `name` and `description` when a language or a field is missing. Provide at least the languages you can write. Text inside a template is shown as written, in every language. For a word the game already translates, use `c.t('key')` with one of the game's translation keys (`c.t('ui.selected_map')`). The examples use only such keys and the game's own text. ## Accent modes {#accent} The accent is the colour of buttons and highlights. The player's *Accent colour* setting offers *Theme default*, *Map artwork* (the hue of the selected map's picture) and *Custom colour*. `accent` in `theme.json` says whether the theme listens: - `"preference"` (default): the accent follows the player's choice; *Theme default* is your `--pv-accent`. The old word `"artwork"` means the same. - `"fixed"`: the accent is always your `--pv-accent`. Use it when the palette needs one colour: phosphor green, a brand orange. - `"map"`: the accent is the selected map's own (the dominant hue of its artwork, or its difficulty colour), whatever the player's accent setting says, except a *Custom colour*, which still wins. Your `--pv-accent` is what shows while no map is selected. Use it when the interface should follow the cover, as the Vinyl theme does. `--pv-accent-2` is a second accent for secondary marks. `--pv-ink` is the text drawn on an accent-coloured surface: check it against both your accent and a light custom colour if the theme is `"preference"`. ## _base inheritance and fallbacks {#base} ### Inheritance {#inheritance} The game's own folder `themes/_base/` holds the templates every theme inherits. It is not a theme. A theme that does not write the template of a screen or a component takes the one of `_base`, component by component. If `_base` has none either, the contract's default render (a Svelte component) draws. A theme with no `theme.ts` at all gets the game's default composition, restyled by its tokens. `_base` styles its classes as `.tpl-base-<name>`, globally. You do not write them. The reading order of a template is: the theme's own, then `_base`'s, then the default render. ### When something fails {#fallbacks} Failure is never silent, and it is contained to the smallest part that failed. From the largest to the smallest: | What failed | What happens | Where you see it | | --- | --- | --- | | The chosen theme is not in the list (deleted, refused) | The game wears the default theme (`stage`), else the first listed, else its built-in neutral tokens. | Nothing is lost; check the list of problems. | | `theme.json`, `tokens.css`, `theme.css`, or an image named by a token or by `preview` is invalid | The **theme is removed from the list**. The other themes are unaffected. | `"<id>": <file>: <where>: <reason>` in the list under the picker and in the log. | | `theme.ts` throws, times out or goes over a budget | The theme **loads without its templates**: tokens, CSS and images stay, and it takes the templates of `_base`. | `"<id>": theme.ts: <message>` | | One template is refused by validation | **That template alone** is dropped; the others stand. `_base`'s, or the default render, draws instead. | `"<id>": theme.ts: <contract> › <node chain>: <reason>` | | A valid template throws while it draws | It is set aside for the session until the themes are reloaded. The default draws at once and the player is told once per contract: *The template of "…" in the interface "…" cannot be drawn; the default one is used.* | A notice in the game. | Rows two to four happen at load and are what `check_theme` reproduces. The last happens in the page; it should not happen with a validated template, and it is the safety net. Practical rule: **never delete a template to "fix" an error**. Read the message; it names the file, the node and the reason. See [reading errors](https://prism.am/dev/md/themes/errors.md). ## Versioning {#versioning} `themeApi` in `theme.json` names the version of the contract your theme was written for. A newer one than the game speaks is refused in one sentence; an older one loads as long as the game can read it; absent means 1. What may change without a new version, and what needs one, is on the [overview](https://prism.am/dev/md/themes.md#versions). ===== Page: Templates (theme.ts) Address: https://prism.am/dev/themes/templates/ Derived from: docs/themes.md, crates/modding/src/theme.rs, crates/modding/src/theme_prelude.js, crates/themes/src/template/mod.rs, crates/themes/src/template/validate.rs, content/mods/sdk/theme.d.ts, content/examples/themes/first-layout/theme.ts, content/examples/themes/recipe-hero-banner/theme.ts, content/examples/themes/recipe-footer-strip/theme.ts, content/examples/themes/recipe-slanted-cards/theme.ts, content/examples/themes/recipe-live-bars/theme.ts, content/examples/themes/recipe-settings-rail/theme.ts # Templates (theme.ts) The language of theme.ts: how a template runs and its budgets, the constructors, bindings, conditions, events, places, each and when, faces, and how to read the typed context. A template tells the game **where the parts of a screen stand and how they are wrapped**. It is written in TypeScript in `theme.ts`, and it returns data. This page is the language guide. For the idea behind it, read [concepts](https://prism.am/dev/md/themes/concepts.md#templates). For the exhaustive list of constructors and attributes, see the generated [nodes](https://prism.am/dev/md/themes/nodes.md) reference; for what each screen offers, the [contracts](https://prism.am/dev/md/themes/contracts.md) reference. Every example below comes from a tested folder: it passes the validator. ## How a template runs {#execution} ### The model {#model} `theme.ts` runs **once**, when the theme loads (and again when the player chooses *Reload themes*). It runs in a throwaway script engine on the game's mod thread, **with no game API at all**: no `game`, `hud`, `storage`, `log`, no `defineMod`. It has the language, and the builders that the game puts in front of your source (`box`, `row`, `text`, `bind`, `defineTheme`…), which also exist as members of the typed context `c`. - The builders return frozen plain values that only they can make. `defineTheme` hands the whole tree to the game as JSON. A function, a `NaN` or a cycle in the result is refused; nothing else of your script survives its run. - Because the result is data, you may structure the file as you like: named functions for each zone, tables that drive repetition, helpers, constants. None of it is in the result. - A script that declares a top-level name of its own (`const box = …`, `function library`) adds `export {};` to be a module. - There is no `import`. There is no clock (`Date`), no proxy, no typed array, no weak reference and no web API. `RegExp` works. `defineTheme` can be called **once**. - Errors in the script (an exception, a wrong argument to a builder, a timeout) fail the whole script: the theme **loads without its templates** and falls back to `_base`. The message is `"<id>": theme.ts: <message>` with the position in your file. ### Budgets {#budgets} Each script runs under these budgets (`ThemeScriptLimits`, `crates/modding/src/theme.rs`). Going over any of them fails the script. | Budget | Value | | --- | --- | | Wall time of the run | 500 ms | | Memory of the engine | 16 MiB | | Size of `theme.ts` | 128 KiB | | Nodes in the tree the script returns (all templates together) | 4 000 | | Size of the tree as JSON | 1 MiB | ### Limits of the validated tree {#tree-limits} After the run, Rust validates the tree. These limits are checked by the validator (`crates/themes/src/template/mod.rs`): | Limit | Value | | --- | --- | | Depth of nesting | 24 | | Nodes in all the templates of one theme | 1 500 | | Templates (screens and components) | 64 | | Children of one node | 64 | | Classes on one node, and conditional classes | 8 each | | Entries of `data` or of `vars` on one node | 8 | | Tracks of a `grid` | 12 | | Characters of a literal text | 200 | ## The typed context {#typed-context} Every template is a function that receives a **context** `c` and returns a node. The context is typed by [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts), a file generated from the table of contracts. In a file that refers to it (see the [quick start](https://prism.am/dev/md/themes/quick-start.md#types)), write: ```ts theme // The `c` of the library screen: its input paths, its places and its classes are typed by theme.d.ts. type Screen = ThemeContext<'screen.library'>; // The entry point: one template for the screen `screen.library`. defineTheme({ screens: { library: libraryScreen } }); ``` `ThemeContext<'screen.library'>` is the builders of the screen `screen.library`, typed with **its** input paths, **its** places, **its** classes, **its** variables and **its** outputs. A path that does not exist, a class that is not allowed, an output with the wrong arguments is a type error in your editor and the same refusal from Rust later. The contract names (`'screen.library'`, `'library.footer'`) are the keys of `ThemeTargets` in `theme.d.ts`. What `theme.d.ts` holds, and how to read it: - `ThemeContext<K>`: the builders for the contract `K`. Every template function takes one. - `ThemeTarget_<contract>` (for example `ThemeTarget_screen_library`): the **places** (`slots`), the **classes** of the host (`hostClasses`), the **variables** (`cssVars`), the **outputs** with their argument types, and the **parts** (`parts`). A comment on each entry says what it is. - `ThemeScope_<contract>`: the **paths** of the input and the **lists** that `each` loops over, with the scope of their items. - `ThemeTargets['screen.library']['target']` and `['scope']`: the same pieces by name, when you need to type a helper. To type a helper that builds the item of a list, take the builders of that list from the scope. The equalizer recipe does it for `map.equalizer`: ```ts theme type Screen = ThemeContext<'screen.library'>; // The element type of `map.equalizer`: `item.bind('live')` reads that bar. type BarItem = ThemeBuilders<ThemeTargets['screen.library']['target'], ThemeTargets['screen.library']['scope']['lists']['map.equalizer']>; ``` The untyped globals (`box`, `row`, `bind('a.b')`, `on.press('confirm')`…) exist too. They accept any string, so they give no completion; prefer `c.…`. ## The entry point {#entry} `defineTheme` takes an object with up to two entries: ```ts theme // The entry point: a screen (to give the list a class of the theme) and two faces. defineTheme({ screens: { library: libraryScreen }, components: { 'library.setCard': setCard, 'library.chartRow': chartRow } }); ``` - `screens`: one template per screen. The key is the screen's name **without** its `screen.` prefix: `library` is `screen.library`, `settings` is `screen.settings`; the others are `download`, `help`, `result`, `lobby`, `chat`, `profile`, `clan`, `replay`, `mods` and `skins`. - `components`: one template per contract of a component or a face (`'library.footer'`, `'library.setCard'`). The key is the contract's full name. A template that you do not write is inherited from `_base`, then from the game's default render ([concepts](https://prism.am/dev/md/themes/concepts.md#base)). A key that is not a screen or a contract is refused with the list of the valid ones (`there is no screen "…" (screens: …)`). ## The constructors in use {#constructors} The node kinds are a closed list. The [nodes reference](https://prism.am/dev/md/themes/nodes.md) has every one with every attribute; here are the ones you will use, each in a tested example. In `c.row({ attributes }, child, child…)` the attributes object comes first and is optional. ### Containers {#containers} `box`, `row`, `column` and `stack` hold children: `row` side by side, `column` one under the other, `stack` on top of each other, `box` a plain block. `as` picks the HTML element (`div`, `section`, `header`, `footer`, `nav`, `aside`, `main`, `article`, `ul`, `li`). They take `gap` and `pad` (steps 0 to 10 of the `--pv-s*` spacing tokens), `align`, `justify`, `wrap` and `grow`. `scroll` is a scrolling area; `spacer` is room that grows, or a fixed `size`. ```ts theme // The screen: two columns side by side, the list first. `pv-screen` is a class of the screen (the game styles it), `screen` is this theme's, defined in theme.css. // `--selection-color` is a variable of the screen: the colour of the selected row, read from the input. function libraryScreen(c: Screen): ThemeNode { return c.row( { class: ['screen', 'pv-screen'], vars: { '--selection-color': c.bind('browser.color') } }, library(c), selectedMap(c), ); } ``` `grid` lays children out in tracks (`auto`, `1fr`, `120px`, `50%`, `minmax(0,1fr)`; 12 at most). It is used in the score card of [Meters and grids](https://prism.am/dev/md/themes/templates.md#meters): `columns: ['44px', 'minmax(0,1fr)', '150px']`. ### Text, icons and pictures {#text-icon-image} `text` draws a value; `as` picks `span`, `p`, `h1` to `h3`, `strong`, `em`, `label` or `small`. `icon` draws one icon of the game's closed list (size 12 to 64). `image` draws a picture, with a required `alt` (an empty `alt` marks it as decoration) and `fit`. Its source is a file of your `images/` folder, or a path of the input (`c.bind('map.background')`), never a web address. ```ts theme // The picture and its shade. The `image` node reads a path bound to the input (`map.background`), never a URL of the web. // It is shown only when the map has a picture. function backdrop(c: Screen): ThemeNode { return c.box( { class: 'hero-backdrop', role: 'presentation' }, present(c, 'map.background', c.image(c.bind('map.background'), { class: 'hero-art', alt: '', fit: 'cover' })), c.box({ class: 'hero-shade' }), ); } ``` ```ts theme // One tile: a small label with its icon over a big value. `c.t` is the game's translated text for a key. function factTile(c: Screen, fact: Fact): ThemeNode { return c.box( { class: 'tile' }, c.row({ class: 'tile-head', align: 'center', gap: 1 }, c.icon(fact.icon, { size: 12, class: 'tile-icon' }), c.text(c.t(fact.label), { as: 'small', class: 'tile-label' })), c.text(fact.value(c), { as: 'strong', class: 'tile-value' }), ); } ``` The second example reads a table: each fact is an icon, a translated label and a value. A text may be a list of values, written one after the other: `c.text(['+', c.bind('strip.more.count')])`. ### Buttons and controls {#controls} `button`, `toggle` and `dropdown` are the only nodes that can **do** something. Each takes an `on` event that calls an **output** of the screen or contract (see [events](https://prism.am/dev/md/themes/templates.md#events)). `button` has a `variant` (`primary`, `plain`, `quiet`), a `label` and the conditions `disabled` and `pressed`; `describedBy` points to a `part` that describes it. `toggle` has `label`, `checked` and `on.change`. `dropdown` has `label`, `value`, `options` (the path of a list of `{ value, label, group, detail }`), `displayValue` and `on.pick`. ```ts theme // A drop-down list: the options come from the input (`rating.options`), the value is the one in force, and picking an entry calls the output // `rating.pick` (or `judgement.pick`) with the entry's value appended to the arguments. function chooser(c: Footer, which: 'rating' | 'judgement'): ThemeNode { return c.dropdown({ class: 'chooser', part: which, label: c.t(which === 'rating' ? 'rating.label' : 'judgement.title'), value: c.bind(`${which}.value`), options: `${which}.options`, displayValue: which === 'judgement' ? c.bind('judgement.label') : undefined, ariaLabel: which === 'judgement' ? c.bind('judgement.ariaLabel') : c.t('rating.label'), on: c.on.pick(`${which}.pick`), }); } // The main button of a map. It is off in the two states where it cannot start, and the reason is a line of text it points at (`describedBy`), so it stays readable. function playButton(c: Footer): ThemeNode { const off = c.field('state').in(['mapBlocked', 'mapRefused']); return c.row( { class: 'go-line', align: 'center', gap: 2 }, c.when(c.field('state').eq('mapBlocked'), c.text(c.bind('reason.text'), { class: 'reason', part: 'reason' })), c.button({ variant: 'primary', class: 'go', part: 'play', label: c.bind('play.label'), disabled: off, classWhen: { off }, describedBy: 'reason', on: c.on.press('confirm') }), ); } ``` The contract of `library.footer` requires that its `confirm` output is called by a button: a theme can restyle and move Play, never remove it. If you write the footer without it, you get `library.footer: the required output "confirm" is not bound to any control (a button must call it)`. ### Meters and grids {#meters} `meter` draws a gauge from a value, with `min`, `max` and a `label` for assistive technology. It is allowed in a face. This score card puts three columns in a `grid`, and a gauge under the accuracy: ```ts theme // One score of the leaderboard, as a FACE: the game keeps the card's plate, its button and the buttons beside it; the theme draws what is inside. // A `grid` places three columns: the rank, the player with the marks of the play, and the accuracy as a meter under its number. function scoreCard(c: ScoreCard): ThemeNode { // A clean run: no misses recorded (`misses` is only there when the card cannot count them by tier). `.and()` joins two conditions. const clean = c.field('misses').ge(0).and(c.field('misses').lt(1)); // `.not()` turns a condition around: the mark is for plays that DO count for a ranking. const ranked = c.field('badges.unranked').truthy().not(); return c.grid( { class: 'sk', columns: ['44px', 'minmax(0,1fr)', '150px'], align: 'center', gap: 3 }, c.text(c.bind('rank'), { as: 'strong', part: 'rank', class: 'sk-rank' }), c.column( { class: 'sk-main', gap: 1 }, c.row( { class: 'sk-head', wrap: true, align: 'center', gap: 1 }, c.text(c.bind('player.label'), { as: 'strong', part: 'name', class: 'sk-name' }), // The rate with two decimals, and the combo as a compact count (1.9k). c.text([c.fmt.rate('rate.value', 2), 'x'], { part: 'rate', class: 'sk-tag' }), c.text(['combo ', c.fmt.count('combo', 1)], { part: 'combo', class: 'sk-tag' }), c.when(clean, c.text('clean', { class: 'sk-tag sk-good' })), c.when(ranked, c.icon('trophy', { size: 12, class: 'sk-ranked' })), ), c.slot('tiers'), ), c.column( { class: 'sk-score', gap: 1 }, // `percent` expects a number that is already a percentage (97.4 gives 97.40%); `fixed` writes a number with a set count of decimals. c.text(c.fmt.percent('accuracy.value', 2), { as: 'strong', part: 'accuracy', class: 'sk-accuracy' }), c.meter({ class: 'sk-meter', value: c.bind('accuracy.value'), min: 0, max: 100, label: c.t('facts.best_accuracy') }), c.when(c.field('misses').gt(0), c.text(['misses ', c.fmt.fixed('misses', 0)], { as: 'small', class: 'sk-meta' })), ), ); } ``` ### Attributes every node takes {#attributes} | Attribute | Meaning | | --- | --- | | `class` | Classes: one of **your** classes (defined in `theme.css`) or a class the screen or contract lists. Up to 8. A class that is neither is refused; a class that is both is ambiguous. | | `classWhen` | `{ covered }` or `{ lit: star.field('lit').truthy() }`: a class present while a condition holds. | | `part` | A `data-part` of the contract, so a stylesheet or a gesture can find the node. Only the contract's own parts. | | `role` | One of `group`, `region`, `toolbar`, `tablist`, `tabpanel`, `status`, `search`, `list`, `listitem`, `navigation`, `none`, `presentation`, `img`. | | `aria` | `busy`, `live`, `label`, `pressed`, `expanded`, `current`, `describedby`. | | `hidden`, `inert` | Conditions. `inert` removes the subtree from the keyboard and the accessibility tree. | | `focusable` | `tabindex="-1"`: focus by script, never a tab stop. | | `data` | `data-<name>` attributes (at most 24 characters; names the game reserves, `layout-*` and `graph-*` are refused). `true` writes `data-name=""`, `false` leaves it out. | | `vars` | CSS variables: one the screen lists, or your own `--tpl-*`. Components may use `--tpl-*` only. Values are text or numbers. | The order of keyboard focus is the order of the tree (the DOM). There is no positive `tabindex`. The shortcuts of a screen (arrows, Enter, Escape) never depend on the template. ## Bindings, conditions and events {#bindings} ### Values {#values} A value is what a node shows or an output receives: - a literal: a string, a number or a boolean; - `c.bind('path')`: a path of the **input** of the screen or contract, read as text, a number or a boolean. `[]` is only allowed in the `from` of a `slot`; `$alias.field` reads the item inside an `each`. A path that holds an object or a list cannot be bound (test it with a condition instead); - `c.t('key', { name: value })`: the game's translated text. A key is lower-case letters, digits, `_` and `.`; at most 8 arguments; - `c.fmt.rate | count | percent | duration | fixed('path', digits?)`: a number formatted as the game does ([concepts](https://prism.am/dev/md/themes/concepts.md#formatting)); - a list of values, written one after the other. A path that does not exist is a type error with `c.` and a validator error at load, with the fields that do exist in its message. At run time, a path that has no data shows nothing and never throws. The paths each contract offers are in the [contracts reference](https://prism.am/dev/md/themes/contracts.md). ### Conditions {#conditions} A condition is built from `c.field('path')`: - `.eq(value)`, `.ne(value)`, `.in([values])` for text, enumerations and booleans (an enumeration is compared only with its own values; `in` takes 1 to 16); - `.gt`, `.ge`, `.lt`, `.le` for numbers; - `.truthy()` and `.falsy()` for any field, including objects and lists: present, non-empty, non-zero; - `.and(…)`, `.or(…)`, `.not()` to combine. Conditions nest 6 levels deep at most. Conditions drive `when`, `classWhen`, `hidden`, `inert`, and the `disabled` and `pressed` of a button. The field `state` that some contracts have is the state of the contract (`mapReady`, `mapBlocked`…); the operators have to fit the type of the field. ```ts theme // The main button of a map. It is off in the two states where it cannot start, and the reason is a line of text it points at (`describedBy`), so it stays readable. function playButton(c: Footer): ThemeNode { const off = c.field('state').in(['mapBlocked', 'mapRefused']); return c.row( { class: 'go-line', align: 'center', gap: 2 }, c.when(c.field('state').eq('mapBlocked'), c.text(c.bind('reason.text'), { class: 'reason', part: 'reason' })), c.button({ variant: 'primary', class: 'go', part: 'play', label: c.bind('play.label'), disabled: off, classWhen: { off }, describedBy: 'reason', on: c.on.press('confirm') }), ); } ``` ### Events {#events} An event is the call an output receives when the player uses a control: - `c.on.press('confirm')` on a `button`: the output `confirm`, no argument. - `c.on.press('playlist.start', c.bind('playlistId'))`: arguments come after the name, in the order of the output, with the right types. An argument may be a literal or a value of the input. - `c.on.change('name', …)` on a `toggle` and `c.on.pick('name', …)` on a `dropdown`: the control appends its new value (a boolean, a string) as the **last** argument; you write the ones before it. The name must be an output of **this** screen or contract. A name that is not is refused with the list of the valid ones, for example `"back" is not an output of screen.library (outputs: …)`. A component cannot call an output of its screen. A face calls none. ```ts theme // The two buttons of a playlist: play it map after map, or as one marathon. Each output takes the playlist's id, found in the input. function playlistButtons(c: Footer): ThemeNode { const off = c.field('state').eq('playlistBlocked'); return c.row( { class: 'go-line', align: 'center', gap: 2 }, c.button({ variant: 'plain', class: 'go', part: 'start', label: c.t('playlists.play'), disabled: off, on: c.on.press('playlist.start', c.bind('playlistId')) }), c.button({ variant: 'primary', class: 'go', part: 'marathon', label: c.t('playlists.marathon'), disabled: off, on: c.on.press('marathon.start', c.bind('playlistId')) }), ); } ``` ## Places and slots {#places} ### Placing a place {#placing} A screen has **places**: named positions the game fills with one of its own components. `c.slot('footer')` puts the footer where you write it. Rules: - Every **required** place must be placed at least once, inside a `when` or not (`the required slot "footer" is not placed (place it with slot("footer"); inside a when it counts)`). The required places are listed in the [contracts reference](https://prism.am/dev/md/themes/contracts.md). Optional places may be left out. - A place may be placed more than once (in a `when` branch and its `else`, for example). - You decide the wrapper, the order and the extra nodes around it. You do not decide its content. ```ts theme // The selected map: the Play strip first (the `footer` place: rating, judgement, Play), then the heading, the tabs and their panels. // While nothing is selected, `when` draws the heading alone: it is the invitation to pick a map. function selectedMap(c: Screen): ThemeNode { return c.column( { as: 'section', class: 'map', aria: { label: c.t('ui.selected_map'), busy: c.bind('selection.busy') }, vars: { '--difficulty-color': c.bind('browser.color') } }, c.when( c.field('selection.shown').truthy(), [c.box({ class: 'play' }, c.slot('footer')), c.box({ class: 'details' }, c.slot('header'), c.slot('tabs'), c.slot('panels'))], c.slot('header'), ), ); } ``` Here the strip is placed first, and the heading alone stands in for it while nothing is selected. ### Mounting a contract {#mounting} A screen may also mount a contract of the table with the data found at a path: `c.slot('library.chartRow', { from: 'entries[]' })`. The contract renders with its own template (or the default render), wherever you put it. The path must have exactly the input shape of that contract, and a contract cannot mount itself. Which contracts a screen may mount is in its entry of the [contracts reference](https://prism.am/dev/md/themes/contracts.md). ### Free places of a component {#component-slots} Inside a **component** template, `c.slot('goal')` or `c.slot('tiers')` is a place the contract leaves free: the game puts one of its own widgets there (a goal mark, a tier count). The contract lists them under *slots*. ## Repeating and choosing: each and when {#each-when} `c.when(condition, then, otherwise?)` draws `then` while the condition holds and `otherwise` if there is one. Both may be a node or a list of nodes. A small helper makes "only when there is something" easy: ```ts theme // "Only when": draws `nodes` while the field at `path` is present (not empty, not zero, not null). function present(c: Screen, path: LibraryPath, ...nodes: ThemeNode[]): ThemeNode { return c.when(c.field(path).truthy(), nodes); } ``` `c.each('path', item => node, { as?, key? })` repeats a node for every element of a list of the input. The function receives `item`, builders **typed for the element**: `item.bind('color')` reads the element's own field, `item.field('lit')` tests it. `as` names the item for `$alias.field` paths used by the nodes inside; `key` names a field that identifies each element. The function must return a node. The equalizer recipe repeats one bar per element: ```ts theme // The band: a row of bars, drawn only when the map has an equalizer (a playlist has none). `data-listening` is set while the music drives the bars, // so the stylesheet can light them. `each` repeats `bar` for every element of the list. function equalizer(c: Screen): ThemeNode { return c.when(c.field('map.equalizer').truthy(), c.row({ class: 'eq', role: 'presentation', data: { listening: c.bind('map.listening') } }, c.each('map.equalizer', bar))); } // One bar: an empty box that hands its live height to the stylesheet as a variable of this theme, `--tpl-live` (a number from 4 to 100). function bar(item: BarItem): ThemeNode { return item.box({ class: 'eq-bar', vars: { '--tpl-live': item.bind('live') } }); } ``` `each` loops over a list of the input; it never loops over numbers or your own arrays. For your own tables (a list of facts, a list of classes), use ordinary TypeScript (`FACTS.map(…)`): the tree you return is the result, and the table disappears. ## Tab groups, panels alone and the pinned preview {#tabs} `c.tabs({ label, collapsible? }, [{ label, icon?, children }, …])` is a group of tabs of your own: 1 to 12 tabs, each with its name (and an icon from the closed list) and what it shows. The bar is the game's (keyboard, focus, `data-selected` on the open tab), and the open tab is kept while the screen stays mounted. **A group of one tab draws no bar**: its content is laid out as it is. A place put in a tab exists only while that tab is open. `collapsible: true` ends the bar with a fold button (`data-part="fold"`): folded, the group shows that button alone and carries `data-collapsed`, which your `theme.css` turns into a slim strip; the page keeps the folded state for the session. A face cannot hold a group. On the song selection, each panel of the selected map also has an optional place of its own: `infoPanel`, `leaderboardPanel`, `modsPanel`, `trainingPanel`, `historyPanel`, `mapsPanel`, `editorPanel`. A panel you place is drawn there, always open, and leaves the `tabs` bar and `panels`: nothing is drawn twice. The leaderboard beside the Info panel is `c.row({}, c.slot('infoPanel'), c.slot('leaderboardPanel'))`. The place `visualizer` put **outside** a `when` that reads `browser.visualizer` (in a tab of a group, or simply in the screen) is a **pinned** preview: it starts as soon as it is on screen, follows the selection, never covers the list and never takes the focus or Escape. The Visualize button and key open the tab that holds it when that tab is closed, and otherwise pause and resume it. The game stays usable while it plays. Two shipped themes show it: `cinema` (a booth down the left edge with two tabs of its own, the preview and the leaderboard placed alone) and `blueprint` (a view always on beside the drawing's tabs). ## Faces {#faces} A **face** is the template of a card that the game keeps drawing the root of: the set card, the difficulty row, the score card (the [contracts reference](https://prism.am/dev/md/themes/contracts.md) marks every face). You write the **inside**, as a component template. You read the same input as the default card. ```ts theme // The set card: a slanted panel on the set's own picture, with the title and the artist over it, then the layout, one round dot per difficulty and the rating range. // `part` names the parts the game hangs gestures on (Ctrl+click on the artist filters by it). function setCard(c: SetCard): ThemeNode { return c.row( { class: 'sc', align: 'center', gap: 3 }, panel(c), c.column( { class: 'sc-info', grow: 1, gap: 0 }, c.text(c.bind('title'), { as: 'strong', part: 'title', class: 'sc-title' }), c.text(c.bind('artist'), { as: 'small', part: 'artist', class: 'sc-artist' }), c.row({ class: 'sc-foot', align: 'center', gap: 2 }, c.text(c.bind('keysText'), { part: 'keys', class: 'sc-keys' }), dots(c)), ), c.text(c.bind('rating.range'), { as: 'strong', part: 'rating', class: 'sc-rating' }), ); } ``` A face places the game's small widgets where it wants (`c.slot('goal')`, `c.slot('tiers')`), loops over lists of the card (`strip.chips`, the ten `stars`), and may use `part` for the gestures the game hangs on parts (Ctrl+click on `artist`). ```ts theme // The difficulty row: a round badge with the key count, the name over ten stars, and the rating at the right. // `stars` is a list of ten entries; the first ones are `lit` according to the rating, and a loop draws one text node for each. function chartRow(c: ChartRow): ThemeNode { return c.row( { class: 'dr', align: 'center', gap: 3 }, c.box({ class: 'dr-ring', part: 'keys' }, c.text(c.bind('keysText'), { class: 'dr-keys' })), c.column( { class: 'dr-main', grow: 1, gap: 0 }, c.row({ class: 'dr-line', align: 'center', gap: 1 }, c.text(c.bind('name'), { as: 'strong', part: 'name', class: 'dr-name' }), c.slot('missing'), c.slot('goal')), c.row({ class: 'dr-stars', role: 'presentation' }, c.each('stars', (star: StarItem) => star.text('★', { class: 'dr-star', classWhen: { lit: star.field('lit').truthy() } }))), ), c.row({ class: 'dr-rate', part: 'rating', align: 'baseline', gap: 1 }, c.text(c.bind('rating'), { as: 'strong', class: 'dr-rating' }), c.text(c.bind('ratingUnit'), { as: 'small', class: 'dr-unit' })), ); } ``` What the validator refuses in a face: | Refused | Why | | --- | --- | | `button`, `toggle`, `dropdown` | They are the game's own controls. A face adds no tab stop and no action. | | A `slot` that mounts another contract | A face cannot embed another one. It may place only its own widgets. | | Any call of an output | There is none to call, and none is required. | The message reads `a button is not allowed in library.setCard: the host draws and owns the card's own button, keyboard, menus and actions…`. To reach the card's root in `theme.css`, use `[data-contract='library.setCard']` after a class of your theme; see [theme.css](https://prism.am/dev/md/themes/css.md#host-elements). ## Screen inputs and outputs {#screen-io} ### Reading the input {#reading-input} A **screen** has its own input, built by the game from its stores; a component has its own, usually a slice. For the map selection, the input carries groups such as the selection (its state, colour, whether it is loading, whether it is entering and which tab is open), the browser (the view, whether the list is covered) and the facts of the selected map (`null` when no map is selected: nothing, a playlist, an invitation). The facts include its artist, title, difficulty, key count, creator, picture, rating, rate, duration, BPM, note counts, density equalizer and skillsets. Treat what is listed in the [contracts reference](https://prism.am/dev/md/themes/contracts.md) as the source: it is generated from the contract, always current, and tells for each field its type and its states. When the same path exists in several states (`mapReady`, `mapBlocked`…), the validator accepts it if any state has it. ### Screen outputs {#screen-outputs} A screen has outputs of its own, which a `button` of the **screen** template may call (a component cannot call them). They are the actions the screen offers: open the menu drawer, pick a random map, open a tab, open the settings. The names and arguments are in the contract of the screen. The Settings window is a screen, and its rail recipe calls none, but places every place it must: ```ts theme // The window: a left column (the rail) and a right column (the panel), side by side. Every place the contract requires is placed: // `title`, `search`, `actions`, `close`, `notices`, `rail` and `panel`; `hints` (the keyboard hints) is the only optional one. function settingsScreen(c: Settings): ThemeNode { return c.row({ as: 'section', class: 'win' }, rail(c), main(c)); } // The left column: the title with, under it, how many settings differ from the shipped ones, then the search, the list of categories, and at the foot the window's buttons. // `changed` is a number of the input of the screen; `c.t` with an argument is the game's translated, pluralised sentence. function rail(c: Settings): ThemeNode { return c.column( { as: 'aside', class: 'side' }, c.column( { class: 'head', gap: 1 }, c.slot('title'), c.when(c.field('changed').gt(0), c.text(c.t('settings.changed_count', { count: c.bind('changed') }), { as: 'small', class: 'changed' })), ), c.box({ class: 'find' }, c.slot('search')), c.slot('rail'), c.row({ class: 'buttons', align: 'center', gap: 1 }, c.slot('actions'), c.slot('close')), ); } ``` `c.t('settings.changed_count', { count: c.bind('changed') })` is the game's translated, pluralised sentence. Its argument is a number of the screen's input. ## What the validator refuses {#refused} Each template is validated alone. A refused template is dropped (the base's, or the game's own render, draws instead) with a notice of the form `<contract>[ › <node chain>]: <reason>`. The rules, with the messages they give: - the kinds, attributes, types and sizes of the node list above (`this node has no attribute "…" (it has: …)`, `"…" is not a node kind (kinds: …)`); - `class` is a class of `theme.css` or a class the screen or contract lists (`the class "…" is neither defined by theme.css nor a class of the game here (game classes: …)`); - every path exists in the input (`the path "…" is not in the screen: no field "…" in "…" (fields: …)`); - the operators go with the type of the field, and an enumeration is only compared with its values; - every output called exists, with its arguments in order and of the right type; a **required** output must be called by a control; - every **required** place of a screen is placed (`the required slot "…" is not placed`); - `part` is a part of the contract; `image` is a file of `images/`; - the limits above. Reading these messages, with a catalogue of the invalid examples, is the subject of [reading errors](https://prism.am/dev/md/themes/errors.md). ## Where to look things up {#lookup} | You want | Look at | | --- | --- | | Every node, attribute and its type | [nodes](https://prism.am/dev/md/themes/nodes.md), or hover in your editor | | What a screen offers: input, outputs, places, classes, variables | [contracts](https://prism.am/dev/md/themes/contracts.md) | | Which token does what | [tokens](https://prism.am/dev/md/themes/tokens.md) | | A complete working theme to copy | the [cookbook](https://prism.am/dev/md/themes/cookbook.md) | | What an error means | [reading errors](https://prism.am/dev/md/themes/errors.md) | | The full types | [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts) | ===== Page: theme.css Address: https://prism.am/dev/themes/css/ Derived from: docs/themes.md, crates/themes/src/stylesheet.rs, crates/themes/src/library.rs, apps/web/src/theme/tokens.css, apps/web/src/menu/settled.ts # theme.css The validated CSS subset of a theme: how it is rewritten, how to reach the game's elements, plate variables, specificity, motion, images, limits and the full allow-list. `theme.css` gives a look to the classes that your `theme.ts` creates. It is optional: a theme with no templates needs none. It is not ordinary CSS: Rust reads it, keeps only a validated subset, and rewrites it so that it can only affect your theme. A file that breaks a rule removes the whole theme from the list, with the line number in the message. This page explains how to think about the subset. The exhaustive list of selectors, at-rules and properties is [generated from the validator](https://prism.am/dev/md/themes/css.md#allowlist) and always matches it. ## What theme.css is for {#what} Tokens set the palette, the fonts and the shapes of the whole game. `theme.css` is for what tokens cannot say: the layout of the boxes you add in a template, a gradient behind one of them, a border on the Play strip, a slanted card, a motion. Everything the game already draws keeps following your tokens; use `theme.css` to place and decorate your own classes and to adjust a few of the game's elements through their marks. A template and its stylesheet go together. Every class a template uses must either be defined in `theme.css` (even a class that only names a box) or be a class the screen lists (`song-select`, `pv-screen`… the [contracts reference](https://prism.am/dev/md/themes/contracts.md) lists them per screen). A class that is neither is refused, and a class that is both is ambiguous. A small stylesheet for the [first layout](https://prism.am/dev/md/themes/quick-start.md#first-layout): ```css /* The classes of theme.ts: two columns, the library first, the selected map second. */ .screen { display: flex; flex-direction: row; align-items: stretch; gap: var(--pv-s6); height: 100%; min-height: 0; } .map { display: flex; flex-direction: column; flex: 1 1 0; min-width: 0; min-height: 0; } .library { display: flex; flex-direction: column; flex: 1 1 0; min-width: 0; min-height: 0; } .map > .details { display: flex; flex-direction: column; flex: 1 1 0; min-height: 0; overflow: hidden; } /* The Play strip stays pinned above the heading; a hairline under it separates it from the map. */ .map > .play { border-bottom: 1px solid var(--pv-line); padding-bottom: var(--pv-s3); } ``` ## How it is rewritten {#rewriting} Before the page sees your file, the validator: - renames every class `.name` to `.tpl-<id>-name` (`<id>` is your theme's id), in the stylesheet and in the templates that use it; - places every selector under `[data-direction="<id>"]`, so a rule can only apply while your theme is worn; - renames every `@keyframes` and the animations that use it the same way; - replaces each `url("images/x.png")` by the address the game serves that picture at. ```text /* what you write */ .play { border-bottom: 1px solid var(--pv-line); } /* what the page receives (for a theme named "first-layout") */ [data-direction="first-layout"] .tpl-first-layout-play { border-bottom: 1px solid var(--pv-line); } ``` You never write the prefix yourself. Class names are lower-case letters, digits and hyphens, starting with a letter, 40 characters at most. ## Selectors {#selectors} - A rule starts with one of **your classes**: `.name`. No element selector (`div`), no `*`, no `#id`, no `:root`, no `body`. - After the first compound selector you may use `[data-state]`, `[data-state="value"]` (letters, digits, `-`, `_` and `.`, 40 characters at most) and your classes. Attributes are `data-<name>` only, with `=` as the only operator. - States: `:hover`, `:focus-visible`, `:focus-within`, `:active`, `:disabled`, `:first-child`, `:last-child`. `:not(…)`, `:is(…)` and `:where(…)` take your classes and these states, not nested. - Combinators: descendant (a space) and `>`. Lists separated by commas. - Pseudo-elements: `::before` and `::after`, once, at the end of a selector, with a `content` that is `none`, `normal` or one short string (80 characters at most, no `\`, no `attr()`, no counter). The text they draw is **decoration** that a screen reader may still read: never put information in it. Use them for arrows, rules and diamonds without adding a node. ## Reaching the game's elements {#host-elements} The game draws most of the screen itself. You reach its elements by their `data-*` marks, **never by their classes** (the game's classes are not part of the contract and may change). - `data-part`: the named parts of a contract, such as `[data-part='play']` on the Play button or `[data-part='tablist']` on the tabs. The parts of each contract are in the [contracts reference](https://prism.am/dev/md/themes/contracts.md). - `data-contract`: the root of a component or a card, such as `[data-contract='library.setCard']`. The dot is allowed in a value so that you can name a contract. - State marks the game puts on its elements: `[data-active]` (the open or selected card), `[data-selected]`, `[data-state]`, `[data-edge]` (the accent edge of a plate), `[data-entering]` (the selection just settled). Your selector must still start with one of your classes, so give an ancestor a class in your template and descend from it: ```text .bar [data-part='play'] { … } .stage .deck [data-part='tablist'] { … } .rack [data-contract='library.setCard'][data-active] { … } ``` The recipes in the [cookbook](https://prism.am/dev/md/themes/cookbook.md) do exactly this. ## Variables {#variables} A rule may set only these custom properties; the validator refuses any other. - **`--tpl-*` variables of your theme.** A template node sets one with `vars: { '--tpl-i': 3 }`, and the stylesheet reads it with `var(--tpl-i)`, for example inside a `calc()`. This is how data reaches the stylesheet: the equalizer recipe passes each bar's height as `--tpl-live`. - **Plate variables of the design system:** `--plate` and `--edge` (a colour or a gradient) and `--clip` and `--clip-edge` (a shape). A plate (`.pv-plate`, the map header, a card) paints its background and its edge with them, so a rule can redraw the plates of a region. - **Design tokens `--pv-*`** of the types colour, length, font, weight, opacity, easing, clip, filter, duration, shadow, ratio and case, with the same grammar as `tokens.css`. Set by a rule, a token applies to its subtree only. - **Variables the game puts on its own elements** can be **read** with `var()`: `--set-color`, `--edge`, `--difficulty-color`, `--row-distance`, `--selection-color`. The [contracts reference](https://prism.am/dev/md/themes/contracts.md) lists those of each screen and contract. What stays in `tokens.css`: layout words, images, the shade layers (`--pv-shade`), the map picture's filter (`--pv-art-filter`) and the colour scheme. The page reads them at the root. ```css /* A design token can be set by a rule: here the heading's rating is smaller. `--plate` is the variable plates paint their background with: transparent lets the picture show. */ .hero-main { display: flex; flex-direction: column; gap: var(--pv-s1); min-width: 0; --pv-fs-rating: clamp(44px, 4.2vw, 76px); --pv-plate-filter: none; } .hero-main [data-edge] { --plate: transparent; --edge: linear-gradient(180deg, var(--difficulty-color), transparent); } ``` The first rule sets two tokens for the banner's subtree only. The second one redraws the plate of the title, so that the map's picture shows through. ## Specificity against the game's components {#specificity} A rule of yours is prefixed and scoped, but it may still be **less specific** than a rule of one of the game's components (`.game .scroller button`), and then the game wins. You cannot use `!important`. To win without it, repeat a mark so that your selector weighs more: ```text .tabs [data-part='tablist'] [data-part='tab'][data-part][data-tab] { … } ``` Do not try to target the game's classes (`.bar-menu`, `.search-bar`); adjust fine details with tokens set on the right subtree instead: `--pv-line: transparent` on `[data-contract='library.search']` removes the hairlines of the search bar. The three menus of the search bar carry `data-part="group"`, `"sort"` and `"filter"` so that a theme can dress all three alike. ## Rules, properties and values {#properties} - **At-rules:** `@keyframes` and `@media` only. `@media` accepts `(min-width | max-width | min-height | max-height: <n>px)` (a whole number from 1 to 10 000) and `(prefers-reduced-motion: reduce | no-preference)`, at most two conditions joined by `and`. No at-rule inside `@media`. - **Properties:** an allow-list (layout, typography, colours, borders, shadows, `clip-path`, transforms, transitions, animations…) with typed values: lengths, colours, `var(--pv-*)`, `calc()`, `color-mix()`, gradients. `z-index` is a whole number from -50 to 50. `position` is any value but `fixed`. `filter` takes `blur`, `saturate`, `brightness`, `contrast`, `grayscale`, `sepia`, `hue-rotate` and `drop-shadow`; `backdrop-filter` takes `blur` (0 to 64 px) and `saturate` (0 to 4), as written numbers. `writing-mode` sets vertical text; `mask-image` takes a gradient or a picture of `images/` (with `mask-size`, `mask-position`, `mask-repeat`) for an edge that fades out. - **Refused anywhere:** `!important`, `@import`, `@font-face` (a theme's fonts are declared in `theme.json`, `fonts`), `expression`, a backslash escape, a url that is not `url("images/…")`. - **Every colour comes from a token** in a well-made theme: `var(--pv-text)`, `var(--pv-line)`, `var(--difficulty-color)`. A hard-coded colour will not follow a light variant or the player's accent. ## Animation and motion {#animation} The central rule: **no infinite animation on a screen at rest.** An `infinite` loop repaints its area every frame even when nothing else moves; it was measured at about three CPU cores for fifteen equalizer bars and two glows on an idle menu. The validator accepts `infinite` but **warns** (`"<id>": theme.css: warning: line N: an infinite animation repaints the page every frame…`). See [concepts](https://prism.am/dev/md/themes/concepts.md#animation-rule) for the reasoning. So decorative motion plays once per selection: - hang it on `[data-entering]` (put `data: { entering: c.bind('selection.entering') }` on the node so it carries the attribute), with a finite iteration count; or on `:hover` and `:focus-visible`; - wrap every moving animation and transition in `@media (prefers-reduced-motion: no-preference)`. The game's own motion stops under reduced motion, yours does not unless you wrap it ([concepts](https://prism.am/dev/md/themes/concepts.md#reduced-motion)); - move with `transform` and `opacity`, not with `width`, `height` or `top`, which lay the page out again each frame; - do not put a `transition` on elements that update many times a second, such as the live bars. A rule of the equalizer recipe that follows all of this: ```css /* A bar is always full height and is SCALED: `transform` does not lay the page out again, where `height` would, thirty times a second. `--tpl-live` runs from 4 to 100. There is NO `transition` here: the page has already eased the levels, and a transition makes the browser restyle every bar on every frame for nothing the eye can see. */ .eq-bar { flex: 1 1 0; min-width: 2px; height: 100%; opacity: .75; transform-origin: bottom; transform: scaleY(calc(var(--tpl-live) / 100)); background: linear-gradient(180deg, var(--pv-accent), color-mix(in srgb, var(--pv-accent) 20%, transparent)); } ``` An `@keyframes` may have 24 steps at most, and an animation must name a `@keyframes` of the same file. ## filter, box-shadow and clip-path {#clip-path} A `filter` or a `box-shadow` set on the **same element** as a `clip-path` is cut by that `clip-path`: the shadow lies outside the shape, so it disappears. To get a shadow that follows a cut shape, put `filter: drop-shadow(…)` on a **parent** of the clipped element, and the `clip-path` on the child: ```text .tile-shadow { filter: drop-shadow(0 4px 8px rgb(0 0 0 / .5)); } .tile { clip-path: polygon(16px 0, 100% 0, 100% 100%, 0 100%); } ``` In the template, `.tile-shadow` is a `box` that holds the `.tile` box. The same applies to the game's plates: they are cut shapes, which is why their depth is the token `--pv-plate-filter` (a `drop-shadow`) and not a box shadow. ## Images {#images} A picture is `url("images/x.png")`, and only that: a file of your folder's `images/` (`png`, `jpg`, `jpeg`, `webp`, `gif` or `svg`, 4 MiB at most). No remote address, no `data:`. A path that does not exist, leaves the folder or is not a picture is refused. A template names the same files with an `image` node (`c.image('images/x.png', { alt: '' })`), and a token with `image("images/x.png")`. The map's own picture is not one of yours: a template reads its path with `c.bind('map.background')` into an `image` node, as the hero-banner recipe does. ## Limits {#limits} | Limit | Value | | --- | --- | | File size | 256 KiB | | Rules | 2048 | | Declarations in one rule | 40 | | Steps in one `@keyframes` | 24 | | Length of a `content` string | 80 characters | | `z-index` | -50 to 50 | | Images | 4 MiB each, 512 files, 4 levels | A file over a limit or outside the subset removes the theme from the list, with the line number in the message (`"<id>": theme.css: line N: …`). Fix the file and use *Reload themes*. ## The exhaustive list {#allowlist} This part is generated from the validator in `crates/themes/src/stylesheet.rs`. It is also available alone as [the CSS allow-list](https://prism.am/dev/md/themes/css-allowlist.md). - **Limits**: file <= 256 KiB; <= 2048 rules (style rules + keyframe steps); <= 40 declarations per rule; <= 200 words/numbers per value; functions nest <= 5; strings <= 80 chars (no `\`); class, keyframes name <= 40 chars (a-z 0-9 -, start with a letter); data-name <= 24, data value <= 40; no `!important`, no nesting, comments allowed. - **Selectors**: `.class` first (compound `.a.b`), `[data-x]`, `[data-x="v"]`; `:hover` `:focus-visible` `:focus-within` `:active` `:disabled` `:first-child` `:last-child`; `:not(.a)` `:is(.a)` `:where(.a)` (classes only, not nested); `::before` `::after` (once, last, with `content`); combinators: descendant, `>`; comma lists. Refused: elements, `*`, `#id`, `+`, `~`, `&`. - **At-rules**: `@keyframes` `@media` only. `@media (<feature>: <value>)` <= 2 joined by `and`; features `max-width` `min-width` `max-height` `min-height` `prefers-reduced-motion` (px 1..10000; reduced-motion reduce|no-preference); style rules only inside. `@keyframes name` steps `from`|`to`|`n%`, <= 24; every animation name must be defined in the file. - **Values**: length px|em|rem|vw|vh|vmin|vmax|ch or 0 (|n| <= 10000); % (<= 10000); number (<= 100000); angle deg|turn|rad (<= 3600); time s|ms (<= 60000); fr (<= 1000); "string"; colour #rgb|#rgba|#rrggbb|#rrggbbaa; `url("images/<file>")` of a picture the theme has; plain words are accepted unless the property is a closed list; `var(--x[, fallback])` anywhere. - **Properties** (any other property is refused; `*` = every property with that prefix): length: letter-spacing word-spacing; length+color: box-shadow text-shadow; length+number+color: outline, outline-*; length+percentage: background-* bottom column-gap flex-basis gap height inset left margin, margin-* mask-position mask-size max-height max-width min-height min-width object-position padding, padding-* right row-gap top transform-origin width; length+percentage+number: flex font-* line-height; length+percentage+number+color: border, border-* (except border-image*) text-*; length+percentage+number+color+angle+url+gradient: background; length+percentage+number+fraction+string+grid: grid, grid-*; length+percentage+number+string: font; percentage+number: opacity; number: aspect-ratio flex-grow flex-shrink order; number+time+easing: animation-* transition, transition-*; color: background-color color; string: content font-family; url+gradient: background-image mask-image; transform: transform; filter+backdrop: filter; backdrop: backdrop-filter; shape: clip-path; words: align-* flex-direction flex-flow flex-wrap justify-* overflow-wrap place-* white-space word-break. - **Closed words**: cursor: auto|default|pointer|text|move|not-allowed|grab|grabbing|wait|help|crosshair|progress|zoom-in|zoom-out|none; display: flex|grid|block|none|inline-flex|inline-block|inline|inline-grid|contents; mask-repeat: repeat|no-repeat|repeat-x|repeat-y|round|space; mix-blend-mode: normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity|plus-lighter; object-fit: fill|contain|cover|none|scale-down; overflow: visible|hidden|auto|scroll|clip; overflow-x: visible|hidden|auto|scroll|clip; overflow-y: visible|hidden|auto|scroll|clip; pointer-events: auto|none; position: static|relative|absolute|sticky; visibility: visible|hidden|collapse; writing-mode: horizontal-tb|vertical-rl|vertical-lr|sideways-rl|sideways-lr; z-index: integer -50..50|auto; content: string (no attr(), counters). - **Functions**: backdrop: blur saturate; color: rgb rgba hsl hsla hwb color-mix; easing: cubic-bezier steps; filter: blur brightness contrast drop-shadow grayscale hue-rotate saturate sepia; gradient: linear-gradient repeating-linear-gradient radial-gradient repeating-radial-gradient conic-gradient repeating-conic-gradient; grid: repeat minmax fit-content; math: calc min max clamp var; shape: polygon inset; transform: translate translatex translatey translatez translate3d scale scalex scaley scale3d rotate rotatex rotatey rotatez skew skewx skewy. - **Variables**: `--tpl-<name>` (<= 32 chars, any value); design tokens of kind case|clip|color|duration|easing|filter|font|length|opacity|ratio|shadow|weight (subtree only; the other kinds and --pv-art-filter stay in tokens.css); plate variables --plate --edge --clip --clip-edge. Class names become `.tpl-<id>-name` and every rule is scoped under `[data-direction="<id>"]`. ===== Page: Token reference Address: https://prism.am/dev/themes/tokens/ Derived from: crates/themes/tokens.json, crates/themes/src/grammar.rs, crates/themes/src/css.rs, crates/themes/src/artwork.rs, crates/themes/src/curves.rs # Token reference Every design token a theme may set in tokens.css: its type, its bounds, its words and what it changes. A token is a CSS custom property `--pv-<name>` that the game's own stylesheets read. A theme sets some of the 310 tokens of the contract in `tokens.css`; the others keep the game's value, so a theme may be partial. This page is generated from `crates/themes/tokens.json`, the file the validator itself reads: a name that is not in it is refused. Each token has a **kind**, a typed value that Rust parses with a strict grammar, and sometimes bounds. ## Contents {#contents} The tables are grouped by purpose. - [Value kinds](#kinds) - [The file tokens.css](#file) - [Base colours](#colors) - [Text colours](#text) - [Surfaces](#surfaces) - [State tones](#tones) - [Results and ranks](#ranks) - [Typography](#typography) - [Spacing and sizes](#spacing) - [Radii](#radii) - [Borders and focus](#borders) - [Plate shapes](#shapes) - [Shadows](#shadows) - [Motion](#motion) - [Map picture and overlays](#artwork) - [Progression graph](#graph) - [Layout choices](#layout) - [Component tokens](#components) - [Rules that cross several tokens](#rules) ## Value kinds {#kinds} Each token has one kind. A value that does not match its kind is refused, whatever the CSS meaning of the words. | Kind | Accepted values | | --- | --- | | `color` | `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`; `rgb()`, `rgba()`, `hsl()`, `hsla()` with plain numbers, in comma syntax or space syntax (`/ alpha`); `color-mix(in srgb, <color> [n%], <color> [n%])`; `transparent`, `white`, `black`; and `var(--pv-<color token>)`, the only reference a value may make. Channels are 0–255 (or percentages), alpha 0–1, hue −360 to 720 `deg`, saturation and lightness 0–100 %. Functions nest at most 4 deep. | | `length` | A number with a unit (`px`, `em`, `rem`, `%`, `vw`, `vh`, `vmin`, `vmax`) or a bare `0`; `clamp(a, b, c)`, `min(a, b)` and `max(a, b)` of lengths, nested at most 2 deep. At most 10 000 px, or 1 000 in any other unit. Never negative unless the token is marked *negative allowed*. The bounds of a token (the Bounds column) are checked on values written in `px`. | | `font` | 1 to 8 families separated by commas: quoted names or plain words (letters, digits, spaces, `.`, `_`, `-`, at most 64 characters), the last one a generic family (`sans-serif`, `serif`, `monospace`, `system-ui`, `ui-monospace`, `cursive`). | | `weight` | A whole number from 1 to 1000. | | `opacity` | A number from 0 to 1. | | `easing` | `ease`, `ease-in`, `ease-out`, `ease-in-out`, `linear`, or `cubic-bezier(x1, y1, x2, y2)` with x from 0 to 1 and y from −4 to 4. | | `clip` | `none`; `polygon(x y, …)` with 3 to 16 points whose coordinates are lengths or `calc(<n>% ± <n>px)`; or `inset(…)` with 1 to 4 offsets, then optionally `round` and 1 to 4 radii. | | `layers` | `none`, or 1 to 4 comma-separated `linear-gradient(…)` or `repeating-linear-gradient(…)`: an optional angle (`90deg`, from −720 to 720) or `to <side> [side]`, then 2 to 12 stops, each a colour followed by up to two positions. Other gradients are refused. | | `filter` | `none`, or up to 6 functions among `saturate()`, `brightness()`, `contrast()`, `grayscale()`, `sepia()`, `opacity()` (a number up to 4, or a percentage up to 400 %), `hue-rotate(<n>deg)`, `blur(<n>px)` (at most 12 px) and `drop-shadow(<x> <y> [<blur>] <color>)` (offsets at most 48 px, blur not negative). | | `image` | `none`, or `image("relative/path.png")`: a picture of the theme folder (png, jpg, jpeg, webp, gif, svg), at most 4 MiB. The path is in double quotes, relative, inside the folder. | | `duration` | A number followed by `ms` or `s`, from 0 to 3 seconds. | | `shadow` | `none`, or 1 to 4 comma-separated shadows `[inset] <x> <y> [<blur> [<spread>]] <color>`. Lengths are in `px` (or a bare `0`), at most 128 px, the blur not negative; the colour comes last. | | `ratio` | A unitless number inside the bounds of the token (line heights). | | `case` | `none`, `uppercase`, `lowercase` or `capitalize`. | | `scheme` | `dark` or `light`. | | `choice` | One word of the list of the token, written alone. Any other word, several words, an empty value, a number or a `var()` is refused. The first word of a list is the current layout and the value of a token that is not set. | ### Reading the tables {#reading} **Bounds** apply to a `px` value: `0–400 px` is a range, `≥ 12 px` a minimum (the type scale never goes under 12 px), `≤ 64 px` a maximum. A length token with no bounds is any non-negative length. `#rrggbb only` means a plain six-digit colour (the progression-graph colours, whose hues the validator compares). For a `choice`, the Bounds column lists the words; the first is the default. ## The file tokens.css {#file} A file holds one `:root` block and up to two `@media (max-width: <n>px)` blocks for narrow windows, each holding one `:root` block: ```text :root { --pv-bg: #0b0a0d; --pv-accent: #ff5c93; } @media (max-width: 1100px) { :root { --pv-art-w: 92px; } } ``` - Nothing else: no other selector, property, at-rule (`@import`, `@font-face`), nesting or `url()`. Comments `/* … */` are allowed. - At most 64 KiB per file, 200 declarations in all and 600 characters per value. A `@media` width is from 320 to 4000 px, and a file has at most 2 such blocks. - A token that is not set keeps the game's value. A token set in a `@media` block is laid over the base block in windows that narrow. Picture tokens (kind `image`) belong in the main `:root` block only. - A value uses letters, digits and the characters ` #%.,()/-+_'"`. These words are refused anywhere in a value: `url(`, `expression`, `@import`, `javascript`, `image-set`, `element(`, `attr(`, `env(`, `calc-size`. - A file that is refused removes its theme from the list; the message names the line, the token and the reason (see [reading errors](https://prism.am/dev/md/themes/errors.md)). ## Base colours {#colors} The palette every other colour starts from: page background, plates, lines, the accent and its states, and the scheme of the native controls. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-bg` | `color` | — | Page background and the colour gaps and cut-outs show. | | `--pv-plate` | `color` | — | Surfaces of panels (plate), raised controls, hovered and selected ones. | | `--pv-plate-raised` | `color` | — | Surfaces of panels (plate), raised controls, hovered and selected ones. | | `--pv-plate-hover` | `color` | — | Surfaces of panels (plate), raised controls, hovered and selected ones. | | `--pv-plate-active` | `color` | — | Surfaces of panels (plate), raised controls, hovered and selected ones. | | `--pv-plate-active-hover` | `color` | — | Surfaces of panels (plate), raised controls, hovered and selected ones. | | `--pv-line` | `color` | — | Hairlines and the empty part of gauges. | | `--pv-track` | `color` | — | Hairlines and the empty part of gauges. | | `--pv-ink` | `color` | — | Text drawn on an accent-coloured surface. | | `--pv-accent` | `color` | — | The theme's own accent: used unless the player opted in to the map's artwork or a colour of their own (`accentSource`), and always by a theme with `"accent": "fixed"`. | | `--pv-accent-2` | `color` | — | A second accent for secondary marks: a goal pin, a goal that follows the current judgement. | | `--pv-color-scheme` | `scheme` | — | Whether native controls (scrollbars, inputs) are dark or light. | | `--pv-thumb` | `color` | — | The raised thumb of a tab bar's or selector's selected tab (with `--pv-layout-controls: pill`); the hovered plate when unset. The Settings segmented control does not read it: it is drawn with `--pv-clip-sm` and the accent. | | `--pv-switch` | `color` | — | The colour of a switch that is on: the shared Settings `Switch` and, with `--pv-layout-controls: pill`, hand-written switches; the accent when unset. | | `--pv-accent-hover` | `color` | — | Accent of a hovered accent-filled control. | | `--pv-accent-press` | `color` | — | Accent of a pressed accent-filled control. | | `--pv-accent-soft` | `color` | — | A faint tint of the accent: the fill of a badge, a selection, a highlighted row. | ## Text colours {#text} Primary, secondary and tertiary text, and the colours of disabled text, placeholders and links. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-text` | `color` | — | Primary, secondary and tertiary text. | | `--pv-text-2` | `color` | — | Primary, secondary and tertiary text. | | `--pv-text-3` | `color` | — | Primary, secondary and tertiary text. | | `--pv-text-disabled` | `color` | — | Text of a disabled control. | | `--pv-text-placeholder` | `color` | — | Text of an empty field (its placeholder). | | `--pv-text-link` | `color` | — | Text of a link. | ## Surfaces {#surfaces} Surface levels (1 resting, 2 raised, 3 hovered, 4 selected, sunken) and the veil behind dialogs. By default they are the `--pv-plate*` tokens. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-scrim` | `color` | — | The veil drawn behind a modal dialog. | | `--pv-surface-1` | `color` | — | Surface of level 1: panels and resting plates. | | `--pv-surface-2` | `color` | — | Surface of level 2: raised controls and cards. | | `--pv-surface-3` | `color` | — | Surface of level 3: a hovered control or row. | | `--pv-surface-4` | `color` | — | Surface of level 4: a selected or pressed control or row. | | `--pv-surface-sunken` | `color` | — | Surface of a recessed area (the inside of a text field). | ## State tones {#tones} Information, success, warning and error tones, their soft tints and the hover and press states of the error tone. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-ok` | `color` | — | Success, warning and error tones. | | `--pv-warn` | `color` | — | Success, warning and error tones. | | `--pv-danger` | `color` | — | Success, warning and error tones. | | `--pv-info` | `color` | — | Information tone. | | `--pv-ok-soft` | `color` | — | A faint tint of the success tone. | | `--pv-warn-soft` | `color` | — | A faint tint of the warning tone. | | `--pv-danger-soft` | `color` | — | A faint tint of the error tone. | | `--pv-info-soft` | `color` | — | A faint tint of the information tone. | | `--pv-danger-hover` | `color` | — | Error tone of a hovered destructive control. | | `--pv-danger-press` | `color` | — | Error tone of a pressed destructive control. | ## Results and ranks {#ranks} Colours of the hit offset on the result screen, of the achievement tiers, of the podium, and how much black darkens the text of tiers and ratings. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-offset-ok` | `color` | — | Mean hit offset colours. | | `--pv-offset-warn` | `color` | — | Mean hit offset colours. | | `--pv-offset-high` | `color` | — | Mean hit offset colours. | | `--pv-offset-bad` | `color` | — | Mean hit offset colours. | | `--pv-tier-platinum` | `color` | — | Achievement tiers above gold (bronze, silver and gold are the podium colours). | | `--pv-tier-diamond` | `color` | — | Achievement tiers above gold (bronze, silver and gold are the podium colours). | | `--pv-tier-prism` | `color` | — | Achievement tiers above gold (bronze, silver and gold are the podium colours). | | `--pv-tier-prism-b` | `color` | — | Achievement tiers above gold (bronze, silver and gold are the podium colours). | | `--pv-tier-prism-c` | `color` | — | Achievement tiers above gold (bronze, silver and gold are the podium colours). | | `--pv-gold` | `color` | — | Podium ranks. | | `--pv-silver` | `color` | — | Podium ranks. | | `--pv-bronze` | `color` | — | Podium ranks. | | `--pv-tier-dark` | `opacity` | — | How much black is mixed into the colour of judgement tier TEXT (0 to 1; 0 keeps the game colours). Light themes raise it so the tier names stay readable; the colour swatches and the colour of the tier in the data are never touched. | | `--pv-rating-dark` | `opacity` | — | How much black is mixed into the colour of rating TEXT (difficulty and skill values, 0 to 1; 0 keeps the game colours, `ratingColor` itself is never touched). Light themes raise it so the numbers stay readable. | ## Typography {#typography} Type scale, line heights, letter spacing, font stacks, weights and text case. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-display-ls` | `length` | negative allowed | Letter spacing of display text, labels, titles and big numerals. | | `--pv-label-ls` | `length` | negative allowed | Letter spacing of display text, labels, titles and big numerals. | | `--pv-title-ls` | `length` | negative allowed | Letter spacing of display text, labels, titles and big numerals. | | `--pv-hero-ls` | `length` | negative allowed | Letter spacing of display text, labels, titles and big numerals. | | `--pv-fs-xs` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-sm` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-md` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-lg` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-xl` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-2xl` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-3xl` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-hero` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-meta` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-accuracy` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-title` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-fs-rating` | `length` | ≥ 12 px | Type scale; every size is at least 12px. | | `--pv-font-display` | `font` | — | Font stacks: display text, body, numerals, labels, technical details (`PrismLegacy` is the game font). | | `--pv-font-body` | `font` | — | Font stacks: display text, body, numerals, labels, technical details (`PrismLegacy` is the game font). | | `--pv-font-num` | `font` | — | Font stacks: display text, body, numerals, labels, technical details (`PrismLegacy` is the game font). | | `--pv-font-label` | `font` | — | Font stacks: display text, body, numerals, labels, technical details (`PrismLegacy` is the game font). | | `--pv-font-mono` | `font` | — | Font stacks: display text, body, numerals, labels, technical details (`PrismLegacy` is the game font). | | `--pv-fw-display` | `weight` | — | Font weights. | | `--pv-fw-num` | `weight` | — | Font weights. | | `--pv-fw-label` | `weight` | — | Font weights. | | `--pv-display-case` | `case` | — | Text transform of display text and labels. | | `--pv-label-case` | `case` | — | Text transform of display text and labels. | | `--pv-fs-2xs` | `length` | ≥ 12 px | Smallest size of the type scale. | | `--pv-fs-4xl` | `length` | ≥ 12 px | Largest size of the type scale. | | `--pv-lh-tight` | `ratio` | 0.8–3 | Line height of big titles and numerals. | | `--pv-lh-snug` | `ratio` | 0.8–3 | Line height of labels and compact text. | | `--pv-lh-normal` | `ratio` | 0.8–3 | Line height of running text. | | `--pv-lh-loose` | `ratio` | 0.8–3 | Line height of long paragraphs. | | `--pv-ls-tight` | `length` | negative allowed | Tight letter spacing (large type). | | `--pv-ls-normal` | `length` | negative allowed | Normal letter spacing. | | `--pv-ls-wide` | `length` | negative allowed | Wide letter spacing (small capitals). | | `--pv-fw-regular` | `weight` | — | Regular weight. | | `--pv-fw-medium` | `weight` | — | Medium weight. | | `--pv-fw-semibold` | `weight` | — | Semibold weight. | | `--pv-fw-bold` | `weight` | — | Bold weight. | | `--pv-fw-body` | `weight` | — | Weight of running text. | ## Spacing and sizes {#spacing} The spacing scale, gutters, control heights, the song-list heights and gaps, the drawer widths and the page margins. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-h-sm` | `length` | — | Control heights. | | `--pv-h-md` | `length` | — | Control heights. | | `--pv-h-lg` | `length` | — | Control heights. | | `--pv-set-row` | `length` | 8–400 px | Song list heights: a set card and a difficulty row (reported to the list model). | | `--pv-set-gap` | `length` | 0–100 px | Song list gaps: below a set card and below a difficulty row (reported to the list model with the heights). | | `--pv-diff-row` | `length` | 8–400 px | Song list heights: a set card and a difficulty row (reported to the list model). | | `--pv-diff-gap` | `length` | 0–100 px | Song list gaps: below a set card and below a difficulty row (reported to the list model with the heights). | | `--pv-set-grid-w` | `length` | 0–600 px | A grid of set cards instead of a list: the least width of a card (0, the default, keeps the list). The list lays out as many columns as fit, from 1 to 6, each card as wide as its share; the expanded set's difficulties stay full-width rows under its row of cards. | | `--pv-set-grid-aspect` | `ratio` | 0.3–3 | With a grid (`--pv-set-grid-w` above 0): the height of a card over its width (1 is a square sleeve). The card's height replaces `--pv-set-row`. | | `--pv-rail-w` | `length` | 40–600 px | Width of the collapsed (icon rail) and expanded Escape drawer. | | `--pv-drawer-w` | `length` | 40–600 px | Width of the collapsed (icon rail) and expanded Escape drawer. | | `--pv-page-pad` | `length` | 0–160 px | The gutter between the window's edge and the menus, at both sides (the default leaves 40px; a theme that wants the screen to fill the window sets a small one). | | `--pv-page-max` | `length` | 800–8000 px | The widest the menus grow: a window wider than this leaves its extra room as margins (the default is 1800px; a theme that fills any window sets a large one). | | `--pv-page-scrim` | `color` | — | The veil laid over the map picture behind every page except the song selection (Download, Multiplayer, Profile, Clan, Skins, Mods, Help, a score's analysis), under the page's titles and tabs: a very bright picture then never reaches their text. Defaults to the page background colour at 78% (at most 90%: the picture stays visible); the song selection keeps `--pv-shade` alone. | | `--pv-page-art-blur` | `length` | 0–40 px | How much the map picture is blurred behind `--pv-page-scrim` on every page except the song selection (0 keeps it sharp). | | `--pv-s0` | `length` | 0–400 px | Spacing step 0 (none). | | `--pv-s1` | `length` | 0–400 px | Spacing step 1. | | `--pv-s2` | `length` | 0–400 px | Spacing step 2. | | `--pv-s3` | `length` | 0–400 px | Spacing step 3. | | `--pv-s4` | `length` | 0–400 px | Spacing step 4. | | `--pv-s5` | `length` | 0–400 px | Spacing step 5. | | `--pv-s6` | `length` | 0–400 px | Spacing step 6. | | `--pv-s7` | `length` | 0–400 px | Spacing step 7. | | `--pv-s8` | `length` | 0–400 px | Spacing step 8. | | `--pv-s9` | `length` | 0–400 px | Spacing step 9. | | `--pv-s10` | `length` | 0–400 px | Spacing step 10. | | `--pv-gap-sm` | `length` | 0–400 px | Small gap between neighbouring elements. | | `--pv-gap-md` | `length` | 0–400 px | Medium gap. | | `--pv-gap-lg` | `length` | 0–400 px | Large gap between zones. | | `--pv-gutter` | `length` | 0–400 px | Gutter of grids and columns. | | `--pv-row-h` | `length` | 16–200 px | Height of a list row. | | `--pv-control-h-sm` | `length` | 16–200 px | Height of a small control. | | `--pv-control-h-md` | `length` | 16–200 px | Height of a medium control. | | `--pv-control-h-lg` | `length` | 16–200 px | Height of a large control. | | `--pv-control-pad-x` | `length` | 0–400 px | Horizontal padding of a control. | ## Radii {#radii} Corner radius scale, from extra small to pill. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-radius-input` | `length` | ≤ 64 px | Accent edge width, gauge height, input corner radius, chart line width and gap between chart bars. | | `--pv-radius-panel` | `length` | 0–40 px | Corner radius of the surfaces that are not plates (the Settings dialog, the message boxes, the miscellaneous cards). | | `--pv-radius-xs` | `length` | 0–1000 px | Extra small corner radius (gauges). | | `--pv-radius-sm` | `length` | 0–1000 px | Small corner radius (badges). | | `--pv-radius-md` | `length` | 0–1000 px | Medium corner radius (buttons, tabs). | | `--pv-radius-lg` | `length` | 0–1000 px | Large corner radius (rows, cards). | | `--pv-radius-xl` | `length` | 0–1000 px | Extra large corner radius (dialogs). | | `--pv-radius-pill` | `length` | 0–1000 px | Fully rounded ends (pills, switches). | ## Borders and focus {#borders} Border colours, border widths and the keyboard focus ring. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-border` | `color` | — | The usual outline of a control or a card. | | `--pv-border-strong` | `color` | — | A more visible outline (a hovered or active control). | | `--pv-border-focus` | `color` | — | Outline of the field that has the keyboard focus. | | `--pv-bw-1` | `length` | 0–16 px | Thin border width. | | `--pv-bw-2` | `length` | 0–16 px | Medium border width. | | `--pv-bw-3` | `length` | 0–16 px | Thick border width. | | `--pv-focus-ring-w` | `length` | 0–16 px | Width of the keyboard focus ring. | | `--pv-focus-ring-offset` | `length` | −16–16 px | Gap between an element and its focus ring (negative draws it inside). | | `--pv-focus-ring-color` | `color` | — | Colour of the keyboard focus ring. | ## Plate shapes {#shapes} The cut-out shapes of plates, their accent edge, gauges and chart bars, and the depth and sheen painted on every plate. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-clip-lg` | `clip` | — | Shape of large (rows, panels), medium (buttons, tabs) and small (badges) plates. | | `--pv-clip-md` | `clip` | — | Shape of large (rows, panels), medium (buttons, tabs) and small (badges) plates. | | `--pv-clip-sm` | `clip` | — | Shape of large (rows, panels), medium (buttons, tabs) and small (badges) plates. | | `--pv-clip-edge-lg` | `clip` | — | Shape of the accent edge drawn on the leading side of each plate size. | | `--pv-clip-edge-md` | `clip` | — | Shape of the accent edge drawn on the leading side of each plate size. | | `--pv-clip-edge-sm` | `clip` | — | Shape of the accent edge drawn on the leading side of each plate size. | | `--pv-clip-meter` | `clip` | — | Shape of gauge fills and of chart bars. | | `--pv-inset-lg` | `length` | — | Horizontal padding that clears the slanted or chamfered ends of each plate size. | | `--pv-inset-md` | `length` | — | Horizontal padding that clears the slanted or chamfered ends of each plate size. | | `--pv-inset-sm` | `length` | — | Horizontal padding that clears the slanted or chamfered ends of each plate size. | | `--pv-edge-w` | `length` | ≤ 64 px | Accent edge width, gauge height, input corner radius, chart line width and gap between chart bars. | | `--pv-meter-h` | `length` | ≤ 64 px | Accent edge width, gauge height, input corner radius, chart line width and gap between chart bars. | | `--pv-meter-ticks` | `layers` | — | Gradient layers: gauge segment ticks, artwork fade mask of a song row (opaque keeps the picture, transparent hides it), the chart scanline overlay and the shade over the map picture. | | `--pv-plate-filter` | `filter` | — | Depth under every plate (cards, rows, panels): `drop-shadow(<x> <y> [<blur>] <colour>)` (drawn by a filter because plates are clipped shapes, so a box-shadow would be cut); `none` for flat. | | `--pv-plate-sheen` | `layers` | — | Up to four linear gradients painted on top of every plate's colour (a bevel, a keycap's shading, a glass highlight): `none` for a flat plate. | ## Shadows {#shadows} Resting shadows of each surface level, shadows of floating layers and glows. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-elev-0` | `shadow` | — | Shadow of a surface of level 0 (flat on the page). | | `--pv-elev-1` | `shadow` | — | Resting shadow of a surface of level 1. | | `--pv-elev-2` | `shadow` | — | Resting shadow of a surface of level 2. | | `--pv-elev-3` | `shadow` | — | Resting shadow of a surface of level 3. | | `--pv-elev-4` | `shadow` | — | Resting shadow of a surface of level 4. | | `--pv-shadow-1` | `shadow` | — | Shadow of a popover or a tooltip. | | `--pv-shadow-2` | `shadow` | — | Shadow of a menu. | | `--pv-shadow-3` | `shadow` | — | Shadow of a dialog. | | `--pv-shadow-4` | `shadow` | — | Shadow of a toast or the highest layer. | | `--pv-glow-accent` | `shadow` | — | Glow around an emphasised accent element. | | `--pv-glow-danger` | `shadow` | — | Glow around an element that signals an error. | ## Motion {#motion} Durations, easing curves and the intensity of entrance animations. Under `prefers-reduced-motion` the game cuts durations and travel distances to zero whatever the theme says. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-shift-base` | `length` | — | Distance entrance animations travel (zero under reduced motion). | | `--pv-ease` | `easing` | — | Easing of motion and of its springy variant. | | `--pv-ease-spring` | `easing` | — | Easing of motion and of its springy variant. | | `--pv-dur-1` | `duration` | — | Shortest motion (hover, press). | | `--pv-dur-2` | `duration` | — | Usual motion. | | `--pv-dur-3` | `duration` | — | Slow motion (panels, entrances). | | `--pv-dur-4` | `duration` | — | Cross-fade of the accent tint. | | `--pv-stagger-step` | `duration` | — | Delay between two elements of a staggered entrance. | | `--pv-ease-in` | `easing` | — | Easing of something leaving. | | `--pv-ease-out` | `easing` | — | Easing of something arriving. | | `--pv-ease-in-out` | `easing` | — | Easing of something that moves and stops. | | `--pv-ease-emphasis` | `easing` | — | Easing of an emphasised movement (a panel sliding in). | | `--pv-motion-intensity` | `opacity` | — | How far entrances travel and how staggered they are (0 for none); always none under reduced motion. | ## Map picture and overlays {#artwork} How the map's picture behind the menus is drawn (shade, filter, fade mask, cover pictures) and the pictures a theme adds. See [the map picture rule](#artwork-rule). | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-art-clip` | `clip` | — | Shape of cover pictures. | | `--pv-art-inset` | `length` | — | Artwork of a song row (the background of its left part): inset, left offset, width (a share of the card, such as 52%) and the left margin of the text (0 when the text lies over the artwork). | | `--pv-art-left` | `length` | — | Artwork of a song row (the background of its left part): inset, left offset, width (a share of the card, such as 52%) and the left margin of the text (0 when the text lies over the artwork). | | `--pv-art-w` | `length` | — | Artwork of a song row (the background of its left part): inset, left offset, width (a share of the card, such as 52%) and the left margin of the text (0 when the text lies over the artwork). | | `--pv-art-pad` | `length` | — | Artwork of a song row (the background of its left part): inset, left offset, width (a share of the card, such as 52%) and the left margin of the text (0 when the text lies over the artwork). | | `--pv-art-opacity` | `opacity` | — | Opacity of cover pictures. | | `--pv-art-mask` | `layers` | — | Gradient layers: gauge segment ticks, artwork fade mask of a song row (opaque keeps the picture, transparent hides it), the chart scanline overlay and the shade over the map picture. | | `--pv-shade` | `layers` | — | Gradient layers: gauge segment ticks, artwork fade mask of a song row (opaque keeps the picture, transparent hides it), the chart scanline overlay and the shade over the map picture. | | `--pv-art-filter` | `filter` | — | Filter applied to the map picture behind the menus. | | `--pv-overlay-image` | `image` | — | A picture of the theme's folder drawn over the map artwork and under the menus (a vignette, a grid, decoration), stretched to the window (the picture's own `preserveAspectRatio` decides whether it is cropped or distorted): `image("images/overlay.svg")`. | | `--pv-bg-image` | `image` | — | Picture of the theme's folder drawn on the page background (`image("images/bg.png")`). | ## Progression graph {#graph} Palette, curves, grid and cursor of the replay progression graph. The three curves stay distinguishable: see [the curves rule](#graph-rule). | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-graph-surface` | `color` | — | Chart plot background, grid lines, zero line and inspection cursor. | | `--pv-graph-grid` | `color` | — | Chart plot background, grid lines, zero line and inspection cursor. | | `--pv-graph-zero` | `color` | — | Chart plot background, grid lines, zero line and inspection cursor. | | `--pv-graph-cursor` | `color` | — | Chart plot background, grid lines, zero line and inspection cursor. | | `--pv-graph-bar-clip` | `clip` | — | Shape of gauge fills and of chart bars. | | `--pv-graph-line-w` | `length` | ≤ 64 px | Accent edge width, gauge height, input corner radius, chart line width and gap between chart bars. | | `--pv-graph-bar-gap` | `length` | ≤ 64 px | Accent edge width, gauge height, input corner radius, chart line width and gap between chart bars. | | `--pv-graph-scan` | `layers` | — | Gradient layers: gauge segment ticks, artwork fade mask of a song row (opaque keeps the picture, transparent hides it), the chart scanline overlay and the shade over the map picture. | | `--pv-graph-low` | `color` | — | Chart palette, from the quietest to the busiest values (the density timeline climbs low, mid, high, peak; judgement tier colours and difficulty colours are never tokens). | | `--pv-graph-mid` | `color` | — | Chart palette, from the quietest to the busiest values (the density timeline climbs low, mid, high, peak; judgement tier colours and difficulty colours are never tokens). | | `--pv-graph-high` | `color` | — | Chart palette, from the quietest to the busiest values (the density timeline climbs low, mid, high, peak; judgement tier colours and difficulty colours are never tokens). | | `--pv-graph-peak` | `color` | — | Chart palette, from the quietest to the busiest values (the density timeline climbs low, mid, high, peak; judgement tier colours and difficulty colours are never tokens). | | `--pv-graph-bar-stroke` | `color` | — | Outline of chart bars. | | `--pv-graph-progression` | `choice` | `steps` (default) · `lines` · `area` · `bars` | How the replay progression graph draws its three curves: `steps` (each sample held until the next, the density as a faint stepped area), `lines` (straight segments joining the real samples, nothing smoothed), `area` (the stepped curves filled underneath) or `bars` (the chart density as bars, combo and accuracy as stepped lines). The player may override it in Settings → Interface. | | `--pv-graph-grid-style` | `choice` | `lines` (default) · `none` · `dots` · `scanlines` | The grid behind the replay graphs: hairlines, nothing, a dot lattice, or fine horizontal scanlines. | | `--pv-graph-cursor-shape` | `choice` | `dashed` (default) · `solid` · `band` | The cursor of the replay progression graph: a dashed line, a solid line or a translucent vertical band. | | `--pv-graph-marker` | `choice` | `none` (default) · `dot` · `diamond` · `square` | A marker where the cursor crosses each visible curve of the progression graph. | | `--pv-graph-miss-style` | `choice` | `bands` (default) · `ticks` | How the miss intervals of the progression graph are drawn: translucent `bands` over the full height, or small `ticks` along the bottom. | | `--pv-graph-curve-w` | `length` | 1–6 px | Stroke width of the progression graph's combo curve (the accuracy curve is three quarters of it, the density outline six tenths). | | `--pv-graph-fill-opacity` | `opacity` | — | Opacity of the fills under the progression curves (`area` and `bars`, and the faint density area of `steps`). | | `--pv-graph-combo` | `color` | `#rrggbb` only | The combo curve (solid). `#rrggbb`. The combo, accuracy and density colours must differ pairwise by at least 30 degrees of hue (greys: 25 % of lightness), or the theme is refused. | | `--pv-graph-accuracy` | `color` | `#rrggbb` only | The accuracy curve (always dashed, whatever the theme). `#rrggbb`; see the hue rule of the combo curve. | | `--pv-graph-density-low` | `color` | `#rrggbb` only | Chart density, quietest part of its magnitude gradient (`#rrggbb`). | | `--pv-graph-density-mid` | `color` | `#rrggbb` only | Chart density, middle of its gradient (`#rrggbb`); this is the colour compared with the combo and accuracy curves. | | `--pv-graph-density-high` | `color` | `#rrggbb` only | Chart density, busiest part of its gradient (`#rrggbb`). | ## Layout choices {#layout} A layout token takes one word of a closed list. The page turns each valid word into a `data-layout-<name>` attribute on the root, and the game's stylesheets react to it. A theme gives no selector and no CSS, only these words. **The first word of each list is the layout the game has today**, and the value of a token a theme does not set. | Token | Words | Effect | | --- | --- | --- | | `--pv-layout-list` | `right` (default) · `left` · `center` | Where the song list stands on the song-select screen. `right` is the usual layout (the selected map's panel on the left); `left` mirrors it; `center` puts the list in the middle with the panel on the right and the art showing on the left. | | `--pv-layout-tabs` | `top` (default) · `rail` · `dock` · `sidebar` | Where the tabs of the selected map (Info, Leaderboard, Mods, Training, Editor) stand: a bar `top`, a vertical `rail` at the panel's left, a `dock` along the bottom of the panel, or a full-height `sidebar` (a source list down the left of the whole panel, collapsing to icons in narrow windows). | | `--pv-layout-play` | `bottom` (default) · `top` | Where the rating and judgement choices and the Play button of the selected map stand: at the `bottom` of its panel or at the `top`, above the title. | | `--pv-layout-density` | `comfortable` (default) · `compact` · `dense` | How tight the menus are: spacing, song-list row heights and gaps shrink step by step. | | `--pv-layout-chrome` | `none` (default) · `titlebar` · `nav` | A decorative bar above the menus: `titlebar` draws a strip with three round window dots and the app name, `nav` a slim translucent site-style navigation bar with the app name and the page title (purely cosmetic; the real window controls are the system's). | | `--pv-layout-drawer` | `left` (default) · `right` · `bottom` | Which edge the Escape drawer comes from: `left`, `right`, or a `bottom` dock of icons. | | `--pv-layout-rows` | `cover` (default) · `strip` · `text` · `list` | How a song-list row is built: the `cover` artwork as the background of the left part of the row, the text over it, the artwork as a faded `strip` behind the whole row, `text` only (a table-like row), or a flat `list` row (the artwork over the left part and the text on no plate, only a tint under the hovered and the selected row, like a music app's list). | | `--pv-layout-profile` | `top` (default) · `rail` | Where the player's identity (name, rating, rank) stands on the Profile page: a bar on `top`, or a `rail` down the left. | | `--pv-layout-cards` | `rich` (default) · `compact` | How a score card of the leaderboard is built: `rich` (big accuracy, judgement counts underneath) or `compact` (one table-like line). | | `--pv-layout-buttons` | `plate` (default) · `bracket` · `link` | How buttons, tabs and icon buttons are drawn: a filled `plate` in the theme's shape, plain text `link`s in the accent colour for every button but the primary one (which keeps its accent fill), or a `bracket` (an outline of corner brackets drawn with gradients, no fill, like a terminal's [ ]); the accent-filled ones keep their accent as the colour of the brackets and of their text. | | `--pv-layout-focus` | `ring` (default) · `blink` | How keyboard focus shows: the usual outline `ring`, or the same outline blinking like a text cursor (`blink`; still, as a ring, under reduced motion). | | `--pv-layout-icons` | `none` (default) · `icon` | Whether tabs carry their icon (`icon`) before the label; the Info, Leaderboard, Mods, Training and Editor tabs have one. | | `--pv-layout-visualize` | `label` (default) · `icon` | How the Visualize button of the song list's bar is drawn: with its word (`label`), or as its eye icon alone (`icon`: the same square as the bar's other icon buttons, its name and tooltip still say Visualize). | | `--pv-layout-groups` | `plain` (default) · `inset` | How the rows of Settings are grouped: `plain` rules between sections, or `inset` cards (a rounded group per section with hairline separators between its rows, as in a system settings window). | | `--pv-layout-controls` | `plain` (default) · `pill` | The look of tab bars, hand-written switches, popup menus and scrollbars: `plain` (the theme's own shapes) or `pill` (capsule tab bars with a raised selected tab, pill switches with a white knob, rounded popup menus with an accent-filled selection, thin overlay scrollbars). The shared Settings controls (`Switch`, `Slider`, `Segmented`, `NumberBox`, `KeyCap`, `pv-field`) do not follow it: they are drawn with the shape tokens (`--pv-clip-sm`, `--pv-clip-meter`). | | `--pv-layout-hero` | `plate` (default) · `open` | How the selected map's header and its four figures are drawn: on `plate`s, or `open` on the page itself (the title and the big rating without a card, the figures as columns between hairlines, like a product page). | | `--pv-layout-settings` | `side` (default) · `top` · `index` · `rail` | Where the categories of Settings stand: a `side` column of tabs at the left (the usual layout), a `top` strip of tabs above a full-width page, an `index` (a ruled list at the left, its selected entry marked by an accent bar, no plates), or a framed `rail` (the list in a panel of its own, its selected entry a plate). | | `--pv-layout-settings-rows` | `inline` (default) · `stacked` | How a setting's row is built: its name with its control on the same line (`inline`, the usual one), or the control set under the name (`stacked`, a page of text with each control beneath its label, like a printed form). | | `--pv-layout-pause` | `panel` (default) · `side` · `open` · `prompt` | How the in-game pause menu is laid out: a `panel` plate in the middle of the screen, a full-height `side` panel on the edge the drawer comes from, an `open` list without plate over the play, or a `prompt` (a terminal at the left, `[ title ]`, `$` and `>` before the lines). The menu keeps its theme roles, shapes and faces in every layout; `side` and `prompt` ignore the position a skin gave the menu. | ## Component tokens {#components} Tokens read by one component of the design system, named `--pv-<component>-<role>[-<state>]`. Their defaults are references to the base tokens (`--pv-card-bg` follows `--pv-surface-2`), so a theme that sets only the base tokens already styles every component. ### Card {#component-card} Colours, outline, padding and shadow of cards. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-card-bg` | `color` | — | Card: background | | `--pv-card-bg-hover` | `color` | — | Card: hovered background | | `--pv-card-fg` | `color` | — | Card: text | | `--pv-card-border` | `color` | — | Card: outline | | `--pv-card-border-w` | `length` | 0–400 px | Card: outline width | | `--pv-card-radius` | `length` | 0–400 px | Card: corner radius | | `--pv-card-pad` | `length` | 0–400 px | Card: inner padding | | `--pv-card-gap` | `length` | 0–400 px | Card: gap between its elements | | `--pv-card-shadow` | `shadow` | — | Card: shadow | ### Button {#component-button} Colours of the plain, primary and destructive buttons, and their size, radius and text. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-button-bg` | `color` | — | Button: background | | `--pv-button-bg-hover` | `color` | — | Button: hovered background | | `--pv-button-bg-press` | `color` | — | Button: pressed background | | `--pv-button-fg` | `color` | — | Button: text | | `--pv-button-border` | `color` | — | Button: outline | | `--pv-button-primary-bg` | `color` | — | Button: background of the primary button | | `--pv-button-primary-bg-hover` | `color` | — | Button: hovered background of the primary button | | `--pv-button-primary-bg-press` | `color` | — | Button: pressed background of the primary button | | `--pv-button-primary-fg` | `color` | — | Button: text of the primary button | | `--pv-button-danger-bg` | `color` | — | Button: background of a destructive button | | `--pv-button-danger-bg-hover` | `color` | — | Button: hovered background of a destructive button | | `--pv-button-danger-fg` | `color` | — | Button: text of a destructive button | | `--pv-button-h` | `length` | 0–400 px | Button: height | | `--pv-button-pad-x` | `length` | 0–400 px | Button: horizontal padding | | `--pv-button-radius` | `length` | 0–400 px | Button: corner radius | | `--pv-button-border-w` | `length` | 0–400 px | Button: outline width | | `--pv-button-fs` | `length` | ≥ 12 px | Button: text size | | `--pv-button-fw` | `weight` | — | Button: text weight | | `--pv-button-disabled-opacity` | `opacity` | — | Button: opacity when disabled | ### Text field {#component-input} Colours, outline and size of text fields. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-input-bg` | `color` | — | Text field: background | | `--pv-input-fg` | `color` | — | Text field: text | | `--pv-input-border` | `color` | — | Text field: outline | | `--pv-input-border-hover` | `color` | — | Text field: hovered outline | | `--pv-input-border-focus` | `color` | — | Text field: outline with the keyboard focus | | `--pv-input-placeholder` | `color` | — | Text field: text of the placeholder | | `--pv-input-h` | `length` | 0–400 px | Text field: height | | `--pv-input-pad-x` | `length` | 0–400 px | Text field: horizontal padding | | `--pv-input-radius` | `length` | 0–400 px | Text field: corner radius | | `--pv-input-border-w` | `length` | 0–400 px | Text field: outline width | ### Tab {#component-tab} Colours, size and selected-tab mark of tabs. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-tab-fg` | `color` | — | Tab: text | | `--pv-tab-fg-hover` | `color` | — | Tab: hovered text | | `--pv-tab-fg-active` | `color` | — | Tab: text of the selected tab | | `--pv-tab-bg` | `color` | — | Tab: background | | `--pv-tab-bg-hover` | `color` | — | Tab: hovered background | | `--pv-tab-bg-active` | `color` | — | Tab: background of the selected tab | | `--pv-tab-indicator` | `color` | — | Tab: mark of the selected tab | | `--pv-tab-h` | `length` | 0–400 px | Tab: height | | `--pv-tab-pad-x` | `length` | 0–400 px | Tab: horizontal padding | | `--pv-tab-radius` | `length` | 0–400 px | Tab: corner radius | | `--pv-tab-indicator-w` | `length` | 0–400 px | Tab: thickness of the selected-tab mark | | `--pv-tab-gap` | `length` | 0–400 px | Tab: gap between tabs | ### Tooltip {#component-tooltip} Colours, size and shadow of tooltips. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-tooltip-bg` | `color` | — | Tooltip: background | | `--pv-tooltip-fg` | `color` | — | Tooltip: text | | `--pv-tooltip-border` | `color` | — | Tooltip: outline | | `--pv-tooltip-radius` | `length` | 0–400 px | Tooltip: corner radius | | `--pv-tooltip-pad-x` | `length` | 0–400 px | Tooltip: horizontal padding | | `--pv-tooltip-pad-y` | `length` | 0–400 px | Tooltip: vertical padding | | `--pv-tooltip-max-w` | `length` | 0–400 px | Tooltip: largest width | | `--pv-tooltip-fs` | `length` | ≥ 12 px | Tooltip: text size | | `--pv-tooltip-shadow` | `shadow` | — | Tooltip: shadow | ### List row {#component-list-row} Colours, size and selected-row mark of list rows. | Token | Kind | Bounds | Description | | --- | --- | --- | --- | | `--pv-list-row-bg` | `color` | — | List row: background | | `--pv-list-row-bg-hover` | `color` | — | List row: hovered background | | `--pv-list-row-bg-selected` | `color` | — | List row: background of the selected row | | `--pv-list-row-bg-selected-hover` | `color` | — | List row: background of the selected row under the pointer | | `--pv-list-row-fg` | `color` | — | List row: text | | `--pv-list-row-fg-muted` | `color` | — | List row: secondary text | | `--pv-list-row-border` | `color` | — | List row: outline | | `--pv-list-row-accent` | `color` | — | List row: accent mark of the selected row | | `--pv-list-row-h` | `length` | 0–400 px | List row: height | | `--pv-list-row-pad-x` | `length` | 0–400 px | List row: horizontal padding | | `--pv-list-row-radius` | `length` | 0–400 px | List row: corner radius | | `--pv-list-row-gap` | `length` | 0–400 px | List row: gap between its elements | ## Rules that cross several tokens {#rules} Two checks look at several tokens together. A theme that breaks one is refused as a whole, and the message names the tokens. ### The map picture stays visible {#artwork-rule} The picture of the selected map behind the menus is part of the game's identity. A theme may tint it (`--pv-shade`), dim, blur, desaturate or recolour it (`--pv-art-filter`), never remove it or bury it. The validator (`crates/themes/src/artwork.rs`) estimates the share of the picture's light that reaches the screen, as a mean over the window: - each gradient of `--pv-shade` covers the mean of its alpha along its axis (stops with `%` positions are integrated; a repeating gradient, or a stop without a `%` position, counts as the plain mean of its stops). A colour the estimate cannot read (a `var()`, a named colour) counts as opaque; - the layers compose: coverage = 1 − Π(1 − layer coverage); - the filter counts for its `brightness()` and `opacity()` factors (each at most 1); - visible share = filter × (1 − coverage). The rules: - the visible share is at least **20 %**; - no single layer of `--pv-shade` covers more than **90 %** on average (a flat opaque layer is refused); - in `--pv-art-filter`, `brightness()` is at least **0.25**, `opacity()` at least **0.4** and `contrast()` at least **0.5**, each on its own. The check runs on the base block and again on each `@media` block laid over it. The message reads `the map picture must stay visible: --pv-shade and --pv-art-filter leave 12% of it on average; at least 20% is required (a theme may tint, dim or blur it, never hide it)`. The only way to hide the picture is the player's own option. ### The progression curves stay distinguishable {#graph-rule} The replay progression graph draws three curves: the combo (always solid), the accuracy (always dashed) and the density (always a filled area or bars). A theme may recolour them with `--pv-graph-combo`, `--pv-graph-accuracy`, `--pv-graph-density-mid`, written as plain `#rrggbb`, but the colours of every pair must stay apart: - at least **30°** of hue apart (the shortest way round the circle), or - at least **0.25** of lightness apart, when either colour is a grey (saturation under 0.18). A colour the theme does not set is the game's own (combo `#69b6ff`, accuracy `#c6a4ff`, density `#ffc968`). A theme that breaks the rule is refused with `<token> and <token>: the combo and accuracy curves of the progression graph must differ by at least 30 degrees of hue (or 0.25 of lightness for greys)`. The colours of judgement tiers and difficulty ratings are never tokens. ## See also {#see-also} [Concepts](https://prism.am/dev/md/themes/concepts.md) explains how tokens, styles and templates fit together; [theme.css](https://prism.am/dev/md/themes/css.md) shows how a rule of your own sets a token for one subtree of the screen. ===== Page: Contracts reference Address: https://prism.am/dev/themes/contracts/ Derived from: apps/web/packages/@pvng/ui-contracts/contracts.json, crates/themes/src/contracts.rs # Contracts reference Every screen and component a theme.ts may template: its input, outputs, slots, parts, host classes and the musts a template keeps. This page is generated from the table of contracts the game embeds (`apps/web/packages/@pvng/ui-contracts/contracts.json`, read by the validator and by the typings of [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts)). It lists 14 screens and 14 components. A **screen** is a whole page whose template places named *slots*; a **contract** is one component (a toolbar, a footer, a card) that a theme may restyle with its own template. The template of either is a function of a typed context `c` ([nodes](https://prism.am/dev/md/themes/nodes.md)); how to write one is in [templates](https://prism.am/dev/md/themes/templates.md). ## Reading a contract {#reading} - **Input** is what a template can read: the paths of `c.bind('…')` and `c.field('…')`. A `?` marks a value that may be absent (`null`); `[]` marks a list (its item is described below it, indented); text between quotes is a closed set of values. A path that does not exist in the current state reads as empty text and never fails. - **States** (contracts only): the input of a contract is a *variant* tagged by `state`; each state has its own fields, listed under `state = <name>:`. A path that exists in any state is valid in a template, so test `state` before relying on it. - **Outputs** are the actions a control may call: `c.on.press('name', args)`. Arguments are typed and given in order. An output marked **required** must be bound to a control, or the template is refused. - **Slots** are the named places a template must put somewhere (`c.slot('name')`). A slot marked **required** must be placed, anywhere, in a `when` or not. A slot that *mounts* a contract renders that component with its own template. - **Parts** are the `data-part` marks of the component's elements; **host classes** are classes of the game's own stylesheet a template may put on a node; **CSS vars** are variables the game sets on the element. **Musts** are what a replacement must keep, checked by the game's tests. ## Contents {#contents} **Screens**: [screen.chat](#screen-chat) · [screen.clan](#screen-clan) · [screen.download](#screen-download) · [screen.help](#screen-help) · [screen.library](#screen-library) · [screen.lobby](#screen-lobby) · [screen.mods](#screen-mods) · [screen.profile](#screen-profile) · [screen.replay](#screen-replay) · [screen.result](#screen-result) · [screen.settings](#screen-settings) · [screen.skins](#screen-skins) · [screen.title](#screen-title) · [screen.tournaments](#screen-tournaments) **Components**: [catalog.card](#catalog-card) · [download.card](#download-card) · [leaderboard.card](#leaderboard-card) · [library.chartRow](#library-chartrow) · [library.footer](#library-footer) · [library.search](#library-search) · [library.setCard](#library-setcard) · [library.toolbar](#library-toolbar) · [lobby.draft](#lobby-draft) · [maps.toPlay](#maps-toplay) · [player.card](#player-card) · [rate.control](#rate-control) · [selected.header](#selected-header) · [selected.tabs](#selected-tabs) ## Screens {#screens} ### `screen.chat` — Chat sheet {#screen-chat} The chat over a page: the tabs of its channels, the players' panel toggle, the close button and the pane of the channel shown (its lines, its composer, or why the chat cannot be used). The sheet's root (fixed over the window, hidden when closed, the focus it takes and gives back, its keys) stays the host's; the template composes what is inside it. The lines, their links and names, the composer and its commands stay the host's: a theme styles them by their marks. - Template: `screens.chat` (`defineTheme({ screens: { chat: (c) => … } })`) - Typed context: `ThemeContext<'screen.chat'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-chat-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text channels[] object id string label string unread number direct boolean clan boolean selected boolean active string gate "ready" | "login" | "offline" | "server" | "unsupported" usersShown boolean unread number ``` #### Regions {#screen-chat-regions} | Region | Slots | Description | | --- | --- | --- | | `bar` | `tabs`, `users`, `close` | The channel tabs, then the players' toggle and the close button at the end. | | `body` | `panes` | The pane of every channel (one is shown): lines and composer. | #### Slots {#screen-chat-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `tabs` | yes | — | The channel tabs: a tab list with arrows, an unread count on each tab, a close button on a private conversation (Delete closes it too). | | `users` | yes | — | The button that shows or hides the players' band (pressed while it shows); nothing while the chat cannot be used. | | `close` | yes | — | The button that closes the sheet. | | `panes` | yes | — | One pane per channel, the one shown visible: the lines (with their time, speaker, links and system lines), the composer with its command list, or the reason the chat cannot be used with its action. | #### Outputs {#screen-chat-outputs} | Output | Arguments | Description | | --- | --- | --- | | `channel.select` | `channel: string` | Shows a channel (what a click on its tab does). An unknown id does nothing. | | `users.toggle` | — | Shows or hides the players' band. | | `close` | — | Closes the sheet and gives the focus back to what had it. | #### Host classes {#screen-chat-classes} | Class | Description | | --- | --- | | `card` | The sheet's plate: a column with the sheet's padding, over an opaque base. | | `bar` | The row of tabs and buttons. | | `push` | An empty item that takes the free width of a row: what follows it is pushed to the end. | | `panes` | The column that holds the channels' panes and takes what is left of the sheet. | | `pv-plate` | The design system's plate (use with `pv-plate--lg`, and `data-tone` `raised` or `data-edge` `accent`). | | `pv-plate--lg` | The large plate: the shape of a panel (`--pv-clip-lg`). | #### Keys {#screen-chat-keys} | Key | Effect | | --- | --- | | F8 | Shows or hides the sheet and the players' band. | | Escape | Closes, in this order: a player's menu, a link confirmation, the command list, the players' band, the sheet. | | ArrowLeft / ArrowRight (on the tabs) | Moves from one channel to the next and shows it. | | Delete (on a private conversation's tab) | Closes the conversation. | | Enter (in the composer) | Sends the line. | ### `screen.clan` — Clan {#screen-clan} The player's clan and the clans' ranking: the way back, the title and the connection chips, what could not be read (with a retry), the clan's header and facts, its members, and the chat or the ranking beside them. The screen's host builds every place from the stores and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. The clan's name, rank and figures are in the input (a template writes its own header); the members, the chat and the ranking are the host's: a template places and restyles them through their marks, it never redraws them. - Template: `screens.clan` (`defineTheme({ screens: { clan: (c) => … } })`) - Typed context: `ThemeContext<'screen.clan'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-clan-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text gate "page" | "offline-note" | "login" mine "loading" | "none" | "clan" side "chat" | "ranking" failure? object text string clan? object name string tag string rank? number top boolean leader boolean members number memberLimit number online number totalPp string averagePp string ranking object sort "total" | "average" | "members" loaded boolean empty boolean loading boolean total number entries number page number pages number chat object available boolean ``` #### Regions {#screen-clan-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `back`, `title`, `online` | The way back, the title with its help bubble, and the connection chip with the chat button. | | `status` | `gate`, `failed` | The notice of offline mode and the line that says what could not be read, with its retry. | | `clan` | `tag`, `manage`, `facts`, `members`, `none` | The player's clan: the tag, the "manage on the site" button, the facts and the members; or the invitation to the site when the account is in none. | | `side` | `tabs`, `chat`, `ranking` | The tabs and the panel they open: the clan's chat or the ranking of the clans. | #### Slots {#screen-clan-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `back` | yes | — | The back arrow: it leads to the song selection. | | `title` | yes | — | The page's heading (`h1`) with the help bubble that says the game only reads a clan. | | `online` | yes | — | The online chip (the account's connection) and the chat button. | | `gate` | yes | — | The notice of offline mode ("Clans need the server") with its button to Settings → Online; nothing otherwise. | | `failed` | yes | — | The line that says what could not be read, with its Retry button; nothing when everything was read. | | `tag` | no | — | The clan's tag `[TAG]` in the game's own style, with the clan's name as its tooltip and accessible name; nothing without a clan. | | `manage` | yes | — | The "Manage on the site" button: it opens the site's clan page in the browser (the game never creates, invites, leads or leaves a clan); nothing without a clan. | | `facts` | no | — | The clan's four figures as a list of terms (members of the limit, online, total and average performance); nothing without a clan. A template that writes its own figures from `clan` leaves it out. | | `members` | yes | — | The members as a grid of cards, the leader first, then the ones online: the picture, the name (a button with the player's menu), the crown, "you", the flag, the title, whether the member is online with their performance, and the site's rank; nothing without a clan. | | `none` | yes | — | What the page says when the account is in no clan, with the button that opens the site's clan page; nothing otherwise. | | `tabs` | yes | — | The two tabs of the side (Chat, Ranking): a segmented control with arrows. | | `chat` | yes | — | The clan's chat (the chat's own pane, lines and composer) or the line that says there is none; drawn on the `chat` side only. | | `ranking` | yes | — | The ranking of the clans: its sort, the count, the table with the player's own clan marked, and the pager; drawn on the `ranking` side only. | #### Outputs {#screen-clan-outputs} | Output | Arguments | Description | | --- | --- | --- | | `back` | — | Leaves the page for the song selection (what the back arrow does). | | `site.open` | — | Opens the site's clan page in the browser: the place to create, invite, lead or leave a clan (what "Manage" and the invitation do). | | `refresh` | — | Reads the clan, its ranking page and the clan channel again (what Retry does). | | `settings.open` | — | Opens Settings → Online (what the offline notice's button does). | | `side.select` | `side: string` | Shows the clan's chat or the ranking (`chat` or `ranking`). An unknown side shows the chat. | | `ranking.sort` | `sort: string` | Sorts the ranking by `total`, `average` or `members` and goes to its first page. An unknown sort sorts by total. | | `ranking.page` | `offset: number` | Shows the page of the ranking that starts at this offset (a multiple of 50: the pager's previous and next); the sort is kept. | #### Host classes {#screen-clan-classes} | Class | Description | | --- | --- | | `clan` | The page's root: a column with the page's padding that fills the window. | | `pv-screen` | A screen root (page padding and entrance). | | `pv-ui` | The design system's plates and buttons under the root, in Classic too. | | `pv-plate` | The design system's plate (use with `pv-plate--lg`, and `data-tone` or `data-edge` `accent`). | | `pv-plate--lg` | The large plate: the shape of a panel (`--pv-clip-lg`). | | `page-head` | The header row (back, title, chips) that wraps when the window is narrow. | | `label-line` | The row of the title and its help bubble. | | `push` | An empty item that takes the free width of a row: what follows it is pushed to the end. | | `body` | The page under the header: a column that fills the free height. | | `cols` | The clan column and the side column side by side (stacked under 1100px). | | `left` | The clan column: a scrolling column. | | `right` | The side column: the tabs and their panel. | | `band` | The clan's header plate: a column (the title line, then the facts). | | `title-line` | The row of the tag, the clan's name, its place, "you lead" and the manage button. | | `place` | The clan's place as a bordered figure (`data-top` in the first ten). | | `lead-badge` | The "You lead this clan" pill. | | `note` | A line of the page's own words in the muted text (while the clan is read). | #### Keys {#screen-clan-keys} | Key | Effect | | --- | --- | | ArrowLeft / ArrowRight (on the side's tabs) | Moves from the chat to the ranking and back. | | Shift+F10 / context menu key (on a member) | Opens the player's menu under the name, like in the chat's panel. | | Enter (in the chat's composer) | Sends the line to the clan. | ### `screen.download` — Download {#screen-download} Find maps (and skins, mods, playlists) and put them in the library: a row of sources, a search with its filters, the results, and the queue of downloads beside them. The screen's host builds every place from the stores and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. What a result looks like is the `download.card` contract (a face: the host keeps the card's root and actions, the theme draws inside it). The keyboard, the paste of a map link, the filters and the queue stay the host's. - Template: `screens.download` (`defineTheme({ screens: { download: (c) => … } })`) - Typed context: `ThemeContext<'screen.download'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-download-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text tab string mode "results" | "prism" | "catalog" section string previewing boolean results object count number loading boolean failed boolean queue object total number active number finished number folder? string ``` #### Regions {#screen-download-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `title`, `sources`, `choices` | The title, the row of sources and the choices of the open source (Prism's sections, the folder, the mirror). | | `browse` | `search`, `notices`, `results`, `catalog` | The search and its filters, the notices of a source that asks for a login, the list of results; or Prism's own listing. | | `queue` | `queue` | The queue of downloads (or the map preview that takes its place). | #### Slots {#screen-download-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `title` | yes | — | The page's heading (`h1`). | | `sources` | yes | — | The row of sources (Prism, osu!, Quaver, Etterna) and the menu of the sources mods added: a tab list with arrows. | | `choices` | yes | — | What belongs to the open source: Prism's sections (Maps, Skins, Mods, Playlists), the folder the downloads go to, the mirror menu of osu!. It can be empty. | | `search` | yes | — | The search bar (with its paste-a-link button and the backend mark) and the filters under it. Drawn in the `results` mode only. | | `notices` | yes | — | The login a source asks for (Quaver's account, a mod's token) and the note of a mod's source. Drawn in the `results` mode, only when there is something to say. | | `results` | yes | — | The scrolling list of cards (`download.card`), the errors of a download that did not start and the status line (loading, end of the list, load more). Drawn in the `results` mode only. | | `catalog` | yes | — | Prism's own listing: its index of maps (search, filters, weekly challenge, cards) or the catalogue of skins, mods and playlists. Drawn in the `prism` and `catalog` modes only. | | `queue` | yes | — | The queue of downloads, with its clear button; the map preview takes its place while it runs. | #### Components drawn by the host {#screen-download-replaceable} Lists and panels the host draws; a template of these contracts restyles each one, it cannot place them. | Contract | Description | | --- | --- | | [download.card](#download-card) | One result of the list (an osu!, Quaver or mod set, a Prism map, an Etterna pack): the list repeats it. | | [catalog.card](#catalog-card) | One entry of Prism's catalogue (a skin, a mod, a playlist), in the `catalog` place: the list repeats it. | #### Outputs {#screen-download-outputs} | Output | Arguments | Description | | --- | --- | --- | | `tab.select` | `tab: string` | Shows a source: `prism`, `osu`, `quaver`, `etterna` or a mod's `mod:<id>/<source>`. An unknown tab shows Prism. | | `link.paste` | — | Reads a map link from the clipboard and starts its download (what the "Paste a link" button does). | | `search.focus` | — | Puts the focus in the search bar of the list shown. | | `queue.clear` | — | Removes the finished downloads from the queue. | #### Host classes {#screen-download-classes} | Class | Description | | --- | --- | | `download` | The page's root: a column with the page's padding. | | `pv-screen` | A screen root (page padding and entrance). | | `top` | The header row (title, sources, choices) with a hairline under it. | | `body` | The browse area and the queue side by side (a narrower queue column; the choices `data-layout-*` do not touch it). | | `panel` | The column of the browse area: search, notices and results one under the other. | | `previewing` | Added to `body` while the map preview runs in the queue's place (the queue column gets wider). | #### Keys {#screen-download-keys} | Key | Effect | | --- | --- | | ArrowDown (in the search) | The focus goes to the first result card. | | ArrowUp / ArrowDown / Home / End (on a card) | Moves from one result card to the previous or next, the first or the last. | | Enter (on a card) | Does what the card's main control does: downloads it, or opens and closes an Etterna pack. | | Ctrl+V | A map link (osu!, Quaver, Etterna) pasted anywhere in the page starts its download; pasted in the search bar it does the same, and a line of filters replaces the filters. | ### `screen.help` — Help {#screen-help} Read how the game works: a search over every topic, the topic list, and the topics' sections (the player's current keys, then a few short texts). The screen's host builds every place from the stores and the catalogs and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. The sections, their keys and the words the search found are the host's: a theme styles them through their marks (`data-part`). - Template: `screens.help` (`defineTheme({ screens: { help: (c) => … } })`) - Typed context: `ThemeContext<'screen.help'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-help-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text topics[] object id string title string current boolean total number search object active boolean query string found number ``` #### Regions {#screen-help-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `back`, `title`, `search` | The way back, the title and the search. | | `body` | `topics`, `content` | The topic list and the scrolling content: the topics' sections, or the line that says the search found none. | #### Slots {#screen-help-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `back` | yes | — | The back arrow: it leads to the page Help was opened from. | | `title` | yes | — | The page's heading (`h1`). | | `search` | yes | — | The search field over every topic (the rules of the Settings search: case and accents ignored, every word found, any order). | | `topics` | yes | — | The topic list: a navigation with one button per topic, Up and Down, Home and End; a click scrolls to the section and gives its heading the focus. It follows the scroll (`aria-current` and `data-active` mark the topic at the top). | | `content` | yes | — | The scrolling region (a focusable region, so the keyboard scrolls it): one section per topic with its title, the player's keys and its texts, the words the search found marked; or the line that says nothing matched. | #### Outputs {#screen-help-outputs} | Output | Arguments | Description | | --- | --- | --- | | `back` | — | Leaves the page for the one Help was opened from (what the back arrow does). | | `topic.jump` | `id: string` | Scrolls the content to a topic's section and gives its heading the focus (what a click on its entry in the list does). An unknown id does nothing. | | `search.focus` | — | Puts the focus in the search field. | | `search.clear` | — | Empties the search and lists every topic again. | #### Host classes {#screen-help-classes} | Class | Description | | --- | --- | | `help-page` | The page's root: a column with the page's padding. | | `pv-screen` | A screen root (page padding and entrance). | | `pv-ui` | The design system's plates and buttons under the root, in Classic too. | | `page-head` | The header row (back, title, search) that wraps when the window is narrow. | | `push` | An empty item that takes the free width of a row: what follows it is pushed to the end. | | `body` | The topic list and the content side by side (a narrow column and a wide one); stacked under 820px. | #### Keys {#screen-help-keys} | Key | Effect | | --- | --- | | ArrowUp / ArrowDown / Home / End (on the topic list) | The focus moves from one topic to the previous or next, the first or the last. | | Enter / Space (on a topic) | Scrolls to the topic's section and gives its heading the focus. | | Enter / ArrowDown (in the search) | The focus goes to the content, so the arrows scroll it. | | Escape (in the search) | Empties the search; with the field empty, Escape opens the game's menu like on every page. | ### `screen.library` — Map selection {#screen-library} Pick what to play: search and browse the library on one side, the selected map (its figures, tabs and the Play strip) on the other. The screen's host builds the input of every contract slot from the stores (`null` while a slot is not shown: the heading of an empty library has no tabs, no panels and no Play) and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. - Template: `screens.library` (`defineTheme({ screens: { library: (c) => … } })`) - Typed context: `ThemeContext<'screen.library'>` #### Input {#screen-library-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text selection object state "map" | "playlist" | "pick" | "empty" shown boolean color string busy boolean entering boolean changed boolean tab string browser object view "maps" | "playlists" | "mapsToPlay" covered boolean visualizer boolean color string map? object artist string title string difficulty string keysText string keys number creator? string background? string rating object value? number text string unit string label string rate? number duration object text string seconds? number bpm string bpmValue? number notes string holds string holdShare? number nps object average string peak string averageValue? number peakValue? number skillsets[] object label string short string display string hue string level number patterns[] object label string short string display string hue string level number rank number position number equalizer[] object i number level number live number listening boolean fresh boolean difficultyCount number record? object plays number bestAccuracy? number bestPerformance? string lastPlayed? string top? object accuracy number performance? string combo number misses number rate number rateText string date string mods[] object key string id string name string short string description string group string groupLabel string icon string enabled boolean conflicts[] string modsOn number preview object shown boolean playing boolean position number duration number progress number positionText string durationText string steps[] object i number at number level number passed boolean online object state "offline" | "signedOut" | "connecting" | "online" name? string avatar? string players? number friendsOnline number friends[] object name string avatar? string status "online" | "inLobby" | "playing" unread number rateControl variant on state state "ready" | "atDefault" | "atMin" | "atMax" value number text string min number max number minText string maxText string step number typed number steps object down number up number state = ready: {} state = atDefault: {} state = atMin: {} state = atMax: {} keys object play string menu string up string down string previousSet string nextSet string random string palette string visualize string chat string ``` #### Regions {#screen-library-regions} | Region | Slots | Description | | --- | --- | --- | | `browser` | `toolbar`, `views`, `online`, `visualize`, `intent`, `search`, `searchField`, `searchTools`, `list`, `playlistSearch`, `playlists`, `visualizer` | The library: the bar over the list, the search and the list itself (maps, playlists, or the visualizer over them). | | `selection` | `header`, `tabs`, `panels`, `infoPanel`, `leaderboardPanel`, `modsPanel`, `trainingPanel`, `historyPanel`, `mapsPanel`, `editorPanel` | The selected map: heading and figures, the tabs with their panels (or panels placed on their own). | | `footer` | `footer` | The strip where the choice becomes a play. | #### Slots {#screen-library-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `toolbar` | no | [library.toolbar](#library-toolbar) | The view switch, Random, the "…" menu, the online side and Visualize. Classic draws its original bar. A template that wants those pieces in different places places `views`, `online` and `visualize` instead (never both: the bar would be drawn twice). | | `views` | no | — | A piece of the toolbar, placed alone: the Maps \| Playlists switch with its counts, Random and the "…" menu of the rare actions (add or refresh folders, new or imported playlists). | | `online` | no | — | A piece of the toolbar, placed alone: the online status (account, connection), the chat button and the multiplayer button. | | `visualize` | no | — | A piece of the toolbar, placed alone: the Visualize button (pressed while the visualizer is open). | | `intent` | yes | — | The bar that tells the selection has another purpose now (the lobby's map is being picked) and lets it be dropped. | | `search` | yes | [library.search](#library-search) | The maps list's search: text, filters, grouping and sort (nothing while the maps to play show: their filters are in the `list` slot). A template that wants the field and the tools in different places places `searchField` and `searchTools` instead (both, and never with `search`). | | `searchField` | no | — | A piece of the maps search, placed alone: the text field with its recent searches, the filter chips and the lines that say a filter cannot apply. It takes the focus when the screen opens, as the whole search does. | | `searchTools` | no | — | A piece of the maps search, placed alone: Group (and fold all), Sort with its direction, the duplicates review and the "+ Filter" button with its window. | | `list` | yes | — | The maps list: sets and their difficulties (their rows are drawn by the `library.setCard` and `library.chartRow` contracts). While `browser.view` is `mapsToPlay` it is the maps to play instead: their filters and their list (the `maps.toPlay` contract), so every template shows them where it shows the maps. | | `playlistSearch` | yes | [library.search](#library-search) | The playlists list's search: text and sort (shown over the playlists). | | `playlists` | yes | — | The playlists list and its notices (shown while the playlists view is on). | | `visualizer` | yes | — | The map visualizer. Shown over the list while `visualizerOpen` (the Visualize button) it is the panel it always was; placed where it is always drawn (outside such a `when`, or as a tab of a `tabs` group) it plays the selected map whenever it is on screen, follows the selection and never holds the library, and the Visualize button no longer closes it. Its pieces carry `data-part`: `visualizer-head` (the card over the playfield), `visualizer-viewport` (the playfield: the game draws in its box, so resize it but never hide it), `visualizer-deck` (the player under it), `visualizer-chapters`, `visualizer-scrubber` and `visualizer-transport` (its rows). A template that draws its own player from `preview` hides the deck with `[data-part="visualizer-deck"] { display: none }`. | | `header` | yes | [selected.header](#selected-header) | Title, difficulty, rating and figures; the invitation when nothing is selected. | | `tabs` | yes | [selected.tabs](#selected-tabs) | The tabs of the map or the playlist. A panel the template places on its own (`infoPanel`, `leaderboardPanel`…) has no tab here. | | `panels` | yes | — | The panel of every tab (Info, Leaderboard, Mods, Training, History, Editor, mods' tabs); the rate control, the score cards and the graphs are in them. A panel the template places on its own is not drawn here. | | `infoPanel` | no | — | One panel placed on its own, always shown: the Info tab of the selected map (analysis, density band, rate advice). It leaves `tabs` and `panels`. Its blocks carry `data-part` (in `panels` too): `analysis-radar`, `analysis-bars`, `analysis-metrics`, `analysis-timeline`, `analysis-text`, `analysis-plays` (the rating's sections), `info-density`, `info-advice`; a theme that shows the patterns itself (`map.patterns`) hides one with `[data-part="analysis-radar"] { display: none }`. | | `leaderboardPanel` | no | — | One panel placed on its own, always shown: the Leaderboard tab of the selected map (local and online boards, score cards). It leaves `tabs` and `panels`. | | `modsPanel` | no | — | One panel placed on its own, always shown: the Mods tab of the selected map (rate, gameplay mods). It leaves `tabs` and `panels`. | | `trainingPanel` | no | — | One panel placed on its own, always shown: the Training tab of the selected map. It leaves `tabs` and `panels`. | | `historyPanel` | no | — | One panel placed on its own, always shown: the History tab of the selected map. It leaves `tabs` and `panels`. | | `mapsPanel` | no | — | One panel placed on its own, always shown: the Maps tab (maps to play). It leaves `tabs` and `panels`. | | `editorPanel` | no | — | One panel placed on its own, always shown: the Editor tab of the selected map. It leaves `tabs` and `panels`. | | `footer` | yes | [library.footer](#library-footer) | Rating, judgement and Play; its `confirm` output must be bound to a button. | #### Components drawn by the host {#screen-library-replaceable} Lists and panels the host draws; a template of these contracts restyles each one, it cannot place them. | Contract | Description | | --- | --- | | [library.setCard](#library-setcard) | One beatmapset (or playlist) of the list; the list repeats it. | | [library.chartRow](#library-chartrow) | One difficulty of the expanded set; the list repeats it. | | [leaderboard.card](#leaderboard-card) | One play of the board (the Leaderboard tab repeats it). | | [rate.control](#rate-control) | The playback rate (the Mods and Training tabs hold it). | | [maps.toPlay](#maps-toplay) | The maps to play: the panel of the Maps tab (charts of the library near the player's level, at a suggested rate). | #### Outputs {#screen-library-outputs} | Output | Arguments | Description | | --- | --- | --- | | `drawer.toggle` | — | Opens or closes the menu drawer (what Escape does): the way out of the screen for a theme that draws its own "menu" button. | | `random` | — | Opens a random map of the current result (what the toolbar's Random does): the list scrolls to it, opens it and selects one of its difficulties. Never a play. | | `mods.open` | — | Opens the Mods tab of the selected map (or playlist). | | `settings.open` | — | Opens the settings (the page the menu drawer's Settings entry opens). | | `mod.set` | `key: string, on: boolean` | Switches a gameplay modifier on or off for the next plays (what its tile in the Mods tab does); switching one on switches off those it conflicts with. A toggle appends the new state: `on.change("mod.set", item.bind("key"))`. | | `rate.set` | `value: number` | Asks for a playback rate (what the rate control does): the action moves it into the range and onto the grid of the open tab. | | `mods.reset` | — | Switches every gameplay modifier off (their parameters are kept). | | `preview.seek` | `at: number` | Moves the preview (music and playfield) to a fraction of the map, 0 to 1: a step of `preview.steps` gives its `at`. Nothing happens while the preview is not shown. | | `preview.toggle` | — | Pauses or resumes the preview. | #### Host classes {#screen-library-classes} | Class | Description | | --- | --- | | `song-select` | The two-column screen (the choices `data-layout-*` place the columns). | | `pv-screen` | A screen root (page padding and entrance). The root of this screen also carries `data-mod-<id>` for every modifier that is on and `data-changed` while `selection.changed`. | | `map-browser` | The library column. | | `browser-body` | The area under the toolbar that holds the lists (positioned: the playlists and the visualizer cover it). | | `browser-list` | The maps search and list. | | `covered` | Added to `browser-list` while the playlists or the visualizer cover it (the list stays mounted, hidden). | | `browser-playlists` | The playlists panel laid over the maps list. | | `selected-map` | The selection column. | | `selected-body` | The selection column's scrolling body (heading, figures, tabs, panels). | | `no-selection` | The invitation shown when nothing is selected. | #### CSS variables {#screen-library-vars} | Variable | Description | | --- | --- | | `--selection-color` | The accent of the selection, for the wash behind the screen. | | `--difficulty-color` | The accent of the selected difficulty (or playlist). | | `--row-distance` | On each row of the maps list (a set card, a difficulty row, the face of `library.setCard` and `library.chartRow` reads it): the number of rows between the row and the one the list centres its curve on, negative above it. The centre is the selected difficulty, else the selected set, else the row in the middle of the viewport. A theme shapes a carousel with it: `transform: translateX(calc(var(--row-distance) * var(--row-distance) * 4px))`. | #### Keys {#screen-library-keys} | Key | Effect | | --- | --- | | ArrowUp / ArrowDown | Previous or next difficulty (`library.up`, `library.down`). | | ArrowLeft / ArrowRight | Previous or next set (`library.previousSet`, `library.nextSet`). | | Enter | Confirms the selection (`chart.confirm`): plays it, trains the section on the Training tab, or picks the lobby's map. | | Escape | Opens or closes the menu drawer (`navigation.drawer`). | ### `screen.lobby` — Multiplayer lobby {#screen-lobby} The room of a multiplayer lobby: its name and join code with the switches that open it and rotate its host, the players with their cards, the map the lobby plays (a card that leads to the song list, with its facts), the files members shared, the lobby's chat (or the player's mods) and the bar with Leave, Spectate and Ready. The screen's host builds every place from the stores and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. What a player looks like is the `player.card` contract (a face: the host keeps the card's root, menu and widgets, the theme draws inside it). The lobby itself, the chat, the preview and every action stay the host's. - Template: `screens.lobby` (`defineTheme({ screens: { lobby: (c) => … } })`) - Typed context: `ThemeContext<'screen.lobby'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-lobby-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text lobby object name string code string codeHidden boolean open boolean hostRotation boolean started boolean self object host boolean ready boolean spectating boolean waiting boolean players object count number rivals number results number map object chosen boolean title string artist string rate number shared boolean files object count number replays number draft object active boolean ``` #### Regions {#screen-lobby-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `title`, `code`, `switches`, `notice` | The lobby's name, its join code and its switches (open to anyone, rotate the host), and the notice of a member who joined mid-round. | | `players` | `playersHead`, `compare`, `roster`, `files` | The players: their heading and count, the HUD gap to compare with and the cards (a `player.card` each), then the files members shared. | | `map` | `map`, `panel` | The map the lobby plays and the panel of the lobby's chat or the player's mods. | | `draft` | `draft` | The pick & ban draft of the lobby. While it runs (`draft.active`) it takes the map's and the chat's place; otherwise it sits between the room and the player's own bar. | | `actions` | `leave`, `spectate`, `ready` | The player's own bar: leave, watch instead of playing, ready. | #### Slots {#screen-lobby-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `title` | yes | — | The lobby's name (`h2`) with its pills (open, rotating host, round started). | | `code` | yes | — | The join code with its hide and copy buttons. | | `switches` | yes | — | The "open lobby" switch (the host only, before the round) and the "rotate the host" switch (the host's to change), each with its help bubble: two labelled switches, side by side. | | `notice` | yes | — | The line that tells a member who joined mid-round they wait for the next one; nothing when it does not apply. | | `playersHead` | no | — | The "Players" heading with the count and, once the round started, whether the results are in. Drawn by the host: a template that prefers its own heading writes it from `players`. | | `compare` | yes | — | The "Gap to" menu that chooses the player the in-play gap is read against; nothing for a spectator, a member who waits, or with no rival. | | `roster` | yes | — | The list of players (a `player.card` each, in the lobby's order or, once the round started, by accuracy), the faded cards of the members who just left and the replay button of each card whose replay the lobby holds. It scrolls. | | `files` | yes | — | The shared files panel: the files members shared (share and download buttons) and the replays to watch. | | `map` | yes | — | The map card: a big button that leads to the song list (the host picks there, a member finds it there) with the map's picture, title, artist, rate, judgement, density graph and facts, the download of a file the lobby shares and the preview button. With no map it says so ("No map chosen yet"). | | `panel` | yes | — | The Chat and Mods tabs and the one panel they open: the lobby's chat (lines, composer) or the player's own modifiers. | | `draft` | no | [lobby.draft](#lobby-draft) | The pick & ban draft of the lobby (`lobby.draft`): the host of a friendly lobby starts one, the captains ban and pick there. A template that leaves it out gets it drawn by the host after its room, so the draft stays reachable. Nothing when the server has no draft (no `lobby-draft` feature) or the lobby runs none and the player is not its host. A template places it where the map is while `draft.active`, and elsewhere otherwise. | | `leave` | yes | — | The Leave button. | | `spectate` | yes | — | The "Watch instead of playing" switch; nothing once the round started. | | `ready` | yes | — | The Ready button (pressed once the player is ready, disabled for a spectator); nothing once the round started. | #### Components drawn by the host {#screen-lobby-replaceable} Lists and panels the host draws; a template of these contracts restyles each one, it cannot place them. | Contract | Description | | --- | --- | | [player.card](#player-card) | One player of the roster: the list repeats it, the card keeps its menu, its replay button and its widgets. | #### Outputs {#screen-lobby-outputs} | Output | Arguments | Description | | --- | --- | --- | | `leave` | — | Leaves the lobby (what the Leave button does). | | `ready.set` | `ready: boolean` | Says whether the player is ready (a spectator cannot be). | | `spectate.set` | `spectate: boolean` | Watches the round instead of playing it, or plays again. | | `code.copy` | — | Copies the join code to the clipboard. | | `map.open` | — | Opens the song list on the lobby's map: the host picks one there, a member finds it there. | #### Host classes {#screen-lobby-classes} | Class | Description | | --- | --- | | `room` | The room's root: a column that fills the page under its header. | | `band` | The header plate: the title, the code and the switches in a row that wraps. | | `grid` | The players column and the map column side by side (stacked under 1000px). | | `people` | The column of the players' panel and the files panel. | | `players-panel` | The plate of the players: heading, HUD gap and the scrolling roster. | | `side` | The column of the map card and the chat panel. | | `actions` | The bottom bar: leave and spectate at the start, ready at the end. | | `push` | An empty item that takes the free width of a row: what follows it is pushed to the end. | | `pv-plate` | The design system's plate (use with `pv-plate--lg` or `pv-plate--md`, and `data-tone` `raised` or `data-edge` `accent`). | | `pv-plate--lg` | The large plate: the shape of a panel (`--pv-clip-lg`). | | `pv-plate--md` | The medium plate: the shape of a button (`--pv-clip-md`). | #### Keys {#screen-lobby-keys} | Key | Effect | | --- | --- | | Enter (in the chat's composer) | Sends the line (one line; Shift+Enter inserts nothing). | | Escape (in the chat's composer) | Takes the focus out of the field, and does not leave the lobby's page on the same press. | | Shift+F10 / context menu key (on a card) | Opens the player's menu; the lobby host's also holds "Make host" and "Kick". | ### `screen.mods` — Mods {#screen-mods} See and manage the mods the game loaded: the page's title with its install, open-folder and reload buttons, the folder they are read from, one card per mod (its state, its enable switch, its permissions with the switches that grant them, Export and Uninstall with its question), the interfaces installed, and the messages the loader and the mods wrote. The screen's host builds every place from the stores and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. The cards are the host's: a template never draws a switch or a permission. - Template: `screens.mods` (`defineTheme({ screens: { mods: (c) => … } })`) - Typed context: `ThemeContext<'screen.mods'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-mods-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text mods object count number active number disabled number failed number folder string interfaces number messages number ``` #### Regions {#screen-mods-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `title`, `actions`, `folder` | The page's title with its buttons, and the folder the mods come from. | | `mods` | `list` | The mods: one card each. | | `footer` | `interfaces`, `messages` | The interfaces installed and the messages of the loader and the mods. | #### Slots {#screen-mods-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `title` | yes | — | The page's heading (`h1`) with the help bubble that says a `.pvmod` file can be dropped on the window. | | `actions` | yes | — | The Install, Open folder and Reload buttons. | | `folder` | yes | — | The line that names the folder the mods are read from. | | `list` | yes | — | The mods' cards (a list with one tab stop and Up and Down between the switches): name, version, author, state, the enable switch, Export and Uninstall, the description, the homepage as plain text, the permissions with the switches the player grants them with, the reason a mod did not start and the question that asks before an uninstall. Or the line that says there is no mod. | | `interfaces` | no | — | The installed interfaces as chips (picture, name, version, author) with the button that leads to the Skins page where one is worn. | | `messages` | yes | — | The "Messages" heading and the log: what the mod loader and the mods wrote, newest at the bottom (a `log` region that follows the newest message). | #### Outputs {#screen-mods-outputs} | Output | Arguments | Description | | --- | --- | --- | | `mod.install` | — | Asks for a `.pvmod` file to install (what the Install button does). | | `mods.folder` | — | Opens the mods folder in the system's file manager. | | `mods.reload` | — | Reads the mods folder again. | | `skins.open` | — | Opens the Skins page, where the interface is chosen. | #### Host classes {#screen-mods-classes} | Class | Description | | --- | --- | | `mods-page` | The page's root: a column, 1100px at most, centred. | | `settings-heading` | The title row of a page (the heading and what sits beside it). | #### Keys {#screen-mods-keys} | Key | Effect | | --- | --- | | ArrowUp / ArrowDown / Home / End (on a mod's switch) | Moves the focus from one mod's enable switch to the previous or next, the first or the last. | | Space (on a mod's switch) | Turns the mod on or off. | ### `screen.profile` — Profile {#screen-profile} The player's local profile: the header (name, rating, accuracy, play time, the medals the player pinned, the trackers, the judgement and rating pickers), the loading bar while the plays are rejudged, the tabs, and the tab shown. The screen's host builds every place from the stores and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. The header's words and numbers are in the input (a template may write its own big name, rating and play time), the figures that count up in place, the lists, the graphs, the heatmap, the achievements and the goals are the host's: a template places and restyles them through their marks, it never redraws them. - Template: `screens.profile` (`defineTheme({ screens: { profile: (c) => … } })`) - Typed context: `ThemeContext<'screen.profile'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-profile-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "pending" | "unavailable" | "empty" | "ready" sessionOpen boolean tab string tabs[] object id string label string count number selected boolean view "best" | "recent" | "pinned" | "left" player object name string initial string charts number plays number playTime string account? object name string offline boolean rating? object value number unit string digits number performance boolean accuracy? number (percent) skillsets[] object name string value number text string color string share number main boolean crowded boolean loading object active boolean done number total number progress number ``` #### Regions {#screen-profile-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `avatar`, `title`, `account`, `badges`, `rating`, `accuracy`, `trackers`, `choices` | The player's picture tile, name, account badge, medals, figures (rating, accuracy, trackers) and the two pickers. | | `status` | `loading` | The bar that says the plays are being rejudged. | | `body` | `tabs`, `panel` | The tabs and the panel of the tab shown. | #### Slots {#screen-profile-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `avatar` | no | — | The player's tile: the first letter of the name on an accent plate. Decorative (hidden from screen readers), so a template may leave it out. | | `title` | yes | — | The page's heading (`h1`): the player's name (the profile is local). | | `account` | yes | — | The online account badge (the account's name, a "no connection" icon when offline) with its tooltip; nothing when the player is not logged in. | | `badges` | yes | — | The medals the player pinned (a group of the achievements' badges, each with its tooltip); nothing when none is pinned. | | `rating` | yes | — | The overall rating as a figure that counts up in place (Performance in pp, or Overall for a rating that is not a sum); nothing before any rated play. Large (`data-size="xl"`). | | `accuracy` | yes | — | The accuracy of the top 20 plays as a figure that counts up in place; nothing without one. | | `trackers` | yes | — | The stat trackers the player chose (up to three: the plays and the play time when none is chosen) and the small button that picks them. | | `choices` | yes | — | The judgement picker and the performance calculator picker the profile is evaluated under: changing either rejudges the plays. | | `loading` | yes | — | The bar (a progress bar with "Evaluating done / total") while the plays are rejudged; nothing otherwise. | | `tabs` | yes | — | The tab list (Overview, Plays, Analysis, Sessions, Achievements, Goals): a roving-focus tab list with arrows, Home and End; the panel is its tab panel. Nothing when the page has no profile to show. | | `panel` | yes | — | The tab shown, as one focusable tab panel (`data-section` names the tab): the radar with the objectives and two short lists of plays; the filtered plays; the calendar and the sessions; the error map; the achievements; or the goals and the progress. Nothing when the page has no profile to show. | #### Outputs {#screen-profile-outputs} | Output | Arguments | Description | | --- | --- | --- | | `tab.select` | `tab: string` | Shows a tab: `overview`, `plays`, `analysis`, `sessions`, `achievements` or `goals`. An unknown tab does nothing. | | `plays.open` | `view: string` | Shows the plays tab on a filter: `best`, `recent`, `pinned` or `left` (what "See all" of the overview's lists does). An unknown filter shows the best plays. | | `refresh` | — | Rejudges the plays again under the current judgement and calculator (what changing either picker does). | #### Host classes {#screen-profile-classes} | Class | Description | | --- | --- | | `profile` | The page's root: a column with the page's padding that fills the window. | | `pv-screen` | A screen root (page padding and entrance). | | `pv-ui` | The design system's plates and buttons under the root, in Classic too. | | `pv-plate` | The design system's plate (use with `pv-plate--lg` or `pv-plate--md`, and `data-tone` `base`, `raised` or `accent`, or `data-edge` `accent`). | | `pv-plate--lg` | The large plate: the shape of a panel (`--pv-clip-lg`). | | `pv-plate--md` | The medium plate: the shape of a button (`--pv-clip-md`). | | `identity-band` | The header plate: a row (avatar, name, medals, figures, pickers) that grows as wide as the page. | | `wraps` | Added to the header while pinned medals or a third tracker fill it: the row wraps and the pickers go to the end. | | `identity` | The name column of the header: a block that takes the free width. | | `name-line` | The row of the name and the account badge. | | `figures` | The row of the rating, the accuracy and the trackers, pushed to the end of the header. | | `section-bar` | The row that holds the tab list. | | `status` | A line of the page's own words (no host, no play yet) in the page's muted text. | #### Keys {#screen-profile-keys} | Key | Effect | | --- | --- | | ArrowLeft / ArrowRight / Home / End (on the tab list) | The focus and the tab shown move to the previous or next tab, the first or the last. | | Tab (on the tab panel) | The panel is a stop of its own, so the keyboard can scroll it; the arrows and Page Up and Page Down scroll it. | ### `screen.replay` — Score analysis {#screen-replay} The analysis of one recorded score, and the result screen a finished play opens: the map, the player and the score's figures (accuracy, performance, best combo, pauses, the map's difficulty at the rate played, the mean offset), the list of every judgement with its count, the three graphs (hit timing, hit-offset distribution, progression) with their zoom and inspection, the judgement, performance and difficulty pickers the figures are re-evaluated under, and the actions on the score (compare with another play of the chart, watch it, watch it beside another, export a video, share it, train its worst section). The screen's host builds every place from the stores and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. The graphs, the pickers, the comparison and the judgement list stay the host's: a template arranges and dresses them, it never redraws one. The figures are plain data the template may also write in its own way (a banner, a sentence), but the host's own figures count up and down in place when the judgement changes. - Template: `screens.replay` (`defineTheme({ screens: { replay: (c) => … } })`) - Typed context: `ThemeContext<'screen.replay'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-replay-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text status "loading" | "ready" | "error" | "unavailable" loading boolean mock boolean lobby boolean playback "stopped" | "loading" | "playing" map object title string artist string difficulty string keys string creator string picture? string color string rate string mods string score? object replayId string player string received boolean playedAt string accuracy number (percent) maxCombo number misses number ranked boolean pauses? number performance? number performanceUnit string rating? number ratingUnit string ratingName string meanOffsetMs? number judgement string tiers[] object id string name string color string count number share number (percent) comparison object shown boolean chosen boolean player string rate string newRecord boolean firstPlay boolean failed boolean references[] object replayId string player string rate string mods string accuracy number (percent) maxCombo number picked boolean ``` #### Regions {#screen-replay-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `back`, `title`, `judgement`, `performance`, `rating`, `compare`, `watch`, `sideBySide`, `export`, `share`, `train` | The way back, the title and the pickers the figures are re-evaluated under, then the actions on the score. | | `status` | `standings`, `notices`, `transport` | What the host has to say about the replay: the lobby's standings, the notices, the transport of a replay being watched. | | `summary` | `banner`, `comparison` | The map and the comparison with another play. | | `score` | `player`, `stats`, `tiers` | The player, the figures, and the judgement list of the score. | | `analysis` | `graphs`, `status` | The three graphs, or what the page says while there is nothing to show. | #### Slots {#screen-replay-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `back` | yes | — | The arrow that leaves the page for the song list (the selection and the leaderboard's pages are kept). | | `title` | yes | — | The heading (`h1`, the page's accessible name and the first place of the focus) with, beside it, the mark of the development host and the "updating" status of a recalculation. | | `judgement` | yes | — | The judgement picker: a menu of the judgements the figures and the graphs are evaluated under, with its quick panel of windows. | | `performance` | yes | — | The performance picker: a menu of the calculators the performance is computed with. | | `rating` | yes | — | The difficulty picker: a menu of the calculators the map's difficulty is read with. | | `compare` | yes | — | The "Compare score" menu: the other plays of the chart, one to choose as the reference, and the button that clears the choice. Its panel opens under the button. | | `watch` | yes | — | The Watch replay button: runs the recorded presses through the game at the recorded rate (never creates a score). | | `sideBySide` | yes | — | The Watch side by side button: the score and the reference beside each other on one clock; off while no compatible reference is chosen, and its tooltip says why. | | `export` | yes | — | The Export video button and the panel it opens (resolution, quality, encoder, a clip). | | `share` | yes | — | The Share button: copies the replay to a file or a link. | | `train` | yes | — | The worst-section button: puts the passage the play lost the most in training at the recorded rate (a menu when several passages tie). | | `standings` | yes | — | The standings of a lobby round (every player's score, the gap to yours, the winner); nothing for a score that is not a lobby's. | | `notices` | yes | — | The lines that tell what is happening: a failed update, no weak passage found, "watching, press Escape to return", a refusal or an error of a replay. Nothing when there is nothing to say. | | `transport` | yes | — | The transport of a replay being watched (play and pause, seek, speed); nothing when no replay runs. | | `banner` | no | — | The map's strip: its picture, the artist, the title and the difficulty, the key count, the recorded rate and the chart modifiers, the mapper. Drawn by the host: a template that prefers its own banner writes it from `map`. | | `comparison` | yes | — | The line about the reference play: its player, the "new record" mark, the gaps (accuracy, combo, misses, rating, performance) that count up and down in place, or "first play of this chart", or the error of the comparison. It may be empty. | | `player` | yes | — | The player's name (`h2`) with the mark of a received replay, and the date of the play. | | `stats` | yes | — | The score's figures (`dl`): accuracy, performance, best combo, pauses, the map's difficulty at the rate played, the mean offset. Each figure counts up or down in place when the judgement changes and carries its own `data-part` (`accuracy`, `performance`, `combo`, `pauses`, `difficulty`, `offset`). | | `tiers` | yes | — | The judgement list: one row per judgement, Miss included, with the player's own symbol, the count (a counter), the share of notes as a bar, the ratios of the first two hit tiers and the total. It has its own bounded scrolling when there are many. | | `graphs` | yes | — | The analysis: the tabs (Hit timing, Hit-offset distribution, Progression), the zoom, the inspection of one hit, the key highlights, the long-note analysis and the comparison curves. Nothing in it is a template's to redraw. | | `status` | yes | — | What the page says while there is no analysis to show: reading the score, the error that stopped it, "no analysis". Nothing once the score is there (place it where `status` is not `ready`). | #### Outputs {#screen-replay-outputs} | Output | Arguments | Description | | --- | --- | --- | | `back` | — | Leaves the page for the song list (what the arrow does and Escape does). | | `watch` | — | Watches the replay in the game (what the Watch replay button does); refused while another one is being watched. | | `watch.sideBySide` | — | Watches the score beside the reference play on one clock (what the Watch side by side button does); the host refuses a reference of another rate or other chart modifiers. | | `share` | `replayId: string` | Shares the replay (what the Share button does). | | `compare.pick` | `replayId: string` | Chooses the play to compare the score with (a `replayId` of `comparison.references`). | | `compare.clear` | — | Clears the chosen reference: the best earlier play is shown again. | #### Host classes {#screen-replay-classes} | Class | Description | | --- | --- | | `replay-page` | The page's root: a column that fills the window, with the page's padding. Keep it, with `data-block: 'replay'`, on the root of a template that wants the host's own sizes. | | `pv-screen` | A screen root (page padding and entrance). | | `page-header` | The header row: the way back, the title and the pickers and actions pushed to the end. | | `replay-controls` | The pickers and the actions in a row that wraps, pushed to the end of the header. | | `replay-actions` | The actions on the score (compare, watch, side by side, export, share, train) as one group. | | `replay-scroll` | The box that holds the page's content (it scrolls under 800px). | | `replay-content` | The centred column of the content: the banner, the comparison and the analysis. | | `replay-layout` | The score overview and the graphs side by side. | | `score-overview` | The score's column: the player, the figures and the judgement list. | | `pv-plate` | The design system's plate (use with `pv-plate--lg`, and `data-edge` `accent`). | | `pv-plate--lg` | The large plate: the shape of a panel (`--pv-clip-lg`). | #### CSS variables {#screen-replay-vars} | Variable | Description | | --- | --- | | `--map-color` | The colour of the difficulty on the chosen rating: the host paints the difficulty's name with it, and a template may do the same (`vars: { '--map-color': c.bind('map.color') }` on its root). | #### Keys {#screen-replay-keys} | Key | Effect | | --- | --- | | Escape | Closes the comparison menu when it is open, else leaves the page for the song list. | | + / - / 0 / arrows (on a graph) | Zoom, pan and reset of the graph the focus is in. | | ArrowLeft / ArrowRight / Home / End (on the graph's tabs and the inspection) | Moves between the tabs, and from one judged note to the previous or the next, the first or the last. | ### `screen.result` — Result {#screen-result} What the last play came to: the accuracy, the best combo and how many hits each judgement got, with a mark when the play was aborted, was an Auto play or does not count for the rankings. The host builds the heading with its marks, the list of judgement counts (a tier's symbol is the player's own, an image or a text) and the close button, and mounts them where the template says; the template writes the figures itself from the input and decides WHERE everything goes and how it is wrapped. It lives ten seconds, then goes away. - Template: `screens.result` (`defineTheme({ screens: { result: (c) => … } })`) - Typed context: `ThemeContext<'screen.result'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-result-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text aborted boolean auto boolean ranked boolean judgement string accuracy number (percent) maxCombo number clear "aborted" | "perfect" | "fullCombo" | "clear" newBest boolean hits number misses number tiers[] object id string name string color string count number ``` #### Regions {#screen-result-regions} | Region | Slots | Description | | --- | --- | --- | | `summary` | `title`, `tiers`, `close` | The heading with its marks, the list of judgement counts and the close button; the figures between them are the template's own. | #### Slots {#screen-result-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `title` | yes | — | The heading (`h2`): "Result" or "Aborted", followed by the marks of an Auto play and of a play that does not count for the rankings. It is the summary's name for assistive technology (the summary is a polite live region). | | `tiers` | yes | — | The list of judgement counts: one entry per judgement with its count, its colour swatch and its symbol (the player's own symbol, else the judgement's name). | | `close` | yes | — | The close button: it removes the summary at once (what the ten-second expiry does later). | #### Outputs {#screen-result-outputs} | Output | Arguments | Description | | --- | --- | --- | | `dismiss` | — | Removes the summary now (what the close button does). | #### Host classes {#screen-result-classes} | Class | Description | | --- | --- | | `results` | The summary's own box: fixed over the foot of the window (left, right and bottom insets), a row with the heading pushed to the left, a plate under the interface themes. A stylesheet cannot make a box fixed, so a template keeps this class on its root and moves or reshapes the box with a class of its own (`top`, `right`, `bottom`, `left`, `width`, `padding`, the plate's `::before` and `::after`); a root without it would sit in the page's flow, under the song list. | ### `screen.settings` — Settings {#screen-settings} Change how the game plays, looks and sounds: seven categories (rail), a search over every setting, the open category's sections (panel) with its live summary. The screen's host builds every place from the stores and the settings and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. The keyboard (arrows in the rail, `/` and Ctrl+F for the search, Escape), the focus trap and the live summaries stay the host's, and the settings controls keep reading the theme tokens. - Template: `screens.settings` (`defineTheme({ screens: { settings: (c) => … } })`) - Typed context: `ThemeContext<'screen.settings'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-settings-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text category object id "gameplay" | "controls" | "audio" | "display" | "library" | "online" | "system" label string blurb string changed number index number hasSummary boolean categories[] object id "gameplay" | "controls" | "audio" | "display" | "library" | "online" | "system" label string blurb string changed number selected boolean search object active boolean query string found number changed number ``` #### Regions {#screen-settings-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `title`, `search`, `actions`, `close` | The title, the search and the window's own buttons. | | `body` | `notices`, `rail`, `panel` | The notices, the category list and the sections of the open category. | | `footer` | `hints` | The line of keyboard hints. | #### Slots {#screen-settings-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `title` | yes | — | The window's heading (`h1`): it names the dialog for assistive technology. | | `search` | yes | — | The search field over every setting (`/` and Ctrl+F reach it from anywhere in the window). | | `actions` | yes | — | Export and import of the settings, and "Restore defaults" for all of them (it asks first). | | `close` | yes | — | The Close button. | | `notices` | yes | — | What the game has to say over the settings (updates…), the notice of an export or an import and the review of an imported file. Position the review (`[data-part='review']`) with the notice box if the layout moves it. | | `rail` | yes | — | The category list: the tab list with arrows, Home and End, the count of changed settings and the pin menu; the choice `--pv-layout-settings` (side, top, index, rail) shapes it. | | `panel` | yes | — | The scrolling panel: the open category's heading with its reset button and live summary, then its sections; or the rows a search found. It is the `tabpanel` of the rail. | | `hints` | no | — | The keyboard hints (search, category, page, Escape): decoration, hidden from assistive technology. | #### Outputs {#screen-settings-outputs} | Output | Arguments | Description | | --- | --- | --- | | `close` | — | Closes the settings (what Escape and the Close button do). | | `category.select` | `id: string` | Opens a category (what a click on its tab does: the search is emptied and the panel scrolls to the top). An unknown id does nothing. | | `search.focus` | — | Puts the focus in the search field (what `/` does). | | `search.clear` | — | Empties the search and shows the open category again. | #### Host classes {#screen-settings-classes} | Class | Description | | --- | --- | | `settings-page` | The window's content: a column that clips what overflows. | | `settings-top` | The header row (title, search, buttons) with a hairline under it. | | `settings-top-actions` | The group of the header's buttons, pushed to the right. | | `settings-layout` | The rail and the panel side by side (the choices `data-layout-settings` place them); stacked under 700px. | #### Keys {#screen-settings-keys} | Key | Effect | | --- | --- | | ArrowUp / ArrowDown / ArrowLeft / ArrowRight | On a category tab: the previous or next category opens and takes the focus; Home and End go to the first and the last. | | / or Ctrl+F | Puts the focus in the search field and selects what it holds. | | Enter / ArrowDown | In the search field: the focus goes to the first row found. | | Escape | Closes what is open in the window first (a list, a capture), then empties the search, then closes Settings. | | Tab / Shift+Tab | Stays inside the window: from the last control to the first and back. | | A letter on a category tab | Starts a search with that letter. | ### `screen.skins` — Skins {#screen-skins} Choose the menus' interface (a carousel of the installed themes) and the skin the plays run: the page's title, the notices of a skin import or a configuration review, the interface picker, and the skins' section (its search and Actions menu, one card per skin with its Use, Customize, export, reset and remove buttons, then the problems the skins folder reported). The screen's host builds every place from the stores and mounts it where the template says; the template only decides WHERE things go and how they are wrapped. The interface picker is the one place a theme can never drop or hide: the host draws the page's default composition whenever the template does not leave it on screen. - Template: `screens.skins` (`defineTheme({ screens: { skins: (c) => … } })`) - Typed context: `ThemeContext<'screen.skins'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-skins-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text interfaces object count number current string currentName string skins object count number shown number selected string searching boolean importers number problems number ``` #### Regions {#screen-skins-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `title`, `notices` | The page's title and the notices of an import or of a configuration review. | | `interfaces` | `interfaces` | The interface picker: the themes as cards in a carousel. | | `skins` | `skinsHead`, `skins`, `problems` | The skins' section: its header, the cards and the folder's problems. | #### Slots {#screen-skins-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `title` | yes | — | The page's heading (`h1`). | | `notices` | yes | — | The review of a configuration the player imported and the progress of a skin import (what was read, with its Edit and Dismiss buttons); nothing when there is none. | | `interfaces` | yes | — | The interface picker: a search, the arrows and the Actions menu (open the themes folder, reload) over a carousel of one card per theme with its picture, name, description and author (arrows, Home and End, drag, the wheel); choosing a card applies the theme at once. The ONE place a template cannot lose: it is how a player leaves a theme that does not suit them, so the host draws its own default page when a template does not leave it visible. | | `skinsHead` | yes | — | The skins' section header: its title with its help, the search (from eight skins) and the Actions menu (convert a skin, per-key-count skins, import, open the folder, reload). | | `skins` | yes | — | One card per skin: preview, name, version, author, "in use" and key-count badges, the customization line, the reset and remove questions, the problems of the skin, and its buttons (Customize, Use, export, the configuration's export and import, remove, reset). Or the line that says there is no skin or none matches. | | `problems` | yes | — | The problems the skins folder reported; nothing when there are none. | #### Outputs {#screen-skins-outputs} | Output | Arguments | Description | | --- | --- | --- | | `interface.use` | `id: string` | Wears an interface (what a click on its card does); an id of no installed theme falls back to the first one the game lists. | | `skin.use` | `id: string` | Runs a skin from the next map launch on (what Use does). | | `skin.customize` | — | Opens the editor on the skin in use (what Customize does). | | `skins.import` | — | Asks for a skin file to import (the Actions menu's Import). | | `skins.folder` | — | Opens the skins folder in the system's file manager. | | `skins.reload` | — | Reads the skins folder again. | #### Host classes {#screen-skins-classes} | Class | Description | | --- | --- | | `skins-page` | The page's root: a scrolling column, 1100px at most, centred. | | `settings-heading` | The title row of a page (the heading and what sits beside it). | | `skins-section` | The skins' section: its header, the cards and the problems, with the section's bottom margin. | #### Keys {#screen-skins-keys} | Key | Effect | | --- | --- | | ArrowLeft / ArrowRight / Home / End (on the interface carousel) | Moves from one theme to the previous or next, the first or the last; the card with the focus is revealed. | | Enter (in the interface search) | Applies the first theme the search found. | | Escape (in a search or a question) | Empties the search, or closes the question of a reset or a removal, and does nothing else (the menu drawer stays shut). | ### `screen.title` — Title {#screen-title} The screen the game opens on, once at each launch: the logo, the name, the cue to press a key, the band that moves with the music, the version, and the map of the library that plays. Any key, click or touch enters the game whatever the template draws (the host owns the window, the keys and the music). While the screen leaves, its root carries `data-leaving`, and `--beat` (0 to 1, on the music's bass) is set on it for a theme's `theme.css` to swell what it likes. - Template: `screens.title` (`defineTheme({ screens: { title: (c) => … } })`) - Typed context: `ThemeContext<'screen.title'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-title-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text version string leaving boolean nowPlaying object known boolean title string artist string ``` #### Regions {#screen-title-regions} | Region | Slots | Description | | --- | --- | --- | | `center` | `logo`, `name`, `press` | The middle of the screen: the logo, the name and the cue. | | `foot` | `band`, `version`, `nowPlaying` | The bottom of the screen: the band, the version and the map that plays. | #### Slots {#screen-title-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `logo` | no | — | The game's mark with its halo, which breathes and swells on the bass (`--beat`). | | `name` | yes | — | The game's name (`h1`): the screen's heading for assistive technology. | | `press` | yes | — | The cue that says how to enter ("press any key"): a player must always be told. | | `band` | no | — | The spectrum band: bars that follow the music (a calm wave while none plays), drawn by the host in a canvas that fills the box it is given. | | `version` | no | — | The game's version in a small plate. | | `nowPlaying` | no | — | The map that plays: its artist and title in one line, nothing while none is drawn. | #### Outputs {#screen-title-outputs} | Output | Arguments | Description | | --- | --- | --- | | `enter` | — | Enters the game now (what any key, click or touch does). | #### Host classes {#screen-title-classes} | Class | Description | | --- | --- | | `title-center` | The default middle column: the logo, the name and the cue centred, a little above the middle. | | `title-foot` | The default foot: a strip along the bottom edge that holds the band, with the version over it. | | `title-glow` | The soft light that breathes behind the middle. | #### CSS variables {#screen-title-vars} | Variable | Description | | --- | --- | | `--beat` | The music's bass, 0 to 1: quick to rise, slow to fall (0 under reduced motion). | #### Keys {#screen-title-keys} | Key | Effect | | --- | --- | | Any key, click or touch | Enters the game (the first one only starts the music when the browser held it back). | ### `screen.tournaments` — Tournaments {#screen-tournaments} The tournaments of the site: the list (filtered by status), one tournament with its facts, its entries and its bracket or standings, one match with its games, and the player's own entries with the next match and its countdown. The host reads the site; the game only reads it, and sends the four actions the site lets a player take from the game. A template places the screen's places and wraps them; the lists, the bracket and the countdown are the host's. - Template: `screens.tournaments` (`defineTheme({ screens: { tournaments: (c) => … } })`) - Typed context: `ThemeContext<'screen.tournaments'>` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Input {#screen-tournaments-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text gate "page" | "offline-note" | "login" view "list" | "detail" | "match" | "mine" filter "all" | "registration" | "running" | "finished" loading boolean failure? object text string notice? object text string list object total number page number pages number empty boolean items[] object slug string name string format string status "draft" | "registration" | "seeding" | "running" | "finished" | "cancelled" statusText string mode string entries number maxEntries? number when string winner? string tournament? object slug string name string description? string format string status "draft" | "registration" | "seeding" | "running" | "finished" | "cancelled" statusText string mode string metric string bestOf number entries number maxEntries? number registration string starts string entered boolean canRegister boolean canWithdraw boolean entriesList[] object id string seed? string name string status string members[] object userId string username string captain boolean self boolean bracket[] object bracket "winners" | "losers" | "grand_final" name string matches[] object id string round string state "pending" | "ready" | "running" | "done" | "void" bestOf number sides[] object name string score? string winner boolean seed? string when? string referee? string forfeit? string standings[]? object rank number name string points string maps[] object slot string value string tiebreaks[]? object label string value string forfeitAfterMin number pool[] object slot string tag string tiebreaker boolean playbackRate string map string qualifier? object rules string phaseText string attempts? string sessions[] object id string n number when string countdown string seats string state "scheduled" | "frozen" | "open" | "running" | "closed" | "cancelled" stateText string seat? object state "subscribed" | "played" | "no_show" | "withdrawn" text string canTake boolean canLeave boolean playable boolean joinable boolean game? object id string round string bestOf number sides[] object name string score? string winner boolean seed? string games[] object number number map string playbackRate string pickedBy? string winner? number scores[] object side number value string mine[] object slug string name string status string entryStatus "registered" | "incomplete" | "disqualified" | "withdrawn" entryText string nextMatch? object id string opponent string when string countdown string joinCode? string qualifier? object attempts string next? object session string when string countdown string playable boolean joinable boolean ``` #### Regions {#screen-tournaments-regions} | Region | Slots | Description | | --- | --- | --- | | `header` | `back`, `title`, `online` | The way back (to the list, or to the tournament), the title with its help bubble, and the connection chip with the chat button. | | `status` | `gate`, `failed`, `notice` | The notice of offline mode, the line that says what could not be read (with its retry), and the result of the last action. | | `toolbar` | `tabs`, `filters` | The tabs between the list and the player's own entries, and the status filter of the list. | | `list` | `list` | The tournaments on the site, as cards, with the pager. | | `detail` | `detail`, `qualifier`, `entries`, `bracket`, `standings` | One tournament: its facts and its actions, then its entries, then its bracket or its standings. | | `match` | `match` | One match: its sides and its games. | | `mine` | `mine` | The player's entries with the next match (or qualifier session) and its countdown. | #### Slots {#screen-tournaments-slots} | Slot | Required | Mounts | Description | | --- | --- | --- | --- | | `back` | yes | — | The back arrow: from a match to its tournament, from a tournament to the list, from the list to the song selection. | | `title` | yes | — | The page's heading (`h1`) with the help bubble that says the game reads the site and sends only four actions. | | `online` | yes | — | The online chip (the account's connection) and the chat button. | | `gate` | yes | — | The notice of offline mode with its button to Settings → Online; nothing otherwise. | | `failed` | yes | — | The line that says what could not be read, with its Retry button; nothing when everything was read. | | `notice` | yes | — | The line that says what the last action did (registered, withdrawn, member removed); nothing otherwise. | | `tabs` | yes | — | The two tabs of the page (All tournaments, My entries). | | `filters` | yes | — | The status filter of the list (all, registration, running, finished) as a segmented control. | | `list` | yes | — | The tournaments as cards (name, format, mode, status, entries, the date that matters) and the pager; or the line that there is none. | | `detail` | yes | — | The tournament's header: name, status, format, mode, metric, dates, entries count and its actions (register, withdraw, join a team with a code). | | `qualifier` | no | — | The qualifier played in lobbies at fixed sessions: its rules, the attempts left and each session with its seats; the player takes a seat, gives it back, or joins the lobby the server opened. Nothing for another tournament. Added in THEME_API 2. | | `entries` | yes | — | The entries: seed, name, state and members, the captain marked and the player's own entry marked; a captain can remove a member. | | `bracket` | yes | — | The bracket as columns of match cards; the columns scroll sideways inside the bracket only. Nothing for a qualifier. | | `standings` | yes | — | The ranking of a qualifier or a Swiss tournament: rank, name, points, then the map by map scores (a qualifier) or the tiebreaks (a Swiss tournament); nothing when the tournament has no standings. | | `match` | yes | — | One match: the sides, the round, the schedule, the referee, the forfeit, and the games with their maps and scores. | | `mine` | yes | — | The player's entries as cards: the state, the next match with its countdown, the join code of a captain's own team. | #### Outputs {#screen-tournaments-outputs} | Output | Arguments | Description | | --- | --- | --- | | `back` | — | Leaves the page for the song selection (what the back arrow does on the list). | | `nav.up` | — | Goes back one level: from a match to its tournament, from a tournament to the list. | | `refresh` | — | Reads the page again (what Retry does): the list or the tournament, its matches and the player's entries. | | `settings.open` | — | Opens Settings → Online (what the offline notice's button does). | | `view.select` | `view: string` | Shows `list` or `mine`. An unknown view shows the list. | | `filter.select` | `filter: string` | Filters the list by `all`, `registration`, `running` or `finished`. An unknown filter shows all. | | `page.select` | `offset: number` | Shows the page of the list that starts at this offset (a multiple of the page size); the filter is kept. | | `tournament.open` | `slug: string` | Opens a tournament: its facts, entries, bracket or standings. | | `match.open` | `matchId: string` | Opens one match of the tournament shown: its sides and games. | | `register` | `teamName: string?` | Registers the player in the tournament shown (a team name is asked for a team tournament). | | `join.team` | `code: string` | Joins a team with its join code (the code the captain shows, never kept after). | | `withdraw` | — | Withdraws the player's entry from the tournament shown. | | `member.remove` | `userId: string` | Removes a member from the captain's team in the tournament shown. | | `session.take` | `sessionId: string` | Takes a seat in a session of the qualifier of the tournament shown (a team: its captain seats it). | | `session.join` | — | Joins the lobby of the qualifier session the server invited the player to (the invitation the notice card also offers). | | `session.leave` | `sessionId: string` | Gives a seat of a qualifier session back, with its attempt. | #### Host classes {#screen-tournaments-classes} | Class | Description | | --- | --- | | `tournaments` | The page's root: a column with the page's padding that fills the window. | | `pv-screen` | A screen root (page padding and entrance). | | `pv-ui` | The design system's plates and buttons under the root, in Classic too. | | `pv-plate` | The design system's plate (use with `pv-plate--lg`, and `data-tone` or `data-edge` `accent`). | | `page-head` | The header row (back, title, chips) that wraps when the window is narrow. | | `label-line` | The row of the title and its help bubble. | | `push` | An empty item that takes the free width of a row: what follows it is pushed to the end. | | `body` | The page under the header: a column that fills the free height. | | `bar` | A row of tabs and filters, wrapping when narrow. | | `cards` | A grid of cards (the list, the entries, my entries). | | `card` | One tournament, entry or match card (a plate). | | `facts` | A list of terms (the tournament's facts). | | `bracket-scroll` | The scrolling area of the bracket: the columns side by side, scrolling sideways. | | `bracket-col` | One column of the bracket: the round's name and its match cards. | | `mark` | A small status mark (`data-state`: registration, running, finished, cancelled, ...). | | `note` | A line of the page's own words in the muted text. | | `pager` | The previous and next buttons and the page number of a list. | | `countdown` | The countdown to the next match, tabular figures. | #### Keys {#screen-tournaments-keys} | Key | Effect | | --- | --- | | ArrowLeft / ArrowRight (on the tabs) | Moves from the list to "My entries" and back. | | Escape (on a sub-page) | Goes back one level (match to tournament, tournament to list). | | Enter (on a tournament card) | Opens the tournament. | ## Components {#components} ### `catalog.card` — Catalogue entry {#catalog-card} One skin, mod or playlist of Prism's catalogue, with the action that installs it. The card is a list item the page provides (`ul.cards`); its state says what the action beside it offers (install, update, cancel, installed), which is what a template must keep. - Template: `components['catalog.card']` - Typed context: `ThemeContext<'catalog.card'>` - Default renderer: `CatalogCard` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Face {#catalog-card-face} This contract is a **face**: the host draws and owns the card's own root (its button or plate, keyboard, menus, tooltips, actions and accessible name); a template draws what is **inside** it from the input, and uses `slots` for the host's own widgets. A face has no `button`, `toggle`, `dropdown`, no `slot` of another contract, calls no output, and none is required of it. #### Input {#catalog-card-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "available" | "update" | "installed" | "downloading" | "installing" kind "skin" | "mod" | "playlist" id string name string versionText string byText string size string hash string description? string tags[] string cover? string shots[] object url string alt string permissions[] string badge? string state = available: {} state = update: from string state = installed: disabled boolean state = downloading: percent? number state = installing: {} ``` #### States {#catalog-card-states} | State | Meaning | | --- | --- | | `available` | Not installed: the action is an Install button. | | `update` | Installed, and the catalogue lists a newer version: the action is an Update button. | | `installed` | In the library: a check mark, the card is muted. | | `downloading` | The file is being received: a Cancel button, the percentage under the card and a meter along its foot. | | `installing` | Being installed: no action, "installing" under the card. | #### Outputs {#catalog-card-outputs} | Output | Arguments | Description | | --- | --- | --- | | `install.ask` | — | Starts the install (what the Install and Update button does): a skin or a playlist installs at once, a mod first asks the player to confirm what it can do. | | `install.cancel` | `kind: "skin" \| "mod" \| "playlist", id: string` | Cancels the download in progress. | #### Slots {#catalog-card-slots} | Slot | Description | | --- | --- | | `permissions` | The permissions a mod asks for, each with its badge and what it means in plain words (or "asks for nothing"): a face may place it; the install confirmation lists them again, so a face that leaves it out hides nothing a player must see. | | `progress` | The progress and the result of an install (percentage, "installing", done with the buttons that follow, failed with its reason): the host draws it under the card itself (a face cannot place it). | | `below` | The question a mod's install asks before it starts (what it can do, its hash, Install and Cancel): the host draws it under the card itself (a face cannot place it). | #### Parts {#catalog-card-parts} | Part | Role | Description | | --- | --- | --- | | `cover` | `img` | The first screenshot. | | `install` | `button` | The Install or Update button. | | `cancel` | `button` | The Cancel button of a running download. | | `installed` | `img` | The check mark of an installed entry. | #### Accessibility {#catalog-card-a11y} - Role: `listitem` - Name: The entry's name, with its version and author. - Focus: The list item is a focus target by program; the buttons inside are in the tab order. | Keyboard | Effect | | --- | --- | | Tab | Reaches the card's buttons: Install, Update or Cancel, then the ones of its result and of its question. | #### Musts {#catalog-card-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `install-button` | `install` exists with role `button`, reachable by keyboard | `available`, `update` | An entry that is not installed offers a real Install or Update button, reachable by the keyboard. | | `install-click` | click on `install` calls `install.ask()` | `available`, `update` | Pressing the button starts the install. | | `install-enter` | Enter on `install` calls `install.ask()` | `available`, `update` | Enter on the button starts the install. | | `no-install-when-running` | `install` is not drawn | `installed`, `downloading`, `installing` | An entry that is installed, being received or being installed offers no Install button. | | `cancel-button` | `cancel` exists with role `button`, reachable by keyboard | `downloading` | A download in progress can be cancelled with a real button, reachable by the keyboard. | | `cancel-click` | click on `cancel` calls `install.cancel(kind, id)` | `downloading` | Pressing Cancel cancels the download. | | `installed-mark` | `installed` exists with role `img`, not a tab stop | `installed` | An installed entry shows its check mark. | ### `download.card` — Download result {#download-card} One result of the Download page: a set of osu!, Quaver, a mod's source or Prism's index, or an Etterna pack, with the action that downloads it. The card is a list item the page provides (`ul.cards`); its state says what the action beside it offers (download, wait, progress, installed, retry), which is what a template must keep. - Template: `components['download.card']` - Typed context: `ThemeContext<'download.card'>` - Default renderer: `DownloadCard` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Face {#download-card-face} This contract is a **face**: the host draws and owns the card's own root (its button or plate, keyboard, menus, tooltips, actions and accessible name); a template draws what is **inside** it from the input, and uses `slots` for the host's own widgets. A face has no `button`, `toggle`, `dropdown`, no `slot` of another contract, calls no output, and none is required of it. #### Input {#download-card-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "idle" | "locked" | "unavailable" | "queued" | "active" | "failed" | "installed" shape "set" | "pack" kind "osu" | "quaver" | "etterna" | "mod" id number title string edge string set? object artist string creator? string creatorText? string cover string badges[] string keySummary string difficulties[] object keysText string keys number rating? string color string title string skills[] object badge string color string more number bpm? string plays? string longNotes? string extra? object tags[] string size? string details[] object label string value string pack? object cover? string nsfw boolean songs string size string plays string tags string skills[] object key string label string value string color string main boolean open boolean progress? number reason? object text string detail? string message? string startDisabled boolean actions[] object id string label string previewable boolean state = idle: redownload boolean state = locked: lock "quaver" | "mod" state = unavailable: {} state = queued: {} state = active: phase "downloading" | "extracting" percent? number state = failed: jobId number state = installed: {} ``` #### States {#download-card-states} | State | Meaning | | --- | --- | | `idle` | Not downloaded: the action is a download button. | | `locked` | Not downloaded and the source needs a login first: the action is a lock that opens the settings. | | `unavailable` | Not downloaded and nothing to start from the action: a result with no public source, or one that only has the buttons its source adds. | | `queued` | Waiting in the queue: a clock. | | `active` | Downloading or extracting: the percentage, and a progress line along the card. | | `failed` | The last try failed: a retry button, and the reason under the card. | | `installed` | In the library: a check mark, the card is muted. | #### Outputs {#download-card-outputs} | Output | Arguments | Description | | --- | --- | --- | | `download.start` | — | Starts the download of the result (its main file). | | `download.action` | `action: string` | Starts the download of another file of a mod's result (a button its source adds); the argument is the action's id. | | `download.retry` | `jobId: number` | Starts a failed download again. | | `settings.open` | `target: string` | Opens the settings where the login of a locked source is made (`quaver-token` or `mod-downloads`). | | `preview.open` | — | Opens the map preview of a Prism result, over the queue. | | `pack.toggle` | `id: number` | Opens or closes the songs of an Etterna pack under its card. | #### Slots {#download-card-slots} | Slot | Description | | --- | --- | | `contents` | The songs of an open Etterna pack: the host draws them under the card itself (a face cannot place them). | #### Parts {#download-card-parts} | Part | Role | Description | | --- | --- | --- | | `toggle` | `button` | The pack's main control: opens or closes its songs. | | `download` | `button` | The download button. | | `retry` | `button` | Starts the failed download again. | | `lock` | `button` | The lock of a source that needs a login: opens the settings. | | `installed` | `img` | The check mark of an installed result. | | `queued` | `img` | The clock of a queued download. | | `progress` | `text` | The percentage of a running download. | | `reason` | `status` | Why the download failed. | | `preview` | `button` | The Preview button of a Prism result. | #### Accessibility {#download-card-a11y} - Role: `listitem` - Name: The result's title and artist (a pack: its name). - Focus: The list item is a focus target by program (the result list's arrows land on it); the buttons inside are in the tab order. | Keyboard | Effect | | --- | --- | | Enter | On the card: does what its main control does (the download button; a pack: opens or closes it). | | Tab | Reaches the card's buttons: the pack's main control, the action, the extra buttons and the preview. | #### Musts {#download-card-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `download-button` | `download` exists with role `button`, reachable by keyboard | `idle` | An idle result with something to download has a real download button, reachable by the keyboard. | | `download-click` | click on `download` calls `download.start()` | `idle` | Pressing the download button starts the download. | | `download-enter` | Enter on `download` calls `download.start()` | `idle` | Enter on the download button starts the download. | | `no-download-when-running` | `download` is not drawn | `queued`, `active`, `failed`, `installed`, `locked`, `unavailable` | A result that is queued, running, failed, installed, locked or without a source offers no download button. | | `retry-click` | click on `retry` calls `download.retry(jobId)` | `failed` | A failed download can be started again. | | `retry-enter` | Enter on `retry` calls `download.retry(jobId)` | `failed` | Enter on Retry starts the failed download again. | | `lock-button` | `lock` exists with role `button`, reachable by keyboard | `locked` | A locked source offers a real lock button that opens the settings, reachable by the keyboard. | | `installed-mark` | `installed` exists with role `img`, not a tab stop | `installed` | An installed result shows its check mark. | | `queued-mark` | `queued` exists with role `img`, not a tab stop | `queued` | A queued result shows its clock. | | `progress-shown` | `progress` shows `percent` | `active` | A running download shows its percentage. | ### `leaderboard.card` — Leaderboard card {#leaderboard-card} One score of the chart's leaderboard: rank, player, the rate it was played at, accuracy, the tiers and the combo, with the buttons beside it (ghost, share, watch, report). A list card sits in a list item the screen provides; the player's own play is drawn alone under the list. Not contracted yet and mounted as they are: TierCounts, PauseChip and the tooltip action. - Template: `components['leaderboard.card']` - Typed context: `ThemeContext<'leaderboard.card'>` - Default renderer: `LeaderboardCard` #### Face {#leaderboard-card-face} This contract is a **face**: the host draws and owns the card's own root (its button or plate, keyboard, menus, tooltips, actions and accessible name); a template draws what is **inside** it from the input, and uses `slots` for the host's own widgets. A face has no `button`, `toggle`, `dropdown`, no `slot` of another contract, calls no output, and none is required of it. #### Input {#leaderboard-card-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "local" | "localGhost" | "online" | "onlineGhost" | "onlineLoading" | "onlineFailed" | "onlineStatic" | "own" rank number podium? "gold" | "silver" | "bronze" player object name? string label string badges object received boolean mirror boolean osuImport boolean unranked boolean rate object value number text string mods? string pauses? ref @pvng/library:PauseCounts combo number misses? number tiers[]? object name string color string gradient[]? string symbol? ref @pvng/desktop:JudgementSymbol count number accuracy object value number text string performance? object text string unavailable boolean nonstandard boolean date object ms number (ms) iso string text string report? object scoreId number player string label string state = local: replayId string state = localGhost: replayId string ghost object id string chosen boolean disabled? boolean title string state = online: replayId number watchLabel string state = onlineGhost: replayId number watchLabel string ghost object id string chosen boolean disabled? boolean title string state = onlineLoading: replayId number watchLabel string ghost? object id string chosen boolean disabled? boolean title string state = onlineFailed: replayId number watchLabel string ghost? object id string chosen boolean disabled? boolean title string state = onlineStatic: {} state = own: {} ``` #### States {#leaderboard-card-states} | State | Meaning | | --- | --- | | `local` | A play of this machine, a button that opens its replay, with a share button; no ghost button (the Ghost modifier is not published). | | `localGhost` | A play of this machine with a ghost button beside the share button. | | `online` | A play of the online board with a replay: a button that opens it, and a watch button. | | `onlineGhost` | A play of the online board with a replay, with a ghost button before the watch button. | | `onlineLoading` | A play of the online board whose replay is downloading: a wait mark replaces the watch button (the ghost button, when offered, stays). | | `onlineFailed` | A play of the online board whose replay could not be downloaded: a retry button replaces the watch button (the ghost button, when offered, stays). | | `onlineStatic` | A play of the online board with no replay: not a button, nothing beside it. | | `own` | The player's own online play, pinned under the list: not a button, nothing beside it. | #### Outputs {#leaderboard-card-outputs} | Output | Arguments | Description | | --- | --- | --- | | `replay.open` **(required)** | `replayId: string` | Opens the replay of a local play. | | `replay.watch` **(required)** | `replayId: number` | Opens the replay of an online play (the host downloads it first when it is not on disk). | | `replay.retry` | `replayId: number` | Asks again for the replay of an online play whose download failed. | | `replay.share` | `replayId: string` | Shares the replay of a local play. | | `ghost.pick` | `ghostId: string, chosen: boolean` | Picks the play as the ghost of the next one, or clears the choice when it is the ghost already. Picking a local play switches the rate and the chart modifiers to the play's; an online play first needs its replay, which is downloaded. | | `play.report` | `scoreId: number, player: string` | Opens the report dialog for a play of the online board: the player tells the staff why it breaks the ranked rules. Nothing changes by itself and the reported player is never told. | #### Slots {#leaderboard-card-slots} | Slot | Description | | --- | --- | | `tiers` | The count of every tier of the judgement (the game's own widget; nothing when the counts do not name the tiers). | | `pauses` | The pauses of the play (the game's own chip, with its tooltip; nothing when none). | #### Parts {#leaderboard-card-parts} | Part | Role | Description | | --- | --- | --- | | `open` | `button` | The card itself, when the play has a replay to open (a local play, or an online play that has one). | | `rank` | `text` | The rank. | | `name` | `text` | The player's name, or the unknown player text. | | `rate` | `text` | The playback rate the play was made at. | | `mods` | `text` | The chart modifiers of the play (a local play that recorded some). | | `combo` | `text` | The best combo. | | `misses` | `text` | The notes missed, when the card has no tier counts. | | `accuracy` | `text` | The accuracy. | | `performance` | `text` | The performance value, or why there is none. | | `date` | `time` | When the play was made. | | `ghost` | `button` | The ghost toggle: pressed when the play is the ghost. | | `share` | `button` | Shares the replay. | | `watch` | `button` | Opens the replay of an online play. | | `retry` | `button` | Asks again for a replay that could not be downloaded. | | `loading` | `img` | The replay is downloading. | | `report` | `button` | Reports a play of the online board to the staff (another player's play, signed in and online). | #### Accessibility {#leaderboard-card-a11y} - Role: `none` - Name: The root has no role of its own (`display: contents`). The card is a button named by its content (a local play) or "Watch the replay of <player>" (an online play); the buttons beside it are named by their own labels. - Focus: The card, then the buttons beside it in reading order: ghost, then share (local) or watch, wait or retry (online), then report (another player's online play). The ghost button is a toggle (`aria-pressed`) that stays reachable when the play cannot be a ghost (`aria-disabled`, the reason in its tooltip). | Keyboard | Effect | | --- | --- | | Enter / Space | On the card: opens the replay. On a button beside it: its action (a ghost toggle, share, watch, retry, report). | #### Musts {#leaderboard-card-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `open-is-button` | `open` exists with role `button`, reachable by keyboard | `local`, `localGhost`, `online`, `onlineGhost`, `onlineLoading`, `onlineFailed` | A play with a replay is a real button, reachable by the keyboard. | | `no-open-without-replay` | `open` is not drawn | `onlineStatic`, `own` | A card with no replay to open is not a button. | | `open-local-click` | click on `open` calls `replay.open(replayId)` | `local`, `localGhost` | Clicking a local play opens its replay. | | `open-local-enter` | Enter on `open` calls `replay.open(replayId)` | `local`, `localGhost` | Enter on a local play opens its replay. | | `open-online-click` | click on `open` calls `replay.watch(replayId)` | `online`, `onlineGhost`, `onlineLoading`, `onlineFailed` | Clicking an online play with a replay opens it. | | `open-online-enter` | Enter on `open` calls `replay.watch(replayId)` | `online`, `onlineGhost`, `onlineLoading`, `onlineFailed` | Enter on an online play with a replay opens it. | | `rate-shown` | `rate` shows `rate.text` | all | The rate the play was made at is shown. | | `name-shown` | `name` shows `player.label` | all | The player's name is shown; a missing one reads as the unknown player, never as the local player. | | `accuracy-shown` | `accuracy` shows `accuracy.text` | all | The accuracy is shown. | | `date-shown` | `date` shows `date.text` | all | The date of the play is shown. | | `no-misses-with-tiers` | `misses` is not drawn | `local`, `localGhost` | A local card counts the misses once, in the Miss tier: there is no separate total. | | `ghost-toggle` | `ghost` exists with role `button`, reachable by keyboard | `localGhost`, `onlineGhost` | The ghost button is a real button, reachable by the keyboard. | | `ghost-click` | click on `ghost` calls `ghost.pick(ghost.id, ghost.chosen)` | `localGhost`, `onlineGhost` | Clicking the ghost button picks the play as the ghost. | | `ghost-enter` | Enter on `ghost` calls `ghost.pick(ghost.id, ghost.chosen)` | `localGhost`, `onlineGhost` | Enter on the ghost button picks the play as the ghost. | | `no-ghost-unoffered` | `ghost` is not drawn | `local`, `online`, `onlineStatic`, `own` | Without the Ghost modifier there is no ghost button. | | `share-click` | click on `share` calls `replay.share(replayId)` | `local`, `localGhost` | Share asks to share the replay. | | `share-enter` | Enter on `share` calls `replay.share(replayId)` | `local`, `localGhost` | Enter on Share asks to share the replay. | | `no-share-online` | `share` is not drawn | `online`, `onlineGhost`, `onlineLoading`, `onlineFailed`, `onlineStatic`, `own` | An online play is not shared from the board. | | `watch-click` | click on `watch` calls `replay.watch(replayId)` | `online`, `onlineGhost` | Watch opens the replay of an online play. | | `watch-enter` | Enter on `watch` calls `replay.watch(replayId)` | `online`, `onlineGhost` | Enter on Watch opens the replay of an online play. | | `wait-while-loading` | `loading` exists with role `img`, not a tab stop | `onlineLoading` | A replay that is downloading shows a wait mark, not a watch button. | | `no-watch-while-loading` | `watch` is not drawn | `onlineLoading`, `onlineFailed`, `onlineStatic`, `own`, `local`, `localGhost` | A replay that is downloading cannot be watched from the beside button. | | `retry-click` | click on `retry` calls `replay.retry(replayId)` | `onlineFailed` | A failed download can be asked again. | | `retry-enter` | Enter on `retry` calls `replay.retry(replayId)` | `onlineFailed` | Enter on Retry asks again for the replay. | | `no-report-own-or-local` | `report` is not drawn | `local`, `localGhost`, `own` | Only a play of the online board is reported, never the player's own or one of this machine. | ### `library.chartRow` — Difficulty row {#library-chartrow} One difficulty of the open set in the song list (or one map of an open playlist): its layout, name, the marks it carries (missing file, silent, note, goals), why it is listed, its main pattern, its rating and that rating as ten stars. The list owns the row it sits in and the context menus; this contract only draws the button and asks. `MissingMark` and `GoalMark` are mounted as they are (not contracted yet). - Template: `components['library.chartRow']` - Typed context: `ThemeContext<'library.chartRow'>` - Default renderer: `LibraryChartRow` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Face {#library-chartrow-face} This contract is a **face**: the host draws and owns the card's own root (its button or plate, keyboard, menus, tooltips, actions and accessible name); a template draws what is **inside** it from the input, and uses `slots` for the host's own widgets. A face has no `button`, `toggle`, `dropdown`, no `slot` of another contract, calls no output, and none is required of it. #### Input {#library-chartrow-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "normal" | "selected" | "playlist" position number difficulty number path string variant number selected boolean themed boolean name string keysText string color string missing? "audio" | "background" | "both" noAudio boolean noted boolean goal? "open" | "reached" rate? object text string title string similar? object text string title string rateOf? object label string help string pattern? object short string color string names string rating string ratingUnit string stars[] object lit boolean plays? object text string title string state = normal: {} state = selected: {} state = playlist: {} ``` #### States {#library-chartrow-states} | State | Meaning | | --- | --- | | `normal` | A difficulty of the open set that is not the selected one. | | `selected` | The selected difficulty (`aria-current`). | | `playlist` | A map of an open playlist: a click selects it, and the selection column then plays it alone (there is no context menu); `selected` says whether it is the focused one. | #### Outputs {#library-chartrow-outputs} | Output | Arguments | Description | | --- | --- | --- | | `activate` **(required)** | `position: number, difficulty: number, alreadySelected: boolean, dragDistance: number (px)` | A click or Enter on the row. The first click selects the difficulty; a click on the already-selected one confirms it (plays it, or picks it as the lobby map) when the player's "click the selected map to play" setting is on, nothing is loading and the pointer did not travel (a scroll or a drag never launches). The renderer only reports how far the pointer travelled between press and release (0 for the keyboard). | | `pickPlaylistMap` **(required)** | `path: string, variant: number` | Selects the map of an open playlist, by its file and difficulty index. | | `menu.open` | `x: number (px), y: number (px)` | The context menu (right click, Menu key, Shift+F10) at a point of the screen; the list owns it and gives focus back to the row when it closes. A playlist's map has none. | #### Slots {#library-chartrow-slots} | Slot | Description | | --- | --- | | `goal` | The goal mark of the chart (drawn when a goal is open or reached; nothing otherwise): the game's own widget, with its tooltip. | | `missing` | The warning mark of a chart that lacks its audio or its picture (nothing when nothing is missing): the game's own widget, with its tooltip. | #### Parts {#library-chartrow-parts} | Part | Role | Description | | --- | --- | --- | | `keys` | `text` | The layout. | | `name` | `text` | The difficulty name, then its marks (missing file, silent, note, goals). | | `rate` | `text` | The rate a playlist plays the map at. | | `similar` | `text` | Why a "Similar maps" list shows the chart. | | `rateOf` | `text` | The proven rate copy label. | | `pattern` | `text` | The main pattern capsule. | | `rating` | `text` | The rating figure and its unit. | | `plays` | `text` | The own plays count. | #### Accessibility {#library-chartrow-a11y} - Role: `button` - Name: The row's own text: layout, name (with the marks' words), the rate, the why, the pattern, the rating and the plays. - Focus: One tab stop per row; the selected row carries `aria-current="true"`. | Keyboard | Effect | | --- | --- | | Enter / Space | Selects the difficulty; on the selected one it confirms it when the setting is on. | | Menu / Shift+F10 | Opens the context menu. | #### Musts {#library-chartrow-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `button` | `root` exists with role `button`, reachable by keyboard | all | A difficulty row is a button the keyboard reaches. | | `activate-click` | click on `root` calls `activate(position, difficulty, selected, 0±1)` | `normal`, `selected` | A click selects (or confirms) the difficulty, naming its indexes. | | `activate-enter` | Enter on `root` calls `activate(position, difficulty, selected, 0±1)` | `normal`, `selected` | Enter selects (or confirms) the difficulty, naming its indexes. | | `pick-playlist-map` | click on `root` calls `pickPlaylistMap(path, variant)` | `playlist` | A click on a playlist's map picks it. | | `name` | `name` shows `name` | all | The difficulty name is shown. | | `keys` | `keys` shows `keysText` | all | The layout is shown. | | `rating` | `rating` shows `rating` | all | The rating is shown. | ### `library.footer` — Footer of the selection {#library-footer} The rating and judgement dropdowns and the main button under the selected map (Play, Train or Choose) or the selected playlist (Play as playlist, Marathon). The reason a button is off is always readable, and the dropdowns stay usable. Not contracted yet and still bound to their stores inside the default renderer: `MenuDropdown`, `JudgementQuick` (the parameters and the tier windows of the quick judgement panel), `UnrankedMark`. - Template: `components['library.footer']` - Typed context: `ThemeContext<'library.footer'>` - Default renderer: `LibraryFooter` #### Input {#library-footer-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "mapReady" | "mapBlocked" | "mapRefused" | "mapNoPlay" | "playlistReady" | "playlistBlocked" rating object value string options[] object value string label string group string detail string judgement object value string label string ariaLabel string options[] object value string label string group string detail string refusal? string state = mapReady: play object label string intent "play" | "train" | "pick-lobby-map" unrankedSlot boolean unranked boolean state = mapBlocked: play object label string intent "play" | "train" | "pick-lobby-map" unrankedSlot boolean unranked boolean reason object kind "lobby" | "loading" | "section" | "staircase" | "busy" text string state = mapRefused: play object label string intent "play" | "train" | "pick-lobby-map" unrankedSlot boolean unranked boolean state = mapNoPlay: {} state = playlistReady: playlistId number state = playlistBlocked: playlistId number reason object kind "empty" | "running" text string ``` #### States {#library-footer-states} | State | Meaning | | --- | --- | | `mapReady` | A map is selected and its main button can be pressed. | | `mapBlocked` | The main button of the map is off for a reason that is not the judgement: the lobby plays the map, the map is loading, no training section is chosen, the staircase options are refused, or the game is busy. `reason` says it. | | `mapRefused` | The main button of the map is off because no judgement can be used: `refusal` is shown and is also what describes the button. | | `mapNoPlay` | A map shown without its main button. The game does not build it any more: a map looked at from a playlist has Play, like any map. | | `playlistReady` | A playlist is selected and can start. | | `playlistBlocked` | A playlist is selected and cannot start (it has no map, or a run of it is going). `reason` says it. | #### Outputs {#library-footer-outputs} | Output | Arguments | Description | | --- | --- | --- | | `rating.pick` | `value: string` | Chooses the rating the game reads charts with. | | `judgement.pick` | `value: string` | Chooses the judgement of the next plays: a set (`set:<key>`) or a custom preset (`custom:<index>`). | | `judgement.settings` | — | Opens the Judgement page of the Settings. | | `confirm` **(required)** | — | The main button of a map: plays it, trains the section (Training tab) or picks it as the lobby's map, as `chart.confirm` decides (it is also what Enter does on the page). | | `playlist.start` | `playlistId: number` | Plays the playlist map after map. | | `marathon.start` | `playlistId: number` | Plays the playlist as one marathon map. | #### Parts {#library-footer-parts} | Part | Role | Description | | --- | --- | --- | | `rating` | `button` | The rating dropdown's trigger. | | `judgement` | `button` | The judgement dropdown's trigger. | | `refusal` | `alert` | The line that says no judgement can be used. | | `play` | `button` | The main button of a map. | | `unranked` | `none` | The room of the "unranked" mark (empty when the chart is ranked or unknown). | | `reason` | `none` | The visually hidden line that says why a button is off; the button is described by it. | | `start` | `button` | Plays the selected playlist map after map. | | `marathon` | `button` | Plays the selected playlist as one marathon. | #### Accessibility {#library-footer-a11y} - Role: `none` - Name: The strip has no role of its own: the dropdowns and buttons are named by their labels, and a button that is off is described by the reason (the hidden line, or the visible refusal). - Focus: The dropdowns and the buttons that are on; a button that is off is skipped, and the reason stays readable. | Keyboard | Effect | | --- | --- | | Tab | Rating, Judgement, then the main button (for a playlist: Play as playlist, then Marathon). | | Enter / Space | On a button: presses it. On the page: Enter does what the main button does (`chart.confirm`). | | ArrowUp / ArrowDown | On a dropdown: opens its list. | #### Musts {#library-footer-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `rating-picker` | `rating` exists with role `button`, reachable by keyboard | all | The rating can be chosen from the keyboard. | | `judgement-picker` | `judgement` exists with role `button`, reachable by keyboard | all | The judgement can be chosen from the keyboard. | | `rating-stays-on` | `rating` can be used | all | The rating stays usable whatever the state of Play. | | `judgement-stays-on` | `judgement` can be used | all | The judgement stays usable whatever the state of Play, so a refusal can be fixed. | | `play-is-a-button` | `play` exists with role `button`, reachable by keyboard | `mapReady` | Play is a real button, reachable by keyboard. | | `play-click` | click on `play` calls `confirm()` | `mapReady` | Clicking Play confirms the chart. | | `play-enter` | Enter on `play` calls `confirm()` | `mapReady` | Enter on Play confirms the chart. | | `play-label` | `play` shows `play.label` | `mapReady`, `mapBlocked`, `mapRefused` | The button says what it does. | | `play-off` | `play` cannot be pressed | `mapBlocked`, `mapRefused` | Play cannot be pressed while it is off. | | `play-reason` | `play` shows `reason.text` | `mapBlocked` | The reason Play is off is readable (it describes the button). | | `play-refusal` | `play` shows `refusal` | `mapRefused` | When no judgement can be used, the refusal describes Play. | | `refusal-alert` | `refusal` exists with role `alert`, not a tab stop | `mapRefused` | The refusal is announced as an alert. | | `no-play-in-playlist` | `play` is not drawn | `mapNoPlay` | A map shown without its main button draws none. | | `marathon-is-a-button` | `marathon` exists with role `button`, reachable by keyboard | `playlistReady` | Marathon is a real button, reachable by keyboard. | | `marathon-click` | click on `marathon` calls `marathon.start(playlistId)` | `playlistReady` | Clicking Marathon plays the playlist as one map. | | `playlist-start-click` | click on `start` calls `playlist.start(playlistId)` | `playlistReady` | Clicking Play as playlist plays it map after map. | | `playlist-off` | `marathon` cannot be pressed | `playlistBlocked` | Neither button of a playlist that cannot start can be pressed. | | `playlist-start-off` | `start` cannot be pressed | `playlistBlocked` | Play as playlist cannot be pressed when the playlist cannot start. | | `playlist-reason` | `marathon` shows `reason.text` | `playlistBlocked` | The reason a playlist cannot start is readable (it describes the buttons). | | `playlist-start-reason` | `start` shows `reason.text` | `playlistBlocked` | The reason also describes Play as playlist. | ### `library.search` — Song search bar {#library-search} The field where the list is searched, with what narrows it (filter chips, grouping, sort) and the popover of recent searches. The same bar serves the playlists list (`mode` playlists), where only the text and the sort apply (the host searches the playlists' names and maps). Not contracted yet and still bound to their own stores inside the default renderer: `MenuDropdown` (the sort and grouping choices), `HelpTip`; the "Filter" button and its window (`FilterWindow`) are the host's content of the `filterWindow` slot. The popover of recent searches is a part of the renderer: it only reads the `history` of the input (which entries are listed, typed text narrowing them and the open state are its own view state). - Template: `components['library.search']` - Typed context: `ThemeContext<'library.search'>` - Default renderer: `LibrarySearch` #### Input {#library-search-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "ready" | "filtered" | "blocked" | "invalid" mode "maps" | "playlists" query string sort object value string label string options[] object value string label string group string descending boolean active boolean caption string directionLabel string group? object value string label string options[] object value string label string group string grouped boolean allFolded boolean canFoldAll boolean caption string filters[] object key string label string value string tip string removeLabel string unavailable boolean fieldKeys[] string history? object enabled boolean entries[] object id string query string label string pinned boolean reviewing boolean syntax object pending? string unrecognised? string state = ready: {} state = filtered: {} state = blocked: status string error? string state = invalid: error string ``` #### States {#library-search-states} | State | Meaning | | --- | --- | | `ready` | The bar works and no filter chip is active. | | `filtered` | The bar works and at least one filter chip narrows the list. | | `blocked` | A filter chip cannot apply now (its provider is gone); `status` says why. `error` is set when the filters window also refused something. | | `invalid` | The last filter could not be applied; `error` says what is wrong. | #### Outputs {#library-search-outputs} | Output | Arguments | Description | | --- | --- | --- | | `query.set` | `text: string` | The text changed (every keystroke), or was emptied. In `playlists` mode it is the playlists' own filter. | | `query.commit` | `text: string` | The field lost the focus, or Enter: the composed search is kept in the history and the closed criteria become chips. Maps only. | | `sort.set` | `key: string` | Another sort key (the playlists' own sort in `playlists` mode). | | `sort.toggleDirection` | — | Ascending or descending. | | `group.set` | `key: string` | Another grouping. | | `group.collapseAll` | — | Folds every group. | | `group.expandAll` | — | Opens every group. | | `reshuffle` | — | Draws the random order again (sort "random"). | | `filter.edit` | `key: string` | Opens the filters window on a criterion (the chip was clicked). The host gives it: the window is its own. | | `filter.remove` | `key: string` | Removes a filter chip. | | `history.restore` | `id: string` | Applies a recent search again. | | `history.pin` | `id: string` | Pins or unpins a recent search. | | `history.remove` | `id: string` | Forgets one recent search. | | `history.clear` | — | Forgets every recent search that is not pinned. | | `history.pause` | — | Stops recording the searches. | | `history.resume` | — | Records the searches again. | | `duplicates.review` | — | Starts or stops the review of the duplicates. | | `duplicates.reveal` | — | Shows the duplicate of the selected map in the list. | #### Slots {#library-search-slots} | Slot | Description | | --- | --- | | `filterWindow` | The "Filter" button and its window (`FilterWindow`, not contracted yet); the host sets the window's criterion when `filter.edit` is asked. Maps only. | #### Parts {#library-search-parts} | Part | Role | Description | | --- | --- | --- | | `bar` | `none` | The plate under the field and the tools (a theme that draws its own field clears it: `--plate: transparent`). | | `field` | `combobox` | The search text; ArrowDown opens the recent searches. | | `clear` | `button` | Empties the text (shown while there is some). | | `history` | `region` | The recent searches popover (open on demand). | | `sort` | `button` | The sort choice. | | `direction` | `button` | Ascending or descending. | | `group` | `button` | The grouping choice (maps only). | | `filters` | `group` | The active filter chips (present while there are some). | | `status` | `status` | The line that says a filter cannot apply now. | | `syntax` | `status` | The line that previews a criterion being typed, or says a word shaped like one is not recognised. | | `error` | `alert` | The line that says the last filter was refused. | #### Host classes {#library-search-classes} | Class | Description | | --- | --- | | `library-search` | The bar's root (placed with its margins by the game). | | `search-bar` | The plate under the field and the tools. | | `filter-chips` | The row of filter chips. | | `bar-menu` | A group of the tools row (grouping, sort, duplicates, filter). | | `pv-plate` | A plate of the design system. | #### Accessibility {#library-search-a11y} - Role: `none` - Name: The bar has no role of its own: the field is a combobox named after the list it searches (the maps or the playlists), the chips and the choices by their labels. - Focus: The field takes the focus when the screen opens; the chips, then the choices follow in reading order. | Keyboard | Effect | | --- | --- | | ArrowDown | Opens the recent searches, then walks them. | | Enter | Keeps the typed criterion as a chip, or applies the recent search under the focus. | | Escape | Closes the recent searches, then empties the text. | | Backspace | In an empty field, removes the last chip. | #### Musts {#library-search-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `field` | `field` exists with role `combobox`, reachable by keyboard | all | The list can always be searched by text. | | `sort` | `sort` exists with role `button`, reachable by keyboard | all | The sort can be changed. | | `direction` | click on `direction` calls `sort.toggleDirection()` | all | The sort direction can be flipped. | | `filters-listed` | `filters` exists with role `group`, not a tab stop | `filtered`, `blocked` | The active filters stay listed in the bar (each chip removable through `filter.remove`). | | `filters-absent` | `filters` is not drawn | `ready` | Without a filter there is no chip row. | | `status-shown` | `status` shows `status` | `blocked` | A filter that cannot apply is said in words. | | `error-alert` | `error` exists with role `alert`, not a tab stop | `invalid` | A refused filter is announced as an alert. | | `error-shown` | `error` shows `error` | `invalid` | The refusal says what is wrong. | ### `library.setCard` — Set card {#library-setcard} One beatmapset (or playlist) of the song list: artwork, title, artist, a line of facts, the layouts, the rating and a strip of difficulty chips. The list owns the row it sits in, the "+N" popover and the context menus; this contract only draws the card and asks. `MissingMark` and `GoalMark` are mounted as they are (not contracted yet). - Template: `components['library.setCard']` - Typed context: `ThemeContext<'library.setCard'>` - Default renderer: `LibrarySetCard` #### Face {#library-setcard-face} This contract is a **face**: the host draws and owns the card's own root (its button or plate, keyboard, menus, tooltips, actions and accessible name); a template draws what is **inside** it from the input, and uses `slots` for the host's own widgets. A face has no `button`, `toggle`, `dropdown`, no `slot` of another contract, calls no output, and none is required of it. #### Input {#library-setcard-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "collapsed" | "selected" | "expanded" | "playlist" | "loading" state = collapsed: position number id string selected boolean expanded boolean themed boolean title string artist string creator? object name string text string color string thumbnail string mosaic[]? string similar? object text string title string newText? string countText string missing? "audio" | "background" | "both" noted boolean plays? object text string title string keysText string goal? "open" | "reached" advice? object kind "comfort" | "push" | "stretch" text string rating object text string range string unit string strip object tier "dot" | "rating" | "full" | "pattern" chipWidth number (px) gap number (px) maxWidth number (px) minWidth number (px) chips[] object key number color string keysText string short string pattern? object short string color string more? object count number label string state = selected: position number id string selected boolean expanded boolean themed boolean title string artist string creator? object name string text string color string thumbnail string mosaic[]? string similar? object text string title string newText? string countText string missing? "audio" | "background" | "both" noted boolean plays? object text string title string keysText string goal? "open" | "reached" advice? object kind "comfort" | "push" | "stretch" text string rating object text string range string unit string strip object tier "dot" | "rating" | "full" | "pattern" chipWidth number (px) gap number (px) maxWidth number (px) minWidth number (px) chips[] object key number color string keysText string short string pattern? object short string color string more? object count number label string state = expanded: position number id string selected boolean expanded boolean themed boolean title string artist string creator? object name string text string color string thumbnail string mosaic[]? string similar? object text string title string newText? string countText string missing? "audio" | "background" | "both" noted boolean plays? object text string title string keysText string goal? "open" | "reached" advice? object kind "comfort" | "push" | "stretch" text string rating object text string range string unit string strip object tier "dot" | "rating" | "full" | "pattern" chipWidth number (px) gap number (px) maxWidth number (px) minWidth number (px) chips[] object key number color string keysText string short string pattern? object short string color string more? object count number label string state = playlist: position number id string selected boolean expanded boolean themed boolean title string artist string creator? object name string text string color string thumbnail string mosaic[]? string similar? object text string title string newText? string countText string missing? "audio" | "background" | "both" noted boolean plays? object text string title string keysText string goal? "open" | "reached" advice? object kind "comfort" | "push" | "stretch" text string rating object text string range string unit string strip object tier "dot" | "rating" | "full" | "pattern" chipWidth number (px) gap number (px) maxWidth number (px) minWidth number (px) chips[] object key number color string keysText string short string pattern? object short string color string more? object count number label string playlistId number state = loading: {} ``` #### States {#library-setcard-states} | State | Meaning | | --- | --- | | `collapsed` | A set of the list, closed and not holding the selected chart. | | `selected` | A closed set that holds the selected chart. | | `expanded` | The open set (its difficulties are listed below it); it may hold the selected chart too (`selected`). | | `playlist` | A playlist card: its maps' pictures as a mosaic, the creator is plain text, a click selects the playlist (`expanded`/`selected`: it is the open one). | | `loading` | The placeholder of a row whose page has not arrived: an empty plate, hidden from assistive technology and not interactive. | #### Outputs {#library-setcard-outputs} | Output | Arguments | Description | | --- | --- | --- | | `toggle` **(required)** | `position: number` | Opens the set (and selects its first or remembered difficulty), or closes it when it is the open one. | | `selectPlaylist` **(required)** | `playlistId: number` | Selects the playlist (a playlist card never opens a set). | | `filter.name` | `key: "host/artist" \| "host/creator", name: string` | Ctrl/Cmd + click on the artist or the mapper filters the list on that name; it never also toggles the card. | | `menu.open` | `x: number (px), y: number (px)` | The context menu (right click, Menu key, Shift+F10) at a point of the screen; the list owns it and gives focus back to the card when it closes. | | `more.show` | `id: string, x: number (px), y: number (px), by: "pointer" \| "focus"` | The popover with the full list of the set's difficulties, above a point of the screen: by pointer (over the "+N" badge) or by focus (a keyboard focus on the card). | | `more.hide` | — | The pointer left the badge or the card lost its focus: the popover goes away after a short delay. | #### Slots {#library-setcard-slots} | Slot | Description | | --- | --- | | `goal` | The goal mark of the set (drawn when some goal is open or reached; nothing otherwise), or in Maps to play the chart's kind badge (comfort, push, stretch, each its colour): the game's own widgets, with their tooltip. | | `missing` | The warning mark of a set that lacks audio or a background (nothing when nothing is missing): the game's own widget, with its tooltip. | #### Parts {#library-setcard-parts} | Part | Role | Description | | --- | --- | --- | | `art` | `presentation` | The set's picture, or the playlist's mosaic, behind the text. | | `title` | `text` | The song title. | | `artist` | `text` | The artist (a filter on Ctrl+click, except on a playlist card). | | `meta` | `text` | The line of facts: why it is listed, NEW, the mapper, the difficulty count, the marks, the plays. | | `creator` | `text` | The mapper's name inside the line of facts (a filter on Ctrl+click, except on a playlist card). | | `keys` | `text` | The layouts, after the goal mark when there is one. | | `rating` | `text` | The rating range. | | `strip` | `presentation` | The chips of the difficulties (hidden from assistive technology: the count is in the meta line). | | `more` | `img` | The "+N" badge of the difficulties the strip has no room for; hovering it opens the full list. | #### Accessibility {#library-setcard-a11y} - Role: `button` - Name: The card's own text: title, artist, the line of facts, the layouts and the rating (the picture and the chips are decoration; the badge is an image named "+N difficulties"). - Focus: One tab stop; the card has `aria-expanded`. A keyboard focus (`:focus-visible`) on a card with a badge opens the popover with the full list of difficulties. | Keyboard | Effect | | --- | --- | | Enter / Space | Opens or closes the set (selects the playlist on a playlist card). | | Menu / Shift+F10 | Opens the context menu. | #### Musts {#library-setcard-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `button` | `root` exists with role `button`, reachable by keyboard | `collapsed`, `selected`, `expanded`, `playlist` | A set card is a button the keyboard reaches. | | `toggle-click` | click on `root` calls `toggle(position)` | `collapsed`, `selected`, `expanded` | A click opens or closes the set, naming its position. | | `toggle-enter` | Enter on `root` calls `toggle(position)` | `collapsed`, `selected`, `expanded` | Enter opens or closes the set, naming its position. | | `select-playlist` | click on `root` calls `selectPlaylist(playlistId)` | `playlist` | A click on a playlist card selects the playlist. | | `select-playlist-enter` | Enter on `root` calls `selectPlaylist(playlistId)` | `playlist` | Enter on a playlist card selects the playlist. | | `title` | `title` shows `title` | `collapsed`, `selected`, `expanded`, `playlist` | The title is shown. | | `artist` | `artist` shows `artist` | `collapsed`, `selected`, `expanded`, `playlist` | The artist is shown. | | `count` | `meta` shows `countText` | `collapsed`, `selected`, `expanded`, `playlist` | The difficulty count is shown. | | `keys` | `keys` shows `keysText` | `collapsed`, `selected`, `expanded`, `playlist` | The layouts are shown. | | `rating` | `rating` shows `rating.range` | `collapsed`, `selected`, `expanded`, `playlist` | The rating range is shown. | | `loading-empty` | `title` is not drawn | `loading` | The loading placeholder shows no text. | | `loading-no-badge` | `more` is not drawn | `loading` | The loading placeholder has no "+N" badge to hover. | ### `library.toolbar` — Song list toolbar {#library-toolbar} What the player does around the list: switch between the maps, the playlists and the maps to play, draw a random map, open the rare actions (folders, playlists), reach the online side and the map visualizer. Slant and Cabinet draw the view switch and one "…" menu for the rare actions (the screen opens it: `menu.open`); Classic draws a heading with the view's count, the rare actions as buttons and a Playlists toggle. Not contracted yet and still bound to their own stores inside the default renderer: the `themed` flag that tells the two bars apart, `Segmented`, `IconButton` and `Button` of the design system; `OnlineChip` and `ChatButton` are the host's content of the `online` slot. - Template: `components['library.toolbar']` - Typed context: `ThemeContext<'library.toolbar'>` - Default renderer: `LibraryToolbar` #### Input {#library-toolbar-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "maps" | "mapsBusy" | "mapsEmpty" | "playlists" | "mapsToPlay" views[] object value "maps" | "playlists" | "mapsToPlay" label string count number countText string exact? string disabled boolean visualizer object open boolean available boolean label string iconOnly boolean menu[] object id string label string unavailable? string menuOpen boolean state = maps: {} state = mapsBusy: {} state = mapsEmpty: locked boolean state = playlists: {} state = mapsToPlay: {} ``` #### States {#library-toolbar-states} | State | Meaning | | --- | --- | | `maps` | The maps view of a library that holds maps: Random works. | | `mapsBusy` | The maps view while the library is busy (scanning) or the visualizer covers the list: Random is off. | | `mapsEmpty` | The library holds no map: Random is off. | | `playlists` | The playlists view: no Random. | | `mapsToPlay` | The maps to play: the charts of the library to push next take the place of the maps list (no Random). | #### Outputs {#library-toolbar-outputs} | Output | Arguments | Description | | --- | --- | --- | | `view.set` **(required)** | `view: "maps" \| "playlists" \| "mapsToPlay"` | Shows the maps, the playlists or the maps to play. Opening the playlists hands the keyboard to their panel (arrows walk, Enter plays). | | `random` | — | Selects a random map. | | `demo` | — | Plays the built-in demo map. The default renderer has no button for it any more; a template may draw one. | | `visualize` | — | Opens or closes the map visualizer. | | `multiplayer` | — | Opens the multiplayer page. | | `menu.open` | `x: number (px), y: number (px)` | Opens the menu of the rare actions under the button; the point is where its top left corner goes. The screen gives it. | | `menu.run` | `id: string` | Runs one action of that menu (`add`, `refresh`, `new`, `import` or `paste`, the `id` of `menu`). | #### Slots {#library-toolbar-slots} | Slot | Description | | --- | --- | | `online` | The online status chip and the chat button (not contracted yet); the multiplayer button is the renderer's own, placed after them. | #### Parts {#library-toolbar-parts} | Part | Role | Description | | --- | --- | --- | | `views` | `radiogroup` | The maps / playlists / maps to play switch (Slant and Cabinet). | | `playlists` | `radio` | The playlists choice: a segment of the switch (Slant and Cabinet) or the toggle (Classic). | | `mapsToPlay` | `radio` | The maps to play choice: a segment of the switch (Slant and Cabinet) or a toggle (Classic). | | `random` | `button` | The random map. | | `menu` | `button` | The menu of the rare actions (Slant and Cabinet). | | `action` | `button` | One of the rare actions laid out as a button (Classic). | | `multiplayer` | `button` | The multiplayer page. | | `visualize` | `button` | The visualizer toggle (pressed while it is open). | #### Host classes {#library-toolbar-classes} | Class | Description | | --- | --- | | `library-toolbar` | The bar's root. | | `bar` | The bar of Slant and Cabinet (one text style, side groups). | | `bar-side` | One side of the bar: the view and its tools, or the online side and Visualize. | | `online` | The frame of the online side (status, chat, multiplayer). | | `viz` | The Visualize button (its word is always shown while the bar is wide enough). | | `viz-label` | The word of the Visualize button. | | `tb-label` | A button's word in Classic's bar (hidden when the bar is narrow). | | `active` | A pressed toggle of Classic's bar. | #### Accessibility {#library-toolbar-a11y} - Role: `none` - Name: The bar has no role of its own: the view switch is a radio group named after the list, the buttons by their labels. - Focus: Reading order; opening the playlists view hands the keyboard to the playlists panel. | Keyboard | Effect | | --- | --- | | Tab | Walks the view switch, the tools, then the online side and Visualize. | #### Musts {#library-toolbar-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `playlists-click` | click on `playlists` calls `view.set("playlists")` | `maps`, `mapsEmpty` | The playlists can be reached from the maps view. | | `maps-to-play-click` | click on `mapsToPlay` calls `view.set("mapsToPlay")` | `maps` | The maps to play can be reached from the maps view. | | `random-click` | click on `random` calls `random()` | `maps` | Random selects a random map. | | `random-off` | `random` cannot be pressed | `mapsBusy`, `mapsEmpty` | Random cannot be pressed while it cannot work. | | `no-random-in-playlists` | `random` is not drawn | `playlists`, `mapsToPlay` | Random is not offered over the playlists or the maps to play. | | `multiplayer-is-a-button` | `multiplayer` exists with role `button`, reachable by keyboard | all | The multiplayer page is one button away, by keyboard. | | `multiplayer-click` | click on `multiplayer` calls `multiplayer()` | all | Clicking it opens the multiplayer page. | | `visualize` | `visualize` exists with role `button`, not a tab stop | all | The visualizer has its button. | ### `lobby.draft` — Lobby draft {#lobby-draft} The pick & ban panel of a friendly lobby. The host sets the draft up (best of, bans per side, first side, pick rule, turn timer and the pool staged from the library), then the captains of the two sides ban and pick the maps in turn; the panel shows the pool (banned maps crossed out, picked and played maps marked with their side), whose turn it is with its countdown, the series score, the host's forfeit and abort, and the reason of the last refused action. A lobby whose server does not offer drafts shows nothing. - Template: `components['lobby.draft']` - Typed context: `ThemeContext<'lobby.draft'>` - Default renderer: `LobbyDraft` #### Input {#lobby-draft-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "setup" | "banning" | "picking" | "playing" | "finished" host boolean denial? "not_in_lobby" | "not_host" | "not_captain" | "not_your_turn" | "wrong_phase" | "bad_config" | "bad_sides" | "unknown_map" | "map_taken" | "map_reserved" | "not_members" | "started" | "draft_active" | "no_draft" | "feature_unavailable" | "unknown" state = setup: poolLimit number pool[] object slot string title string artist string art? string difficulty? string rateText string noteHash string playbackRate number judgement string candidate? object title string artist string rateText string inPool boolean sides? object a[] string b[] string state = banning: series object bestOf number a number b number sides object a object captain? string members[] string mine boolean b object captain? string members[] string mine boolean bansPerSide number pickRule "alternate" | "loser_picks" | "unknown" maps[] object slot string title string artist string art? string difficulty? string rateText string status "open" | "banned" | "picked" | "played" by? "a" | "b" winner? "a" | "b" game? number auto boolean current boolean tiebreaker boolean turn? object side "a" | "b" kind "ban" | "pick" mine boolean secondsLeft? number state = picking: series object bestOf number a number b number sides object a object captain? string members[] string mine boolean b object captain? string members[] string mine boolean bansPerSide number pickRule "alternate" | "loser_picks" | "unknown" maps[] object slot string title string artist string art? string difficulty? string rateText string status "open" | "banned" | "picked" | "played" by? "a" | "b" winner? "a" | "b" game? number auto boolean current boolean tiebreaker boolean turn? object side "a" | "b" kind "ban" | "pick" mine boolean secondsLeft? number state = playing: series object bestOf number a number b number sides object a object captain? string members[] string mine boolean b object captain? string members[] string mine boolean bansPerSide number pickRule "alternate" | "loser_picks" | "unknown" maps[] object slot string title string artist string art? string difficulty? string rateText string status "open" | "banned" | "picked" | "played" by? "a" | "b" winner? "a" | "b" game? number auto boolean current boolean tiebreaker boolean turn? object side "a" | "b" kind "ban" | "pick" mine boolean secondsLeft? number game object number number slot string title string state = finished: series object bestOf number a number b number sides object a object captain? string members[] string mine boolean b object captain? string members[] string mine boolean bansPerSide number pickRule "alternate" | "loser_picks" | "unknown" maps[] object slot string title string artist string art? string difficulty? string rateText string status "open" | "banned" | "picked" | "played" by? "a" | "b" winner? "a" | "b" game? number auto boolean current boolean tiebreaker boolean turn? object side "a" | "b" kind "ban" | "pick" mine boolean secondsLeft? number winner? "a" | "b" reason "won" | "forfeit" | "aborted" | "unknown" ``` #### States {#lobby-draft-states} | State | Meaning | | --- | --- | | `setup` | The host sets the draft up: a form (best of, bans per side, first side, pick rule, turn timer) and the staged pool, with what the host can add from the library. | | `banning` | Bans: the captain on turn bans a map with the button on its card; the others wait for theirs. | | `picking` | Picks: the captain on turn picks the map of the next game. | | `playing` | Playing: the series plays the picked map; the panel keeps the pool and the score. | | `finished` | Finished: the series is over, with its winner or why it ended. | #### Outputs {#lobby-draft-outputs} | Output | Arguments | Description | | --- | --- | --- | | `start` | `bestOf: number, bansPerSide: number, first: "a" \| "b", pickRule: "alternate" \| "loser_picks", turnSecs: number` | Starts the draft from the setup form: the best of, the bans per side, the first side, the pick rule and the turn timer in seconds (0 for none). The sides are the lobby's players. | | `ban` | `slot: string` | Bans a map of the pool, by its slot (the captain on turn). | | `pick` | `slot: string` | Picks a map of the pool, by its slot (the captain on turn). | | `forfeit` | `side: "a" \| "b"` | Forfeits the draft for a side (the host). | | `abort` | — | Aborts the draft (the host). | | `pool.add` | — | Stages the library's selected chart in the pool (the host). | | `pool.remove` | `slot: string` | Takes a map out of the staged pool, by its slot (the host). | #### Parts {#lobby-draft-parts} | Part | Role | Description | | --- | --- | --- | | `heading` | `heading` | The panel's title. | | `denial` | `status` | The reason of the last refused action, in words. | | `problem` | `status` | What the setup form lacks to start, in words. | | `start` | `button` | Starts the draft from the setup form. | | `poolAdd` | `button` | Stages the library's selected chart in the pool. | | `poolRemove` | `button` | Takes a map out of the staged pool. | | `pool` | `list` | The staged pool, or the maps of the running draft. | | `map` | `listitem` | A map card of the pool: its cover, title, artist and difficulty, slot, rate and state. | | `ban` | `button` | Bans a map: the button on its open card (the captain on turn only). | | `pick` | `button` | Picks a map: the button on its open card (the captain on turn only). | | `turn` | `status` | Whose turn it is to ban or pick, with the countdown. | | `score` | `status` | The series score. | | `forfeit` | `button` | Forfeits the draft for a side (the host only). | | `abort` | `button` | Aborts the draft (the host only). | #### Accessibility {#lobby-draft-a11y} - Role: `region` - Name: The panel's heading. - Focus: Nothing takes the focus when the state changes: the panel announces its turn and its denial in its status parts. | Keyboard | Effect | | --- | --- | | Tab | Moves through the form, the pool and the buttons in reading order. | | Enter / Space | Presses the focused button. | #### Musts {#lobby-draft-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `heading` | `heading` exists with role `heading`, not a tab stop | all | The panel has a title. | | `setup-start` | `start` exists with role `button`, reachable by keyboard | `setup` | Starting the draft is the host's button. | | `setup-start-click` | click on `start` calls `start(3, 1, "a", "alternate", 60)` | `setup` | Starting sends the set-up draft. | | `pool-add-click` | click on `poolAdd` calls `pool.add()` | `setup` | The library's selected chart is added to the pool. | | `pool-remove-click` | click on `poolRemove` calls `pool.remove("M1")` | `setup` | A staged map is taken out of the pool. | | `problem` | `problem` exists with role `status`, not a tab stop | `setup` | A form that cannot start says what it lacks. | | `ban-click` | click on `ban` calls `ban("M2")` | `banning` | Banning a map is the captain on turn's button. | | `pick-click` | click on `pick` calls `pick("M3")` | `picking` | Picking a map is the captain on turn's button. | | `turn` | `turn` exists with role `status`, not a tab stop | `banning`, `picking` | The panel says whose turn it is, with the countdown when there is a timer. | | `score` | `score` exists with role `status`, not a tab stop | `playing`, `finished` | The series score is on the panel. | | `forfeit-click` | click on `forfeit` calls `forfeit("a")` | `banning`, `picking`, `playing` | Forfeiting a side is the host's button. | | `abort-click` | click on `abort` calls `abort()` | `banning`, `picking`, `playing` | Aborting the draft is the host's button. | | `no-times-sign` | `pool` never contains `×` | `banning`, `picking`, `playing`, `finished` | A rate is never written with a multiplication sign. | | `no-check-mark` | `pool` never contains `✓` | `banning`, `picking`, `playing`, `finished` | The pool carries no bare check mark: a picked map says so in words on its card. | | `denial` | `denial` exists with role `status`, not a tab stop | `setup`, `banning`, `picking`, `playing`, `finished` | A refused action says why, in a status. | ### `maps.toPlay` — Maps to play {#maps-toplay} Charts of the player's own library to push next: near their level, in their strong patterns, at a suggested rate, with the expected Prism accuracy. Filtered by key count and pattern; going to a map selects it and sets the suggested rate. - Template: `components['maps.toPlay']` - Typed context: `ThemeContext<'maps.toPlay'>` - Default renderer: `MapsToPlay` #### Input {#maps-toplay-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "loading" | "ready" | "notEnough" | "noLevel" | "empty" | "unavailable" | "retry" keys? number keyOptions[] object value number label string active boolean pattern string patterns[] object id string label string color? string plays number levelText? string listed boolean active boolean ratingName string state = loading: {} state = ready: entries[] object id string index number title string artist string difficulty string keys number pattern string patternColor? string kind "comfort" | "push" | "stretch" rate number rateText string ratingText string ratingAtRateText string expectedText string bandText string current boolean state = notEnough: have number need number state = noLevel: {} state = empty: {} state = unavailable: reason "judgement" | "noRating" state = retry: reason "busy" | "failed" ``` #### States {#maps-toplay-states} | State | Meaning | | --- | --- | | `loading` | The host is working the list out. | | `ready` | A list of charts, comfort first, then push, then stretch. | | `notEnough` | Fewer comparable plays than the method needs: how many there are and how many it needs. No number about any chart. | | `noLevel` | Enough plays, but the accuracy is below the target at every difficulty played: there is no level to propose around. | | `empty` | A level, but no chart of the library fits it (or none is rated yet). | | `unavailable` | Nothing can be said: the judgement is not Prism's (the target is Prism's accuracy) or no rating names the patterns. | | `retry` | The host could not answer now (a play holds the background work, or the library could not be read): it can be asked again. | #### Outputs {#maps-toplay-outputs} | Output | Arguments | Description | | --- | --- | --- | | `goTo` **(required)** | `index: number, title: string, rate: number` | Goes to the map: selects it in the library and sets the suggested rate (the title is what the list searches for). | | `filter.keys` | `keys: number` | Shows the list for another key count. | | `filter.pattern` | `pattern: string` | Shows the list for one pattern; the empty text is the player's strongest ones. | | `retry` | — | Asks the host for the list again. | #### Parts {#maps-toplay-parts} | Part | Role | Description | | --- | --- | --- | | `heading` | `heading` | The title of the panel. | | `keys` | `group` | The key count filter. | | `key` | `button` | One key count (repeats). | | `patterns` | `group` | The pattern filter. | | `pattern` | `button` | One pattern, the first being "Strongest" (repeats). | | `list` | `list` | The charts. | | `entry` | `listitem` | One chart (repeats). | | `goTo` | `button` | Goes to a chart: the row is the button (repeats). | | `message` | `status` | What the panel says when there is no list. | | `retry` | `button` | Asks again. | #### Accessibility {#maps-toplay-a11y} - Role: `region` - Name: Maps to play. - Focus: The filters are tab stops; the list is ONE tab stop (the chart that was last on) and the arrows move inside it. | Keyboard | Effect | | --- | --- | | ArrowDown / ArrowUp | Moves to the next or previous chart of the list. | | Home / End | First or last chart. | | Enter | Goes to the chart: selects it and sets its suggested rate. | #### Musts {#maps-toplay-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `heading` | `heading` exists with role `heading`, not a tab stop | all | The panel has a title. | | `keys` | `keys` exists with role `group`, not a tab stop | `ready`, `notEnough`, `noLevel`, `empty` | The key count filter is a group. | | `key-click` | click on `key` calls `filter.keys(4)` | `ready`, `notEnough`, `noLevel`, `empty` | Pressing a key count shows the list for it. | | `patterns` | `patterns` exists with role `group`, not a tab stop | `ready`, `notEnough`, `noLevel`, `empty` | The pattern filter is a group. | | `strongest-click` | click on `pattern` calls `filter.pattern("")` | `ready`, `notEnough`, `noLevel`, `empty` | The first pattern button is the strongest ones. | | `list` | `list` exists with role `list`, not a tab stop | `ready` | The charts are a list. | | `go-to-reachable` | `goTo` exists with role `button`, reachable by keyboard | `ready` | A chart is a button the keyboard reaches. | | `go-to-click` | click on `goTo` calls `goTo(12, "Strong 280", 1.15)` | `ready` | Pressing a chart goes to it, at its suggested rate. | | `go-to-enter` | Enter on `goTo` calls `goTo(12, "Strong 280", 1.15)` | `ready` | Enter on a chart goes to it, at its suggested rate. | | `no-times-sign` | `list` never contains `×` | `ready` | A rate is never written with a multiplication sign. | | `message` | `message` exists with role `status`, not a tab stop | `loading`, `notEnough`, `noLevel`, `empty`, `unavailable`, `retry` | Without a list the panel says why, in a status. | | `no-list-without-numbers` | `goTo` is not drawn | `loading`, `notEnough`, `noLevel`, `empty`, `unavailable`, `retry` | Without a list there is no chart on the panel. | | `retry-click` | click on `retry` calls `retry()` | `retry` | Asking again asks the host again. | ### `player.card` — Player card {#player-card} One player: a member of the multiplayer lobby (before the round, or while it runs) or a connected player of the chat's players' panel. The card is a list item the host provides (the lobby's list of members, the panel's grid); its state says which of the three it is. The game keeps the item, the player's menu, the name's button, the picture, the flag, the title, the clan tag, the friend mark, the rank chip, the tier counts and the replay button; a theme draws what is inside, with the facts of the input (host, ready, standing, status…) as plain text and the game's widgets by `slot`. - Template: `components['player.card']` - Typed context: `ThemeContext<'player.card'>` - Default renderer: `PlayerCard` - Added in theme API 2 (a theme must declare `"themeApi": 2` to template it) #### Face {#player-card-face} This contract is a **face**: the host draws and owns the card's own root (its button or plate, keyboard, menus, tooltips, actions and accessible name); a template draws what is **inside** it from the input, and uses `slots` for the host's own widgets. A face has no `button`, `toggle`, `dropdown`, no `slot` of another contract, calls no output, and none is required of it. #### Input {#player-card-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "lobby" | "round" | "user" userId string name string initial string channel string self boolean index number tone number place number picture boolean host boolean spectator boolean waiting boolean hasMap? boolean rank? object value number text string top boolean label string tip string country? string title? object name string style? string colour? string clan? object tag string name string friend? object mutual boolean watchable boolean side? "a" | "b" strip boolean state = lobby: ready boolean last? object accuracy string detail string tiers[]? object name string color string gradient[]? string symbol? ref @pvng/desktop:JudgementSymbol count number state = round: standing? object kind "result" | "live" figures object accuracy string detail string tiers[]? object name string color string gradient[]? string symbol? ref @pvng/desktop:JudgementSymbol count number note "noScore" | "waiting" | "spectating" | "none" state = user: status "online" | "inLobby" | "playing" statusText string ``` #### States {#player-card-states} | State | Meaning | | --- | --- | | `lobby` | A lobby member before the round: the name, the marks and whether the member is ready (a spectator is not asked). | | `round` | A lobby member while the round runs: the accuracy and the figures of their play, live or replayed, or a note saying why there is none. | | `user` | A connected player of the chat's panel: the name, the country and title, the status and the rank. | #### Outputs {#player-card-outputs} | Output | Arguments | Description | | --- | --- | --- | | `replay.watch` | `userId: string` | Opens the replay the lobby holds of this member (what the button over the card does; the argument is the member's account id). | #### Slots {#player-card-slots} | Slot | Description | | --- | --- | | `avatar` | The profile picture, to lay over the tile that holds the initial (the tile is `position: relative; overflow: hidden`; nothing when the player has no picture). | | `playerName` | The player's name: a button in the players' panel (a left click runs the chat's primary action, a right click opens the menu), the plain name in the lobby. | | `clan` | The clan tag `[TAG]` (nothing without a clan). | | `friend` | The friend mark: a heart and its word, a second heart when mutual (nothing for the account itself or a player who is not a friend). | | `flag` | The flag of the player's country as a picture with its name (nothing without a country). | | `title` | The equipped title in the site's style (nothing without one). | | `rank` | The site's rank as a chip with its tooltip (nothing without a rank). | | `marks` | The lobby's pills: host, spectator, waiting for the next round, has or lacks the map, "you" (nothing in the players' panel). | | `status` | The players' panel's status: the mark and its words, with the full text as a tooltip (nothing in the lobby). | | `tiers` | The count of every tier of the judgement under a finished play's accuracy (the game's own widget; nothing when the counts do not name the tiers). | #### Parts {#player-card-parts} | Part | Role | Description | | --- | --- | --- | | `avatar` | `img` | The tile of the picture and the initial. | | `name` | `text` | The player's name. | | `rank` | `text` | The site's rank. | | `status` | `text` | The status of the player in the panel. | | `ready` | `status` | Whether the member is ready. | | `accuracy` | `text` | The accuracy of the round. | | `watch` | `button` | The button over the card that opens the member's replay. | #### Accessibility {#player-card-a11y} - Role: `listitem` - Name: Nothing of its own: the card holds named parts (the name's button in the panel, the replay button over a lobby card). - Focus: The name's button (the panel) and the replay button (a lobby member whose replay is held) are in the tab order; the card itself is not. | Keyboard | Effect | | --- | --- | | Shift+F10 / context menu key | With the focus on or in the card: opens the player's menu under the name. | | Enter / Space | On the name in the players' panel: runs the chat's primary action; on the card of a member whose replay the lobby holds: opens it. | #### Musts {#player-card-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `name-shown` | `name` shows `name` | all | The player's name is shown. | | `status-shown` | `status` shows `statusText` | `user` | The panel says what the player does. | ### `rate.control` — Rate control {#rate-control} The playback rate of the selected chart: a typed value between − and +, a slider over a ruler, the quarter rates as marks a click asks for, and a reset to 1. - Template: `components['rate.control']` - Typed context: `ThemeContext<'rate.control'>` - Default renderer: `RateControl` #### Input {#rate-control-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "ready" | "atDefault" | "atMin" | "atMax" value number text string min number max number minText string maxText string step number typed number steps object down number up number state = ready: {} state = atDefault: {} state = atMin: {} state = atMax: {} ``` #### States {#rate-control-states} | State | Meaning | | --- | --- | | `ready` | A rate inside the range that is not 1. | | `atDefault` | The rate is 1: there is nothing to reset. | | `atMin` | The lowest rate: it cannot go down. | | `atMax` | The highest rate: it cannot go up. | #### Outputs {#rate-control-outputs} | Output | Arguments | Description | | --- | --- | --- | | `set` **(required)** | `value: number` | Asks for a rate. The action moves it into the range and onto the grid of the open tab. | #### Slots {#rate-control-slots} | Slot | Description | | --- | --- | | `aside` | What sits beside the title (the Mods tab shows the chart's rating at this rate there). | #### Parts {#rate-control-parts} | Part | Role | Description | | --- | --- | --- | | `heading` | `heading` | The title of the control. | | `value` | `spinbutton` | The field where a rate is typed; the arrows step it. | | `decrease` | `button` | One step down. | | `increase` | `button` | One step up. | | `slider` | `slider` | The rate on its range. | | `reset` | `button` | Back to 1. | | `mark` | `button` | A rate marked under the slider (its ends and every quarter between): a click asks for it. Out of the Tab order: the slider walks every rate (repeats). | #### Accessibility {#rate-control-a11y} - Role: `none` - Name: The root has no role of its own: the heading "Rate", the field and the slider are named by their own labels. - Focus: Reset, Decrease, the field, Increase, then the slider (Classic: Decrease, the field, Increase, the slider, then Reset). | Keyboard | Effect | | --- | --- | | Enter | Asks for the typed rate. | | Escape | Puts the current rate back in the field. | | ArrowUp / ArrowDown | One step up or down, from the field. | | ArrowLeft / ArrowRight / Home / End | Move the slider. | #### Musts {#rate-control-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `value-field` | `value` exists with role `spinbutton`, reachable by keyboard | all | A rate can be typed freely. | | `value-shows-rate` | `value` shows `text` | all | The field reads the rate in force. | | `no-times-sign` | `root` never contains `×` | all | The rate is never written with a multiplication sign. | | `enter-commits` | Enter on `value` calls `set(value)` | all | Enter asks for the typed rate. | | `arrow-up` | ArrowUp on `value` calls `set(steps.up)` | all | The up arrow in the field is one step up. | | `arrow-down` | ArrowDown on `value` calls `set(steps.down)` | all | The down arrow in the field is one step down. | | `slider` | `slider` exists with role `slider`, reachable by keyboard | all | The rate is on a slider. | | `increase-asks-step` | click on `increase` calls `set(steps.up)` | `ready`, `atDefault`, `atMin` | Increase asks for one step up. | | `decrease-asks-step` | click on `decrease` calls `set(steps.down)` | `ready`, `atDefault`, `atMax` | Decrease asks for one step down. | | `no-decrease-at-min` | `decrease` cannot be pressed | `atMin` | Decrease cannot be pressed at the lowest rate. | | `no-increase-at-max` | `increase` cannot be pressed | `atMax` | Increase cannot be pressed at the highest rate. | | `reset-to-one` | click on `reset` calls `set(1)` | `ready`, `atMin`, `atMax` | Reset goes back to 1. | | `no-reset-at-default` | `reset` cannot be pressed | `atDefault` | Reset cannot be pressed at 1. | ### `selected.header` — Selected map heading {#selected-header} Who and what is selected: the song and its difficulty, the rating on the chosen scale, and the duration, BPM, notes and holds (for a playlist: its length, maps count, peak rating and notes). With a map it also holds the line that says why the rate is unavailable. When nothing is selected it is the invitation: pick a playlist, or add a songs folder to an empty library. Not contracted yet and still bound to their stores inside the default renderer: `AnimatedNumber`, `HelpTip`, `MissingMark`. - Template: `components['selected.header']` - Typed context: `ThemeContext<'selected.header'>` - Default renderer: `SelectedHeader` #### Input {#selected-header-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "map" | "rateCopy" | "playlist" | "pick" | "empty" | "emptyBusy" color string state = map: artist string title string difficulty string keysText string creator? string favourite boolean missing? object kind "audio" | "background" | "both" chart string rating object value? number unit string label string title string stats[] object label string text string numbers[] number clock boolean icon "clock" | "activity" | "music" | "rectangle-vertical" | "library" | "zap" rateStatus object error? string unavailable? string previous? string state = rateCopy: artist string title string difficulty string keysText string creator? string favourite boolean missing? object kind "audio" | "background" | "both" chart string rateCopy object label string help string baseIndex number baseTitle string rating object value? number unit string label string title string stats[] object label string text string numbers[] number clock boolean icon "clock" | "activity" | "music" | "rectangle-vertical" | "library" | "zap" rateStatus object error? string unavailable? string previous? string state = playlist: name string countText string creator? string missingText? string rating object value? number unit string label string title string stats[] object label string text string numbers[] number clock boolean icon "clock" | "activity" | "music" | "rectangle-vertical" | "library" | "zap" state = pick: {} state = empty: {} state = emptyBusy: {} ``` #### States {#selected-header-states} | State | Meaning | | --- | --- | | `map` | A chart is selected (its figures are the library's until its analysis arrives). | | `rateCopy` | A chart that is a proven rate copy of another one is selected: a line says so and goes to the base map. | | `playlist` | A whole playlist is selected: its heading and figures stand in for a map's. | | `pick` | The playlists list is open and none is selected: the heading invites to pick one. | | `empty` | Nothing is selected: the library holds no map; the heading invites to add a folder. | | `emptyBusy` | The same invitation while the library is locked by a scan or an import: the button cannot be pressed. | #### Outputs {#selected-header-outputs} | Output | Arguments | Description | | --- | --- | --- | | `name.filter` | `key: "host/artist" \| "host/creator", name: string` | Ctrl/Cmd + click on the artist or the mapper filters the list on that name. | | `rateCopy.go` | `index: number, title: string` | Goes to the base map of a rate copy. | | `folders.add` **(required)** | — | Adds a songs folder (the empty state's button; without it an empty library is a dead end). | #### Parts {#selected-header-parts} | Part | Role | Description | | --- | --- | --- | | `heading` | `none` | The plate that holds the title, the artist, the difficulty and the rating (a theme that draws its own heading folds it). | | `title` | `heading` | The song title, the playlist name or the invitation (level 1). | | `artist` | `text` | The artist (a filter on Ctrl+click). | | `difficulty` | `text` | The difficulty name, its key count and the mapper. | | `rating` | `group` | The rating on the chosen scale. | | `stats` | `none` | The duration, BPM, notes and holds plates, each with an icon before its label (not under Classic). | | `rateCopy` | `button` | Go to the base map of a rate copy. | | `rateStatus` | `status` | The line that says the rate cannot be used, or the one it falls back to. | | `addFolders` | `button` | Adds a songs folder (the empty library's invitation). | #### Host classes {#selected-header-classes} | Class | Description | | --- | --- | | `song-heading` | The identity plate: artist, title, difficulty and rating (a `header`). | | `pv-plate` | A plate of the design system. | | `pv-plate--lg` | The large plate (the heading). | | `pv-plate--sm` | The small plate (a stat). | | `pv-stat` | A label over a value. | | `artist` | The artist line (the accent label of the heading). | | `difficulty-name` | The difficulty line: badge, name, mapper. | | `name-filter` | An artist or mapper name that is a button (Ctrl/Cmd + click filters). | | `rate-copy` | The line of a rate copy with its go-to button. | | `main-rating` | The rating figure, the loudest number of the heading. | | `rating-value` | The rating's number (keeps room for five characters). | | `favourite-mark` | The small filled star after the title of a favourite. | | `map-metrics` | The row of four stat plates. | | `map-stat` | One stat plate. | | `rate-status` | The rate line (a fixed-height status). | | `no-selection` | The invitation block. | #### Accessibility {#selected-header-a11y} - Role: `none` - Name: The heading has no role of its own: the title is the level-1 heading, the rating is a group named after its calculator, the rate line is a polite status. - Focus: Reading order; the heading itself takes no focus. | Keyboard | Effect | | --- | --- | | Tab | The artist and mapper names are buttons (Ctrl/Cmd + Enter filters the list), then the rate copy button; for an empty library, the add button. | | Enter / Space | On the rate copy or the add button: presses it. | #### Musts {#selected-header-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `title` | `title` exists with role `heading`, not a tab stop | all | The level-1 heading is always there: the selected map's title, the playlist's name or the invitation. | | `title-shows` | `title` shows `title` | `map`, `rateCopy` | The heading reads the title of the map. | | `playlist-name` | `title` shows `name` | `playlist` | The heading reads the name of the playlist. | | `rating-named` | `rating` exists with role `group`, not a tab stop | `map`, `rateCopy`, `playlist` | The rating figure is named after the calculator that gives it. | | `rating-label` | `rating` shows `rating.label` | `map`, `rateCopy`, `playlist` | The group's name says which scale the number is on. | | `rate-status` | `rateStatus` exists with role `status`, not a tab stop | `map`, `rateCopy`, `playlist` | The rate line is a polite status, always there (empty when the rate is fine). | | `rate-copy-reachable` | `rateCopy` exists with role `button`, reachable by keyboard | `rateCopy` | A rate copy can go back to its base map. | | `rate-copy-click` | click on `rateCopy` calls `rateCopy.go(rateCopy.baseIndex, rateCopy.baseTitle)` | `rateCopy` | Going to the base map asks for it with its index and title. | | `add-folders-off` | `addFolders` cannot be pressed | `emptyBusy` | The invitation's button cannot be pressed while the library is locked. | | `add-folders` | `addFolders` exists with role `button`, reachable by keyboard | `empty` | The empty library's invitation is a button the keyboard reaches. | | `add-folders-click` | click on `addFolders` calls `folders.add()` | `empty` | The invitation's button adds a songs folder. | | `add-folders-enter` | Enter on `addFolders` calls `folders.add()` | `empty` | Enter on the invitation's button adds a songs folder. | ### `selected.tabs` — Selected map tabs {#selected-tabs} What the player can look at or set for the selected map, one tab at a time. The panel of each tab is placed by the screen (`controls` is the id of the panel a tab shows). - Template: `components['selected.tabs']` - Typed context: `ThemeContext<'selected.tabs'>` - Default renderer: `SelectedTabs` #### Input {#selected-tabs-input} `?` optional, `[]` list (item below), quoted words are a closed set, `ref T` is an `@pvng` type that a template cannot look into. ```text state "chart" | "playlist" active string vertical boolean tabs[] object id string label string icon string dirty boolean controls string state = chart: {} state = playlist: {} ``` #### States {#selected-tabs-states} | State | Meaning | | --- | --- | | `chart` | The tabs of a map, then the ones mods add (their order is the host's). | | `playlist` | The three tabs of a playlist; the choice is local to the page (no action). | #### Outputs {#selected-tabs-outputs} | Output | Arguments | Description | | --- | --- | --- | | `select` **(required)** | `id: string` | Shows another tab of the map. | | `playlist.select` | `id: string` | Shows another tab of the playlist. | #### Slots {#selected-tabs-slots} | Slot | Description | | --- | --- | | `actions` | The "…" actions of the map at the end of the tabs (`MapActions`, not contracted yet and still bound to its stores; none for a playlist). | #### Parts {#selected-tabs-parts} | Part | Role | Description | | --- | --- | --- | | `tablist` | `tablist` | The row (or rail) of tabs. | | `tab` | `tab` | One tab (repeats). The tab shown carries `data-selected` (and `aria-selected="true"`): a theme's `theme.css` reaches it with `[data-part="tab"][data-selected]`. | | `actions` | `none` | The map's "…" actions after the tabs (a flex row holding the button and the goal pin; nothing for a playlist). | | `more` | `button` | The "…" button that opens the map's menu. | | `moreLabel` | `none` | The word of that button ("More"): hidden while the bar is narrow, so a theme that draws the button as a row of a rail shows it. | #### Host classes {#selected-tabs-classes} | Class | Description | | --- | --- | | `chart-bar` | The bar of tabs (and the actions at its end): the layouts place it by this class; it is the container the actions' labels fold by. | #### Accessibility {#selected-tabs-a11y} - Role: `tablist` - Name: The view of the selected map. - Focus: One tab stop (the active tab); the arrows move inside the list. | Keyboard | Effect | | --- | --- | | ArrowLeft / ArrowRight (ArrowUp / ArrowDown on a rail) | Moves to the neighbouring tab and shows it. | | Home / End | First or last tab. | #### Musts {#selected-tabs-musts} What a template of this component must keep. A *state* column says where the check holds. | Id | Check | States | Requirement | | --- | --- | --- | --- | | `tablist` | `tablist` exists with role `tablist`, not a tab stop | all | The tabs are one tab list with a single tab stop. | | `tab` | `tab` exists with role `tab`, reachable by keyboard | all | Every tab is a `tab` the keyboard reaches. | | `tab-click` | click on `tab` calls `select("info")` | `chart` | Pressing a tab of a map shows it. | | `playlist-tab-click` | click on `tab` calls `playlist.select("info")` | `playlist` | Pressing a tab of a playlist shows it. | ===== Page: Nodes and context reference Address: https://prism.am/dev/themes/nodes/ Derived from: content/mods/sdk/theme.d.ts, crates/themes/src/template/mod.rs, crates/themes/src/template/validate.rs, crates/modding/src/theme.rs, content/dev-src/notes/themes-nodes.en.md # Nodes and context reference The node kinds of theme.ts, their attributes, the typed context (bind, field, on, t, fmt, conditions) and the closed lists and limits of a template. A template is a function that receives a typed context `c` and returns a tree of **nodes** from a closed list of 17 kinds. This page is generated from [theme.d.ts](https://prism.am/dev/sdk/theme.d.ts), the declarations the game writes from its Rust contracts: every signature, attribute and closed list below is read from it, so it cannot drift from the validator. The descriptions come from the notes of `content/dev-src/notes/themes-nodes.<lang>.md`, checked for coverage in both languages. For the screens and components a template may be written for, see the [contracts reference](https://prism.am/dev/md/themes/contracts.md); for a guided tour, see [templates](https://prism.am/dev/md/themes/templates.md). The same builders also exist as untyped globals (`box`, `row`, `bind('a.b')`, `on.press('confirm')`…). Use `c.…` for completion and for the checks of the type checker. A script that declares a top-level name of its own (`const box = …`) adds `export {}` to be a module. ## defineTheme {#define-theme} `defineTheme` is called once, at the top level of `theme.ts`. Each template is built once from its typed context. `theme.ts` calls it once with two optional tables: `screens` (keyed by the screen name without `screen.`: `library`, `settings`) and `components` (keyed by contract name: `library.footer`). Each entry is a function that receives the typed context `c` of that screen or component and returns one node. A template you do not write is inherited from `_base`. An unknown screen or contract name is refused with the list of the known ones. A script runs once: loops, helper functions and constants build the tree; nothing else survives, and a function, a `NaN` or a cycle in the result is refused. ```text screens?: { [screen name without `screen.`]?: (c: ThemeContext<'screen.<name>'>) => ThemeNode } components?: { [contract name]?: (c: ThemeContext<'<contract>'>) => ThemeNode } ``` ## Node constructors {#nodes} Each constructor returns a node. The children are nodes, lists of nodes, or `null`, `undefined` and `false` for an empty place (`cond && node`). The first argument may be an attributes object. ### `box` {#node-box} A block. A plain block: a container with no layout of its own, whose children flow as normal blocks. Give it `as` to choose the element (`section`, `header`, `nav`, `ul`…). It takes the common, layout and container attributes. Prefer `row` or `column` when the children must line up. ```text box(...children: ThemeChild[]): ThemeNode box(attrs: ThemeContainerAttrs, ...children: ThemeChild[]): ThemeNode ``` Also takes: common attributes, layout attributes, container attributes ([attributes](#attributes)). ### `row` {#node-row} Children side by side. A flex container with `flex-direction: row`: the children sit side by side. `gap`, `align`, `justify`, `wrap` and `grow` tune it. ```text row(...children: ThemeChild[]): ThemeNode row(attrs: ThemeContainerAttrs, ...children: ThemeChild[]): ThemeNode ``` Also takes: common attributes, layout attributes, container attributes ([attributes](#attributes)). ### `column` {#node-column} Children one under the other. A flex container with `flex-direction: column`: the children stand one under the other. ```text column(...children: ThemeChild[]): ThemeNode column(attrs: ThemeContainerAttrs, ...children: ThemeChild[]): ThemeNode ``` Also takes: common attributes, layout attributes, container attributes ([attributes](#attributes)). ### `stack` {#node-stack} Children on top of each other. A container whose children are all drawn in the same cell, on top of each other, the last one on top. Use it for a banner picture behind a title, or an overlay on a card. ```text stack(...children: ThemeChild[]): ThemeNode stack(attrs: ThemeContainerAttrs, ...children: ThemeChild[]): ThemeNode ``` Also takes: common attributes, layout attributes, container attributes ([attributes](#attributes)). ### `grid` {#node-grid} A grid; tracks are `auto`, `1fr`, `120px`, `50%`, `minmax(0,1fr)`. A CSS grid. `columns` and `rows` are lists of at most 12 tracks written as `auto`, `<n>px`, `<n>fr`, `<n>%`, `minmax(0,<n>fr)` or `minmax(<n>px,<n>fr)`. Children fill the cells in order. It takes the common and layout attributes, not `as`. ```text grid(...children: ThemeChild[]): ThemeNode grid(attrs: ThemeLayout & { columns?: readonly string[]; rows?: readonly string[] }, ...children: ThemeChild[]): ThemeNode ``` Also takes: common attributes, layout attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `columns?` | `readonly string[]` | | `rows?` | `readonly string[]` | ### `scroll` {#node-scroll} A scrolling area. A scrolling area. `axis` is `y` (default), `x` or `both`. The area shrinks to its container (`min-width` and `min-height` are 0), so give its parent a height. ```text scroll(...children: ThemeChild[]): ThemeNode scroll(attrs: ThemeLayout & { axis?: "y" | "x" | "both" }, ...children: ThemeChild[]): ThemeNode ``` Also takes: common attributes, layout attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `axis?` | `"y" \| "x" \| "both"` | ### `spacer` {#node-spacer} Empty room that grows, or a fixed `size`. Empty room. Without `size` it grows to fill the free space of a `row` or `column` (it pushes what follows to the end); with a `size` from 0 to 10 it is a fixed square of that step of the spacing scale. ```text spacer(attrs?: ThemeAttrs & { size?: ThemeStep }): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `size?` | `ThemeStep` | ### `text` {#node-text} Text: a literal, `bind("path")`, `t("key")`, `fmt.rate("path")` or a list of those. `tween: true` (a `fmt` value only) counts the number up or down to its new value instead of jumping, and puts `data-changed="up"` or `"down"` on the element for 700 ms after each change (what a `theme.css` animation hangs on); under reduced motion the number jumps and the mark is still set. `letters: true` makes each letter its own element (`[data-letter]`, `--i` its position from 0, `--n` on the text the number of letters): a `theme.css` staggers an animation along the word with `animation-delay: calc(var(--i) * 40ms)`. `scramble: true` shows random characters that settle on the new text, left to right, in 400 ms each time the value changes (never the first value, never under reduced motion); both carry `data-changed` for 700 ms after a change. Neither goes with `tween`. A text. `value` is a literal, a binding (`c.bind('map.title')`), a translated key (`c.t('menu.play')`), a formatted number (`c.fmt.rate('map.rate')`) or a list of these written one after the other. `as` chooses the element (`span` by default, `p`, `h1` to `h3`, `strong`, `em`, `label`, `small`). A literal is at most 200 characters. ```text text(value: ThemeText, attrs?: ThemeAttrs & { as?: ThemeTextTag; tween?: boolean; letters?: boolean; scramble?: boolean }): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `as?` | `ThemeTextTag` | | `tween?` | `boolean` | | `letters?` | `boolean` | | `scramble?` | `boolean` | ### `icon` {#node-icon} A lucide icon: its name, or `bind("path")` of a text field that holds one (`mod.bind("icon")`: the mod's own icon). An icon from the game's closed list ([icons](#icons)). `size` is a whole number from 12 to 64 (pixels). The icon is decoration: it is hidden from screen readers, so put the meaning in a label. ```text icon(name: ThemeIcon | ThemeValue<string>, attrs?: ThemeAttrs & { size?: number }): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `size?` | `number` | ### `image` {#node-image} An image of the theme (`"images/x.png"`) or the picture found at a path of the data (`bind("path")`). A picture. `src` is either the path of a picture of the theme (`'images/logo.png'`, which must exist in the theme's `images/` folder) or a path of the data that holds a picture URL (`c.bind('map.background')`). `alt` is required: the text a screen reader says. `fit` is `cover` or `contain`. A path that is neither is refused. ```text image(src: string | ThemeValue<string>, attrs: ThemeAttrs & { alt: ThemeText; fit?: "cover" | "contain" }): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `alt` | `ThemeText` | | `fit?` | `"cover" \| "contain"` | ### `button` {#node-button} A button; its `on` is `on.press("output")`. A real button: the game's own `Button` (a plain `button` element under Classic). It needs a `label` or children, which give its name, and an `on: c.on.press('output')`. `variant` is `primary`, `plain` (default) or `quiet`. `disabled` and `pressed` are conditions; `describedBy` names a `part` whose text describes the button (how the Play button tells why it is off). A button is not allowed inside a face. ```text button(attrs: ThemeAttrs & { variant?: "primary" | "plain" | "quiet"; label?: ThemeText; disabled?: ThemeCond; pressed?: ThemeCond; describedBy?: Part; on: ThemeEvent<"press"> }, ...children: ThemeChild[]): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `variant?` | `"primary" \| "plain" \| "quiet"` | | `label?` | `ThemeText` | | `disabled?` | `ThemeCond` | | `pressed?` | `ThemeCond` | | `describedBy?` | `Part` | | `on` | `ThemeEvent<"press">` | ### `toggle` {#node-toggle} A switch; its `on` is `on.change("output")`. A switch. `label` is its name, `checked` a condition, `on` is `c.on.change('output')`: the output receives the new state (a boolean) after the arguments you give. Not allowed inside a face. ```text toggle(attrs: ThemeAttrs & { label: ThemeText; checked: ThemeCond; on: ThemeEvent<"change"> }): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `label` | `ThemeText` | | `checked` | `ThemeCond` | | `on` | `ThemeEvent<"change">` | ### `meter` {#node-meter} A gauge. A gauge. `value` must be a number of the data; `min` and `max` are literal numbers; `label` is the accessible name. ```text meter(attrs: ThemeAttrs & { value: ThemeText; min?: number; max?: number; label: ThemeText }): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `value` | `ThemeText` | | `min?` | `number` | | `max?` | `number` | | `label` | `ThemeText` | ### `dropdown` {#node-dropdown} A drop-down list of the `{ value, label, group, detail }` options found at the path `options`; its `on` is `on.pick("output")`. The game's own drop-down list. `options` is the path of a list of objects with a text `value` and `label` (and optionally `group` and `detail`), `value` the current value, `label` the visible name, `displayValue` an optional text shown on the closed control, and `on` is `c.on.pick('output')`: the picked value is appended to the arguments. A dropdown has no children. Not allowed inside a face. ```text dropdown(attrs: ThemeAttrs & { label: ThemeText; ariaLabel?: ThemeText; value: ThemeText; options: keyof S["paths"] & string | keyof S["lists"] & string; displayValue?: ThemeText; on: ThemeEvent<"pick"> }): ThemeNode ``` Also takes: common attributes ([attributes](#attributes)). **Own attributes of this node** | Attribute | Type | | --- | --- | | `label` | `ThemeText` | | `ariaLabel?` | `ThemeText` | | `value` | `ThemeText` | | `options` | `keyof S["paths"] & string \| keyof S["lists"] & string` | | `displayValue?` | `ThemeText` | | `on` | `ThemeEvent<"pick">` | ### `slot` {#node-slot} A named place of the screen (a screen template) or of the contract (a component template). Puts a part of the screen or component where you say. `slot('name')` places a place of the current screen (a screen template) or a place a component leaves free (`slots` of its contract); a place can be used several times. `slot('library.chartRow', { from: 'entries[]' })` mounts a whole contract with the data found at `from`: it renders with its own template. `[]` is only valid in `from`, and a contract cannot mount itself. A face can only place its own slots. ```text slot(name: Slot): ThemeNode slot(contract: Contract, options: { from: ThemeFrom<S> }): ThemeNode ``` ### `each` {#node-each} Repeats what `build` returns for every element of a list; `item` reads the element (`item.bind("name")`). Repeats what its function returns for every element of a list of the data: `each('entries', (item) => …)`. Inside, `item.bind('name')` reads a field of the element, and a path may start with `$alias.` for the element of an enclosing `each` (`as` names the alias of the item, a letter then letters or digits, at most 16; `key` names a text or number field that identifies the element). The path must be a list. ```text each<L extends keyof S["lists"] & string>(of: L, build: (item: ThemeBuilders<T, S["lists"][L]>) => ThemeNode | readonly ThemeNode[], options?: { as?: string; key?: keyof S["lists"][L]["paths"] & string }): ThemeNode ``` ### `when` {#node-when} Shows `then` while the condition holds, `otherwise` else. Shows `then` while a condition holds, `otherwise` (optional) else: `when(c.field('pauses.total').gt(0), then, otherwise)`. A place put in a `when` still counts as placed for the required-slot check. For "this class only when", use `classWhen`. ```text when(test: ThemeCond, then: ThemeNode | readonly ThemeNode[], otherwise?: ThemeNode | readonly ThemeNode[]): ThemeNode ``` ## Attributes {#attributes} Attributes are the members of the object given as the first argument. Three groups are shared by several nodes. ### Common attributes {#attrs-common} | Attribute | Type | Description | | --- | --- | --- | | `class?` | `HostClass \| string \| readonly (HostClass \| string)[]` | Classes: the theme's own (selectors of its `theme.css`) or host classes of the screen or contract. The classes of the node: classes of your `theme.css` (written without a prefix) or classes the screen or contract lists as host classes. A class that is neither is refused, and a class defined in both places is ambiguous. At most 8 per node; each is lower-case letters, digits and `-`, starting with a letter (40 characters at most). | | `classWhen?` | `{ readonly [name: string]: ThemeCond } \| readonly { class: string; if: ThemeCond }[]` | Classes present while a condition holds: `{ selected: field("selected").truthy() }`. Classes that are present only while a condition holds: `{ selected: c.field('selected').truthy() }`, or a list of `{ class, if }`. At most 8 entries. | | `part?` | `Part` | `data-part` of an element of the contract. The `data-part` of the element: a part the contract declares (a screen has none). Styles and tests find elements by their part, and the game itself reads a few (the `artist` and `creator` of a card are what a Ctrl-click filters). | | `role?` | `ThemeRole` | The ARIA role of the element, from the closed list [roles](#roles). Layout nodes are generic by default: give `role` only when the element really is that (a `toolbar`, a `list`). | | `aria?` | `{ busy?: ThemeText; live?: "polite" \| "assertive" \| "off"; label?: ThemeText; pressed?: ThemeText; expanded?: ThemeText; current?: ThemeText; describedby?: ThemeText }` | ARIA attributes: `busy`, `label`, `pressed`, `expanded`, `current`, `describedby` take text; `live` takes `polite`, `assertive` or `off`. | | `hidden?` | `ThemeCond` | A condition: while it holds the node is `hidden` (not drawn, not read, not focusable). | | `inert?` | `ThemeCond` | A condition: while it holds the node and its children cannot be focused or clicked. | | `data?` | `{ readonly [name: string]: ThemeText }` | `data-<name>` attributes: `true` gives `data-name=""`, `false` leaves the attribute out. `data-<name>` attributes: `true` gives `data-name=""`, `false` leaves it out. Style them with `[data-name]` in `theme.css`. At most 8 entries, names of 24 characters at most, and a few names the game reserves. | | `vars?` | `{ readonly [K in CssVar \| `--tpl-${string}`]?: ThemeText }` | Custom properties: the CSS variables of the screen or `--tpl-*`. CSS custom properties set on the element: `--tpl-<name>` of your own, or the variables the screen or contract lists. Read them with `var(--tpl-…)` in `theme.css`. At most 8 entries. | ### Layout attributes {#attrs-layout} | Attribute | Type | Description | | --- | --- | --- | | `gap?` | `ThemeStep` | The space between children, a step of the spacing scale (0 to 10, the tokens `--pv-s0` to `--pv-s10`). | | `pad?` | `ThemeStep` | The padding of the container, a step of the spacing scale (0 to 10). | | `align?` | `"start" \| "center" \| "end" \| "stretch" \| "baseline"` | `align-items` of the container: where children stand on the cross axis. | | `justify?` | `"start" \| "center" \| "end" \| "between" \| "around" \| "evenly"` | `justify-content` of the container: how children share the main axis (`between`, `around`, `evenly` space them). | | `wrap?` | `boolean` | `true` lets the children of a flex container (`row` or `column`) wrap onto several lines. | | `grow?` | `0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6 \| 7 \| 8 \| 9 \| 10 \| 11 \| 12` | `flex-grow`, 0 to 12. `flex-grow` of the node in its parent, a whole number from 0 to 12. | | `focusable?` | `boolean` | The node can take keyboard focus (a container that acts as a control). Makes the node a target for programmatic focus (`tabindex="-1"`): the game can focus it, but it is never a tab stop. Keyboard order is always the order of the tree. | ### Container attributes {#attrs-container} | Attribute | Type | Description | | --- | --- | --- | | `as?` | `ThemeContainerTag` | The HTML element of a container (`div` by default; `section`, `header`, `footer`, `nav`, `aside`, `main`, `article`, `ul`, `li`). | ### The aria attribute {#attrs-aria} `aria` takes these keys; each value is text (a literal, a value of the data or a list of them), except `live`. | Attribute | Type | | --- | --- | | `busy` | `ThemeText` | | `live` | `"polite" \| "assertive" \| "off"` | | `label` | `ThemeText` | | `pressed` | `ThemeText` | | `expanded` | `ThemeText` | | `current` | `ThemeText` | | `describedby` | `ThemeText` | ### Reserved data names {#attrs-data} `data` sets `data-<name>` attributes (at most 8 entries). These names belong to the renderer or the game's styles and cannot be set: `part`, `contract`, `state`, `direction`, `gap`, `align`, `justify`, `wrap`, `grow`, `pad`, `size`, `axis`, `variant`, `kind`, `slot`. ## Values, conditions and events {#context} The members of the context that are not nodes: they build the values a node shows, the conditions that show or hide, and the events that call an output. ### Values {#ctx-values} #### `c.bind` {#ctx-bind} The data at a path of the input (`""` is the item of an `each`). `c.bind('path')` reads the data at a dotted path of the input of the screen or component: text, a number or a boolean (a list or an object cannot be bound). Inside an `each`, `item.bind('field')` reads the element and `c.bind('$alias.field')` an outer one. A path that exists in no state of the input is refused when the theme loads; a path that exists but is empty in the current state reads as empty text. ```text bind<P extends ThemeBindable<S>>(path: P): ThemeValue<S["paths"][P]> ``` #### `c.t` {#ctx-t} A translated text; `args` fill its placeholders. `c.t('menu.key', { name: value })` is the game's own translated text for a catalogue key (lower-case letters, digits, `_` and `.`, at most 64 characters), with placeholders filled by the arguments (at most 8, names of at most 16 letters or digits). It follows the player's language, which a literal does not. ```text t(key: string, args?: { readonly [name: string]: ThemeText }): ThemeValue<string> ``` #### `fmt.rate` {#ctx-fmt-rate} A playback rate: `1.25` (no `x`). A playback rate written without the `x`: `1.25`. `digits` (0 to 6) is optional. The path must be a number. ```text rate(path: ThemeNumeric<S>, digits?: 0 | 1 | 2 | 3 | 4 | 5 | 6): ThemeValue<string> ``` #### `fmt.count` {#ctx-fmt-count} A compact count, floored: `12k`, `1.9k`. A compact count, rounded down: `12k`, `1.9k`. `digits` (0 to 6) is optional. ```text count(path: ThemeNumeric<S>, digits?: 0 | 1 | 2 | 3 | 4 | 5 | 6): ThemeValue<string> ``` #### `fmt.percent` {#ctx-fmt-percent} A number that is ALREADY a percentage (97.4 gives `97.40%`); 2 digits by default. A number that is already a percentage: `97.4` gives `97.40%` (2 digits by default). A fraction such as `0.974` is not multiplied. ```text percent(path: ThemeNumeric<S>, digits?: 0 | 1 | 2 | 3 | 4 | 5 | 6): ThemeValue<string> ``` #### `fmt.duration` {#ctx-fmt-duration} A duration in SECONDS as `m:ss` (or `h:mm:ss`). A duration given in seconds, written `m:ss` (or `h:mm:ss` from an hour). ```text duration(path: ThemeNumeric<S>, digits?: 0 | 1 | 2 | 3 | 4 | 5 | 6): ThemeValue<string> ``` #### `fmt.fixed` {#ctx-fmt-fixed} A number with a fixed count of decimals (`toFixed(digits)`, 2 by default). A number with a fixed count of decimals (`toFixed(digits)`, 2 by default). ```text fixed(path: ThemeNumeric<S>, digits?: 0 | 1 | 2 | 3 | 4 | 5 | 6): ThemeValue<string> ``` ### Conditions {#ctx-conditions} #### `c.field` {#ctx-field} A field of the input, to compare: `field("pauses.total").gt(0)`. `c.field('path')` names a field of the input to compare in a condition; it returns an object whose methods (`eq`, `gt`, `truthy`…) build a condition. The methods offered depend on the type of the field: numbers have `gt`, `ge`, `lt`, `le`; texts, enums and booleans have `eq`, `ne`, `in`; objects and lists only have `truthy` and `falsy`. The field `state` of a contract is its state (`mapReady`…). ```text field<P extends keyof S["paths"] & string>(path: P): ThemeFieldOf<S["paths"][P]> ``` #### `field(…).truthy` {#ctx-field-truthy} The data is present (an object, a non-empty list or text, a number other than 0, true). True when the data is present: an object that is not null, a list that is not empty, a text that is not empty, a number other than 0, `true`. The only test an object or a list accepts. ```text truthy(): ThemeCond ``` #### `field(…).falsy` {#ctx-field-falsy} The opposite of `truthy`. ```text falsy(): ThemeCond ``` #### `field(…).eq` {#ctx-field-eq} True when the field equals the value. For text, enums and booleans. An enum field is only compared with one of its own values: any other word is refused with the list. ```text eq(value: T): ThemeCond ``` #### `field(…).ne` {#ctx-field-ne} True when the field differs from the value (same types as `eq`). ```text ne(value: T): ThemeCond ``` #### `field(…).in` {#ctx-field-in} True when the field is one of 1 to 16 values (text or enum): `c.field('state').in(['mapReady', 'mapBlocked'])`. ```text in(values: readonly T[]): ThemeCond ``` #### `field(…).gt` {#ctx-field-gt} True when the number is greater than the value. ```text gt(value: number): ThemeCond ``` #### `field(…).ge` {#ctx-field-ge} True when the number is greater than or equal to the value. ```text ge(value: number): ThemeCond ``` #### `field(…).lt` {#ctx-field-lt} True when the number is less than the value. ```text lt(value: number): ThemeCond ``` #### `field(…).le` {#ctx-field-le} True when the number is less than or equal to the value. ```text le(value: number): ThemeCond ``` #### `cond.and` {#ctx-cond-and} `cond.and(other, …)` is true when this condition and all the others hold (at most 8 conditions in all). ```text and(...others: ThemeCond[]): ThemeCond ``` #### `cond.or` {#ctx-cond-or} `cond.or(other, …)` is true when this condition or any of the others holds (at most 8 conditions in all). ```text or(...others: ThemeCond[]): ThemeCond ``` #### `cond.not` {#ctx-cond-not} `cond.not()` inverts a condition. Conditions nest at most 6 levels. ```text not(): ThemeCond ``` ### Events {#ctx-events} #### `on.press` {#ctx-on-press} The button is pressed (click, Enter, Space): calls the output with these arguments. `c.on.press('output', arg, …)` is the `on` of a `button`: the output is called when the button is pressed (click, Enter or Space) with the arguments, in order and of the type the output declares. The name must be an output of the screen or component, or the theme is refused with the list of its outputs. ```text press<O extends keyof T["outputs"] & string>(output: O, ...args: ThemeArgs<T["outputs"][O]>): ThemeEvent<"press"> ``` #### `on.change` {#ctx-on-change} The toggle changes: calls the output with these arguments, then the new state (a boolean). `c.on.change('output', arg, …)` is the `on` of a `toggle`: the output is called with the arguments you give, then the new state (a boolean) as the last one. ```text change<O extends keyof T["outputs"] & string>(output: O, ...args: ThemeArgs<ThemeLead<T["outputs"][O]>>): ThemeEvent<"change"> ``` #### `on.pick` {#ctx-on-pick} An option of the dropdown is picked: calls the output with these arguments, then the option's value (a string). `c.on.pick('output', arg, …)` is the `on` of a `dropdown`: the output is called with the arguments you give, then the value of the picked option (a string) as the last one. ```text pick<O extends keyof T["outputs"] & string>(output: O, ...args: ThemeArgs<ThemeLead<T["outputs"][O]>>): ThemeEvent<"pick"> ``` ## Closed lists {#lists} Every list below is closed: a value outside it is refused with its list in the message. ### Roles {#roles} Values of `role`. `group`, `region`, `toolbar`, `tablist`, `tabpanel`, `status`, `search`, `list`, `listitem`, `navigation`, `none`, `presentation`, `img`. ### Spacing steps {#steps} `gap`, `pad` and `size` take a step from 0 to 10, which is the spacing token `--pv-s0` to `--pv-s10` ([tokens](https://prism.am/dev/md/themes/tokens.md#spacing)). `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`. ### Element names {#tags} Values of `as`: for containers (`box`, `row`, `column`, `stack`), then for `text`. - `box`, `row`, `column`, `stack`: `div`, `section`, `header`, `footer`, `nav`, `aside`, `main`, `article`, `ul`, `li` - `text`: `span`, `p`, `h1`, `h2`, `h3`, `strong`, `em`, `label`, `small` ### Icons {#icons} Values of the `name` of an `icon` node (and of a tab's `icon`): any lucide icon, by its name on lucide.dev/icons. The page loads an icon the first time it is drawn. For example: `heart`, `music-2`, `play`, `skull`, `swords`, `zap`. ## Limits {#limits} Limits of the tree a template produces and of the script that builds it. A tree over a limit is refused with a message that names it; a script over a budget loads the theme without its templates. | Limit | Value | Where | | --- | --- | --- | | Nesting depth of nodes in a template | 24 | validator (`crates/themes/src/template`) | | Nodes of all the templates of one theme together | 1,500 | validator (`crates/themes/src/template`) | | Characters of a literal text | 200 | validator (`crates/themes/src/template`) | | Templates (screens and components) of one theme | 64 | validator (`crates/themes/src/template`) | | Children of one node | 64 | validator (`crates/themes/src/template`) | | Classes of one node (and conditional classes) | 8 | validator (`crates/themes/src/template`) | | Entries of `data` and of `vars` of one node | 8 | validator (`crates/themes/src/template`) | | Tracks of a grid (`columns`, `rows`) | 12 | validator (`crates/themes/src/template`) | | Nesting depth of a value (a list of values inside a list…) | 6 | validator (`crates/themes/src/template`) | | Nesting depth of a condition (`and`, `or`, `not`) | 6 | validator (`crates/themes/src/template`) | | Arguments of an output call | 8 | validator (`crates/themes/src/template`) | | Values of an `in([…])` comparison | 16 | validator (`crates/themes/src/template`) | | Themes loaded at once | 64 | `crates/themes/src/library.rs` | | Wall time of `theme.ts` (the whole run, builders included) | 500 ms | `ThemeScriptLimits` (`crates/modding/src/theme.rs`) | | Memory of the script engine | 16 MiB | `ThemeScriptLimits` (`crates/modding/src/theme.rs`) | | Stack of the script engine | 1 MiB | `ThemeScriptLimits` (`crates/modding/src/theme.rs`) | | Size of `theme.ts` | 128 KiB | `ThemeScriptLimits` (`crates/modding/src/theme.rs`) | | Nodes the script may build (every template, counted with repetitions) | 4,000 | `ThemeScriptLimits` (`crates/modding/src/theme.rs`) | | Size of the tree as JSON | 1 MiB | `ThemeScriptLimits` (`crates/modding/src/theme.rs`) | ===== Page: theme.css allow-list Address: https://prism.am/dev/themes/css-allowlist/ Derived from: content/dev-src/generated/theme-css.json, crates/themes/src/stylesheet.rs, crates/modding/examples/theme_reference.rs # theme.css allow-list Every selector, at-rule, property, value form and variable that theme.css accepts, and its limits, read from the validator. `theme.css` is a validated subset of CSS for the classes of a theme. This page lists exactly what the validator accepts; anything else is refused with the line and the reason. The lists are generated from the validator itself (`themes::stylesheet::check`, probed by the cargo example `theme_reference`), so they cannot drift from the game. How to use the subset, and what the rewriting does to your file, is in [theme.css](https://prism.am/dev/md/themes/css.md). ## Limits {#limits} | Limit | Value | | --- | --- | | File size | 256 KiB | | Rules in a file (style rules and keyframe steps together) | 2,048 | | Declarations in one rule | 40 | | Words, numbers and symbols in one value | 200 | | Nesting depth of functions in a value | 5 | | Characters of a string (no `\`, no control character) | 80 | | Steps of one `@keyframes` | 24 | | Characters of a class name (lower-case letters, digits, `-`, starting with a letter) | 40 | | Characters of a `@keyframes` name (same alphabet) | 40 | | Characters of a `data-` name in a selector, after `data-` | 24 | | Characters of the value in `[data-name="value"]` (letters, digits, `-`, `_`, `.`) | 40 | | Characters of a `--tpl-` variable name, after `--tpl-` (lower-case letters, digits, `-`) | 32 | | Conditions joined by `and` in one `@media` | 2 | ## Selectors {#selectors} A selector is made of the theme's own classes and the game's `data-*` marks. - `.name`: a class of the theme. A selector **starts with** one of the theme's classes. Compound selectors chain them: `.card.selected`. - `[data-name]` and `[data-name="value"]` (the `data-` attributes of the game's elements and of your `data` attributes), after a class or further along a selector. Nothing else is an attribute selector. - Pseudo-classes: `:hover`, `:focus-visible`, `:focus-within`, `:active`, `:disabled`, `:first-child`, `:last-child`. - Functional pseudo-classes, holding simple selectors of classes and not nested: `:not()`, `:is()`, `:where()`. - Pseudo-elements, once, **last** in a selector: `::before`, `::after`. They draw decoration with `content`. - Combinators: the descendant (a space) and the child `>`. Selectors are separated by commas. Refused: element selectors (`div`), the universal selector `*`, id selectors `#x`, the combinators `+`, `~` and `&`, any other pseudo-class or pseudo-element, a pseudo-element in the middle of a selector, and any selector that does not start with one of the theme's classes. ## At-rules {#at-rules} Only `@keyframes` and `@media`. Any other at-rule (`@import`, `@font-face`, `@supports`…) is refused. - `@media` holds style rules only (no at-rule inside, no nesting). Its conditions are written `(feature: value)`, at most 2 joined by `and`. Features: `max-width`, `min-width`, `max-height`, `min-height`, `prefers-reduced-motion`. A size is a whole number of px from 1 to 10,000; `prefers-reduced-motion` is `reduce` or `no-preference`. - `@keyframes <name>` holds steps `from`, `to` or `<n>%` (0 to 100), at most 24. An animation named in `animation` or `animation-name` must be defined by a `@keyframes` of the same file. ## Properties and values {#properties} A property outside these lists is refused with `this property is not allowed in theme.css`. A property takes values of the classes shown. Plain words (`center`, `bold`, `row`…) are accepted for every property that is not a closed list; the browser ignores a word it does not know. `!important`, backslashes in strings and `url()` outside `images/` are refused everywhere. ### Value classes {#value-classes} | Class | Accepts | | --- | --- | | `length` | A number with a unit (`px`, `em`, `rem`, `vw`, `vh`, `vmin`, `vmax`, `ch`) or a bare `0`; at most 10,000 in absolute value. | | `percentage` | `<n>%`, at most 10,000. | | `number` | A unitless number, at most 100,000. A bare `0` also stands for a length, a percentage, an angle or a time. | | `color` | `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, and the colour functions listed below. Colour names (`red`, `transparent`) are plain words. | | `angle` | A number with `deg`, `turn`, `rad`, at most 3,600. | | `time` | A number with `s` or `ms`, at most 60,000. | | `fraction` | `<n>fr`, at most 1,000. | | `string` | A quoted string of at most 80 characters. | | `url` | `url("images/<file>")`: one quoted path of a picture that exists in the theme's `images/` folder (png, jpg, jpeg, webp, gif, svg). Nothing else. | | `gradient` | A gradient function (listed below). | | `transform` | A transform function (listed below). | | `filter` | A filter function (listed below). | | `backdrop` | A backdrop-filter function (listed below). | | `shape` | A basic shape function (listed below). | | `easing` | An easing function (listed below), or a keyword. | | `grid` | A grid function (listed below). | ### Properties by value {#by-value} Properties that accept the same classes are grouped. A name ending in `*` is a family: every property of that prefix (`margin-*` is `margin-top`, `margin-inline-start`…). | Value classes | Properties | | --- | --- | | `length` | `letter-spacing`, `word-spacing` | | `length` · `color` | `box-shadow`, `text-shadow` | | `length` · `number` · `color` | `outline`, `outline-*` | | `length` · `percentage` | `background-*`, `bottom`, `column-gap`, `flex-basis`, `gap`, `height`, `inset`, `left`, `margin`, `margin-*`, `mask-position`, `mask-size`, `max-height`, `max-width`, `min-height`, `min-width`, `object-position`, `padding`, `padding-*`, `right`, `row-gap`, `top`, `transform-origin`, `width` | | `length` · `percentage` · `number` | `flex`, `font-*`, `line-height` | | `length` · `percentage` · `number` · `color` | `border`, `border-*` (except `border-image*`), `text-*` | | `length` · `percentage` · `number` · `color` · `angle` · `url` · `gradient` | `background` | | `length` · `percentage` · `number` · `fraction` · `string` · `grid` | `grid`, `grid-*` | | `length` · `percentage` · `number` · `string` | `font` | | `percentage` · `number` | `opacity` | | `number` | `aspect-ratio`, `flex-grow`, `flex-shrink`, `order` | | `number` · `time` · `easing` | `animation-*`, `transition`, `transition-*` | | `color` | `background-color`, `color` | | `string` | `content`, `font-family` | | `url` · `gradient` | `background-image`, `mask-image` | | `transform` | `transform` | | `filter` · `backdrop` | `filter` | | `backdrop` | `backdrop-filter` | | `shape` | `clip-path` | | words only | `align-*`, `flex-direction`, `flex-flow`, `flex-wrap`, `justify-*`, `overflow-wrap`, `place-*`, `white-space`, `word-break` | ### Properties with a closed list of words {#closed-words} These properties take one of these words (and the CSS-wide `inherit`, `initial`, `unset`, `revert`) and nothing else. | Property | Words | | --- | --- | | `cursor` | `auto` `default` `pointer` `text` `move` `not-allowed` `grab` `grabbing` `wait` `help` `crosshair` `progress` `zoom-in` `zoom-out` `none` | | `display` | `flex` `grid` `block` `none` `inline-flex` `inline-block` `inline` `inline-grid` `contents` | | `mask-repeat` | `repeat` `no-repeat` `repeat-x` `repeat-y` `round` `space` | | `mix-blend-mode` | `normal` `multiply` `screen` `overlay` `darken` `lighten` `color-dodge` `color-burn` `hard-light` `soft-light` `difference` `exclusion` `hue` `saturation` `color` `luminosity` `plus-lighter` | | `object-fit` | `fill` `contain` `cover` `none` `scale-down` | | `overflow` | `visible` `hidden` `auto` `scroll` `clip` | | `overflow-x` | `visible` `hidden` `auto` `scroll` `clip` | | `overflow-y` | `visible` `hidden` `auto` `scroll` `clip` | | `pointer-events` | `auto` `none` | | `position` | `static` `relative` `absolute` `sticky` | | `visibility` | `visible` `hidden` `collapse` | | `writing-mode` | `horizontal-tb` `vertical-rl` `vertical-lr` `sideways-rl` `sideways-lr` | ### Special cases {#special} - `z-index`: a whole number from −50 to 50, or `auto`. - `animation` and `animation-name`: the names they use are the `@keyframes` of the file; the validator renames them with the theme's prefix. - `content`: `none`, `normal` or a short quoted string, for `::before` and `::after`. No `attr()`, no counters. The text it draws is decoration that screen readers may read: never put information in it. - `border-image*`: refused. ## Functions {#functions} Functions are allowed only where the value class of the property takes them. `var(--name)` and `var(--name, fallback)` are allowed in every value. | For | Functions | | --- | --- | | numbers, lengths, angles, times (`calc` and the like) | `calc()` `min()` `max()` `clamp()` `var()` | | colours | `rgb()` `rgba()` `hsl()` `hsla()` `hwb()` `color-mix()` | | gradients (`background`, `background-image`) | `linear-gradient()` `repeating-linear-gradient()` `radial-gradient()` `repeating-radial-gradient()` `conic-gradient()` `repeating-conic-gradient()` | | `transform` | `translate()` `translatex()` `translatey()` `translatez()` `translate3d()` `scale()` `scalex()` `scaley()` `scale3d()` `rotate()` `rotatex()` `rotatey()` `rotatez()` `skew()` `skewx()` `skewy()` | | `filter` | `blur()` `brightness()` `contrast()` `drop-shadow()` `grayscale()` `hue-rotate()` `saturate()` `sepia()` | | `backdrop-filter` | `blur()` `saturate()` | | `clip-path` | `polygon()` `inset()` | | easing (`transition*`, `animation*`) | `cubic-bezier()` `steps()` | | grid templates | `repeat()` `minmax()` `fit-content()` | | pictures | `url()` | ## Variables {#variables} A rule may declare three kinds of custom property. Read any of them with `var(--name)`. - `--tpl-<name>`: your own variables (at most 32 characters after the prefix). Their values may be of any value class. Set them from a template with the `vars` attribute. - The design tokens of kind `case`, `clip`, `color`, `duration`, `easing`, `filter`, `font`, `length`, `opacity`, `ratio`, `shadow`, `weight`, set for the subtree of the rule only (the type scale of a banner, the accent of a panel). The value follows the grammar of the token ([tokens](https://prism.am/dev/md/themes/tokens.md#kinds)). - The plate variables `--plate`, `--edge`, `--clip`, `--clip-edge`: the fill and edge (colour or gradient) and the shapes (clip) of a `.pv-plate` of the game. The tokens of the other kinds (`scheme`, `layers`, `image`, `choice`: the layout and graph words, pictures, gradient layers, the colour scheme) stay in `tokens.css`, and so does `--pv-art-filter`, which is judged on the whole screen. Setting one in `theme.css` is refused with `this token is set in tokens.css, not in theme.css`. ## Notices {#notices} An animation that runs forever (`infinite`) is accepted with a notice, not refused: it repaints its region every frame even when nothing else moves, which costs the game's web view on a menu left alone. ## What the game does to the file {#rewriting} Every class `.name` becomes `.tpl-<id>-name`, every selector is placed under `[data-direction="<id>"]` (a theme cannot touch the rest of the game), every `@keyframes` name and its uses get the same prefix, and every `url()` becomes the protocol URL of the picture. ===== Page: Theme cookbook Address: https://prism.am/dev/themes/cookbook/ Derived from: content/examples/themes/recipe-hero-banner/theme.ts, content/examples/themes/recipe-slanted-cards/theme.ts, content/examples/themes/recipe-poster-scrim/theme.ts, content/examples/themes/recipe-terminal-list/theme.ts, content/examples/themes/recipe-live-bars/theme.ts, content/examples/themes/recipe-settings-rail/theme.ts, content/examples/themes/recipe-footer-strip/theme.ts, crates/themes/src/stylesheet.rs, crates/themes/src/artwork.rs, crates/modding/src/theme.rs # Theme cookbook Seven small complete themes, each built around one idea, with the rules that shaped them. Each recipe is a complete theme, small enough to read in one sitting. It inherits the default templates, so it overrides one idea and leaves the rest alone. Every recipe comes from a shipped theme: the shipped one is the full version, the recipe is the idea with the rest removed. ## How to use a recipe {#using} The recipes are real folders in `content/examples/themes/<name>/`. The pages show them by inclusion, so what you read is what the test suite checks: each folder passes the same validator as the game, with no problem. To try one, copy its folder next to your other themes and check it: ```bash cargo run -p modding --example check_theme -- content/examples/themes ``` The command prints one line per theme and exits with code 1 if any file has a problem. See [Errors](https://prism.am/dev/md/themes/errors.md#running-check) to read its output. A screen template **replaces the whole screen**, so each recipe that changes a screen writes out the default composition and changes one thing in it. This is also why a recipe keeps game classes such as `song-select`, `pv-screen` and `map-browser`: they are listed by the screen and the game styles them. The list of those classes, of the places a screen must fill and of the paths a template may read is on the [contracts](https://prism.am/dev/md/themes/contracts.md) page. ## Hero banner {#hero-banner} From `content/themes/stage/`. Folder: `content/examples/themes/recipe-hero-banner/`. ![The hero banner recipe: the selected map's heading over its blurred picture, with a strip of four facts under it.](https://prism.am/dev/img/themes/recipe-hero-banner.png) **What it does.** The heading of the selected map sits on the map's own picture, blurred and shaded, and a strip of four facts (duration, BPM, notes, keys) stands under it. The tabs go to a rail beside their panel. **The picture.** An `image` node bound to `map.background` reads the path of the map's picture from the input. It is drawn only when the map has one. ```ts theme // The picture and its shade. The `image` node reads a path bound to the input (`map.background`), never a URL of the web. // It is shown only when the map has a picture. function backdrop(c: Screen): ThemeNode { return c.box( { class: 'hero-backdrop', role: 'presentation' }, present(c, 'map.background', c.image(c.bind('map.background'), { class: 'hero-art', alt: '', fit: 'cover' })), c.box({ class: 'hero-shade' }), ); } ``` **The edge trick.** The backdrop is larger than the banner (`inset` with negative values) and the blur is applied to the backdrop as one piece, so the blur eats its own edges and the picture melts into the screen instead of stopping on a rectangle. ```css /* The banner is not a box: its backdrop reaches past it and is blurred as a whole, so the blur eats its own edges and the picture melts into the screen. */ .hero { position: relative; z-index: 0; flex: none; display: flex; flex-direction: column; margin-bottom: var(--pv-s3); } .hero-backdrop { position: absolute; inset: -22px -22px -12px -14px; z-index: 0; overflow: hidden; filter: blur(16px); pointer-events: none; } .hero-art { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; transform: scale(1.08); filter: saturate(1.4) brightness(.85); } ``` **The title on the picture.** The heading is the game's own, placed with `slot('header')`. A rule makes the plate it paints transparent through the plate variables, so the title stands on the picture. A rule may also set a design token for its subtree: here the rating figure is smaller inside the banner. ```css /* A design token can be set by a rule: here the heading's rating is smaller. `--plate` is the variable plates paint their background with: transparent lets the picture show. */ .hero-main { display: flex; flex-direction: column; gap: var(--pv-s1); min-width: 0; --pv-fs-rating: clamp(44px, 4.2vw, 76px); --pv-plate-filter: none; } .hero-main [data-edge] { --plate: transparent; --edge: linear-gradient(180deg, var(--difficulty-color), transparent); } ``` **The strip is a table.** One row per fact. Add a row and the strip gets one more tile; nothing else changes. ```ts theme // A table drives the strip: one row per fact, with its label key, its icon and how its value reads the input. // Add a row and the strip has one more tile; nothing else changes. interface Fact { readonly label: string; readonly icon: ThemeIcon; readonly value: (c: Screen) => ThemeText; } const FACTS: readonly Fact[] = [ { label: 'ui.duration', icon: 'clock', value: c => c.bind('map.duration.text') }, { label: 'metrics.bpm', icon: 'activity', value: c => c.bind('map.bpm') }, { label: 'maps.notes', icon: 'music', value: c => c.bind('map.notes') }, { label: 'search.keys', icon: 'keyboard', value: c => c.bind('map.keysText') }, ]; ``` **Why it is written this way** - `mask-image` is not in the CSS subset, and `clip-path` only has hard edges. A backdrop that overflows and is blurred whole is the way to a soft edge. - The picture is a `bind` to the input, never a URL: a theme cannot load an address from the web. A picture of the theme itself is written `c.image('images/x.png', …)` and the file must exist in the theme's `images/` folder. - An `image` needs an `alt`. A decorative picture uses `alt: ''` and sits in a node with `role: 'presentation'`. - A playlist has no `map` facts. `present(c, 'map', …)` wraps what needs them in a `when` on that field, so a path that does not exist in the current state never breaks the template. - The game's own heading has four plates of figures. `classWhen: { lit: … }` marks a banner that has the strip, so `theme.css` can hide them (`.lit [data-part='stats']`): the strip says the same. - Text is never put straight on a busy picture: the shade is a gradient made with `color-mix` of the page colour, strongest where the heading is. - `tokens.css` keeps the game's own map picture visible: `--pv-shade` and `--pv-art-filter` may tint, dim and blur it, never hide it (see [limits](https://prism.am/dev/md/themes/cookbook.md#limits)). **Limits to know.** `filter: blur()` and `backdrop-filter: blur()` are in the allow-list; the allowed filter functions are listed on the [CSS allow-list](https://prism.am/dev/md/themes/css-allowlist.md) page. In `tokens.css`, `blur()` of `--pv-art-filter` is limited to 12 px (`crates/themes/src/grammar.rs`). In `theme.css`, `backdrop-filter` is bounded because the GPU recomputes it behind the whole box: `blur()` takes one written number from 0 to 64 px and `saturate()` one from 0 to 4 (or 0 % to 400 %), with no `var()` or `calc()` (`crates/themes/src/stylesheet.rs`, `MAX_BACKDROP_BLUR`, `MAX_BACKDROP_SATURATE`). ## Slanted cards {#slanted-cards} From `content/themes/carousel/`. Folder: `content/examples/themes/recipe-slanted-cards/`. ![The slanted cards recipe: slanted set cards on their pictures, difficulty rows with a round key count and ten stars, a list that curves around the selection.](https://prism.am/dev/img/themes/recipe-slanted-cards.png) **What it does.** Set cards are slanted panels on the set's picture, with the title and the artist over it. Each difficulty is a round badge with the key count and ten stars. The list curves: the farther a row is from the selected one, the more it slides right and fades. **Two faces.** A set card, a difficulty row and a score card are *faces*: the game draws the card's root (its button, its keyboard, its menu, the virtual row it sits in) and the theme draws what is inside. That is why the template below has no button and calls no output. ```ts theme // The set card: a slanted panel on the set's own picture, with the title and the artist over it, then the layout, one round dot per difficulty and the rating range. // `part` names the parts the game hangs gestures on (Ctrl+click on the artist filters by it). function setCard(c: SetCard): ThemeNode { return c.row( { class: 'sc', align: 'center', gap: 3 }, panel(c), c.column( { class: 'sc-info', grow: 1, gap: 0 }, c.text(c.bind('title'), { as: 'strong', part: 'title', class: 'sc-title' }), c.text(c.bind('artist'), { as: 'small', part: 'artist', class: 'sc-artist' }), c.row({ class: 'sc-foot', align: 'center', gap: 2 }, c.text(c.bind('keysText'), { part: 'keys', class: 'sc-keys' }), dots(c)), ), c.text(c.bind('rating.range'), { as: 'strong', part: 'rating', class: 'sc-rating' }), ); } ``` **The ten stars.** `stars` is a list of ten entries. The first ones are `lit` according to the rating, and a loop draws one text node for each. The theme only reads `lit`; the arithmetic belongs to the game. ```ts theme // The difficulty row: a round badge with the key count, the name over ten stars, and the rating at the right. // `stars` is a list of ten entries; the first ones are `lit` according to the rating, and a loop draws one text node for each. function chartRow(c: ChartRow): ThemeNode { return c.row( { class: 'dr', align: 'center', gap: 3 }, c.box({ class: 'dr-ring', part: 'keys' }, c.text(c.bind('keysText'), { class: 'dr-keys' })), c.column( { class: 'dr-main', grow: 1, gap: 0 }, c.row({ class: 'dr-line', align: 'center', gap: 1 }, c.text(c.bind('name'), { as: 'strong', part: 'name', class: 'dr-name' }), c.slot('missing'), c.slot('goal')), c.row({ class: 'dr-stars', role: 'presentation' }, c.each('stars', (star: StarItem) => star.text('★', { class: 'dr-star', classWhen: { lit: star.field('lit').truthy() } }))), ), c.row({ class: 'dr-rate', part: 'rating', align: 'baseline', gap: 1 }, c.text(c.bind('rating'), { as: 'strong', class: 'dr-rating' }), c.text(c.bind('ratingUnit'), { as: 'small', class: 'dr-unit' })), ); } ``` **The curve.** The list sets `--row-distance` on each row: how many rows separate it from the centre row (negative above). The centre is the chosen difficulty, else the chosen set, else the middle row of the list window. The theme reads it with `var()`. ```css /* Recipe: slanted cards. The list's rows carry `--row-distance`: their number of rows from the selected one (negative above). A row slides right with its square, up to a bound, and fades, so the list curves around the selection. The selected row (`data-active`) stays left and fully opaque. */ .rack [data-pvng-list] { overflow-x: hidden; } .rack [data-contract='library.setCard'], .rack [data-contract='library.chartRow'] { padding: 0; gap: 0; overflow: visible; --plate: transparent; --edge: transparent; transform: translateX(min(calc(var(--row-distance) * var(--row-distance) * 60px), 64px)); opacity: calc(1 - min(calc(var(--row-distance) * var(--row-distance) * .04), .5)); } .rack [data-contract='library.setCard'][data-active] { transform: translateX(-26px); opacity: 1; } .rack [data-contract='library.chartRow'][data-active] { transform: translateX(-30px); opacity: 1; } ``` **The slanted shape.** ```css /* The set card. `--set-color` is the colour of the set's hardest difficulty: a variable of the game's row, readable here. */ .sc { position: relative; flex: 1; display: flex; align-items: center; min-width: 0; height: 100%; padding: 0 var(--pv-s5) 0 var(--pv-s6); } .sc-art { position: absolute; inset: 0; z-index: -1; overflow: hidden; background: var(--pv-plate-raised); clip-path: polygon(24px 0, 100% 0, 100% 100%, 0 100%); border-left: 3px solid var(--set-color); } ``` **Why it is written this way** - The curve uses the *square* of the distance, bounded: `min(…, 64px)` for the slide, `min(…, .5)` for the fade. Near rows barely move, far rows never leave the window or vanish. - The selected row has its own rule through `[data-active]`, which the game sets on the open or selected card. It stays left and fully opaque. - The recipe changes the screen only to give the library column the class `rack`. A `theme.css` selector must start with a class of the theme, so a game element such as `[data-contract='library.setCard']` is reached through a class of the theme placed above it. - A dot's colour travels as a variable of the theme: the node sets `--tpl-chip` with `vars`, and the stylesheet reads `var(--tpl-chip)`. `vars` accepts only the variables of the screen or `--tpl-*`. - The game's variables `--set-color` (the hardest difficulty's colour) and `--difficulty-color` are read with `var()`. The theme writes no colour of its own for them. - `part: 'artist'` keeps Ctrl+click on the artist working: the game filters by that part. A face that does not set the part only loses that gesture. - `[data-pvng-list] { overflow-x: hidden }` stops the slid rows from adding a horizontal scrollbar. **Limits to know.** A face refuses `button`, `toggle`, `dropdown`, a `slot` that mounts another contract, and any output call: the message is `a button is not allowed in library.setCard: …` (see [Errors](https://prism.am/dev/md/themes/errors.md#face-with-button)). A `filter` or a `box-shadow` on the **same element** as a `clip-path` is cut by it, so the shadow disappears. For a shadow that follows a slanted shape, put `filter: drop-shadow(…)` on a **parent** of the clipped element and the `clip-path` on the child. In `tokens.css`, `--pv-plate-filter` does the same for the plates and takes a `drop-shadow`. ## Poster and scrim {#poster-scrim} From `content/themes/cinema/`. Folder: `content/examples/themes/recipe-poster-scrim/`. ![The poster and scrim recipe: the map's picture fills the window, a scrim darkens the foot, the title is large and serif over a glass sheet, the list is a slim column.](https://prism.am/dev/img/themes/recipe-poster-scrim.png) **What it does.** The selected map's picture is the whole page (the game draws it behind the menus). The theme adds a **scrim**, a gradient from clear to the page colour that darkens the foot of the poster, sets the heading as a large serif title, and puts the tabs and their panel on a sheet of glass. The list becomes a slim column on the right. **The scrim is a pseudo-element.** ```css /* The poster rests on the foot of the window. Its scrim is a pseudo-element: a gradient from clear to the page colour, behind everything the poster holds. `z-index: 0` on a positioned box makes it a stacking context, so the scrim's negative z-index stays inside the poster. */ .poster { position: relative; z-index: 0; display: flex; flex-direction: column; justify-content: flex-end; gap: var(--pv-s4); min-width: 0; min-height: 0; } .poster::before { content: ''; position: absolute; inset: -40px -24px 0 -24px; z-index: -1; pointer-events: none; background: linear-gradient(180deg, transparent 0%, color-mix(in srgb, var(--pv-bg) 55%, transparent) 45%, color-mix(in srgb, var(--pv-bg) 92%, transparent) 100%); } ``` **The glass sheet** is a translucent panel with a blurred backdrop. ```css /* The glass sheet: a blurred, translucent panel. `backdrop-filter` is in the allowed list (blur and saturate only). */ .sheet { flex: 0 1 46%; min-height: 0; padding: 0; background: color-mix(in srgb, var(--pv-bg) 55%, transparent); border-top: 1px solid var(--pv-line); backdrop-filter: blur(14px) saturate(1.2); } ``` **The picture stays.** The scrim is the theme's own box over the poster, but the game's picture behind the menus is governed by two tokens, and the recipe keeps them light on purpose. ```css /* The picture behind the menus is dimmed a little, never hidden: the validator keeps at least a fifth of its light on screen. */ --pv-art-filter: saturate(1.05) brightness(.9); --pv-shade: linear-gradient(180deg, rgb(0 0 0 / .1), rgb(0 0 0 / .3)); ``` **Why it is written this way** - The scrim sits **behind** the poster's content with `z-index: -1`. `z-index: 0` on the positioned poster makes it a stacking context, so the negative index stays inside the poster instead of going behind the page. - A scrim made of a gradient and no extra node: `::before` takes `content: ''` and is written last in its selector, once. - The heading's plates are made transparent with `--plate: transparent` on `[data-edge]`, so the serif title stands on the scrim. The game's heading is not replaced. - Play moves into a bar at the foot of the poster with `slot('footer')`. Play can move; the footer place is required, so it can never disappear. - `--pv-layout-tabs: top` puts the tab bar above the panel inside `selected-body`. The theme asks the game for a layout with a word of a closed list; it writes no CSS for it. - The nothing-selected state places the heading alone in the same spot, large: it is the invitation to pick a map. **Limits to know.** The game's map picture must keep at least 20 % of its light on screen, averaged over the window. Each `--pv-shade` gradient may cover at most 90 % on average, so an opaque flat colour is refused. In `--pv-art-filter`, `brightness()` may not go below 0.25, `opacity()` below 0.4, `contrast()` below 0.5 (`crates/themes/src/artwork.rs`). `backdrop-filter` takes only `blur` and `saturate`. `z-index` runs from −50 to 50. A pseudo-element takes a `content` string of at most 80 characters, without `\`. ## Terminal list {#terminal-list} From `content/themes/hack/`. Folder: `content/examples/themes/recipe-terminal-list/`. ![The terminal list recipe: monospace everywhere, bracketed buttons, one line per map.](https://prism.am/dev/img/themes/recipe-terminal-list.png) **What it does.** A phosphor-terminal look: monospace text, sharp rectangles, bracketed buttons, and one line per set in the list, like a directory listing. **Layout words do half the work.** The tokens choose the shape of rows, buttons and tabs by a word of a closed list. No selector is written for it. ```css /* Layout words: dense spacing, text rows, bracketed buttons. */ --pv-layout-density: dense; --pv-layout-rows: text; --pv-layout-buttons: bracket; --pv-layout-tabs: top; ``` **One line per set.** The face of the set card is a single row; a grid of four columns in `theme.css` aligns title, artist, rating and tags. ```ts theme // The set card as one line: the title (with NEW when the set is new), the artist, the rating and the difficulties. // `part` names the parts the game hangs gestures on (Ctrl+click on the artist filters by it). The game's marks (goal, missing file) stay available as slots. function setCard(c: SetCard): ThemeNode { return c.row( { class: 'sc', align: 'center' }, c.row( { class: 'sc-name', align: 'center', gap: 2 }, c.slot('goal'), c.text(c.bind('title'), { as: 'strong', part: 'title', class: 'sc-title' }), c.when(c.field('newText').truthy(), c.text(c.t('library.new'), { class: 'sc-new' })), c.slot('missing'), ), c.text(c.bind('artist'), { as: 'small', part: 'artist', class: 'sc-artist' }), c.text(c.bind('rating.range'), { part: 'rating', class: 'sc-rating' }), tags(c), ); } ``` **Brackets and cursor come from pseudo-elements.** ```css /* The cursor: a `>` before the title of the open or selected line (the game marks it `data-active`), and a dim one under the pointer. */ .sc-name::before { content: '>'; flex: none; width: 1ch; color: var(--pv-accent); opacity: 0; } .crate [data-contract='library.setCard']:hover .sc-name::before { opacity: .45; } .crate [data-contract='library.setCard'][data-active] .sc-name::before { opacity: 1; } ``` ```css /* A tag is the difficulty's rating between brackets, in the difficulty's colour. */ .sc-tags { justify-content: flex-end; min-width: 0; overflow: hidden; } .tag { flex: none; font-size: var(--pv-fs-xs); color: var(--tpl-chip); } .tag::before { content: '[ '; color: var(--pv-text-3); } .tag::after { content: ' ]'; color: var(--pv-text-3); } ``` **Why it is written this way** - `--pv-layout-buttons: bracket` draws every button as `[ ]` in the game's own components. The theme does not restyle buttons; it picks a word. The same holds for `--pv-layout-rows: text` (a row of a table) and `--pv-layout-density: dense`. - Each tag is the rating between two brackets written with `::before` and `::after`. The game's selected line is marked `data-active`, which the stylesheet uses for the `>` cursor. - Text from `content` is **decoration** that screen readers may read. Never put information in it: the brackets and the cursor are decoration, the rating is a real text node. - The mono stack ends with a generic family (`monospace`), as a font token requires. - The recipe does not use `--pv-layout-focus: blink`: it loops forever, which is an infinite animation (see [Errors](https://prism.am/dev/md/themes/errors.md#css-infinite-animation)). The shipped Hack theme keeps the plain ring too. **Limits to know.** A `--pv-layout-*` token takes one word from its list; any other word, several words, an empty value, a number or a `var()` is refused. A pseudo-element is allowed once, at the end of a selector, never after another pseudo-element. Font stacks have 1 to 8 families and end with a generic one. ## Live bars {#live-bars} From `content/themes/stage/`. Folder: `content/examples/themes/recipe-live-bars/`. ![The live bars recipe: an equalizer band under the heading of the selected map.](https://prism.am/dev/img/themes/recipe-live-bars.png) **What it does.** A band of bars under the heading of the selected map. Each bar has two heights from 4 to 100: `level`, the note density of the map, and `live`, the same bar as the menu music plays it (the game's spectrum, folded into the same bars). **Bind `live` and you get the music.** The theme gives each bar's `live` to the stylesheet as a variable. ```ts theme // The band: a row of bars, drawn only when the map has an equalizer (a playlist has none). `data-listening` is set while the music drives the bars, // so the stylesheet can light them. `each` repeats `bar` for every element of the list. function equalizer(c: Screen): ThemeNode { return c.when(c.field('map.equalizer').truthy(), c.row({ class: 'eq', role: 'presentation', data: { listening: c.bind('map.listening') } }, c.each('map.equalizer', bar))); } // One bar: an empty box that hands its live height to the stylesheet as a variable of this theme, `--tpl-live` (a number from 4 to 100). function bar(item: BarItem): ThemeNode { return item.box({ class: 'eq-bar', vars: { '--tpl-live': item.bind('live') } }); } ``` **Scale, do not resize.** ```css /* A bar is always full height and is SCALED: `transform` does not lay the page out again, where `height` would, thirty times a second. `--tpl-live` runs from 4 to 100. There is NO `transition` here: the page has already eased the levels, and a transition makes the browser restyle every bar on every frame for nothing the eye can see. */ .eq-bar { flex: 1 1 0; min-width: 2px; height: 100%; opacity: .75; transform-origin: bottom; transform: scaleY(calc(var(--tpl-live) / 100)); background: linear-gradient(180deg, var(--pv-accent), color-mix(in srgb, var(--pv-accent) 20%, transparent)); } ``` **Why it is written this way** - A theme that binds `live` (or `map.listening`) is enough: the screen then asks the game for the spectrum, only while a map is shown and the player has not asked for less motion. A theme that does not bind it costs nothing: no request, no analysis. - The bar is full height and **scaled**: `transform: scaleY(…)` does not lay the page out again, where `height` would, about thirty times a second. - There is **no `transition`**. The page already eases the heights (a bar rises fast, falls slowly), and a transition would make the browser restyle every bar on every frame for nothing visible. - There is **no animation at all**, so nothing runs when the screen is at rest. An equalizer built from `@keyframes` with `infinite` would repaint the page every frame; the validator warns about it (see [Errors](https://prism.am/dev/md/themes/errors.md#css-infinite-animation)). - Without music (menu music off, loading, paused for the settings, or during a play), `live` equals `level`: the bars glide to the density and stay there. For a player who asks for less motion the page never asks for the spectrum: the bars are still. - `data-listening` is set while the music drives the bars, so the stylesheet can make them brighter. - `vars` is limited to the variables of the screen and `--tpl-*`, at most 8 entries per node. **Limits to know.** The cost is one update of the screen input per spectrum frame, about thirty a second, and only while the music plays; at rest nothing runs. The bars come from one `each`: a single node in the template, however many bars the game gives. The tokens of the map picture and the filters of `theme.css` have their own limits (see [limits](https://prism.am/dev/md/themes/cookbook.md#limits)). ## Settings rail {#settings-rail} From `content/themes/stage/`. Folder: `content/examples/themes/recipe-settings-rail/`. ![The settings rail recipe: the Settings window with the title, the search and the categories in a left column, the buttons at its foot, the panel on the right.](https://prism.am/dev/img/themes/recipe-settings-rail.png) **What it does.** The Settings window as a rail: the title with the count of changed settings, the search, the list of categories and the window's buttons in a column on the left, the panel of the open category on the right. **A second screen.** The window is the screen `screen.settings`, with its own contract. The game keeps the modal dialog: the focus trap, Escape, giving focus back. The template composes **what is inside it** from places: it draws neither a setting row nor a control. ```ts theme // The window: a left column (the rail) and a right column (the panel), side by side. Every place the contract requires is placed: // `title`, `search`, `actions`, `close`, `notices`, `rail` and `panel`; `hints` (the keyboard hints) is the only optional one. function settingsScreen(c: Settings): ThemeNode { return c.row({ as: 'section', class: 'win' }, rail(c), main(c)); } // The left column: the title with, under it, how many settings differ from the shipped ones, then the search, the list of categories, and at the foot the window's buttons. // `changed` is a number of the input of the screen; `c.t` with an argument is the game's translated, pluralised sentence. function rail(c: Settings): ThemeNode { return c.column( { as: 'aside', class: 'side' }, c.column( { class: 'head', gap: 1 }, c.slot('title'), c.when(c.field('changed').gt(0), c.text(c.t('settings.changed_count', { count: c.bind('changed') }), { as: 'small', class: 'changed' })), ), c.box({ class: 'find' }, c.slot('search')), c.slot('rail'), c.row({ class: 'buttons', align: 'center', gap: 1 }, c.slot('actions'), c.slot('close')), ); } // The right column: the notices (the game's messages, an import review), the panel of the open category, the keyboard hints. function main(c: Settings): ThemeNode { return c.column({ class: 'main' }, c.slot('notices'), c.slot('panel'), c.slot('hints')); } ``` **Reaching the game's parts.** ```css .side { flex: none; width: 280px; min-height: 0; gap: var(--pv-s3); } .main { flex: 1; min-width: 0; min-height: 0; } /* The game's own parts are reached by their `data-part` marks, never by their classes. The panel is the part that scrolls: it takes the room of the column. */ .main [data-part='panel'] { flex: 1; min-width: 0; } .side [data-part='rail'] { flex: 1; min-height: 0; } ``` **Why it is written this way** - Every place the screen requires is placed; only the optional ones may be left out. A missing required place is refused (see [Errors](https://prism.am/dev/md/themes/errors.md#ts-missing-slot)). The list of places, with their required flag, is on the [contracts](https://prism.am/dev/md/themes/contracts.md) page. - `changed` is a number of the screen's input. `c.when(c.field('changed').gt(0), …)` shows the sentence only when something changed; `c.t('settings.changed_count', { count: c.bind('changed') })` is the game's translated, pluralised sentence. - The panel and the rail are reached by `data-part` marks, never by classes of the game: `[data-part='panel']`, `[data-part='rail']`. - The tokens choose the look of the categories (`--pv-layout-settings: rail`: a rounded vertical list) and of the groups of rows (`--pv-layout-groups: inset`). - The template calls no output: closing, searching and choosing a category are done by the components placed in `close`, `search` and `rail`. A `button` that does call one of the screen's outputs must name an output that the contract lists, with its arguments. **Limits to know.** A `button` in a screen template may call only an output that the screen lists. A name outside the list is refused, with the list of the screen's own outputs in the message (see [Errors](https://prism.am/dev/md/themes/errors.md#ts-unknown-output)). ## Footer strip {#footer-strip} Folder: `content/examples/themes/recipe-footer-strip/`. No shipped theme templates the footer: this recipe shows **component templates**. Its score card follows the face written by `content/themes/stage/`, simplified. **What it does.** Two templates under `components`, where the other recipes write screens: the strip under the selected map (two drop-down lists, a refusal line and the main button), and one score of the leaderboard as a face with a grid, a meter and formatted numbers. **The strip.** The two choosers on the left, a spacer, the refusal line only when there is one, then the Play button, or the two buttons of a playlist. ```ts theme // The strip under the selected map: the two choosers on the left, then the refusal line (only when no judgement can be used), then the main button. // The contract REQUIRES its `confirm` output to be called by a button, so a theme can move Play and restyle it, never remove it. function footer(c: Footer): ThemeNode { const playlist = c.field('state').in(['playlistReady', 'playlistBlocked']); return c.row( { class: 'strip', align: 'center', gap: 3 }, chooser(c, 'rating'), chooser(c, 'judgement'), c.spacer(), c.when(c.field('refusal').truthy(), c.text(c.bind('refusal'), { class: 'refusal', part: 'refusal', role: 'status' })), // A map seen from a playlist has no Play: the playlist is what plays. Otherwise a playlist gets its two buttons, a map gets one. c.when(c.field('state').ne('mapNoPlay'), c.when(playlist, playlistButtons(c), playButton(c))), ); } ``` **A drop-down list.** The options come from a list of the input; the value is the one in force. Picking an entry calls an output with the entry's value appended to the arguments. ```ts theme // A drop-down list: the options come from the input (`rating.options`), the value is the one in force, and picking an entry calls the output // `rating.pick` (or `judgement.pick`) with the entry's value appended to the arguments. function chooser(c: Footer, which: 'rating' | 'judgement'): ThemeNode { return c.dropdown({ class: 'chooser', part: which, label: c.t(which === 'rating' ? 'rating.label' : 'judgement.title'), value: c.bind(`${which}.value`), options: `${which}.options`, displayValue: which === 'judgement' ? c.bind('judgement.label') : undefined, ariaLabel: which === 'judgement' ? c.bind('judgement.ariaLabel') : c.t('rating.label'), on: c.on.pick(`${which}.pick`), }); } ``` **Play can move, never vanish.** The contract requires its `confirm` output to be called by a button. ```ts theme // The main button of a map. It is off in the two states where it cannot start, and the reason is a line of text it points at (`describedBy`), so it stays readable. function playButton(c: Footer): ThemeNode { const off = c.field('state').in(['mapBlocked', 'mapRefused']); return c.row( { class: 'go-line', align: 'center', gap: 2 }, c.when(c.field('state').eq('mapBlocked'), c.text(c.bind('reason.text'), { class: 'reason', part: 'reason' })), c.button({ variant: 'primary', class: 'go', part: 'play', label: c.bind('play.label'), disabled: off, classWhen: { off }, describedBy: 'reason', on: c.on.press('confirm') }), ); } ``` **Why it is written this way** - The keys of `components` are contract names. Each template is validated alone against its contract, and a refused one is replaced by the default. - `confirm` is a **required** output of the footer. A template without a `button` that calls it is refused (see [Errors](https://prism.am/dev/md/themes/errors.md#ts-required-output-unbound)). - A `dropdown` is the game's own list and has no children: you give it the path of its options, its value, and an output for `on.pick`. - `disabled` takes a **condition**, not a boolean, and `describedBy` names a part of the contract: the reason text is what the disabled button points at, so it stays readable. - States are read with `c.field('state')` and `.eq`, `.ne` or `.in([...])`; conditions combine with `.and()`, `.or()` and `.not()`. - The score card is a **face**: no button, no output. The game keeps its plate and the buttons beside it, and `c.slot('tiers')` places a widget of the game. The formatters `c.fmt.rate`, `count`, `percent` and `fixed` write numbers; `percent` expects a number that is already a percentage (97.4 gives `97.40%`). **Limits to know.** A grid has at most 12 tracks. The arguments of an output are checked in order and by type: a wrong count reads `<output> takes <n> arguments (…) and <m> are given`. A component template cannot call an output of a screen. ## Combining recipes {#combining} A theme may hold several ideas, each as in its recipe. Two points keep the result valid. - **One template per screen.** A screen is replaced as a whole, so two recipes that both change `screen.library` must be merged into one function. Faces and component templates are separate and add up: the slanted cards and the terminal list both write `library.setCard`, so a theme picks one. - **Class names are one namespace per theme.** Two recipes that define `.panel` or `.head` differently collide when merged. Rename one. ## Limits at a glance {#limits} | What | Limit | Where it is enforced | | --- | --- | --- | | `theme.ts` source | 128 KiB | `crates/modding/src/theme.rs` (`ThemeScriptLimits`) | | `theme.ts` run | 500 ms, 16 MiB, 4 000 nodes built, 1 MiB of JSON | `crates/modding/src/theme.rs` | | Validated templates | 24 levels deep, 1 500 nodes per theme, 64 templates, 200 characters per text, 64 children per node, 8 classes per node, 8 entries in `data` or `vars`, 12 grid tracks | `crates/themes/src/template/mod.rs` | | `theme.css` | 256 KiB, 2048 rules, 40 declarations per rule, `z-index` from −50 to 50 | `crates/themes/src/stylesheet.rs` | | `tokens.css` | 64 KiB, 200 declarations, 600 characters per value, 2 `@media` blocks | `crates/themes/src/css.rs`, `crates/themes/src/grammar.rs` | | Pictures | 4 MiB each, 512 per theme | `crates/themes/src/library.rs` | | Map picture | at least 20 % visible; a `--pv-shade` layer at most 90 %; `brightness()` ≥ 0.25, `opacity()` ≥ 0.4, `contrast()` ≥ 0.5 | `crates/themes/src/artwork.rs` | | Motion | no infinite animation (a warning) | `crates/themes/src/stylesheet.rs` | ===== Page: Reading theme errors Address: https://prism.am/dev/themes/errors/ Derived from: crates/modding/examples/check_theme.rs, crates/themes/src/library.rs, crates/themes/src/template/validate.rs, crates/themes/src/stylesheet.rs, crates/themes/src/css.rs, crates/themes/src/grammar.rs, crates/themes/src/artwork.rs, crates/themes/src/api.rs, crates/modding/src/theme.rs, content/examples/themes-invalid/ # Reading theme errors How to run the checker, how to read a message, what each kind of problem removes, and a catalogue of the common errors with their fix. A theme that fails is never silent. The game tells you which file, where in it, and why, in plain words. This page shows how to run the checker, how to read what it prints, and what each kind of problem costs you. Then it walks through fourteen real mistakes, each from a folder you can open and check yourself. ## Run the checker {#running-check} The checker is the game's own loading code, run on a folder, with no game window: ```bash cargo run -p modding --example check_theme -- path/to/themes ``` The argument is a folder that **holds** theme folders (`<data>/themes`, or a working copy), not a theme folder itself. With no argument it checks the game's own themes in `content/themes`. It runs the same steps as the game: the manifest, `tokens.css`, `theme.css`, then `theme.ts` on the script engine under its budgets, and the tree it returns validated against the contracts. ```text <folder>: <n> theme(s) loaded (theme API <version>) <id> <n> template(s), <n> byte(s) of theme.css problem: "<id>": <file>: <where>: <reason> ``` It prints one line for each theme that loaded, then one `problem:` line for each problem, and exits with code 1 if there is any problem, **warnings included**. A theme that failed to load is missing from the first list and appears only in a `problem:` line. A theme that loaded with `0 template(s)` while its `theme.ts` has a problem has lost its templates. Run it after every change. The invalid examples of this page live in `content/examples/themes-invalid/` and can be checked the same way: `check_theme -- content/examples/themes-invalid` prints every message below. ## Read a message {#reading-errors} A message names the theme, then the **file**, then the **place** in that file, then the **reason** in full words. Read it left to right. ```text "<theme>": <file>: <where>: <reason> ``` | Part | What it is | | --- | --- | | `"<theme>"` | The id of the theme, which is its folder name. | | `<file>` | `theme.json`, `tokens.css`, `theme.css` or `theme.ts`. Open that file. | | `<where>` | For the CSS files, `line N`. For the manifest, the field. For `theme.ts`, the template and the node chain (below). | | `<reason>` | What is wrong, and almost always what is allowed instead. | A problem in the manifest, `tokens.css` or `theme.css` is reported **one at a time**: the first problem stops the file. Fix it and run the checker again. The templates of `theme.ts` are different: every template is checked on its own, and one template can report several problems at once. ### The anatomy of a `theme.ts` message {#template-anatomy} A message about a template reads in six steps. Here is one, from the case [ts-unknown-output](https://prism.am/dev/md/themes/errors.md#ts-unknown-output): ```text "ts-unknown-output": theme.ts: screen.library › box.song-select › button.back (on.press › output): "back" is not an output of screen.library (outputs: <the outputs of the screen>) [at children[0]/on.press/output] ``` | Part | In the example | Meaning | | --- | --- | --- | | Template | `screen.library` | The screen, or the contract of a component, that holds the problem. | | Node chain | `box.song-select › button.back` | The nodes from the root to the one at fault. A node is its kind, a dot, and its first class (`box.song-select`); a `slot` reads `slot footer`; a node with no class reads as its kind alone (`when`, `text`). | | Attribute | `(on.press › output)` | Which part of the node is at fault, when it is not the node itself (`class[0]`, `label › bind`). It is absent when the whole node is wrong. | | Reason | `"back" is not an output of screen.library (…)` | What is wrong. The list in parentheses is read from the contract, so it is always the current one. | | Raw path | `[at children[0]/on.press/output]` | The same place as a path in the raw tree, for tools. You do not need it to fix the problem. | A message with no node chain is about the template as a whole (a required place that is missing, for example). ## Where you see them {#where} The same line appears in four places. - **The checker**, as above. - **Skins**, in the Interface picker: a list under the theme cards, named *Theme folders that cannot be used*. It holds every problem of every folder, warnings and refused templates included. - **The game log**, one line for each problem, each starting with `Themes: `. - **On screen, while you play**: a notice, only for a template that fails while it is being drawn (see below). ## What a problem removes {#consequences} | Where the problem is | What happens to the theme | | --- | --- | | The folder name, `theme.json`, `tokens.css`, `theme.css` (an error) | The theme is **not loaded**. It is not in the Interface list. The line in the list and in the log says why. | | `theme.css`, a warning (an infinite animation) | The theme loads. The warning is listed, and the checker exits with code 1. | | `theme.ts`, the script fails (an exception, a budget exceeded, the time limit, `defineTheme` never called) | The theme loads with its tokens, CSS and images, **without any template**: the game's default templates are used. | | `theme.ts`, one template is refused | The theme loads. **Only that template** is removed: the default one for it takes over. The other templates stay. | | A template fails **while drawing** | The template is set aside for the rest of the session and the default one draws at once. See the next section. | ### The fallback at run time {#runtime-fallback} A template that passes the checker can still fail while it draws, for a reason the validator cannot see. The game then sets that template aside for the whole session, draws the default one in its place, and tells the player once for each contract and session: ```text The template of "<contract>" in the interface "<theme>" cannot be drawn; the default one is used. ``` This is the translation key `theme.template_failed`. It is a safety net, not a way to test: a theme that triggers it has a bug to report. ## The catalogue {#catalogue} Each entry below is a folder in `content/examples/themes-invalid/<case>/`. The tests check that the checker reports, for each folder, the text written in its `expect.txt`. The messages are shown as the game prints them. Parts between `<` and `>` are filled from the contracts and change when the contracts do. | Case | File | The theme is | | --- | --- | --- | | [api-too-new](https://prism.am/dev/md/themes/errors.md#api-too-new) | `theme.json` | not loaded | | [api-needs-version-2](https://prism.am/dev/md/themes/errors.md#api-needs-version-2) | `theme.ts` | loaded, without the template | | [token-unknown](https://prism.am/dev/md/themes/errors.md#token-unknown) | `tokens.css` | not loaded | | [token-bad-value](https://prism.am/dev/md/themes/errors.md#token-bad-value) | `tokens.css` | not loaded | | [artwork-hidden](https://prism.am/dev/md/themes/errors.md#artwork-hidden) | `tokens.css` | not loaded | | [css-element-selector](https://prism.am/dev/md/themes/errors.md#css-element-selector) | `theme.css` | not loaded | | [css-property-not-allowed](https://prism.am/dev/md/themes/errors.md#css-property-not-allowed) | `theme.css` | not loaded | | [css-infinite-animation](https://prism.am/dev/md/themes/errors.md#css-infinite-animation) | `theme.css` | loaded (warning) | | [script-timeout](https://prism.am/dev/md/themes/errors.md#script-timeout) | `theme.ts` | loaded without templates | | [ts-unknown-path](https://prism.am/dev/md/themes/errors.md#ts-unknown-path) | `theme.ts` | loaded, one template removed | | [ts-unknown-output](https://prism.am/dev/md/themes/errors.md#ts-unknown-output) | `theme.ts` | loaded, one template removed | | [ts-class-not-declared](https://prism.am/dev/md/themes/errors.md#ts-class-not-declared) | `theme.ts` | loaded, one template removed | | [ts-missing-slot](https://prism.am/dev/md/themes/errors.md#ts-missing-slot) | `theme.ts` | loaded, one template removed | | [ts-required-output-unbound](https://prism.am/dev/md/themes/errors.md#ts-required-output-unbound) | `theme.ts` | loaded, one template removed | | [face-with-button](https://prism.am/dev/md/themes/errors.md#face-with-button) | `theme.ts` | loaded, one template removed | The files below are invalid on purpose, so they are shown as plain text. ### api-too-new {#api-too-new} The manifest asks for a theme API that the game does not speak. ```text "tokens": "tokens.css", "localized": {}, "themeApi": 99 } ``` ```text "api-too-new": theme.json: themeApi 99 is newer than this game speaks (theme API <n>): update the game, or use a version of the theme written for API <n> ``` **Cause.** `themeApi` is the version of the theme contract the theme was written for. This game speaks version `<n>` and refuses a newer one in one sentence, instead of failing later on a node or a property it cannot know. A value that is not a whole number from 1 is refused too, with what was found. **Fix.** Write the version the game speaks, or leave the field out (it means 1). If the theme really needs the newer contract, update the game. ### api-needs-version-2 {#api-needs-version-2} The manifest declares theme API 1 (`"themeApi": 1`) and `theme.ts` templates a screen that theme API 2 added. ```text "themeApi": 1, ``` ```text defineTheme({ screens: { settings: settingsScreen } }); ``` ```text "api-needs-version-2": theme.ts: screen.settings: requires themeApi 2: the screen "screen.settings" was added in theme API 2 and this theme declares themeApi 1; set "themeApi": 2 in theme.json once the theme is written for version 2 ``` **Cause.** A theme that declares an older `themeApi` keeps loading, but the screens, faces and `"accent": "map"` that a later version added are refused for it, one notice each, so a theme written for version 1 never meets a contract it was not written for. The rest of the theme (tokens, CSS, its other templates) works, and the Settings window keeps the game's own layout. **Fix.** Write `"themeApi": 2` in `theme.json` once the theme is written for version 2. For a face the notice says `the face contract "catalog.card"` instead of `the screen`; for `accent` it names `accent "map"`. ### token-unknown {#token-unknown} ```text :root { --pv-color-scheme: dark; --pv-bg: #0b1320; --pv-text: #eef5fb; --pv-acent: #2dd4bf; } ``` ```text "token-unknown": tokens.css: line 5: --pv-acent is not a theme token ``` **Cause.** A typo: the name `--pv-acent` is not in the contract. Only the tokens of the contract are accepted, and the file is refused at the first one that is not. **Fix.** Write `--pv-accent`. The complete list of names is on the [tokens](https://prism.am/dev/md/themes/tokens.md) page. ### token-bad-value {#token-bad-value} ```text :root { --pv-color-scheme: dark; --pv-bg: #0b1320; --pv-text: #eef5fb; --pv-accent: #12345; } ``` ```text "token-bad-value": tokens.css: line 5: --pv-accent: a hex colour has 3, 4, 6 or 8 digits ``` **Cause.** `#12345` has five digits. Each token has a type (colour, length, font, and so on) and a value that does not fit the type of its token is refused with the rule it broke. **Fix.** Write a colour of 3, 4, 6 or 8 digits, such as `#123456`. The type of each token and its range are on the [tokens](https://prism.am/dev/md/themes/tokens.md) page. ### artwork-hidden {#artwork-hidden} ```text :root { --pv-color-scheme: dark; --pv-bg: #0b1320; --pv-text: #eef5fb; --pv-accent: #2dd4bf; /* An opaque black layer over the whole picture: the map would disappear. */ --pv-shade: linear-gradient(180deg, rgb(0 0 0 / 1), rgb(0 0 0 / 1)); } ``` ```text "artwork-hidden": tokens.css: the map picture must stay visible: a --pv-shade layer covers 100% of the picture on average; at most 90% ``` **Cause.** The image of the map behind the menus is part of the game's identity. A theme may tint it (`--pv-shade`), dim it, blur it or recolour it (`--pv-art-filter`), never hide it. An opaque layer covers 100 % of it. The rules (`crates/themes/src/artwork.rs`): at least 20 % of the picture's light must reach the screen on average, a `--pv-shade` layer covers at most 90 % on average, and in `--pv-art-filter` `brightness()` stays at or above 0.25, `opacity()` at or above 0.4 and `contrast()` at or above 0.5. **Fix.** Give the layer an opacity below 1 (`rgb(0 0 0 / .5)`), or remove the layer. When the total is too low, the message gives the share that is left: `the map picture must stay visible: --pv-shade and --pv-art-filter leave <n>% of it on average; at least 20% is required (a theme may tint, dim or blur it, never hide it)`. ### css-element-selector {#css-element-selector} ```text /* Only the theme's own classes can be selected: `button` is an element. */ button { color: var(--pv-accent); } ``` ```text "css-element-selector": theme.css: line 2: the selector "button": element selectors are not allowed: select the theme's classes ``` **Cause.** `theme.css` styles only the classes of the theme. A selector like `button` would reach into the rest of the game, so the validator refuses every element selector, `*`, `#id`, `:root` and `body`. **Fix.** Give a node of `theme.ts` a class and select it with `.name`. To reach an element of the game, use a class of the theme and then its `data-*` mark: `.name [data-part='play']`. A selector must start with a class of the theme. ### css-property-not-allowed {#css-property-not-allowed} ```text .box { isolation: isolate; } ``` ```text "css-property-not-allowed": theme.css: line 1: isolation: this property is not allowed in theme.css ``` **Cause.** `theme.css` accepts the properties of an allow-list, with typed values. `isolation` is not in it. **Fix.** Use a listed property. The list, and the forms each one accepts, is on the [CSS allow-list](https://prism.am/dev/md/themes/css-allowlist.md) page. To get the effect of `isolation`, a positioned box with `z-index: 0` also makes a stacking context. ### css-infinite-animation {#css-infinite-animation} ```text @keyframes pulse { from { opacity: .4; } to { opacity: 1; } } @media (prefers-reduced-motion: no-preference) { .glow { animation: pulse 1s ease-in-out infinite alternate; } } ``` ```text "css-infinite-animation": theme.css: warning: line 3: an infinite animation repaints the page every frame, even on an idle screen; play it a few times (a finite `animation-iteration-count`), or once per selection under `[data-entering]` ``` **Cause.** An animation that never stops repaints its region on every frame, even when nothing else moves. It was measured in the game's web view: fifteen equalizer bars and two glows cost about three processor cores on a menu left alone. The checker reports any line that has the word `infinite`. This one is a **warning**: the theme still loads, but the checker exits with code 1 until you fix it. **Fix.** Play decorative motion once for each selection by hooking it to `[data-entering]` (give the node `data: { entering: c.bind('selection.entering') }`), or on `:hover` and `:focus-visible`, with a finite count. Put every moving animation inside `@media (prefers-reduced-motion: no-preference)`, as this example does. The [live bars](https://prism.am/dev/md/themes/cookbook.md#live-bars) recipe shows a moving element with no animation at all. ### script-timeout {#script-timeout} ```text // The script runs once under a 500 ms budget: a loop that never ends is stopped. defineTheme({ screens: {} }); while (true) {} ``` ```text "script-timeout": theme.ts: interrupted ``` **Cause.** `theme.ts` runs once, under a budget of 500 ms, 16 MiB of memory, 128 KiB of source, 4 000 nodes built and 1 MiB of JSON (`crates/modding/src/theme.rs`). A loop that never ends is stopped, and the engine reports it as `interrupted`, followed by one or more `at …` lines (the stack). A script that throws gives its own message in the same place. **Fix.** Remove the unbounded loop. The script only builds a tree; plain loops over small lists are enough. This error removes **every template** of the theme, which keeps its tokens, CSS and images. ### ts-unknown-path {#ts-unknown-path} ```text function libraryScreen(c: Screen): ThemeNode { return c.box( { class: ['song-select', 'pv-screen'] }, // `map.titel` is a typo of `map.title`: a type error in the editor, a refusal in Rust. c.text(c.bind('map.titel'), { class: 'title' }), c.slot('intent'), c.slot('toolbar'), c.slot('search'), c.slot('list'), c.slot('playlistSearch'), c.slot('playlists'), c.slot('visualizer'), c.slot('header'), c.slot('tabs'), c.slot('panels'), c.slot('footer'), ); } ``` ```text "ts-unknown-path": theme.ts: screen.library › box.song-select › text.title (value › bind): the path "map.titel" is not in the screen: no field "titel" in "map" (fields: <the fields of map>) [at children[0]/value/bind] ``` **Cause.** `bind` reads a path of the input of the screen, and `map.titel` is a typo of `map.title`. With the typed `c`, an editor and `tsc` flag it before Rust does; this example uses a cast to get past them, so you can read the message. **Fix.** Use a path that the contract lists: the message names the fields found at that level. Every path of every screen and contract is on the [contracts](https://prism.am/dev/md/themes/contracts.md) page. ### ts-unknown-output {#ts-unknown-output} ```text function libraryScreen(c: Screen): ThemeNode { return c.box( { class: ['song-select', 'pv-screen'] }, // "back" is not an output of screen.library (it has drawer.toggle, random, mods.open, settings.open). c.button({ class: 'back', label: 'Back', on: c.on.press('back') }), c.slot('intent'), c.slot('toolbar'), c.slot('search'), c.slot('list'), c.slot('playlistSearch'), c.slot('playlists'), c.slot('visualizer'), c.slot('header'), c.slot('tabs'), c.slot('panels'), c.slot('footer'), ); } ``` ```text "ts-unknown-output": theme.ts: screen.library › box.song-select › button.back (on.press › output): "back" is not an output of screen.library (outputs: <the outputs of the screen>) [at children[0]/on.press/output] ``` **Cause.** A `button` calls an output by name, and the name must be an output of that screen or contract, with its arguments in order and of the right type. `back` is not one. **Fix.** Call an output from the list in the message, or remove the button. A component template cannot call the output of a screen. ### ts-class-not-declared {#ts-class-not-declared} ```text function libraryScreen(c: Screen): ThemeNode { return c.box( { class: ['song-select', 'pv-screen'] }, // `unknown` is not defined in theme.css, and the screen does not list it. c.box({ class: 'unknown' }, c.slot('intent')), c.slot('toolbar'), c.slot('search'), c.slot('list'), c.slot('playlistSearch'), c.slot('playlists'), c.slot('visualizer'), c.slot('header'), c.slot('tabs'), c.slot('panels'), c.slot('footer'), ); } ``` ```text .known { padding: 4px; } ``` ```text "ts-class-not-declared": theme.ts: screen.library › box.song-select › box.unknown (class[0]): the class "unknown" is neither defined by theme.css nor a class of the game here (game classes: <the classes of the screen>) [at children[0]/class[0]] ``` **Cause.** Every `class` is a class of the theme, defined in `theme.css`, or a class of the game that the screen or contract lists. `unknown` is neither. A class in both is refused too, as ambiguous: rename the theme's. **Fix.** Write a rule for `.unknown` in `theme.css` (a class that only names a box still needs a rule), or use a listed class of the game. ### ts-missing-slot {#ts-missing-slot} ```text // The `footer` place (rating, judgement, Play) is missing: a theme can move Play, never remove it. function libraryScreen(c: Screen): ThemeNode { return c.box( { class: ['song-select', 'pv-screen'] }, c.slot('intent'), c.slot('toolbar'), c.slot('search'), c.slot('list'), c.slot('playlistSearch'), c.slot('playlists'), c.slot('visualizer'), c.slot('header'), c.slot('tabs'), c.slot('panels'), ); } ``` ```text "ts-missing-slot": theme.ts: screen.library: the required slot "footer" is not placed (place it with slot("footer"); inside a `when` it counts) ``` **Cause.** A screen template must place every place the screen requires. `footer` holds the rating, the judgement and Play: a theme can move Play, never remove it. This message has no node chain: it is about the template as a whole. **Fix.** Add `c.slot('footer')` somewhere in the template. A place inside a `when` counts. Which places are required is on the [contracts](https://prism.am/dev/md/themes/contracts.md) page. ### ts-required-output-unbound {#ts-required-output-unbound} ```text // The footer contract requires its `confirm` output (Play) to be called by a button. This template only shows text. defineTheme({ components: { 'library.footer': footer } }); function footer(c: Footer): ThemeNode { return c.row({ class: 'foot' }, c.text('Ready')); } ``` ```text "ts-required-output-unbound": theme.ts: library.footer: the required output "confirm" is not bound to any control (a button must call it) ``` **Cause.** A contract can require an output. `library.footer` requires `confirm`, which is Play, and a template that only shows text would make Play disappear. **Fix.** Add a `button` that calls it: `c.button({ label: 'Play', on: c.on.press('confirm') })`. A complete footer, with the two choosers, is in the [footer strip](https://prism.am/dev/md/themes/cookbook.md#footer-strip) recipe. ### face-with-button {#face-with-button} ```text // A face is the inside of a card whose own button, keyboard and menu belong to the game: it cannot hold a button. defineTheme({ components: { 'library.setCard': setCard } }); function setCard(c: SetCard): ThemeNode { return c.row({ class: 'sc' }, c.text(c.bind('title')), c.button({ label: 'Open', on: c.on.press('toggle', c.bind('position')) })); } ``` ```text "face-with-button": theme.ts: library.setCard › row.sc › button: a button is not allowed in library.setCard: the host draws and owns the card's own button, keyboard, menus and actions, a theme draws what is inside it (box, row, column, text, icon, image, meter, slot, each, when) [at children[1]] ``` **Cause.** `library.setCard`, `library.chartRow` and `leaderboard.card` are **faces**: the game owns the card's button, its keyboard, its menus and its actions, and the theme draws only what is inside. A face may not hold a `button`, a `toggle` or a `dropdown`, a `slot` that mounts another contract, or an output call, so it cannot add a tab stop or an action. **Fix.** Remove the button and show the text, an `icon` or a `meter` instead; the card itself is already the game's button. The [slanted cards](https://prism.am/dev/md/themes/cookbook.md#slanted-cards) recipe is a valid face. ## Other frequent messages {#other-messages} Parts between `<` and `>` are the variable part of the message. Messages are in English in every language of the docs. ### The folder and the manifest {#messages-manifest} | Message | Cause and fix | | --- | --- | | `the folder name must be lower-case letters, digits and hyphens (at most 32)` | The folder name is also the id. Rename it: no capitals, no spaces. | | `no theme.json` | The folder has no manifest. | | `theme.json: the id "<id>" must be the folder name` | `id` differs from the folder name. | | `theme.json: <what the JSON reader says>` | The file is not valid JSON, or a required field (`id`, `name`) is missing. | | `name: 1 to 48 characters` | Also `description: 0 to 240 characters`, `author: 0 to 64 characters`. The name is 1 to 48 characters, without control characters. | | `version: letters, digits and . _ + - only (at most 32)` | Fix the version string. | | `order: from 0 to 1000` | `order` is the position in the picker. | | `theme.json: themeApi is the version of the theme contract the theme was written for, a whole number from 1 (this game speaks theme API <n>); found <value>` | `themeApi` is not a whole number from 1 (`"1"`, `0`, `1.5`, `true`). | | `"_base" in <folder>: the base templates belong to the game's own themes folder; this folder is ignored` | `_base` is the game's default templates. Do not create it. | | `"<id>" in <folder>: the theme "<id>" was already found earlier in the search path and wins` | The same id exists twice: the first folder in the search order is used. | ### tokens.css {#messages-tokens} | Message | Cause and fix | | --- | --- | | `the file has no :root block` | Put the declarations in `:root { … }`. | | `a second :root block (put width-dependent values in @media blocks)` | One `:root` only; narrow-window values go in `@media (max-width: <n>px)` (n from 320 to 4000, two blocks at most). | | `line <n>: only --pv-* properties are allowed, not "<name>"` | A plain CSS property in `tokens.css`. Only tokens belong there. | | `line <n>: --pv-<name> is declared twice` | Delete one of the two. | | ``line <n>: the declaration of --pv-<name> does not end with `;` `` | Add the semicolon. | | ``line <n>: only a `:root { … }` rule is allowed (no other selector, at-rule or nesting)`` | Nothing but `:root` and `@media`. | | `<n> declarations exceed the 200 limit` | The file may hold 200 declarations. | | `line <n>: --pv-<name>: the value exceeds 600 characters` | Shorten the value. | | `line <n>: --pv-<name>: "url(" is not allowed in a token value` | Also `expression`, `@import`, `javascript`, `attr(`, `env(`. Pictures are written `image("images/x.png")`. | | `line <n>: --pv-<name>: "<value>" is not a colour` | Also `<name>() is not a colour function`. | | `line <n>: --pv-<name>: blur is at most 12px` | A `filter` token may blur at most 12 px. | | `<tokens> and <tokens>: the <label> and <label> curves of the progression graph must differ by at least 30 degrees of hue (or 0.25 of lightness for greys)` | Two of the three replay-graph colours are too close to tell apart. The message names the two tokens. | | `the map picture must stay visible: --pv-shade and --pv-art-filter leave <n>% of it on average; at least 20% is required (a theme may tint, dim or blur it, never hide it)` | See [artwork-hidden](https://prism.am/dev/md/themes/errors.md#artwork-hidden). | ### theme.css {#messages-css} | Message | Cause and fix | | --- | --- | | ``line <n>: the selector "<selector>": a selector starts with one of the theme's classes (`.name`)`` | The first part of a selector is a class of the theme. | | `line <n>: the selector "<selector>": ::<name> is not allowed (only ::before and ::after, last in a selector of a rule)` | A pseudo-element ends its selector, once. | | `line <n>: <property>: this property is not allowed in theme.css` | See [css-property-not-allowed](https://prism.am/dev/md/themes/errors.md#css-property-not-allowed). | | ``line <n>: <property>: `!important` and `!` are not allowed`` | Raise the specificity by repeating a `data-*` mark instead. | | `line <n>: <property>: the value is empty` | Write a value. | | `line <n>: @<name> is not allowed in theme.css (only @keyframes and @media)` | No `@import`, `@font-face`, `@supports`. | | `line <n>: the animation "<name>" has no @keyframes in this file` | Define the `@keyframes` in the same file. | | ``line <n>: `\` escapes are not allowed`` | Write the character itself. | | `line <n>: z-index: a z-index is a whole number from -50 to 50, or auto` | Lower the `z-index`. | | `line <n>: url("<path>"): the theme has no such picture in images/` | Only `url("images/x.png")`, a file of the theme. | | `line <n>: <name>: this token is set in tokens.css, not in theme.css (a rule may set the colours, lengths, fonts, weights, shadows, durations and easings)` | Layout words, pictures and the map picture's layers are set once, in `tokens.css`. | | ``line <n>: <name>: a custom property is `--tpl-<name>` (lower-case letters, digits, `-`), a design token or a plate variable (<the plate variables>)`` | A variable you define is `--tpl-*`. | | `the file exceeds 262144 bytes` | Also `line <n>: more than 2048 rules` and `line <n>: more than 40 declarations in a rule`. | ### theme.ts, the script {#messages-script} | Message | Cause and fix | | --- | --- | | `theme.ts: interrupted` | See [script-timeout](https://prism.am/dev/md/themes/errors.md#script-timeout). | | `theme.ts is <n> bytes, over the 131072 limit` | The source is over 128 KiB. | | `theme.ts never called defineTheme({ screens, components })` | The file must call `defineTheme` once. | | `defineTheme() can be called once` | Merge the calls. | | `theme.ts does not compile: <details>` | A syntax error. | | ``defineTheme(): component "<contract>": button(): attribute `on` is required`` | The builder (here `button`) is missing an attribute. The same shape reports `unknown attribute`, and a wrong type with what was found. The line is followed by the stack. The whole script stopped, so the theme loses **all** its templates, not one. | | `the script built more than <n> nodes (at most <n> may stay in the theme)` | Also `the templates have <n> nodes, over the 4000 limit`. A loop built too much. | ### theme.ts, the templates {#messages-templates} | Message | Cause and fix | | --- | --- | | `there is no screen "<name>" (screens: <list>)` | Also `there is no contract "<name>" (contracts: <list>)`. The key of `screens` or `components` is not in the contracts table. | | ``the required slot "<name>" is not placed (place it with slot("<name>"); inside a `when` it counts)`` | See [ts-missing-slot](https://prism.am/dev/md/themes/errors.md#ts-missing-slot). | | `"<name>" is not a slot of the <place> (slots: <list>)` | `c.slot` names a place the template does not have. | | `the required output "<name>" is not bound to any control (a button must call it)` | See [ts-required-output-unbound](https://prism.am/dev/md/themes/errors.md#ts-required-output-unbound). | | `"<name>" is not an output of <owner> (outputs: <list>)` | See [ts-unknown-output](https://prism.am/dev/md/themes/errors.md#ts-unknown-output). | | `<output> takes <n> arguments (<name>: <type>, …) and <m> are given` | The call has the wrong number of arguments. | | `the path "<path>" is not in the <place>: no field "<name>" in <where> (fields: <list>)` | See [ts-unknown-path](https://prism.am/dev/md/themes/errors.md#ts-unknown-path). | | `"<value>" is not a value of the field (values: <list>)` | An enumeration is compared only with its own values. | | `the class "<name>" is neither defined by theme.css nor a class of the game here (game classes: <list>)` | See [ts-class-not-declared](https://prism.am/dev/md/themes/errors.md#ts-class-not-declared). | | `the class "<name>" is both a class of the game and a class of theme.css: rename the theme's` | Rename the class in `theme.css` and `theme.ts`. | | `<name>: "<part>" is not a part of <contract> (parts: <list>)` | `part` names a `data-part` the contract does not have. A screen has no parts. | | `"<image>" is not in the theme's images/ folder` | An `image` node names a picture the folder does not have. | | ``a button has a `label` or `children` (it needs a name)`` | A `button` needs a text for its accessible name. | | `a <kind> is not allowed in <contract>: …` | See [face-with-button](https://prism.am/dev/md/themes/errors.md#face-with-button). | | `<n> nodes in children exceed the limit of 64` | Also `nodes nest deeper than 24 levels`, `the templates of the theme exceed the limit of 1500 nodes`, `a text of <n> characters exceeds the limit of 200`. | | `"<kind>" is not a node kind (kinds: <list>)` | The list of kinds is on the [nodes](https://prism.am/dev/md/themes/nodes.md) page. | When a message is not in these lists, read it the same way: file, place, reason. The reason says what is allowed. If it does not, the reference pages [tokens](https://prism.am/dev/md/themes/tokens.md), [nodes](https://prism.am/dev/md/themes/nodes.md), [contracts](https://prism.am/dev/md/themes/contracts.md) and [CSS allow-list](https://prism.am/dev/md/themes/css-allowlist.md) hold the complete lists. For installing and sharing a theme, see [Sharing](https://prism.am/dev/md/themes/sharing.md). ===== Page: Install, share, troubleshoot Address: https://prism.am/dev/themes/sharing/ Derived from: crates/themes/src/library.rs, apps/desktop/src/app/interface_themes.rs, apps/desktop/src/app/assets.rs, apps/web/src/components/ThemePicker.svelte, apps/web/src/theme/themes.ts, services/api/docs/CATALOG.md, docs/catalogue.md, crates/themes/src/interface.rs # Install, share, troubleshoot Install a theme, what is and is not available to share one today, the checklist before you publish, and a symptom-to-fix table. A theme is a folder, so installing one is copying a folder and sharing one is sending a folder. This page covers both, what the game tells you when it refuses a theme, and what to check before you hand a theme to someone. ## Installing a theme {#installing} ### Where the folder goes {#install-where} Put the theme's folder in your own themes folder, `<data>/themes`: 1. Open the **Skins** page and, in the *Interfaces* section, the *Actions* menu. Choose *Open themes folder*. The game creates `<data>/themes` if needed and opens it. On Windows it is `%LOCALAPPDATA%\Prism\PrismNG\data\themes` (`PrismNG-PBE` for the preview channel). If the environment variable `PRISM_THEMES_DIR` is set, that folder is used instead. 2. Copy the theme's folder in. The path to its manifest must be `themes\<id>\theme.json`. A zip usually unpacks to one extra level (`themes\my-theme-1.0\my-theme\theme.json`): move the inner folder up. 3. The folder's name must be the theme's `id`. Rename it if it is not. 4. Back in the game, choose *Reload themes* in the same menu. Then click the theme's card. The game also reads `themes/` next to `prism.exe`: that is where the themes that ship with the game live, and it is searched **first**. You do not need to touch it. Because it comes first, a theme of yours cannot replace a shipped theme by taking its id. See [where themes are looked up](https://prism.am/dev/md/themes.md#lookup). To try a theme without touching your own, start the game with `PRISM_THEMES_DIR` pointing at an empty folder. ### When a theme is refused {#notices} The game never drops a theme without saying so. Every problem is a notice of the form `"<id>": <file>: <where>: <reason>`, shown in two places: - in the *Interfaces* section of the Skins page, in the list under the cards, titled *Theme folders that cannot be used*. The list also holds warnings and refused templates, not only whole themes; - in the game's log, one line per problem, prefixed `Themes: `. What each kind of notice means: | Notice looks like | Meaning | | --- | --- | | `"<id>": theme.json: …`, `tokens.css: …` or `theme.css: …` | The theme is **not listed**. Fix the file named. | | `"<id>": theme.ts: <message>` | The script failed or went over a budget: the theme **is listed without its templates** (it takes `_base`'s). | | `"<id>": theme.ts: <contract> › <nodes>: <reason>` | One template was refused: the others stand. | | `"<id>": theme.css: warning: line N: …` | The theme is listed and works; the author should read it (today: an infinite animation). | | `"<id>" in <folder>: the theme "<id>" was already found earlier in the search path and wins` | The same id exists in an earlier folder; yours is ignored. | | `"<id>": at most 64 themes are loaded` | Too many theme folders. | | `"_base" in <folder>: the base templates belong to the game's own themes folder; this folder is ignored` | A `_base` folder in your themes folder. Delete it: only the game's own is read. | [Reading errors](https://prism.am/dev/md/themes/errors.md) explains how to read the longer messages of `theme.ts` and has a catalogue of them. ### The log lines {#log} The game writes its theme messages to its **standard error**, as `Themes: <notice>`: one line per notice in the list above, plus `Themes: creating <path>: <error>` when the themes folder cannot be created, and `Themes: file <id>/<path>: <error>` when a picture of a theme cannot be served. To see them, start `prism.exe` from a terminal. The same sentences are in the list in Skins, so you rarely need the terminal. ## Sharing a theme {#sharing} ### What to ship {#package} Send the **whole folder**, named after the id, as a `.zip` that unpacks to that one folder: ```text my-theme/ theme.json tokens.css theme.css (if you have one) theme.ts (if you have one) preview.png (if theme.json names one) images/… (what your tokens, templates and stylesheet refer to) ``` Leave out everything the game does not read: a copy of `theme.d.ts`, a `tsconfig.json`, notes, source art, `node_modules`. The game ignores them, but they weigh on the zip. The limits that apply to the content: the manifest 64 KiB; `tokens.css` and `theme.css` 64 KiB each; `theme.ts` 128 KiB; each picture 4 MiB. ### What exists today, and what does not {#today} Be precise with the people you share with: - **A theme is installed by copying its folder.** There is no button that imports a theme's zip: unlike skins, a theme has no import dialog. - **The game's catalogue does not carry themes.** The catalogue (`GET /api/catalog`, the Download page's *Mods*, *Skins* and *Playlists*) knows three kinds, `mod`, `skin` and `playlist` (`services/api/docs/CATALOG.md`, `docs/catalogue.md`). An item of another kind is ignored. So there is no catalogue entry, listing or one-click install for a theme. - **`ts_package` is not packaging.** The function of that name in `crates/themes/src/interface.rs` writes the TypeScript types (`@pvng/themes`) that the game's own page uses to receive validated themes. It does nothing to a theme folder. - **The themes that ship with the game** are the folders of `content/themes/` in the repository (and `themes/` next to `prism.exe` in a release). A theme that you write lives in `<data>/themes` for you and for anyone you give it to. So today, sharing a theme means handing over a zip (or a link to a repository) with the instructions of [Installing a theme](https://prism.am/dev/md/themes/sharing.md#installing). ### Versioning your theme {#versioning} - `version` in `theme.json` is **your** label: letters, digits and `. _ + -`, 32 characters at most. Raise it when you publish a change. - `themeApi` is the version of the **game's contract** the theme was written for. Write the version you tested against. A theme that asks for a newer one than the game speaks is refused with `themeApi N is newer than this game speaks (theme API M): update the game, or use a version of the theme written for API M`. An older one loads as long as the game can read it, but it is refused the screens, faces and `"accent": "map"` that a later version added: see [what changes in version 2](https://prism.am/dev/md/themes.md#version-2). See [versions and stability](https://prism.am/dev/md/themes.md#versions). - Within one `themeApi`, the game only adds: a game update does not break a valid theme. When a new `themeApi` arrives, re-run `check_theme` on your theme (it reports the version the game speaks) and port what it reports. - Say in your release notes which `themeApi` it needs, and which languages `localized` covers. ### Checklist before you share {#checklist} - [ ] `check_theme` prints **no problem**, and **no warning**. A warning is a problem you chose not to fix ([concepts](https://prism.am/dev/md/themes/concepts.md#animation-rule)). - [ ] `id` equals the folder's name; `name`, `description`, `version` and `author` are filled in; `themeApi` is written. - [ ] `localized` has at least **English and French** (`en` and `fr`: the name and the description), and the languages of anyone you know you will help (`zh`, `ko`). - [ ] **Reduced motion.** Every moving animation and transition is inside `@media (prefers-reduced-motion: no-preference)`; no infinite animation. Switch your system's *reduce motion* setting on and look at the theme. See [concepts](https://prism.am/dev/md/themes/concepts.md#reduced-motion). - [ ] **Contrast.** Text is readable on every plate in light and dark: the tokens `--pv-text*` on `--pv-plate*`, and `--pv-ink` **on your accent** and on a few custom accents if `accent` is `"preference"`. A common target is a contrast ratio of 4.5:1 for body text; the game does not enforce one. A light theme sets `--pv-color-scheme: light` and redefines the tokens whose defaults assume a dark surface ([tokens](https://prism.am/dev/md/themes/tokens.md)). - [ ] **The map's picture** is still visible (the validator refuses a theme that buries it) and the text over it reads on bright and dark pictures. - [ ] **Sizes.** Look at 1920×1080, 1366×768 and 1280×720, and at a narrow window (your `@media (max-width)` blocks). - [ ] **Keyboard.** Tab order follows your tree. Enter plays, Escape closes, arrows move the list. These do not depend on your template, but a bad `overflow` or `inert` can hide the focus ring. - [ ] **Both accent modes**, if `accent` is `"preference"`: *Theme default*, *Map artwork* and a *Custom colour*. - [ ] **A picture for the card.** `preview` names an image of the folder; it is cropped to fill the card (`cover`). Without it the game draws the card from your tokens, which is a fair preview. - [ ] **A clean install.** Copy the folder, and only the folder, into an empty `PRISM_THEMES_DIR`, start the game, and pick the theme. - [ ] Screenshots for your readers: the map selection, and the Settings window if you template it. ## Troubleshooting {#troubleshooting} Read the list under the cards in Skins first: it names the file, the line or the node, and the reason. The table covers the cases where the cause is not in a message. | Symptom | Likely cause | Fix | | --- | --- | --- | | The theme is not in the list and no notice mentions it | The folder is in the wrong place, one level too deep, or the list was not reloaded. `PRISM_THEMES_DIR` may point elsewhere. | Use *Open themes folder*, check that `themes\<id>\theme.json` exists, then *Reload themes*. | | `no theme.json` | The folder is nested (`my-theme\my-theme\…`) or the file is misnamed. | Move the inner folder up; the file is `theme.json`. | | `the id "…" must be the folder name` | `id` and the folder differ. | Make them equal. | | `the folder name must be lower-case letters, digits and hyphens (at most 32)` | A capital, a space, an underscore or a long name. A name that starts with `_` is never a theme. | Rename the folder and the `id`. | | `already found earlier in the search path and wins` | A shipped or other theme has the same id. | Change your `id` and your folder name. | | The theme is listed, but the layout did not change | `theme.ts` failed or one of its templates was refused (a notice says which), or the old file is still loaded. | Read the `theme.ts` notice; fix; *Reload themes*. A template that fails is replaced by the base's: the theme looks like the default layout. | | The theme is listed, tokens work, my template does not | Its key is wrong (`screens: { 'screen.library' }` instead of `library`), or it is for a contract that the screen does not use. | Use the key rules of [templates](https://prism.am/dev/md/themes/templates.md#entry). | | Tokens are ignored | The value was refused (the whole theme is then unlisted), or the token is overridden in a subtree by `theme.css`. Layout words, images and `--pv-art-filter` work only in `tokens.css`. | Check the notice; search your `theme.css` for the token. | | `the required slot "…" is not placed` or `the required output "confirm" is not bound to any control` | The template forgot a place or the button. | Place every required place; bind `confirm` to a `button`. | | The **Play button vanished** | A template cannot remove it: the validator refuses a footer without a button bound to `confirm`, and a screen without the `footer` place. So it is hidden or pushed out by layout: a parent with `overflow: hidden` and no room, zero height, a wrong `z-index`, the strip drawn only `when` something is selected, or a `disabled` button. Enter still plays. | Give the parent room; look at the footer's `class` and `when`; test with the rule removed. | | `theme.css` is ignored | A rule of a refused file takes the whole theme out. If the theme loads, a game rule is more specific (the game wins), the selector aims at a class the template does not put on a node, or it aims at a game class instead of a `data-*` mark. | Repeat a `data-*` mark to gain specificity; check the class is on a node in `theme.ts`. See [theme.css](https://prism.am/dev/md/themes/css.md#specificity). | | `a selector starts with one of the theme's classes (.name)` | The selector starts with an element, `[data-…]`, `:root` or `*`. | Start with one of your classes and descend. | | A picture does not show | The path does not match, the extension is not an image, it is over 4 MiB, or it is outside `images/`. A log line says `Themes: file <id>/<path>: …`. | Use `images/name.png`, a supported type, and the folder. | | The accent is not the one I set | `accent` is `"preference"`: the player's setting wins. | Set `"accent": "fixed"` if the palette needs it. | | The theme drops frames, or the fans spin on a menu left alone | An infinite animation (the validator warns), a `transition` on elements updated every frame (the live bars), animation of `width`, `height` or `top`, an animation outside `prefers-reduced-motion: no-preference`. | Play motion once per selection under `[data-entering]`; animate `transform` and `opacity`; see [animation rule](https://prism.am/dev/md/themes/concepts.md#animation-rule). | | `theme.ts: interrupted`, or `… over the … limit` | `interrupted` is the script stopped at its 500 ms budget (a heavy loop at load time). `over the … limit` is a source, a tree or a node count over a budget. | Build less at load time; see the [budgets](https://prism.am/dev/md/themes/templates.md#budgets). | | `themeApi N is newer than this game speaks` | The theme was written for a newer game. | Update the game, or use an older version of the theme. | | `the map picture must stay visible: …` | A shade, a filter or an overlay hides the map's picture. | Lighten the layers in `tokens.css`; see [tokens](https://prism.am/dev/md/themes/tokens.md). | If a case is not here, run `check_theme` on the folder and read [reading errors](https://prism.am/dev/md/themes/errors.md). ===== Page: Menus: behaviour and themes Address: https://prism.am/dev/menus/ Derived from: docs/menus.md # Menus: behaviour and themes Menus: behaviour, the behaviour API and themes, the modifier selector. Menus separate what they **do** from what they **look like**: - a typed **behavior layer** (`apps/web/src/menu/`): named *stores* (what the menus display, as JSON values) and named *actions* (what they can do), with no markup; - the interface's **Svelte components**, written on top of this layer (they read the same stores and call the same actions); - **interface themes** (Classic, Slant, Cabinet…): data (a manifest, CSS tokens validated by the host, images) that restyle these components without replacing them, see [themes](https://prism.am/dev/md/themes.md) and interfaces. There is no longer an HTML menu model: a third-party theme contains neither markup nor script. ```mermaid flowchart LR host[Rust host<br/>window.ipc] <--> shell[Main page<br/>bridge.ts, host.ts] shell --> behavior[Behavior layer<br/>stores + actions] behavior --> svelte[Svelte components] themes[Themes<br/>validated tokens] --> svelte ``` This layer covers map selection; Settings, Mods, Skins, and the Workshop are opened through its actions, like the Esc menu. ## Map selection The list on the right shows the chartsets (song folders). As in osu!, clicking a set **opens it in place**: its difficulties appear below it, each with its layout ("4K"), its name, and the rating of the view recorded by the chosen mod. A missing value stays "—" and takes a neutral color; a MinaCalc value uses a ramp adapted to MSD, and a star rating uses the star spectrum. Opening a set selects its already chosen difficulty, otherwise the first one; clicking a difficulty selects it; clicking the open set closes it again. Only one set is open at a time. The left panel follows the selection: title, artist, chosen rating and essential statistics, then the analysis panels declared by the rating mod. The theme does not decide their content from the calculator's name: Etterna chooses a radar accompanied by bars carrying the real skillset names, osu a chart profile and a timeline. Etterna declares a fixed scale of 0 to 40: 10 fills a quarter of a bar, 20 fills half; beyond 40, the fill saturates without changing the displayed number. A missing value has no fill. The Info / Leaderboard / Mods tabs sit directly under the statistics, before their content; Local / Online remains a compact sub-choice of the leaderboard. Only the score list scrolls: the title, the statistics, the tabs, Local / Online, the Performance selector, and the footer stay fixed. The leaderboard shows no explanatory paragraphs about the current judgement, the selected performance, or the simulator values. Mods contains the native rate (`playbackRate`), from 0.50 to 2.00 in steps of 0.05, with text entry, slider, and reset to 1, under the simple label "Rate". No inactive effect or explanatory paragraph about the rate or development data is offered. Changing the rate keeps the previous consistent analysis during computation, without a flickering loading message. Errors remain reported in a fixed location. Below the rate, Mods lists a compact toggle for each gameplay modifier published by mods (`gameplayMods`), for example **Auto** from `pvng.auto`: label only, with the description in a custom tooltip on hover or focus, nothing else. The choice is the `gameplayMods` setting, removed with a notification if the mod that provides the modifier disappears. Numbers move to their new value without recreating the graphs or shifting the controls. An interruption restarts from the displayed number; reduced motion disables this interpolation, which is purely visual. Responses from an old chart, rate, or computation are ignored. Score cards and the replay page display the recorded rate, without a multiplication sign, with their own density and difficulty recomputed natively. Changing the menu rate does not rewrite these plays. The replay page has a **Difficulty** selector next to Judgement and Performance: it is the same component (`RatingPicker`) and the same setting (`ratingSystem`) as the selector in the selection footer, so ONE choice for the whole game (changing one changes the other, as with Judgement and Performance). Same calculators, grouped by mod, with search and keyboard; hiding a difficulty remains a separate action in Settings. The value, colored by `ratingColor` and rounded to 2 decimals, is that of the chart **at the recorded rate** of the replay (native analysis of that rate, never a 1x value multiplied); the rate is written below it ("at speed 1.50"). Switching calculators simply reads another already computed value: the number moves to its new value in place, without reloading. A calculator with no value for this chart displays "Unavailable" in the same layout (the name always takes two lines), without shifting anything. Leaderboard cards do not display the difficulty: their row already carries rank, player, rate, combo, accuracy, performance, and tiers, and one more value would overload it; the replay page displays it. The panel footer stays visible on a single line: Rating and Judgement, clickable across their whole surface, then Play on the right. Menus are drawn by the theme (not native `select` elements), grouped by mod, with bounded height, with search beyond eight choices. ↑/↓, Home/End, and Enter browse and choose; Esc closes without opening navigation. The parameters of the chosen judgement remain in its menu. Settings distinguishes Use from Hide/Show for a rating, without a checkbox. Settings open in a large centered modal window, above the dimmed selection. The library stays mounted: search, open set, chosen difficulty, and scroll position are preserved. The categories (one icon each) are on the left, the search at the top; only the content scrolls (structure, search, restoration, export/import: reglages.md). Valid changes apply immediately, with no Apply button. The close button or Esc hands control straight back to the selection, without opening navigation. An open dropdown or an active key capture consumes Esc first. Focus stays in the window and returns to its available entry point; settings notifications are displayed in the window so they remain readable and dismissible. The **Scroll speed** category is independent of Game and Judgement. It presents the mods' providers, including Prism in ms, and accepts free decimals outside the suggested slider. The Play button follows `scrollSpeed.playDisabled`, so as not to play a conversion that is still unknown. Settings → Judgement simply displays the name of the active judgement ("Etterna · J4", for example), with a small chevron: clicking this name opens the list, with no large full-width field or permanent grid. A choice, a second click on the name, an outside click, or Esc closes the list; it opens above or below depending on the available space. Parameters have a theme-drawn slider and an editable value box with −/+ buttons. Enter confirms, Esc cancels an unconfirmed entry; the mod's available bounds, steps, and combinations remain respected. Under the sliders, the windows of each tier are displayed in milliseconds with their colors and update immediately from the host's tables. "−" means before the note, "+" after; "±" indicates the same tolerance on both sides. The small menu in the selection also displays these values under its sliders; Settings keeps the detailed table. The theme distinguishes title, main rating, and secondary information; map rows have accents tied to their difficulty rather than an identical border everywhere. Selection, tabs, and menus have short transitions, disabled with `prefers-reduced-motion: reduce`. Timelines color low values in blue/cyan and high values in warm tones. The cursor gives the exact value and time of the bin, with mouse and keyboard alike; color does not replace the numbers. Timelines, radar points, and their value lines use the same custom tooltip: full label declared by the mod, actual value, unit, and time interval or declared scale. A missing data point remains "Unavailable". The time cursor and the radar lines are keyboard accessible; the tooltip accepts the pointer and stays bounded to the window. Esc or an outside click closes it without opening the navigation menu. The graph uses the available space (160 to 240 px tall) instead of leaving a large gap before the controls. At low heights, the panels keep their readable sizes and scrolling stays within the details, never across the whole page. Leaderboard offers Local / Online. Local shows a single leaderboard of clickable cards: player, rank, accuracy, combo, and performance above the date. The small colored counters give the hits for each tier of the current judgement; Miss is not repeated as a second metric. Clicking a card opens the dedicated replay page. All entries are re-judged from the replay's key presses and releases with the currently selected judgement, not with the one from the original play. Changing the judgement set or settings restarts the evaluation off the interface thread; old results never replace the current request. Missing or unreadable replays are flagged, without using their old accuracy as a fallback result. The full history can be browsed page by page, with no cap of twelve or twenty scores. The host keeps the re-evaluated leaderboard cached; requesting the next page does not re-judge all the replays. Pages from a previous map or a previous evaluation are rejected. The name is saved in each new replay. Settings → Interface lets you choose the name for upcoming plays; if left blank, the native application uses the Windows account name. An older replay without a name stays flagged as such, without being retroactively attributed to the current player. On desktop, the replay page places the player, the dominant accuracy, and the counters on the left and the analysis on the right, with no grid of rounded tiles. The chart stays in the header. The vertical name / count list never assumes six tiers: the 32 custom tiers and Miss remain accessible in their own scroll area, without moving the score or the graphs. The fill of each row represents its actual share of the total judgements. The Timing, Distribution, and Progression tabs avoid stacking or shrinking all the graphs; ←/→, Home, and End also let you select them from the keyboard. Typography stays readable and the page fits almost without scrolling at common desktop sizes. Axes are rendered in HTML, with no distortion from the SVG. Timing shows one point per native judge event, at its exact time, with its key, tier, and actual offset, with no averaging or min–max bar. The Canvas draws every event, including simultaneous hits, without sampling. Hovering or focusing a key highlights it; clicking it keeps it selected, and "All keys" restores all columns. Arrow keys, Home, and End also move through the keys from the keyboard. A column with no measured hit keeps its Miss counts and shows statistics as unavailable, never a false zero. Each Miss is a bright red cross on the center line, at its judgement time, with no offset. The crosses are drawn above the points so they are not hidden by a perfect hit. They are included in neither the offset statistics nor the histogram. The before/after windows of the active judgement keep their subtle background and colored limits, even when asymmetric. The help next to "Hit offset" explains signed offsets and the Miss crosses. Hovering inspects the nearest event; the control below the graph steps through events by time, with their identity to tell simultaneous notes apart. The tooltip gives the key, tier, exact time, and actual offset, or "Miss · no offset". ←/→, Home, and End step through the notes; Esc closes the tooltip without leaving the replay. The **LN** button opens a compact analysis: missed heads, early releases, releases within the window, and notes held to the end. The means and ranges for heads and releases come from the native engine's events, using the active judgement's hold model. A head that was actually pressed remains measurable even if the hold fails afterward; an automatic end does not fabricate a zero-offset release or an independent tail judgement. The distribution initially frames the populated bins (without losing any hits) and keeps zero as a reference. Its bars reuse the colors of the current judgement's windows, with their independent early/late bounds. A bin crossing a bound changes color at that point, without claiming to know the exact split of its hits between tiers. All three views offer zoom via the mouse wheel, anchored under the pointer, or with the −/+ buttons, up to 32×: the wheel alone zooms the horizontal axis (time, or offset for the distribution), **Shift + wheel** zooms the vertical axis (Timing's ±ms offset, the distribution's count, the scale of each curve in Progression, which share the same vertical zoom; the visible bounds are shown below each curve). The ↕−/↕+ button group is the equivalent. Once zoomed, the view pans by dragging (both axes at once) or with the arrow keys; **Full view** restores the full extent of both axes. From the keyboard, the selected graph responds to + / − (horizontal axis), Shift + ↑ / ↓ (vertical axis), arrow keys (panning), and 0 (full view). Timing and Progression share the same time window; the distribution keeps its own independent offset window. Axes and inspection follow the visible extent, without enlarging text or inventing new points. Timing's keyboard and Progression's interval cursor bring the chosen measurement back into view. Zoom (horizontal and vertical) is preserved when changing judgement or calculator, and clamped if the data extent changes. The view state lives in `lib/graph-view.ts` (pure, tested functions). The **mean offset** (left panel, Timing tab, Progression interval, audio offset prompt, detail of an error map cell) is colored by its distance from zero, in a continuous gradient: white up to 2 ms, yellow around 4 ms ("not great, be careful"), orange around 7 ms ("change your settings"), red from 10 ms ("change your settings now"). The four colors are the tokens `--pv-offset-ok/-warn/-high/-bad` (a light theme redefines them); `lib/offset-color.ts` (`offsetColor`, named anchors) computes the blend. The sign (early/late) stays in the text, and the advice is a tooltip and text read by screen readers. Combo is blue, accuracy is dotted purple; density keeps a subtle fill and an amber/orange/red color tied to its magnitude. View transitions do not move the axes. Progression keeps the end-of-interval combo and accuracy values, without interpolation. Combo, accuracy, and chart density (notes/s) are overlaid in a single graph. The three legend buttons show or hide their curves independently, by mouse or keyboard. Scales and units are shown in these controls, with no value columns or space reserved to the left of the graph. The time axis and cursor remain shared. Hiding a curve does not resize the other scales and does not move the graph; hiding everything shows a prompt to pick one. The fills of intervals containing Misses are hidden by default. The **Miss intervals** button shows or hides those of the replay and its reference, independently of the curves, without changing the axes or the cursor. Their count remains shown on inspection, with no invented exact position. Density bins keep their native width, independent of the replay's intervals; the inspected value corresponds to the end of the selected interval. A missing density disables its button, without showing a curve at zero. The statistics come from native judge events; the absence of an offset on a Miss is never mistaken for a perfect hit. The full timing is loaded in pages of 2048 events from the same native snapshot, without re-reading or re-judging the replay on each page. A new analysis and its point histories are published together, once all pages have been received; stale pages cannot replace the displayed pair. Only Progression and Distribution keep their bounded aggregates. Returning to the leaderboard keeps the map, the loaded score pages, and the position in the library. **Compare score** picks another score on the same chart, with access to every page of the leaderboard and an action to remove the reference. A single request evaluates both replays under the same current judgement and calculator; a deleted or unreadable reference does not make the main score disappear. The reference shows its player, its recorded rate, and the available differences in accuracy, combo, difficulty, and performance. Its timing points are hollow, in the colors of the tiers, and its red Miss crosses are circled. Its progression curves are dashed and its distribution is drawn as an outline. The **Reference** button hides these overlays without changing the scales. If the rates differ, the reference's times are aligned by chart position (`time × reference rate / main rate`); the axis keeps the real seconds of the main replay, and offsets remain in real milliseconds. **Watch replay** starts native playback of the recorded physical inputs, with the replay's rate and the judgement currently displayed. The playfield, audio, and HUD follow this playback; the overlay shows **REPLAY** and its rate. The spectator's key presses do not affect the notes; Esc returns to the preserved analysis, as does the natural end of the replay. Playback creates neither a score nor a new replay. In the development server only, a clearly identified simulator visualizes the chart and the fictitious inputs, without pretending to be the native rendering or judge. Changing the judgement or the calculator no longer unmounts the analysis: the last consistent result remains displayed during recalculation. Numbers count up or down to the new values over 260 ms; an interruption restarts from the displayed number. This interpolation changes neither the stores, nor the calculations, nor the recorded results. Graphs keep a 180 ms transition, without inventing points between two aggregates. The tab, the cursor, the hidden curves, and the scroll position are preserved. Performance and its unit belong to the same result, with no mixing of old accuracy and the new calculator. Stale responses are still ignored. The animation is disabled, or stopped if it is in progress, with the reduced-motion preference. The simulator generates its density from the same notes as its replays; it does not stretch an independent graph to hide a different duration. Visual references: [Etterna results](https://github.com/etternagame/etterna/issues/670), [Quaver interface](https://store.steampowered.com/app/980610/Quaver/) and [osu!mania results](https://osu.ppy.sh/wiki/en/Client/Interface#results-screen). By default, performance follows the active judgement: osu!mania accuracy → osu! pp (Metron calculator `osu-2018`, displayed "osu!mania", in pp), Wife3 → MinaCalc 527 SSR. The player can choose another calculator with the Performance selector visible above the leaderboard, on the replay page, or in Settings. It is not hidden in the judgement menu. The difficulty rating remains separate. The accuracy of the current judgement is passed to the chosen calculator: a combination of different models is flagged as non-standard, and not as official pp/SSR. Only `osu-2018` (pp) and `etterna-515` (SSR) have a performance value; inputs that a calculator would additionally require are never invented. The SQLite index is written after the replay is saved; interrupted plays are excluded. The identity includes the chart path and its difficulty index. Older replays without this identity are not matched by title. Online indicates the absence of the service, without inventing scores. In the development web host (`bun run dev`), each difficulty in the mock library receives a rich deterministic history, with demo player names and simulated inputs re-judged when the judgement changes. The same data reappears after reload; the demo remains empty. Completed plays in the simulator are added to this history in memory, specific to each chart. `MockOptions.replays` lets you provide replay entries; `scores` provides already-evaluated rows for interface scenarios only. `scores: {}` leaves all leaderboards empty until a play is completed. The mock displays deterministic numeric pp/SSR values to work on the presentation, as requested: these are development fixtures, not a reimplementation of Metron. Its graphs still come from the simulated inputs. These fixtures are never written to the native library and do not make the online service available. | Key | Action | Effect | |---|---|---| | ↓ | `library.down` | next difficulty of the open set, otherwise first difficulty of the next set | | ↑ | `library.up` | previous difficulty, otherwise last difficulty of the previous set | | → / ← | `library.nextSet` / `library.previousSet` | next / previous set, on its first difficulty | | Enter | `play` | plays the selected difficulty | | Esc | `navigation.drawer` | first closes open Settings; otherwise opens or closes the menu | With no selection, ↓ opens the first visible set. Selection keys only act on the Library page, with the menu and Settings closed. In a text field (the search), only Esc, Enter, ↑ and ↓ pass through; on a button outside the list, Enter and Space stay with the button; on a slider, a dropdown list, in a dialog box or a popover, only Esc passes through. The mouse wheel and the scrollbar only scroll the list. ### Difficulty strip and map changes Each set card carries a **difficulty strip**: as many pills as the strip's width allows on **a single line**, from the easiest to the hardest on the chosen rating, each colored by `ratingColor`, followed by a "+N" badge (N = difficulties not shown, accessible label "N more difficulties") whose hover or keyboard focus on the card opens the shared popover (`ChartPopover`) listing all difficulties. Depending on the available space, a pill is a plain colored bar, the rounded rating, or the layout and the rating (`menu/difficulty-strip.ts`, `fitStrip`): the computation depends only on the width of the list (measured once, never per row or per pill) and on the number of difficulties, because pill widths are fixed. The height is constant, nothing overflows, and no row moves: the list remains virtualized. Choosing another map updates the left panel **in place**: the title and the graphs cross-fade, the numbers scroll (`AnimatedNumber`), and the panel keeps the last delivered analysis until the new one arrives, with no clearing and no layout jump. The panels' entrance animation replays **only once the selection has settled**: `menu/settled.ts` (`createEntrance`) sets `data-entering` on `.selected-map` 250 ms after the last change (the delay restarts on each change), only if the settled map belongs to a different set than the previous one (changing difficulty within a set replays nothing), and never under reduced motion. The trigger is shared by all three interfaces; each interface decides in its own CSS what `.selected-map[data-entering]` animates. ### Virtual list `LibraryBrowser` (`apps/web/src/menu/library-browser.ts`) keeps the list independent of its rendering: - **Geometry.** Each set occupies `setHeight` px (row pitch, spacing included); the open set adds `number of difficulties × difficultyHeight`. With a single open set, the position of a set and the set under a given offset are computed directly (`ListLayout`), without measuring the DOM. The renderer declares its steps (`library.metrics`); switching renderers keeps the first visible set at the top. - **Stable height.** From the first page on, the total height is `total × setHeight`; the arrival of pages never changes it. Opening a set reserves the height of its difficulties, which is known since its page is loaded; if a taller open set closes, the scroll is corrected so that the clicked set stays under the pointer. - **Pages by set index.** Pages of 80 sets (`libraryPage`, offset a multiple of 80), at most 12 kept (those farthest from the view are dropped); the pages requested are those that cover the view plus 5 sets on each side, and the next one. A scrollbar jump directly requests the target page; in the meantime, empty rows of the same height stand in for it. - **Bounded rows.** Only the sets around the view and, for the open set, the difficulties close to the view are rendered. - **Keyboard.** Moving to a set whose page is not loaded requests it and opens it when it arrives; any other action cancels that wait. The movement scrolls just enough to show the chosen difficulty. - **Stale responses.** A page from an old search or from a changed library (different `requestId`) is ignored; the selection (`lib/selection.ts`) ignores responses from a replaced selection and stays interactive while loading. Ratings arrive with the page or the selection; the mod catch-up refreshes the rating and the detail columns of each view, without restarting the selection or losing the result of a play. - **Structured search.** `libraryPage.query` is a `LibraryQuery` generated by `@pvng/db`: `{ text, filters: [{ key, value }] }`. Free text waits 150 ms after the last keystroke; adding, editing, or removing a filter immediately applies the current text. All words and all criteria must match **the same difficulty**. Sets contain only the matching difficulties, with their native indices unchanged; searching never reselects a chart. The search field receives focus on opening; **+ Filter** opens the fields grouped by provider, then a compact editor. - **Extensible catalog.** `libraryFilters` publishes the full catalog and its monotonic revision. The picker groups neutral fields under "Chart" and contributions under the real name of their mod. The default theme offers a keyboard-searchable list, then an editor for inclusive numeric bounds or for "contains / equals" text. Chips let you edit and remove each criterion. Esc closes the picker or cancels the edit before opening the navigation menu; a click outside closes the picker. - **Validation and availability.** At most 512 characters of free text and 16 criteria; at least one finite numeric bound (negatives and decimals allowed, minimum ≤ maximum), or 1 to 256 characters of non-blank text. Text search is literal, ASCII case-insensitive: `%`, `_`, and `\` are not wildcards. A provider that is removed, disabled, failing, or whose field changes type leaves a chip unavailable: results are blocked until the provider returns or the criterion is explicitly removed. Old catalog revisions are ignored. - **Background computations.** Without a mod filter, ratings are corrected in place: no reset, and no change to scroll, open set, or selection. With a mod filter, the catch-up may change the results: the browser asks the native side for the filtered rank of at most two identities (`libraryPage.anchors`: the view's folder, the open folder). The `library.anchors` response maps each folder to its exact rank, or `null` if it no longer matches. The rank follows the folder's first **original** index, not that of the first remaining difficulty. The browser directly loads the pages for these ranks and for the view, then replaces them atomically: same open folder and same offset in the view, even after a jump of thousands of sets, without loading the entire library. The old rows remain usable during this preparation. The native selection is never replaced; if the ranks or the total change during the bounded requests, the anchors are resolved again. Components implement no difficulty computation and do not receive the entire library. The Web mock applies the same conjunctions and the host-side pagination, with deterministic ratings and tags; disabling/reloading their mods exercises the real lifecycle of the catalog. ## Behavior API `apps/web/src/menu/behavior.ts` exports `stores`, `actions`, `invoke(name, arguments)` and `act(name, ...arguments)` (a typed version for components). Value types come from the generated `@pvng/*` types: the views (`views.ts`) are computed from `BeatmapSet`, `LibraryEntry`, `SongInfo`, `Analysis`, `JudgementSetInfo`…; no exchange type with Rust is rewritten. `StoreValue<name>` and `ActionArgs<name>` give the type of a store and of an action's arguments. ### Stores | Store | Contents | |---|---| | `library` | `query` (entered text), `filtered` (text or active criteria), `total`, `loaded`, `empty`, `folders`, `hasFolders`, `scanning`, `progress`, `percent`, `issues` (count), `locked` (host absent or import in progress) | | `libraryFilters` | `ready`, `revision`, `options` (key, translated label, group, type, unit), `groups` (`name`, `options`), `active` (metadata, `summary`, `unavailable`, `removeLabel`), `editor` (`key`, `label`, `group`, `unit`, `number`, `available`, `min`, `max`, `text`, `match`), translated `error`, `blocked`, translated `status`, `limit` (16 criteria reached) | | `scrollSpeed` | `ready`, `scrollMs` (exact resolved time or `null`), `playDisabled` (library lock or conversion unavailable) | | `sets` | the virtual list: `extent` (px), `rows`, `total`, `loaded`, `expanded` (position, -1 with no open set), `scroll` (`{ top, seq }`: scroll request) | | `selection` | `hasSong`, `loading`, `demo`, `title`, `artist`, `creator`, `difficulty`, `keys`, `keysText`, `color`, `rating`, `ratingUnit`, `duration`, `bpm`, `notes`, `holds`, `averageNps`, `peakNps`, `panels`, `density`, `binSeconds`, `background`; `value`, `durationSeconds`, `bpmMin`, `bpmMax` are the resolved numbers for an animated presentation | | `chartPanel` | `info`, `leaderboard` or `mods`: view of the selected chart | | `visualizer` | `open` (the list panel is replaced by the chart preview), `status` (`loading`, `playing`, `paused`, `ended`, `closed`), `positionUs` (last report from the host), `durationUs`, `playbackRate`, `seeking` (docs/visualiseur.md) | | `playbackRate` | `value`, `min`, `max`, `step`, `loading`, `error`, `available`, `displayedRate`, `mock`; `displayedRate` identifies the last consistent result during recalculation | | `gameplayMods` | `label`, `mods`: published gameplay modifiers (`key`, `modId`, `kind`, `name`, `short`, `description`, `enabled`, `group`, `icon`, `conflicts`, `params`) for the selector in the Mods tab | | `leaderboardSource` | `local` or `online` | | `leaderboard` | `loading`, `loadingMore`, `entries`, `total`, `evaluationId`, `unavailableReplays`, `performance`, `performanceLabel`, `mock`: paginated leaderboard re-judged with the current judgement, saved names, per-tier counters and the chosen performance (pp / SSR, or `null`) | | `performance` | `chosen` (empty string for Auto), `label`, `choices`: available native performance calculators, independent of the difficulty rating | | `replay` | `open`, `loading`, `replayId`, `evaluationId`, `detail`, `judgement`, `error`, `performance`, `performanceLabel`, `mock`, `analysis`, `rating`, `ratingUnit`, `ratingLabel`, `color`: analysis at the recorded rate, with the current judgement and calculator | | `judgement` | `ready`, `label` ("osu!mania · OD 8"), `sets` (`key`, `name`, `mod`, `active`), `tiers` (`index`, `name`, `color`, `gradient?`), `refusal` (localized message when no judgement mod is installed and the choice is a mod set, otherwise `null`: `play` then does nothing) | | `rating` | `chosen` (`<mod>/<id>`), `calculator`, `label`, `choices` (displayable ratings), `options` (all of them, with `hidden` and `performance`); the calculator determines the numbers in `sets` and `selection`, never the judgement rules | | `navigation` | `page` (underlying page), `drawer`, `settings` (modal window open), `pages` (`id`, `label`, `active`) | | `result` | `visible`, `aborted`, `auto` (Auto play: no score or replay), `accuracy`, `maxCombo`, `tiers` (`name`, `color`, `gradient?`, `count`); summary hidden after ten seconds, without touching saved scores or replay analysis | | `i18n` | `locale`, `messages` (the language's catalog, English as fallback) | | `modOptions` | `groups` (`modId`, `name`, `elements`: `key`, `name`, `resettable`, `options`: `name`, `label`, `kind`, `min`, `max`, `step`, `values`, `maxLength`, `value`, `default`, `resettable`): the options that mods declare `player: true` (their own global settings), generated from their declarations | | `skinCustomization` | `editing` (current skin editor session) and `skins`: one element per installed skin, with `id`, `selected`, `customized` (the player's configuration is not empty), `playfield` (playfield values that have been set), `lanes` (lanes that have their own values), `elements` (HUD widgets that have been set), `imported` (imported images, `null` until the host has reported them) and `canCustomize` (the current skin, outside a session) | `selection.panels` provides the resolved panels in the mod's order. Each panel has `kind` and `title`; value panels have `fields` (`label`, `unit`, `decimals`, `value` or `null`, `display` ready to show), timelines have `series` (`label`, `source`, `unit`, `values`, `binSeconds`). A row of `sets.rows` has `kind`, `key`, `position`, `top`, `height` and: - `set`: `expanded`, `selected`, `set` (`id`, `title`, `artist`, `creator`, `count`, `countText`, `keysText`, `ratingText`, `color`, `chips`, `thumbnail`); `chips` lists its difficulties from easiest to hardest on the chosen rating (`index`, `name`, `keysText`, `value`, `rating`, `short` = rounded rating, `color` = `ratingColor`), with unrated ones last; - `difficulty`: `difficulty` (rank within the set), `selected`, `last`, `entry` (`index`, `name`, `keys`, `keysText`, `rating`, `ratingUnit`, `color`, `notes`, `duration`); - `placeholder`: a page that has not arrived yet. The displayed texts ("3 difficulties", "4K", "12.40–21.03 MSD") are already translated: all themes show the same values. ### Actions | Action | Arguments | Effect | |---|---|---| | `play` | — | plays the selection (no effect during an import) | | `chart.panel` | `info`, `leaderboard` or `mods` | changes the chart panel, without reselecting it | | `editor.open` | none | opens the selected map in the map editor ("Edit" button to the right of the tabs) and displays the editor page; a map that is not a `.rox` is edited through a `.rox` copy alongside it, the original is never overwritten | | `gameplayMod.set` | key `<modId>/<id>`, boolean | enables or disables a published modifier (no effect for an unknown key); synchronizes `Settings.gameplayMods` | | `playbackRate.set` | number | sets the native rate, clamped between 0.5 and 2 on the 0.05 grid (0.001 on the Training tab); synchronizes `Settings.playbackRate` | | `playbackRate.step` | integer (1 or −1) | one press of − or +: moves by the player's rate step (`rateStep`, 0.025 on the Training tab), back on the grid and between 0.5 and 2; no effect while the visualizer covers the list (the rate keys call it) | | `leaderboard.source` | `local` or `online` | changes the displayed leaderboard source | | `leaderboard.more` | — | loads the next page of the current leaderboard | | `replay.open` | identifier of a leaderboard replay | opens its analysis page | | `replay.back` | — | returns to the preserved selection | | `replay.compare` | identifier of another leaderboard replay, or empty string | chooses or removes the reference, re-evaluated with the main score | | `replay.watch` | — | watches the current replay at the recorded rate, without creating a score | | `replay.share` | identifier of a leaderboard replay | writes this score to a `.pvreplay` file chosen with the native save dialog (see docs/game.md) | | `replay.import` | — | opens a `.pvreplay` file with the native picker; dropping it onto the window does the same thing | | `performance.choose` | identifier of an available calculator, or empty string for Auto | recomputes the performance with the accuracy of the current judgement; model mixes are flagged | | `library.search` | text | search (applied 150 ms after the last keystroke) | | `library.filter.edit` | catalog key | opens the field editor, prefilled if the criterion already exists | | `library.filter.field` | field (`min`, `max`, `text`, `match`), text | edits the draft; `match` is `contains` or `exact`; an empty bound means no limit | | `library.filter.apply` | — | validates and applies the criterion; an error keeps the draft and the previous query | | `library.filter.cancel` | — | discards the draft without changing the results | | `library.filter.remove` | key | explicitly removes this criterion, even if its provider is unavailable | | `library.toggle` | position | opens the set, or closes it if it is open | | `library.select` | position, rank | selects a difficulty (opens its set) | | `library.collapse` | — | closes the open set | | `library.up`, `library.down`, `library.previousSet`, `library.nextSet` | — | see the keys | | `library.viewport` | top, height (px) | offset and height of the rendered list | | `library.metrics` | set step, difficulty step (8 to 1000 px) | geometry of the rendered list | | `library.import`, `library.refresh`, `library.demo` | — | add folders, refresh, demo without audio (the song list's toolbar no longer has a "Demo" button: a template can draw one) | | `library.visualize` | — | opens the map visualizer on the selected chart in place of the list, or closes it; requires the default panel (a template has no viewport to carve out) | | `navigation.open` | destination (`library`, `editor`, `skins`, `settings`, `mods`) | switches page, except `settings`, which opens the modal window on the last category | | `navigation.settings` | category (`gameplay`, `controls`, `audio`, `video`, `judgement`, `scroll`, `library`, `interface`, `mods`; the old `general`, `display` and `hud` open `interface`, `video` and `interface`) | opens the Settings window above the library, on this category | | `navigation.drawer` | — | closes Settings if they are open; otherwise opens or closes the Esc menu | | `judgement.choose` | key of a playable set | chooses this judgement set | | `rating.choose` | key of a registered, visible rating | changes the calculator displayed for the whole library | | `rating.toggle` | key of a registered rating | hides or shows its choice in the selector again, independently of the mod that provides it | | `skin.customize` | — | starts the skin editor on the current skin (`editLayout`); Settings are hidden for the duration of the session | | `skin.resetCustomization` | skin id | removes all of the player's configuration for this skin (`skinConfig` setting, no dedicated host command); refused during a session | | `modOption.set` | element key (`<mod>/<element>`), option name, value (boolean, number or text) | changes a player option of an element (`editElement` with `commit`); a value outside the declaration is refused without a command, numbers are clamped | | `modOption.reset` | element key, option name | restores its declared default value | | `modElement.reset` | element key | restores the default values of all its player options | `invoke` rejects an unknown name (including the names from `Object.prototype`), a different number of arguments, or an argument of the wrong kind (integer, finite number, text of at most 1000 characters, boolean or finite number or text for an option value, known page or category). ## Themes and the behavior layer `pages/Library.svelte` (toolbar, search, import state), `components/SongList.svelte` (the virtual list, `data-pvng-list="sets"`, steps read from the `--pv-set-row/-gap` and `--pv-diff-row/-gap` tokens), `components/SelectedMap.svelte` (left panel, `JudgementPicker`, Play) read `stores` and call `act(...)`; `App.svelte` applies the keymap (`DEFAULT_KEYMAP`, `menu/keys.ts`) and the Esc menu follows `navigation.drawer`. The chosen theme (Skins → Interface, `uiTheme` setting) is the `data-direction` attribute of `<html>`; its `--pv-*` tokens are set by `theme/apply.ts` from the `interfaces` event that the host publishes after validation. The `classic` theme keeps the components' original styles; the others receive the design system's structure (`theme/ui.css`). ## Modifier picker (the map's Mods tab) The **Mods** tab of the selected map (not to be confused with the drawer's **Mods** page, which lists installed mods with their toggles: it is not changed here; a grouped list with one icon per mod would be the logical next step) first shows **Rate** (compact, no paragraph), then the gameplay modifiers as **tiles**: `components/ModPicker.svelte`. This is the **only** interface in this tab: the modifiers and their parameters are the ones the host declares; the interface does not invent any. - **Layout**: the families are side-by-side blocks that **flow across the width of the tab** (flex-wrap): on a single row as long as they fit (the three current families fit on one row at 1400×850, in French too), otherwise a family wraps to the next row, without ever breaking a name. The tiles of a family stay on one row (width based on content, at least 84 px, name at 12 px, no truncation) and do not move when you select one (the name does not turn bold; the space for the Settings button is reserved). Arrows: left/right follow reading order from one family to the next; up/down go to the neighboring row, to the nearest tile by column (nothing below: no effect). - **Families** (small heading, empty families omitted): the host's `group` field (`longNotes`, `layout`, `assist`, `timing`, `difficulty`, `other`), in this order: Long notes first (the built-in No LN and Full LN side by side, in conflict), then Layout, Assists, etc. An unknown group comes last; its texts are `chartgroup.<group>`. - **Tile**: a lucide icon, a short name, a toggle button (`aria-pressed`); when selected, the icon takes the theme accent and the tile carries the accent edge of its plates. The description and the conflicts are in the shared tooltip (`use:tooltip`) and, for screen readers, in `aria-describedby`. Theme tokens only. - **Icons**: the host's `icon` field is looked up in the closed table `lib/mod-icons.ts` (the 28 lucide icons of `MODIFIER_ICONS` in `crates/modding/src/modifiers.rs`, a list that `mod-icons.test.ts` re-reads from the Rust source); any other text yields the puzzle piece, and nothing is ever injected into the page. - **Conflicts**: the host's `conflictsWith`, symmetric (either side is enough). Enabling a modifier **disables** those it conflicts with (`setGameplayMod`) and a polite announcement (`role="status"`) says so; an old selection that contained both shows both tiles with a warning (triangle, `warn` text), and the host plays without either. - **Keyboard**: a single tab stop on the grid (roving tabindex); left/right arrows from one tile to the next, up/down to the neighboring row, Home/End; Space or Enter toggles. Reduced motion removes the transitions. - **A modifier's settings**: a modifier for which the host declares `params` receives, **only while it is selected**, a small "Settings" icon button placed on its tile (a separate tab stop). It opens a small menu (`ChartPopover` with `role="dialog"`, `ModParamsMenu.svelte`): Escape or a click outside closes it and returns focus to the button; it is bounded by the window (it scrolls internally if it is long) and does not move anything in the grid. The menu is **generated** from the host's schema: headings = `section`, a slider + an editable numeric field (unit on the right) for a `slider` parameter, segmented buttons (`radiogroup`, left/right arrows) for a `choice`, only the parameters whose `showWhen` condition is true (`gapMs` if the gap unit is fixed, `gapPercent` if it is in %), a "Defaults" icon button. Each change is written immediately to the `gameplayModParams` setting (same synchronization as the other settings; the host validates, rounds, and records it in the replay), and a status line gives the counter computed by the host (`chartModsPreview`, requested 120 ms after the last change). **Rate** has no options: no settings button. - **Contract**: `GameplayModifierInfo` (`group`, `icon`, `conflictsWith`, `params: ModParamInfo[]`, see docs/modding.md and docs/game.md); the development simulator publishes the Rust schema (`src/mock/full-ln-params.json`, kept up to date by a test). The texts come from the `chartgroup.*` and `chartparam.*` keys, the fallback is the host's English text. - Tests: `lib/mod-picker.test.ts`, `lib/mod-icons.test.ts`, `lib/gameplay-mods.test.ts`; `tests/mod-picker.spec.ts` (tiles, exclusion, tooltip, generated menu, choices and conditions, counter, keyboard, no overlap at 1400×850 and 1000×700 in classic, cabinet, macos).