# Tide Engine documentation
Source revision: 36904d8e07dd044bd665de823e6b8022ed4f4248 (modified working tree).
Documentation SHA-256: ea38a553efadfaf8a016c33e947825b8c4d3d2005abcf32eb4f4a64094909e97.
Website source checkout; not matched to an installed Tide release. Check tide version and the project toolchain.
The language spec is omitted. Read [the spec separately](https://tide-engine.dev/spec.md) or download [the bundle with the spec](https://tide-engine.dev/llms-full-with-spec.txt).
- [Tide Engine | Deterministic Multiplayer Game Engine](#doc-index)
- [Introduction](#doc-guide)
- [Install](#doc-guide--install)
- [Editors](#doc-tools--editors)
- [Your first game](#doc-guide--first-game)
- [Using Tide with AI](#doc-guide--ai)
- [Quick reference](#doc-guide--ai-context)
- [Playground](#doc-guide--playground)
- [Samples](#doc-guide--samples)
- [Earth demo](#doc-guide--earth)
- [Benchmarks](#doc-benchmarks)
- [Components and entities](#doc-game--entities)
- [Systems](#doc-game--systems)
- [The schedule](#doc-game--schedule)
- [Events](#doc-game--events)
- [Commands](#doc-game--commands)
- [Assets](#doc-game--assets)
- [Build code](#doc-game--build-code)
- [Scenes](#doc-game--scenes)
- [State visibility](#doc-game--visibility)
- [Endless worlds](#doc-game--endless-worlds)
- [Async and tasks](#doc-game--tasks)
- [Input](#doc-game--input)
- [Views and drawing](#doc-game--views)
- [Views and the match](#doc-game--views-and-the-match)
- [Draw settings](#doc-game--draw-settings)
- [Meshes and textures](#doc-game--meshes-and-textures)
- [Drawing in 3D](#doc-game--3d)
- [Skinned meshes and animation](#doc-game--animation)
- [Cameras and coordinates](#doc-game--cameras)
- [Render targets and post-processing](#doc-game--render-targets)
- [Frags and verts](#doc-game--shaders)
- [Audio](#doc-game--audio)
- [Local state](#doc-game--local-state)
- [Files and directories](#doc-game--files)
- [GUI](#doc-game--gui)
- [Good-looking UI](#doc-game--ui-style)
- [Packages](#doc-packages)
- [Using and writing packages](#doc-packages--using-and-writing)
- [Render2D](#doc-packages--render2d)
- [Render3D](#doc-packages--render3d)
- [Corner Culling](#doc-packages--cornerculling)
- [Geometry](#doc-packages--geometry)
- [Particles](#doc-packages--particles)
- [Box2D: 2D physics](#doc-packages--box2d)
- [Box3D: 3D physics](#doc-packages--box3d)
- [Rooms](#doc-packages--rooms)
- [Lobby: lobbies and matchmaking](#doc-packages--lobby)
- [Steam](#doc-packages--steam)
- [Voice chat](#doc-packages--voice)
- [Matches](#doc-multiplayer--matches)
- [Managed hosting](#doc-multiplayer--hosting)
- [Shards](#doc-multiplayer--shards)
- [Your own network and service](#doc-multiplayer--own-network)
- [Networking](#doc-multiplayer--networking)
- [Determinism](#doc-multiplayer--determinism)
- [Basics](#doc-language--basics)
- [Structs and functions](#doc-language--functions)
- [Generic functions](#doc-language--generics)
- [Errors](#doc-language--errors)
- [Math](#doc-language--math)
- [Text and lists](#doc-language--text-and-lists)
- [JSON](#doc-language--json)
- [Grids](#doc-language--grids)
- [Namespaces and files](#doc-language--namespaces)
- [Virtual and override](#doc-language--overrides)
- [The tide command](#doc-tools--cli)
- [Tide Motion](#doc-tools--motion)
- [Debugging](#doc-tools--debugging)
- [Debug views](#doc-tools--debug-views)
- [Dev tools](#doc-tools--dev-tools)
- [Usage data](#doc-tools--telemetry)
- [Calling C](#doc-c--functions)
- [C hosts](#doc-c--hosts)
- [A game's own network](#doc-c--network)
---
Source: https://tide-engine.dev/index.md
Build multiplayer games with Tide Engine: deterministic simulation, rollback netcode and an ECS language that compiles to native code or WebAssembly.
# Tide Engine
A networking-first game engine. One deterministic simulation that every player shares, on desktop or in the browser, written in a language made for it.
[Get started](#doc-guide) · [Browse samples](#doc-guide--samples) · [Install](#doc-guide--install)
**Multiplayer by default**: Rollback netcode with full server authority. Clients have no input delay, and single-player is a match too, so there's only one path to get right.
**Deterministic floats**: The same build and the same inputs give the same bits on every platform, the web included. Plain floats, no fixed point.
**A language for the ECS**: Games are written in Tide, a language of its own, built around the ECS. Systems say what they read and write, and the compiler works out the rest. It compiles to C, then to native code or WebAssembly.
**A schedule you can read**: The compiler knows every system's data, so it plans which ones can run at the same time, and tells you why the others wait.
**The web is a real platform**: Every game also builds as one self-contained web page on WebGPU, running the same simulation as desktop.
**Nothing to set up**: One tide command, with clang built in. Write a .tide file and run tide run. Editor support for VS Code and JetBrains IDEs.
Explore the [ECS benchmarks](#doc-benchmarks) for measured workloads, implementation details and comparison methodology.
## A whole game
A game is a folder of `.tide` files, and needs no other code. This one bounces a ball:
```csharp
component Ball
{
float2 position;
float2 velocity = float2(160, 120);
}
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Ball);
}
system Move(mut Ball ball, Time time)
{
ball.position += ball.velocity * time.dt;
if (Math.Abs(ball.position.x) > 300) ball.velocity.x = -ball.velocity.x;
if (Math.Abs(ball.position.y) > 200) ball.velocity.y = -ball.velocity.y;
}
view DrawBalls(Ball ball)
{
Draw.Circle(ball.position, 20, Color.red);
}
```
Save it as `game.tide`, then run `tide run --stats` in its folder. [Install tide](#doc-guide--install) to get started, or see [your first game](#doc-guide--first-game) for a longer tour.
---
Source: https://tide-engine.dev/guide.md
Learn how Tide Engine combines deterministic multiplayer, an ECS and its own language to build games for desktop, Android and the web.
# Introduction
Tide is a game engine built for multiplayer first. Its simulation is deterministic: given the same inputs and commands, it gives the same results on every machine, down to the last bit of every float. Players on desktop, Android and the web share one world, with their inputs and commands driving it.
Games are written in **Tide**, a language of its own, built around an ECS. It compiles to C, and the C to native code or WebAssembly, together with the engine, so calls between your code and the engine's cost nothing.
**Warning: Early days**
Tide is young, and its language changes freely until 1.0. The [language spec](https://tide-engine.dev/spec.md) says which parts are decided and which are still provisional.
## The big ideas
**A game is data and systems.** Entities are made of components, which are plain data. Systems are code that runs every tick, once for each entity that has the components it asks for. Singletons hold what there's one of per world, like the score or the rules.
```csharp
component Health
{
int value = 100;
}
component Poisoned { }
system Poison(mut Health health, with Poisoned)
{
health.value -= 1;
}
```
**Systems say what they touch.** `mut` means a system writes a component, and a plain parameter means it only reads it. `with` and `without` pick entities without reading anything. From that, the compiler plans which systems can run at the same time and which have to wait, and shows you why (see [the schedule](#doc-game--schedule)).
**Everything is a match.** The simulation, called the match, is what every machine runs the same way. It runs on a server, and even single-player is a match on a server this machine runs itself. The engine has rollback netcode built in: clients predict ahead and correct themselves when the server disagrees. See [Matches](#doc-multiplayer--matches).
**Local state is everything else.** Menus, settings, particles and the camera belong to one machine and are never sent. **Views** read the match and draw it once per frame, and they can change local state but never the match. The compiler enforces that boundary, so a view can't break the simulation by accident.
**Players act through inputs and commands.** Movement and held buttons reach the match as [input](#doc-game--input), sampled once per tick and sent over the network. One-off actions, like choosing a team or sending a chat message, use [commands](#doc-game--commands), which the server puts into a tick. Both enter the simulation through match code; views draw the result.
## A tick and a frame
The match advances in fixed **ticks**, 60 per second by default:
1. Systems run, in a fixed order that's the same on every machine.
2. Structural changes (spawning, adding and removing components, destroying) and events apply at the end of the tick, in the order they were made.
The screen updates every **frame**, as fast as the display allows:
1. Views run, drawing the match blended between its last two ticks, so motion is smooth at any tick rate.
2. The GUI draws over the world.
## Where to go next
- [Install tide](#doc-guide--install), then make [your first game](#doc-guide--first-game).
- Give an AI coding agent the [Tide overview, starter prompt and optional skill](#doc-guide--ai).
- Edit and hot reload a running game in the [Playground](#doc-guide--playground).
- Read what a game is made of, a topic at a time, starting with [components and entities](#doc-game--entities).
- See how machines share a match, and how the engine keeps them in step: [matches](#doc-multiplayer--matches), [networking](#doc-multiplayer--networking) and [determinism](#doc-multiplayer--determinism).
- Find optional physics, menus and Steam integration in [Packages](#doc-packages), with setup and API docs for each bundled package.
- Look things up in [the language](#doc-language--basics) and the [tide command](#doc-tools--cli).
- Browse the [samples](#doc-guide--samples) to play complete games in your browser, alone or with friends.
---
Source: https://tide-engine.dev/guide/install.md
Install the tide command on Windows, Linux or macOS, with built-in clang for native and web games, and learn how to update it.
# Install
Tide comes as one command, `tide`, which builds and runs games. It has its C compiler built in (clang), for native and web games alike.
## Windows
In PowerShell:
```powershell
Invoke-RestMethod https://tide-engine.dev/install.ps1 | Invoke-Expression
```
Windows needs nothing else: `tide` brings the headers and libraries games build with.
## Linux and macOS
```sh
curl -fsSL https://tide-engine.dev/install.sh | sh
```
The installer uses `curl`, `tar` and `python3`. Native games also need the system's own headers and libraries:
- **Linux** (x64): your distribution's C development files, which come with gcc: `sudo apt install build-essential` on Debian and Ubuntu, `sudo dnf install gcc` on Fedora. Playing in [rooms](#doc-multiplayer--matches--rooms) needs OpenSSL's `libssl` too, which nearly every distribution has, and so do the players of your game.
- **macOS** (Apple Silicon): Apple's command-line tools, `xcode-select --install`. Install them before tide: they bring the `python3` the installer uses.
## What the installer does
It installs `tide` for your user, in `%LOCALAPPDATA%\Tide` on Windows or `~/.tide` elsewhere, and puts its `bin` folder on your `PATH`: the user's `PATH` on Windows, and elsewhere a line in your shell's profiles (`~/.zshrc`, `~/.bashrc`, `~/.profile` and the like, or fish's `conf.d`). It needs no admin rights. Open a new terminal afterwards so the `PATH` change applies, then check it worked:
```sh
tide version
```
This shows tide's version and channel, where it's installed, and which compilers it found.
The installer also adds Tide to VS Code, Cursor, VSCodium and Windsurf when it
finds them, and to existing JetBrains IDE profiles (2024.2+). JetBrains gets
the plugin bundled with your Tide version, including LSP4IJ when missing;
restart the IDE to load it. Open a new JetBrains IDE once before running
`tide editors`. If you run the installer again when `tide` is already there,
it upgrades it instead, on the channel it's on unless you set `TIDE_CHANNEL`,
and adds Tide to editors installed since.
## Set up your editor
See [Editor setup](#doc-tools--editors) for VS Code, JetBrains, Emacs, Vim and
Neovim. Tide includes the Emacs and Vim/Neovim modes. Run the command for your
editor, then copy its output into your init file:
```sh
tide ide emacs
tide ide vim
tide ide neovim
```
Prefer your existing package manager? Install the MIT plugins through
[Emacs's built-in package-vc](#doc-tools--editors--emacs) or
[vim-plug/lazy.nvim](#doc-tools--editors--vim-and-neovim). Those instructions link
the official public repositories and explain how to connect to Tide's language
server. The Emacs mode installs directly from GitHub; it is not on MELPA yet.
## Nightly versions
Stable versions come out now and then. Nightly versions are previews published when ready. For a nightly version, set `TIDE_CHANNEL` before running the installer:
```powershell [Windows]
$env:TIDE_CHANNEL = 'nightly'
Invoke-RestMethod https://tide-engine.dev/install.ps1 | Invoke-Expression
```
```sh [Linux and macOS]
curl -fsSL https://tide-engine.dev/install.sh | TIDE_CHANNEL=nightly sh
```
**Tip**
This site follows development, so it describes the nightly version. Some of what it shows may not be in the stable version yet.
## Stay up to date
```sh
tide upgrade # the newest version of your channel
tide upgrade --nightly # switch to nightly versions
tide upgrade --stable # back to stable ones
```
`tide` also tells you, at most once a day, when a new version is out. Upgrades check every download against the release's checksums.
`tide upgrade` only ever moves forward. Switching channels, or `tide upgrade --version `, installs what you ask for, even an older version.
An upgrade replaces tide while your editor and your games keep running. When it can't replace a file, because another program is reading it, it stops and says which one. Until it's finished, `tide` builds no games and says the installation isn't whole: close what had the file open and run `tide upgrade` again, which installs the version again even when it's the newest already.
## Uninstall
Delete the folder tide is in (`tide version` says where), and the line that puts its `bin` folder on your `PATH`: on Windows, in **Edit environment variables for your account**; elsewhere, the lines after `# tide` in your shell's profiles, or fish's `conf.d/tide.fish`. Remove the Tide extension from your editors as you would any other.
If you opted into Windows prefab registration, remove
`HKEY_CURRENT_USER\Software\Classes\Tide.Prefab` and the `Tide.Prefab` value
under `HKEY_CURRENT_USER\Software\Classes\.tprefab\OpenWithProgids` in Registry
Editor. Keep any other applications' values.
---
Source: https://tide-engine.dev/tools/editors.md
Set up Tide in VS Code, JetBrains, Emacs, Vim or Neovim with highlighting and language server support.
# Editors
Local worker declarations share normal function navigation and diagnostics.
Hovers and symbol outlines identify them as `local worker`; syntax highlighting
recognizes the modifier without reserving `worker` as an ordinary variable name.
## Choose your editor
[Install Tide](#doc-guide--install) first, then choose your setup:
| Editor | Setup with Tide | Install through your editor's package manager |
|---|---|---|
| [VS Code, Cursor, VSCodium and Windsurf](#doc-tools--editors--vs-code-cursor-vscodium-and-windsurf) | `tide editors` | Installed by Tide |
| [JetBrains IDEs](#doc-tools--editors--jetbrains-ides) | Installed with Tide; run `tide editors` for a new IDE | Bundled plugin; Marketplace also available |
| [Emacs 29.1+](#doc-tools--editors--emacs) | `tide ide emacs` | [tide-emacs](https://github.com/Tide-Engine/tide-emacs) with built-in `package-vc` |
| [Vim 8+](#doc-tools--editors--vim-and-neovim) | `tide ide vim` | [tide-vim](https://github.com/Tide-Engine/tide-vim) with vim-plug |
| [Neovim 0.11+](#doc-tools--editors--vim-and-neovim) | `tide ide neovim` | [tide-vim](https://github.com/Tide-Engine/tide-vim) with lazy.nvim |
For Emacs, Vim and Neovim, the `tide ide` commands print configuration to copy
into your init file; the modes and matching language server already come with
Tide. If you prefer your existing package manager, follow the install examples
in [Emacs](#doc-tools--editors--emacs) or [Vim and Neovim](#doc-tools--editors--vim-and-neovim) below instead.
Choose one installation method per editor.
VS Code and JetBrains select a trusted project's pinned Tide version for both
the compiler and language server. Standalone games use `tide = ` in
`tide.packages`; Unity projects use their locked Tide package and the installation
Unity selected. Open Unity once to resolve and install that version. Installations
selected with Unity's `-tide-command ` are used only while that editor
process is alive; closing it or a crash returns the IDE to the pin. Installations
are shared in `TIDE_VERSIONS` (by default `%LOCALAPPDATA%/Tide/versions` or
`~/.tide/versions`). A missing pinned version is reported rather than silently
using another. Package/lock changes restart the language server; separate VS Code
workspace folders and separate JetBrains projects can use different versions.
Explicit executable settings and a trusted engine checkout's built server take
precedence. In VS Code, `tide.path` also selects its sibling language server unless
`tide.server.path` is set. Emacs/Vim/Neovim retain their configured server command.
The standalone Emacs and Vim/Neovim plugins are MIT-licensed. **Emacs users:
the mode is available directly from GitHub now, but is not listed on MELPA yet.**
The plugins need Tide installed separately for its `tidels` language server.
## Language server features
Tide's language server, `tidels`, comes with `tide`. Open your game's folder, the one you run `tide run` in, and every `.tide` file in it is one game, with its [packages](#doc-packages--using-and-writing). The server provides these features across the game; which appear depends on your editor's language server client:
- Image attribute completion offers `[Linear]` for assets and fields; hover explains sRGB sampling, alpha, valid formats and source-preserving GPU helpers. `Math.ToLinear` and `Math.ToDisplay` offer scalar, float3 and Color signatures.
- Completion, and errors as you type, with quick fixes: a name spelled wrong, a missing `mut`, a missing or stray `out`, an error nothing handles, a name from another namespace, a local that's never read (which is faded), and a parameter that's never used (removed, or a component's made a `with` filter).
- Enum assignments prioritize and preselect the expected enum type: after `zombie.state =`, `ZombieState` comes first, followed by its qualified members. With [enum shorthand](#doc-language--basics--enums-and-switch), `zombie.state = .` offers just that enum's members. A leading dot also completes members in typed declarations, returns, comparisons, enum switch cases and arguments whose parameter type is unambiguous.
- Hovers, go to definition or to a value's type, find usages, the uses of a name highlighted, and rename. A prefab's hover is the prefab as its file writes it, its components and entities (a big one's first lines), and for one made in Unity, the Unity asset it's of.
- Go to implementation, from an event to its handlers, from the input to its `Sample`, `Sanitize` and `Predict` and from a `virtual` declaration to its [override](#doc-language--overrides), and the call hierarchy: what calls a function, and what it calls.
- Formatting, of a file or a selection, parameter hints and inlay hints. Parameter hints list every function that shares the name being called, with every parameter and its default, and follow an argument written by name; where an argument starts, completion offers the names the other parameters go by. Inlay parameter hints label written literal arguments; omitted defaults and arguments already written by name have no label.
- The outline, symbols across the workspace's games, folding, growing a selection, and semantic highlighting. A shared package contributes the declarations active in each game that uses it, with identical symbols listed once.
- After `asset`, completion offers the supported asset types as you start typing, with forms such as `Mesh`, `Grid2` and `Map`. Inside a list or map, it offers the supported element types; mesh vertex and contract arguments offer structs. Assets also complete by name, with their type's methods and parameter hints, including `Texture.Sample` in a frag or vert. They highlight as ordinary read-only variables; fields use the editor's property styling. The editor's theme chooses their colors.
- A known [skinned model or animation asset](#doc-game--animation) exposes its clip names in completion: `hero.animations.idle` or `movement.run`. Hover shows each clip's original source name, and a model exposes its bone names, `defaultPose`, `blendShapes` and `Shaped` too. The editor reads the glTF JSON or FBX catalog without importing geometry or animation samples; invalid or unavailable metadata is diagnosed separately from an absent clip. Their asset paths complete `.glb`, `.gltf` and `.fbx` files.
- Moving a declaration to a file of its own.
- In a [Unity project](#doc-tools--cli--unity), a rename also edits the prefabs and scenes that use the name and the project's C#: a component, field, singleton, event, command, struct, enum, enum member or namespace renamed in Tide is renamed in the scripts of `Assets` and of the project's embedded and local packages, as the C# twins in `Packages/com.tide.game` name it (`_` added where C# needs it). Only references known to be the game's are edited: a member of a value known to be of the game's type (declared as it, a cast, `as`, a pattern, a generic call, or a field, property or method of the project's own classes, partial ones too), a type or namespace the file's usings make the game's, and doc comments' `cref`s. Other comment text, strings, other types' members of the same name and names a type of the project's own also has are left alone.
- Enum completion includes `EnumType.Count()` and `EnumType.Values()`; hover and signature help explain the compile-time member count and the array of every member, with its length. A cast written as `(int)value` reports the Tide spelling, `int(value)`.
- [Assets](#doc-game--assets) kept in step with their files: renaming a file an `asset` names, or a folder above it, in the editor rewrites every path to it, in every file of the game and its packages, each relative to its own file (a glob isn't rewritten: a file it stops matching gets an error instead). Changes to watched asset files refresh their diagnostics, including external glTF buffers and replacement files that keep the same size and timestamp. A file moved outside the editor is found again by its bytes, which `tidels` and `tide` keep the SHA-256 of in the game's `.tide/`: the error says where it is now, with a quick fix that writes the path, or else lists the files of that name, a fix each. Inside an `asset`'s path, completion offers the folders and files it can lead to, the type's own files (`.png`, `.psd`, `.jpg`, `.jpeg`, `.tga` and `.bmp` for a `Grid2`, `Texture`, `Cubemap` or `TextureArray`; `.wav`, `.ogg`, `.mp3` and `.flac` for a `Clip`; `.glb`, `.gltf`, `.fbx` and `.obj` for a `Mesh`; `.glb`, `.gltf` and `.fbx` for a `SkinnedMesh`, `Animation` or `AnimationCatalog`), and `*` and `**/*` with each accepted format for a list, map, cubemap, texture array or combined `AnimationCatalog` catalog. Each literal in an animation file list supports the same path completion and rename edits; checked clip completion cleans exporter names and shows original names and source filenames on hover. Hovering a [`Mesh`](#doc-game--assets--meshes) asset says what its file has: how many vertices and triangles, and whether it has normals, uvs, colors and tangents for the vertex struct to take.
- Each system's place in [the schedule](#doc-game--schedule) above it: its stage, what it reaches through its `World`, each system it waits for and why, what runs alongside it, and for a system that runs for each entity, whether its entities go across threads or what keeps them on one (clicking that goes to the place in its code). A part that names a system goes to it when clicked.
- Above a declaration a package replaced, which package did, and above an [override](#doc-language--overrides), what it replaces. A click goes to the other.
- Above a declaration, how many places name it ("3 references"), which a click lists: types, functions, methods, constants, assets, frags and verts, where "0 references" is code nothing uses. A system, view or handler has the line only when a `[Before]` or `[After]` names it.
- Above functions and methods, an **entry points** lens traces callers through helpers to the systems, views, event or command handlers that can reach them. Input `Sample`, `Sanitize` and `Predict`, custom `Interpolate` methods and audio callbacks are entry points too. Clicking a single entry point goes to its declaration; several open a list to choose from. Each entry point counts once, even through several paths or recursive calls. This is static call reachability, independent of runtime branches; tracing stops at handlers rather than following event sends or command submissions. A helper with no known root says **0 entry points**. The call hierarchy lets you inspect the intermediate calls.
## VS Code, Cursor, VSCodium and Windsurf
VS Code and JetBrains recognize `.tprefab` files as Tide. They use the same
game/package context as scripts, report invalid authored components and references,
and include prefab files when renaming components, fields and named prefabs.
Language-server rename/completion for authored entity names and paths remains
limited. See
[Authored prefabs](#doc-game--scenes--authored-prefabs) for the text format.
The installer adds Tide to the ones it finds, and `tide upgrade` keeps it up to date. Installed one later? Run:
```sh
tide editors
```
An editor window that's open gets a newer extension once it's reloaded: **Developer: Reload Window**.
Renaming a file or a folder in the Explorer asks `tidels` first, so the paths of the assets it holds follow it; the extension asks only about the files assets name, and the folders above them. Moving several files together updates all their asset paths in the same edit, across the games and shared packages affected by the move. A shared package's assets update every consuming game in the workspace. CMake games that list individual files with `SOURCES` work the same way.
The extension runs `tidels` from your `PATH`, or from where `tide` is installed; in a folder with a `build/tools/tidels`, like Tide's own repo once it's built, it runs that one. The `tide.server.path` setting runs another one: in it, `~` is your home folder, and `${workspaceFolder}` and relative paths are the folder whose settings set it. After updating the server, run **Tide: Restart Language Server**. The `tide.trace.server` setting shows what the editor and the server say to each other, in the **Tide Trace** output.
In a folder you haven't trusted (VS Code's Restricted Mode), nothing from it runs: the server is the `tidels` that comes with `tide`, or one your user settings name outside the workspace. Servers on `PATH` inside the workspace are skipped too, including paths through symlinks or junctions. Games don't run, since running one runs its code. Trusting the folder restarts the server.
### Running the game
The play button above a `.tide` file runs its game, which is the folder you opened, or the folder of the game it's in when that has a `tide.packages` of its own; a [package](#doc-packages--using-and-writing)'s file runs the open game that lists it:
- **Tide: Run** plays it in a window of its own, as `tide run` does.
- **Tide: Run on the Web** plays it in a browser tab beside your code: VS Code's integrated browser, or the Simple Browser in editors without it. A game only gets keys while its tab has focus, and the editor may pause it while its tab is hidden, so keep it in a group of its own.
- **Tide: Run on Android** plays it on the Android phone or emulator that's connected, as `tide run --android` does (see [Android](#doc-tools--cli--android)).
Each runs `tide run` in a terminal of its own, so saving a file reloads the game (on Android, builds it again and starts it over), and typing `r` and Enter in that terminal starts it over. Running it again starts the game over. The first run on Android may ask to download Android's tools from Google: type `y` and Enter in that terminal to accept. The `tide.path` setting runs another `tide`.
Starting a replacement waits for the preceding run's processes to stop. Closing its terminal stops the run too. If the editor cannot confirm cleanup, it explains how to stop the remaining processes before running again.
On the web, each reload says what it did in the page's console: **Tide: Game Developer Tools** shows it.
### Debugging
Breakpoints go in `.tide` files, and the **Tide** debug configurations (**Run and Debug**, then add a configuration) stop at them, with your values shown as Tide's: **Attach to Unity (Tide)**, **Debug Tide game**, which builds the game to debug and starts it, and **Attach to Tide game (tide run)**, for the game **Tide: Run** plays. They use Microsoft's C/C++ extension on Windows, and LLVM's LLDB DAP or CodeLLDB on macOS and Linux. In Restricted Mode they don't start. See [Debugging](#doc-tools--debugging).
## JetBrains IDEs
CLion, Rider, IntelliJ and the others, 2024.2 or later: Tide's installer adds
the bundled plugin to existing IDE profiles. It includes LSP4IJ when that
dependency isn't installed, without a Marketplace download. `tide upgrade`
updates Tide in profiles that already have it, using the plugin from the same
Tide release.
For an IDE installed later, open it once to create its profile, then run:
```sh
tide editors
```
Restart the IDE after installation or an upgrade. If it holds the plugin's
files open, close it and run `tide editors` again. Other plugins, settings and
an existing LSP4IJ installation are preserved. A disabled Tide plugin stays
disabled.
Discovery uses the standard JetBrains profile locations on Windows, macOS
and Linux (including Linux's `XDG_CONFIG_HOME` and `XDG_DATA_HOME`). Custom
`idea.config.path` or `idea.plugins.path` locations need manual installation.
You can also install Tide through **Settings > Plugins > Marketplace**;
Marketplace updates follow its chosen channel independently of your CLI.
The plugin runs the `tidels` chosen under **Settings > Languages & Frameworks > Tide**, if any; else the project's own `build/tools/tidels`, like Tide's repo once it's built, once you trust the project; else the one on your `PATH`, or where `tide` is installed. When there's none, `.tide` files say so above the code, with links to install `tide`, choose a `tidels`, or try again. The **Language Servers** tool window restarts the server, after an update, and shows what it and the IDE say to each other.
Renaming a file or a folder (Refactor > Rename, or in the Project view) asks `tidels` first, so the paths of the assets it holds follow it. LSP4IJ asks about every file, and `tidels` answers from the game's assets.
JetBrains' dark color schemes draw type names like plain text, so Tide's types stay uncolored until you pick colors. Each kind of type has its own color under **Settings > Editor > Color Scheme > Language Server**:
- **Struct type**: components
- **Classes > Class reference** and **Class declaration**: singletons
- **Interface**: inputs
- **Type**: built-in types such as `Color`, `Entity` and `Devices`
### Running the game
Right-click a `.tide` file and pick **Run**, or press Ctrl+Shift+F10 in it (Ctrl+Shift+R on macOS), to run its game, which is the project's folder, or the folder of the game it's in when that has a `tide.packages` of its own; a [package](#doc-packages--using-and-writing)'s file runs the project's game when it lists the package. The run is named after the folder, like `mygame`:
- **mygame** plays it in a window of its own, as `tide run` does.
- **mygame (web)** plays it on the web, in the **Tide Game** tool window. Its **Open DevTools** button shows the page's console, where each reload says what it did. The game only gets keys while the tool window has focus.
- **mygame (Android)** plays it on the Android phone or emulator that's connected, as `tide run --android` does (see [Android](#doc-tools--cli--android)).
They're Tide run configurations, which you can also make and edit under **Run > Edit Configurations**, where **Play it** picks among the three. They use `tide run`. `tide`'s output is in the Run tool window, where an error's place links to the file: saving a file reloads the game (on Android, builds it again and starts it over), and typing `r` and Enter there starts it over. The first run on Android may ask to download Android's tools from Google: type `y` and Enter there to accept. A run configuration can run another `tide`.
### Debugging
In CLion, breakpoints go in `.tide` files. **Run > Debug Tide Game** (also in a `.tide` file's context menu) plays the game as its run configuration does and attaches the debugger; **Run > Attach to Unity (Tide)** attaches to the Unity editor running the project. Both stop at your breakpoints and show your values as Tide's. On Windows, put the **Visual Studio** toolchain first, whose debugger reads the game's `.pdb`. See [Debugging](#doc-tools--debugging).
## Emacs
### Install with a package manager
The official [tide-emacs repository](https://github.com/Tide-Engine/tide-emacs)
can be installed directly with Emacs 29.1+'s package manager. Evaluate this once:
```elisp
(require 'package-vc)
(package-vc-install
'(tide-lang-mode :url "https://github.com/Tide-Engine/tide-emacs"))
```
Add this to your init file:
```elisp
(require 'tide-lang-mode)
(add-hook 'tide-lang-mode-hook #'eglot-ensure)
```
Install Tide separately and put `tidels` on Emacs's `exec-path`. The package
manager updates the mode; `tide upgrade` updates the compiler and server.
Use **M-x package-vc-upgrade** to update the mode. A MELPA recipe is prepared,
but the package is not listed there yet: its submission rules require a month
of public maintenance and human review.
### Use Tide's bundled mode
Tide bundles [tide-lang-mode](https://github.com/Tide-Engine/tide-emacs)
for Emacs 29.1 or later. Run:
```sh
tide ide emacs
```
Copy the result into your Emacs init file (usually `~/.emacs.d/init.el`), then
restart Emacs. It loads the bundled mode, selects this installation's `tidels`
by its full path and connects through Eglot when you open a Tide file. Emacs
does not need `tidels` on its `exec-path` with this configuration.
It detects `.tide` and `.tprefab`, with basic highlighting, four-space C-style
indentation and comment editing. The name is separate from the TypeScript
package called `tide`.
To connect manually instead, omit the generated hook below and use **M-x eglot**
in a Tide buffer. To select another server, change `tide-lang-server-command`:
```elisp
(setq tide-lang-server-command '("/path/to/tide/bin/tidels"))
;; The helper includes this for automatic connection:
(add-hook 'tide-lang-mode-hook #'eglot-ensure)
```
Use **M-.** for definitions, **M-?** for references, **C-M-i** for completion,
**M-x eglot-rename** and **M-x eglot-format-buffer**. See
[Eglot's setup guide](https://www.gnu.org/software/emacs/manual/html_node/eglot/Setting-Up-LSP-Servers.html)
for client configuration.
## Vim and Neovim
### Install with a plugin manager
The official [tide-vim repository](https://github.com/Tide-Engine/tide-vim)
works directly with Git-based plugin managers. In an existing vim-plug setup,
add this between `plug#begin()` and `plug#end()`, then run **:PlugInstall**:
```vim
Plug 'Tide-Engine/tide-vim'
```
For lazy.nvim on Neovim 0.11+, add this plugin specification:
```lua
{
'Tide-Engine/tide-vim',
lazy = false,
config = function()
vim.lsp.enable('tidels')
end,
}
```
Install Tide separately and put `tidels` on `PATH`. Use your plugin manager
to update the runtime and `tide upgrade` to update the compiler and server.
Plain Vim still needs a separately configured LSP client.
### Use Tide's bundled runtime
Tide bundles the [Tide Vim runtime](https://github.com/Tide-Engine/tide-vim)
for Vim 8+ and Neovim. Print the configuration for your editor:
```sh
tide ide vim
tide ide neovim
```
Copy the Vim output into your vimrc (`~/.vimrc`, or `~/_vimrc` on Windows),
or the Neovim output into `init.lua` (usually `~/.config/nvim/init.lua`, or
`%LOCALAPPDATA%/nvim/init.lua` on Windows). Custom configurations can use the
same output in their own init file. Restart the editor after adding it.
Both `.tide` and `.tprefab` get highlighting, four-space C-style indentation
and comment settings. Interpolated strings have string highlighting throughout.
The Neovim configuration requires 0.11 or later and enables the supplied
language server configuration automatically, using this installation's full
`tidels` path. No `nvim-lspconfig` plugin or server lookup on `PATH` is needed.
To select another executable, call
`vim.lsp.config('tidels', { cmd = { '/path/to/tide/bin/tidels' } })` before
enabling it. The configuration selects the nearest `tide.packages`, then a
CMake/Git root, then the source file's folder. Use **K** for hover,
`:lua vim.lsp.buf.definition()`, `:lua vim.lsp.buf.rename()` and
`:lua vim.lsp.buf.format()`. Neovim's **:help lsp** describes completion and
other client features; see its [LSP guide](https://neovim.io/doc/user/lsp/).
Plain Vim needs a language server client of your choice. Register filetype
`tide` with the server command printed in the snippet's comments, over stdio.
The runtime does not install a client.
These [setup helpers](#doc-tools--cli--ide) print configuration; they do not change your
init files. If you move Tide, generate the configuration again and replace the
old paths. `tide editors` installs the VS Code extension. Enable automatic server
startup only for projects you trust.
Choose either the package-manager copy or Tide's bundled copy of each mode;
loading both can make it unclear which version your editor is using.
Use `tide run` in a terminal for games.
The terminal integrations do not adapt the VS Code-specific clickable code-lens
commands.
## Other editors
`tide`'s `editors` folder holds the TextMate grammar (`tide-syntax`), a VS Code-style bundle, for highlighting in editors that load those. Any editor with a language server client can run `tidels`, from `tide`'s `bin` folder, for everything else. It talks over stdin and stdout.
---
Source: https://tide-engine.dev/guide/first-game.md
Build your first Tide game with components, systems, input and drawing, then host a multiplayer match and invite another player.
# Your first game
This page builds a small game: a ball bouncing around, and a player for everyone who joins, which they steer with the keyboard. It takes a few minutes, and shows most of what a Tide game is made of.
You'll need `tide` [installed](#doc-guide--install). [Set up your editor](#doc-tools--editors)
for highlighting, completion and diagnostics before writing your first file.
Working with an AI coding agent? Use the [Tide overview and starter prompt](#doc-guide--ai)
to give it the language context and validation commands.
## A folder of files
A game is a folder of `.tide` files: every `.tide` file in it and its subfolders, but for hidden ones, whose names start with a dot. Every declaration is visible from every file, with no imports. Make a new folder, and a file in it called `game.tide`.
## Data: components
Entities are made of **components**, plain data with fields. Fields can have defaults, and start at zero otherwise.
```csharp
component Body
{
float2 position;
float2 velocity;
float radius = 20;
}
component Ball { }
```
`Ball` has no fields: it marks which bodies are balls.
## Where it starts: the Main scene
The game starts in the scene called `Main`. When it loads, it gets the built-in `Spawned` event, and a handler of that event sets it up:
```csharp
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Body { velocity = float2(160, 120) }, Ball);
}
```
`Spawn` makes an entity from a list of components. `Body { velocity = ... }` sets one field and leaves the others at their defaults, and a bare `Ball` has all of them at their defaults.
## Behavior: systems
A **system** runs every tick, once for every entity that has the components it takes. Parameters are read-only, unless they're `mut`. `with Ball` only picks entities that have a `Ball`, without reading it.
```csharp
system Move(mut Body body, Time time)
{
body.position += body.velocity * time.dt;
}
system Bounce(mut Body body, with Ball)
{
if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x;
if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y;
}
```
`Time` is a built-in singleton: there's one per world, and `time.dt` is the length of a tick in seconds. Systems run in the order they're written, and always in the same order on every machine.
## Drawing: views
A **view** looks like a system, but it runs once per frame instead of once per tick, and it can only read the match. `Draw` functions only work in views.
```csharp
view DrawBalls(Body body, with Ball)
{
Draw.Circle(body.position, body.radius, Color.red);
}
```
The camera starts at the origin, one world unit per pixel, with `y` up.
## Run it
In the folder:
```sh
tide run --stats
```
`tide` compiles the game and opens a window with the ball bouncing. It keeps its work in a hidden `.tide` folder, which you can delete any time. Whenever you save, `tide` rebuilds the game and the window picks up the new code (see [hot reload](#doc-tools--cli--hot-reload)).
This is the game so far, built for the web and running in the page:
**The game so far** ([Run example](https://tide-engine.dev/examples/first-ball/?stats))
```tide
component Body
{
float2 position;
float2 velocity;
float radius = 20;
}
component Ball { }
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Body { velocity = float2(160, 120) }, Ball);
}
system Move(mut Body body, Time time)
{
body.position += body.velocity * time.dt;
}
system Bounce(mut Body body, with Ball)
{
if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x;
if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y;
}
view DrawBalls(Body body, with Ball)
{
Draw.Circle(body.position, body.radius, Color.red);
}
```
The next part adds players.
## Players and input
Each player's **input** is what the network sends of them, once per tick. It's declared once per game, and its `Sample` method fills it on the player's own machine, from this machine's `Devices`:
```csharp
input Controls
{
float2 move;
Sample(Devices devices)
{
var keys = devices.keyboard;
if (keys.d.pressed) move.x += 1;
if (keys.a.pressed) move.x -= 1;
if (keys.w.pressed) move.y += 1;
if (keys.s.pressed) move.y -= 1;
}
}
```
Keys are named by their position on a US keyboard, so `WASD` is in the same place on every layout.
When a player joins, the world gets the built-in `PlayerJoined` event. This handler gives them a body, with an `Owner`, a built-in component that ties an entity to a player:
```csharp
event(PlayerJoined joined) AddPlayer()
{
Spawn(Body { radius = 16 }, Owner { player = joined.player });
}
```
A system that takes the input gets the input of the player who owns the entity it's running for:
```csharp
system Steer(Controls input, mut Body body, with Owner)
{
body.velocity = Math.Normalize(input.move) * 250;
}
```
Put `Steer` before `Move`, so bodies move the tick they're steered. Last, draw the players. Views can read `Session`, where this machine stands, so yours can be yellow and the others gray:
```csharp
view DrawPlayers(Body body, Owner owner, Session session)
{
var color = owner.player == session.player ? Color.yellow : Color.gray;
Draw.Circle(body.position, body.radius, color);
}
```
A view that's only for your own player, like a camera that follows them, picks them with a filter instead: `with ownership` (see [Your own entities](#doc-game--views-and-the-match--your-own-entities)).
Save, then type `r` and press Enter in `tide`'s terminal, and steer with `WASD`. The game carried over to the new code when you saved, but your player had joined before `AddPlayer` existed, so they had no body yet. Starting over makes them join again.
## Play together
Single-player was already a match, on a server this machine ran for itself. So the same game plays with others. In one terminal:
```sh
tide run --host --stats
```
And in another, on this machine or another one on the network:
```sh
tide run --connect localhost --stats
```
Use the host's address instead of `localhost` from another machine, like `tide run --connect 192.168.1.5 --stats`. The host takes players on UDP port 7777; `--host 8000` picks another. Each player steers their own yellow body, with no input delay.
Where nobody is there to steer (a test, a build server, an agent), `tide run --players 2 --frames 300 --capture match.png --stats` plays both at once with no window, and writes a picture from each machine: `match-1.png` and `match-2.png` (see [Several players](#doc-tools--cli--several-players)).
No input delay means a machine doesn't wait to hear what the other players did: it guesses, by repeating their last input for a moment, and puts the match right when the server's answer arrives. That moves their body in one frame, each time they start or stop, by up to what they move in 0.15 seconds (see [What other machines guess](#doc-game--input--what-other-machines-guess)). Mark the position, and views draw the correction over a few frames instead:
```csharp
component Body
{
[Position] float2 position;
float2 velocity;
float radius = 20;
}
```
Only what's drawn changes: the match is put right at once, the same on every machine (see [correction smoothing](#doc-game--views--provisional-correction-smoothing)).
Here are two machines in one match, each running [the whole game](#doc-guide--first-game--the-whole-game): the first hosts it, and the second joined its room, as `tide run --join` does with a room's code (see [Matches](#doc-multiplayer--matches--rooms)). Click a frame so it has the keyboard, and steer with `WASD`: its player is yellow there, and gray in the other frame.
**Two players, in one match** ([Run example](https://tide-engine.dev/examples/first-game/?stats))
## Build it for the web
```sh
tide run --web --stats
```
This builds the game as a web page, which draws with WebGPU, and opens it in your browser. `tide` serves the page on your machine and keeps running until you stop it with Ctrl+C. Saving a file reloads the game in the page. For a page to put online:
```sh
tide build --release --web
```
It goes in `.build/web/`, a folder to put online as it is: `index.html`, which shows the game downloading, and the game's files beside it, which browsers keep between visits. To try that page on your own machine, serve the folder (`npx serve .build/web`): a page opened from disk can't download its files. `tide build --release --web --single-file` makes one `.html` file with the game inside instead, which opens straight from disk. Web and desktop players play together in rooms, which they join by a code (see [Matches](#doc-multiplayer--matches--rooms)).
## The whole game
Click the game so it has the keyboard, and steer with `WASD`.
**game.tide** ([Run example](https://tide-engine.dev/examples/first-game/?stats))
```tide
component Body
{
[Position] float2 position;
float2 velocity;
float radius = 20;
}
component Ball { }
input Controls
{
float2 move;
Sample(Devices devices)
{
var keys = devices.keyboard;
if (keys.d.pressed) move.x += 1;
if (keys.a.pressed) move.x -= 1;
if (keys.w.pressed) move.y += 1;
if (keys.s.pressed) move.y -= 1;
}
}
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Body { velocity = float2(160, 120) }, Ball);
}
event(PlayerJoined joined) AddPlayer()
{
Spawn(Body { radius = 16 }, Owner { player = joined.player });
}
system Steer(Controls input, mut Body body, with Owner)
{
body.velocity = Math.Normalize(input.move) * 250;
}
system Move(mut Body body, Time time)
{
body.position += body.velocity * time.dt;
}
system Bounce(mut Body body, with Ball)
{
if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x;
if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y;
}
view DrawBalls(Body body, with Ball)
{
Draw.Circle(body.position, body.radius, Color.red);
}
view DrawPlayers(Body body, Owner owner, Session session)
{
var color = owner.player == session.player ? Color.yellow : Color.gray;
Draw.Circle(body.position, body.radius, color);
}
```
## Next
- `tide schedule` shows which of these systems could run at the same time, and why the others wait. See [the schedule](#doc-game--schedule).
- Read what a game is made of, a topic at a time, starting with [components and entities](#doc-game--entities). The language itself starts with [the basics](#doc-language--basics).
- Browse the [samples](#doc-guide--samples) for complete games to play in your browser, with links to their source.
---
Source: https://tide-engine.dev/guide/ai.md
Give your AI coding agent a Tide overview, persistent project instructions and an optional portable skill, with downloadable Markdown documentation.
# Using Tide with AI
An AI agent can work with Tide without knowing it beforehand. Give it the [quick reference](#doc-guide--ai-context), access to the relevant references, and a compiler it can use to check its work. Start with the guide; add project instructions or the skill when you want the setup to carry across conversations.
## Start a conversation
Copy the starter prompt above and add what you want to build. It points the agent to the compact overview and asks it to validate its changes. If your chat cannot fetch links, download the guide and attach it instead. For work needing more APIs without internet access, also attach the [full documentation bundle](https://tide-engine.dev/llms-full.txt); ask the agent to search the relevant topic rather than read it all at once.
The starter prompt is also plain text:
```text
This project uses Tide. Before writing code, read the project's instructions and https://tide-engine.dev/guide/ai-context.md (or the attached Tide overview). Use its linked topic references for exact APIs; https://tide-engine.dev/llms.txt is the documentation index.
Inspect the existing project and run tide version. The website can be newer than the installed compiler; use project-pinned documentation when available and do not silently upgrade the toolchain. Build early, fix diagnostics, and validate the requested behavior with bounded hidden runs and captures when execution tools are available. Report what you actually tested and any unavailable coverage.
Task:
```
Tell the agent the gameplay you want, the intended platforms and any existing project conventions. An agent with a terminal can compile and inspect captures. A chat without filesystem or execution tools can suggest code, but you will need to build and test it yourself.
## Play a game interactively
An agent with process input/output and image tools can play the same running
game dynamically: `tide run --interactive play.txt` draws its first frame and
waits. Send `capture menu.png`, inspect the PNG, queue future-frame script
lines such as `2 mouse 640 353` and `3 button left`, then send `step 30`.
Wait for `tide: interactive ready 31`, inspect another capture and choose the
next actions. The game waits while the agent thinks; `quit` or closing input
ends it. Executed actions are saved to `play.txt` for normal scripted replay.
For GUI widgets, `controls` lists each one with its label and position, and
`click "Play"` (or `click 1`) clicks it. This works whatever size the
picture is, with no guessing of pixels.
For an agent's terminal tools, use a persistent terminal session (a PTY when
needed) and retain its session handle. Launch the command without waiting for
the game to exit. Write subsequent control lines to that same session. After
`capture`, use the agent's image-viewing tool to actually inspect the picture,
then choose the next input from what it shows. Keep repeating this loop in the
same process; `play.txt` is the automatic recording, not a command inbox. The
agent needs terminal-session input and image viewing, with no additional file
control channel or game-specific integration.
See [Interactive play](#doc-tools--cli--interactive-play) for the protocol,
multiple players and limits. This uses ordinary player input and rendered
pictures; it does not require game-specific agent code.
## Profile a game
An agent can collect a structured report from the standard host without opening
the profiler panel or writing a custom C host:
```sh
tide run --release --script play.txt --frames 360 --profile profile.json --profile-warmup 60
```
Set `TIDE_HIDDEN=1` in the agent's shell before native runs. Use a script that
reaches the situation being investigated; interactive play can record it first.
Keep the same seed, resolution, player count and saves for comparisons. The
report is written when the run ends and identifies measured frames, CPU work,
system/view source locations, GPU totals and per-pass timings with shader membership,
and engine draw counters. For GPU optimization, rank `gpu_passes.rows` and inspect
its coverage counters before changing rendering work.
It measures actual work rather than treating the hidden run's fixed simulation
step as a frame-time result. Capture is currently native desktop only.
Check the schema version, measured-frame count, build metadata and dropped-row
counters before ranking costs. Source locations identify declarations; worker
rows are aggregate categories, and helpers remain inside their caller's time.
Ask the agent to connect cost to useful work: for example, how many mesh
instances were tested and rejected while recording an expensive view. A low
culling rejection rate suggests inspecting earlier visibility selection; it
does not prove culling can be removed, especially for another camera or shadow
pass. Make one change, replay the same scenario in an optimized build, compare
the report and inspect captures. Include simulation checks when the change
could affect the match, and repeat measurements when noise could explain the
difference. See [Profile captures](#doc-tools--debug-views--profile-captures) for
timing meanings, limits and the culling example.
## Keep project context between conversations
Put the [starter AGENTS.md](https://tide-engine.dev/ai/AGENTS.md) in your **game folder** and keep it in source control. Merge it into existing instructions rather than overwriting them. It points to the overview and contains game build/run guidance. Add your own project's important decisions and validation commands as they become established. This is separate from the Tide engine repository's contributor guide.
[Codex reads AGENTS.md](https://learn.chatgpt.com/docs/agent-configuration/agents-md) as project instructions. Current [Claude Code versions can read AGENTS.md](https://code.claude.com/docs/en/memory#agentsmd), subject to their instruction-file settings. For a Claude setup that does not load it, put the [starter CLAUDE.md](https://tide-engine.dev/ai/CLAUDE.md) beside it; the file imports `AGENTS.md` rather than duplicating its rules. If you already have `CLAUDE.md`, add the import to it:
```text
@AGENTS.md
```
Other agents have their own discovery rules. Explicitly ask your agent to read the project instructions if its client does not load them automatically. A web link alone is not guaranteed to be fetched or remembered in a new chat.
For an offline project, save the overview as `TIDE.md` next to `AGENTS.md`; the starter instructions prefer that local copy. Keep its source-revision header when updating it.
## Install the optional Tide skill
Download [tide-skill.zip](https://tide-engine.dev/ai/tide-skill.zip). It contains one `tide` folder with `SKILL.md` and a generated `references/overview.md`, the same overview shown in the docs. The skill guides an agent through version checks, topic lookup, implementation and bounded validation. It does not install Tide or grant the agent additional permissions.
Extract the `tide` folder into your agent's project skill directory:
- **Codex:** `.agents/skills/tide/`, with `SKILL.md` directly inside it. Invoke it as `$tide`, or let the agent select it for a matching task. See the [OpenAI skill documentation](https://learn.chatgpt.com/docs/build-skills).
- **Claude Code:** `.claude/skills/tide/`, with `SKILL.md` directly inside it. Invoke it as `/tide`, or let Claude select it. See [Claude's skill documentation](https://code.claude.com/docs/en/skills).
- **Other compatible agents:** install the folder using the client's [Agent Skills](https://agentskills.io/home) support. The format is portable; discovery and installation paths depend on the client.
The skill and `AGENTS.md` serve different purposes: project instructions retain this game's rules, while the skill supplies a reusable Tide workflow. Either can use the same overview. No MCP server is required to read the docs or use the local compiler.
## Match the documentation to your tools
Run `tide version` when starting a project or diagnosing a compiler error. The website and its downloads identify their documentation source revision; they are not a release archive and may describe features newer than your installed Tide. Keep a known-working compiler version and the downloaded guide together when pinning a project. Prefer that project's versioned references when supplied, and verify unfamiliar syntax with the compiler.
Updating the guide or skill is an explicit download; existing project copies are not silently replaced. Do not solve a docs/compiler mismatch by upgrading the user's toolchain without their agreement.
## Reference downloads
Every documentation page has a clean Markdown export at its page URL plus `.md`, for example `/game/commands.md`; the introduction is `/guide.md`. Exports include source examples as code, without needing the website's embedded game controls.
- [Quick reference](#doc-guide--ai-context): the first attachment for a new conversation. Use the download button above for the Markdown file.
- [Documentation index](https://tide-engine.dev/llms.txt): a small list of topics and Markdown links for agents with web access.
- [Full documentation bundle](https://tide-engine.dev/llms-full.txt): an optional single file for offline search.
- [Project instructions](https://tide-engine.dev/ai/AGENTS.md), [Claude import](https://tide-engine.dev/ai/CLAUDE.md), and [starter prompt](https://tide-engine.dev/ai/starter-prompt.txt): editable starting points for your game.
Keep descriptions of your game's intent and decisions in the project. When the agent repeatedly misunderstands a Tide feature, retain the failing request and compiler diagnostic so the guide can be corrected against a real example.
---
Source: https://tide-engine.dev/guide/ai-context.md
Tide on one page: a complete game, the essential rules of the language and engine, and links to each topic's full reference.
# Quick reference
Tide on one page: a complete game, the rules most games rely on, and links to each topic's full reference. It covers the common path; follow the links when a task needs more. It's also the page to give an AI agent: [Using Tide with AI](#doc-guide--ai) explains how.
## Find the project and version
A Tide game is a folder of `.tide` files, including its subfolders. Declarations are visible across files without imports. An ordinary new game needs no project generator, CMake project or C host: create a folder and a `game.tide`. Optional packages are listed in `tide.packages`; [authored scenes and prefabs](#doc-game--scenes) also use `.tprefab` files. Every `.tide` file under the folder is compiled, except in hidden folders, whose names start with a dot: `tide build` writes to `.build/`, and scratch or probe copies of the game belong in a hidden folder or outside the game folder.
Inspect the existing game and its instructions before changing it. Run `tide version` to identify the installed compiler and `tide help build` or `tide help run` for its actual CLI. These docs describe the website's source revision, which can be newer than an installed release. Prefer documentation supplied with the project's pinned toolchain when available. On a mismatch, report the versions and use compiler diagnostics to check the relevant feature; do not silently upgrade the user's installation.
## A complete game
Save the following as `game.tide` in an otherwise empty game folder. It is the same source used by [Your first game](#doc-guide--first-game): a bouncing ball and a WASD-controlled player for each joining player. The built-in host starts the match and joins a player even in single-player.
```tide
component Body
{
[Position] float2 position;
float2 velocity;
float radius = 20;
}
component Ball { }
input Controls
{
float2 move;
Sample(Devices devices)
{
var keys = devices.keyboard;
if (keys.d.pressed) move.x += 1;
if (keys.a.pressed) move.x -= 1;
if (keys.w.pressed) move.y += 1;
if (keys.s.pressed) move.y -= 1;
}
}
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Body { velocity = float2(160, 120) }, Ball);
}
event(PlayerJoined joined) AddPlayer()
{
Spawn(Body { radius = 16 }, Owner { player = joined.player });
}
system Steer(Controls input, mut Body body, with Owner)
{
body.velocity = Math.Normalize(input.move) * 250;
}
system Move(mut Body body, Time time)
{
body.position += body.velocity * time.dt;
}
system Bounce(mut Body body, with Ball)
{
if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x;
if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y;
}
view DrawBalls(Body body, with Ball)
{
Draw.Circle(body.position, body.radius, Color.red);
}
view DrawPlayers(Body body, Owner owner, Session session)
{
var color = owner.player == session.player ? Color.yellow : Color.gray;
Draw.Circle(body.position, body.radius, color);
}
```
Build with `tide build`. For a human's interactive session, `tide run --stats` watches files and reloads when they change. Automated checks (a script, CI or an AI agent) use a bounded hidden run instead, as shown below.
## The model
- **Components** hold each entity's data. A component with no fields is a tag. **Singletons** hold one value per world; declare one with `singleton Score { int value; }` and request it as a parameter.
- **Systems** run each fixed tick for every entity matching their component parameters. `mut Body body` writes data, `Body body` reads it, and `with Ball` or `without Ball` filters without reading data. Repeat the modifier for each filter: `with Ball, without Frozen`. A system with only singleton/input parameters runs once per tick. Use `this` for its current entity, not an invented entity parameter.
- **Views** run each rendered frame, in declaration order, and later views draw on top. They read the presented match and draw; they can change local state, but cannot change match state. `Time` is a singleton: a system takes a `Time time` parameter and moves by `time.dt`, the fixed tick interval. Views animate local effects by `Frame.dt`, the frame interval. `Frame` and `Screen` are not parameters: views read `Frame.dt`, `Screen.width` and `Screen.height` directly. [Views](#doc-game--views) explains interpolation and drawing order.
- **Events** notify code inside the game. `scene Main;` is the initial scene; `event(Spawned) Setup(with Main)` initializes it once. `event(PlayerJoined joined) ...` initializes a joining player's entities. [Events](#doc-game--events) explains handlers and their data parameters.
- Every game is a networked **match**, including single-player. Keep gameplay state in match components and singletons. Menus, camera preferences and presentation-only effects belong in `local singleton`, `local` fields or local entities. [Local state](#doc-game--local-state) explains their lifetimes and access.
Systems declare access so the compiler can schedule them. Component filters create no data dependency. Conflicting systems follow deterministic declaration order unless explicit ordering changes it; put a system that sets velocity before one that integrates it. See [Systems](#doc-game--systems) and [The schedule](#doc-game--schedule).
## Syntax that matters
Values are read-only unless declared `mut`, including locals. `var value = ...;` infers a read-only type; use `mut var value = ...;` for an accumulator that changes. A `for (var i = 0; i < n; i++)` loop permits its step to change `i`; changing it inside the body requires `mut var`. Fields are writable through a mutable component or singleton binding. Pass singletons explicitly through helper parameters instead of looking them up by type.
Construct components with `Body { radius = 12 }`, without `new`. Fields not specified use defaults or zero. `float2(x, y)` constructs a vector; arithmetic is component-wise, and `==`/`!=` compare two vectors whole, giving one bool (`if (cell == target)`), so no `Same(a, b)` helper is needed. `Math` supplies deterministic operations such as `Math.Normalize`, `Math.Length`, `Math.Clamp` and `Math.Sin`. Angles are radians; `90deg` is a radians literal. String interpolation is `$"Score: {score.value}"`. Fixed tables of plain values (no text) are constants: `const float[3] SPEEDS = [1, 2.5, 4];` or `const List QUAD = [0, 1, 2, 0, 2, 3];`, up to 4096 values written out, read as `SPEEDS[int(kind)]` anywhere, GPU code included; `Kind.Values()` is every member of an enum, for `foreach`, and two values of one enum order with `<`. Read [Basics](#doc-language--basics), [Functions](#doc-language--functions), [Math](#doc-language--math) and [Text and lists](#doc-language--text-and-lists) for signatures, collections and copy/borrow rules.
`Spawn(Body { position = at }, Ball)` returns an `Entity` handle. `entity.Add(Component { ... })`, `entity.Remove(Component)` and `entity.Destroy()` record structural changes. Those changes apply at the end of the tick, not immediately: a spawned entity cannot be queried yet, and recording a destroy does not remove a row from a running query. Guard against counting the same pending removal twice. Entity changes in local code apply to local entities at the local frame boundary. See [Entities](#doc-game--entities).
For a second set of entities, declare a query parameter:
```csharp
system CountBalls(query (with Ball) balls, mut Score score)
{
mut var count = 0;
foreach (var ball in balls) count += 1;
score.value = count;
}
```
This fragment assumes the `Ball` tag and `Score` singleton above. Query bindings are read-only match data; a row exposes its bound values and `.entity`. An ordinary explicit `World world` parameter supports handle lookups, for example `world.Get(entity)` (a copy) and `world.Has(entity)`. A `mut World world` parameter permits `world.Set(entity, replacement)`, and changing another entity's component in place with `world.Edit(entity, body) { body.velocity.y = 5; }`: in the block, `body` is that entity's component, put back when the block ends, even on `return` or `continue`; an entity without one skips the block. Prefer `Edit` to a `Get`, a change and a `Set`. Look up the [query and World rules](#doc-game--systems--another-set-of-entities) before building cross-entity changes; do not invent `world.Entities`, `GetComponent` or writable query bindings.
## Input and submitted actions
Use a declared `input` for per-tick controls, as in the complete game. `Sample(Devices devices)` reads this machine's devices; gameplay systems receive the input of the entity's `Owner`. `Owner.player` is a `PlayerID`. The input sampler starts from field defaults each tick. Keys are named as in Unity's Input System: `a`, `space`, `r`, `leftArrow`, `upArrow`, `digit1`, `leftShift`.
Input carries whether keys are **held**: a late player's input is guessed by repeating it, and a repeated "just pressed" would press twice. In `Sample`, record `.pressed`, not a key's `.down`. Match code gets one-shot edges from the input's own `bool` fields, which have `.down` and `.up`:
```csharp
input Controls
{
bool restart;
Sample(Devices devices) { restart = devices.keyboard.space.pressed; }
}
system Restart(Controls input, mut Score score, with Owner)
{
if (input.restart.down) score.value = 0;
}
```
A view can read local devices, including `.down` edges, but its device reads cannot directly alter the match: a view turns a press into a command, below. See [Input](#doc-game--input).
Use typed **commands** for submitted actions from local UI. A minimal entity-targeted action is:
```csharp
component Ready { bool value; }
command SetReady { bool value; }
view ReadyButton(Ready ready, with ownership)
{
if (GUILayout.Button(ready.value ? "Unready" : "Ready"))
this.Send(SetReady { value = !ready.value });
}
command(SetReady action) ApplyReady(mut Ready ready, with ownership)
{
ready.value = action.value;
}
```
Spawn `Ready` alongside each player's `Owner` to use this fragment. In a command handler, `with ownership` runs it only for an entity the command's sender owns (`without ownership`, only for others'); a handler without it names the sender, `command(SetReady action, PlayerID sender)`, and checks it, such as `if (sender != owner.player) return;`. The connection supplies the sender; never trust a sender ID in the payload. Validate ownership and game rules before writing state. Handlers return void, with ordinary guard clauses. They have no acceptance method or transaction. A global command uses `Send(...)`; an entity-targeted command uses `entity.Send(...)`. See [Commands](#doc-game--commands) and [GUI](#doc-game--gui).
Initialize multiplayer entities in `PlayerJoined`, and clean up their entities/state in `PlayerLeft` when the game needs it. **Treat `PlayerID` as an opaque identity, not a display index:** retain `joined.player` or read an entity's `Owner.player`; do not assume the players are `PlayerID(1)` and `PlayerID(2)`. When the game needs ordered seats (left and right paddle, wallet slots), assign them in the `PlayerJoined` handler from a singleton, such as `mut Seats seats` holding each seat's `PlayerID`, and free them in `PlayerLeft`. Do not count the entities spawned for earlier players instead: spawns apply at the end of the tick, and two players can join in the same tick. `with ownership` selects this machine's entities in local code, and the command sender's in a command handler; match systems use `with Owner`. Write separate filters as `with Wallet, with ownership`.
All machines in a match must execute identical simulation rules. Read [Matches](#doc-multiplayer--matches) before implementing room setup, admission or migration. Optional [Rooms](#doc-packages--rooms) supplies a Play/Host/Join menu; it is not automatically included in a new folder.
## Draw and validate
The default 2D view uses world coordinates centered on the window, with Y up and one world unit per pixel. **`Draw.SetScreen()` changes subsequent drawing to logical pixels from the top left, with X right and Y down**, the same coordinates as GUI rectangles and script `mouse x y`. It also affects later views in that frame until another camera is selected; `Draw.Screen() { ... }` limits the change to a block. For a grid whose row 0 is at the top, screen Y increases with the row. `Draw.Circle(position, radius, color)` and `Draw.Rect(center, size, color)` use the shape's center; a GUI `Rect(x, y, width, height)` uses its top-left corner. `Draw.Text(text, position, size, color)` accepts an `Anchor` to align text.
There is no window-size setting: players resize the window, which opens at 960×540 on desktop. For a game designed at a fixed size such as 640×360, draw the play area in world units and set the camera in the first view, so it scales with the window: `Draw.SetCamera(float2(0, 0), 180)` shows 360 units of height (its size is half the visible height), and `Math.Max(180, 320 * Screen.height / Screen.width)` instead also keeps all 640 units of width visible. The camera stays for later views in that frame.
Device pointer positions use bottom-left, Y-up coordinates even when drawing in screen mode; use `Screen.Flip(devices.pointer.position)` before screen-space hit tests. Read [Views and drawing](#doc-game--views), [Cameras](#doc-game--cameras) and [GUI](#doc-game--gui) for signatures and layout. Do not assume the default world camera and GUI use the same axes. For 3D, read [Drawing in 3D](#doc-game--3d) before choosing meshes, depth or lighting.
Compile early, then check behavior. These are game commands; building the engine repository is a different workflow.
```sh
tide version
tide build
tide build --web
```
For automated native runs, set `TIDE_HIDDEN=1` in that shell before running the game. PowerShell:
```powershell
$env:TIDE_HIDDEN = '1'
tide run --frames 120 --capture smoke.png --stats
```
POSIX:
```sh
TIDE_HIDDEN=1 tide run --frames 120 --capture smoke.png --stats
```
This finishes after 120 frames and captures the final picture. Add `--size 640 360` to test a particular logical window size; use `Screen.width` and `Screen.height` for responsive layout. For dynamic play in the same session, use `tide run --interactive play.txt`: send `capture menu.png`, inspect it, queue future-frame input lines, then send `step 30` and wait for `tide: interactive ready ` ([protocol](#doc-tools--cli--interactive-play)). To press a GUI widget, send `controls` to list the widgets with their labels and positions, then `click "Play"` or `click `, rather than estimating pixels from the picture. Open the PNG and inspect it; a successful build alone does not establish that the game draws or behaves correctly. If inspection is inconclusive, take a later capture or check simulation values with `Debug.Log`/`Debug.Assert` before concluding the game is blank or broken. For input, use `tide run --script smoke.txt --frames 180 --capture smoke.png --stats`, with a script such as:
```text
1 key d down
60 key d up
120 capture after-move.png
150 quit
```
Script times are frames, and lines go in frame order; key actions use `down`/`up`, or neither for a one-frame tap. A `capture` path in a script is relative to the script's folder. `--players 2` runs two game processes in one match over a simulated network on this machine, with `player 2` after a frame number to target the second player; each capture name gains the player's number, `after-move-1.png` and `after-move-2.png`. `300 player 2 leave`, `drop`, `sleep` and `rejoin` test what happens when a player goes and comes back. `--latency 80`, `--jitter 10` and `--loss 5` put every joining player that far from the match's server (`--latency 2:120` for one player), and the run still repeats exactly. It does not exercise real network transports. Read [CLI capture and scripts](#doc-tools--cli--without-a-window) for the supported actions, output naming and exit codes. A web build still needs a browser test; native captures do not verify WebGPU. Launch automated Chrome/Edge with `--mute-audio` and a bounded test, not an unbounded `tide run --web`.
For numerical behavior, supplement pictures with `Debug.Log` of state changes or `Debug.Assert` of invariants. A multiplayer money transfer can assert that balances never go negative and that the pool plus all balances stays constant; a collector can log cell and score after each move. With several players, a client runs a tick again after a wrong guess about another player's input, and logs in it print again: include `time.tick` in the line. Check the actual log as well as the captures. A failed or unclear image inspection is not evidence of a replication bug.
For performance work, capture a representative scripted run in an optimized
build:
```sh
tide run --release --script play.txt --frames 360 --profile profile.json --profile-warmup 60
```
For GPU bottlenecks, inspect `gpu_passes.rows`: target, pass order, shader
membership and mean/p95/max GPU time. Check missing-sample counters; a mixed
pass's time cannot be assigned to one shader. See the
[GPU pass reference](#doc-tools--debug-views--finding-expensive-gpu-passes).
This native desktop report is written when the run ends, independently of the
panels; it measures frames after warmup and
includes source locations and engine draw counters. Read actual CPU work and
GPU availability, not the hidden run's fixed-step FPS. Follow expensive views
into their draw diagnostics: many frustum tests with few rejections are a
candidate for investigation, not proof that culling is redundant. Compare one
change at a time using the same script, seed, resolution, saves and build mode,
and inspect captures and relevant simulation checks before claiming an
improvement. CPU, concurrent worker and asynchronous GPU intervals overlap.
See [Profile captures](#doc-tools--debug-views--profile-captures) for the report's
measurement meanings and limits.
Fix diagnostics using the current compiler and relevant reference rather than guessing APIs. Report the builds, behavior checks and platforms actually tested. If a tool or backend is unavailable, say which check remains unverified.
## References on demand
The [documentation index](https://tide-engine.dev/llms.txt) links to clean Markdown pages. The optional [full documentation download](https://tide-engine.dev/llms-full.txt) is for offline searching, not required reading on every task. The [language spec](https://tide-engine.dev/spec.md) separates decided behavior from provisional implementation and open proposals; an open design is not an available API.
Use [Assets](#doc-game--assets) for imports, [Packages](#doc-packages) for optional dependencies and their pinned documentation, [Determinism](#doc-multiplayer--determinism) for simulation constraints, and [Visibility](#doc-game--visibility) for secrets and recipient state. Keep gameplay state deterministic and use Tide's math/random APIs; C reached through `extern` is trusted and can violate those guarantees.
---
Source: https://tide-engine.dev/guide/playground.md
Edit a running Tide game in your browser. Compile real Tide code locally and hot reload while keeping the game's state.
# Playground
Change the code and watch the running game pick it up. Compilation happens in
your browser; there is nothing to install and your source is not sent to a
build server.
```tide
// Change the color or speed below. The ball keeps its position on reload.
const float SPEED = 1;
const float RADIUS = 18;
const Color INK = Color(0.98, 0.75, 0.14);
component Ball
{
[Position] float2 position;
float2 velocity = float2(130, 95);
int bounces;
}
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Ball);
}
system Move(mut Ball ball, Time time)
{
ball.position += ball.velocity * time.dt * SPEED;
if (Math.Abs(ball.position.x) > 145)
{
ball.position.x = Math.Sign(ball.position.x) * 145;
ball.velocity.x = -ball.velocity.x;
ball.bounces += 1;
}
if (Math.Abs(ball.position.y) > 105)
{
ball.position.y = Math.Sign(ball.position.y) * 105;
ball.velocity.y = -ball.velocity.y;
ball.bounces += 1;
}
}
view Backdrop()
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0), Math.Max(185, 185 * Screen.height / Screen.width));
Draw.Rect(float2(0), float2(330, 250), Color(0.15, 0.15, 0.17));
}
view Show(Ball ball)
{
Draw.Circle(ball.position, RADIUS, INK);
Draw.Text($"{ball.bounces} bounces", float2(-145, -155), 15, Color(0.64, 0.64, 0.68));
}
```
## Try a live change
- Change `INK` to `Color(0.18, 0.83, 0.75)` to turn the ball teal.
- Change `SPEED` to `2` to make it move faster, or `0` to hold it still.
- Change `RADIUS` to `30` to make it bigger.
The bounce count and position carry over. **Restart** starts the last successful
build from the beginning. **Reset code** restores the original example and
starts it again.
**Auto reload** compiles after you stop typing. With it off, press
**Compile & reload** or Ctrl+Enter (Cmd+Enter on macOS). If the code has an
error, diagnostics appear below the editor and the last successful game keeps
running. Try removing a semicolon, then putting it back.
## The editor
The editor runs the same language server as the [editor extensions](#doc-tools--editors),
so it already knows your code before you compile it:
- Type `.` after a value, or press Ctrl+Space, for completions. Hover a name to see its type and documentation.
Parameter hints appear as you type a call.
- Mistakes are underlined as you type and listed under the editor; click one to jump to it.
- F12 goes to a definition in this file, F2 renames, and Shift+Alt+F formats the code.
Ctrl+/ comments lines, and Ctrl+F finds text.
Drag the divider between the code and the game to give either more room, or press
**Expand** to fill the window. Esc or **Exit** brings back the page.
## What runs here
This is the real Tide compiler and engine: Tide is transpiled to C, compiled
to WebAssembly and loaded into the running preview. The first compilation
downloads about 25 MiB of compiler tools, which your browser can cache. Later
edits reuse them. The first build also initializes the tools and can take longer
than later edits; progress appears below the editor. The compiler runs in a
worker so you can keep editing while it builds. The editor's language server is
a separate download of under 2 MiB, so suggestions work before the first build.
This demo edits one `.tide` file with no external assets or packages. The
engine's normal component, system and view features work here, including
procedural drawing and shaders. Files named by an `asset` declaration must
exist in the compiler's virtual filesystem; this page has no file upload or
package manager. Native-only integrations are unavailable. [Build code](#doc-game--build-code)
requires the installed tools; use `tide run --web` to build and preview a project
that makes assets or constants during its build.
[Hot reload](#doc-tools--cli--hot-reload) carries fields over by name. New fields
use their defaults; changing a default does not overwrite an existing field.
Renaming or removing state can reset it. Web reload currently closes connections
to other players, so this playground demonstrates a solo match.
For a complete project, [install Tide](#doc-guide--install) and follow
[Your first game](#doc-guide--first-game). Use `tide run --web --stats` for the same browser
preview with local project files and watched rebuilds.
---
Source: https://tide-engine.dev/guide/samples.md
Play Tide Engine sample games in your browser, from falling sand and arena combat to 2D and 3D physics, and invite friends to a room.
# Samples
Choose a game to play in your browser. Each thumbnail opens the full game in a new tab. Use **Source** to browse its code on GitHub.
Explore a shared planet in the [Earth demo](#doc-guide--earth), with walking, driving and biome-specific scenery. It starts only when you choose **Play Earth**.
To play together, open a room with the game's **Host** or **Invite** button and send its code to a friend. They open the same game and choose **Join**.
- [Falling sand (opens in a new tab)](https://tide-engine.dev/sand/?stats): 2D · Simulation. Paint sand, water and walls together, and watch them flow. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/bench/sand).
- [Duel (opens in a new tab)](https://tide-engine.dev/duel/?stats): 2D · Arena. Jump, shoot and block, then pick upgrades between rounds. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/duel).
- [Towers (opens in a new tab)](https://tide-engine.dev/towers/?stats): 2D · Physics. Race to stack falling bricks into the tallest tower. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/towers).
- [Sumo arena (opens in a new tab)](https://tide-engine.dev/sumo/?stats): 3D · Physics. Ram heavy balls through crates and off a collapsing arena. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/sumo).
- [Tag (opens in a new tab)](https://tide-engine.dev/samples/tag/?stats): 3D · Party. Playground tag for up to eight: whoever's it the least by the bell wins. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/tag).
- [Pong (opens in a new tab)](https://tide-engine.dev/samples/pong/?stats): 2D · Arcade. Keep the ball in play and send it past your opponent's paddle. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/pong).
- [Snake (opens in a new tab)](https://tide-engine.dev/samples/snake/?stats): 2D · Survival. Share one board and outlast the other snakes. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/snake).
- [Tanks (opens in a new tab)](https://tide-engine.dev/samples/tanks/?stats): 2D · Arena. Drive, aim and fire bouncing bullets around a walled arena. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/tanks).
- [Bomberman (opens in a new tab)](https://tide-engine.dev/samples/bomberman/?stats): 2D · Arcade. Lay bombs, break crates and collect power-ups. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/bomberman).
- [Connect four (opens in a new tab)](https://tide-engine.dev/samples/connect-four/?stats): 2D · Board game. Take turns dropping pieces and line up four of your color. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/connect-four).
- [Asteroids (opens in a new tab)](https://tide-engine.dev/samples/asteroids/?stats): 2D · Co-op. Break asteroids, share a score and rescue stranded ships. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/asteroids).
- [Sumo ring (opens in a new tab)](https://tide-engine.dev/samples/sumo/?stats): 2D · Arena. Bump and dash to push the other players out of the ring. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/sumo).
- [Tower defense (opens in a new tab)](https://tide-engine.dev/samples/tower-defense/?stats): 2D · Co-op. Build and upgrade towers together, with shared gold and lives. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/tower-defense).
- [Marbles (opens in a new tab)](https://tide-engine.dev/samples/marbles/?stats): 3D · Arcade. Roll around the platform, collect coins and stay away from the edge. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/marbles).
---
Source: https://tide-engine.dev/guide/earth.md
Explore a shared little planet in Tide Engine: walk, drive, visit towns and inspect the live performance stats.
# Earth demo
Walk or drive around a little planet with everyone else playing. Visit its towns, roads, gentle hills and different biomes. The demo loads only when you choose **Play Earth**.
[Play Earth](https://tide-engine.dev/earth/?stats)
## Controls
Click or tap the planet to land. Drag to turn the globe or camera. On the ground, use **WASD** to move, **C** to switch between walking and driving, **Space** to jump and **E** to wave. Tap the ground to go there; touch buttons provide the other actions. Use **Esc** or **Globe** to return to space.
Tap the **FPS line** at bottom right, or press **F8**, to open the engine's performance stats. **Expand** gives the game the whole page without restarting it. **Stop** leaves the match and releases the demo's resources.
The demo joins the shared hosted world when available; otherwise it starts a local world. Its [source is on GitHub](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/earth).
---
Source: https://tide-engine.dev/benchmarks.md
Measured ECS performance for Tide and other ECS implementations, with workload details, methodology, variation and the limits of each comparison.
# Benchmarks
How much work can Tide's ECS do in a tick? These small CPU workloads give a baseline for comparing ECS performance.
This measures **ECS updates**, including deferred structural changes where used. It excludes setup, world hashing, snapshots, networking and rendering. It does not measure the cost of a complete Tide multiplayer tick or predict a game's frame rate.
**Tide, Bevy, Flecs and EnTT: one thread**
2026-10-29 · AMD Ryzen 9 7900X · Windows 11 x86-64.
4 processes per implementation and workload; 200 warmup ticks and 400 measured ticks per process.
Tide revision: [fe5e96be1c61c7372590e7466dc26810a910bb14](https://github.com/Tide-Engine/tide-engine/commit/fe5e96be1c61c7372590e7466dc26810a910bb14).
- Tide fe5e96be1: Generated C storage and scheduled systems; moving Frozen tags. Clang 23.1.2, -O2, baseline x86-64.
- Bevy 0.20.0: Table storage and scheduled systems; Rust 1.95.0, opt-level 2, baseline x86-64.
- Flecs 4.1.6: Cached archetype systems and pipeline; Clang 23.1.2, -O2, baseline x86-64.
- EnTT 4.0.0: Views and an owning filtered group with explicit dispatch, without an integrated scheduler; Clang 23.1.2, -O2, baseline x86-64.
| Workload | Threads | Tide, ms (min–max) | Bevy, ms (min–max) | Flecs, ms (min–max) | EnTT, ms (min–max) |
| --- | --- | --- | --- | --- | --- |
| 1M particles | 1 | 0.44648 (0.43545–0.57870) | 1.15563 (1.14835–1.26580) | 1.66710 (1.66455–1.73415) | 1.88397 (1.84365–1.91285) |
| 1M wide components, all active | 1 | 1.29137 (1.22825–1.34430) | 2.40837 (2.38005–2.60395) | 2.25955 (2.24280–2.28730) | 2.85360 (2.82575–2.88020) |
| 1M wide components, 50% frozen | 1 | 0.44522 (0.42905–0.46295) | 1.14358 (1.10590–1.20100) | 1.10347 (1.09495–1.12315) | 1.46560 (1.43635–1.46895) |
| 1M wide components, 95% frozen | 1 | 0.02925 (0.02890–0.02930) | 0.10120 (0.10000–0.10690) | 0.10963 (0.10910–0.11205) | 0.13195 (0.13005–0.13720) |
| 1M wide components, 99% frozen | 1 | 0.00575 (0.00570–0.00580) | 0.02022 (0.02010–0.02060) | 0.02187 (0.02165–0.02250) | 0.02903 (0.02670–0.02970) |
| 2k bullets, churn | 1 | 0.34695 (0.33555–0.38910) | 0.52038 (0.46550–0.68610) | 0.56875 (0.45420–0.73950) | 0.26267 (0.25980–0.27045) |
Tide has the lowest sampled median for particles, dense wide components and the three frozen densities. EnTT has the lowest churn median. Bevy and Flecs churn ranges are wide; these observations describe this run, not a universal ranking.
The 96 accepted processes use four cyclic rounds: each implementation occupies every launch position once per workload. One complete attempt that overlapped a build was excluded; its raw evidence and the accepted replacement are both retained. Attempts were not selected by their timing.
Before timing, 75 validation cases matched across the four native implementations, an independent C reference and Tide WASI; the harness passed 26 checks. The raw report records source and binary hashes, correctness evidence and the attempt ledger. Bevy, Flecs and EnTT WebAssembly were not measured or validated in this report.
**Tide and Bevy: one and four threads**
2026-10-29 · AMD Ryzen 9 7900X · Windows x86-64.
3 processes per implementation and workload; 200 warmup ticks and 400 measured ticks per process.
Tide revision: [fe5e96be1c61c7372590e7466dc26810a910bb14](https://github.com/Tide-Engine/tide-engine/commit/fe5e96be1c61c7372590e7466dc26810a910bb14).
- Tide fe5e96be1: Generated C storage and scheduled systems; Clang 23.1.2, -O2, baseline x86-64.
- Bevy 0.20.0: Table storage and scheduled systems; Rust 1.95.0, opt-level 2, baseline x86-64.
| Workload | Threads | Tide, ms (min–max) | Bevy, ms (min–max) |
| --- | --- | --- | --- |
| 1M particles | 1 | 0.45830 (0.44730–0.48030) | 1.15210 (1.15060–1.17375) |
| 1M particles | 4 | 0.12650 (0.12480–0.12740) | 0.43015 (0.42965–0.43565) |
| 1M wide components, all active | 1 | 1.33280 (1.32535–1.40350) | 2.49640 (2.38615–2.59715) |
| 1M wide components, all active | 4 | 0.67165 (0.67150–0.82120) | 1.17735 (1.14365–1.19100) |
| 1M wide components, 50% frozen | 1 | 0.43605 (0.41605–0.48060) | 1.13585 (1.08350–1.14465) |
| 1M wide components, 50% frozen | 4 | 0.41065 (0.40415–0.41980) | 0.41150 (0.41115–0.41365) |
| 1M wide components, 95% frozen | 1 | 0.02940 (0.02920–0.02940) | 0.10050 (0.10025–0.10110) |
| 1M wide components, 99% frozen | 1 | 0.00570 (0.00570–0.00580) | 0.01995 (0.01990–0.02000) |
| 1M wide components, 99% frozen | 4 | 0.00570 (0.00570–0.00580) | 0.02210 (0.02130–0.02330) |
| 2k bullets, churn | 1 | 0.33850 (0.33725–0.34030) | 0.32020 (0.29680–0.35150) |
| 2k bullets, churn | 4 | 0.35025 (0.33120–0.36550) | 0.30455 (0.26305–0.51825) |
The four-thread 50%-frozen workload is effectively tied. Churn measurements overlap and vary substantially, especially with four threads; these runs do not establish a reliable winner for churn.
Three alternating Tide/Bevy process pairs were run independently for each workload. Two earlier full batches affected by contention were excluded; the raw archive records both the accepted and discarded runs.
## Reading the results
Lower is faster. Each cell is the median of separate process medians, in milliseconds per tick. The smaller numbers underneath give the minimum and maximum of those process medians. These ranges show run-to-run variation; they are **not confidence intervals**. Close or overlapping results need more measurements before calling a winner.
Every workload stays visible, including cases where another implementation is faster. There is no overall score: moving particles, filtering wide components and changing entity structure exercise different costs. Reports from different runs remain separate.
## What the workloads do
| Workload | Work measured |
| --- | --- |
| 1M particles | Update position and velocity for one million particles. |
| 1M wide components | Update one million entities with wider component data. |
| 50%, 95% or 99% frozen | Update only the remaining active entities. Frozen membership is fixed during the run; this does not measure changing filter membership. |
| 2k bullets, churn | Repeated spawning and destruction alongside movement. Deferred changes are applied inside the timed tick. |
The implementations use the same initial values and update arithmetic. The runner checks final state digests across implementations before accepting a result. That checks these workloads; it does not establish cross-platform determinism for the other ECS libraries.
## What is being compared
Tide generates specialized C storage and systems for each game. Bevy uses its Table component storage and schedule. The broader serial comparison also uses Flecs cached archetype systems and EnTT views and an owning filtered group with explicit dispatch. EnTT does not supply an integrated scheduler in this comparison, so these paths do not provide identical engine services.
Each report names its exact implementations, versions and thread count. Compiler settings preserve the update's floating-point operation order: no fast math or fused multiply-add contraction. Tide keeps its determinism requirements; the harness does not disable them to improve a result.
These are selected synthetic workloads on one machine, maintained by the Tide project. Cache layout, entity count, query shape, structural changes, scheduling and hardware can change the outcome. Use them as a starting point for a workload that resembles your game.
---
Source: https://tide-engine.dev/game/entities.md
Define components, entities and singletons in Tide's ECS, then spawn, add, remove and destroy data to build your game's world.
# Components and entities
Tide is an ECS: the world is made of **entities**, entities are made of **components**, and **systems** run code over them. This page is about the data; [Systems](#doc-game--systems) is about the code.
## Components
A component is plain data, declared with `component`:
```csharp
component Health
{
int value = 100;
int max = 2 * 2 * 25;
}
component Poisoned { }
```
A component with no fields, like `Poisoned`, is still useful: systems can pick the entities that have it, or don't.
### Defaults
Fields can have a default. It must be a constant: literals, constructors of built-in types, struct values of constants, `Math` functions, built-in constants like `quaternion.identity`, and operators on those. It can name an [asset](#doc-game--assets--a-field-s-default) too, like `Texture face = logo;`. A default can't read other fields, singletons or `Time`.
```csharp
component Turret
{
float angle = Math.Radians(45);
float3 offset = float3(0, 1.5, 0);
Color tint = Color.red;
}
```
Fields without a written default take their type's default: zero for numbers, `false` for bools, empty text and collections, and a struct's own field defaults for a struct. `Entity` fields always start as the null entity, and can't have another default. [Default values](#doc-language--basics--default-values) explains the `default` expression.
## Singletons
A singleton holds state there's one of per world, like the rules, the score or a random seed. Other ECSs call them resources.
```csharp
singleton Physics
{
float3 gravity = float3(0, -9.81, 0);
int collisionCount;
}
```
Singletons start with their defaults when the world is created. Systems take them as parameters, like components (see [Systems](#doc-game--systems)).
`Time` is a built-in singleton. Systems can read it, but not write it:
| Field | What it is |
|---|---|
| `float dt` | The length of a tick in seconds |
| `int tick` | The tick, which counts from 0 |
| `float t` | The seconds since the match started: `tick * dt` |
| `int tickRate` | The ticks in a second: 1 / `dt` to the nearest whole number |
| `float maxRewind` | Configured collider history in seconds, from `settings`; 0 disables it |
`t` is worked out from the tick each time, so it never drifts, and [views](#doc-game--views--smooth-at-any-tick-rate) see it move every frame. A float holds about 7 digits, so it gets coarser as the match goes on (after a day, its steps are about 8 milliseconds): a timer that has to be exact counts in `tick`.
What makes one match unlike another is its seed, [`Random.seed`](#doc-language--math--the-match-s-seed), which the match's [random numbers](#doc-language--math--random-numbers) come from.
## Spawning entities
`Spawn` makes an entity from a list of component values:
```csharp
var e = Spawn(Transform { localScale = float3(1, 1, 1) }, Player);
```
A component value is written like `Health { max = 200 }`, without `new`. Fields left out take their defaults, and a bare type name, like `Player`, takes every default.
An existing value or a helper's result works too: `Spawn(savedHealth, MakeInventory())` and `e.Add(savedHealth)`. Each argument is evaluated once in written order and copied when the change is recorded, including owned lists and maps. Editing the source afterward leaves that recorded copy intact. A component copy carries ordinary fields; each new entity gets fresh local-field defaults.
An entity has at most one component of each type. When it needs several of something, use a list inside one component, one entity per item that points back at its owner, or separate component types.
## Changing entities
```csharp
e.Add(Stunned { duration = 2 });
e.Remove(Stunned);
e.Destroy();
```
- `Add` of a component the entity already has replaces its value.
- `Remove` of a component the entity doesn't have does nothing.
- `Add`, `Remove` and `Destroy` on an entity that's already gone do nothing.
These are **structural changes**, and they don't happen right away. They're recorded, and applied together at the end of the tick, in the order they were made. The handle `Spawn` returns can be used at once, for example to store in a component, but the entity's data can only be read once the changes apply.
`Spawn` returns its final opaque logical identity immediately. It stays the same across rollback and recipient projection loading for the same causal spawn, independently of physical slots, row order or hidden allocations. Helpers, query rows, events and waiting tasks retain that causal origin. Authority correcting the initializer values alone does not reset the entity's local fields. The components still become readable only when the recorded spawn applies.
Code that depends on hidden state can still need authority corrections: stable identities do not simulate missing private entities. C uses the same identity; see [Calling C](#doc-c--functions).
That's what lets systems run side by side: nothing they do changes which entities exist until they're all done.
A [function](#doc-language--functions--sending-and-spawning) can `Spawn`, `Add`, `Remove` and `Destroy` too, for the code that calls it. It takes the entity it changes as a parameter:
```csharp
Entity Drop(float3 at)
{
return Spawn(Transform { localPosition = at }, Crate);
}
void Stun(Entity target)
{
target.Add(Stunned { duration = 2 });
}
```
Each ball below is an entity with a `Ball` and a `Health`. Tap one to `Add` a `Poisoned` to it: a system that takes `with Poisoned` then drains its health, and destroys it when none is left. Tap it again to `Remove` the component, and it recovers. Tapping the ground spawns a ball. A view can't change the match itself, so each tap goes in as a [command](#doc-game--commands).
**Spawn, Add, Remove and Destroy** ([Run example](https://tide-engine.dev/examples/entities/?stats))
```tide
settings { title = "Entities"; tickRate = 30; maxPlayers = 1; }
component Ball
{
float2 position;
float radius = 0.3;
}
component Health { int value = 100; }
component Poisoned { } // No fields: it only marks an entity
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Ball { position = float2(-1.2, 0.4) }, Health);
Spawn(Ball { position = float2(0, -0.3) }, Health, Poisoned);
Spawn(Ball { position = float2(1.2, 0.5) }, Health);
}
// What a tap asks of the match. Views can't change it themselves.
command Drop { float2 at; }
command Poison { }
command Cure { }
command(Drop drop, PlayerID sender) DropBall()
{
Spawn(Ball { position = drop.at }, Health { value = 40 });
}
// `this` is the entity the command was sent to. Add and Remove wait for the
// end of the tick, and so does Destroy.
command(Poison poison, PlayerID sender) PoisonBall(with Ball) { this.Add(Poisoned); }
command(Cure cure, PlayerID sender) CureBall(with Ball) { this.Remove(Poisoned); }
system Sicken(mut Health health, with Poisoned)
{
health.value -= 1;
if (health.value <= 0) this.Destroy();
}
system Recover(mut Health health, without Poisoned)
{
health.value = Math.Min(health.value + 1, 100);
}
// This machine's side: what the pointer is on, and the counts to show.
local singleton Pointing
{
float2 world;
bool down;
bool onBall;
int balls;
int poisoned;
}
view Begin(Devices devices, mut Pointing pointing)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0), 2.2);
pointing.world = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position));
pointing.down = devices.pointer.press.down;
pointing.onBall = false;
pointing.balls = 0;
pointing.poisoned = 0;
}
view Healthy(Ball ball, Health health, mut Pointing pointing, without Poisoned)
{
var size = ball.radius * (0.4 + health.value * 0.006);
Draw.Circle(ball.position, size, Color(0.98, 0.75, 0.14));
pointing.balls += 1;
if (Math.Distance(pointing.world, ball.position) > ball.radius) return;
pointing.onBall = true;
if (pointing.down) this.Send(Poison { });
}
view Sick(Ball ball, Health health, mut Pointing pointing, with Poisoned)
{
var size = ball.radius * (0.4 + health.value * 0.006);
Draw.Circle(ball.position, size, Color(0.18, 0.83, 0.75));
Draw.WireCircle(ball.position, ball.radius, 0.03, Color(0.18, 0.83, 0.75));
pointing.balls += 1;
pointing.poisoned += 1;
if (Math.Distance(pointing.world, ball.position) > ball.radius) return;
pointing.onBall = true;
if (pointing.down) this.Send(Cure { });
}
view Ground(Pointing pointing)
{
if (pointing.down && !pointing.onBall) Send(Drop { at = pointing.world });
Draw.SetScreen();
Draw.Text($"{pointing.balls} entities, {pointing.poisoned} with Poisoned", float2(16, 14), 18, Color.white);
Draw.Text("Tap a ball to poison or cure it. Tap the ground to spawn one.",
float2(16, Screen.height - 30), 13, Color(0.64, 0.64, 0.68));
}
```
## Transform and parenting
`Transform` is built in, with `float3 localPosition` (zero), `quaternion localRotation` (identity), and `float3 localScale` (one). Each is relative to the entity's parent; a root's values are its world placement. Add it like any other component.
Match `Transform` fields have [correction smoothing](#doc-game--views--provisional-correction-smoothing) built in: `localPosition` behaves as `[Position]`, and `localRotation` as `[Rotation]`. Views preserve their displayed values across prediction corrections and let the error decay. Scale keeps ordinary tick interpolation; local entities use their current values. Use `entity.Snap()` for an intentional jump. This smooths view bindings; `World` queries and the ancestors read by `position` still use stored state.
Its computed `float3 position` property reads world position. Setting it converts the requested position into parent space and changes `localPosition`; it needs a mutable Transform and leaves the parent unchanged:
```csharp
system Move(mut Transform transform)
{
transform.position += float3(1, 0, 0);
}
view Mark(Transform transform)
{
var screen = Draw.WorldToScreen(transform.position);
Draw.Screen() { Draw.Circle(screen.xy, 10, Color.red); }
}
```
The getter uses the binding's current `localPosition` and stored ancestors, including after changing that local value in the same routine. Helpers retain the attached binding when it is passed directly. An explicit copy is detached, so use `localPosition` on copies. Singular parent transforms and nonfinite setter results leave the local position unchanged. Properties are also [user-definable](#doc-language--functions--properties).
`world.ParentToWorld(entity)` gives the matrix from parent space into world space. It includes retained placement when visibility hides a parent, and gives identity for an ordinary root or dead entity. Thus `Math.Transform(world.ParentToWorld(entity), localPosition)` is the same computation available to a component's own property. `world.LocalToWorld(entity)` includes the entity's own stored transform as well; its `c3.xyz` is the stored world position.
```csharp
event(Spawned) Assemble(with Main)
{
var parent = Spawn(Transform { localPosition = float3(10, 0, 0) });
var child = Spawn(Transform { localPosition = float3(2, 0, 0) });
child.SetParent(parent, worldPositionStays: false);
}
```
After those changes apply, the child's world position is `(12, 0, 0)`. `SetParent(parent)` preserves its world placement by adjusting its local values; `false` keeps its local values. `SetParent(null)` detaches it. These changes apply at the end of the tick or local frame, in recorded order.
Read `world.LocalToWorld(entity)` for its composed `float4x4`, and `world.Parent(entity)` for its parent's handle. They read the latest stored state, as other `World` methods do. An entity without a Transform contributes identity; a missing entity gives identity or a null parent.
With [state visibility](#doc-game--visibility--spatial-parents), a hidden spatial parent does not hide its public child. The projected hierarchy cuts private links and preserves placement only for subtrees containing permitted `Transform` state; a parent can therefore read as null on a client.
Destroying a parent destroys its descendants, children before their parent. A cycle, a dead handle or a parent from the other world is rejected. Runtime rejections print their reason and leave the hierarchy unchanged. Preserving world placement requires a Transform on the child and an invertible parent transform. Nonuniform scales combined with rotation can create shear; three local TRS values cannot preserve that matrix exactly.
The same `Transform` works on local entities: use `local Spawn(Transform)` and `local Transform transform` in a view's parameters. `Entity` and `LocalEntity` still prevent crossing the match/local boundary. Loaded scene entities remain independent roots. Reparenting ordinary entities into a different scene transfers their descendants into that scene; detaching retains scene ownership.
## Entity handles
`Entity` is a handle to an entity. Components can hold them, to point at each other:
```csharp
component Weapon
{
Entity owner;
}
```
`default` is the null entity, so `weapon.owner == default` tells whether it points anywhere, and `weapon.owner = default;` clears it.
A handle leads to the other entity's components through the `World`: `world.Get(weapon.owner)` (see [Other entities](#doc-game--systems--other-entities-the-world)).
In a system, view or event handler that runs for an entity, `this` is that entity:
```csharp
system Expire(mut Lifetime life)
{
life.ticks -= 1;
if (life.ticks <= 0) this.Destroy();
}
```
In local code that runs for a local entity, like a view of local components, `this` is a `LocalEntity`. Code that runs once per tick, frame or event runs for no entity, so it has no `this`, and neither do functions. In a [frag](#doc-game--shaders--where-the-pixel-is), `this` is the pixel it runs for.
A component's methods have `this` too: the entity whose component they're called on. Methods are specialized for the placement used by the caller, so `this` is an `Entity` for a match component and a `LocalEntity` for a local component. Explicit parameter and return types keep their meaning.
```csharp
component Health
{
int value;
bool IsMine(Entity attacker) { return attacker == this; }
}
```
So a method that uses `this` can only be called on a component the code runs for, like a system's `Health health`. A copy of one, in a local variable or a function's parameter, belongs to no entity.
## Archetypes
An archetype is a set of components that entities share, and entities with the same set are stored together. There are no archetype declarations: the compiler finds every one from the code, from what each `Spawn` makes and what `Add` and `Remove` can turn it into. It follows the code as written: `this.Add(Stunned)` in a system only reaches the entities that system runs for, and `e.Add(Stunned)` on an `e` a `Spawn` in the same code made reaches that one, so toggling a component on a few kinds of entity makes a few archetypes. An `Add` on an entity read from a field or a parameter could be on any entity, so it reaches every archetype.
## Limits
Adding or removing a component moves the entity to the archetype of its new set, tags (components with no fields) included, at the end of the tick. That's what makes `without Sleeping` cheap: the system runs through the archetypes of awake entities and never looks at a sleeping one. Each move copies the entity's row, so a status that flickers, gained and lost every few ticks by many entities, is better kept in the row. Mark it `[Sparse]`: it's kept as a presence bit and its value in every archetype it can reach, so `Add` and `Remove` of it move no entity, and systems that take or filter on it skip the rows that haven't got it.
```csharp
[Sparse]
component Stunned
{
float left;
}
system Recover(Time time, mut Stunned stunned)
{
stunned.left -= time.dt;
if (stunned.left <= 0) this.Remove(Stunned);
}
```
Every component an entity can gain or lose doubles the archetypes it can reach. When tags would take a game past the limit below, the compiler keeps some of them in the row as if they were `[Sparse]`, starting with the tags added to entities read from fields or parameters, until the archetypes fit. A component with fields isn't chosen that way: past the limit it's an error, which marking the ones entities gain and lose most `[Sparse]` fixes.
For now, a game has at most 256 components and 1024 archetypes. Entities, the rows of each archetype, and the structural changes and events in a tick grow as they need, with no limit but memory (see [C hosts](#doc-c--hosts--memory)).
---
Source: https://tide-engine.dev/game/systems.md
Write Tide ECS systems that query entities each tick, declare data access and control execution order in a deterministic simulation.
# Systems
A system is code that runs every tick. Its parameters say which entities it runs for, and what it does with their data.
```csharp
system ClampPlayer(mut Transform trs, with Player)
{
if (trs.position.y < 0)
trs.position.y = 0;
}
```
## Parameters are the query
A system's component parameters describe the entities it runs for. Each parameter's modifier says how the system relates to that component or singleton:
| Modifier | Meaning |
|---|---|
| none | Reads it |
| `mut` | Writes it |
| `with` | The entity must have it. No data, so no data dependency. |
| `without` | The entity must not have it. |
So `ClampPlayer` runs for every entity that has a `Transform` and a `Player`, and changes its `Transform`.
Keeping what a system touches (its access) apart from which entities it picks (its filters) is what lets the engine run systems side by side safely: two systems that only filter on the same component never wait for each other.
Only the amber row has `Moving` without `Frozen`, so only those entities match `Move`. Their positions change by `time.dt` in the match, and views draw the result. The button sends a command to pause or resume the match's movement.
**Component filters in motion** ([Run example](https://tide-engine.dev/examples/systems/?stats))
```tide
settings { title = "System queries"; tickRate = 30; maxPlayers = 1; }
component Body { float2 position; float speed = 1; }
component Moving { }
component Frozen { }
singleton Demo { bool running = true; }
command SetRunning { bool value; }
scene Main { }
event(Spawned) Setup(with Main)
{
for (var i = 0; i < 3; i++)
{
Spawn(Body { position = float2(i * 1.2 - 1.2, 1) }, Moving);
Spawn(Body { position = float2(i * 1.2 - 1.2, 0) }, Moving, Frozen);
Spawn(Body { position = float2(i * 1.2 - 1.2, -1) });
}
}
// Only the first row matches both filters.
system Move(mut Body body, Time time, Demo demo, with Moving, without Frozen)
{
if (!demo.running) return;
body.position.x += body.speed * time.dt;
if (body.position.x > 2)
{
body.position.x -= 4;
this.Snap(); // Wrap immediately instead of interpolating across the lane.
}
}
// The button sends a match command instead of changing state in a view.
command(SetRunning change, PlayerID sender) Run(mut Demo demo)
{
demo.running = change.value;
}
view Background()
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0), 3);
for (var i = -1; i <= 1; i++)
Draw.Line(float2(-2.1, i), float2(2.1, i), 0.025, Color(0.24, 0.25, 0.27));
}
view Active(Body body, with Moving, without Frozen)
{
Draw.Circle(body.position, 0.19, Color(0.98, 0.75, 0.14));
}
view Blocked(Body body, with Moving, with Frozen)
{
Draw.Circle(body.position, 0.19, Color(0.98, 0.44, 0.52));
}
view Excluded(Body body, without Moving)
{
Draw.Circle(body.position, 0.19, Color(0.64, 0.64, 0.68));
}
view Labels(Demo demo)
{
var first = Draw.WorldToScreen(float2(0, 1));
var second = Draw.WorldToScreen(float2(0, 0));
var third = Draw.WorldToScreen(float2(0, -1));
Draw.SetScreen();
Draw.Text("Systems run every tick", float2(16, 14), 18, Color.white);
Draw.Text("with Moving, without Frozen", float2(16, first.y - 34), 14, Color(0.98, 0.75, 0.14));
Draw.Text("Moving + Frozen: excluded", float2(16, second.y - 34), 14, Color(0.98, 0.44, 0.52));
Draw.Text("No Moving: excluded", float2(16, third.y - 34), 14, Color(0.64, 0.64, 0.68));
GUI.SetTheme(GUITheme { radius = 6 });
if (GUI.Button(Rect(16, Screen.height - 48, Screen.width - 32, 32), demo.running ? "Pause the match" : "Resume the match"))
Send(SetRunning { value = !demo.running });
}
```
Other parameters:
- **Singletons**, read or `mut`, like components: `system Score(mut Stats stats, Rules rules)`.
- **The input**, or **`Devices`**: what the player who owns the entity does (see [Input](#doc-game--input)).
- **The `World`**: any other entity's components (below).
- **A `query`**: another set of entities to inspect (below). Match data stays read-only; [local code](#doc-game--views-and-the-match--other-entities) can also read and write attached local fields.
Views take the same parameters, and one filter more: `with ownership` and `without ownership`, the entities this machine's player owns, or doesn't (see [Your own entities](#doc-game--views-and-the-match--your-own-entities)). It's for views only: a system runs the same on every machine, so there it's an error, which points to `with Owner`, the entities any player owns.
The entity itself isn't a parameter: it's `this` (see [Entity handles](#doc-game--entities--entity-handles)).
## Another set of entities
A bullet system runs for bullets, but needs to inspect fighters too. A `query` parameter selects that second set:
```csharp
system BulletHits(Body shot, Bullet bullet, query (Body body, with Fighter) fighters)
{
foreach (var fighter in fighters)
{
if (Intersects(shot, fighter.body))
fighter.entity.Send(Hit { damage = bullet.damage });
}
}
```
`Intersects` is a function the game defines. The outer `Body` and `Bullet` parameters select each bullet; `Body` and `with Fighter` inside the query select the candidates it inspects. The query never requires a bullet to be a fighter.
Inside `foreach`, `fighter.body` is read-only component data and `fighter.entity` is that fighter's entity handle. Add more component bindings when their values are needed, and `with` or `without` filters when only presence matters:
```csharp
query (Body body, Health health, with Fighter, without Invulnerable) fighters
```
Sparse components and tags are checked for each candidate, and an empty query runs no iterations. A system with only query parameters runs once per tick.
Queries use normal deterministic ECS traversal. They do not sort by entity ID, distance or hit time. For a swept projectile, calculate each candidate's intersection and keep the earliest one before sending a hit.
Query data reads the current world and participates in [the schedule](#doc-game--schedule). A system that also changes a queried component runs on one thread, following the same rule as reading its own writes through `World`: it sees rows changed earlier in that run. A binding marked [`previous`](#doc-game--systems--as-the-tick-started) reads the tick's start instead, and does neither. Events and structural changes still wait for the end of the tick, so sending a hit or recording a destroy through `fighter.entity` does not change what this iteration reads.
Queries have read-only component bindings and component filters. Queries are used directly in `foreach`, or [borrowed by synchronous helpers](#doc-language--functions--borrowing-a-query) with the same `query (...)` parameter syntax. The caller's selection and data timing stay intact. Queries and whole rows cannot be stored or returned; whole rows cannot be passed to functions. Keep iteration and forwarding outside parallel loops (other than the query's own, below) and callback blocks. A component value such as `fighter.body` can be copied or passed to a function. It follows the usual component copy rules, so a method that uses `this` needs the entity's own component parameter.
Systems, views and synchronous event and command handlers take queries. A match handler reads the current world at its turn in the tick-end queue: see [Events](#doc-game--events--querying-other-entities). A view's rows are the match as it draws it, blended between ticks, or [`verified`](#doc-game--views-and-the-match--confirmed-state): see [Views and the match](#doc-game--views-and-the-match--other-entities). A local handler's are the match as the tick that sent its event left it: see [Events](#doc-game--events--other-entities). Async handlers and tasks take none yet.
### As the tick started
Write `previous` before a binding to read every entity's component as it was when this tick started, whatever has run since:
```csharp
system Flock(mut Bird bird, query (previous Bird other) others)
{
mut var center = float3(0, 0, 0);
mut var seen = 0;
foreach (var o in others)
{
if (Math.Distance(o.other.position, bird.position) > 2) continue;
center += o.other.position;
seen++;
}
if (seen > 0) bird.velocity += (center / float(seen) - bird.position) * 0.001;
bird.position += bird.velocity;
}
```
Every bird steers by where the others were when the tick began, not by where the birds before it in the loop have already moved to. That is usually what such code means, and it is what lets it run fast:
- **It waits for nothing.** Nothing in a tick can change what a `previous` binding reads, so the system doesn't wait for the systems that change `Bird` this tick, and they don't wait for it. See [the schedule](#doc-game--schedule--when-systems-wait).
- **Its entities go across threads.** A system that changes a component and reads everyone's through an unmarked query runs its entities one after another on one thread, as each sees what the ones before it wrote. With `previous` there is nothing of the others' to see, so the birds are shared out over every core, with the same results as on one.
- **Its search is made once.** A loop that [starts by skipping rows](#doc-game--systems--only-the-rows-that-can-pass) by a number of a `previous` binding goes through an index of the tick's start. It's made at most once a tick, for every system that searches the same way, and the system may change the very field it searches by (`bird.position` above), which an unmarked query's loop can't.
`previous` goes on a binding of a system's query (or a [match handler's](#doc-game--events--querying-other-entities)), and reads the component's values: its text, lists, maps, sets and grids as they were too. The query has the same entities either way, as entities and their components come and go at the tick's end: one spawned this tick is in no query yet, and one destroyed this tick is still there with the values it started the tick with. Other bindings of the same query read the world as it is, and a [function handed the query](#doc-language--functions--borrowing-a-query) reads what the query reads. Filters, a system's own parameters, views and local handlers don't take it. To compare a component now with what it was, take two queries, one with the word and one without. For one entity by its handle, the World has the same: [`world.GetPrevious(target)`](#doc-game--systems--as-the-tick-started-by-handle).
Only what code reads of the tick's start is kept, and only for the tick. This is provisional but for the word and what it reads.
### Going through the rows at once
A `parallel` loop goes through a query's rows at once, on threads, where each row's work doesn't depend on the others:
```csharp
system Hits(query (Body body, with Fighter) fighters, Arena arena)
{
parallel (var f in fighters)
{
if (Math.Distance(f.body.position, arena.center) > arena.radius) continue;
f.entity.Send(Hit { damage = 1 });
}
}
```
The row is a foreach's: `f.entity` and the bindings, read-only. Steps follow a [parallel loop's rules](#doc-language--grids--going-through-every-cell): they change only the variables they declare, and can't spawn, add, remove, destroy or draw. Unlike a list's or a grid's steps, they can send the match's events, to the world or to an entity, and those arrive in the order the `foreach` would have sent them, so the results are the same on any number of threads. An event that holds text or lists can't be sent from a step.
In a view, a step also reads its row's [local fields](#doc-game--views), and writes them through a `mut` binding: each row is one entity's, so each step's local fields are its own. That is how a view works something costly out for every row on all the threads, then draws from the results in order:
```tide
view Crowd(query (mut Fighter fighter) fighters)
{
// `shown` is a local field of Fighter: where to draw him, worked out for every row at once
parallel (var f in fighters) f.fighter.shown = Stance(f.fighter.position, f.fighter.yaw);
foreach (var f in fighters) Draw.Circle(f.fighter.shown, 0.5, Color.white);
}
```
A local field that holds text or lists can be read in a step but not changed there, and a step can't read the local fields of the view's own entity where the rows write the same component's. A frame's loops take the threads whenever a host hands them its pool, as the standard one does. This is provisional.
## Only the rows that can pass
A loop that starts by skipping rows is read by the compiler. When the condition bounds a number of the row by values the loop doesn't change, the loop visits only the rows within those bounds, found through an index, instead of every row:
```csharp
system Separate(mut Body body, Sight sight, query (Body other, with Boid) boids)
{
foreach (var b in boids)
{
if (Math.Distance(b.other.position, body.position) > sight.range) continue;
body.velocity += Push(body, b.other);
}
}
```
Each boid looks at the boids near it, not at all of them. Nothing changes about what the loop does: the condition still runs for every row the index gives, and the rows come in the loop's normal order.
The condition can be a distance (`Math.Distance`, `DistanceSq`, `Length` or `LengthSq` of a difference, or `dx * dx + dy * dy`), a box written axis by axis, a comparison of one of the row's numbers (`b.unit.health < 10`), or an equality (`b.unit.team == myTeam`), combined with `&&`, `||` and `!`, written in the loop or in a function that returns it. Read-only locals can come first. The same goes for lists: `foreach (var wall in level.walls)`.
Equalities of whole numbers are found exactly, all of them at once, unless the condition also bounds a `float` place both ways (a distance or a box), which is searched instead. A world of chunks finds one by its place, an `int3`, and its dimension:
```csharp
foreach (var row in chunks)
{
if (row.chunk.at.x != at.x || row.chunk.at.y != at.y || row.chunk.at.z != at.z) continue;
if (row.chunk.dimension != dimension) continue;
found = row.entity;
}
```
The loop visits the chunks at that place in that dimension and no others, however many share its `x`. Any of the row's `int`, `long`, `byte` and `char` numbers, enums and bools count, and an `int2`'s or `int3`'s components: a `long` a place is packed into (`row.chunk.key == key`) is found the same way. A whole number compared as a `float` or a `double` (`double d = row.chunk.key;`) is not exact, and is searched as the number it's compared as. Other bounds in the same condition, like `row.chunk.heat < limit`, narrow those further.
Write `indexed` before a loop that has to be indexed:
```csharp
indexed foreach (var b in boids) { ... }
```
`indexed` changes nothing about the loop. It turns a loop that can't be indexed into an error that says why, instead of a loop that quietly looks at every row. Common reasons:
- Something happens before the condition, such as a `Send`. Move the condition first.
- The value compared with changes inside the loop.
- The system changes the same field of its own entity, such as `body.position += body.velocity` in a system whose loop finds boids by `position`. The index is kept while the rows it was made from don't change, so read the others as [the tick started](#doc-game--systems--as-the-tick-started) (`query (previous Body other, with Boid) boids`), or move that change into a system of its own. Handing the component as `mut` to a function or a task counts where that changes its match fields; a view handing its own to a [local task](#doc-game--tasks--local-fields) changes only its local fields, which no loop finds rows by. Handing it to C as `mut` (an `extern` function, or one that passes it on to one) counts as changing all of it.
`tidec --schedule` lists every loop that skips rows, and whether an index finds the rest or why not. An index of rows that don't change, like walls, is made once and kept across ticks.
An index pays when the condition leaves most rows out. A condition most rows pass, such as `if (b.unit.down) continue;` in a battle where few are down, gains nothing from one, so when a search of a query's rows finds more than about one row in six, the loop goes through every row instead, which costs less for each. The results are the same either way, and nothing needs writing differently.
## Other entities: the World
A system often needs another entity's component in the same tick: the target it attacks, the leader it follows. A `World` parameter gives it, by the entity's handle:
```csharp
system Attack(Attacker attacker, World world, mut Stats stats)
{
if (!world.Has(attacker.target)) return;
var target = world.Get(attacker.target);
if (target.value <= attacker.damage) stats.kills += 1;
}
```
- `world.Get(e)` is a copy of that entity's `Health`, or its zero value when it has none.
- `world.Has(e)` tells whether it has one.
- `world.TryGet(e, out var health)` is both in one: whether it has one, and the copy, or the component's default when it has none (see [Out parameters](#doc-language--functions--out-parameters)).
- `world.Set(e, value)` puts one back, and needs `mut World`. It does nothing for an entity without one.
- A read-only `Health` parameter keeps the value captured on entering that entity's invocation, including preceding invocations' writes. `Set` updates the world immediately: a following `Get` or query sees the new value.
- With `mut Health`, setting the current entity also replaces that active parameter immediately, including through helpers. Setting another entity leaves the parameter unchanged. Whole-value replacement discards unfinished edits; later edits are written back normally.
```csharp
system Reset(mut Health health, mut World world)
{
world.Set(this, Health { value = 20 });
health.value++; // Finishes at 21.
}
```
Between the `Set` and the final write-back, `Get` and queries read the published value of 20. An explicit copy made before `Set` keeps its old value.
What `Get` gives is a copy, as a list's element is. To change another entity's component, `Edit` it where it is: the block after the call names the component, and what the block changes is put back on the entity as the block ends.
```csharp
system Heal(Healer healer, mut World world)
{
world.Edit(healer.patient, health)
{
if (health.value >= 100) return;
health.value += 1;
health.lastHealer = this;
}
}
```
- In the block, `health` is the entity's `Health` itself, as a `mut` parameter is the component of the entity a system runs for: its fields change where they are, its lists and text too, with nothing copied, and a function's `mut` parameter can take it. The name is new, and only the block has it.
- It's put back however the block is left: at its end, or by a `return`, or a `break` or `continue` of a loop the `Edit` is in, or a `try` or `fail` in a function that can fail, in an async handler as anywhere. There's no `Set` to forget on an early `return`.
- An entity that's gone, or has no `Health`, skips the block, as `Set` does nothing then. Check `world.Has(e)` first for what to do instead.
- It needs `mut World`, like `Set`, and the schedule counts it as `Set`: it reads and writes every entity's `Health`, and keeps the system on one thread. So an `Edit` whose block never changes its name is a warning: read with `TryGet` instead.
- `this` can be edited beside a read-only parameter of the same component, as it can be `Set`: the stored component changes, and the parameter keeps what it read. Beside a `mut` parameter of it, change the parameter.
- Inside the block, read and change `health`, not `world.Get` of the same entity: the compiler says so where it can tell they're the same, and a task can't `await` there.
- `world.Edit(from, a), world.Edit(to, b) { ... }` edits two entities in one block, as other calls that take a block are listed. If they turn out to be one entity, `a` and `b` are the same component, and both changes land.
Taking it out, changing it and putting it back is what `Edit` does for you, and still works:
```csharp
mut var health = world.Get(healer.patient);
health.value += 1;
world.Set(healer.patient, health);
```
### As the tick started, by handle
`GetPrevious`, `HasPrevious` and `TryGetPrevious` are `Get`, `Has` and `TryGet` of the entity as it was when the tick started, whatever has run since:
```csharp
system Chase(mut Body body, Bot bot, World world)
{
if (world.TryGetPrevious(bot.target, out var was))
body.velocity = Math.Normalize(was.position - body.position) * bot.speed;
}
```
Like a [`previous` binding](#doc-game--systems--as-the-tick-started), they read nothing the tick can change: the system waits for no system that changes `Body`, none waits for it, and its entities go across threads though it changes `Body` itself, where `world.Get` would keep them on one. An entity that wasn't there when the tick started (spawned this tick) has no `Body` then: `HasPrevious` is false and `GetPrevious` gives the zero value. Systems, match handlers and the functions they hand their World to can call them; views and tasks can't.
The signature doesn't say which components a system reaches this way: the engine reads it off the calls. Each counts as access to every entity's component, so the system is scheduled like one that touches them all, and one that calls `Set` or `Edit` runs on one thread. [The schedule](#doc-game--schedule--through-the-world) and your editor show what each system reads and writes through its `World`. Where the change can wait for the end of the tick, an event (`e.Send(Hit { ... })`) keeps systems running side by side; see [Events](#doc-game--events).
A function or method can take the `World` too, and the system passes its own:
```csharp
bool TryFind(Entity target, World world, out Health health)
{
return world.TryGet(target, out health);
}
system Aim(mut Attacker attacker, World world)
{
if (TryFind(attacker.target, world, out var health)) attacker.threat = health.value;
}
```
What the function reaches through it counts as the system's own, through however many functions it's passed, so nothing about the schedule changes: `Aim` reads every entity's `Health`. A function that calls `Set` or `Edit` takes `mut World`, and so does the system that passes it. The parameter rules above apply through helpers too, and a view can't call one that changes the match.
Views and event handlers take a `World` too; a view only reads the match through it, and can change local entities with `mut World`. A [local handler](#doc-game--events--local-handlers) of one of the match's events takes none: it hears the match as the event left it, and the `World` is the match as it is now.
## Once per entity, or once per tick
A system with component parameters runs once for every matching entity, and `this` is the entity it's running for. One without them runs once per tick, for no entity, so it has no `this`:
```csharp
system CountDown(mut Round round, Time time)
{
round.timeLeft -= time.dt;
}
```
`return;` ends the system for the current entity, and it goes on with the next one.
## Order
Systems run in one order, the same on every machine. By default, it follows the files, sorted by path, then the order of the systems in each file. A game's [packages](#doc-packages--using-and-writing) come first, each after the packages it needs.
`[Before]` and `[After]` change that. They take any number of systems:
```csharp
[After(Gravity, Collisions)]
system Move(mut Body body, Time time)
{
body.position += body.velocity * time.dt;
}
```
Of the systems whose constraints are met, the earliest in the default order runs next. Constraints that form a loop are an error that names the loop. Hover a system in your editor to see its place in the order.
Systems can share a name when their parameters differ, as [functions can](#doc-language--functions--default-values-names-and-overloads). Nothing calls a system, so where one of them is named, it's written with its parameters' types, in order, with its filters and without names or `mut`:
```csharp
system Move(mut Body body, Speed speed, with Player) { ... }
system Move(mut Body body, Speed speed, with Enemy) { ... }
[After(Move(Body, Speed, with Player)), Before(Move(Body, Speed, with Enemy))]
system Aim(mut Turret turret, Body body) { ... }
```
A name alone is fine while only one system has it. When several share it, `[After(Move)]` is an error that lists them as they're written, and so is a parameter list that isn't exactly one's. Views and event handlers work the same way, and the schedule and the profiler show a shared name with its parameters.
A system marked `virtual` can be replaced by another package's `override`, which runs where it would have: at its place in this order, with its attributes, and under its name where others name it (see [Virtual and override](#doc-language--overrides)).
### Named phases
An enum gives shared names to parts of the tick. Assign systems to its phases with `Stage`:
```csharp
enum TickStages { Input, Simulation, Late }
[Stage(TickStages.Simulation)]
system Move(mut Body body, Time time)
{
body.position += body.velocity * time.dt;
}
[Stage(TickStages.Simulation, 10)]
system Collisions(...) { ... }
[After(TickStages.Simulation)]
system Finish(...) { ... }
```
Phases follow the enum members' declaration order. The optional comma-separated offset orders systems within a phase: lower first, with 0 as the default. Negative offsets work too, and the enum needs no numeric spacing. Equal offsets keep the usual order and can use `Before` or `After` on particular systems.
`After(TickStages.Simulation)` follows every system in that phase, including its offsets; `Before` precedes all of them. Empty phases keep their position. A system in a later phase waits for the earlier phases to finish, while systems at the same offset can still run alongside each other. Unassigned systems keep their default order wherever the constraints allow. Separate enums have independent phase orders.
The same attributes order views among views and event handlers among the handlers of one event. They don't move code between the tick, the frame and event handling.
## Running side by side
Two systems that write the same component isn't a mistake: it's normal. Such systems run one after the other, in the order above. Systems that share nothing they write can run at the same time. The compiler works this out from the parameters, and can tell you why each system waits (see [The schedule](#doc-game--schedule)):
```
stage 2 Move (per entity)
after Steer: both write Body
```
Declaring more than a system uses makes others wait for nothing, so it's a warning: a parameter that's never used, or a `mut` one that's never written (a `mut World` that never calls `Set` or `Edit` too). A component that's only there to pick entities belongs in `with`. The editors offer quick fixes for these.
## Written in C
A system's code can be C's: a library's, or a loop over every entity's numbers that's worth writing by hand. `extern system Move(mut Position position, Velocity velocity);` declares one, with no body, and C is handed the components as the arrays the match keeps them in, rather than an entity at a time. It's a system like the others to everything on this page: its parameters pick its entities, and it's ordered and scheduled by them. See [Systems written in C](#doc-c--functions--systems-written-in-c).
## What systems can't do
Systems run the match, so they can't read this machine's local state, and they can't draw: drawing happens every frame, in [views](#doc-game--views).
---
Source: https://tide-engine.dev/game/schedule.md
Read Tide's system schedule and see how the compiler uses data dependencies to run ECS systems across threads without changing results.
# The schedule
Every system declares what it reads and writes, so the compiler knows, before the game runs, which systems can run at the same time and which have to wait. That plan is the **schedule**.
The tick follows it on every core: a system starts as soon as what it waits for is done, and big systems split their entities across threads too. Running in parallel never changes results, so every machine still gets the same match. A small tick, where waking the other threads would cost more than they'd save, runs on one thread: under about half a millisecond of work, by the time its systems took in the ticks before. On the web, ticks run on threads when the page is cross-origin isolated (see [The tide command](#doc-tools--cli--threads-on-the-web)), and on one thread elsewhere.
## Reading it
`tide schedule` prints systems grouped by stage, keeping their tick order within each stage. This example is from a demo where balls bounce around an arena:
```
demo: 5 systems each tick, 4 stages deep; 5 can run alongside others.
A system starts once everything it runs after is done.
stage 1 Steer (per entity)
writes Body, Aim
alongside Expire
stage 1 Expire (per entity)
writes Lifetime
alongside Steer, Fire, Move, Bounce
stage 2 Fire (per entity)
reads Body, Aim
after Steer: it writes Aim, which this reads
alongside Expire
stage 3 Move (per entity)
reads Time
writes Body
after Steer: it writes Body.velocity, which this reads (and through Fire)
after Fire: it reads Body.position, which this writes
alongside Expire
stage 4 Bounce (per entity)
reads Arena
writes Body
after Steer: both write Body.velocity (and through Fire)
after Fire: it reads Body.position, which this writes (and through Move)
after Move: both write Body.position
alongside Expire
Views, every frame in this order (they only read, so nothing waits):
DrawArena
DrawBalls
DrawPlayers
Options
Event handlers, at the end of the tick, as their events are sent:
Spawned: Setup
```
`Steer` and `Expire` are both stage 1: neither waits for another system. `Expire` only touches `Lifetime`, so it can run alongside everything else. The others work on the same fields of `Body`, so they wait for each other, in the order they're written, and each wait says which field it's over: `Fire` reads a ball's position, which `Steer` doesn't write, so it's the `Aim` it waits for. Stages show dependency depth; `Fire` can start when `Steer` finishes, even if `Expire` is still running.
In the editors, each system shows its stage and why it waits right above it, like `stage 2 · after Move: both write Body`, and on hover. A system that runs for each entity also says whether its entities go across threads, or [what keeps them on one](#doc-game--schedule--splitting-across-threads).
Each event's handlers are listed in the order they run. A game with [local handlers](#doc-game--events--local-handlers) of the match's events has those listed after the match's, apart, since they run on each machine at the start of a frame and not in the tick. The ones that wait for the server say `(verified)`:
```
Event handlers, at the end of the tick, as their events are sent:
Spawned: Setup
Hit: TakeHit
Local handlers of the match's events, at the start of a frame, for what the ticks since the last one sent:
Destroyed: Mourn (verified)
Hit: Count (verified), Flash
Glanced: Spark
```
### Through the World
A system's parameters say what it reads and writes of the entities it runs for. What it reaches through a [`World`](#doc-game--systems--other-entities-the-world) parameter is any entity's, and its signature doesn't name those components, so the schedule does, on lines of their own:
```
stage 1 Heal (per entity)
reads Healer
reads any entity's Armor, through World
writes any entity's Health, through World
alongside Aim, Chase
stage 2 Drain (per entity)
writes Health
after Heal: both write Health
```
The editors show it above the system too, `stage 1 · World: reads Armor; writes Health`, and when you hover the system or its `World` parameter.
A system that passes its `World` to a function reaches what the function does, and it's listed the same way: the schedule doesn't tell the two apart.
[Read-only query parameters](#doc-game--systems--another-set-of-entities) also read components of a separate entity set. Those bindings count as reads of any entity's component and appear in the schedule and editor hints, so `query (Body body, with Fighter) fighters` waits for earlier systems that write `Body`, even when their outer entity filters differ. The query's `with` and `without` filters access no component data.
In a big game, the long lists are cut short. Every wait that's a system's own is there, but the ones that go through another system (`and through Fire`) and the systems it runs alongside are named up to 32 each and counted past that: `after 412 more, through those`, `alongside Expire, Fade and 168 more`.
## When systems wait
Two systems **conflict** when one writes a field of a component or singleton that the other reads or writes. It goes by field: a system that writes `Party.money` and one that reads `Party.at` don't wait for each other, on the same parties at the same time, and `tide schedule` and the editors name the field a wait is over (`it writes Party.money, which this reads`, with `and 2 more of its fields` where there are several). What counts as a system's is what its code does with the value, through the functions it hands it to: reading or copying it whole, calling one of its own methods on it, or handing it to C is every field. A field is as far as it goes (two elements of one array are one field), and small fields kept side by side in a component (four `bool`s, say) count as one. What a system reaches through its `World` is the whole component; a query's rows are the fields its loops read of them, where the system does nothing else with the query. Conflicting systems keep their order in the tick; `[Before]` and `[After]` order systems too. A system starts as soon as everything it waits for is done, with no barriers between stages: a system's stage is only how deep it is in that chain.
[Named phases](#doc-game--systems--named-phases), assigned with `[Stage(MyStages.Simulation)]`, add explicit ordering requirements to that plan. Later phases wait for earlier ones, and higher offsets wait for lower offsets within a phase. These names are separate from the numbered dependency stages printed above: systems at one phase and offset can share a dependency stage and run together. The schedule explains these waits as requirements of the stage order.
Some things never make systems wait:
- **Filters.** `with` and `without` read nothing.
- **Entities that can't overlap.** Two systems that write the same component don't conflict if they can never touch the same entity, which the compiler proves from the archetypes: `with Player` against `with Enemy`, when nothing is both. A [sparse component](#doc-game--entities--limits) doesn't count for this: entities with it and without it are one archetype, kept side by side, so `with Stunned` and `without Stunned` still wait for each other. A component a system reaches through its `World` or a read-only query is any entity's, so this doesn't hold for it: `world.Get(e)` and `query (Health health) targets` wait for every earlier system that writes `Health`.
- **What code reads as the tick started.** A binding marked [`previous`](#doc-game--systems--as-the-tick-started), `query (previous Body other) others`, and the World's [`GetPrevious`, `HasPrevious` and `TryGetPrevious`](#doc-game--systems--as-the-tick-started-by-handle) read an entity's `Body` as it was when the tick began, which nothing in the tick changes. The system waits for no writer of `Body` over it, and none waits for it. `tide schedule` lists it apart: `reads any entity's Body as the tick started: no wait over it`.
- **Structural changes and events.** `Add`, `Remove`, `Destroy` and `Send` are recorded and applied at the end of the tick, in order. Event handlers run then too, so they aren't part of the tick's schedule.
- **Input and `Time`**, which systems only read. An entity's input is its owner's, though, so a system that reads its entities' input reads their `Owner`: it waits for an earlier system that changes it.
- **C.** Calls to C are trusted: they make no system wait, and a system that calls C splits across threads like any other. What C does when it's called from several threads at once is the game's to get right. A [system written in C](#doc-c--functions--systems-written-in-c) is scheduled by what it declares, as its code can't be read, and shows as `(per entity, in C)`.
Some things systems wait for each other over whatever entities they run for:
- **Text, lists, maps, sets and grids.** Each component, singleton and event keeps what its fields hold of these in memory of its own, which one system changes at a time. So two systems that change the same component's text or lists wait for each other even when they run for different entities (`with Player` against `with Enemy`), and two that change different components' or singletons' don't. A `Spawn`, `Add` or `Send` whose values hold text or a list changes that component's or event's. `tide schedule` says whose: `both change the text, lists or grids of Party`. Reading them alongside is fine. What C can write is the exception: a component or singleton your code hands to a C function that may change it shares one such memory with every other one handed to C, so systems that change any of those wait for each other.
- **Spawns and queued effects.** Spawning makes no system wait: a spawn's identity comes from the entity and the place in the code that made it, and each system's entities are registered once it's done, in the tick's order. Structural and event effects keep system order, then the order of the entities that made them.
- **Tasks.** A system that starts [tasks](#doc-game--tasks) runs their code until they first wait, which can spawn and change text, and the match keeps its tasks in the order they start. So it runs on one thread, and waits for the systems before it that start tasks, spawn or change text. Tasks that go on later do so after the tick's changes, one at a time, in the order they started: `tide schedule` says so at its end.
## Keeping it wide
- Take a component as `with` when a system only needs it to pick entities.
- Don't declare `mut` for what a system only reads. Unused access is a warning, and the editors offer a quick fix for it.
- Read and write the fields a system needs where it needs them (`party.money`), rather than copying a component or singleton whole into a variable: a copy reads every field. Systems that use different fields of a big component run side by side without it being split up.
- Reach other entities through the `World` only where the answer is needed this tick. An event sent to the other entity makes no system wait.
- Where a system looks at other entities and last tick's values will do (who is near, who to chase), read them as the tick started: `query (previous Body other) others`, or `world.GetPrevious(target)` for one by its handle. It then waits for nobody, and goes across threads even when it changes `Body` itself.
- Do the costly work new entities need (a chunk made from its seed) in a system that records nothing. One that changes its own entities' text, lists or grids and records nothing shares them out over the threads whatever order they were made in, so those spawned the tick before are spread too. One that also spawns, sends or destroys gives each thread a run of the entities in the order they were made, and the newest, the ones with the work, are all in the last.
## Splitting across threads
The other kind of parallelism is a system splitting its entities across threads: each thread takes a run of them, 2,048 at most. How small the runs get depends on what the entities cost: the engine times each system as the match runs, so a few hundred entities that each take a lot of work are shared out over every core, down to a few dozen a thread, while a few hundred cheap ones stay on one thread, where they're done sooner than another thread would wake. It doesn't change results either, and needs nothing from you, but a system only splits when no entity's turn depends on another's. One that changes a singleton and reads it back runs on one thread, alongside the others (below). One that changes its own entities' text, lists, maps, sets or grids (`party.path.Add(next)`, `unit.name = "..."`, `chunk.blocks[x, y, z] = Block.Stone`, `chunk.blocks = Grid3(16, 16, 16)`) splits like any other: the result is the same as on one thread, on every machine. So a system that makes each new chunk of a world from its seed makes them on every core, and one that steps every chunk's cells does too. Two things keep such a system on one thread, and `tide schedule` says which: a component your code hands to a C function that may change it, and a game split across [shards](#doc-multiplayer--shards), whose components keep all of these in the match's one memory. A game with [hidden state](#doc-game--visibility) splits them as any other does, and a system whose entities set their groups' audiences (`Visibility.Set(group, audience)`, as a chunk made from its seed is shown to the players waiting for it) does too: the audiences are set after its entities, in their order, as one thread sets them. What else of visibility it does keeps it on one thread: making or ending a group (`Visibility.CreateGroup`, `DestroyGroup`) in the system, a `Set` in a function it calls rather than in its own code, and a `Visibility` component's own `Set`. Writing an element of a fixed array in the entity's own component (`bot.seen[i] = x`) is a write to that component like any other, and splits. So does one that calls its `World`'s `Set` or `Edit`, which may change any entity, or that reads through its `World` or a query a component it also changes: it then sees the entities it already ran for as it left them, the same on every machine. Reading the component as the tick started (a `previous` binding, `world.GetPrevious`) isn't such a read: the system splits. Everything a system records (spawns, adds, removes, destroys, events) is applied in the order one thread would have recorded it: a system that records anything goes through its entities in the order of their identities, and threads take runs of that order.
For a per-entity system that stays on one thread, `tide schedule` says what keeps it there, and where in the code it first does:
```
stage 3 Tally (per entity)
reads Body
writes Score
on one thread: it changes the singleton Score (game.tide:42)
```
The editors say it above the system as well: `on one thread: it changes the singleton Score`, which goes to that place when clicked, or `its entities go across threads` beside its stage. Hovering the system says the same.
### Adding to a singleton
A system that runs for each entity and takes a singleton `mut` usually only adds to it: it counts, sums, keeps a least or a most, adds to a list, or hands the singleton to a function that does. No entity's turn then reads what another's wrote, and the system's entities go across threads like any other's. Each thread works out what its entities add, and once they're all done the singleton is changed with those values in the entities' order, on one thread: the count, the list and its order, and a `float` sum to its last bit are what one thread would have made. `tide schedule` says so:
```
stage 2 Enlist (per entity)
reads Trooper
writes Crowd
across threads: what its entities change of Crowd is changed after them, in their order
```
```tide
system Enlist(Trooper t, mut Crowd crowd)
{
if (t.down) return;
crowd.standing[t.team] += 1;
crowd.sum += t.position.xz;
crowd.spots.Add(Spot { id = this, at = t.position });
}
```
What makes a system one: every statement that names the singleton is an assignment into it or a call that changes it (a list's or a map's method, a function handed it `mut`), and what that statement takes from the entity is plain values: fields, variables, constants, operators, `Math` and constructors of those, or text written out or interpolated from them. A system stays in order on one thread when a row reads what rows write (`if (score.total > 10)`, `unit.rank = score.total`), when what a statement takes from the entity is a call of the game's own or a list, when the function handed the singleton sends, spawns, rolls or starts a task, or when the system calls C. Reading a field of the singleton that the system never writes (`if (unit.id < score.limit)`) is fine anywhere.
It only pays where the entities have work of their own, since the adding itself still happens on one thread. A system whose entities do little else than add stays in order as it was, and says so: `on one thread: it changes the singleton Score, and adding to it is most of what its rows do`. Working something out for each entity in the same system as it's added (a path, a score, a nearest enemy) is what the threads take.
## Which waits cost time
A wait only costs a tick time when it's on the longest run of systems that each wait for the one before. `tide schedule --measured ` takes the report a [profiled run](#doc-tools--debug-views--profile-captures) wrote (`tide run --release --frames 600 --profile report.json`) and adds, after the schedule:
```
Measured (report.json, 100 ticks, 4 of 4 systems ran):
6.500 ms a tick, the systems one after another
3.500 ms, the longest chain of systems that wait for each other: no tick is shorter, on any number of threads
That chain, last to first (a wait that isn't on it costs the tick nothing):
0.500 ms Settle (across threads)
after Count: it writes Score, which this reads
2.000 ms Count (on one thread: it changes the singleton Score (game.tide:10))
after Move: it writes Body.position, which this reads
1.000 ms Move (across threads)
The costliest systems:
3.000 ms 46% Think (across threads)
2.000 ms 31% Count (on one thread: it changes the singleton Score (game.tide:10)), on the chain
```
The first number is the tick on one thread. The second is what the waits alone leave of it: more threads can't go under it, so a tick gets shorter by making a system on the chain cheaper, by getting its entities across threads, or by removing one of the chain's waits. `Think` costs the most here and isn't on the chain: nothing waits for it, so it runs beside the other three. A system's time is from its start to its end, with its entities on whatever threads they went to, so one that already goes across threads counts as it ran. Systems that didn't run in the profiled ticks count as nothing.
A second part does the same for the frame's views, from the same report: what they took one after another, as they run today, and the longest chain of views that wait for each other, by what their parameters read and write and the order `[After]` and `[Before]` give them.
A spawn returns its final logical identity immediately; there is no temporary handle or later identity rewrite. Structural installation remains deferred. Queries executed by match/simulation code traverse ascending logical entity identity across archetypes. Presentation/view queries retain their existing traversal order. Extern systems receive contiguous runs in that same global order, while ordinary C function calls from otherwise independent parallel rows retain the game's existing determinism and thread-safety responsibility.
## Parallel loops
The third kind is inside a system: a `parallel` loop goes through a grid's cells, or blocks of them, all at once (see [Grids](#doc-language--grids)). It can also go through a [list's elements by index](#doc-language--text-and-lists--going-through-every-element-at-once). Its steps spread across the threads that are free, even while other systems run, and the system goes on once they're all done. Each step reads the collection as the loop found it and changes only its own cell, element or block, so the result is the same as on one thread. A foreach over a grid whose steps only touch their own cell runs the same way. The system itself waits for others as any system that writes the collection's component or singleton would, and the schedule shows its loops: `Fall (once, 1 parallel loop)`.
`tide schedule` ends with every parallel loop: what one step of it is reckoned to cost, and from how many steps the loop is worth the threads, or what keeps its steps on one:
```
Parallel loops, and when their steps go to the threads:
Crowd, line 107: a query's rows, a step reckoned at 4843: on the threads from 413 steps a frame
Weigh, line 72: a list's elements, on one thread: its steps read 'scale', which lives on the thread that made it, as text, lists, maps, sets and grids in variables do
```
The reckoning is of the code as written: a step that returns on its first line counts as much as one that runs it all. A loop under its number runs in order on the thread that reached it, with the same results. The numbers are where a loop starts: as the game runs, the engine times each loop, and one whose steps take longer than their code looks goes to the threads from fewer.
A view that runs for each entity and starts with `if (...) return;` tests of this machine's own state (the entity's [local fields](#doc-game--views), a local singleton's fields), or of the entity's `bool`, `int`, enum and `Entity` fields, has those tests run before anything else of the entity is copied, so a view that goes through a thousand entities to draw six costs little for the rest. `tide schedule` lists them:
```
Views that test an entity before copying anything of it:
DrawChosen: 2 tests, down to line 90
PoseChosen, the rows of its loop at line 120: 1 test, down to line 122
```
The second line is a view's query: a view that runs once and goes through its one query in one loop, whose steps start with `if (...) continue;` tests of the same kind, makes no row for an entity they turn away. The loop may be in a function the view hands its query to. The tests may also read fields of the match's that a frame shows exactly as the tick has them: a `bool`, an `int`, an enum or an `Entity`, as in `if (!row.t.laserOn || row.t.holstered) continue;`. A test that calls a function, or reads a field that's drawn between two ticks (a position, an angle), is run by the view's code as usual, after the entity's components are read.
## In CMake builds
In a CMake build of the engine's repo, `_schedule` is a build target that prints it, and `tidec --schedule` prints it for any files.
---
Source: https://tide-engine.dev/game/events.md
Send and handle Tide events in the match and local presentation, with predicted and verified handlers that work through rollback.
# Events
An event is something that happened, sent from one part of the game to the rest: a hit, a pickup, a round ending. Events carry their context in fields, like a struct's.
```csharp
event Hit
{
Entity attacker;
int damage;
}
```
## Sending
`entity.Send(...)` sends an event to an entity, and `Send(...)` sends it to the whole world:
```csharp
system Explode(Bomb bomb)
{
if (bomb.timer > 0) return;
bomb.target.Send(Hit { attacker = bomb.owner, damage = 50 });
this.Destroy();
}
system EndRound(Round round)
{
if (round.timeLeft <= 0) Send(RoundOver { winner = round.leader });
}
```
The sender isn't recorded. When handlers need it, put it in a field: the entity that sends is often not the one that matters, like a bomb sending a `Hit` for whoever threw it.
An event is a value, so a local can hold one, a handler can send its event on (`other.Send(hit)`), and ordinary functions and methods can take or return the whole payload (`int Damage(Hit hit) { return hit.damage; }`). Factories can return `Hit { damage = amount }`; the caller chooses whether to send it. Command payloads follow the same value rules. Passing one grants no world or sending access and supplies no authenticated sender; handlers pass that separately when needed. Payloads cannot be stored fields. Local handlers still receive only the match data their event journal captures. The engine's own events, below, are only the engine's to send.
A [function](#doc-language--functions--sending-and-spawning) can send too, for the code that calls it:
```csharp
// Called from a system or a handler, which could send Hit themselves
void Splash(Entity target, int damage)
{
target.Send(Hit { damage = damage });
Send(Splashed { });
}
```
A view that calls it gets an error, as a view can't send the match's events.
## Handling
A handler is code that runs when an event is sent. It's declared with `event` too: the first parentheses hold the event that triggers it, and the second hold the same parameters as a system's, including read-only [queries](#doc-game--systems--another-set-of-entities) in synchronous handlers.
```csharp
// Health and this come from the entity the Hit was sent to.
event(Hit hit) TakeHit(mut Health health)
{
health.value -= hit.damage;
if (health.value <= 0) this.Destroy();
}
// Takes nothing from the entity, so it runs once per Hit.
event(Hit hit) CountHits(mut Stats stats)
{
stats.hits += 1;
}
```
- A handler's components and `this` come from the entity the event was sent to. If that entity doesn't match its parameters, the handler doesn't run for it.
- A handler that takes no components runs once per event, whether it was sent to an entity or not, and has no `this`.
- A handler that needs an entity needs every `Send` of its event to name one. The compiler checks: `Send(Hit { ... })` is an error when a `Hit` handler takes components, and says to write `entity.Send(...)`.
- A handler that doesn't read the event can leave its name out: `event(Spawned) Arm(...)`.
### Querying other entities
A match handler can inspect another set of entities with the same query syntax as a system:
```csharp
event(RoundOver) ResetPlayers(query (with Player) players)
{
foreach (var player in players)
player.entity.Send(Reset {});
}
```
This runs once per `RoundOver`. The query selects the players to visit; it does not require the event to target a player. Ordinary component parameters still select the event's target.
Each `foreach` reads the current match at the handler's turn in the tick-end queue. Earlier handlers' completed writes and structural changes already applied are visible. Sends, spawns, adds, removes and destroys recorded by the handler remain deferred, including changes recorded inside a query loop. `Spawned` queries include the new entity; `Destroyed` queries include the entity before it goes.
Rows are read-only. To act on an entity, send it an event or use an explicit `mut World` with the existing `Set` rules. A `Set` is visible to later query reads. Setting the handler's current entity also replaces its active mutable component parameter immediately. Subsequent parameter edits retain usual write-back timing: queries see the value published by Set until the handler finishes, and following handlers see the written-back value.
Async handlers and tasks cannot take queries yet. Local handlers' [recorded query rows](#doc-game--events--other-entities) retain their own timing rules.
A handler's query can read the tick's start too: `query (previous Body was) all` gives each entity's `Body` as it was when the tick started, whatever the tick's systems and the handlers before this one did to it, and `world.GetPrevious(entity)` the same for one entity. By a handler's turn entities have come and gone, so such a query has the entities that are in the world now and had the component then: one spawned this tick is no row. See [As the tick started](#doc-game--systems--as-the-tick-started).
## When they run
Events are handled at the end of the tick, along with structural changes, in the order they were all recorded. A `Send` before a `Destroy` of the same entity is handled while the entity still exists. An event sent to an entity that's gone by its turn is dropped.
Handlers can send events and change entities in turn. Those are handled next, until nothing is left, so everything settles within the tick. Systems later in the same tick don't see an event's effects yet, as with `Spawn`.
The handlers of one event run in the order they're declared, and `[Before]` and `[After]` order them as they do systems, among the handlers of the same event.
Handlers can also use [named phases](#doc-game--systems--named-phases): `[Stage(MyStages.Apply)]`, optionally with an offset such as `[Stage(MyStages.Apply, 10)]`. `Before` and `After` can name a whole phase. Each event has its own order, even when different events use the same phase enum.
A handler of an event nothing sends is a warning: it would never run. So is declared access a handler doesn't use, as for systems (see [Systems](#doc-game--systems)).
Events waiting to be handled are part of the world: a snapshot holds them, and running a tick again sends and handles them again the same way. What a machine shows of an event is heard [once](#doc-game--events--once-under-rollback) all the same, by a local handler.
## Built-in events
The engine sends these. They cost nothing where no handler takes them. The match's handlers take the first four, and so do [local handlers](#doc-game--events--the-engine-s-events), on each machine.
| Event | Sent to | When |
|---|---|---|
| `Spawned` | The entity | It's spawned, or its scene is loaded |
| `Destroyed` | The entity | It's destroyed, while its components can still be read |
| `PlayerJoined` | The world | A player joins, with their `PlayerID` in `player` |
| `PlayerLeft` | The world | A player leaves, with their `PlayerID` in `player` |
| `Shown` | The entity, on this machine | The entity and the components a local handler needs become available |
| `Hidden` | The entity, on this machine | The entity or components a local handler needs become unavailable |
| `Forgotten` | The entity, on this machine | Its [local fields](#doc-game--local-state--letting-go) go: a local event, for local handlers |
```csharp
// Spawned has no fields, so it needs no name.
event(Spawned) Arm(with Player)
{
Spawn(Weapon { owner = this });
}
event(PlayerJoined joined) GiveBody()
{
Spawn(Body, Owner { player = joined.player });
}
```
The server picks the tick a player joins or leaves on, so every machine handles it on the same one.
Handlers can't draw: drawing happens every frame, in [views](#doc-game--views). What a machine shows of an event goes through a local handler, which leaves it in local state for the views.
## Local handlers
A match handler changes the match. What a machine shows of an event is something else: a flash, a burst of sparks, a line in the chat. That's a **local handler**'s, which hears the match's events on each machine. It's `local` before the same `event(...)`, with no keyword of its own:
```csharp
component Fighter
{
int health = 100;
local float flash; // This machine's: how long the hit still shows
}
struct Spark
{
float2 position;
float2 velocity;
float age;
}
local singleton Fx
{
List sparks;
float shake;
}
event Hit
{
int damage;
}
// The match handles the hit...
event(Hit hit) TakeHit(mut Fighter fighter)
{
fighter.health -= hit.damage;
}
// ...and each machine shows it.
local event(Hit hit) ShowHit(Body body, mut Fighter fighter, mut Fx fx)
{
fighter.flash = 0.2; // A local field of the fighter that was hit
fx.sparks.Add(Spark { position = body.position, velocity = float2(0, hit.damage * 0.1) });
}
// Views draw what the handler left.
view DrawFighter(Body body, mut Fighter fighter)
{
fighter.flash = Math.Max(0, fighter.flash - Frame.dt);
Draw.Circle(body.position, 0.5, fighter.flash > 0 ? Color.white : Color.red);
}
```
A local handler changes [local state](#doc-game--local-state) and never the match. Like every handler it can't draw: it leaves what happened where views find it, in a local singleton, in local entities, or in the [local fields](#doc-game--local-state--local-fields) of the entity the event was sent to.
Tap a ball below, three times. Each tap reaches the match as a command, whose handler sends the ball a `Hit`. The match's handler of `Hit` takes a health off, and a local one makes the ball flash, through a local field. A ball that meets a wall sends `Bounced` to the world: nothing in the match handles it, and a local handler makes sparks of it. The third hit destroys the ball, and `Destroyed` has two handlers too: the match's spawns another ball, and a local one bursts where the ball was.
**Events, and what a machine shows of them** ([Run example](https://tide-engine.dev/examples/events/?stats))
```tide
settings { title = "Events"; tickRate = 30; maxPlayers = 1; }
component Ball
{
float2 position;
float2 velocity;
int health = 3;
local float flash; // This machine's: how long a hit still shows
}
event Hit { int damage; } // Sent to a ball
event Bounced { float2 at; } // Sent to the world, only for what's shown
command Poke { }
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Ball { position = float2(-1, 0.5), velocity = float2(1.6, 1.1) });
Spawn(Ball { position = float2(0.8, -0.4), velocity = float2(-1.2, 1.5) });
Spawn(Ball { position = float2(0, 1), velocity = float2(0.9, -1.7) });
}
system Fly(mut Ball ball, Time time)
{
ball.position += ball.velocity * time.dt;
if (Math.Abs(ball.position.x) > 1.5)
{
ball.position.x = Math.Sign(ball.position.x) * 1.5;
ball.velocity.x = -ball.velocity.x;
Send(Bounced { at = ball.position });
}
if (Math.Abs(ball.position.y) > 1.5)
{
ball.position.y = Math.Sign(ball.position.y) * 1.5;
ball.velocity.y = -ball.velocity.y;
Send(Bounced { at = ball.position });
}
}
// A tap pokes a ball, and the match answers with an event sent to it.
command(Poke poke, PlayerID sender) PokeBall(with Ball)
{
this.Send(Hit { damage = 1 });
}
// The match's handler changes the match, at the end of the tick...
event(Hit hit) TakeHit(mut Ball ball)
{
ball.health -= hit.damage;
if (ball.health <= 0) this.Destroy();
}
// ...and another ball takes the place of one that's gone.
event(Destroyed) Replace(Ball ball)
{
Spawn(Ball { velocity = float2(-ball.velocity.y, ball.velocity.x) });
}
// Local handlers show what happened, on each machine, and never change the match.
struct Spark
{
float2 position;
float2 velocity;
float age;
}
local singleton Fx { List sparks; }
local event(Hit) ShowHit(mut Ball ball)
{
ball.flash = 0.25; // A local field of the ball that was hit
}
local event(Bounced bounced) ShowBounce(mut Fx fx)
{
for (var i = 0; i < 6; i++)
fx.sparks.Add(Spark { position = bounced.at, velocity = float2(Math.Cos(i * 1.05), Math.Sin(i * 1.05)) });
}
// The ball as it was when it went, though it's gone by the frame.
local event(Destroyed) Burst(Ball ball, mut Fx fx)
{
for (var i = 0; i < 24; i++)
fx.sparks.Add(Spark { position = ball.position, velocity = float2(Math.Cos(i * 0.26), Math.Sin(i * 0.26)) * (1 + i % 3) });
}
view Arena()
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, 0.15), 2.3);
Draw.WireRect(float2(0), float2(3.8, 3.8), 0.03, Color(0.24, 0.25, 0.27));
}
view Balls(mut Ball ball, Devices devices)
{
ball.flash = Math.Max(0, ball.flash - Frame.dt);
var pointer = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position));
if (devices.pointer.press.down && Math.Distance(pointer, ball.position) < 0.45) this.Send(Poke { });
Draw.Circle(ball.position, 0.14 + ball.health * 0.07, ball.flash > 0 ? Color.white : Color(0.98, 0.75, 0.14));
}
view Sparks(mut Fx fx)
{
mut var i = 0;
while (i < fx.sparks.count)
{
mut var spark = fx.sparks[i];
spark.age += Frame.dt;
if (spark.age >= 0.5)
{
fx.sparks.RemoveAt(i);
continue;
}
spark.position += spark.velocity * Frame.dt;
fx.sparks[i] = spark;
Draw.Circle(spark.position, 0.04, Color(1, 0.9, 0.5, 1 - spark.age * 2));
i++;
}
Draw.SetScreen();
Draw.Text("Tap a ball three times", float2(16, 14), 18, Color.white);
}
```
### What they take
- **The event**, as a match handler does. One that doesn't read it leaves its name out.
- **The components of the entity the event was sent to**, to read. `mut` on one reaches only its local fields, as in a view: `fighter.flash` above. `with` and `without` filter as they do for a match handler.
- **The match's singletons**, to read. `Time` is the tick the event was sent in.
- **Local singletons**, which it changes.
- **Queries**, to go through other entities than the one the event was sent to ([below](#doc-game--events--other-entities)).
A handler that takes no components runs once per event, as a match handler does, and one that takes components needs every `Send` of its event to name an entity.
What it takes of the match is a copy from the event's turn: as the match's handlers of that event left it, and for `Destroyed`, before the entity goes. So it's all there even when the entity is gone by the frame, which is what lets `Destroyed` say where something ended:
```csharp
// Where a shot ended: its Body as it was when it went
local event(Destroyed) ShotEnded(Body body, mut Fx fx, with Bullet)
{
fx.sparks.Add(Spark { position = body.position });
}
```
An event sent to an entity that's gone by its turn isn't heard, as it isn't handled. Local fields are the entity's whether or not it's still there: what a handler writes for an entity that's gone goes with the rest of its local fields, at that frame.
Text, lists, maps, sets and grids follow the same recorded timing. The journal retains the values a handler may read, including through synchronous helpers, so later edits or destruction can't invalidate them. Unread container fields add no capture cost. A conditional read still counts as a possible read; copying a whole value reads its fields.
Match values stay read-only. You can copy a list, map, set or text into local state using ordinary assignment; grids keep their existing read-only borrowing and copying restrictions. Attached local fields continue to read and write current local state.
### Other entities
A local handler takes `query` parameters, as a [view](#doc-game--views-and-the-match--other-entities) does, to go through entities other than the one its event was sent to:
```csharp
event Blast
{
float2 at;
float radius;
}
// Every fighter the blast reached throws a spark
local event(Blast blast) ShowBlast(mut Fx fx, query (Body body, with Fighter) fighters)
{
foreach (var fighter in fighters)
{
if (Math.DistanceSq(fighter.body.position, blast.at) > blast.radius * blast.radius) continue;
fx.sparks.Add(Spark { position = fighter.body.position, velocity = float2(0, 3) });
}
}
```
- **Rows are from the tick that sent the event**, like what the handler takes of the entity the event was sent to: the match as that tick left it, whatever it is by the frame the handler runs in. They aren't blended. A handler of a [`verified`](#doc-game--events--verified-handlers) event gets the confirmed tick's.
- **They're the tick's once it's done**, after all its events and changes. An entity the tick destroyed is in no row, the one the event was sent to included, and an entity it spawned is in them. The handler's own components are still as the event's turn left them.
- **Nothing in it says `verified`**: the handler's event says which tick. Match fields, including captured text, lists, maps, sets and grids, stay read-only. Attached local fields use the entity's current local state when the handler runs. A binding such as `query (mut Fighter fighter) fighters` can write those local fields, including local containers. Local fields are never recorded in the event journal.
- **A query of this machine's entities**, `query (Spark spark) sparks`, is the local world as it is when the handler runs. It's the only kind a handler of a local event takes.
- **The entities are recorded once for a tick**, however many of its events have a handler that goes through them, and only for ticks that sent one.
### At the start of a frame
Local handlers run at the start of a frame, before the views, for each tick this machine simulated since the last frame, in order. What they spawn, change and send locally is handled at the end of the frame, like a view's, and they send [commands](#doc-game--commands) as views do. [Local state](#doc-game--local-state--a-frame-in-order) has a frame's whole order.
An event's local handlers run in the order they're declared, and `[Before]` and `[After]` order them among themselves, apart from the match's handlers of the event. An event has 64 of them at most. A local handler of an event nothing sends is a warning, like a match handler's, and `tide schedule` lists each event's local handlers after the match's (see [the schedule](#doc-game--schedule--reading-it)).
### Once, under rollback
In a match with other machines, a client predicts ticks ahead of the server, and runs some of them again when the server turns out to have had them otherwise (see [Networking](#doc-multiplayer--networking--prediction-and-rollback)). The match's handlers run again with their tick. A local handler doesn't: it hears each event once.
- An event the tick sends again as it runs again **stays silent**. It's the same event when it's of the same tick, with the same fields, sent to the same entity.
- An event **only the corrected tick has** is heard then, late.
- An event **the correction removed** isn't taken back: the spark it made has been shown.
Two events alike in one tick are two, and each is heard once. The same entity is the entity, not only its handle: when running a tick again gives a handle to another entity, an event sent to it is another event, and it's heard (see [After a rollback](#doc-game--local-state--after-a-rollback)).
### `verified` handlers
Where what's shown must not be wrong, like a death or a goal, the handler waits for the server. `verified` before the event hears it once the server has confirmed the tick that sent it:
```csharp
event Died
{
Entity killer;
}
// The spark as it's predicted, the death once it's certain
local event(verified Died) ShowDeath(Body body, mut Fx fx)
{
fx.sparks.Add(Spark { position = body.position, velocity = float2(0, 4) });
fx.shake = 0.3;
}
```
- **It's never wrong, and never taken back.** It runs once, for what the tick sent as the server ran it.
- **It's late**, by as far as this machine runs ahead of what the server has confirmed.
- **What it takes of the match is that confirmed tick's**, as the event's turn left it, so nothing else in it is marked `verified`.
- **Both kinds can hear one event**: a handler of `Hit` for the spark, at once, and one of `verified Hit` for the damage number, once it's certain.
`verified` is local code's word. On a match handler it's an error, as the match is the same on every machine and has no "confirmed". Views take it on what they read: see [Confirmed state](#doc-game--views-and-the-match--confirmed-state).
### Events only local code handles
The match can send an event no match handler takes, purely for what's shown:
```csharp
// Nothing in the match handles Impact: it's sent for whoever shows it
event Impact
{
float2 at;
float2 normal;
}
system Fly(mut Body body, Arena arena, Time time, with Bullet)
{
body.position += body.velocity * time.dt;
if (Math.Abs(body.position.x) > arena.halfSize.x)
{
Send(Impact { at = body.position, normal = float2(body.position.x > 0 ? -1 : 1, 0) });
this.Destroy();
}
}
local event(Impact impact) ShowImpact(mut Fx fx)
{
fx.sparks.Add(Spark { position = impact.at, velocity = impact.normal * 3 });
}
```
It costs the match nothing. The world's bytes, its hash, its snapshots and what's sent are what they'd be without the event, and a machine with nobody to show it to does no work for it.
### The engine's events
`Spawned`, `Destroyed`, `PlayerJoined` and `PlayerLeft` have local handlers too:
```csharp
local event(PlayerJoined joined) Greet(mut Chat chat)
{
chat.lines.Add($"{joined.player} joined");
}
// It takes a component of the match's, so it hears the match's entities
local event(Spawned) CrateLanded(Body body, with Crate)
{
Spawn(Puff { position = body.position }); // A local entity
}
```
- **`Spawned` and `Destroyed` are sent in both worlds.** A local handler of one hears the match's when it takes something of the match, a component, a filter or a singleton, or when it's `verified`. One that takes only local state hears this machine's local entities'. One that takes a local component and something of the match is an error.
- **A machine hears what's sent from the tick it joins in**: its own `PlayerJoined`, and every later one. Nothing is made up for what happened before: the hits, the joins and the entities that came and went.
- **`Shown` initializes what this machine comes to have.** It runs for newly available entities and components: those in the world when a machine joins, those revealed later, and genuine spawns. `Spawned` describes a genuine spawn in a tick; joining or receiving an existing entity doesn't make up another spawn. Initialize [local fields](#doc-game--local-state--local-fields) in `Shown`:
```csharp
asset Texture crate = "art/crate.png";
component Box
{
float3 position;
local Texture skin; // This machine's
}
// For every Box this machine comes to have: spawned in a tick, there as
// the match started, or already in the match it joined
local event(Shown) Dress(mut Box box)
{
box.skin = crate;
}
```
Keep a puff caused by a genuine spawn in `local event(Spawned)`. That effect doesn't run for crates already present when a player joins.
- **`Hidden` distinguishes concealment from destruction.** It runs with the last state this machine was permitted to know, before its local fields are discarded. It can hide a model or move presentation data into a game-owned cache. Concealing an entity doesn't invoke match destruction handlers, and destroying an already hidden entity doesn't automatically disclose its destruction.
- **Availability follows each handler's requirements.** Revealing an `Inventory` on an entity that already has a visible `Body` runs `Shown` handlers needing that inventory. It doesn't run a `Shown(Body body)` handler again. Required and excluded components both count, as they do in ordinary queries. A whole visible component includes all its fields.
- **Availability is reconciled at presentation delivery boundaries (provisional).** Transient add/remove/re-add changes coalesce to the final state. `Hidden` reads the previously delivered endpoint and its query rows, then `Shown` reads the new endpoint. Predicted and verified endpoints are tracked separately. If a correction restores something that became unavailable, `Shown` prepares it again; unchanged replay emits nothing. A local rebuild starts fresh availability history, so initialization should safely reuse or replace existing local resources.
- **These are local notifications of match availability.** Write `local event(Shown)` or `local event(Hidden)`, using match components and read-only match singletons, local fields and local singletons as other local handlers do. They can't take local-world components or change the match. `verified Shown` and `verified Hidden` wait for confirmed availability. `Forgotten` remains the resource-release hook when local fields are discarded.
- **Ticks that were skipped say nothing**: when a client's world went wrong and the server sent it again, the ticks in between were never run there. Existing entities that are newly available receive `Shown` as that world arrives; nothing a machine already had is shown again.
- **A match that changes hands** goes on from the new host's last confirmed tick (see [Host migration](#doc-multiplayer--matches--host-migration)), so the ticks after it are heard again on a machine that had heard them. The entities it had before aren't new to it, and aren't heard again.
### When a field changes
`Changed` hears a field of the match that changed over a tick, with what it was, `old`, and what it is, `value`. Nothing has to send it, and a view needn't keep the last value to compare:
```csharp
component Health
{
int value = 100;
local float flash; // This machine's
}
local event(Changed change) Hurt(Body body, mut Health health, mut Fx fx)
{
if (change.value < change.old) health.flash = 1; // It went down
fx.numbers.Add(DamageNumber { at = body.position, amount = change.old - change.value });
}
// A singleton's field: the handler runs once, and takes no components
local event(Changed change) Cheer(mut Fx fx)
{
fx.confetti = change.value - change.old;
}
```
- **A change is the tick's.** As a tick ends, after its events and changes are done, the field is compared with what it was as the tick began. Several writes in a tick are one change, from the first value to the last, and a field written back to what it was didn't change. It's compared bit for bit, as the match's hash compares it.
- **It's sent to the entity whose field changed**, which its handler takes components of, as the tick left it. A singleton's change is sent to the world.
- **Only fields that were there before and after change.** Spawning, destroying, adding or removing the component, and an entity this machine comes to have, change nothing: `Spawned`, `Destroyed`, `Shown` and `Hidden` say those.
- **The path goes through structs**: `Changed` watches one field of a struct in a component. A field of text, a list, a map, a set or a grid can't be watched; watch a count or a version kept beside it.
- **It's like any match event a local handler hears.** It's heard once under rollback, `verified` hears it once the server has confirmed the tick, and ownership filters work. With only local handlers, only the field is compared, and only on machines with a handler of it, so the match's bytes, hash and traffic are what they'd be without it.
Match code can handle a change too. What depends on a field then follows it, whatever code set it:
```csharp
singleton Workshop
{
int level;
int board; // The level the board was built for
int serial; // Moves sent before the board changed are stale
}
// Only the number is set...
void OpenLevel(mut Workshop workshop, int level) { workshop.level = level; }
// ...and the board follows it
event(Changed change) Load(mut Workshop workshop)
{
workshop.board = change.value;
workshop.serial += 1;
}
```
- **It's taken as the tick ends**, after its events and changes are done, the same tick.
- **What a handler changes makes another round.** If a handler changes a field something watches (`serial` above, if a handler watched it), that change is sent in a round of its own, the same tick, with what it was after the round before as `old`. Rounds go on until one finds nothing changed. Handlers that keep changing each other's fields stop the program, as any endless chain of events does.
- Every machine compares the fields match code watches on every tick, so the match comes out the same on all of them.
### Ownership filters
Use `with ownership` or `without ownership` as in a view:
```csharp
// Only this machine's own fighter shakes the screen.
local event(Hit) Shake(mut Fx fx, with ownership)
{
fx.shake = 0.2;
}
```
The filter uses the owner recorded at the event's turn, after its match handlers ran. Transferring ownership later, removing `Owner` or destroying the entity before the next frame doesn't redirect the event. No `Owner` or `Session` parameter is needed. `without ownership` includes other players' entities and entities with no permitted `Owner`; `with Owner, without ownership` additionally requires that component.
The same filters work on `verified` handlers, using their confirmed recording. Ordinary predicted events retain their once-under-replay rule, including when a correction changes only the captured ownership. `Shown` and `Hidden` use their respective delivered endpoints: gaining or losing ownership changes availability for an ownership-filtered handler. A filter alone targets an entity and makes a `Spawned` or `Destroyed` handler hear the match's events. Local-world events, `Forgotten` and query row filters don't accept ownership.
### What isn't there yet
- **Container capture follows possible reads**, including through helpers and borrowed queries. Unread container fields are omitted; explicit whole-value copies read their fields. Captured event-payload containers contribute their contents to replay occurrence identity. Local fields use current local state.
- **The `World`**, which is the match as it is now and not as the event left it. Nor `Devices` or the input.
- **`async`.** A local handler of one of the match's events starts a [task](#doc-game--tasks) instead, by calling an async function with what the task needs.
- **`verified` components beside a predicted event.** A handler that hears a tick as it's predicted takes the match as that tick left it.
Local state has events of its own too, `local event`, sent and handled on one machine: see [Local state](#doc-game--local-state--local-scenes-and-events).
---
Source: https://tide-engine.dev/game/commands.md
Send player actions to a Tide multiplayer match with commands, validate their payloads and control delivery, ticks and ordering channels.
# Commands
A command is an action a player sends into the match: submit a name, choose a team, equip an item, or press a ready button. Declare its payload like an event:
```csharp
command Rename
{
string name;
}
```
## Sending
Views send commands with `entity.Send(...)`, or `Send(...)` for an action on the whole match. The text field and other UI state stay local until the player submits them:
```csharp
component Name { string value; }
local singleton RenameUI { string draft; }
view RenameMenu(Name name, mut RenameUI ui, with ownership)
{
GUILayout.Label(name.value);
GUILayout.TextField("Name", ui.draft);
if (GUILayout.Button("Rename"))
this.Send(Rename { name = ui.draft });
}
```
The engine copies the payload when it is sent, so editing the field afterwards does not change the queued command. Sending is available while connected to a match. Single-player uses the same queue and handler as multiplayer.
## Handling
Declare a handler with `command`, like an event handler. Its first parentheses hold the payload and the sender; the second describe the components and singletons it uses:
```csharp
command(Rename rename, PlayerID sender) RenamePlayer(
Owner owner, mut Name name)
{
if (sender != owner.player) return;
if (rename.name.length == 0 || rename.name.length > 32) return;
name.value = rename.name;
}
```
The engine supplies `sender` from the player's connection. It is not a field that the player sends. `Owner` identifies the target's owner; targeting an entity does not grant permission to change it.
### Only the sender's own entities
Most handlers that take a target begin by checking that the sender owns it. `with ownership` says that in the signature, and the guard and the `Owner` parameter go:
```csharp
command(Rename rename) RenamePlayer(mut Name name, with ownership)
{
if (rename.name.length == 0 || rename.name.length > 32) return;
name.value = rename.name;
}
```
The handler runs only when the entity the command was sent to has an `Owner` whose `player` is the command's sender. A command sent for any other entity is dropped, as the guard dropped it: it counts as handled, a resend of it is refused, and nothing changes. `without ownership` is the other side, any entity the sender doesn't own, another player's or nobody's, for something like an attack:
```csharp
command(Steal steal, PlayerID sender) Take(mut Purse purse, without ownership)
{
purse.coins -= steal.amount;
}
```
It's the word a [view](#doc-game--views-and-the-match) filters with, where it means this machine's player; in a command handler, the player is the one who sent the command. A handler that filters this way can leave its sender out of the first parentheses, or name it to read it. One that does neither is an error: a command handler names the player who sent it, so it can check what that player may do. Systems and event handlers can't filter by ownership: nothing there is a player's, so write `with Owner` for entities any player owns.
Below are two machines in one match, each with a badge its player owns. Click the name's field in a frame, type one, and press **Rename my badge**: the command goes to the server, which picks its tick, and both machines run the handler. **Rename theirs** sends the same command for the other player's badge. Nothing stops a machine from sending it, so the handler looks at who did, refuses, and counts.
**A command, and a handler that says no** ([Run example](https://tide-engine.dev/examples/commands/?stats))
```tide
settings { title = "Commands"; tickRate = 30; maxPlayers = 4; }
scene Main { }
component Badge
{
string name = "Player";
int seat;
}
singleton Roster
{
Map badges;
int arrivals;
int refused;
}
// An action a player submits. It holds what the player says, never who they are.
command Rename { string name; }
event(PlayerJoined joined) Arrive(mut Roster roster)
{
roster.badges[joined.player] = Spawn(Badge { seat = roster.arrivals % 2 }, Owner { player = joined.player });
roster.arrivals += 1;
}
event(PlayerLeft left) Depart(mut Roster roster)
{
roster.badges[left.player].Destroy();
roster.badges.Remove(left.player);
}
// The badge is the one the command was sent to, and `sender` comes from the
// player's connection. Being sent a badge isn't permission to change it.
command(Rename rename, PlayerID sender) RenameBadge(Owner owner, mut Badge badge, mut Roster roster)
{
if (sender != owner.player)
{
roster.refused += 1;
return;
}
if (rename.name.length == 0 || rename.name.length > 12) return;
badge.name = rename.name;
}
// What's typed stays on this machine until it's sent.
local singleton Draft { string name = "Ada"; }
float2 Seat(int seat)
{
return float2(Screen.width * (0.27 + seat * 0.46), 190);
}
view Backdrop(Roster roster)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetScreen();
GUI.SetTheme(GUITheme { radius = 6 }); // For the views after this one too
Draw.Text($"Commands the match refused: {roster.refused}", float2(16, Screen.height - 30), 14, Color(0.64, 0.64, 0.68));
}
view Mine(Badge badge, mut Draft draft, with ownership)
{
var at = Seat(badge.seat);
Draw.RoundRect(at, float2(150, 64), 12, Color(0.36, 0.26, 0.04));
Draw.WireRoundRect(at, float2(150, 64), 12, 2, Color.white);
Draw.Text(badge.name, at, 20, Color.white, Anchor.MiddleCenter);
Draw.Text("yours", at + float2(0, 48), 13, Color(0.64, 0.64, 0.68), Anchor.MiddleCenter);
GUI.TextField(Rect(12, 12, Screen.width - 24, 32), "Name", draft.name);
if (GUI.Button(Rect(12, 52, Screen.width - 24, 32), "Rename my badge")) this.Send(Rename { name = draft.name });
}
view Theirs(Badge badge, without ownership)
{
var at = Seat(badge.seat);
Draw.RoundRect(at, float2(150, 64), 12, Color(0.2, 0.2, 0.23));
Draw.Text(badge.name, at, 20, Color.white, Anchor.MiddleCenter);
// Nothing stops a machine from sending this. The handler does.
if (GUI.Button(Rect(at.x - 75, at.y + 42, 150, 30), "Rename theirs")) this.Send(Rename { name = "Mine now" });
}
```
A handler is void. Guard clauses end processing, and writes take effect normally, just as in a system or event handler. There is no acceptance call, return status, or transaction that undoes earlier changes. Each command can have at most one handler. The handler can send ordinary events when other parts of the game should react.
Components and `this` refer to the target entity, as in an event handler. A handler that takes components, or [filters by ownership](#doc-game--commands--only-the-sender-s-own-entities), runs for the entity the command is sent to, and the compiler requires an entity target for it. A handler with neither runs once for the command. A target that no longer exists, or no longer matches the handler, has no effect.
Synchronous command handlers also take read-only `query` parameters, using the same [query rules as match events](#doc-game--events--querying-other-entities). A query selects a separate set of entities, so a handler taking only queries and singletons requires no entity target. It reads the current match at the command's turn in the tick-end queue; recorded events and structural changes remain deferred. Check the authenticated sender's permissions before acting on queried entities, as with any command target.
## Delivery and ticks
Commands are queued independently of input. Multiple submissions between ticks remain separate commands, and a late command is not lost because its original input tick passed. The engine resends pending commands and identifies duplicates by a per-player sequence.
The server chooses the tick and order. Handlers run at the end of that tick with the existing event and structural-change queue. Each handler sees the changes made by the commands handled before it. Full-world games send recorded commands with tick history so every machine replays that order. With [state visibility](#doc-game--visibility), command handlers execute only on the authoritative server; clients receive their permitted state consequences rather than raw command targets or payloads.
Sequence state belongs to the world: snapshots, state hashes and host migration include it. A received command occupies one entry in the authoritative timeline, but its handler can run again during rollback. External side effects must account for replay, as in any simulation code that calls C.
## Ordering: channels
A player's commands are handled in the order they were sent, each after every earlier one: the server holds a command back until the one before it has arrived. That's right for most actions, and wrong for a big one: a chat line sent after a file would wait until the file had been uploaded.
A command's ordering is its type's. Without an attribute, a command is in the **default channel**, in order with every other command of that channel. `[Channel(...)]` with an enum member of the game's puts it in a channel of its own: in order among that channel's commands, and in no order against the others, so a chat line never waits behind an upload. `[Unordered]` gives a command no order at all: the server handles it in whichever tick it arrives, before or after commands sent earlier, still exactly once.
```csharp
enum Channels { Uploads }
command Say { string text; } // The default channel
[Channel(Channels.Uploads)]
command SetBackground { List png; } // Its own: a Say never waits for one
[Unordered]
command Ping { int at; } // Whenever it arrives, once
```
Whatever the ordering, the server picks the tick and every handler runs in the tick's end queue, in the server's order: a channel only decides what the server holds back waiting for an earlier command. Commands can share a channel, and a channel's name can come from any enum. Each channel has a sequence of its own in the world, and an unordered command has an id of its own, which the world keeps a window of the last 64 of, per player, to drop a resend. The 32 pending commands per player are per channel, so a full channel holds back only its own.
## Big commands
A command holds a `List` too, so a player's file goes into the match as it is: an image's bytes, a text's, any file's, for a handler to keep in a component or decode. Such a command is 4 MiB at most. One that doesn't fit a datagram goes as a numbered transfer in chunks, the way worlds go, resent until acknowledged and paced under the input traffic (16 KB an update, about a megabyte a second), so a transfer never delays a tick. It lands in a later tick, as any command may.
A command holds lists of other values as well: numbers, bools, enums, vectors, entity or player IDs, and structs of those, in a field or in a struct the command holds.
```csharp
struct Slot { [Clamp(0, 9)] int level; float weight = 1; }
command Enlist
{
[Clamp(0, 20)] List attributes; // Each element is bounded
List slots;
}
```
Each element goes on the wire as a field of its type would, after the list's count, and is checked the same way: a float that isn't finite becomes the element type's default, an enum value no member has becomes its default, and `[Clamp]`, `[Min]` and `[Max]` bound each element, on the list or on a struct's fields. A command with a list follows the same rules as one with a `List`: 4 MiB at most, sent in chunks when it doesn't fit a datagram. A list of text or of other lists can't be sent: send text in string fields or a fixed `string[N]`, or its bytes as a `List`. Commands can't hold maps, sets or grids; a map's keys and values can go as two lists.
In full-world games, the server distributes a big command to every player before scheduling it, so no player's tick waits for its download; later joiners receive the resulting world. Visibility-enabled games keep that upload server-side and replicate only permitted state consequences. A few megabytes is fine; larger public media can be a URL fetched by each machine. Put a big command in a channel of its own, or make it unordered, so nothing waits behind it.
## Untrusted payloads
The engine checks payload structure and size, UTF-8, numeric values and declared bounds before match code sees the fields. A command holds numbers, bools, enums, vectors, entity or player IDs, strings, `List`, lists of those but strings, and structs of those; it does not hold lists of text or lists, maps, sets, grids, components or device records.
The initial limits are 1024 packed bytes per command (4 MiB for one with a list), 32 pending commands per player in each channel, and 16 commands scheduled per authoritative tick. The packed limit includes the command type, target and string bytes. Incoming queues are bounded before allocation. A full session queue leaves local submissions of that channel waiting for capacity. Sending a payload larger than the packed limit, or filling a channel's local submission queue, is a programming error that stops the program with a diagnostic.
Starting or leaving a match clears its pending submissions. Host migration preserves them. A hot reload that changes the game's data layout clears pending packed commands, because the new build can give their types a different wire layout.
Those checks establish well-formed data. The handler checks permissions, allowed choices, affordability, cooldowns and any other rules of the game. A valid name, item ID or target is not permission to act on it.
Use [input](#doc-game--input) for state sampled each tick, commands for submitted actions, and [events](#doc-game--events) for notifications produced inside the simulation.
---
Source: https://tide-engine.dev/game/assets.md
Import images, audio and glTF, FBX or OBJ models as Tide assets. See supported formats and their limits, then load files or fetch URLs while the game runs.
# Assets
[Dedicated server builds](#doc-tools--cli--dedicated-servers) can omit assets used
only by views and other client code. Assets reached by simulation helpers,
defaults and dynamic match asset references remain available. Server and client
retain the same match identity even when their packs differ. Projects with
custom C retain assets conservatively unless explicitly opting into pruning.
An asset is a file a game is built with: an image, a model, a text, some bytes. The language names it, the compiler checks it, and the build packs what's named and nothing else. The second half of this page covers what a machine loads while the game runs instead: a file of the player's, or a URL, which is local to that machine until the match is told about it.
`tide build` and `tide run` reuse expensive imports between launches from
`.tide/assets/imports`: static/skinned models and animations, generated tangents,
audio validation/conversion, and prepared texture pixels or mip blocks. Unchanged
draw-only textures can skip image decoding too. The cache is keyed by source
contents, external model buffers, import options and importer/decoder revision;
editing code, or updating to a Tide whose importers are unchanged, keeps it
useful. Entries unused for 30 days, and other Tide versions' results after 14
days, are removed. Each build still discovers glob matches and
packs the current declarations and vertex layouts. Grid images keep their exact
CPU-readable decoder path. Cache files are disposable: missing, incompatible or
damaged entries fall back to the ordinary import, and an unwritable cache does
not prevent a build.
## Supported formats
| Asset | Build-time source formats | What reaches the game |
| --- | --- | --- |
| `Texture`, `Grid2`, cubemap faces | PNG, PSD, JPEG (`.jpg`, `.jpeg`), TGA, BMP, [RGBA8 DDS](#doc-game--assets--authored-mipmaps) | Decoded pixels; textures and cube faces use RGBA8 |
| `Mesh` | glTF 2.0 (`.gltf`, `.glb`), binary or ASCII FBX, OBJ | Static vertices and triangles |
| `SkinnedMesh` | glTF 2.0, binary or ASCII FBX | Geometry, skeleton and animation; see [Animation](#doc-game--animation) |
| `AnimationCatalog` | glTF 2.0 (`.gltf`, `.glb`), binary or ASCII FBX | Skeleton and every animation clip; see [Animation files](#doc-game--animation--animation-files) |
| `Animation` | glTF 2.0 (`.gltf`, `.glb`), binary or ASCII FBX | The only clip, or an exact `[Name("source name")]` selection |
| `Clip` | WAV, Ogg Vorbis, MP3, FLAC | WAV/Vorbis bytes, or float PCM WAV converted from MP3/FLAC; see [Audio](#doc-game--audio--clips) |
| `Font` | TrueType fonts: `.ttf`, an `.otf` of TrueType outlines, a `.ttc`'s first font | Its glyphs' outlines, checked; see [Fonts](#doc-game--views--fonts) |
| `string` | Any UTF-8 text file | Text |
| `List` | Any file | Its original bytes |
These are source imports. Runtime [`grid.Decode`](#doc-game--assets--decoding-a-png) reads PNG only, runtime [`Mesh.Decode`](#doc-game--assets--meshes) reads GLB, a glTF with its buffers inside it and OBJ, runtime [`SkinnedMesh.Decode`](#doc-game--animation--load-while-playing) reads self-contained GLB only, and runtime [`Font.Decode`](#doc-game--views--fonts) reads what a `Font` asset does. `AnimationCatalog` has no runtime `Decode` operation. A supported extension doesn't imply every feature of that format: the image and model limits below say what is read.
WebP, TIFF, animated images, SVG, HDR/EXR, compressed DDS and KTX/KTX2 aren't image imports yet. USD, Collada (`.dae`), Alembic, STL, PLY and Blender project files aren't model imports; export a model as glTF 2.0 or FBX, or OBJ for static geometry. Model materials and their textures still need separate declarations and draws.
Fonts of CFF (PostScript) outlines, which many `.otf` files have, aren't read: convert one to `.ttf`. Video playback isn't built. Any file can still be packed as `List`, which preserves its bytes without interpreting them.
## Declaring an asset
`asset` declares a file's contents under a name, at the top of a file like a constant. The type is what the file is read as:
```csharp
asset Grid2 hero = "art/hero.png"; // An image, decoded as the game is built: cells code reads
asset Texture tiles = "art/tiles.psd"; // An image that's only drawn
asset string rules = "rules.txt"; // UTF-8 text
asset List table = "data/table.bin"; // Any file, as its bytes
```
Code reads `hero` wherever it reads a `Grid2`: a system indexes its cells, a view draws it as a texture with `Draw.Mesh`, and a frag samples it by name, `hero.Sample(uv)`, as it samples a singleton's grid. Those four are the plain ones: `string`, `List`, `Grid2` and `Texture`. A sky is a [`Cubemap`](#doc-game--assets--cubemaps), a static model a [`Mesh`](#doc-game--assets--meshes), a model with bones a [`SkinnedMesh`](#doc-game--animation), animation clips an [`AnimationCatalog`](#doc-game--animation--animation-files) asset, a sound a [`Clip`](#doc-game--audio--clips), and a font a [`Font`](#doc-game--views--fonts).
**A sprite from a file** ([Run example](https://tide-engine.dev/examples/assets/?stats))
```tide
settings { title = "A sprite from a file"; maxPlayers = 1; }
// The file is read as the game is built and packed with it: every machine has
// the same pixels, so match code can read them too.
asset Grid2 sprite = "art/sprite.png";
component Bouncer
{
float2 position;
float2 velocity;
}
singleton Arena { float2 half = float2(5, 4); }
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Bouncer { position = float2(-2, 1), velocity = float2(3, 2) });
Spawn(Bouncer { position = float2(2, -1), velocity = float2(-2, 3) });
}
// The match reads the sprite like any grid: here its size, to bounce by its edges.
system Move(mut Bouncer bouncer, Arena arena, Time time)
{
var extent = float2(sprite.size.x, sprite.size.y) / 24 * 0.5;
bouncer.position += bouncer.velocity * time.dt;
if (bouncer.position.x < -arena.half.x + extent.x || bouncer.position.x > arena.half.x - extent.x) bouncer.velocity.x = -bouncer.velocity.x;
if (bouncer.position.y < -arena.half.y + extent.y || bouncer.position.y > arena.half.y - extent.y) bouncer.velocity.y = -bouncer.velocity.y;
}
view Background(Arena arena)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0), arena.half.y * 2);
Draw.WireRect(float2(0), arena.half * 2, Color(0.24, 0.25, 0.27));
}
// A view draws it as a texture, point-sampled so its pixels stay crisp.
view Sprites(Bouncer bouncer)
{
var p = bouncer.position;
var h = 0.5;
Draw.Mesh([Vertex { position = p + float2(-h, h), uv = float2(0, 0), color = Color.white },
Vertex { position = p + float2(h, h), uv = float2(1, 0), color = Color.white },
Vertex { position = p + float2(h, -h), uv = float2(1, 1), color = Color.white },
Vertex { position = p + float2(-h, -h), uv = float2(0, 1), color = Color.white }],
[0, 1, 2, 0, 2, 3], sprite, Filter.Point);
}
```
An asset is read-only. Nothing assigns it, takes it `mut`, or clears it: it's the file as the game was built, the same on every machine. To change pixels, keep a `Grid2` field of your own and copy cells in.
Match code reads assets like any value, since every machine has the same pack; a `Texture` is the one that's local code's alone (below). What a machine loads as the game runs is another matter, further down.
### Release builds
A standalone `tide build --release` or `--distribution` omits asset declarations that no checked Tide code, default or shader references. An asset named in a helper or a type's default stays, even if that helper or type is unused. A referenced list or map keeps every file its path matches. Every declaration is still checked, so an unused asset with a missing or invalid file remains a build error.
Debug and hot-reload builds keep every declared asset. So do games or packages with C/C++ sources or prebuilt libraries, and games with a custom C host: their C code may read assets through the generated API or by name in the pack.
A web distribution also compresses the retained pack inside its self-contained page when that saves space. The page decodes the same packed bytes before the game starts; the asset values and match results stay the same.
### A field's default
A field's default can name an asset, as it names a constant:
```csharp
asset Texture logo = "art/logo.png";
asset string motto = "motto.txt";
asset List table = "data/table.bin";
struct Sprite
{
Texture image = logo;
Color tint = Color.white;
}
component Sign
{
string text = motto; // The match's own copy of the text
int size = table.count; // An expression can read one
local Texture face = logo; // This machine's, as every Texture is
local Sprite art; // Its image starts as the logo too
}
```
- The field gets the asset's value where the default is given: as an entity is spawned, as a match or this machine's local state starts, and for an entity's [local fields](#doc-game--local-state) nothing wrote yet.
- Text, bytes and a glob's list or map become independent field values: changing one changes neither the asset nor another field. Asset-backed lists can share immutable bytes until the first write, when that value detaches into owned storage. A field keeps the value it was assigned across asset reloads.
- A `Texture`, a [`Clip`](#doc-game--audio--clips) and a `Cubemap` name their asset, so they cost nothing to give, and under `tide run` a saved file shows through them.
- A `Grid2` field can't start as an asset's grid, since a grid is never copied: read the asset's by its name, or give an ordinary color grid to a `Texture` field, `Texture face = hero;`. A numeric `[Raw]` grid uses a [Raw texture field](#doc-game--shaders--textures-that-are-numbers).
- One of a glob's, like `run[0]` or `icons["art/icons/star.png"]`, isn't a default yet: a view assigns it.
- Only a field's default takes one. A `const`, a setting, an attribute's bound, an asset's path and a parameter's default are constants alone, as the compiler works those out while it builds.
## Images to draw with
For color images used by lighting, declare `[Linear] asset Texture albedo = "art/albedo.png";`.
The same mark works on a singular `TextureArray` or `Cubemap` asset. GPU reads then return
linear light, with filtering and mipmaps in that space, while alpha stays unchanged.
Unmarked images keep their existing display-number behavior. A glob's `List` or
`Map` takes the mark for every image it holds, each packed for that reading;
`[Linear]` does not go on a CPU-readable grid or a glob of grids. See
[Linear-light color](#doc-game--shaders--linear-light-color) for fields, parameters and helper functions.
`[Raw, Linear]` is refused; `[Linear, Lossless]` keeps a color image uncompressed.
Marked DDS images rebuild their mip chain from the base image in linear light, so authored
levels with an unknown filtering space cannot silently produce display-space mipmaps.
Compression still uses BC1/BC3, through their sRGB forms on devices that support them.
A device without BC receives the same mip chain decoded to sRGB RGBA8.
Most of a game's images are only ever drawn: sprites, tile sheets, backgrounds, icons. Those are `Texture`s:
```csharp
asset Texture hero = "art/hero.png";
asset List run = "art/run/*.png";
asset Map icons = "art/icons/*.png";
local singleton Player
{
int frame;
Texture badge; // Whichever image it's given
}
view Show(mut Player player)
{
Draw.Mesh(corners, faces, hero);
Draw.Mesh(corners, faces, run[player.frame % run.count], Filter.Point);
player.badge = icons["art/icons/star.png"];
Draw.Mesh(small, faces, player.badge);
}
```
- An ordinary color `Texture` is a value (see [A Texture is a value](#doc-game--meshes-and-textures--a-texture-is-a-value)): a draw's texture in 2D and 3D, the source a [frag's `Texture` parameter](#doc-game--shaders--textures) is given, a [`Draw.Blit`](#doc-game--render-targets--post-processing)'s source, something a field or a local holds and a function takes. A frag samples one by its name too: `hero.Sample(uv)`. Numeric Raw sources follow the field rules below.
- Its RGBA pixels keep a byte per channel: a quarter of what the same image takes as a `Grid2`. Eligible color images use a smaller compressed image instead, described below.
- `texture.size` reads its base-level dimensions as an `int2`, without uploading pixels. An image whose pixels the game needs is a `Grid2`, which draws as a `Texture` too, and one file can be declared both ways.
- It's this machine's, like everything that's drawn: views, local handlers and frags use it, and match code can't name one. The match reads a `Grid2`.
- What a field keeps of `hero` or of `run[2]` is that image as the files have it now: under `tide run`, a saved picture shows through the copies a game kept, as it does through `hero` itself.
- How it's sampled can be said once, on its declaration: `[Filter(Filter.Point), Wrap(Wrap.Repeat)]` before the asset (see [Saying it once, on the texture](#doc-game--meshes-and-textures--saying-it-once-on-the-texture)). The `Texture` carries it: what a field keeps of `hero` is sampled as `hero` is.
For numeric images, declare `[Raw] asset Texture masks = "art/masks.png";` and retain it in a `[Raw] Texture` field, or sample the asset by name in a shader. A folder of them is a glob's `[Raw] asset List normals = "art/normals/*.png";` (or a `Map`), each image kept as numbers and each element a Raw image. Raw images preserve all channels and stay out of ordinary color draws and `Texture` values. See [Textures that are numbers](#doc-game--shaders--textures-that-are-numbers) for field assignments, parameters and GPU helper forwarding.
### GPU compression
`Texture` assets are compressed automatically during the build when both dimensions are powers of two and at least 128 pixels: color images and [`[Raw]` images of numbers](#doc-game--shaders--textures-that-are-numbers) alike, such as normal, roughness and mask maps. Opaque images use BC1; images with transparency use BC3. This includes images in asset lists and maps. Compression is lossy, so sampled values can differ slightly from the source, especially around sharp changes or faint transparency. A Raw image's channels are compressed as the file has them, never multiplied by its alpha.
A full mip chain takes roughly one eighth of RGBA's bytes for BC1, or one quarter for BC3, and the pack keeps only the compressed image: a 4096 by 4096 picture is 11 or 22 MB rather than 64 MB of RGBA. Mips are prepared during the build; `Filter.Trilinear` reads them, while Point and Bilinear retain their existing sampling behavior. Vulkan uses BC where the device has it, and WebGPU uses its optional BC feature. A device without any of those (most phones) decodes every mip to RGBA as it uploads the image, preserving the prepared distant levels. That fallback uses the memory of a full RGBA mip chain.
Small images, non-power-of-two images, cubemaps, grids and render targets keep their current representation. Images that come out the same bytes are one image in the pack and on the GPU, whichever declarations name them: the same opaque file declared with and without `[Raw]`, or two copies of one picture.
`[Lossless]` keeps an image exact, a byte per channel, for numbers that must not move: a lookup table, a flow map, an ID mask. It goes before a `Texture` asset, alone or a glob's list or map, or a `TextureArray` asset, and beside `[Raw]` too:
```csharp
[Raw, Lossless] asset Texture flow = "art/flow.png"; // Every byte as the file has it
```
A lossless image costs its full RGBA in the pack, 64 MB for 4096 by 4096, and on the GPU a third more for the mips a `Filter.Trilinear` draw makes as it first reads it.
To see what each asset costs, build with `--asset-sizes` (see [the CLI](#doc-tools--cli--asset-sizes)): a line for each declaration, biggest first, with how its images are kept.
The renderer keeps recently hidden pack images in a bounded GPU cache, avoiding another upload when they return soon. This is whole-image residency; mip streaming and virtual textures aren't built yet.
### Authored mipmaps
For cutout leaves and distant sprites, ordinary averaging can make thin shapes disappear when an alpha test rejects their smaller mipmaps. Prepare a mip chain whose alpha preserves coverage at the material's exact cutoff, then import it as an ordinary texture:
```csharp
[Filter(Filter.Trilinear)]
asset Texture leaves = "art/leaves.dds";
[Raw, Filter(Filter.Trilinear)]
asset Texture normals = "art/leaf-normal.dds";
```
The DDS must contain one tightly packed, uncompressed RGBA8 or BGRA8 2D image, with power-of-two sides from 4 through 16,384 and every mip through 1 × 1. Use the legacy DDS header with explicit RGB and alpha channel masks. DX10 headers, BC-compressed data, cubes, arrays, volumes, padded rows, missing mips and extra payloads are rejected. Source bytes and decoded pixels plus retained mips each have a 512 MiB import budget.
Supply straight RGBA color pixels. The importer premultiplies RGB by alpha separately at every mip; `[Raw]` retains all channels independently. It preserves the supplied mip pixels without recompressing them. The pack and GPU hold the full RGBA8 chain, roughly a third larger than the base image. `Grid2` and cubemap declarations read only the DDS base image. Runtime `grid.Decode` remains PNG-only.
Vulkan and WebGPU preserve the chain. Unity's draw recorder currently retains only the base image and does not preserve authored mipmaps. Alpha coverage also becomes approximate at tiny mips because a handful of texels cannot represent every area fraction; atlas authors should preserve each view separately and supply suitable gutters.
### Image formats
PNG supports its standard color types and bit depths, palette/key transparency and Adam7 interlacing. PNG metadata, color profiles and gamma aren't applied; an APNG supplies its default image, without animation. PSD retains the saved composite described below. All image formats have a maximum of 16,384 pixels per side.
JPEG, TGA and BMP are decoded during the build, through the same `Texture`, `Grid2` and cubemap declarations. Only their pixels enter the pack, so the game needs none of these source decoders. JPEG is lossy and has no alpha; use PNG, PSD or TGA for transparent art. Imported textures keep eight bits per channel, including when the source has more. Color profiles and JPEG EXIF orientation aren't applied; export sRGB pixels in the intended orientation.
| Format | Accepted variants |
| --- | --- |
| JPEG | 8-bit baseline/sequential or progressive, grayscale, RGB/YCbCr or Adobe-marked CMYK/YCCK converted to RGB; no arithmetic coding or 12-bit channels |
| TGA | Non-interleaved raw/RLE RGB, grayscale or indexed images, with either vertical/horizontal origin; use 32-bit RGBA for pixel alpha |
| BMP | 1/4/8/16/24/32-bit uncompressed pixels or RGB bitfields; no RLE or embedded JPEG/PNG |
JPEG/TGA/BMP source data and combined decoder/output allocations are bounded to 512 MiB. Larger images get an error asking for smaller dimensions. A progressive JPEG has at most 256 scans: each one decodes the whole picture again, so a small file of thousands of scans would take minutes to build. These limits, and the Photoshop and FBX ones below, are provisional.
### Photoshop images
PSD import needs no Photoshop installation, including when CI builds the game:
```csharp
asset Texture portrait = "art/portrait.psd";
asset Grid2 mask = "art/mask.psd";
asset List portraits = "art/portraits/*.psd";
```
Tide reads the composite image saved in the PSD: the visible layers combined into one picture. Save with Photoshop's **Maximize Compatibility** enabled so the file includes it. Tide doesn't read individual layers or render their effects, text or smart objects itself; their saved appearance is in that composite.
The file must be an ordinary PSD (version 1) in RGB mode, with 8 or 16 bits per channel and at most 16,384 pixels per side. Uncompressed, RLE, ZIP and ZIP with prediction are supported. PSB files, other color modes such as CMYK, and 32-bit channels are errors at the asset's path, as is a missing or damaged composite. A `Texture` keeps a byte per channel, while a `Grid2` keeps each decoded channel as a float. Color profiles aren't applied; save RGB art as sRGB for matching display colors.
A PSD is at most 16384 pixels a side and 8192 × 8192 in all.
Only the decoded pixels are packed, as with a PNG. The game needs no Photoshop files or decoder when it runs. [`grid.Decode(bytes)`](#doc-game--assets--decoding-a-png) still reads PNG only.
## Texture arrays
Images of one size, read by a uv and a layer (see [Texture arrays](#doc-game--shaders--texture-arrays)), are a `TextureArray`: a glob's files, in their paths' order, or a list of paths in its own, each a file or a glob:
```tide
asset TextureArray ground = "art/ground/*.png";
asset TextureArray picked = ["art/grass.png", "art/rock.png"];
```
Every image is the same size, 256 at the most. `[Filter]` and `[Wrap]` say how a `Sample` that says neither reads it.
## Cubemaps
A sky or a room's surroundings is six images, the faces of a cube, which a frag reads by a direction (see [Skybox and reflections](#doc-game--shaders--skybox-and-reflections)). That's a `Cubemap`, and its path is a glob that matches the six files:
```csharp
asset Cubemap sky = "art/sky_??.png";
```
- **Each file is named for its face** by how its name ends before the extension: `px` and `nx` are the faces `+x` and `-x` point at, `py` and `ny` the ones above and below, `pz` and `nz` the ones ahead and behind. `sky_px.png`, `px.png` and `dusk-PX.png` are all the first.
- **Each is a face as it's seen from the cube's middle,** the way a picture is: `+y` is up for the four around, with `+x` to the right of `+z`. The one above has `-z` at its top, and the one below `+z`.
- Each uses a supported image format, is square, and all six are one size. A file that's none of the six, a face that's missing or there twice, and a size that differs are errors at the path, which name the file.
- A file is in the pack once, as any is: a face that's also an `asset Texture` shares its pixels.
- It's a value, like a `Texture`: a field or a local holds one, a function takes one, and a frag samples one by its name, `sky.Sample(direction)`. It's this machine's, so match code can't name one.
- No list or map of cubes yet, and no `[Filter]` on one: a cube's filter is said where it's sampled.
## Meshes
To keep a static model selection in a component, use a checked asset reference:
```csharp
asset Mesh rock = "art/rock.glb";
component Model { Asset> model = rock; }
view Render(Model model, World world)
{
Draw.Mesh(model.model.Value, world.LocalToWorld(this));
}
```
Assign a matching singular asset name in code or a prefab override. `.Value`
reads the currently loaded mesh; the stored reference survives geometry reloads
and world snapshots. `default` reads an empty mesh. The compiler rejects missing
assets and mismatched vertex types. A borrowed mesh variable or a collection
element cannot become a persistent reference in this first version.
Use `==` and `!=` to compare references of the same mesh type, including aliases:
`model.model == rock` or `model.model != default`. Equality identifies the named
declaration, so reloading its geometry preserves equality; two declarations
naming identical files remain different. References have no ordering or public
numeric identity.
The same reference rules support `Asset>`, including transparent
type aliases. Its `.Value` preserves the packed model's skinning palette and LOD
paths; persistent model assignment still uses ordinary owned value semantics.
See [Skinned meshes and animation](#doc-game--animation) for an example.
A model an artist made, or one a tool generated, is a mesh file: glTF (a `.glb`, or a `.gltf` with its buffers), FBX (`.fbx`, binary or ASCII) or a Wavefront `.obj`. `asset Mesh` declares one as vertices of a struct of yours, `V`, which the file fills by its fields' names:
```csharp
struct Corner
{
float3 position;
float3 normal;
Color color = Color.white;
}
asset Mesh tree = "art/tree.glb";
asset List> rocks = "art/rocks/*.glb"; // In order of their paths
asset Map> props = "art/props/*.glb"; // By them: props["art/props/bench.glb"]
frag Look(Corner corner, out Color color, Instance instance, Sun sun)
{
color = corner.color * Math.Max(Math.Dot(instance.Normal(corner.normal), -sun.direction), 0.2);
color.a = 1;
}
view Trees(Tree at)
{
Draw.Mesh(tree, float4x4.Translate(at.position), Look);
}
```
The rocket below is a `.glb` as a modelling tool exports one: five meshes with a material's color each, placed by the file's nodes, and no normals. Here it's one mesh, and a frag lights it from the normal each triangle was given.
**A model from a file** ([Run example](https://tide-engine.dev/examples/model/?stats))
```tide
settings { title = "A model from a file"; }
local scene Main { }
// What the file fills, by these names: where each corner is, which way its
// face looks, and the color of the part it's in.
struct Corner
{
float3 position;
float3 normal;
Color color;
}
// A glTF: five meshes in it, a color each, placed by its nodes. Here it's one mesh.
asset Mesh rocket = "art/rocket.glb";
local singleton Stand
{
float turn = 2.4;
float lightAngle = 0.8;
bool spin = true;
}
// The engine has no lighting, so this is ours: the file's normal against a light.
frag Lit(Corner corner, out Color color, Instance instance, Stand stand)
{
float3 normal = instance.Normal(corner.normal);
float3 toLight = Math.Normalize(float3(Math.Cos(stand.lightAngle), 0.6, -Math.Sin(stand.lightAngle)));
color = corner.color * (0.25 + 0.75 * Math.Max(Math.Dot(normal, toLight), 0));
color.a = 1;
}
view Show(mut Stand stand)
{
if (stand.spin) stand.turn += Math.Min(Frame.dt, 0.05) * 0.6;
if (stand.turn > Math.TAU) stand.turn -= Math.TAU;
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float3(0, 0.7, -7), quaternion.identity, 45);
var turned = quaternion.AxisAngle(float3(0, 1, 0), stand.turn);
// The mesh where its vertices and its indices would go
Draw.Mesh(rocket, float4x4.TRS(float3(0, 1.2, 0), turned, float3(0.85)), Lit);
GUI.SetTheme(GUITheme { radius = 6 });
GUILayout.Area(Rect(12, Screen.height - 124, Screen.width - 24, 112))
{
// Its two lists are there to read, like any list
GUILayout.Label(rocket.vertices.count + " vertices, " + rocket.indices.count / 3 + " triangles");
GUILayout.Slider("Light", stand.lightAngle, 0, Math.TAU);
GUILayout.Toggle("Spin", stand.spin);
}
}
```
**A draw takes it where its vertices and its indices go.** `Draw.Mesh(tree, transform, ...)` and `Draw.Instanced(tree, instances, ...)`, a render target's too, with whatever follows a mesh's lists after it: a texture, a vert, a frag, [values](#doc-game--shaders--values-for-one-draw). A view that runs for each of a thousand trees draws them [all at once](#doc-game--shaders--many-at-once), and the mesh is sent to the GPU once, however often it's drawn.
**The file fills the struct by its fields' names**, each a type the file's values are:
| Field | Type | What the file gives it |
| --- | --- | --- |
| `position` | `float3` | Where the vertex is. Every mesh's vertex has one. |
| `normal` | `float3` | Which way the surface faces there. A file with none gets each triangle's own, so it's lit flat. |
| `uv` | `float2` | Where in a texture the vertex is, (0, 0) at its top left. (0, 0) where the file has none. |
| `uv2` | `float2` | The file's second set of those, which a lightmap uses. |
| `color` | `Color` | The vertex's color times its material's. White where the file has neither. |
| `tangent` | `float4` or `float3` | Tangent direction in `xyz`; a `float4` also carries bitangent handedness in `w`. Missing tangents are generated only for static `Mesh` layouts declaring `float4 tangent`. |
| `joints` | `int4` | A skinned model's four heaviest bones at the vertex, heaviest first, numbered as a [`SkinnedMesh`](#doc-game--animation) of the file numbers its `Bone`s. 0 where no bone moves it. |
| `weights` | `float4` | Those bones' weights, which sum to 1. Zeros where no bone moves it. |
- A struct has the ones it needs, in any order: `Corner` above takes no uvs, so the pack holds none.
- **A field of any other name keeps its default.** So one struct serves the meshes a game makes in code and the ones it loads: `float glow = 1;` is 1 at every vertex of a file's. A default can read another asset, even one declared later; each pack load supplies its current value and refreshes what is drawn when that value changes.
- A field with one of those names and another type is an error at the declaration, which says the type the file's is.
- The built-in [`Vertex3`](#doc-game--3d) is a position, a uv and a color: `asset Mesh crate = "art/crate.glb";` draws with no frag, `Draw.Mesh(crate, transform, wood)`.
- **A mesh with bones is the model at rest.** A vertex with `joints` or `weights` reads the file as a skinned model: its `position` and `normal` are where the model's rest pose puts them, as a `SkinnedMesh` of the file draws at rest, in its skeleton's space (a model in centimetres comes out in metres, as it's drawn). A vert of the game's can then skin it itself, against bones of its own: a crowd's thousands in one instanced draw, each bone's `pose.Model(bone)` times the inverse of its rest's in a list the vert reads. `[LOD]` weighs the bones as it does a skinned mesh's.
Only a static `Mesh` whose vertex layout declares `float4 tangent` gets a tangent-generation variant. For its primitives without authored tangents, import derives tangents from triangle UV gradients and averages them with corner-angle weights. Generated `xyz` is normalized and orthogonal to the imported normal, with handedness `w` of +1 or -1; the bitangent is `w * cross(normal, tangent.xyz)`. A vertex shared by generated corners with opposite UV handedness splits at that seam. Missing or degenerate UVs get a finite fallback frame. Authored tangents retain their existing coordinate/node-transform conversion, including authored zero and nonorthogonal values; the generated-basis guarantees do not apply to them. Generated tangents support ordinary tangent-space normal maps but do not guarantee a match to a MikkTSpace normal-map bake.
Layouts without a tangent field, layouts with `float3 tangent`, and skinned meshes retain their prior imported streams, vertex counts, indices and canonical hashes. Missing `float3` tangents remain zero. Generating a variant for one declaration does not change another declaration's canonical import. Metadata-only language-server checks use canonical imports and do not generate tangent variants.
**It's two lists.** `tree.vertices` is a `List` and `tree.indices` a `List`, three for each triangle, and `Draw.Mesh(tree.vertices, tree.indices, transform, Look)` is the same draw. Any code reads them, the match too, since every machine has the same pack, to the bit: a system can build a collider from a rock's own triangles. They're read-only, like every asset; copy one to change it, `mut var mine = tree.vertices;`.
**One file is one mesh.** Everything the file's scene places is in it, where its nodes place it, as one list of vertices and one of triangles, with each part's material color in its vertices' `color`. Only vertices its triangles use are kept; a glTF primitive that shares a larger vertex array with other materials keeps its own part of that array. That's all a model in flat colors needs. What a game moves apart, a car's wheels from its body, is a file each, and a glob names them: `asset Map> car = "art/car/*.glb";`.
**What's read, and what isn't:**
- From a glTF: its meshes' positions, normals, tangents, two sets of uvs and vertex colors, its nodes' places, and each material's base color. Not its textures, nor the rest of a material; not skins, animation, morph targets, cameras or lights: a skinned model is the mesh as it stands. Required Draco/meshopt compression and other unsupported required extensions give an error with export guidance. Optional compression can use the file's valid uncompressed fallback.
- From an OBJ: positions, uvs, normals and faces of any number of corners, with a color after a position where a tool wrote one. Not its materials file.
- From an FBX: polygon meshes, node transforms, normals, tangents, two sets of uvs, vertex colors and material base colors. Polygons are triangulated, and the file's axes and units are converted to Y-up meters before Tide's coordinate conversion. An attribute index past its array, which some exporters write, reads the array's last element, as Blender and Unity read the file. Embedded textures and the rest of a material are not imported. A static `Mesh` takes the rest geometry; use [`SkinnedMesh`](#doc-game--animation) for bones and animation. A file's polygons can't take more than 2^32 steps to triangulate in all (a polygon's corners squared, summed: one polygon of 65,536 corners), and its animation takes bake to 16,777,216 keys at the most.
- **A texture a model has is a file of its own**, using a supported image format, declared like any: `asset Texture bark = "art/bark.png";`, and given to the draw.
- A mesh holds 16,777,216 vertices and 8,388,608 triangles at the most. A glTF's description can have 4,194,304 JSON values, and 536,870,912 numbers are read from its accessors in all, an accessor counting again for each part that names it. A file past one of these is refused before anything is made for it. The numbers are provisional.
**It comes in as Tide has the world.** Tide's world is left-handed with fronts [clockwise](#doc-game--3d--which-side-draws), like Unity's. glTF is right-handed with fronts counterclockwise: a file's `x` is turned around and its triangles are wound the other way, so `+y` stays up and a model that faces `+z` still faces `+z`. OBJ uses the same conversion. FBX first converts its declared axes and units to right-handed Y-up meters, then uses that conversion too. A glTF's colors are light, and a `Color` is what the screen shows, so they're converted; an OBJ's are taken as written.
**An asset's mesh value is a stable ID.** Fields, lists, arrays, maps, parameters and tasks can keep a `Mesh` without copying an asset's vertices or indices. Reading `.vertices` or `.indices` borrows the currently loaded geometry. `Asset>` holds only that ID, for a reference that must name an asset (the editor assigns one); it goes wherever a `Mesh` does, and its `.Value` is that `Mesh`.
```csharp
component Prop
{
float3 position;
Mesh model;
}
singleton Models
{
List> choices;
Mesh[2] favorites;
}
view Props(Prop prop)
{
Draw.Mesh(prop.model, float4x4.Translate(prop.position));
}
```
**A mesh the game makes is a `Mesh` too.** `Mesh(vertices, indices)` takes a `List` of a 3D vertex struct and a `List` of indices, three a triangle, and makes a static mesh of copies of them. Nothing changes the copies after, whatever happens to the lists they came from, so there is nothing to free: the mesh lasts as long as the value holding it, like any list. It goes wherever an asset's mesh goes: fields, lists and maps of meshes beside assets', parameters, `Draw.Mesh` and `Draw.Instanced`, and anything else that takes a `Mesh`. A type alias makes one too: `Model(vertices, indices)`.
```csharp
using Model = Mesh;
singleton Terrain { Model ground; List pieces; }
system Build(mut Terrain terrain)
{
List corners = [Vertex3 { position = float3(0, 0, 0) }, Vertex3 { position = float3(1, 0, 0) },
Vertex3 { position = float3(0, 0, 1) }];
terrain.ground = Mesh(corners, [0, 2, 1]);
terrain.pieces = [rock, terrain.ground];
}
```
- **Where it's kept decides its cost.** In match state its geometry is part of the match: in snapshots and hashes, sent whole to a player who joins, and to the others once, as it's made. Its pages never change after, so rollback copies and the per-tick hash cost almost nothing more. Keep geometry only the screen needs in local state, where none of that applies, or make it in a view each frame.
- **Copies are one mesh on the GPU.** Every copy draws with no list read: the mesh's id is worked out from its contents once, when it's made, and the draw uses it as the geometry's version. A copy of the value copies its two lists.
- **Equality compares contents:** two meshes made of the same lists are `==`, and a made mesh is never an asset's or `default`, even with no triangles.
- **Levels of detail** are the draw's to ask for, `lod:`, as for any mesh your game makes (below).
- **Not there:** a made `SkinnedMesh`; and a 2D mesh, which draws from its two lists, `Draw.Mesh(vertices, indices)`.
**A mesh read while the game runs is a `Mesh` too.** `Mesh.Decode(bytes)` reads a model from a `List`, from [`await Web.Fetch(url)`](#doc-game--files), `File.ReadAllBytes(path)` or a player's upload, and gives a `Mesh fails IOError`. It reads the file as an `asset Mesh` of it does: the same vertices, filled by your vertex struct's field names, every other field its default, a `float4 tangent` made where the file has none. It's the same bits on every machine, so match code can decode too, and the mesh then lives as a mesh your game makes does (above).
```csharp
using Model = Mesh;
singleton Arena { Model statue; PlayerID host; string message; }
command SetStatue { List model; }
command(SetStatue value, PlayerID sender) Apply(mut Arena arena)
{
if (sender != arena.host) return;
if (Model.Decode(value.model) is Model statue) arena.statue = statue;
else arena.message = "That isn't a model";
}
```
- **Formats:** a `.glb`, a `.gltf` whose buffers are inside it (data URIs), and an `.obj`, told apart by their first bytes, as the bytes have no name. A `.gltf` that names buffer files, and an FBX, which Tide reads at build time only, are `IOError.InvalidData`, as is anything else that isn't a mesh.
- **A vertex with `joints` or `weights`** is a [Mesh with bones](#doc-game--animation), read from a `.glb` as its asset is: at rest, each corner with its four heaviest bones.
- **Limits:** a file of more than 512 MiB, 1,048,576 vertices, 6,291,456 triangle corners, 4,194,304 JSON values or 67,108,864 numbers read (an `.obj`'s vertex, normal and uv lines count) is `InvalidData` before anything is made for it, and so is a mesh whose numbers a node's transform takes past what a float holds. Each machine that refused one says why on its log, naming the limit: `tide: Mesh.Decode refused a mesh: it has 2,000,000 vertices in a part, more than the 1,048,576 Mesh.Decode takes (TIDE_MESH_DECODE_MAX_VERTICES)`.
Collections follow ordinary value-copy and mutation rules. Copying an immutable asset collection can share its ID storage until a write. Geometry stays in the asset pack. Singular IDs follow the qualified declaration name; glob-element IDs also include the written file key, so changing a glob's order keeps retained selections stable. A removed or unknown ID resolves to empty geometry. Renaming a declaration or file key changes that identity.
A frag and a vert don't read a mesh's two lists: the draw sends them to the GPU as the mesh they are.
### Levels of detail
A model with thousands of triangles costs the same to draw when it's a dot on the horizon as when it fills the screen. `[LOD]` before a mesh asset has simpler versions of it made as the game is built, and each draw then picks one by how big the mesh is on screen:
```csharp
[LOD] asset Mesh rock = "art/rock.glb";
view Rocks(Scenery scenery)
{
Draw.Instanced(rock, scenery.transforms, Look); // Each rock at its own level
}
```
That's all there is to write. There are no distances to set, no levels to author and nothing more to pass a draw.
- **It's opt-in.** A mesh without `[LOD]` is drawn as it always was, with nothing made for it.
- **A level is fewer of the mesh's own triangles.** Each has about half the triangles of the one before, over the same vertices: none is added or moved, so the pack grows by the levels' triangles alone, about as much again as the mesh's own. Open edges stay where they are, and so do the seams where a texture or a color changes, so no hole opens and no texture tears.
- **Static layouts with a `float4 tangent` preserve opposite handedness signs as separate seams.** Tangent `xyz` adds no simplification error metric. Other vertex layouts and skinned meshes retain their previous LOD behavior and cache keys.
- **A mesh of under 1,000 triangles gets no levels.** Levels only pay by the triangles they take off a draw, and picking one costs a little for each instance, so such a mesh draws exactly as if it weren't marked, with nothing picked. A bigger mesh's chain goes on to levels of a few dozen triangles, and stops before one of under 64: a crowd far off draws each figure that small.
- **A draw picks by estimated visual error on screen.** Each level knows how far its surface, and what's on it, is from the full mesh's. A normal or a color is off by as much as the patch it's off on: a bevel shaded a little differently counts for the bevel's size, not the whole mesh's. A draw takes the simplest level within its pixel tolerance, 1 by default. A mesh drawn large keeps more detail at any distance.
- **Each instance picks its own.** `Draw.Instanced` over a field of rocks draws the near ones whole and the far ones simple: one GPU draw for each level in use, the instances of each in the order the list has them. A view that runs for each entity is grouped the same way.
- **Your code reads the full mesh.** `rock.vertices` and `rock.indices` are what they are without `[LOD]`, for the match too: a collider built from a rock's triangles is built from all of them, on every machine.
- **It works on a [`SkinnedMesh`](#doc-game--animation) too:** `[LOD] asset SkinnedMesh hero = "art/hero.glb";`. Its levels are made from the model at rest, weighing how each vertex follows its bones so joints keep the vertices that bend them, and a pose deforms a level as it deforms the full mesh.
- **A list or a map of meshes** takes it for every file: `[LOD] asset List> rocks = "art/rocks/*.glb";`.
- **An asset can accept more error:** `[LOD(2)] asset Mesh rock = "art/rock.glb";` multiplies the draw's pixel tolerance by 2. `[LOD]` means 1. The argument must be a positive finite constant number; fractions below 1 keep more detail. It applies to every file in a list or map and works on skinned meshes too. The generated levels stay the same.
- **They're made once.** tide keeps a mesh's levels in the game's `.tide/` folder, by what's in the file, so later builds don't make them again.
**A mesh your game makes gets levels with `lod:`.** Terrain chunks, generated buildings, anything built into a `List` or a list of your own vertex while the game runs: write `lod:` last in its 3D `Draw.Mesh` or `Draw.Instanced`, with the same multiplier `[LOD(...)]` takes:
```csharp
view Terrain(Chunk chunk)
{
Draw.Mesh(chunk.vertices, chunk.indices, chunk.transform, Look, lod: 1);
}
```
- **The levels are the ones an asset of the same mesh would get**, made by the same code: the same floor of 1,000 triangles, the same seams kept, the same picking, and the same levels on every machine.
- **They're made in the background**, on threads beside the frame's, never in it. Until they're there the mesh draws whole: a frame or so for a mesh of thousands of triangles, longer for a big one. Where there are no threads to make them on (a web page that isn't [cross-origin isolated](#doc-tools--cli--threads-on-the-web)), such meshes draw whole.
- **They're kept by what's in the mesh.** Drawing the same lists again costs nothing more, nor does making the same mesh again or drawing it again after a while away. Lists made again with other numbers start over: what was being made of the old ones stops. A mesh that changes every frame keeps drawing whole, which is right for one that moves its vertices.
- **The fields weighed are your vertex's `position` (a `float3`), and `normal`, `uv`, `uv2`, `color` and `tangent` where it has them** with those names and types, as an asset's file fills them.
- **The same lists drawn without `lod:` are another mesh**, drawn whole, and so are the same lists drawn with another multiplier. `lod: 0`, or a multiplier that's no number, is 1, as `Draw.LODPixels` takes them.
- It's for 3D meshes: a 2D mesh draws as it is. A model with bones takes it too, `Draw.SkinnedMesh(model, transform, lod: 1)`, with its bones weighed as `[LOD]` weighs them, so a model decoded while the game runs (`SkinnedMesh.Decode`) gets the levels its file would get as a marked asset.
**A game's vert isn't known to the pick.** Where the mesh is and how big it is come from the file's own geometry and the draw's transform. A vert that moves vertices far from there, or grows the mesh, gets levels picked for where the mesh would have been: draw such a mesh with `Draw.LOD(0)`, below, or leave `[LOD]` off it.
**`Draw.LODPixels` controls the quality/performance tradeoff** while each mesh still picks automatically. The default is 1 pixel of estimated visual error. Higher values allow coarser meshes at the same distance; positive values below 1 keep more detail:
```csharp
Draw.LODPixels(4)
{
Draw.Instanced(rock, scenery.transforms, Look);
}
```
`Draw.SetLODPixels(4);` applies to following window draws. A render target has its own tolerance: `shadow.SetLODPixels(4);`. The asset's multiplier applies too: `[LOD(2)]` allows 2 pixels normally and 8 in that shadow pass. Both draw-setting forms restore 1 with no arguments; a block restores the previous value when it ends, including an early exit. Nonpositive or nonfinite draw-setting values also use 1. This changes selection among the levels already built; it doesn't generate more levels. Pixels are counted through the same camera and resolution as automatic selection.
**`Draw.LOD` names the level** instead of picking it, a [draw setting](#doc-game--draw-settings) with the two forms the others have. A named level overrides the pixel tolerance. `0` is the full mesh, `1` the first simpler one, and a number past a mesh's last level is its last:
```csharp
Draw.LOD(0)
{
Draw.Mesh(rock, transform, Look); // Whole, wherever it is
}
```
With no number, `Draw.LOD() { ... }` and `Draw.SetLOD();`, each mesh picks again. Every instance of an instanced draw has the level that's named, so the draw is one GPU draw in the list's order, which is what instances drawn with a blend and no depth need.
**`Draw.LODCamera` names the camera to pick through**, in place of the one the meshes are drawn through. A [shadow map](#doc-game--render-targets) picks with its lamp's camera and its own pixels, so a mesh could cast the shadow of another level than the one the player sees. Told the player's camera, it casts what's shown:
```csharp
view Cast(Lamp lamp, Viewer viewer, Rock rock)
{
lamp.shadow.SetCamera(lamp.transform, lamp.projection); // What the shadow is drawn through
lamp.shadow.SetLODCamera(viewer.position, viewer.rotation, 60); // What picks its levels
lamp.shadow.Mesh(rocks[rock.model], float4x4.Translate(rock.position), Depth);
}
```
It takes what `Draw.Camera` takes for a 3D camera: a position, a rotation and a field of view, or a transform and a projection (`Draw.CameraTransform()` and `Draw.CameraProjection()` give the window's). With nothing, `SetLODCamera()`, the destination's own camera picks again. A level that's named wins over a camera that's named.
A shadow map covers more than the player sees: meshes beside the player and behind them. Those pick by how far out of the view they are, so they cast coarser shadows the farther out they are, and the shadow map's `SetLODPixels` coarsens them as it does the rest.
**Info**
That a mesh opts in with `[LOD]`, that everything after it is automatic, that each instance picks its own, that skinned meshes have it, and that a game can name a level, a pixel tolerance or a camera to pick by, are decided. How the levels are made and the other rules above are how it works today, and may still change.
### Blend shapes to keep
A skinned model's [blend shapes](#doc-game--animation--blend-shapes) are all imported, which can be most of a pack: a head with fifty facial shapes carries fifty sets of vertex deltas. `[BlendShapes(...)]` before a `SkinnedMesh` asset keeps only the shapes whose source names match one of its arguments, a name or a pattern where `*` is any run of characters:
```csharp
[BlendShapes("masculineFeminine", "default*")]
asset List> parts = "sidekick/parts/*.fbx";
```
The other shapes are left out of the import, deltas and all, and the vertices keep every shape at the file's default weight as before. A pattern that matches nothing in a file is fine, as in a glob of parts where only some have a shape; `[BlendShapes()]` keeps none, and a model left with no shapes packs as it would with none in its file. It applies to every file of a list or a map. Without it, every shape is kept.
## Paths
A path is relative to the `.tide` file that names it, whatever that file's namespace: there's no assets folder and no root. A package's files name files beside its own code the same way. Forward slashes, on every platform.
A path is a constant: a string literal, or a `const string`, so a game that wants one path twice names it once:
```csharp
const string TILES = "art/tiles.png";
asset Grid2 tiles = TILES;
```
### Globs
A glob names every file it matches, in order of their paths (byte by byte): `*` matches within a name, `**` across folders, and `?` one character. The type says what you get:
```csharp
asset List> run = "art/run/*.png"; // Their contents, in order: run[0], run[1], ...
asset Map> tiles = "art/tiles/**/*.png"; // Each path as written from this file, with its contents
asset List notes = "notes/*.txt";
asset List frames = "art/walk/*.png"; // Images to draw with, in order
```
A map's keys are the paths as you'd have written them, `"art/tiles/grass.png"`, so a game finds a file by name: `tiles["art/tiles/grass.png"]`, `tiles.Has(name)`. A glob that matches nothing is an error, and so is a glob for a type that holds one file.
A list or a map can name one file, and is then a list or a map of that one:
```csharp
asset List shots = "sfx/shot.wav"; // shots.count is 1, and shots[0] is the file
asset Map named = "sfx/shot.wav"; // named["sfx/shot.wav"]
```
Synchronous CPU helpers can [borrow resource asset collections](#doc-language--functions) through read-only `List`, `List`, `List>` or `Map` parameters. Pass the asset directly; the call reads its existing collection without copying it.
That's for a path that changes while the game is made. Start with the one file there is, widen the path to `"sfx/shot*.wav"` or `"sfx/*.wav"` when there are more, or narrow it again, and the type and the code that reads it stay as they are. A map's key for the one file is its path as written, which is the key a glob gives it. A URL in a list or a map is the same: one entry, keyed by the URL.
A frag samples an asset by its own name: it can't index a list of them (`run[1].Sample(uv)` is an error), so declare the one it samples as an asset of its own, or for a `Texture`, give the draw that one as the frag's source: `Draw.Mesh(corners, faces, frames[1], Shade)`.
### URLs
A path can be an `http://` or `https://` URL. The compiler fetches it as the game is built and packs what it got, so it's a file kept elsewhere and nothing else: nothing is fetched when the game runs, and the game plays offline.
```csharp
asset string credits = "https://example.com/credits.txt";
```
What was fetched is kept in the game's `.tide/`, with the server's ETag. Each build asks the server whether the file changed, and builds from what it has when the server can't be reached, so an offline build works once the file was fetched once. A URL that can't be fetched and was never cached is an error.
## Assets made by code
An asset's value can be a call of code that runs while the game builds, which makes it from nothing or from another asset's file: `asset Texture hero = Outlined(heroSource, Color.black);`. A sound's samples are an asset too: `asset ClipData step = "sfx/step.wav";`. See [Build code](#doc-game--build-code).
## What's checked
Anything wrong that can be known as the game is built is an error at the declaration, in the editor as you type and in `tide build` alike:
- A file that isn't there. The error says where a file with the same bytes is now, if the file was moved (the compiler keeps a hash of every named file in the game's `.tide/`), or else lists the files of that name, with a quick fix for each in the editor.
- A glob that matches nothing.
- Bytes that aren't what the type says: an unsupported image/audio/model format, a damaged supported file, an unsupported codec or required extension, or text that isn't UTF-8. The diagnostic names the source file and the reason, with supported alternatives or export guidance.
- A type an asset can't be, a path that isn't a constant, a `local` or `virtual` asset, a write to one.
The editor keeps assets in step with their files: renaming a file or a folder rewrites the paths that name it, and a path's completion offers the files it can lead to. See [Editors](#doc-tools--editors).
## The pack
`tide build` packs the closure of the game's `asset` declarations, and nothing else in the folder. A file is in the pack once however many declarations name it, and they all read the same value: a `Grid2` of the pack lives in a read-only region every world can name, outside every world's heap, so no world copies, hashes or sends it. A file declared as a `Grid2` and as a `Texture` is in it once as each, and so is a text file with characters past ASCII that's declared as a `string` and as a `List`.
Where the pack is: beside the program as `.pack` on desktop, inside the self-contained page on the web, and in the APK on Android. A release or distribution build's pack is compressed as a file and read into the same memory, so a game's assets take the room on disk and in a download that their content needs, and the room in memory that they always did. Under `tide run`, tide watches the files assets name. Ordinary images and static models reload as data. [Skinned models and animation catalogs](#doc-game--animation) and assets their vertex defaults read require a matching game build because their values can become match state; the running game refuses a mismatched pack and keeps the current one. This also applies to asset dependencies of vertex defaults used by runtime skinned decoding. A C host of its own (`tide_add_game` with `HOST`) gets the pack as a C array, `tide_game_pack`, to hand `tide_assets_load`.
## Loading at runtime
[Skinned models](#doc-game--animation) import as `SkinnedMesh` from glTF, with checked animation and bone catalogs. They can also be loaded while playing with `SkinnedMesh.Decode(bytes)` or its optional contracted form; runtime decoding accepts self-contained GLB bytes and fails with `IOError.InvalidData` for malformed data or unmet requirements.
Two things bring bytes in while a game runs, both local, both failing with `IOError`:
- `File.ReadAllBytes(path)` reads a file of this machine's (see [Files and directories](#doc-game--files)).
- `await Web.Fetch(url)` fetches an `http://` or `https://` URL, in a task, so frames go on meanwhile.
Bytes that every player should see go into the match through a [command](#doc-game--commands), and the match keeps them as its own state, which the netcode sends like any other, to those in the match and to whoever joins.
## Decoding a PNG
`grid.Decode(bytes)` reads a PNG into a `Grid2` field of a component, singleton or scene, sizing the grid as the image is and writing every pixel. It fails with `IOError.InvalidData` for bytes that aren't a PNG, or are wrong anywhere, and then the grid is as it was.
Bytes can come from anywhere, so a small file can't ask for much. A picture of more than 4096 × 4096 pixels (16,777,216) is `InvalidData` before anything is made for it, whatever its shape; at that size its cells are 256 MiB of the match. So is a file whose compressed data goes on for more than 1 MiB past its last row. These limits are the engine's, the same for every game, so every machine in a match refuses the same files. A picture refused for one says so on each machine's log, naming the limit: `tide: grid.Decode refused a PNG: it's 5000 by 5000 pixels, 25,000,000 in all, more than the 16,777,216 grid.Decode takes (TIDE_GRID_DECODE_MAX_PIXELS)`. Build-time imports past a limit are errors that name it the same way.
It's pure, so it runs in match code as well as local code: a handler that decodes gives every machine the same pixels, bit for bit, because the engine's own reader does the decoding, with no system library in the way. The grid then draws as a texture like any `Grid2` (see [Meshes and textures](#doc-game--meshes-and-textures--textures)).
A player's own picture, decoded for this machine alone:
```csharp
local singleton Picker
{
string path;
bool load;
Grid2 preview;
string message;
}
view Pick(mut Picker picker)
{
if (!picker.load) return;
picker.load = false;
var bytes = File.ReadAllBytes(picker.path) ?? [];
if (picker.preview.Decode(bytes) is IOError error) picker.message = "Not a PNG: " + error;
else picker.message = "Loaded " + picker.preview.size.x + " by " + picker.preview.size.y;
}
```
In the match, the handler of a command decodes, and every machine gets the same pixels:
```csharp
singleton Arena
{
Grid2 background;
PlayerID host;
}
command SetBackground { List png; }
command(SetBackground value, PlayerID sender) Apply(mut Arena arena)
{
if (sender != arena.host) return;
arena.background.Decode(value.png)!;
}
```
A command's `List` goes to the server and on to every player, one that doesn't fit a datagram in chunks, so a few megabytes is fine; see [Commands](#doc-game--commands).
Every kind of PNG decodes: gray, color, with a palette, with or without alpha, 1 to 16 bits a sample, interlaced or not. A clear black pixel is a cell that's zero, which takes no memory. A picture past 16384 pixels a side, or past 4096 × 4096 in all, is `InvalidData`. Decoding runs where it's called, on the frame's or the tick's thread: a 4K picture takes a frame, so decode once, when the picture arrives, not every frame.
## Fetching a URL
`await Web.Fetch(url)` gives the body as a `List`. It's local only, like `File`: views, local handlers, local tasks and the functions they call, never the match, input sampling, the GPU, a sort comparison or a parallel loop. The task waits while this machine fetches, and the bytes arrive in a frame to come.
| Result | When |
| --- | --- |
| `IOError.NotFound` | The server answered 404. |
| `IOError.InvalidPath` | The URL doesn't start with `http://` or `https://`. |
| `IOError.Failed` | Anything else: no connection, a certificate the system doesn't trust, another status, a body over 64 MiB, more than 5 redirects, or on the web a server whose CORS refuses the page. |
```csharp
local singleton Download { string status; Grid2 preview; }
async void Fetch(string url, mut Download download)
{
download.status = "fetching";
if (await Web.Fetch(url) is IOError error)
{
download.status = "failed: " + error;
return;
}
download.status = "fetched";
}
```
Big media is better fetched by each machine than sent through the match: what goes through the match goes player to server to everyone, so a host uploads it once per player. Keep a URL in the match and let each machine fetch and decode.
---
Source: https://tide-engine.dev/game/build-code.md
Make and process Tide assets and constants with code that runs while the game builds: outline an image, bake a curve, generate a mesh, its levels of detail or a sound.
# Build code
Build code is Tide code that runs while the game builds. It makes an [asset](#doc-game--assets) or a constant: an image with an outline drawn on it, a table of numbers, a mesh, its levels of detail, a sound. What it made goes into the build as a file's contents do, so every machine has the same value and the game spends no time on it while it runs.
Build code runs through the installed tools, including when building a web game
with `tide run --web`. The browser playground cannot run its native build program.
An asset's value is either its file's path or a call of code that makes it. That code is ordinary Tide: functions that return the value.
```csharp
void Outline(mut Grid2 image, Color color)
{
for (int y = 0; y < image.size.y; y++)
{
image[int2(0, y)] = color;
image[int2(image.size.x - 1, y)] = color;
}
}
Grid2 Outlined(Grid2 source, Color color)
{
mut Grid2 image = source.Copy();
Outline(image, color);
return image;
}
asset Grid2 heroSource = "art/hero.png";
asset Texture hero = Outlined(heroSource, Color.black);
```
`heroSource` is the file's pixels, and `hero` is the texture the game draws: the outlined copy. Functions that return and change grids are what any code can write (see [Grids in code](#doc-language--grids--grids-in-code)).
## What code makes
An asset of these types can be made by code, which returns:
| Asset | What its code returns |
|---|---|
| `string`, `List` | The text or the bytes |
| `Grid2` | The grid, with a size: `Grid2(width, height)` |
| `Texture` | Its pixels, a `Grid2`, which become the texture as a file's would |
| `Mesh` | `Mesh(vertices, indices)`, or with [levels of detail](#doc-game--build-code--levels-of-detail) of its own |
| `Clip` | A `ClipData`: its `rate`, its `channels` (1 or 2) and its `samples`, interleaved |
| `ClipData` | The same, kept as data the game reads |
Code can make an asset from nothing:
```csharp
Grid2 Checker(int size)
{
mut Grid2 image = Grid2(size, size);
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
if ((x / 8 + y / 8) % 2 == 0) image[int2(x, y)] = Color.white;
}
}
return image;
}
ClipData Beep()
{
mut ClipData beep = ClipData { rate = 48000, channels = 1 };
for (int i = 0; i < 4800; i++)
{
beep.samples.Add(Math.Sin(i * 0.06) * 0.5);
}
return beep;
}
asset Texture board = Checker(64);
asset Clip beep = Beep();
```
An image must have a size, and every pixel and sample must be a number, not NaN or infinity. A mesh's triangles must name vertices it has.
## Files code reads
A file that code changes is declared as the data the code reads: an image as a `Grid2`, a sound as a `ClipData`, a mesh as a `Mesh`, text as a `string`. The asset code makes from it has a name of its own.
```csharp
asset ClipData stepSource = "sfx/step.wav";
asset Clip step = Quieter(stepSource, 0.5);
ClipData Quieter(ClipData source, float scale)
{
mut ClipData quiet = source;
for (int i = 0; i < quiet.samples.count; i++)
{
quiet.samples[i] *= scale;
}
return quiet;
}
```
Code can read other assets and what other code made: an asset whose code reads another asset made by code is made after it. A game built without what nothing reads (`--strip-unused-assets`, as release builds are) leaves out a file only build code reads.
## Constants
A constant whose value calls a function is made by build code too:
```csharp
const List CURVE = Curve(64);
const float SCALE = Twice(0.25);
List Curve(int count)
{
mut List curve = [];
for (int i = 0; i < count; i++)
{
curve.Add(Math.Sin(i * 0.1));
}
return curve;
}
float Twice(float x)
{
return x * 2;
}
```
A constant build code makes can be an array or a list of plain values (numbers, vectors, colors and structs of those) as well as what any constant can be: `const int[16] SQUARES = Squares();`. A list can be as long as you like, where one [written out](#doc-language--basics--tables) holds 4096 values at the most. Code and field defaults read it. A `case` label, a bound, a setting or another constant can't, as its value isn't known until the game builds, and neither can a frag or a vert yet; build code that makes another constant can (`const float FIRST = Head(CURVE);`).
## Build functions
Build code can call any function that doesn't need a running game. `build` marks a function that only runs while the game builds: anything but build code calling it is an error, and its body is checked as build code where it's written. It follows the same rules as any other code.
Build code runs before there's a game. It can't use a world (queries, `Spawn`, `Send`), `Devices`, drawing, audio, files beyond the assets it names, tasks, or the match's random numbers. `Math.Hash`, or a `Random` the code makes with a seed, gives it random numbers. It can't call [C](#doc-c--functions) yet either. The error points at the asset, constant or build function, with a note at the function that does it.
## Levels of detail
A mesh can have levels of detail of its own instead of `[LOD]`'s: `Mesh(vertices, indices, levels)`. Each `MeshLevel` is triangles of the mesh's own vertices, and its error: how far that level's surface is from the full mesh's, in the mesh's units. Draws pick among them just as they pick `[LOD]` levels.
```csharp
asset Mesh rockSource = "art/rock.glb";
asset Mesh rock = Leveled(rockSource);
build Mesh Leveled(Mesh source)
{
mut List levels = [];
levels.Add(MeshLevel { indices = Simplify(source, 0.5), error = 0.02 });
levels.Add(MeshLevel { indices = Simplify(source, 0.1), error = 0.2 });
return Mesh(source.vertices, source.indices, levels);
}
```
A mesh has at most 7 levels after the full one, each error at least the one before it. An asset can have `[LOD]` or levels from its code, not both. Only build code makes a mesh with levels of its own; a mesh made as the game runs gets its levels from the draw's `lod:` (see [Levels of detail](#doc-game--assets--levels-of-detail)).
## How it runs
tidec turns the game's build code into a small program, compiles it with the engine's sources, and runs it on the machine that builds, whatever the game is built for. `tide build` and `tide run` do this with the compiler they build the game with. What it made is kept in the game's `.tide/`, by everything that made it: the code, what it calls, the types it uses and the files it reads. A build where nothing of that changed runs no build code. Under `tide run`, saving a file that build code reads makes it again.
Build code that runs for more than ten minutes is stopped, and the build fails. What it logs with `Debug.Log` shows as the game builds.
The details, and which choices are still provisional, are in the [specification](https://tide-engine.dev/spec.md#build-code).
---
Source: https://tide-engine.dev/game/scenes.md
Author rooted scenes and prefabs, choose a startup scene, load and unload levels, and manage scene ownership and multiple instances.
# Scenes
A scene is a group of entities that load and unload together: a menu, a level, an arena. Several scenes can be loaded at once, and several copies of the same one.
```csharp
scene Arena
{
int size = 20;
}
```
A loaded scene is an entity like any other. The declaration is its component, and its fields are the scene's state, so a system that takes `Arena` runs once per loaded arena.
## Systems for one scene's entities
`with scene Arena` runs a system, a view or an event handler only for the
entities of a loaded arena; `without scene Arena`, only for the others:
```csharp
system Spinning(Spin spin, mut Transform transform, Time time, with scene Arena)
{
transform.localRotation = Math.Mul(quaternion.Euler(0, spin.speed * time.dt, 0), transform.localRotation);
}
```
An entity is in the scene it was spawned into: the scene of the entity the code
that spawned it runs for. A loaded scene's own entity is one of its entities
too. `with Arena`, without `scene`, still takes that entity alone, as it does
for any component, so `event(Spawned) Setup(with Arena)` runs once per loaded
arena. A scene filter on its own runs for every entity of the scene.
For an empty scene, use `scene Arena;` as shorthand for `scene Arena { }`.
The same works for local scenes: `local scene Main;`. Both forms are complete
declarations, and braces remain valid.
## Authored prefabs
An authored `.tprefab` file describes a reusable rooted entity tree. The same
tree can be spawned as an entity or loaded as a scene:
```csharp
// Enemy.tprefab
prefab Enemy
{
Transform;
Health { value = 100 };
Target { weapon = Weapon };
entity Weapon
{
Transform { localPosition = float3(0, 1, 0) };
}
}
```
Declare `Health` and `Target` in ordinary `.tide` code. A reference field can use
`[SceneRequired] Entity weapon;` to require a named entity in authored prefabs.
The compiler checks unused prefabs too; missing components, fields, references
and recursive inclusion are errors. Ordinary code-driven construction can still
leave these fields unset and initialize them later.
```csharp
var enemy = Spawn(Enemy, Health { value = 50 });
var level = Scene.Load(Level, LevelSettings { difficulty = 2 });
Scene.Unload(level);
```
Settings are normal root components. Component literals override only the fields
they name and can add root components. An existing component value replaces the
whole root component. A bare component argument resets that
component to its declared defaults. A match scene uses the ordinary root
`Visibility` component: `Scene.Load(Level, Visibility { group = group })`.
All entities, component values, references and parenting exist before the
instance's `Spawned` handlers run, root-first. Nested children move with their
parents and are destroyed with them. `entity Weapon : Pistol { ... }` reuses
another named prefab; fields in its block override that prefab's root. Paths such
as `Weapon.Muzzle` resolve through nested instances, and omitted values use the
authored prefab and component defaults.
Override an inherited descendant by matching its existing name with another
`entity` block. This changes values on this instance without changing Pistol:
```csharp
entity Weapon : Pistol
{
entity Muzzle
{
Transform { localPosition = float3(0, 0, 0.8) };
}
}
```
Inside an inherited descendant, only field values of existing components can
change. Match further `entity` blocks to reach deeper descendants. These blocks
cannot add, remove or replace components or children, or name another base
prefab. A nested instance's root can still add components and new named children.
Reference paths keep the scope of the prefab whose source wrote them; `this`
means the entity containing the value. Overrides do not create extra entities.
`local Spawn(Enemy)` creates local entities, and `Scene.Load` from local code
loads into the local world. References must use the corresponding `Entity` or
`LocalEntity` type. Prefab names are factories, so filters use explicit root
components. The initial limits are 1024
entities per instance and 128 nesting levels.
## Startup scene
An authored scene can start the game directly. In an ordinary `.tide` file, name
its declaration in project settings:
```csharp
settings
{
startScene = Levels.Start;
}
```
`startScene` takes a prefab or scene name, including its namespace when needed,
not a string or a call. A prefab starts as a match scene with its own root,
authored values and complete tree. Normal `Spawned` handlers, systems, views,
camera and input run; no handwritten `Main` is needed. An ordinary scene can be
selected too, including a local scene for a menu outside a match.
For one run or build, override the project selection:
```sh
tide run . --scene Levels.Start --stats
tide build . --scene Levels.Start
```
This leaves project settings and any existing `Main` declaration unchanged.
## Main
Without a selected startup scene, the game starts in the scene called `Main`,
and there must be exactly one. It sets up the first scene, not the game loop:
the engine runs the tick.
```csharp
scene Main;
event(Spawned) Setup(with Main)
{
Spawn(Transform { localScale = float3(1, 1, 1) }, Player);
}
```
A match `Main`, like this one, starts a single-player match with it right away. A local `Main` starts the program outside any match, usually in a menu, which starts one later (see [Local state](#doc-game--local-state) and [Matches](#doc-multiplayer--matches)).
## Loading and unloading
```csharp
var arena = Scene.Load(Arena { size = 30 });
Scene.Unload(arena);
```
`Scene.Load` loads a scene into the current world and returns its entity. `Scene.Unload` unloads it, destroying every entity it owns, and so does `Destroy` on a scene's entity. `Scene.Unload` of an entity that isn't a scene does nothing. `Spawn` of a scene is an error that says to use `Scene.Load`.
Additional component arguments attach to the loaded root, for example
`Scene.Load(Arena { size = 30 }, Visibility { group = group })`. They use the
same component names, literals and existing values as `Spawn` and are present before `Spawned`
handlers run. Local scenes can also take root components, using local placement.
Loading and unloading happen at the end of the tick, like `Spawn` and `Destroy`.
A scene can do heavy preparation before its `Spawned` handlers run, as described
below. Its entities get `Destroyed` when it unloads.
## Switching scenes
To leave one scene for another, switch:
```csharp
Scene.Switch(Arena { size = 30 });
```
`Scene.Switch` unloads every scene loaded in the world and loads this one,
returning its entity. It takes what `Scene.Load` takes, root components included,
and needs no handle to the scene being left, so any code can call it: a system of
the scene, or a button in a view that runs for no entity. A match scene switches
the match's scenes and a local scene this machine's. Entities in no scene stay.
It happens at the end of the tick, in its turn: scenes loaded earlier in the same
tick go too, and scenes loaded after it stay. The world is never left without a
scene, so the startup scene doesn't load in between.
Functions and methods can load, switch and unload scenes, for the code that calls
them. A function that loads a match scene is for match code to call, and one that
loads a local scene is for views and local handlers:
```csharp
local scene Menu;
local scene Lobby { int seats; }
void OpenLobby(int seats)
{
Scene.Switch(Lobby { seats = seats });
}
view MenuButtons(with Menu)
{
if (GUILayout.Button("Play")) OpenLobby(4);
}
```
A prefab belongs to neither side. In a function it loads into the match; write
`local Scene.Load(MenuPrefab)` or `local Scene.Switch(MenuPrefab)` to load it on
this machine instead.
### From a menu into a match
A menu is usually a local scene, and the game a match that `Session.Start` or
`Session.Join` puts this machine in. Unload the menu as the match starts and it
stays gone for the whole match:
```csharp
local scene Main;
view Menu(with Main)
{
if (GUILayout.Button("Play"))
{
Session.Start(Arena);
Scene.Unload(this);
}
}
```
With a local scene for the match's own interface, switch to it instead:
`Scene.Switch(Hud)`. The startup scene loads again by itself once this machine is
offline with no local scene loaded: when the match ends, the player leaves, or
joining fails. Nothing has to bring the menu back.
The startup scene is also the fallback: the selected scene or prefab, or `Main`
without a selection. When the last scene of its world unloads, the fallback loads
again at the end of that tick, initialized as at startup. A match startup returns
in the match, and a local one in local state, while this machine is offline: in a
match, or with one asked for, it waits. Unloading one scene and loading
another in the same tick never brings it back, and entities in no scene don't
count. It returns at most once a tick: one that unloads itself as it loads leaves
the world without a scene until the next.
A match can't load a local startup scene. When startup is local, a match whose
last scene unloads ends there. Every machine in it goes back offline and gets
`Disconnected` with the reason `Ended` (see [Matches](#doc-multiplayer--matches)).
Local state carries on as it was.
```csharp
// Sets up each arena. The floor joins that arena.
event(Spawned) SetupArena(Arena arena)
{
Spawn(Floor { size = arena.size });
}
system Collapse(Arena arena)
{
if (arena.size <= 0) Scene.Unload(this);
}
```
Each button below loads a `Room`, or unloads the one that's there. A `Spawned` handler furnishes a room with four balls as it loads. They're spawned for the room, so they join it, and unloading it takes them with it.
**Rooms that load and unload** ([Run example](https://tide-engine.dev/examples/scenes/?stats))
```tide
settings { title = "Scenes"; tickRate = 30; maxPlayers = 1; }
scene Main { }
// A scene's fields are its state. Each loaded Room is an entity with a Room.
scene Room
{
int slot;
}
component Ball
{
float2 position;
float2 velocity;
int slot;
}
singleton Slots { List rooms = [default, default, default]; }
command Toggle { int slot; }
float2 Center(int slot)
{
return float2((slot - 1) * 1.3, 0);
}
command(Toggle toggle, PlayerID sender) LoadOrUnload(mut Slots slots)
{
if (toggle.slot < 0 || toggle.slot > 2) return;
if (slots.rooms[toggle.slot] == default)
slots.rooms[toggle.slot] = Scene.Load(Room { slot = toggle.slot });
else
{
// Unloading destroys the room and every entity spawned into it.
Scene.Unload(slots.rooms[toggle.slot]);
slots.rooms[toggle.slot] = default;
}
}
// Sets each room up as it loads. These spawns join that room.
event(Spawned) Furnish(Room room)
{
for (var i = 0; i < 4; i++)
{
Spawn(Ball { position = Center(room.slot), slot = room.slot,
velocity = float2(Math.Cos(i * 1.9 + room.slot), Math.Sin(i * 1.9 + room.slot)) * 0.9 });
}
}
system Bounce(mut Ball ball, Time time)
{
ball.position += ball.velocity * time.dt;
var offset = ball.position - Center(ball.slot);
if (Math.Abs(offset.x) > 0.4) ball.velocity.x = -Math.Sign(offset.x) * Math.Abs(ball.velocity.x);
if (Math.Abs(offset.y) > 1) ball.velocity.y = -Math.Sign(offset.y) * Math.Abs(ball.velocity.y);
}
local singleton Count { int balls; }
view Buttons(Slots slots, mut Count count)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, 0.2), 2.2);
count.balls = 0;
GUI.SetTheme(GUITheme { radius = 6 });
for (var slot = 0; slot < 3; slot++)
{
var loaded = slots.rooms[slot] != default;
Draw.WireRoundRect(Center(slot), float2(1.1, 2.3), 0.1, 0.03, loaded ? Color(0.98, 0.75, 0.14) : Color(0.24, 0.25, 0.27));
var corner = Draw.WorldToScreen(Center(slot) + float2(-0.55, -1.3));
var width = Draw.WorldToScreen(Center(slot) + float2(0.55, 0)).x - corner.x;
if (GUI.Button(Rect(corner.x, corner.y, width, 32), loaded ? "Unload" : "Load")) Send(Toggle { slot = slot });
}
}
view Balls(Ball ball, mut Count count)
{
Draw.Circle(ball.position, 0.1, Color(0.18, 0.83, 0.75));
count.balls += 1;
}
view Total(Count count)
{
Draw.SetScreen();
Draw.Text($"{count.balls} balls, in the rooms that are loaded", float2(16, 14), 16, Color.white);
}
```
## Which scene owns what
A spawn joins the scene of the entity the code is running for. In a handler, that's the entity the event was sent to, so the floor above joins the arena it was spawned for. A spawn into a scene that's unloaded by the spawn's turn is never made, like the loot an enemy drops while its arena unloads. Code that isn't running for an entity, like a system that runs once per tick, spawns into no scene, and those entities live until they're destroyed.
A scene itself is never owned: it lives until it's unloaded, whoever loaded it.
Loaded scenes share their world: the same systems, singletons and `Time`.
## Heavy preparation
Put expensive deterministic setup inside a scene's `prepare(...)` block:
```csharp
singleton Geography
{
int completed;
int total;
}
scene Campaign
{
int seed = 42;
prepare(mut Geography geography)
{
geography.total = 3;
GenerateTerrain(seed, geography);
geography.completed = 1;
GenerateRoads(seed, geography);
geography.completed = 2;
GenerateSettlements(seed, geography);
geography.completed = 3;
}
}
```
The generation functions above are game code. A scene has at most one block,
and parentheses are required even with no dependencies: `prepare() { ... }`.
Scene fields and methods are available directly; `this` is the scene's entity.
Other data uses the same explicit parameters as match handlers. A component
parameter belongs to the root and must be supplied to `Scene.Load`; singletons
and queries keep their ordinary meaning.
Preparation runs for the initial scene and for later loads, before `Spawned`.
Its spawns belong to the scene and exist before the scene's `Spawned` handlers.
The match stops advancing ticks while this machine prepares; `Time` does not
advance. On hosts with background workers, views and networking keep running.
Views can read consistent progress snapshots between completed top-level
preparation statements. Progress fields are ordinary game data: the engine
doesn't infer a percentage, and a long helper or loop need not publish an
intermediate update.
```csharp
bool loading = !Scene.IsPrepared(campaign);
bool playerReady = Scene.IsPrepared(campaign, player);
```
The one-argument form checks completion on this machine. The player form reads
readiness acknowledged through the server's ordered commands, so match code can
decide when to admit a player to gameplay. Missing, unloaded and non-scene
handles return false. Scenes without a block finish immediately; their players
still acknowledge readiness. Local scenes support the one-argument form and
use ordinary `Spawned` setup.
Read match readiness from match code and views; synchronous local event
handlers operate on their recorded event state.
Every peer with the complete match independently prepares the same committed
state. The server resumes when its own preparation finishes. Slower peers catch
up from buffered ticks, using normal state recovery if needed. Waiting for
players, deadlines and kicks are game policy. In visibility-enabled matches,
clients receive the permitted prepared result from the server, because they may
lack private generation inputs.
Preparation is deterministic match code. It can call synchronous helpers,
change declared match data, query and spawn. It cannot access local state,
await, start async tasks, or load another scene, including through helpers and
sent events. Start follow-up work in `Spawned`. Trusted C retains its ordinary
determinism and thread-safety responsibilities.
Heavy work starts only for committed loads. Completed preparation becomes the
baseline for subsequent prediction and rollback. Leaving the match discards
unfinished work. Hosts without a background provider execute preparation
synchronously; sharded matches currently reject preparation blocks.
## Private scenes
Scenes are public by default. Give a match scene root an ordinary `Visibility`
component to restrict the scene and every entity it owns:
```csharp
scene Hand
{
PlayerID player;
}
event(PlayerJoined joined) DealIn()
{
var group = Visibility.CreateGroup(Audience.Only(joined.player));
Scene.Load(Hand { player = joined.player }, Visibility { group = group });
}
```
Use `Visibility.Set(group, audience)` to replace the scene's audience. The same
group can serve several scenes and ordinary entities. Audience changes are match
state, so only match code changes them. Local scenes belong to this machine and
do not take `Visibility`.
A scene whose group has `Audience.None` stays on the server. Including a player
supplies its current permitted state; excluding one conceals it. An entity's
group can restrict the scene audience further, and a component's policy can
restrict the entity audience further. These three scopes intersect; an inner
scope cannot broaden an outer one. See [State visibility](#doc-game--visibility) for
shared groups and component policies. The server simulates the complete match
and corrects clients where hidden simulation affects their permitted state.
---
Source: https://tide-engine.dev/game/visibility.md
Control Tide client state with scene, entity and whole-component visibility, shared audience groups, partial simulation and local availability events.
# State visibility
Visibility decides which match scenes, entities and components a player's machine receives. The server still runs the full match. A client predicts with the state it is allowed to have, and authoritative corrections supply consequences that its partial simulation could not reproduce.
The server's own machine is the exception: its player sees the whole match, as the server does, so that machine runs each tick once. Its views and local handlers see hidden entities and components too, and hear every event the match sends. Visibility keeps state from the other machines.
The API names below are provisional. Visibility applies to entities and whole components. To hide a card's face while keeping its back public, put the face in a separate component; individual fields do not have visibility rules.
## Share an audience
An `Audience` is a set of players. `Audience.All` includes everyone and `Audience.None` includes nobody. `Audience.Only(player)` selects one player; `Audience.From(players)` takes a `List`. An audience value has `Add(player)`, `Remove(player)` and `Contains(player)`, and two audiences are equal (`==`) when they have the same players.
A `VisibilityGroup` gives many entities one live audience:
```csharp
singleton Region { VisibilityGroup group; }
component Block { int kind; }
scene Main { }
event(Spawned) Setup(mut Region region, with Main)
{
region.group = Visibility.CreateGroup(Audience.None);
Spawn(Block { kind = 1 }, Visibility { group = region.group });
Spawn(Block { kind = 2 }, Visibility { group = region.group });
}
event(PlayerJoined joined) Admit(Region region)
{
Visibility.Set(region.group, Audience.Only(joined.player));
}
```
`Visibility.Set(group, audience)` replaces the audience for every entity using that group. Build an audience with all interested players before setting it. Changing an `Audience` variable after `CreateGroup` or `Set` does not change the group until another `Set` call.
For a voxel world, make each chunk an entity with a group of its own, and update the group's audience as players approach or leave. A player's machine is then sent the chunks it walks into and nothing of the rest; chunks nobody is near can be saved and destroyed ([Saving the match](#doc-game--files--saving-the-match)). For distant players on a map, give each player entity its own group and compute the observers in match code. The engine supplies the mechanism; the game chooses distances, teams, occlusion and update frequency.
An entity without `Visibility` is public, subject to its enclosing scene. A default `Visibility` uses an all-player group. `Visibility.DestroyGroup(group)` makes existing references to that group see nobody; a later group does not reuse the stale handle.
## Restrict a scene
Scenes use the same groups. Put `Visibility` on the loaded root:
```csharp
var group = Visibility.CreateGroup(Audience.Only(player));
var hand = Scene.Load(Hand { player = player }, Visibility { group = group });
```
The root's group limits every entity owned by that scene, including entities
spawned later. `Visibility.Set(group, audience)` updates them together. Use
`Audience.None` for a server-only scene, or share a group across multiple scenes
and entities. Scene ownership still controls loading and unloading; destroying
a group conceals its members without unloading them.
## Hide a component
Keep public and private data in separate components:
```csharp
component Card { int back; }
component CardFace { int rank; int suit; }
event(Spawned) ProtectFace(Owner owner, mut Visibility visibility, with CardFace)
{
visibility.Set(Audience.Only(owner.player));
}
```
The entity must carry `Visibility`. Set the restriction during construction, before initial state can be published; waiting for the next system tick can expose the initial component. Update the policy when the holder changes. `visibility.Set(audience)` restricts the whole component. It also accepts a shared group: `visibility.Set(handGroup)`. `visibility.Reset()` removes that override, so the component follows the entity again.
The effective audience is the intersection of the scene root's group, the entity's group and the component's restriction. An entity or component cannot broaden its enclosing scope. Ordinary transform parenting does not inherit visibility. A component outside a recipient's audience is absent on that client, including from queries and `Has()`; `without CardFace` can therefore match there.
For poker, keep the public card back on the entity and restrict `CardFace` to the holder. Put an undealt deck in an audience of nobody, or a private scene with no members. Membership, group contents and component overrides are server policy; clients receive their permitted state rather than the policy's private membership data.
`Time.seed` is public, and default `Random` state derives from it. Hiding card faces alone does not make a shuffle derived from that public seed unpredictable. A secret shuffle needs a private seed supplied authoritatively, with its RNG state and undealt deck kept restricted.
## Spatial parents
A public child can remain visible while its transform parent or the parent's `Transform` is hidden. The projected hierarchy cuts that private link. Where the visible subtree contains a permitted `Transform`, an internal placement anchor preserves its composed placement, including rotated nonuniform scales. The child's local transform values stay unchanged; no private parent entity or component payload is copied.
That derived placement is part of the permitted spatial state. A visible entity with no permitted `Transform` in its visible subtree does not receive an anchor just because its parent has one. Calling `world.LocalToWorld` on such an entity in a partial client can omit hidden influence. `world.Parent` reflects the projected links, so a concealed parent can appear null. Choose visibility for spatial state according to what players may infer from visible children.
## Availability and actual lifetime
Use `local event(Shown)` to initialize presentation when an entity or a handler's required components become available. It runs for arrivals, reveals and genuine spawns. `local event(Hidden)` removes presentation when that availability ends, and reads the last permitted state. The same forms accept `verified Shown` and `verified Hidden`.
`local event(Spawned)` and `local event(Destroyed)` describe actual match lifetime. Joining, revealing an existing entity or receiving a repair does not fabricate either event. A concealed entity's later destruction does not announce its death to a recipient who could not see it at destruction. [`Forgotten`](#doc-game--local-state--letting-go) remains the cleanup hook for local fields.
On the server's own machine, which sees the whole match, an entity only leaves as the match destroys it, so its handlers hear `Destroyed` rather than `Hidden` while its player keeps up with the server. Where that player takes the server's world whole (after a new build takes over, or once it fell behind), an entity that went in the ticks it skipped is `Hidden` there, and one that came is `Shown` without `Spawned`, as for a joining player. Another player's machine hears `Hidden` for an entity hidden from it, even when the match destroys it in the same tick, since it couldn't see it at its destruction. Its predicted handlers hear what its own run of a tick did, which can be the destruction of an entity the server hid in that tick; its `verified` handlers then hear `Hidden`. To let go of what local code keeps for an entity however it leaves a machine, use `Forgotten`, which every machine sends once.
Each handler's component requirements determine its availability. A handler reading `Card` can remain active while a handler reading `CardFace` becomes hidden. A `Shown` handler should prepare resources; a true `Spawned` handler can play the effect for a new object.
**Provisional delivery rule:** availability follows the endpoints delivered to local presentation. Changes inside one tick or between frames coalesce to their final availability, so adding, removing and adding a component before a frame cannot leave its presentation released. A correction that restores an entity or component runs `Shown` again; an unchanged replay does nothing. Predicted and verified handlers follow separate presentation endpoints, and their queries read the corresponding old or new endpoint. A local rebuild clears this history and prepares available objects again, so `Shown` initialization should reuse or replace existing resources safely.
## In a sharded world
In a [sharded world](#doc-multiplayer--shards--visibility), a group means the same on every shard: an entity in it is shown to the same players on whichever shard has it, and each shard sends its own players only what they may see. The groups are kept with the first shard. Code on another shard that creates, changes or destroys a group waits on the border for them, and other shards see the change a tick or two later.
## Consequences across a visibility boundary
The server may simulate a hidden object affecting a public one. The client receives the corrected public result; it does not need the hidden cause. Design public state to contain the consequences players need, such as damage, a revealed projectile or a public combat log.
Custom `local event(...)` and `local event(verified ...)` handlers currently hear events produced by the client's permitted simulation. They are not a general authoritative server-to-audience event channel. A hidden system's custom event is not automatically forwarded to other players. Choose public fields and input payloads deliberately, and decide what each command handler publishes.
Commands execute only on the authoritative server in this path; clients receive permitted results. Projected clients also cannot become a new host: host migration needs a trusted complete-state handover, which is not currently implemented.
Match task continuations and opaque `Resident` state stay on the authoritative server in a visibility-enabled match. They are not copied into projected clients. Publish the state needed for presentation and prediction in ordinary permitted components. Public match singletons remain public, so keep per-entity secrets in components or private scenes.
The physics packages keep their worlds in `[Native]` fields, the library's own state: Box2D's `Physics.image`, Box3D's `Resident`, both packages' handles, collider and rewind-history lists. A client doesn't receive those. Its world arrives with them at zero, as on a shard an entity comes to, and the package makes its physics world again from the bodies the client has. A hidden body is absent from that world, so what it does to visible ones comes with the server's corrections. Rewind history starts again on a client after each correction, so a client's own `Physics.Rewind` can fail where the server's succeeds: hits are decided on the server.
On a client, `Visibility.CreateGroup` can't number a group: the server does. What a client's own tick puts in a group without the client's player stays out of its projection, as it's out of the server's projection for it; what it puts in one with its player is visible to it. `Visibility.Set` does nothing there, so something coming into or going out of sight always arrives as a correction.
See [Scenes](#doc-game--scenes--private-scenes) for scene ownership and audiences and [Networking](#doc-multiplayer--networking--who-sees-what) for verification and corrections.
---
Source: https://tide-engine.dev/game/endless-worlds.md
Build an endless world of blocks in Tide: chunks as entities with grids, each player sent only the chunks near them, dimensions as scenes, the server's store for what nobody is near, read off the tick's thread and listed by prefix, chunk faces meshed across their edges, and far ground drawn from the seed with far regions of what players built.
# Endless worlds
A world of blocks that goes on as far as players walk, in several dimensions, played together: more than any machine holds at once, and more than any player should be sent. Tide has no world type for it. It's made of what every game has, put together as this page shows: entities, grids, [State visibility](#doc-game--visibility), [Scenes](#doc-game--scenes) and [the server's store](#doc-game--files--saving-the-match).
`bench/voxels` in the engine's repository is such a game, with bots that fly, dig and build across it, and a version people play. The code below is shortened from it. The names of the store's calls and of visibility are provisional.
## Chunks are entities
A chunk is an entity with a grid of its own, found by its place:
```csharp
component Chunk
{
int3 at; // In chunks
int dimension;
Grid3 blocks = Grid3(16, 16, 16);
Stage stage; // Asked for, missing from the store, or made
int edits; // Changes players made
}
```
An entity is what the engine already serves one at a time: each player is sent only the entities they may have, `Destroy` unloads one, an event can go to one, and a sharded world splits its entities by place. One grid for a whole world would have none of that.
A chunk is found by its place with an indexed loop: the loop's guard is one key of the place's three numbers and the dimension, and the loop visits only the chunks there ([Systems](#doc-game--systems)).
```csharp
Block At(int dimension, int3 cell, query (Chunk chunk) chunks)
{
var at = int3(cell.x >> 4, cell.y >> 4, cell.z >> 4);
mut var found = Block.Air;
indexed foreach (var row in chunks)
{
if (row.chunk.at.x != at.x || row.chunk.at.y != at.y || row.chunk.at.z != at.z) continue;
if (row.chunk.dimension == dimension) found = row.chunk.blocks[cell.x & 15, cell.y & 15, cell.z & 15];
}
return found;
}
```
## Dimensions are scenes
Each dimension is a scene, loaded once, with a seed of its own. A chunk spawned by code that runs for the dimension's entity is in that scene, so unloading a dimension destroys its chunks.
```csharp
scene Dimension
{
int number;
int seed;
}
```
## Who has which chunks
Each chunk has a visibility group of its own, whose audience is the players near it. A player is sent the chunks they come near and nothing of the rest, and a player's machine drops a chunk once its group no longer has them.
The code that decides it is the server's alone. It runs for components no player may have, so a player's machine runs none of it and has nothing of it to get wrong:
```csharp
// On each dimension's entity: who is where, and its chunks by their places
component Streamer
{
Map watching;
Map chunks;
List making; // Chunks asked for and not yet made, in the order they were asked for
Map asking; // Players whose box isn't all asked for yet: how far through it they are
int asked; // Chunks spawned this tick
}
// On each chunk: who wants it
component Seen
{
VisibilityGroup group;
Audience audience;
bool shown; // Made, and its group has its audience
bool dear; // It has ground in it: what making it costs
bool ready; // The store had nothing for it...
bool go; // ...and it may be made this tick (Pace, below)
int emptied; // The tick its last player left
}
```
Both are restricted to `Audience.None` where they're added (`visibility.Set(Audience.None)`). A player's moves tell their dimension which chunk they're in, and its handler adds them to the chunks their box of chunks took in and removes them from those it left. A chunk nobody has yet is spawned with an audience of nobody, and the group's audience is set once its blocks are made, so no player ever has a chunk that isn't.
The box is asked for nearest first: a ring of chunks around the player's own at a time, the player's own height before the ones above and below. The store answers in the order it's asked, so what a player stands in and looks at is there before the edge of their view; and around each ring, each chunk beside the one before it, because a player is sent new entities in the order they were spawned and chunks side by side are alike, which makes what's sent smaller.
A whole box isn't spawned in one tick. A view of 96 cells each way is 845 chunks; at twice that it's 3,125 and at three times 6,845, and a tick that spawns them all, each with a group and a load asked of the store, is as long as they are many (9 ms for 3,125). The handler spawns up to an allowance of new chunks for its dimension each tick and remembers how far through the box it got; the player's move in the next tick (which says where they are every tick) goes on from there:
```csharp
event(Want want) Watch(mut Streamer streamer, Worlds worlds, Time time, mut World world)
{
var known = streamer.watching.TryGet(want.player, out var from);
var going = streamer.asking.TryGet(want.player, out var gone);
var moved = !(known && Same(from, want.to));
if (!moved && !going) return; // Where they were, with their whole box asked for
// ...moved: the chunks the old box had and the new one hasn't lose the player
mut var place = 0; // Places of the box gone through, nearest first
mut var full = false;
// for each place of the box, nearest first, while !full:
// place++; if (place <= (moved ? 0 : gone)) continue;
// a chunk that's there: the player joins its audience, while the tick's joins are under their allowance
// none, and streamer.asked < worlds.ask: Spawn it, ask the store for it, streamer.asked += 1
// none, and the tick's allowance is spent: place--; full = true;
if (full) streamer.asking[want.player] = place;
else streamer.asking.Remove(want.player);
streamer.watching[want.player] = want.to;
}
```
The allowance costs a player nothing while it's more than the store answers in a tick (256): the box is asked for faster than it can be made, in the same order. `bench/voxels` spawns 1,024 a tick, so the default view is still asked for at once.
Chunks that are already there cost a tick something too: each one a player joins or leaves is its `Seen` and its group's audience changed, and the world's check of that change, about a microsecond each. A player who comes where others are joins a whole view of them in one tick, and one who goes leaves one; several players coming or going in one tick are several views. So joins have an allowance of their own, and so have leaves, eight times the spawns' in `bench/voxels` (8,192 a tick for a dimension), the box's places gone through the same way. A box left goes in a list (`Streamer.leaving`, the player and the chunk they were in), and each tick takes the allowance's worth of its chunks from the oldest box first, passing over those inside the box the player has now, so one who comes back keeps what they came back to:
```csharp
void Depart(mut Streamer streamer, mut World world, Worlds worlds, int tick)
{
// for each box in streamer.leaving, oldest first, while the tick's leaves are under the allowance:
// for each of its places from box.place on: the chunk there, if it's outside where the player is now
// (streamer.watching) and has them, loses them
// a box gone through leaves the list; one that isn't keeps its place
}
```
The handler that sees the move runs it, and so does a system each tick, as a player who left the dimension sends it nothing more to go on by. What the game chooses here is the audience: a chunk is a leaving player's a few ticks longer than their box says, never a tick less than it, and a player who joins has the nearest of a box first.
A player's view taken in or let go over two ticks costs that player a round trip: what they're sent of it is a second repair, which waits for the first to be acknowledged. With an allowance of four times the spawns' (4,096), a view at three times the default radius (6,845 chunks) went over two ticks, and with eight bots hopping the server's longest updates lost their handlers' share (6 to 9 ms), but a player hopping to where another is had all of their box 2 ticks later (40 for 38), and a bot's verified world was 69 ticks behind the server's at most, for 59. At 8,192 no lone view is split: the allowance holds the ticks in which several players come or go at once.
The server finds its chunks in `Streamer.chunks`, not with a query: a spawn joins the tables only once its tick's changes are applied, so two players who come near one place in one tick would otherwise make two chunks there. `Spawn` gives the entity at once, but its components are there only once the tick's changes are applied: `world.Has(chunk)` is false for a chunk another player's coming spawned this tick, and what's set on it is lost. The handler stops there for the tick, as if its allowance were spent, and goes on from that place in the next, when the chunk takes the player.
## Making chunks on every core
A system that fills each new chunk from its dimension's seed, and then shows it to the players waiting for it, runs across every core, in a game that hides state as in any other ([The schedule](#doc-game--schedule--splitting-across-threads)):
```csharp
system Generate(mut Chunk chunk, mut Seen seen)
{
if (chunk.stage != Stage.Missing || !seen.go) return;
// ...the chunk's blocks, from Math.Perlin of the seed
chunk.stage = Stage.Made;
Visibility.Set(seen.group, seen.audience);
}
```
Each chunk's blocks are its own, and the groups' audiences its rows set are set after them, in the chunks' order, as one thread would. Making or ending groups in the same system keeps it on one thread, so a game makes a chunk's group where it spawns the chunk.
The chunks a tick makes go to every thread, wherever they are among the chunks: a system that starts with a test most of its entities fail (`if (...) return;`) hands out the ones that pass. A tick that made every chunk the store answered for would be as long as they are many, so the game says how much a tick makes (`seen.go` above):
```csharp
// On each dimension's entity: the chunks the store had nothing for, in the order they were asked for, up to
// `make` a tick by what each costs. One of air costs 1, one with ground in it (caves' noise, cell by cell) 10
system Pace(mut Streamer streamer, Worlds worlds, mut World world)
{
mut var left = worlds.make;
mut var kept = 0;
for (var i = 0; i < streamer.making.count; i++)
{
var chunk = streamer.making[i];
mut var seen = world.Get(chunk);
if (seen.go || seen.shown) continue; // Made, or let be: off the line
if (seen.ready && left > 0) // The store answered: nothing kept of it
{
left -= seen.dear ? 10 : 1;
seen.go = true;
world.Set(chunk, seen);
continue;
}
streamer.making[kept] = chunk; // Still asked for, or over this tick's allowance
kept++;
}
while (streamer.making.count > kept) streamer.making.RemoveAt(streamer.making.count - 1);
}
```
`bench/voxels` makes 480 a tick: 48 chunks with ground, about 7 ms of one thread, 1.5 ms across twelve.
## Keeping what nobody is near
A chunk is asked for from the store as it's spawned, and made from the dimension's seed only if the store has nothing:
```csharp
var made = Spawn(Chunk { at = at, dimension = dimension.number }, visibility, Seen { group = group });
streamer.chunks[KeyOf(at)] = made;
Storage.Load(SavedAs(dimension.number, at), made);
event(Loaded loaded) Fill(mut Chunk chunk, mut Seen seen)
{
if (chunk.stage != Stage.Asked || loaded.failed) return; // Unreadable: asked again later, never made over
if (loaded.found && Grid3.FromBytes(loaded.bytes) is Grid3 saved)
{
chunk.blocks = saved.Copy();
chunk.stage = Stage.Made;
Visibility.Set(seen.group, seen.audience);
return;
}
chunk.stage = Stage.Missing; // Made from the seed by a system
}
```
A chunk nobody has had for a while goes. It's let go in an event, which runs after the tick's moves, so a player who came back to it in the same tick keeps it:
```csharp
system Idle(Seen seen, Chunk chunk, Time time)
{
if (seen.audience == Audience.None && chunk.stage == Stage.Made && time.tick - seen.emptied >= LINGER) this.Send(Expire { });
}
event(Expire) Drop(Seen seen, Chunk chunk)
{
if (seen.audience != Audience.None) return;
if (chunk.edits > 0) Storage.Save(SavedAs(chunk.dimension, chunk.at), chunk.blocks.ToBytes());
Visibility.DestroyGroup(seen.group);
this.Destroy();
}
```
`ToBytes` writes only a grid's chunks that have something in them, and runs of one block short: a chunk of air is a few bytes ([Grids as bytes](#doc-language--grids--grids-as-bytes)). A system that writes a chunk players changed into the store every while, as well as when it goes, keeps a server that stops from losing more than that while. A load whose answer never comes (the server stopped first) leaves the chunk waiting: ask again after a while, as `bench/voxels` does.
A box a player left empties in one tick, so all of its chunks would go in one tick, a linger later: saved, forgotten and destroyed, 12 ms for 3,125 of them. Where the handler takes a player out of the box they left, `bench/voxels` gives each tick's allowance of the dimension's emptied chunks an `emptied` a tick later than the ones before (a tick and a count on the dimension's entity), so a box goes over as many ticks as it was asked for in. A border's row of chunks still goes together: spread by where each chunk is instead, every tick would have chunks going, and a tick in which entities come or go costs the server more than one in which none do.
`Idle` writes nothing while it waits: `emptied` is a tick, not a counter. A system that counts in every chunk every tick changes every chunk every tick, and the server's checks cost what changes.
The server reads and writes the chunks' files on a thread of their own, after the tick that asked: a player's first view of fresh ground asks for hundreds of chunks in one tick, and the tick doesn't wait for the disk. Their answers come over the next ticks, 256 a tick in a game that hides state (64 in one that doesn't, whose answers go to every player).
What a dimension has saved can be listed, a page of keys at a time, for a map of where players built or to move a world's saves elsewhere: `Storage.List($"chunks/{dimension.number}/", this)` answers with a `Listed` event, and the next page is asked for after its last key ([Saving the match](#doc-game--files--saving-the-match)). Keys made of folders (`chunks//...`) keep a listing to the folder its prefix names.
A match task can wait for the store instead of handling its events, which keeps a job of several steps in one place. A dimension's map of saved chunks, a page at a time:
```csharp
async void Survey(mut Atlas atlas, int dimension)
{
mut var after = "";
mut var going = true;
while (going)
{
var page = await Storage.List($"chunks/{dimension}/", after);
if (page is StorageKeys keys)
{
atlas.saved += keys.keys.count;
going = keys.more;
if (going) after = keys.keys[keys.keys.count - 1];
}
else going = false; // The store couldn't be listed
}
}
```
The task goes on in the tick each answer is given to, the same on every machine, and what it waits for is kept in it: a task whose entity goes ends with it, its answer changing nothing, and a rewind asks again for what the rewound tasks wait for ([Waiting for the answer in a task](#doc-game--files--waiting-for-the-answer-in-a-task)).
## Drawing what's far
A chunk's faces are made into a mesh by a `local worker`, off the frame, and kept in the chunk's `local` fields ([Local state](#doc-game--local-state), [Async and tasks](#doc-game--tasks)); they're made again when its blocks change. Meshes outside the view aren't drawn ([frustum culling](#doc-game--3d--frustum-culling)).
### Faces across a chunk's edges
A worker reads only what it's handed. Given a chunk's own grid, everything past its edge reads as air, so every block on its edge has a face there: two faces between every pair of solid chunks, hidden and drawn all the same. Hand it the neighbours' grids too, and those faces aren't made:
```csharp
local worker Built Faces(Grid3 blocks, Grid3 east, Grid3 west, Grid3 above,
Grid3 below, Grid3 north, Grid3 south)
{
// ...for each block, the one beside it, in this chunk or across its edge
var right = x < 15 ? blocks[int3(x + 1, y, z)] : east[int3(0, y, z)];
if (Shows(block, right)) Face(vertices, indices, ...);
// ...and each of the chunk's own sides as one number, for its neighbours
}
async void Remesh(mut Chunk chunk, Grid3 east, Grid3 west, Grid3 above, Grid3 below,
Grid3 north, Grid3 south)
{
var built = await Faces(chunk.blocks, east, west, above, below, north, south);
chunk.mesh = Mesh(built.vertices, built.indices);
}
// The blocks of the chunk at a place, or no grid's, all air
Grid3 Near(query (Chunk other) chunks, int3 at, int dimension)
{
indexed foreach (var row in chunks)
{
if (row.other.at.x != at.x || row.other.at.y != at.y || row.other.at.z != at.z) continue;
if (row.other.dimension != dimension) continue;
return row.other.blocks.Copy();
}
return default;
}
view Chunks(mut Chunk chunk, query (Chunk other) chunks)
{
// ...when its faces are to be made
var d = chunk.dimension;
chunk.job = Remesh(chunk, Near(chunks, chunk.at + int3(1, 0, 0), d), Near(chunks, chunk.at - int3(1, 0, 0), d),
Near(chunks, chunk.at + int3(0, 1, 0), d), Near(chunks, chunk.at - int3(0, 1, 0), d),
Near(chunks, chunk.at + int3(0, 0, 1), d), Near(chunks, chunk.at - int3(0, 0, 1), d));
}
```
The view finds each neighbour by its place, an indexed loop over the chunks it has, and hands the task the neighbours' grids, which are the task's own copies ([Async and tasks](#doc-game--tasks--what-a-task-keeps)): a neighbour that changes while the faces are made doesn't change them. Handing the task its own chunk as `mut` changes only the chunk's local fields, so the loop is still indexed by the chunks' places. Each mesh gives back its chunk's six sides and its neighbours' sides toward it as it read them, each as one number, kept in a map of this machine's. Its neighbours' meshes have been made from blocks of their own time, so whichever of two neighbours is made last compares the two: a neighbour made from another side of this chunk than this mesh's has its faces made again, and so has this chunk where it read another side of the neighbour than the neighbour's mesh was made from. That holds whichever was begun first, and when a side changes and changes back while one of them is being made. A change at the edge makes them again at once; a chunk that came or went, once its other neighbours have stopped coming, since a view's worth of chunks comes over many frames and the faces between them are hidden ones. Chunks that come together read each other's blocks, and each one's faces are made once. A chunk whose side is all air has no faces its neighbour hides: a chunk of sky has sides of air, its coming changes nobody's faces, and a block built under it changes none of its faces. In `bench/voxels` this draws fewer than a third of the triangles it did, with the same picture.
When a player arrives somewhere, hundreds of chunks want faces at once. The chunks around the player go first: each call says its `priority:` ([Async and tasks](#doc-game--tasks--which-call-starts-first)), and the same `Faces` serves them all.
```csharp
// In Remesh, which the view hands a priority
var built = await Faces(chunk.blocks, east, west, above, below, north, south, priority: priority);
// In the view: how far the chunk is from the player's, in chunks
var away = Math.Max(Math.Max(Math.Abs(chunk.at.x - sight.chunk.x), Math.Abs(chunk.at.z - sight.chunk.z)),
Math.Abs(chunk.at.y - sight.chunk.y));
var priority = !changed ? WorkerPriority.Background // Only a neighbour came or went: mostly hidden faces
: away <= 2 ? WorkerPriority.Urgent : WorkerPriority.Normal;
```
The ground far off (below) is one big mesh, made with `WorkerPriority.Background`: after the chunks' faces, and never so late that it's missing for long, as a background call waits for at most sixteen others to start.
Two things keep that picture whole. A block dug at a chunk's edge uncovers a face of the neighbour's, which only the neighbour's new mesh has: the chunk keeps its own new mesh aside until the neighbour's is made, and the two show in the same frame, rather than a hole into the neighbour for a frame or two. And a chunk that leaves this machine has the faces toward it made again, in a `local event(Forgotten)` handler, which keeps its place in a local field, as the match's fields are gone by then. `Forgotten` comes whichever way the chunk leaves this machine: hidden from its player, or destroyed, which is the only way on the hosting machine, whose views see the whole match.
### What players built far off
Past the chunks a player has, the ground can be drawn from the dimension's seed: every machine has the seed, so the same hills the server would make are drawn there with nothing sent for them. What players built is sent as **far regions**: an entity for each 8 by 8 chunk columns, with a summary of each column of 8 by 8 cells that players changed, its highest block and how high it is.
```csharp
struct Column
{
byte at; // In its region
Block top;
int height;
}
component Far
{
int2 at;
int dimension;
List columns; // Only those unlike the seed's
int version; // Counts the times they changed
}
```
A far region is an entity of its own, not a part of its chunks, because its audience is wider than theirs: the players within its far distance (768 cells in `bench/voxels`, where the chunks go out about a hundred). A component can be restricted further than its entity, never wider. Each has a visibility group, kept as a chunk's is, whose audience is set only while it has columns, so a world nobody built in sends nobody anything for it. The server's side is in components restricted to nobody, as the chunks' is: what the region is as it changes, and who wants it.
The server keeps the summaries as players change chunks. A handler of the change that only the server runs, declared after the one that changes the block, tells the region the top of the chunk's part of that column; the region works out the column's top from it (higher where something was built above it, looked for below where it was dug out), and keeps it only where it isn't what the seed makes there:
```csharp
// ...after Apply, which changes the block: handlers of one event run in the order they're declared
event(Change change) Note(Chunk chunk, mut Seen seen, query (Far far, Summary summary) regions)
{
// The quarter of the chunk the cell is in, whose top goes to its far region as a Top event
Summarise(chunk, seen, (change.cell.z & 15) / 8 * 2 + (change.cell.x & 15) / 8, regions);
}
```
What changed goes to players at a pace, so building doesn't flood anyone. A region whose columns changed goes into its dimension's line once (`queued`), and every half second each dimension sends the regions in its line, in the order they changed, 64 columns at most in all: a player far off gets at most two corrections a second of it, however much is built.
```csharp
system Publish(mut Streamer streamer, Worlds worlds, Time time, mut World world)
{
if (streamer.line.count == 0 || time.tick % worlds.gap != 0) return;
mut var budget = worlds.pace;
while (streamer.line.count > 0 && budget > 0)
{
var region = streamer.line[0];
mut var done = true;
world.Edit(region, summary), world.Edit(region, far), world.Edit(region, seen)
{
// Far.columns, a step nearer the server's own: `all` once they're alike
var changes = Follow(far.columns, summary.columns, budget, out var all);
budget -= changes;
if (changes > 0) far.version += 1;
done = all;
if (all) summary.queued = false; // Into the line again at its next change
// Shown once it has columns; hidden once it has none left to send, not while a removal has used
// the last of the budget before an addition
var shown = far.columns.count > 0 || (seen.shown && !all);
if (shown != seen.shown)
{
seen.shown = shown;
Visibility.Set(seen.group, shown ? seen.audience : Audience.None);
}
}
if (!done) break;
streamer.line.RemoveAt(0);
}
}
```
A far region comes and goes as chunks do, a while after nobody is within its distance, and is kept in the server's store: `Storage.Save($"far/{dimension}/{at.x}_{at.y}", Json.Write(summary.columns).ToBytes())`, read back with `Json.Read>(loaded.bytes)`. It's saved apart from its chunks, so a server that stops between the two saves can leave a region with a build its chunk didn't keep: a region read back looks again at the chunks the server has, and a chunk made from the seed tells its region what it has where the region has a column, so what the region says comes back to what the chunks have. A player's machine draws a column where a far region it has gives one, in place of the seed's square, with walls down to the seed's ground around it, and the seed's ground everywhere else; where the player's own chunks are, it draws only what's above or below them.
## What it costs
`bench/voxels` on one machine (a 12-core desktop, one core of it: the tick is one thread's work), 60 ticks a second, 50 ms each way with a datagram in a hundred lost, bots that fly, dig, build and change dimension every 20 seconds (`notes/voxels.md`, At scale, has every table and how each was measured; 2026-11-16):
| | 8 players, 845 chunks each | 3,125 chunks each | 6,845 chunks each | 32 players | 32, far apart | 64 players |
|---|---|---|---|---|---|---|
| Chunks the server holds | 6,490 | 16,941 | 32,827 | 12,669 | 28,549 | 17,598 |
| Server's update, median / 99th percentile / longest, ms | 0.28 / 2.9 / 6 | 0.70 / 7.6 / 12 | 1.4 / 10.5 / 20 | 1.5 / 8.2 / 15 | 5.4 / 16.5 / 24 | 3.6 / 16.2 / 28 |
| Server, ms of every second | 28 | 66 | 119 | 104 | 300 | 214 |
| Sent to each player, KB a second | 22 | 57 | 116 | 25 | 24 | 28 |
| A player's machine's ticks, 99th percentile, ms | 0.9 | 2.5 | 4.4 | 1.4 | 1.4 | 1.9 |
| A whole view on a player's machine after a dimension hop, ticks | 25 | 43 | 52 | 26 | 30 | 24 |
(The first three columns and 32 far apart are of the build that asks for a box over a few ticks and packs a whole view off the tick's thread, on every core; the two others are of the build before it.)
- **What holds 60 ticks a second**: 32 players at the default view (96 cells each way) with room, 64 at the edge of a frame when they start together; 8 players at twice the radius with room, and at three times but for its longest updates (20 ms: the tick a player joins or leaves every chunk of a view others are in). Players far apart, who share no chunk, cost the server more than players together: what it pays goes with the chunks it holds. 32 apart hold 60 Hz while nobody hops (11.6 ms at the 99th percentile). Threads change none of it.
- **A player is sent** 17 KB a second flying over fresh ground, 22 to 25 with a dimension hop every 20 seconds, 5 standing, whatever the number of players. A chunk is about 140 bytes as sent, a thirtieth of its cells. Players who turn every tick, as a mouse does, add 8 to 19 KB a second to what each is sent.
- **A whole view arrives in a third of a second**: one player hopping into a dimension nobody is in has its 845 chunks 20 ticks after the hop (21 with a datagram in a hundred lost, 29 with five), nearest first; at twice the radius, 40. Seven of those ticks are the player's own lead on the server.
- **A dimension nobody is in costs nothing**, and eight players a dimension each cost what eight far apart in one do. Leaving a dimension frees its chunks once nobody has been near them for the linger, and the server lets go of the memory that held nothing else: about a quarter of what the dimension took in this game's runs, as memory that still holds one small value of another chunk stays.
- **A long session is level**: 8 players flying outward for 20 minutes hold 9,000 chunks and far regions in 24 MB from the fourth minute on, the server's update 1.2 ms on average throughout.
- **A player's own frame** at 1920 by 1080, paced at 60 Hz, takes 0.7 ms of CPU at the default view of the version to play (405 chunks) and 2.1 ms with 3,125. The chunks around the player have their faces 0.12 s after a hop at any view, and all of them are there after 0.15 s (405 chunks), 0.45 s (1,445) and 1 s (3,125).
- **What breaks first**: the one thread for what isn't chunks being made. A tick in which a player joins or leaves the audiences of a whole view of chunks that are already there is 18 ms for 6,845 of them, and what a player is sent of a whole view is read on the tick's thread, 2 to 4 ms a view (its packing is another thread's, and a view of more than 4 MB goes out a tick later for it). Eight players who hop together have the last tenth of their views a few ticks later than one who hops alone: the server starts as many whole views in an update as fit in it.
The engine's notes (`notes/voxels.md`) have the rest, and what's still missing.
---
Source: https://tide-engine.dev/game/tasks.md
Write Tide async functions and tasks that wait for time, ticks, frames or other async calls, in the match or local presentation.
# Async and tasks
Some code takes longer than a tick: a countdown before a round, an ability that ends after a moment, a sign-in that waits for a service. An `async` function can wait, with `await`, and pick up where it stopped. Calling one starts a **task**, which goes on by itself, tick after tick or frame after frame, until it's done.
```csharp
singleton Round
{
int count;
}
event RoundStarted { }
// Counts down a second at a time, then the round begins.
async event(RoundStarted) Countdown(mut Round round)
{
for (var i = 3; i > 0; i--)
{
round.count = i;
await Wait.Seconds(1);
}
round.count = 0;
}
```
The round below is one task: it counts down a second at a time, lets the runners go for five seconds, and ends. While they run, tap a runner. Each dash is a task of its own, which speeds its runner up, waits, and slows it down again.
**A countdown, and a dash** ([Run example](https://tide-engine.dev/examples/tasks/?stats))
```tide
settings { title = "Tasks"; tickRate = 30; maxPlayers = 1; }
component Runner
{
float angle;
float speed = 1;
}
singleton Round
{
int count; // 3, 2, 1 while it counts down
bool running;
bool busy;
}
event RoundStarted { }
event Boost { }
command StartRound { }
command Dash { }
scene Main { }
event(Spawned) Setup(with Main)
{
for (var i = 0; i < 3; i++) Spawn(Runner { angle = i * 2.1 });
}
command(StartRound start, PlayerID sender) Begin(mut Round round)
{
if (round.busy) return;
round.busy = true;
Send(RoundStarted { });
}
// One task for the whole round: it waits, and goes on where it stopped.
async event(RoundStarted) Countdown(mut Round round)
{
for (var i = 3; i > 0; i--)
{
round.count = i;
await Wait.Seconds(1);
}
round.count = 0;
round.running = true;
await Wait.Seconds(5);
round.running = false;
round.busy = false;
}
command(Dash dash, PlayerID sender) DashRunner(with Runner)
{
this.Send(Boost { });
}
// A task for each runner that dashes. It gets the runner again after the
// wait, as it is then, and ends by itself if the runner is gone.
async event(Boost) Sprint(mut Runner runner)
{
runner.speed = 4;
await Wait.Seconds(0.6);
runner.speed = 1;
}
system Run(mut Runner runner, Round round, Time time)
{
if (round.running) runner.angle += runner.speed * time.dt;
}
view Track(Round round)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, -0.2), 2.3);
Draw.WireCircle(float2(0), 1.5, 0.03, Color(0.24, 0.25, 0.27));
var word = round.count > 0 ? $"{round.count}" : round.running ? "GO" : "";
Draw.Text(word, float2(0), 0.9, Color.white, Anchor.MiddleCenter, Font.Bold);
}
view Runners(Runner runner, Round round, Devices devices)
{
var at = float2(Math.Cos(runner.angle), Math.Sin(runner.angle)) * 1.5;
Draw.Circle(at, 0.16, runner.speed > 1 ? Color.white : Color(0.98, 0.75, 0.14));
var pointer = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position));
if (round.running && devices.pointer.press.down && Math.Distance(pointer, at) < 0.4) this.Send(Dash { });
}
view Controls(Round round)
{
Draw.SetScreen();
Draw.Text(round.running ? "Tap a runner to make it dash" : "A round is a task that waits",
float2(16, 14), 16, Color.white);
GUI.SetTheme(GUITheme { radius = 6 });
GUI.Disabled(round.busy)
{
if (GUI.Button(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Start the round")) Send(StartRound { });
}
}
```
## Async functions
`async` before a function lets it wait. Its declaration names the completion value: `async int`, `async string`, or `async void` for nothing. Calling it returns a started task handle.
```csharp
async int Doubled(int x)
{
await Wait.Ticks(1);
return x * 2;
}
```
A call can be awaited immediately, kept, or discarded:
- **`await` it** for its value, from async code: `var n = await Doubled(3);`. The code waits there until the call is done, then goes on with its value. `await` binds like `try`, so `await Doubled(3) + 1` adds 1 to the value.
- **Keep its handle**: `var build = BuildMesh(voxels);`. The operation has already started. `await build` gets its result; `build.Cancel()` requests cancellation.
- **Call it as a statement** to start a task: `Doubled(3);`. The task goes on by itself, and the code that started it doesn't wait. A started task's value is dropped.
Match calls produce `Task`; local calls and local workers produce `LocalTask`. Void uses `Task` or `LocalTask`. The type preserves the complete declared result: an `async MeshData Build(...) fails MeshError` call produces `Task` or `LocalTask` in its world. Optional results use `Task` or `LocalTask`.
Copied handles name the same operation. Multiple tasks can await it, and repeated awaits get independent ordinary value copies of the same result. Awaiting a handle never restarts its operation.
An async function that can fail works as any function that fails (see [Errors](#doc-language--errors)): `await Fetch(name) ?? "nobody"`, `if (await Fetch(name) is string token) { ... }`, `try await Fetch(name)`, and `await Fetch(name)!`.
## Async handlers
`async` before an event handler makes each event start a task, which can wait like an async function:
```csharp
async event(Spawned) Arm(mut Turret turret)
{
await Wait.Seconds(2); // Ready two seconds after it's spawned
turret.armed = true;
}
```
Local handlers can be async too: `local async event(...)` (see [Local state](#doc-game--local-state)). A local handler of one of the match's events can't be yet: it starts a task by calling an async function (see [Events](#doc-game--events--what-isn-t-there-yet)).
Systems and views can't wait, as they run again every tick or frame: they start tasks instead, by calling an async function.
## What tasks wait for
`await` waits for a task handle or an immediate async call. These engine operations also return started handles, so a timer can be kept and awaited later:
| | |
|---|---|
| `await Wait.Ticks(n)` | `n` of the match's ticks. Match code only. |
| `await Wait.Frames(n)` | `n` of this machine's frames. Local code only. |
| `await Wait.Seconds(s)` | `s` seconds: in the match, the nearest whole number of ticks (at least one), the same on every machine; in local code, this machine's time. |
| `await Storage.Load(key)` | What the [server's store](#doc-game--files--waiting-for-the-answer-in-a-task) keeps under the key, as a `List`, failing with `IOError`. Match code only: the task goes on in the tick the answer is given to, on every machine. |
| `await Storage.List(prefix)`, `(prefix, after)` | The store's keys that start with the prefix, a page of them, as a `StorageKeys`, failing with `IOError`. Match code only. |
A wait of 0, or less, doesn't wait at all. The store's two have no handle to keep: without `await`, they're answered by a `Loaded` or `Listed` event.
For now:
- Methods, extern functions and functions that take an `Action` can't be async.
- `await` can't go in a block written after a call (an `Action`).
- Tasks can't draw, or read this frame's `Devices`: that's what views do, every frame.
- The input's `Sample`, `Sanitize` and `Predict`, frags and verts, operators and `Interpolate` start no tasks. A plain function or method does, as the code that calls it could: see [Starting a task](#doc-language--functions--starting-a-task).
- Awaiting an event isn't supported yet. An event can start an async handler, which then waits for time or other tasks.
`Storage.Flush()`, `Web.Fetch(url)` and `request.Send()` follow the same handle model. For example, `LocalTask flush = Storage.Flush();` starts one flush; `try await flush;` handles its eventual result. See [Files](#doc-game--files) for the provider and storage APIs.
## Where tasks run
A task belongs to a world, like the code that starts it. A system's or a match handler's tasks are the match's: they're part of it, in snapshots, state hashes and rollback, they go to players who join, and they carry on when the match changes hands. A view's or a local handler's tasks are this machine's, in its local state.
An async function's world comes from what it does: changing the match (spawning its entities, changing its components through `mut`, sending its events) makes it match code, and using local state, the [local fields](#doc-game--tasks--local-fields) of the match's components among it, or reading [`Frame.dt`](#doc-game--local-state--time), makes it local. A [function it calls](#doc-language--functions--sending-and-spawning) that sends or spawns counts as its own doing. One that does neither runs in whichever world starts it. Doing both is an error, as a task runs in one world.
## What a task keeps
While a task waits, it keeps its locals and its parameters, copied: text, lists and grids too, a grid a `target.Read()` gave and one of an asset's among them. A `foreach` over an asset reads the asset as it is each time round, so a loop that waits a frame per element of `asset List> run` goes on through the files [tide run](#doc-tools--cli) loaded again while it waited; the element it held as it waited is its own copy. Its **components and singletons** it gets again each time it goes on, as they are then, so it sees what changed while it waited. They have to be the caller's own, its parameters:
```csharp
async void Dash(mut Body body)
{
body.speed = 10;
await Wait.Seconds(0.2);
body.speed = 1; // The entity's Body as it is now
}
system StartDash(mut Body body, Controls controls)
{
if (controls.dash.down) Dash(body);
}
```
An async function's `mut` parameters are its components and singletons; it can't keep the caller's other variables while it waits, so it returns what it works out instead. For the same reason it has no `out` parameters: a struct returns several values.
**A grid parameter** is a copy of the task's own, made where it's called, as a list parameter is: a system or a view that changes its grid after starting the task doesn't change the task's, and the task reads its copy where it is after every wait, however many, with no copy made again. The pack's grid is copied whole, so a pack [tide run](#doc-tools--cli) loads again while the task waits leaves the task's copy as it was. An async function the task awaits with the grid gets a copy of its own too. A match task's copy is part of the match, in snapshots, hashes and what a joining player gets, like its other grids; a local task's is this machine's. A grid parameter can't be `mut`: to change a field's grid, take the component or singleton it's in.
```csharp
singleton Field
{
Grid2 cells = Grid2(64, 64);
bool watching;
int changed;
}
int Differences(Grid2 now, Grid2 before)
{
mut var count = 0;
foreach (var at in now) count += now[at] != before[at] ? 1 : 0;
return count;
}
async void Settle(mut Field field, Grid2 before)
{
await Wait.Ticks(30);
field.changed = Differences(field.cells, before); // The cells now, against the copy as they were 30 ticks ago
}
system Watch(mut Field field)
{
if (field.watching) return;
field.watching = true;
Settle(field, field.cells);
}
```
### Local fields
A local task reads and writes the [local fields](#doc-game--local-state--local-fields) of the match components and singletons it takes, as a view does. They come with the component each time the task goes on, from where this machine keeps the entity's, so the task sees what views wrote while it waited, and what it writes is there for the next frame's views:
```csharp
component Chunk
{
float3 corner;
Grid3 blocks = Grid3(16, 16, 16);
int edits;
local Mesh mesh;
local int drawn; // The edits its mesh was made at, plus one
local LocalTask job; // The task making it, while it does
}
async void Remesh(mut Chunk chunk, int version)
{
var built = await Faces(chunk.blocks); // A local worker
chunk.mesh = Mesh(built.vertices, built.indices);
chunk.drawn = version;
}
view Chunks(mut Chunk chunk)
{
if (!chunk.job.isRunning && chunk.drawn != chunk.edits + 1) chunk.job = Remesh(chunk, chunk.edits + 1);
if (chunk.drawn > 0) Draw.Mesh(chunk.mesh, float4x4.Translate(chunk.corner));
}
```
- **It's this machine's task.** Using local fields makes an async function local, so a view or a local handler starts it, never a system. `mut` on a match component lets it write the local fields alone: a task that also changes the component's match fields is an error, as it would run in both worlds.
- **The view and the task share them.** What the view wrote before it started the task, the task reads, and the other way round. They're the entity's own from then on.
- **Handing it the component changes nothing of the match.** A view that starts the task with its `mut Chunk chunk` changes the chunk's local fields, never its match fields, so a loop in that view over the other chunks that skips them by a match field of its own chunk, like `if (row.other.at.x != chunk.at.x + 1) continue;`, is still an [indexed loop](#doc-game--systems--only-the-rows-that-can-pass), and it can hand the task the neighbour's grid, `Remesh(chunk, row.other.blocks)`, which is the task's own copy. The same goes for a function the view hands it to that writes its local fields alone. A function written in C, or one that hands the component on to C, counts as changing all of it: what C writes isn't the compiler's to know.
- **It ends with the entity**, once the world this machine draws no longer has it, and the entity's local fields go once neither that world nor the one the server confirmed has it. So a task never writes for an entity that's gone. If the server undoes a destroy this machine predicted, the local fields come back as the task left them, but the task doesn't. That's why the example keeps the task's handle rather than a flag the task clears: `job.isRunning` is false once the task has ended, however it ended, so the view starts another.
- **Hidden or without the component**, the same: an entity this machine's player can no longer see is gone, with its local fields and its task, and comes back with its defaults; a task that takes a component the entity loses ends at the next frame, whether it was waiting or due to go on, and that component's local fields go. If the component comes back, it comes with new local fields and no task.
- **Rollback and reloads** leave them as they are: a task that goes on after a correction reads its component as corrected, and its local fields as this machine left them. A task that carries over a hot reload finds them where the new build keeps them.
## When tasks go on, and when they end
Tasks whose time has come go on at the end of the tick (or frame), after its changes and events, in the order they started; what they change, spawn and send then applies too. A task ends when its code does, and:
- **with what started it**: a task started by code that runs for an entity belongs to that entity, and ends when the entity is destroyed. A task started by a task belongs to the same entity, and one a function starts belongs to what the code that called the function runs for. Code that runs for no entity starts tasks that belong to the world, which last as long as it does.
- **without its components**: a task whose entity no longer has the components it takes ends.
- **with its match**, for a local task of one of the match's entities, or one that takes the match's components or singletons: once this machine leaves the match, it ends at the next frame, even if the next match has an entity with the same handle.
Immediate nested awaits can share a private frame. A kept handle identifies a separate started operation; its existing entity/world ownership still applies. An async function can't immediately await itself, as its private frame would hold itself; it can start another operation and keep its handle.
## Cancellation and lifetime
`build.Cancel()` cancels that operation and ends every task awaiting it. Cancellation ends an awaiting continuation without inventing a success value or a declared error. Cancelling one awaiting task preserves a shared build for its other consumers. A task that ends while it waits, cancelled or with its owner, lets go of what it waited for at once: a file's or a fetch's, and a GPU read's, whose slot and pixels go free for the next read.
`isRunning` is true while an operation is queued, running or waiting. `isCompleted` includes cancellation; `isCancelled` also describes default or stale handles. Cancelling a completed or stale handle has no effect. Old handles never refer to a newer operation that reused its storage. Equality compares operation identity.
Running Tide code stops cooperatively at generated safe points in loops, statements and helper calls. Trusted C finishes its current call. An unused worker can be abandoned once no retained handle or awaiting task needs it; discarded ordinary async calls continue by themselves. Completed results are retained while reachable handles need them and reclaimed afterward, including unreachable cycles.
Local saves and compatible reloads preserve handles and cached results. A task dropped by an incompatible reload leaves cancelled handles. Local jobs restart from saved owned inputs; native callbacks and provider pointers aren't saved. Match handles, results and cancellation remain deterministic match state. Local code can inspect a match handle's status; cancelling it belongs to match code, usually through a command.
Match handles aren't supported in sharded games yet. Local handles and workers,
and existing directly awaited or discarded match async calls, remain available.
Distributed task identity, result retention and cancellation need their own
ownership contract.
With per-recipient visibility, match tasks remain authoritative server work.
Their registries, continuations and cached results stay private. A projected
client cannot start a retained match operation, and a published handle whose
operation is absent there is stale. Publish permitted ordinary progress and
results for views.
## Local workers
Use a `local worker` for expensive CPU calculations such as chunk meshing.
Capture its input from local code, await it from an async function, and publish
the completed result there. The view can keep drawing the previous mesh.
```csharp
struct MeshData
{
List vertices;
List indices;
}
local singleton ChunkVisual
{
List voxels;
MeshData mesh;
int generation;
bool building;
}
local worker MeshData BuildMesh(List voxels)
{
return GreedyMesh(voxels); // The game's ordinary calculation helper
}
async void Rebuild(mut ChunkVisual visual)
{
visual.building = true;
var generation = visual.generation;
var mesh = await BuildMesh(visual.voxels);
if (visual.generation == generation)
visual.mesh = mesh;
visual.building = false;
}
```
Start `Rebuild(visual)` from a view or local handler when the input changes and
`building` is false. Advance the local generation whenever that meshing input
changes, including neighboring boundaries and rollback corrections; discard an
outdated result and request the latest input. For many chunks, keep a local queue
and schedule the visible chunks first. This example uses a local singleton; for
one of the match's entities, the task can keep the result in the entity's
[local fields](#doc-game--tasks--local-fields) instead.
Workers receive independent copies of their inputs and return independent
values. Numbers, text, lists, maps, sets, ordinary structs, fixed arrays and
optional/error results follow their normal value rules. A worker takes no
`mut`, `out`, component/singleton binding, World, query, devices, resource handle,
asset reference/borrow or callable/shader binding. Pass the CPU data it needs.
Its helpers have the same restrictions: no live world, drawing, frame services,
file/network operations, task starts or implicit match randomness. C remains trusted; C called by workers
must be safe to run on their threads.
A worker can also take read-only `Grid2` and `Grid3` snapshots:
```csharp
local worker List FindSolidCells(Grid3 voxels)
{
mut List cells = [];
foreach (var at in voxels)
if (voxels[at] != 0) cells.Add(at);
return cells;
}
```
Await it with a grid field or grid asset. Capture copies its directory and
existing chunks before dispatch; later source edits or pack replacement cannot
change the worker's input. Capture costs time on the calling thread, so pass a
chunk's grid rather than a whole voxel world's when possible. Ordinary helpers
can read and forward the snapshot. Grid parameters stay read-only, including
through those helpers; grid locals and return values remain unsupported.
GPU `Sample` operations remain unavailable in workers.
Arguments are captured in their written order. If a later argument changes the
source or awaits another task, an earlier grid capture keeps its original cells.
Loop semantics stay the same. Workers additionally permit `parallel` over
their own lists of plain values, including local variables:
```csharp
local worker List NormalizePoints(List points)
{
mut List result = points;
parallel (var i in result)
{
result[i] = Math.Normalize(result[i]);
}
return result;
}
```
Each step changes only its own output element or block. Code after the loop
waits for all steps. Ordinary `for` and list `foreach` loops remain ordered.
Grid `foreach` uses the existing independence analysis inside workers too;
appending to an output list or reducing a total keeps the loop ordered. Explicit
list-parallel steps can read the captured grids while writing their own output.
Jobs and their parallel steps share the host's bounded pool. With no background
provider, a worker runs synchronously when polled, so expensive work can still
stall a frame on a host without threads. Small parallel loops run serially:
small is the steps' reckoned work in all, counting the functions they call, so
a short loop of costly steps still shares out.
Local code can start a worker and keep its `LocalTask` handle; only local
async code awaits its result. Bare `worker` is reserved for a future match
contract and is currently an error. An owner disappearing drops its
continuation. Abandoned queued calculations are skipped, and running Tide
calculations stop cooperatively. Reload drains old callbacks before unloading
their code; trusted C must return before that drain can finish.
Saved or retained waiting tasks restart their pending worker after restoration
or reload. No worker state enters match snapshots, hashes or networking.
### Which call starts first
More worker calls can wait than there are threads free. A call says when it
starts among them with `priority:`, written last, by name:
```csharp
// The chunk the player stands in, before the ones far off
var built = await BuildMesh(voxels, priority: near ? WorkerPriority.Urgent : WorkerPriority.Normal);
// A handle's call takes it too
LocalTask far = BuildMesh(horizon, priority: WorkerPriority.Background);
```
`WorkerPriority` has three members. `Urgent` calls start first, then `Normal`
ones, which is what a call that says nothing is, then `Background` ones, each
in the order they came. Nothing waits for ever: a waiting normal call starts
after four urgent starts, and a waiting background call after sixteen starts
of the others. The worker is the same function for all of them, so one mesher
serves the chunk underfoot and the horizon.
A priority says which waiting call a free thread takes. It never interrupts a
call that has started, and it doesn't make the copy of a call's inputs cheaper.
The match's ticks keep their threads first, as before. Each priority has its
own room for waiting calls, so a flood of background calls keeps no urgent one
out.
The value is read once, as the call begins: before the call waits for room and
before its arguments. It can be any `WorkerPriority` value, but not one that
has to be awaited. A worker can't name a parameter `priority`.
## In C
Hosts tell local code how long each frame is, before `tide_frame`: `tide_local_frame_time(local, seconds)`, which local tasks' waits count down and `Frame.dt` reads. `tide/run.h` does. Under `tide run`, a waiting task carries over to a new build when its code is the same; when it changed, the task is dropped, and tide says so.
Custom hosts set `gui.jobs` to their `tide_jobs` provider before `tide_frame`
to enable local background workers. The standard host supplies
`tide_platform_jobs()`. Providers implement the optional `background` and
`help` callbacks from `tide/jobs.h`; `tide/worker.h` describes item ownership
and completion. A zeroed GUI retains the synchronous fallback.
`gui.worker_limits` optionally supplies `tide_worker_limits`. Zero fields use
the current defaults: 64 pending private jobs, 64 MiB of retained input
captures, and 4 MiB of capture/result transfers per frame. Direct worker awaits
wait for admission before evaluating their arguments. Nested awaited arguments
don't hold a reservation while waiting for another worker. The first two
limits count each priority apart: normal calls have them, urgent calls as much
again, and background calls half as much.
Local state hands a provider as many calculations as it has threads beside the
caller's, and keeps the rest in its own queues by priority, so a provider's
`background` needs no ordering of its own.
Transfer limits are soft: one transfer that crosses the budget finishes, then
later transfers wait for another frame. This lets an oversized job make
progress. Started handle calls evaluate and snapshot their arguments when
called; their saved async input frames are outside the private-job capture
limit. These controls aren't a hard per-job or process memory cap. Feed very
large bursts from an async queue when input snapshots themselves are costly.
The profiler reports worker compute and queue wait per completed job, with
input-capture and result-transfer totals. Frame-thread copying remains part of
the frame's cost; worker compute runs on the background pool.
---
Source: https://tide-engine.dev/game/input.md
Sample keyboard, mouse, touch and gamepad devices into Tide player input, then predict, sanitize and share it across the multiplayer match.
# Input
A player's **input** is what they do in one tick, and it's what the network sends. A game can declare one `input`, whose fields systems read, or read [devices directly in the match](#doc-game--input--devices-in-the-match).
```csharp
input PlayerInput
{
float2 move;
bool jump;
Sample(Devices devices)
{
var keys = devices.keyboard;
if (keys.d.pressed) move.x += 1;
if (keys.a.pressed) move.x -= 1;
move += devices.gamepad.leftStick;
jump = keys.space.pressed || devices.gamepad.buttonSouth.pressed;
}
}
system Jump(PlayerInput input, mut Velocity velocity)
{
if (input.jump.down)
velocity.value.y = 5;
}
```
Click the game below so it has the keyboard, then walk with `A` and `D` or the arrows and jump with space. A drag works too: sideways to walk, up to jump. `Sample` turns what the devices say into the input's two fields, a system moves the hero by them, and the line at the top shows what the match got.
**An input, sampled and read** ([Run example](https://tide-engine.dev/examples/input/?stats))
```tide
settings { title = "Input"; tickRate = 30; maxPlayers = 1; }
// A drag of the pointer, which a view turns into a stick for the input.
local singleton Stick
{
float2 start;
float2 drag;
bool up;
}
// What a player does in one tick. It's the only thing a machine sends the others.
input Pad
{
[Clamp(-1, 1)] float2 move;
bool jump;
Sample(Devices devices, Stick stick)
{
var keys = devices.keyboard;
if (keys.d.pressed || keys.rightArrow.pressed) move.x += 1;
if (keys.a.pressed || keys.leftArrow.pressed) move.x -= 1;
move += devices.gamepad.leftStick + stick.drag;
jump = keys.space.pressed || keys.w.pressed || keys.upArrow.pressed
|| devices.gamepad.buttonSouth.pressed || stick.up;
}
}
component Hero
{
float2 position;
float2 velocity;
float2 move; // What the views show of the input, which only the match reads
bool jump;
int jumps;
}
scene Main { }
// The hero is its player's, so it reads that player's input.
event(PlayerJoined joined) GiveHero()
{
Spawn(Hero, Owner { player = joined.player });
}
system Walk(Pad pad, mut Hero hero, Time time)
{
hero.velocity.x = pad.move.x * 3;
// The input says held. The match works out `down` against the tick before.
if (pad.jump.down && hero.position.y <= 0)
{
hero.velocity.y = 6;
hero.jumps += 1;
}
hero.velocity.y -= 16 * time.dt;
hero.position += hero.velocity * time.dt;
if (hero.position.y < 0)
{
hero.position.y = 0;
hero.velocity.y = 0;
}
hero.position.x = Math.Clamp(hero.position.x, -1.7, 1.7);
hero.move = pad.move;
hero.jump = pad.jump;
}
view Drag(Devices devices, mut Stick stick)
{
var pointer = devices.pointer;
if (pointer.press.down) stick.start = pointer.position;
var pull = pointer.press.pressed ? pointer.position - stick.start : float2(0);
stick.drag = float2(Math.Clamp(pull.x / 50, -1, 1), 0);
stick.up = pull.y > 40; // The devices count y up
}
view DrawHero(Hero hero)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, 1), 2.2);
Draw.Line(float2(-2.2, -0.3), float2(2.2, -0.3), 0.04, Color(0.24, 0.25, 0.27));
Draw.RoundRect(hero.position + float2(0, 0.05), float2(0.5, 0.7), 0.16, Color(0.98, 0.75, 0.14));
Draw.Line(hero.position + float2(0, 0.6), hero.position + float2(hero.move.x * 0.6, 0.6), 0.06, Color(0.18, 0.83, 0.75));
Draw.SetScreen();
Draw.Text($"move.x = {hero.move.x:F1} jump = {hero.jump} jumps: {hero.jumps}", float2(16, 14), 16, Color.white);
Draw.Text("Click here, then A and D or the arrows, and space.\nOn a touchscreen, drag sideways, and up to jump.",
float2(16, Screen.height - 46), 13, Color(0.64, 0.64, 0.68));
}
```
## Sampling
The engine calls the input's `Sample` method on the player's own machine, once per tick. Its fields start at their defaults, and `Sample` assigns them by name, without `mut`.
`Sample` runs outside the match. It reads this machine's `Devices`, and the local singletons it takes as parameters, like `Sample(Devices devices, Settings settings)`, but never the match. It's the place to work out what the match needs from things only this machine knows: an aim direction from the mouse, which is in this machine's window, or anything that depends on its settings.
## Who gets which input
An input parameter gives a system the input of the player who **owns** the entity it's running for. `Owner` is a built-in component that ties an entity to a player:
```csharp
Spawn(Body, Owner { player = joined.player });
```
It's a normal component: it can be read, written, added and removed, and writing it hands control over.
Entities without an `Owner`, or whose owner is no player the match has a place for (`default`, or a `PlayerID` past its `maxPlayers`), get the **server's input**, and so do systems that run once per tick. An owner the match has a place for who isn't in it right now is still that player: the entity reads their input, not the server's. That's how the server controls what no player owns. An input parameter doesn't pick entities: add `with Owner` to only run on owned ones.
Below are two machines in one match. Move the pointer over a frame to steer that machine's player. One system moves every body, and for each it reads the input of whoever owns that body. The gray body has no `Owner`, so it reads the server's input, which here is player 1's machine's: it follows player 1's pointer, slowly. **Trade bodies** writes the two `Owner`s the other way round, and from then on each player steers the other's body.
**Whose input a system reads** ([Run example](https://tide-engine.dev/examples/owners/?stats))
```tide
settings { title = "Owners"; tickRate = 30; maxPlayers = 4; }
scene Main { }
component Body
{
[Position] float2 position; // Drawn gliding to where a correction put it
Color color;
float speed = 2.5;
}
singleton Roster { Map bodies; int arrivals; }
command Trade { }
// Where this machine's pointer is in the arena, which its input sends.
local singleton Aim { float2 world; bool moved; }
input Steer
{
// A place, not something a player does: what another machine guesses of it stays
[Absolute, Clamp(-3, 3)] float2 target;
[Absolute] bool steering;
Sample(Devices devices, Aim aim)
{
target = aim.world;
steering = aim.moved;
}
}
// A body nobody owns. It reads the server's input: the machine hosting the match.
event(Spawned) Setup(with Main)
{
Spawn(Body { position = float2(0, 1.4), color = Color(0.64, 0.64, 0.68), speed = 0.8 });
}
// Owner ties an entity to a player, so it reads that player's input.
event(PlayerJoined joined) Arrive(mut Roster roster)
{
var first = roster.arrivals % 2 == 0;
roster.arrivals += 1;
roster.bodies[joined.player] = Spawn(
Body { position = float2(first ? -1 : 1, 0), color = first ? Color(0.98, 0.75, 0.14) : Color(0.18, 0.83, 0.75) },
Owner { player = joined.player });
}
event(PlayerLeft left) Depart(mut Roster roster)
{
roster.bodies[left.player].Destroy();
roster.bodies.Remove(left.player);
}
// One system for every body. `steer` is the input of whoever owns the one it runs for.
system Follow(Steer steer, mut Body body, Time time)
{
if (!steer.steering) return;
var way = steer.target - body.position;
var step = body.speed * time.dt;
body.position += Math.Length(way) > step ? Math.Normalize(way) * step : way;
}
// Owner is a component like any other: writing it hands control over.
command(Trade trade, PlayerID sender) TradeBodies(mut Roster roster)
{
mut PlayerID other = sender;
foreach (var seat in roster.bodies)
{
if (seat.key != sender) other = seat.key;
}
if (other == sender) return; // Nobody to trade with
var mine = roster.bodies[sender];
var theirs = roster.bodies[other];
mine.Add(Owner { player = other });
theirs.Add(Owner { player = sender });
roster.bodies[sender] = theirs;
roster.bodies[other] = mine;
}
view Point(Devices devices, mut Aim aim)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, 0.2), 2.4);
aim.world = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position));
if (Math.LengthSq(devices.pointer.delta) > 0) aim.moved = true;
GUI.SetTheme(GUITheme { radius = 6 });
if (GUI.Button(Rect(12, Screen.height - 44, Screen.width - 24, 32), "Trade bodies")) Send(Trade { });
}
// Every body this machine's player doesn't own: the other player's, and nobody's.
view Others(Body body, without ownership)
{
Draw.Circle(body.position, 0.2, body.color);
}
view Unowned(Body body, without Owner)
{
Draw.Text("no Owner", body.position + float2(0, 0.3), 0.17, Color(0.64, 0.64, 0.68), Anchor.LowerCenter);
}
view Mine(Body body, with ownership)
{
Draw.Circle(body.position, 0.2, body.color);
Draw.WireCircle(body.position, 0.32, 0.04, Color.white);
Draw.Text("yours", body.position + float2(0, 0.4), 0.2, Color.white, Anchor.LowerCenter);
}
```
A view picks the entities this machine's player owns with `with ownership`, and every other one with `without ownership` (see [Your own entities](#doc-game--views-and-the-match--your-own-entities)). That's for views: the match runs the same on every machine, so a system has no player of its own to ask about.
Players are `PlayerID`s, not ints or connections. Like `Entity`, a `PlayerID` is opaque, compared with `==`, and has a null value. A player who reconnects gets their `PlayerID` back, and keeps everything they owned. `PlayerID(0)` names a player by number, for local play and tests.
## Held, not pressed
Input carries whether buttons are held, not whether they just went down: when a player's input is late, the other machines guess it by repeating their last one, and a repeated "just went down" would press twice. In the match, `bool` fields of the input get `.down` and `.up`, worked out against the previous tick, inside structs too: `input.aim.fire.down`.
## Passing input to helpers
Synchronous functions and methods can read the same input as their caller:
```csharp
bool WantsJump(PlayerInput controls)
{
return controls.jump.down;
}
system Jump(PlayerInput input, mut Velocity velocity)
{
if (WantsJump(input)) velocity.value.y = 5;
}
```
Pass the caller's input parameter directly. The helper borrows its current and previous tick together, preserving the selected player's input, nested `.down`/`.up` edges, prediction and replay behavior. Helpers can forward it to other helpers, without an extra argument or a full input copy. They gain no implicit player, entity or world access.
Input parameters are read-only: no `mut`, `out`, `in` or default. A borrow cannot be stored, returned or kept by a task. Copy individual fields when ordinary values need to outlive the call. Synchronous action blocks, comparisons and parallel steps can read or forward input under their existing rules. Externs, operators, shaders, audio declarations and async routines take no input borrow. `Sample`, `Sanitize` and `Predict` still pass their field values to helpers; they have no input parameter to borrow.
## What other machines guess
A machine runs ahead of the last tick the server confirmed to it, by about its round trip (see [Networking](#doc-multiplayer--networking--prediction-and-rollback)). For those ticks it has to guess what the other players do, and its guess is their last input, repeated. A guess that turns out wrong is put right when the server's answer comes, and the further ahead a machine runs, the more there is to put right: at a ping of 500 ms, a player who stopped running is shown running for half a second more, and then moved back all of it.
So a guess only repeats an input for 0.15 seconds past what the machine knows. After that it takes the player to have let go: every field of their input is back at its default. However slow the connection, a guess that was wrong moves things by what a player does in 0.15 seconds, at most. A machine with a round trip under about a tenth of a second never runs that far ahead, and nothing changes for it.
That suits what a player is **doing**: an axis that's pushed, a button that's held. A field that says **where something is**, like an aim or the cell under a pointer, has no rest to go back to: its default is only another place. Mark those `[Absolute]`, and a guess keeps them for as long as it goes on:
```csharp
input Controls
{
[Clamp(-1, 1)] float move; // Doing: back to 0
bool fire; // Doing: let go
[Absolute] float2 aim; // Where: kept
[Absolute] int weapon; // Which: kept
}
```
- **Letting go presses nothing.** No field's `.up` is true for it, so a shot that fires when a button is let go doesn't fire on a guess.
- **The devices match code reads** (see [Devices in the match](#doc-game--input--devices-in-the-match)) are let go the same way: keys up, sticks centered.
- **Only guesses change.** What the server runs, and what it confirms, is the input each player sent. A player whose input arrives late still keeps their last one for that tick, on every machine.
- **What it costs.** A player who keeps going is shown a little behind where they'll turn out to be, and each tick the server confirms, the machine runs the ticks past its guess again. For the default guess, both happen only on a machine further ahead than 0.15 seconds, and only while someone is doing something. Custom guesses can require replay sooner.
`[Absolute]` takes no arguments, and goes on the input's own fields, not on the fields of a struct it holds.
## Choosing a guess
Use `[DontPredict]` for actions that should occur only when a real input sample says so. On every guessed tick, the field starts at its declared default:
```csharp
input Controls
{
float2 move;
[DontPredict] bool jump;
[DontPredict] bool dash;
[Absolute] float2 aim;
}
```
Movement continues from the previous input; jump and dash become false immediately. Real input from this machine still acts immediately, and received input keeps its actions. The attribute takes no arguments and goes on the input's own fields. A marked struct or array resets as a whole. It cannot combine with `[Absolute]` on the same field.
For a computed guess, add `Predict()`:
```csharp
input Controls
{
float2 move;
bool dash;
Predict()
{
dash = false;
move *= 0.9;
}
}
```
It runs once per guessed tick, starting from the previous input, after `[DontPredict]` resets. Fields it leaves untouched continue; computations such as the movement fade accumulate across guessed ticks. It can also explicitly replace a marked field's default. Repair, bounds and `Sanitize()` apply afterward. The existing 0.15-second limit still resets non-absolute fields after `Predict()` runs.
`Predict()` takes no parameters and reads only the input's fields. It can call pure helpers, as `Sanitize()` does. It cannot read devices, match or local state, frame time or randomness, or send events, spawn entities or start tasks. The engine's `viewTime` remains read-only.
These changes apply to client guesses of other players and a remote server. Actual samples, authoritative server ticks and confirmed replay keep their existing behavior. Changing a guess creates no `.down` or `.up` edges, so clearing an action does not invent a release. Normal `.down` already avoids repeated presses when a held bool is repeated; use these hooks when the held value itself or another action field should not continue into guessed ticks.
## Devices
`Devices` has a keyboard, a mouse, a gamepad, a touchscreen and the pointer. Every button has `.pressed` (held), `.down` (went down since the last sample) and `.up` (went up). On a device, `.pressed` means held at any point since the last sample, so a quick tap between ticks is never lost. A match that starts from a menu doesn't read what was pressed there: its first tick gets what's held as it starts.
- **Keyboard:** every key by its position, named after the US layout, so `WASD` is in the same place on AZERTY:
- `a` to `z`, and `digit0` to `digit9`
- `space`, `enter`, `escape`, `tab`, `backspace`
- `insert`, `delete`, `home`, `end`, `pageUp`, `pageDown`
- `upArrow`, `downArrow`, `leftArrow`, `rightArrow`
- `leftShift`, `rightShift`, `leftCtrl`, `rightCtrl`, `leftAlt`, `rightAlt`, `capsLock`
- `f1` to `f12`
- `minus`, `equals`, `leftBracket`, `rightBracket`, `backslash`, `semicolon`, `quote`, `comma`, `period`, `slash`, `backquote`
- `numpad0` to `numpad9`, `numpadEnter`, `numpadPlus`, `numpadMinus`, `numpadMultiply`, `numpadDivide`, `numpadPeriod`
- `text`, a `string`: what was typed since the last frame, which views read (see [Typed text](#doc-game--input--typed-text))
- **Mouse:** `position`, `delta` and `scroll` (`float2`), and the buttons `left`, `right`, `middle`, `back` and `forward`. `position` is in window pixels from the bottom left, with `y` up, as a touch's and the pointer's are; in a view, `Screen.Flip(position)` gives it from the top left, as the screen and the GUI count (see [Screen and world coordinates](#doc-game--cameras--screen-and-world-coordinates)). While the cursor is [locked](#doc-game--input--locking-the-cursor), `position` stays where it was and `delta` is the mouse's own movement.
- **Gamepad:** `connected`, `leftStick` and `rightStick` (`float2`), `leftTrigger` and `rightTrigger` (0 to 1), the face buttons by position (`buttonSouth`, `buttonEast`, `buttonWest`, `buttonNorth`, which is A, B, X and Y on Xbox), `dpad.up` and the other directions, `leftShoulder`, `rightShoulder`, `leftStickButton`, `rightStickButton`, `start` and `select`.
- **Touchscreen:** `connected`, `primaryTouch`, and `touches`, a slot for each of 10 fingers. Each `Touch` has:
- `press`, a button: `.down` when the finger touched, and `.up` when it lifted
- `id`, the same while the finger touches, and a new one for each touch
- `position`, `delta` and `startPosition` (`float2`)
- **Pointer:** `position`, `delta` and `press`: the mouse, with its left button, or the primary touch, whichever was used last. Once a finger lifts, the pointer stays where it lifted, until another finger touches or the mouse is used.
Each part has a type of its own: `Keyboard`, `Mouse`, `Gamepad`, `Dpad`, `Touchscreen`, `Touch`, `Pointer` and `Button`. Functions take them, and `Devices`, as parameters to read:
```csharp
float2 Steer(Gamepad pad)
{
return pad.leftStick + float2(pad.dpad.right.pressed ? 1 : 0, 0);
}
```
Axes follow Unity: `y` is positive up, for sticks, the mouse, touches and the pointer, and `scroll.y` is positive scrolling away from you.
### Touch
A finger keeps its slot in `touches` while it touches, and lifts out of it. With ten fingers on the screen, an eleventh is left out. `primaryTouch` is the finger that touched while no other was the primary one, until it lifts: the one to follow for a single finger. A finger that touches and lifts between two samples reads as held for one, like a quick key press, so no tap is lost.
`touches[i]` is the touch in slot `i` (an empty one past the last), `touches.count` is how many slots there are, and `foreach` goes through every slot, touching or not:
```csharp
mut var fingers = 0;
foreach (var touch in devices.touchscreen.touches)
{
if (touch.press.pressed) fingers += 1;
}
```
A finger is never the mouse, as in Unity's Input System: the mouse only sees mice. Code that should work with both reads the **pointer**, which follows the mouse or the primary touch, whichever was used last, as Unity's `Pointer.current` does. The GUI follows it too, so buttons work with a finger.
```csharp
input Brush
{
[Absolute] int x;
[Absolute] int y;
bool paint;
// Cells of 16 pixels, under the mouse or a finger
Sample(Devices devices)
{
var pointer = devices.pointer;
x = int(Math.Floor(pointer.position.x / 16));
y = int(Math.Floor(pointer.position.y / 16));
paint = pointer.press.pressed;
}
}
```
Touches come from Android, the web on phones and desktops, and touchscreens on Windows and Linux, a Steam Deck's among them. On Linux they're X11's touch events, which XWayland has too; on a Steam Deck, Steam may make a mouse of the screen's touches itself unless the game is set to take them as touches. Native iOS support isn't built yet, and a Mac has no touchscreen. A browser on any desktop can still report touches. Where no touchscreen is available, `connected` is false and no finger ever touches.
The cell coordinates above are `[Absolute]` because a prediction should keep the last cell the player pointed at, even after it guesses they stopped painting.
Try a mouse, then a finger in the example below. The amber ring is the pointer; teal circles are individual touches, with lines back to where each started. A touch leaves the mouse where it was, and lifting it leaves the pointer where it ended. The ten slots show which fingers are still held. Click or tap the frame first so swipes go to the example.
**The pointer and individual fingers** ([Run example](https://tide-engine.dev/examples/pointer/?stats))
```tide
settings { title = "Pointer and touch"; }
local scene Main { } // Device inspection needs no match
local singleton Trace
{
int presses;
float flash;
float2 last;
string edge = "Move the pointer, then press";
}
view Inspect(Devices devices, mut Trace trace)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetScreen();
var quiet = Color(0.64, 0.64, 0.68);
var amber = Color(0.98, 0.75, 0.14);
var teal = Color(0.18, 0.83, 0.75);
var pointer = devices.pointer;
var at = Screen.Flip(pointer.position); // Devices count from the bottom left
trace.flash = Math.Max(0, trace.flash - Frame.dt);
if (pointer.press.down)
{
trace.presses += 1;
trace.last = at;
trace.flash = 0.7;
trace.edge = "down: the press began";
}
if (pointer.press.up) trace.edge = "up: the press ended";
Draw.Text("Pointer and touch", float2(16, 14), 20, Color.white);
Draw.Text($"held: {pointer.press.pressed} presses: {trace.presses}",
float2(16, 44), 14, amber);
Draw.Text(trace.edge, float2(16, 68), 13, quiet);
// A touch never moves the mouse. Its outline stays at the mouse's position.
Draw.WireCircle(Screen.Flip(devices.mouse.position), 9, 2, quiet);
mut var held = 0;
for (var i = 0; i < devices.touchscreen.touches.count; i++)
{
var touch = devices.touchscreen.touches[i];
var center = float2(16 + (i + 0.5) * (Screen.width - 32) / 10, Screen.height - 88);
Draw.Circle(center, 10, touch.press.pressed ? teal : Color(0.24, 0.25, 0.27));
Draw.Text($"{i}", center, 12, Color.white, Anchor.MiddleCenter);
if (!touch.press.pressed) continue;
held += 1;
var finger = Screen.Flip(touch.position);
Draw.Line(Screen.Flip(touch.startPosition), finger, 2, teal);
Draw.Circle(finger, 12, Color(teal.r, teal.g, teal.b, 0.3));
Draw.Text($"id {touch.id}", finger + float2(16, 0), 13, teal);
}
Draw.WireCircle(at, pointer.press.pressed ? 20 : 15, 3, amber);
if (trace.flash > 0)
Draw.WireCircle(trace.last, 20 + (0.7 - trace.flash) * 60, 2,
Color(amber.r, amber.g, amber.b, trace.flash / 0.7));
Draw.Text($"{held} fingers held; slots 0 to 9", float2(16, Screen.height - 62), 13, quiet);
Draw.Text("Amber: pointer Teal: touch Gray: mouse\nTap here first, then try dragging several fingers.",
float2(16, Screen.height - 40), 12, quiet);
}
```
### Locking the cursor
A camera that turns with the mouse locks the cursor: a view calls `Cursor.Lock()` every frame the game wants the mouse (see [Looking around](#doc-game--cameras--looking-around)). `Cursor.locked` is whether the window holds it right now, which the system decides, not the game: the cursor goes back to the player when they press Escape, and a window that loses the focus lets it go.
`Sample` reads `Cursor.locked`, so the mouse only turns the camera while the cursor is locked, and moving it over a menu doesn't:
```csharp
input PlayerInput
{
float2 look;
Sample(Devices devices)
{
if (Cursor.locked) look = devices.mouse.delta * 0.003;
}
}
```
`Sample` can't call `Cursor.Lock()`: it runs once per tick, and the lock is asked for every frame, by views. The match can't read `Cursor.locked`, as it can't read anything of this machine's: put what it needs in the input, as `look` is here.
### Typed text
`devices.keyboard.text` is what the player typed since the last frame, as a `string`. Unlike keys, it follows the keyboard's layout: on AZERTY, the key in the `q` position types `a`, and `text` says `a`. Shift, accents and a phone's keyboard are applied, and what's pasted with Ctrl+V comes through it too. Backspace, Enter and the arrows are keys, not characters.
A text field of the GUI's reads it for you. Views read it themselves, and so do the functions they call, for a text box of their own, or to pass on to a library:
```csharp
local singleton Chat
{
string line;
}
view Typing(Devices devices, mut Chat chat)
{
chat.line += devices.keyboard.text;
if (devices.keyboard.backspace.down) chat.line = chat.line.Substring(0, chat.line.length - 1);
}
```
It's a frame's, so `Sample` can't read it, and neither can the match: an input holds no text, and what's typed is never sent. It's empty while the GUI has the keyboard, as when the player types into a `TextField`, and in every view but the one whose [control](#doc-game--gui--widgets-of-your-own) has the focus, or that [claimed the keyboard](#doc-game--gui--widgets-that-read-the-devices-themselves). A long paste comes over a few frames, 32 characters in each.
### Devices in the match
Match code can read devices too, with a `Devices` parameter: the devices of the player who owns the entity, like an input parameter. The input then sends what match code reads of them, and nothing else. A game can do without an `input` declaration this way:
```csharp
system Hop(Devices devices, mut Velocity velocity)
{
if (devices.keyboard.space.down || devices.gamepad.buttonSouth.down)
velocity.value.y = 5;
}
```
Device access always takes a `Devices` parameter. `Sample` and views receive this machine's devices; match code receives the entity owner's, or the server's. A system takes at most one `Devices` parameter and one input parameter. Views can't read the input. Local event handlers and tasks can't take devices.
The match can't read positions on the screen either, the mouse's, a touch's or the pointer's: they're in this machine's window, which the other machines don't have. Work out what the match needs from them in `Sample`, like an aim direction, and read that from the input.
## Input is an attack point
Inputs come from other players' machines, so the engine doesn't trust them:
- NaN and infinite floats and doubles become the field's default. Double fields retain their full 64 bits in input packets and deltas.
- Fields can declare bounds, `[Clamp(lo, hi)]`, `[Min(x)]` and `[Max(x)]`, which the engine applies to every input. A number bounds every component of a vector.
- Then the input's `Sanitize` method runs, if it has one, for what bounds can't say.
```csharp
input PlayerInput
{
[Clamp(-1, 1)] float2 move;
[Min(0), Max(3)] int gear = 1;
bool boost;
Sample(Devices devices) { move = devices.gamepad.leftStick; }
// After the bounds: what attributes can't say.
Sanitize()
{
if (gear == 0) boost = false;
}
}
```
Every input goes through these steps before the match reads it, including this machine's, so systems can rely on them without checking again. Devices are repaired the same way, since the engine knows their ranges.
An input holds numbers, bools, chars, enums, vectors and structs of those; not text or lists. A match takes as many players as the game's `maxPlayers` setting says, 16 without one (see [Matches](#doc-multiplayer--matches--how-many-players)).
## Presented view time
With `settings { maxRewind = 0.25; }`, your input gains `ViewTime viewTime`; do not declare this field yourself. It is read-only and stamped by the engine after `Sample`, from the last actually presented confirmed frame. `tick` names the upper endpoint, `alpha` its interpolation fraction, and `valid` is false before a frame is presented. Use it with [collider rewind](#doc-multiplayer--networking--collider-rewind); the server validates the wire value as an untrusted claim.
---
Source: https://tide-engine.dev/game/views.md
Draw a Tide game with views: the camera, shapes, colors, text and the screen's pixels, motion that's smooth between ticks, and a frame's length.
# Views and drawing
A **view** draws the game. It looks like a system and takes the same parameters, components and singletons, but it runs once per rendered frame instead of once per tick, and it never changes the match. It reads this machine's devices through a `Devices devices` parameter, and can't read the input (see [Input](#doc-game--input--devices-in-the-match)).
```csharp
view DrawBalls(Body body, Ball ball)
{
Draw.Circle(body.position, body.radius, ball.color);
}
view DrawHud(Arena arena)
{
Draw.SetCamera(float2(0, 0), arena.halfSize.y);
Draw.Text("fire: space", float2(-arena.halfSize.x, arena.halfSize.y), 18, Color.gray);
}
```
Drawing is immediate mode: views record their drawing calls every frame. Views run after the frame's ticks, in the order they're declared, and later ones draw on top. `[Before]` and `[After]` order views among themselves, as they do systems. A frame can draw as much as it needs: shapes go to the GPU together, so tens of thousands of rects or circles a frame are cheap, on the web too.
A view's `mut` parameters, `Spawn`, `Add`, `Remove`, `Destroy` and `Send` are all local: views can change this machine's own state, like particles or a menu, but not the match (see [Local state](#doc-game--local-state)). Only views, and the functions they call, can draw.
For expensive preparation such as voxel meshing, start a local async function
that awaits a [local worker](#doc-game--tasks--local-workers), and draw the last
completed geometry while it works. A heavy calculation directly in a view
blocks that frame.
For see-through shapes, sprites and 3D meshes, see [Transparency](#doc-game--draw-settings--transparency): alpha controls opacity, and 3D also needs the right depth setting and draw order.
Tap a circle to select it, then change the camera's size. The grid and circles use world coordinates; the heading and slider keep their size in screen pixels. Pointer picking uses `ScreenToWorld` with that frame's camera.
**A view draws the world** ([Run example](https://tide-engine.dev/examples/views/?stats))
```tide
settings { title = "Views and coordinates"; maxPlayers = 1; }
component Dot
{
float2 position;
Color color;
local bool selected;
}
local singleton CameraSettings { float size = 3; }
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Dot { position = float2(-1.5, 0.6), color = Color(0.98, 0.75, 0.14) });
Spawn(Dot { position = float2(0, -0.6), color = Color(0.98, 0.44, 0.52) });
Spawn(Dot { position = float2(1.5, 0.6), color = Color(0.18, 0.83, 0.75) });
}
// The camera applies to every view that draws after this one.
view Background(CameraSettings camera)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0), camera.size);
for (var i = -6; i <= 6; i++)
{
Draw.Line(float2(i, -6), float2(i, 6), Color(0.15, 0.15, 0.17));
Draw.Line(float2(-6, i), float2(6, i), Color(0.15, 0.15, 0.17));
}
Draw.Line(float2(-6, 0), float2(6, 0), Color(0.3, 0.3, 0.33));
Draw.Line(float2(0, -6), float2(0, 6), Color(0.3, 0.3, 0.33));
}
// Run once for each Dot. Only selected, a local field, can change here.
view Dots(mut Dot dot, Devices devices)
{
var pointer = devices.pointer;
var screen = float2(pointer.position.x, Screen.height - pointer.position.y);
var world = Draw.ScreenToWorld(screen);
var hovered = Math.Length(world - dot.position) < 0.4;
if (hovered && pointer.press.down) dot.selected = !dot.selected;
Draw.Circle(dot.position, 0.32, dot.color);
if (hovered || dot.selected)
Draw.WireCircle(dot.position, 0.43, 0.035, Color.white);
}
view Pointer(Devices devices)
{
var pointer = devices.pointer;
var screen = float2(pointer.position.x, Screen.height - pointer.position.y);
var world = Draw.ScreenToWorld(screen);
Draw.Line(world - float2(0.12, 0), world + float2(0.12, 0), Color.white);
Draw.Line(world - float2(0, 0.12), world + float2(0, 0.12), Color.white);
}
// Screen-space text keeps its pixel size when the camera zooms.
view Controls(mut CameraSettings camera)
{
Draw.SetScreen();
Draw.Text("Tap a circle to select it", float2(16, 14), 18, Color.white);
GUI.SetTheme(GUITheme { radius = 6 });
GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Camera size", camera.size, 2.5, 4.5);
}
```
Views can share [named phases](#doc-game--systems--named-phases) instead of depending on individual view names:
```csharp
enum RenderStages { Prepare, Objects, Effects, UI }
[Stage(RenderStages.Prepare)]
view ClearScene() { Draw.Clear(Color.black); }
[Stage(RenderStages.Objects)]
view DrawBalls(Body body, Ball ball)
{
Draw.Circle(body.position, body.radius, ball.color);
}
[After(RenderStages.Objects), Before(RenderStages.UI)]
view Effects() { ... }
```
An offset such as `[Stage(RenderStages.Objects, 10)]` runs later within `Objects`. `After(RenderStages.Objects)` waits until every view in that phase has run for all its entities, including views with offsets.
This page has what a 2D game draws with: the draw functions, colors, shapes, the screen, text, and how a view sees time. The rest is on pages of its own:
- [Views and the match](#doc-game--views-and-the-match): entities other than a view's own, the ones this machine's player owns, and what the server has confirmed.
- [Draw settings](#doc-game--draw-settings): blending, tints, stencil, transforms and clipping, and what's see-through.
- [Meshes and textures](#doc-game--meshes-and-textures): triangles, and the images they're drawn with.
- [Drawing in 3D](#doc-game--3d): 3D meshes and primitives, depth, and which side of a triangle draws.
- [Cameras and coordinates](#doc-game--cameras): between the screen and the world, a camera that turns with the mouse, projections, and cameras as matrices.
- [Render targets](#doc-game--render-targets): drawing into an image, and post-processing.
- [Frags and verts](#doc-game--shaders): code of the game's that runs on the GPU.
## Draw functions
`Draw` draws into the window: shapes, text and 2D meshes, 3D meshes and primitives, with a 2D camera and a 3D camera of its own. The 2D and 3D forms of a function are told apart by their arguments: `Draw.Camera(center, size)` is the 2D camera and `Draw.Camera(position, rotation, fieldOfView)` the 3D one, `Draw.Mesh(vertices, indices)` draws a `List` where its vertices are and `Draw.Mesh(vertices, indices, transform)` a `List` in the world, and `Draw.WorldToScreen` takes a `float2` through the 2D camera or a `float3` through the 3D one. A [render target](#doc-game--render-targets) has the same functions as its methods; `Draw.Clear` clears the window and its depth, and `Draw.list` hands the frame's draw list to C.
Positions and sizes are in world units, with `y` up. The camera maps them to the screen.
| Function | What it draws |
|---|---|
| `Draw.Clear(color)` | Fills the screen |
| `Draw.ClearDepth()` | Sets depth back and leaves the picture: 3D meshes drawn after are in front of everything before (see [3D](#doc-game--3d)) |
| `Draw.SetCamera(center, size)` | Sets the camera for the calls after it: `center` is the world position at the middle of the screen, and `size` is half the visible height, like Unity's orthographic size. One of the [draw settings](#doc-game--draw-settings), like the rows that name them below |
| `Draw.Circle(center, radius, color)` | A filled circle |
| `Draw.WireCircle(center, radius, color)` | A circle's outline |
| `Draw.Rect(center, size, color)` | A filled rectangle |
| `Draw.WireRect(center, size, color)` | A rectangle's outline |
| `Draw.Line(from, to, color)` | A line a pixel wide |
| `Draw.Line(from, to, width, color)` | A line `width` thick, with round ends: the first of the [smooth shapes](#doc-game--views--smooth-shapes), as are the rows from here to `Draw.Shape` |
| `Draw.WireRect(center, size, width, color)`, `Draw.WireCircle(center, radius, width, color)` | Outlines `width` thick |
| `Draw.Rect(center, size, rotation, color)` | A rectangle turned about its center |
| `Draw.RoundRect(center, size, radius, color)` | A rectangle with round corners. `RoundRect(center, size, radius, rotation, color)` turns it, and `WireRoundRect(center, size, radius, width, color)` is its outline |
| `Draw.Ellipse(center, radii, color)` | An ellipse. `Ellipse(center, radii, rotation, color)` turns it, and `WireEllipse(center, radii, width, color)` is its outline |
| `Draw.Arc(center, radius, start, sweep, width, color)` | Part of a ring |
| `Draw.Shape(shape)` | A [`Shape`](#doc-game--views--the-general-shape): a fill from one color to another, an outline around a fill, an edge that fades |
| `Draw.Rect(rect, radius, fill)`, `Draw.Shape(shape, fill)` | A shape [filled by a function](#doc-game--views--fills) of where in it each pixel is: a `Gradient`, or any `Func` |
| `Draw.Shadow(rect, radius, size)` | A soft shadow under a box at `rect`, fading out over `size` pixels, a quarter of `size` lower: black at 0.4, or `Draw.Shadow(rect, radius, size, color)`. Draw it before the box |
| `Draw.Text(text, position, size, color)` | Text, with `position` its top left corner and `size` its font size, the height of a line of it (see [Text](#doc-game--views--text)) |
| `Draw.Text(text, position, size, color, anchor)` | Text with `position` another place of its box: `Anchor.MiddleCenter` centers it there |
| `Draw.Text(text, position, size, color, font)` | Text in a font: `Font.Bold`, or one of the game's (see [Fonts](#doc-game--views--fonts)). An anchor goes before it: `Draw.Text(text, position, size, color, anchor, font)` |
| `Draw.MeasureText(text, size)` | Nothing: it returns how big `Draw.Text` would draw the text, a `float2` of its width and height (see [Measuring text](#doc-game--views--measuring-text)). `MeasureText(text, size, font)` measures in a font |
| `Draw.Mesh(vertices, indices)` | Triangles, with a color at each corner (see [Meshes](#doc-game--meshes-and-textures--meshes)) |
| `Draw.Mesh(vertices, indices, texture)` | Triangles drawn with a texture, read as it says or with the filter and the wrap after it (see [Textures](#doc-game--meshes-and-textures--textures)) |
| `Draw.Sprite(texture, center, size, color)` | A texture upright over a box, its top left at the box's top left, times `color` (white without one). `Sprite(texture, center, size, part, color)` draws the part of it a `Rect` of uvs covers, and a `rotation` before the color turns it (see [Sprites](#doc-game--meshes-and-textures--sprites)) |
| `Draw.Blend(mode) { ... }` | How what's drawn in the block goes over what's there: added, multiplied, replaced (see [Blending](#doc-game--draw-settings--blending)) |
| `Draw.Tint(color) { ... }` | Fades or colors what's drawn in the block (see [Tints](#doc-game--draw-settings--tints)) |
| `Draw.Stencil(test, value, operation) { ... }` | What's drawn in the block is drawn only where a number kept for each pixel passes a test, and changes that number where it draws: masks, cut-outs, counting (see [Stencil](#doc-game--draw-settings--stencil)) |
| `Draw.Transform(offset, rotation, scale) { ... }` | Moves, turns and scales what's drawn in the block (see [Transforms](#doc-game--draw-settings--transforms)) |
| `Draw.Clip(rect) { ... }` | Only what's inside `rect` draws, in the block (see [Clipping](#doc-game--draw-settings--clipping)) |
| `Draw.Screen() { ... }` | The calls in the block are in the screen's pixels, from the top left, with `y` down (see [On the screen](#doc-game--views--on-the-screen)) |
| `Draw.SetCamera(position, rotation, fieldOfView)` | Sets the 3D camera for the 3D meshes after it (see [3D](#doc-game--3d)) |
| `Draw.Depth(mode) { ... }` | What the 3D meshes drawn in the block do with depth: hide and are hidden, are only hidden, or neither (see [Depth](#doc-game--3d--depth)) |
| `Draw.Cull(side) { ... }` | Which side of the triangles of the 3D meshes drawn in the block isn't drawn: the back, the front, or neither (see [Which side draws](#doc-game--3d--which-side-draws)) |
| `Draw.Mesh(vertices, indices, transform)` | A 3D mesh, placed in the world by `transform`, with a texture, a filter and a wrap as a mesh's (see [3D](#doc-game--3d)) |
| `Draw.Cube(center, size, color)` | A box with full widths `size.x`, `size.y` and `size.z` |
| `Draw.Sphere(center, radius, color)` | A sphere |
| `Draw.Cylinder(center, radius, height, color)` | A capped cylinder along its local `y` axis, with full `height` |
| `Draw.Plane(center, size, color)` | A rectangle in the local `xz` plane, with full widths `size.x` and `size.y` |
| `Draw.Instanced(vertices, indices, instances)` | One mesh for each instance in a list, 2D or 3D by its vertices, with optional textures and shaders (see [Instances from a list](#doc-game--shaders--instances-from-a-list)) |
Each frame starts black, with the camera at the origin and one world unit per pixel.
## Colors
`Color` has `r`, `g`, `b` and `a`, floats from 0 to 1, as in Unity. Its constructor takes scalars and vectors totaling 3 or 4 channels, in order, just as vector constructors do. `Color(r, g, b)`, `Color(uv.xy, 0)` and `Color(rgb)` have alpha 1; `Color(r, g, b, a)`, `Color(rgb, a)` and `Color(rgba)` set it. Ints and int vectors convert to floats. The constants are `Color.white`, `black`, `red`, `green`, `blue`, `yellow`, `cyan`, `magenta`, `gray` and `clear`. Components and singletons can hold colors.
Colors add, subtract and multiply channel by channel, alpha too, and scale by a number: `tint * Color.red * 0.5`. `==` and `!=` compare two colors whole, every channel and alpha, as they do vectors ([Operators](#doc-language--math--operators)). `Math`'s component-by-component functions take them the same way: `Math.Lerp(a, b, t)` blends two colors, in a view or in a frag.
A color's numbers are the display's own: `Color(0.5, 0.5, 0.5)` is the middle gray a paint program shows for 128, a PNG's pixels are drawn as the file has them, and colors blend and add as those numbers. Nothing is converted on the way in or out, and the screen performs no automatic color-space conversion. It's what sprites and UI want. It isn't how light adds up: two lamps of half don't make white's brightness, and a half-clear white over black is darker than half the light. A game that wants that uses [Linear image sampling](#doc-game--shaders--linear-light-color) for its color textures and works in light in a float target. For unmarked inputs, explicit conversion is also available:
```csharp
// Colors and textures to light as they're read, in the frags that draw the scene
Color paint = models.wood.Sample(vertex.uv);
Color light = Math.ToLinear(paint);
// The last pass, from the float target to the window: under 1 first, then back to the display's numbers
frag Present(Vertex vertex, out Color color, Texture source)
{
Color lit = source.Sample(vertex.uv);
color = Math.ToDisplay(Color(lit.r / (1 + lit.r), lit.g / (1 + lit.g), lit.b / (1 + lit.b)));
}
```
`Math.ToLinear` and `Math.ToDisplay` take `float`, `float3` or `Color` on the CPU and GPU. They use the sRGB transfer curve, clamp RGB to [0, 1], map NaN to zero, and preserve a color's alpha. GPU results have the same rounding limits as other `Math` operations.
The scene is drawn into a [`Format.Rgba16f`](#doc-game--render-targets--what-a-target-holds) target, where light adds up past 1, and `Draw.Blit(scene.color, Draw.window, Present)` shows it. Without the last step the picture is too dark between its lights and flat white where they meet. What's drawn after it, the GUI and text among it, is in the display's numbers as ever.
`Color.none` is no color, for where one can be left out, like a [`Shape`](#doc-game--views--the-general-shape)'s second color. It isn't one to draw with: nothing shows.
## Smooth shapes
`Rect`, `WireRect` and the `Line` without a width fill whole pixels: rects side by side leave no seam between them, and a line is a pixel wide wherever it lands. A circle's edge is smooth, and so are the edges of the shapes that follow, at any size and turned any way:
```csharp
view Bar(Health health)
{
Draw.SetScreen();
var middle = float2(120, 40);
Draw.RoundRect(middle, float2(200, 24), 12, Color(0, 0, 0, 0.6)); // A pill
Draw.RoundRect(float2(22 + health.left * 98, 40), float2(health.left * 196, 20), 10, Color.red);
Draw.WireRoundRect(middle, float2(200, 24), 12, 2, Color.white); // Its outline, 2 pixels thick
Draw.Line(float2(20, 64), float2(220, 64), 3, Color.gray);
Draw.Arc(float2(250, 40), 14, 0, Math.TAU * health.cooldown, 4, Color.yellow); // A ring that fills up
}
```
- Lengths are in the units the calls are in, like positions: world units under the camera, pixels [on the screen](#doc-game--views--on-the-screen). That goes for sizes, radii and widths alike.
- An outline is `width` thick and inside the shape's edge, so a wire shape is as big as the filled one.
- A `radius` rounds a rectangle's corners, up to half its smaller side: that much makes a pill, or a circle of a square.
- An ellipse takes its `radii`, half its width and half its height, as a circle takes its radius.
- A thick line reaches half its width past both ends, which are round, so lines that meet at a point join without a gap.
- Angles are in radians, from `+x` towards `+y`, as `Math.Atan2(y, x)` gives them: counterclockwise under the camera, where `y` goes up, and clockwise on the screen, where it goes down. A `rotation` turns a shape about its center.
- `Arc` draws the part of a circle's outline from the angle `start` on for `sweep`, the other way round for a sweep under 0, and its ends are cut straight across. A `width` of the whole radius makes it a slice of a disc, and a sweep of a whole turn or more is the whole ring.
- A size, radius or width that isn't above 0 draws nothing.
The engine's own shaders draw these, so they take no `frag` or `vert`. For anything they don't draw, there's a [mesh](#doc-game--meshes-and-textures--meshes) and a [frag](#doc-game--shaders) of your own.
Move the slider to fill the bar and ring and rotate the ellipse. The card uses `Shape` for its gradient, outline and soft shadow.
**Smooth shapes** ([Run example](https://tide-engine.dev/examples/shapes/?stats))
```tide
settings { title = "Smooth shapes"; maxPlayers = 1; }
scene Main { }
local singleton ShapeSettings { float amount = 0.65; }
view Shapes(ShapeSettings settings)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0), 3.6);
// A shadow and a card with a gradient, rounded corners and an outline.
Draw.Shape(Shape { center = float2(-1.2, -0.08), size = float2(2, 2.6), radius = 0.2,
color = Color(0, 0, 0, 0.6), soft = 0.3 });
Draw.Shape(Shape { center = float2(-1.2, 0), size = float2(2, 2.6), radius = 0.2,
color = Color(0.22, 0.22, 0.25), color2 = Color(0.12, 0.12, 0.14),
outline = 0.025, outlineColor = Color(0.36, 0.37, 0.41) });
// A pill-shaped bar fills with the slider's value.
Draw.RoundRect(float2(-1.2, 0), float2(1.6, 0.28), 0.14, Color(0.086, 0.086, 0.094));
Draw.RoundRect(float2(-2 + settings.amount * 0.8, 0), float2(settings.amount * 1.6, 0.28), 0.14, Color(0.98, 0.75, 0.14));
Draw.WireRoundRect(float2(-1.2, 0), float2(1.6, 0.28), 0.14, 0.02, Color.white);
// Outlines stay equally wide all the way around an ellipse.
Draw.Shape(Shape { center = float2(1.2, 0.65), size = float2(1.7, 0.8), ellipse = true,
rotation = settings.amount, color = Color(0.98, 0.44, 0.52),
outline = 0.045, outlineColor = Color.white });
Draw.WireCircle(float2(1.2, -0.7), 0.5, 0.13, Color(0.24, 0.25, 0.27));
Draw.Arc(float2(1.2, -0.7), 0.5, 0, Math.TAU * settings.amount, 0.13, Color(0.18, 0.83, 0.75));
Draw.Line(float2(-2, -1.8), float2(2, -1.8), 0.08, Color(0.18, 0.83, 0.75));
}
view Controls(mut ShapeSettings settings)
{
Draw.SetScreen();
Draw.Text("Shapes, gradients and outlines", float2(16, 14), 18, Color.white);
GUI.SetTheme(GUITheme { radius = 6 });
GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Amount", settings.amount, 0, 1);
}
```
Shapes of every kind drawn one after another go to the GPU together, in one draw call, in the order they're written, so thousands a frame are cheap. Text or a mesh between them starts another.
### The general shape
Those calls are short for `Draw.Shape`, which takes everything a shape can have:
For a rectangle already represented by a `Rect`, use `Draw.Rect(rect, color)`,
`Draw.Rect(rect, radius, color)` or `Draw.Rect(rect, radii, color)`. All three
have antialiased edges, including square corners. A `float4` gives the top-left,
top-right, bottom-right and bottom-left radii; each is clamped to half the
smaller side. Equal radii use the ordinary rounded-box path. These filled boxes
need no GUI theme and work inside `GUI.Draw` as well as ordinary views.
The center/size `Draw.Rect` overload keeps its whole-pixel behavior for seamless
adjacent tiles. `Shape` continues to provide gradients, outlines and soft edges
with a uniform corner radius.
```csharp
struct Shape // Built in
{
float2 center;
float2 size; // Its width and height
float rotation;
float radius; // Its corners'
bool ellipse; // The ellipse that fits `size`, rather than a box
Color color = Color.white; // Its fill...
Color color2 = Color.none; // ...and its fill at its bottom, when it's another
float outline; // How wide its outline is, inside its edge
Color outlineColor = Color.white;
float soft; // How far its edge fades
}
```
```csharp
view Card(Deal deal)
{
Draw.SetScreen();
// A shadow first: a dark shape whose edge fades outwards
Draw.Shape(Shape { center = deal.at + float2(0, 6), size = float2(180, 240), radius = 16,
color = Color(0, 0, 0, 0.5), soft = 18 });
// The card: lighter at its top than at its bottom, with an outline
Draw.Shape(Shape { center = deal.at, size = float2(180, 240), radius = 16,
color = Color(0.16, 0.2, 0.34), color2 = Color(0.07, 0.09, 0.17),
outline = 2, outlineColor = Color(0.5, 0.62, 0.8) });
}
```
- **`color2`** makes the fill go from `color` at the shape's top to `color2` at its bottom. Top and bottom are the shape's own, as it is before `rotation` turns it, and the top is the upper one on the screen whether `y` goes up or down. Left at `Color.none`, the fill is `color` all over. A fill that goes to a clear color fades out without getting darker on the way.
- **`outline`** is an outline that wide in `outlineColor`, inside the edge, over the fill.
- **`soft`** above 0 fades the edge outwards: the shape's color goes on past its edge and is gone `soft` further out, which is a glow in a light color and a shadow in a dark one. Under 0, it fades inwards from the edge instead and leaves the middle clear, like a vignette over the whole screen. At 0 the edge is sharp, smooth over one pixel.
- **`ellipse`** makes it the ellipse that fits `size`, whatever `radius` says.
`Arc` is the one call `Shape` doesn't cover.
### Fills
A fill colors a shape by a function of where in it each pixel is: `Draw.Rect(rect, radius, fill)`, `Draw.Rect(rect, radii, fill)` with four corners, and `Draw.Shape(shape, fill)`, where `fill` is a `Func`. It runs on the GPU for each pixel, given the pixel's place in the shape from `(0, 0)` at its top left to `(1, 1)` at its bottom right. `Gradient`'s functions make the usual ones:
```csharp
view Buttons()
{
Draw.SetScreen();
// Lighter at the top: a button that looks raised
Draw.Rect(Rect(20, 20, 200, 48), 12, Gradient.Vertical(Color(0.35, 0.5, 0.9), Color(0.15, 0.25, 0.6)));
// Three colors, left to right
Draw.Rect(Rect(20, 80, 200, 48), 24, Gradient.Horizontal(Color.red, Color.yellow, Color.green));
// A glow: bright in the middle, clear at the edge
Draw.Rect(Rect(240, 20, 108, 108), 54, Gradient.Radial(Color(1, 0.9, 0.5), Color.clear));
// Any function of the place: stripes
Draw.Rect(Rect(20, 140, 200, 48), 8, (float2 uv) => int(uv.x * 8) % 2 == 0 ? Color.white : Color.gray);
}
```
| Function | From, to |
|---|---|
| `Gradient.Vertical(top, bottom)` | The shape's top to its bottom |
| `Gradient.Horizontal(left, right)` | Its left to its right |
| `Gradient.Linear(angle, from, to)` | Across it at `angle`, in radians from `+x` towards `+y`, one corner to the opposite one |
| `Gradient.Radial(inner, outer)` | Its middle out to the middle of its sides, and on to its corners |
`color.WithAlpha(a)` is the color with another alpha, its red, green and blue as they are: a glow of an item's color, `rarity.WithAlpha(0.4)`. It works in a fill, and in any GPU code, too.
`color.rgb` is its red, green and blue as a `float3`, for the math a light or a blend does on them: `Color(tint.rgb * shade, tint.a)`. It's read, never assigned, and works in GPU code.
A `Rect` reads as vectors too: `rect.position` is its top left corner, `rect.size` its width and height and `rect.center` its middle, each a `float2`, so a label goes at `slot.center` with `Anchor.MiddleCenter`. `rect.Contains(point)` says whether a point is in it, like the pointer over a slot (its left and top edges are in, its right and bottom ones out, so slots side by side share no point), and `rect.Inset(amount)` is the rect with every edge moved in by that much, or out by an amount under 0: `Draw.Rect(slot.Inset(1), 4, fill)` inside a border.
Each takes two, three or four colors, spread evenly: `Gradient.Vertical(a, b, c)` is `b` at the middle. Colors blend with their alpha, so a gradient to `Color.clear` fades without darkening.
- **A fill is a value.** Keep one in a field, pass it to a helper, or write your own: a function `Color Name(float2 uv)` named where a fill goes, or a lambda, which can use the variables around it: `Draw.Rect(rect, 8, (float2 uv) => tint * (1 - uv.y * 0.3))`. Calling one on the CPU gives the color a pixel there gets.
- **A fill can take the shape's size too:** a `Func`, given the place and the shape's size in the units it's drawn in (pixels on the screen), for patterns of a fixed size whatever the shape's: `Draw.Rect(bar, 6, (float2 uv, float2 size) => int(uv.x * size.x / 12) % 2 == 0 ? light : dark)` has stripes 12 pixels wide.
- **The rest of the shape is as ever.** `Draw.Shape(shape, fill)` takes its center, size, rotation, corners, outline, soft edge and ellipse from `shape`, and the fill replaces `color` and `color2`. Its place in the shape is the shape's own, before `rotation` turns it, and its top is the upper one on the screen whether `y` goes up or down.
- **Fills drawn one after another are drawn together,** whatever their functions: a menu of gradient buttons costs one draw. The function is GPU code, with [what the GPU runs](#doc-game--shaders--what-the-gpu-runs)' rules.
- **They're local code.** A fill is drawn by views and the functions they call, in the window or inside [`GUI.Draw`](#doc-game--gui--custom-controls-in-layout). A [render target](#doc-game--render-targets)'s own `Rect` and `Shape` take one too, drawn by the target's size: `card.Rect(Rect(0, 0, 200, 60), 12, Gradient.Vertical(top, bottom))`.
## On the screen
In `Draw.Screen() { ... }`, Draw calls are in the screen's pixels: from the top left, with `y` down, as the GUI's are, `Screen.width` by `Screen.height`. After the block, the camera is what it was, so a view of the world can draw a label in pixels and leave the world's camera alone for the views after it:
```csharp
view Nameplates(Player player, Body body)
{
var above = Draw.WorldToScreen(body.position + float2(0, 1.5));
Draw.Screen()
{
var size = Draw.MeasureText(player.name, 14);
Draw.Text(player.name, above - float2(size.x * 0.5, size.y), 14, Color.white);
}
}
```
A view that only draws on the screen can set it for the views that follow instead, with `Draw.SetScreen()`:
```csharp
view Health(Stats stats)
{
Draw.SetScreen();
Draw.Rect(float2(110, 30), float2(200, 20), Color.gray);
Draw.Rect(float2(10 + stats.health, 30), float2(stats.health * 2, 20), Color.red);
}
```
`Draw.SetCamera` goes back to the world. What views draw on the screen is under the GUI's widgets, which draw last.
The mouse, touches and the pointer count pixels from the bottom left instead, with `y` up. `Screen.Flip(devices.pointer.position)` is where the pointer is in the screen's pixels: see [Screen and world coordinates](#doc-game--cameras--screen-and-world-coordinates).
## Text
`Draw.Text(text, position, size, color)` draws text in the engine's font. Its `size` is its font size, as CSS's and Unity's: the height of a line of it, with its capitals in the line's middle. A newline in the text starts another line under it. Text is fitted to the display's pixels, so it's sharp at the sizes it's read at.
### Anchors
Without more, `position` is the text's top left corner. An `Anchor` after the color says which place of the text's box it is instead, the nine of Unity's `TextAnchor`: `UpperLeft`, `UpperCenter`, `UpperRight`, `MiddleLeft`, `MiddleCenter`, `MiddleRight`, `LowerLeft`, `LowerCenter` and `LowerRight`.
```csharp
view Banner(Round round)
{
Draw.SetScreen();
var middle = float2(Screen.width, Screen.height) * 0.5;
Draw.Text("FIGHT!", middle, 64, Color.white, Anchor.MiddleCenter);
Draw.Text($"Round {round.number}", float2(Screen.width - 16, 16), 24, Color.gray, Anchor.UpperRight);
}
```
That's a word in the middle of the screen, and the round's number against its top right corner, wherever the window's edges are and however wide the text comes out.
The box is as wide as the text's widest line and as tall as its lines. Upper is towards the top of the screen, whether the calls are in the world, where `y` goes up, or in the screen's pixels, where it goes down: a name over a body is `Draw.Text(player.name, body.position + float2(0, 1), 0.5, Color.white, Anchor.LowerCenter)` under any camera. Text of several lines lines up on the anchor's side: its lines start together at a left anchor, end together at a right one, and are centered on one between.
### Bold
The font has two weights. `Font.Bold`, last in the call, draws text in the font's own bold:
```csharp
Draw.Text("DUEL", at, 88, Color.white, Font.Bold);
Draw.Text("DUEL", at, 88, Color.white, Anchor.MiddleCenter, Font.Bold);
```
`Font.Regular` is the weight text has without one. A `Font` is a value, so a function can take one and pass it on, and `.Bold` and `.Regular` name the two where a `Font` goes.
Bold is a second font file, and a game only carries it when its code says `Font.Bold`: about 95 KB more in the program, and nothing for a game that never does. Its strokes are a whole number of pixels thick, as the regular weight's are, so text stays sharp. At the smallest sizes, under 13 of the display's pixels, that's one pixel in both weights: bold is for text of about that size and up, and for titles. A letter the bold weight doesn't have (it covers Latin, Greek and Cyrillic, less widely than the regular one) is drawn in the regular weight.
The GUI's widgets are in the regular weight, unless their [theme](#doc-game--gui--themes) says another font.
### Fonts
A game can have fonts of its own, as many as it likes, each drawn wherever a call names it. A font file is an asset:
```csharp
asset Font title = "fonts/Title.ttf";
asset Map fonts = "fonts/*.ttf";
view Hud(Round round)
{
Draw.Text("ROUND 3", float2(40, 40), 64, Color.white, title);
Draw.Text(round.message, float2(40, 120), 20, Color.white, fonts["fonts/Body.ttf"]);
}
```
A `Font` asset is a TrueType font: a `.ttf`, an `.otf` of TrueType outlines, or the first font of a `.ttc`. Many `.otf` files have CFF (PostScript) outlines instead, which aren't read: the build says so, and a font tool converts one to `.ttf`. A file that isn't a font it can read is an error where it's declared.
A font that comes as the game runs, a player's file or one fetched from the web, is decoded from its bytes in local code:
```csharp
local singleton Chat { Font font; bool loaded; }
view Load(mut Chat chat, ChatSettings settings)
{
if (chat.loaded) return;
chat.font = Font.Decode(settings.fontBytes)!;
chat.loaded = true;
}
```
`Font.Decode` fails with `IOError.InvalidData` for bytes that aren't such a font. It reads every file with the engine's own reader, which checks every place a file names before it reads anything there, so a broken or hostile file can't make the game read or write outside it. A file past its limits (64 MiB, or more glyphs and outlines than any font has) is refused too. Decoding the same bytes again gives the same font, at no cost.
A `Font` is this machine's, as a `Texture` is: views, local handlers and local tasks hold one, and the match doesn't. A font every player should see goes into the match as bytes, a `List` field, which each machine decodes.
A character a font has no glyph for is drawn in `Font.Regular`. Every font is fitted to the display's pixels as the engine's is, so text in it is sharp; hints and kerning in the file aren't read.
### Measuring text
To fit a panel around a text, or to put something beside it, ask how big it will be: `Draw.MeasureText(text, size)` returns a `float2`, the width of the text's widest line in `x` and the height of its lines in `y`. One line is `size` high, and each newline adds a line. It's the box an anchor names a place of.
```csharp
view Banner(Round round)
{
Draw.SetScreen();
var middle = float2(Screen.width, Screen.height) * 0.5;
var size = Draw.MeasureText(round.message, 48, Font.Bold);
Draw.Rect(middle, size + float2(32, 16), Color.black);
Draw.Text(round.message, middle, 48, Color.white, Anchor.MiddleCenter, Font.Bold);
}
```
That's the message in the middle of the screen, on a panel that fits it. Bold text is wider than regular, so it's measured in its weight: `Draw.MeasureText(text, size, Font.Bold)`, as text in any font is measured in it.
Below, the cross is the position the text is given, and the frame is the box `MeasureText` says it has. Move the anchor's slider to put another place of the box on the cross, and change the size and the weight to see the box follow.
**Anchors, sizes and weights** ([Run example](https://tide-engine.dev/examples/text/?stats))
```tide
settings { title = "Text"; }
local scene Main { }
local singleton Label
{
string words = "Tide\nfits text to pixels";
float size = 26;
int anchor = 4; // Anchor.MiddleCenter
bool bold;
}
view Show(mut Label label)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetScreen();
var at = float2(Screen.width * 0.5, Screen.height * 0.3);
var anchor = Anchor(label.anchor);
var font = label.bold ? Font.Bold : Font.Regular;
// The box MeasureText gives is the one an anchor names a place of.
var size = Draw.MeasureText(label.words, label.size, font);
var corner = at - float2(size.x * (label.anchor % 3) * 0.5, size.y * (label.anchor / 3) * 0.5);
Draw.WireRect(corner + size * 0.5, size, Color(0.3, 0.3, 0.33));
Draw.Text(label.words, at, label.size, Color.white, anchor, font);
// The position the text was given.
Draw.Line(at - float2(10, 0), at + float2(10, 0), 2, Color(0.98, 0.75, 0.14));
Draw.Line(at - float2(0, 10), at + float2(0, 10), 2, Color(0.98, 0.75, 0.14));
GUI.SetTheme(GUITheme { radius = 6 });
GUILayout.Area(Rect(12, Screen.height - 178, Screen.width - 24, 166))
{
GUILayout.Label($"Anchor.{anchor}: {size.x:F0} by {size.y:F0} pixels");
GUILayout.IntSlider("Anchor", label.anchor, 0, 8);
GUILayout.Slider("Size", label.size, 10, 56);
GUILayout.Toggle("Font.Bold", label.bold);
}
}
```
The answer is in the units the Draw calls are in: pixels on the screen, and the world's under a camera.
It's what `Draw.Text` would draw at that point of the view, to the pixel. Text is fitted to the display's pixels to stay sharp, so the same text can come out a little wider or narrower on another display, under another camera or in a window of another size: measure where you draw, each frame, rather than keeping the answer. A [render target](#doc-game--render-targets) has its own camera, and pixels of its own to fit text to, so `target.MeasureText(text, size)` measures for it.
## Smooth at any tick rate
Views draw at whatever frame rate the game renders, not the tick rate, and see the match blended between its last two ticks. So motion is smooth even at 20 ticks per second, at the cost of drawing up to a tick late.
Every float, vector, quaternion and color a view reads of the match is blended, `Time.t` among them. Ints, bools, enums, entities and text come from the upper endpoint. An entity that wasn't there at the previous endpoint is drawn as it is. What a view reads [`verified`](#doc-game--views-and-the-match--confirmed-state) blends on a separate confirmed clock, which holds at the latest confirmation and never extrapolates.
The match below ticks only five times a second. Both discs are the same position: the amber one is an ordinary field, which the view sees blended between ticks, and the teal one a `[Snap]` field, drawn as the last tick left it.
**Five ticks a second, drawn every frame** ([Run example](https://tide-engine.dev/examples/tick-rate/?stats))
```tide
settings { title = "Tick rate"; tickRate = 5; maxPlayers = 1; } // Five ticks a second
component Mover
{
float angle;
float2 position; // A view sees it blended between the last two ticks
[Snap] float2 stepped; // Kept out of blending: as the last tick left it
}
scene Main { }
event(Spawned) Setup(with Main)
{
Spawn(Mover { position = float2(1.3, 0), stepped = float2(1.3, 0) });
}
// The match only moves five times a second.
system Orbit(mut Mover mover, Time time)
{
mover.angle += time.dt * 1.6;
mover.position = float2(Math.Cos(mover.angle), Math.Sin(mover.angle)) * 1.3;
mover.stepped = mover.position;
}
// Views run every frame, and draw the same match.
view Show(Mover mover, Time time)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, -0.1), 2.2);
Draw.WireCircle(float2(0), 1.3, 0.02, Color(0.24, 0.25, 0.27));
Draw.Circle(mover.stepped, 0.2, Color(0.18, 0.83, 0.75));
Draw.Circle(mover.position, 0.14, Color(0.98, 0.75, 0.14));
Draw.SetScreen();
Draw.Text($"tick {time.tick}, at {time.tickRate} ticks a second", float2(16, 14), 18, Color.white);
Draw.Text("float2 position: blended", float2(16, Screen.height - 50), 14, Color(0.98, 0.75, 0.14));
Draw.Text("[Snap] float2 stepped: as the tick left it", float2(16, Screen.height - 30), 14, Color(0.18, 0.83, 0.75));
}
```
`[Snap]` keeps a field out of blending, for angles that wrap and values that jump:
```csharp
component Body
{
float2 position; // Blended
[Snap] float heading; // Wraps from 360 to 0: as it is
int lives; // Ints are as they are
}
```
### Jumps
Something that jumps, like a respawn, a portal or a camera cut, says so from match code: `entity.Snap()` or `singleton.Snap()`. For the tick it happens in, views draw it as it is, instead of sliding from where it was.
```csharp
event(Died dead) Respawn(mut Body body, Arena arena)
{
body.position = arena.start;
this.Snap(); // No sliding from where it died
}
```
`entity.Snap()` is applied at the end of the tick, like `Destroy`, so it never makes systems wait. `singleton.Snap()` needs the singleton as a `mut` parameter.
A single field can jump too: `field.Snap()` is the per-field counterpart of `entity.Snap()`. For the tick it happens in, views draw that field as it is at the newer tick, and from the next tick it blends again. The rest of its component or singleton keeps blending, so a position doesn't stutter.
Use it whenever a float starts over together with something that doesn't blend. Here a stance is an enum, so views see the new stance at once, and `since` counts the seconds in it:
```csharp
component Fighter
{
Stance stance;
float since; // Seconds in this stance
float3 hand;
mut void Enter(Stance next)
{
stance = next;
since = 0;
since.Snap(); // Drawn from 0 with the new stance
}
}
```
**Warning: A timer that starts over**
Without `since.Snap()`, every frame between the two ticks shows the new stance with `since` blended between its old value and 0: a timer running backwards, which pops whatever the view works out from it. `[Snap]` on the field would avoid it, but then `since` never blends, and `this.Snap()` stops the whole entity blending, position included.
`field.Snap()` goes on a field of a match component or singleton that views blend, wherever code may write that field: systems, match event handlers, and the functions and methods they pass it to. A field that holds a struct snaps all of it, as in `arm.pose.Snap()`; a struct's own field can't snap alone. Each field that snaps keeps a count of its snaps beside it in the match, so snapshots, rollback and host migration carry it, and it is part of the match hash.
### Provisional correction smoothing
**Warning: Provisional**
`[Position]` and `[Rotation]` are available, with provisional names and behavior. They may change as games test them.
Tick interpolation makes motion smooth between ticks. A prediction correction can still move the next frame abruptly. These attributes tell Tide how to preserve the displayed value and remove the correction error over time:
```csharp
component Body
{
[Position] float2 position;
[Rotation] float heading; // Radians, for 2D
float2 velocity; // Ordinary tick interpolation
}
```
`[Position]` accepts `float`, `double` and their vector types. It keeps linear tick interpolation and accumulates an additive presentation offset in the field's own precision. Double positions and correction errors remain double, preserving small offsets at large world coordinates. `[Rotation]` on a float uses the shortest wrapped angular difference, in radians. On a quaternion it uses the shortest relative rotation, for both tick interpolation and correction smoothing.
For a game with its own large-world transform, the same attribute works on double coordinates:
```csharp
component WorldPosition
{
[Position] double3 position;
}
```
This smooths the value views read. Convert to rendering coordinates after subtracting the camera position in double precision; the drawing APIs still take floats.
The error decays exponentially with frame time toward zero, or the identity rotation, with a provisional half-life of 75 ms. Another correction accumulates with whatever error remains. Ordinary movement follows the corrected simulation, so moving and aiming stay responsive. Untagged fields keep ordinary tick interpolation.
The built-in `Transform` already uses this behavior for its match fields: `localPosition` is a `[Position]` and `localRotation` a `[Rotation]`. Its scale uses ordinary tick interpolation. These defaults apply to view bindings; `World.LocalToWorld` and other stored-state queries retain their existing behavior. Local-entity Transforms read their current values.
This state belongs to this machine's presentation. Simulation values and collisions correct immediately, and snapshots, hashes and network state are unaffected. `entity.Snap()` and `singleton.Snap()` also clear any accumulated error, keeping intentional jumps immediate. A new match, a hot reload or a replacement world with no comparable presentation history clears the error too. While a host migration reconnects, the frozen presentation retains its error; adopting the new network timeline clears it.
The tags take no arguments. Use them on match fields; local state, inputs and events cannot carry them. A field cannot combine `[Position]`, `[Rotation]` and `[Snap]`, and such a field can't snap alone with `field.Snap()`: snap its entity or singleton, which clears its error too.
Ordinary structs can contain annotated built-in fields, including through nested structs. Correction smoothing for a type with its own `Interpolate` is deferred; its existing tick interpolation remains available. No new custom-type method or correction-rate setting is agreed. The [specification](https://tide-engine.dev/spec.md#provisional-correction-smoothing) records the provisional contract.
### Blending your own way
A struct or component can say how it blends with an `Interpolate` method, declared in it like an operator. It replaces the default blend for that type wherever views see it:
```csharp
struct Angle
{
float degrees;
Angle Interpolate(Angle from, Angle to, float t)
{
mut var d = to.degrees - from.degrees;
if (d > 180) d -= 360;
if (d < -180) d += 360;
return Angle { degrees = from.degrees + d * t };
}
}
component Body
{
float2 position; // Blended as usual
Angle heading; // Blended the short way round
}
```
`Interpolate` isn't for code to call. Custom interpolation is declared on structs or components; a singleton blends its own way through a struct in it that has one.
## A frame's length
Frames come at the display's rate: 60 a second on one screen, 144 on another, fewer when the machine is busy. What a view animates of its own, like particles, a menu that slides in or a camera's shake, moves by time rather than by frames. `Frame.dt` is the seconds since the previous frame started:
```csharp
struct Spark
{
float2 position;
float2 velocity;
float age;
float life = 0.4;
}
local singleton Sparks
{
List list;
}
view DrawSparks(mut Sparks sparks)
{
mut var i = 0;
while (i < sparks.list.count)
{
mut var spark = sparks.list[i];
spark.age += Frame.dt;
if (spark.age >= spark.life)
{
sparks.list.RemoveAt(i);
continue;
}
spark.velocity.y -= 9.8 * Frame.dt;
spark.position += spark.velocity * Frame.dt;
sparks.list[i] = spark;
Draw.Circle(spark.position, 0.1 * (1 - spark.age / spark.life), Color.yellow);
i++;
}
}
```
- **It's this machine's, not the match's.** It's there with no match, in a menu and while connecting, where a view that takes `Time` doesn't run. In a match it's the same value, whatever the tick rate.
- **The match has `Time`.** What's in the match moves by `time.dt`, a tick's length, in systems. A view draws the match as it is, already [blended](#doc-game--views--smooth-at-any-tick-rate) to the frame, and uses `Frame.dt` for what it adds on top. A system that reads `Frame.dt` is an error that says so.
- **It's the frame's real length.** A frame after the window was dragged, or the page was hidden, is as long as that took. Clamp it where a big step would show: `var dt = Math.Min(Frame.dt, 0.05);`.
- **There's no clock beside it.** No `Frame.time`: code that asks `Frame` for one is an error that says what to write. A float of seconds gets coarser as it grows: after four and a half hours it counts in steps of 2 milliseconds, and whatever it animates starts to judder. Keep a clock of your own instead, in [local state](#doc-game--local-state): add `Frame.dt` up into a field, and wrap it where what it drives repeats:
```csharp
local singleton Spinner
{
float turn; // Radians, always under a full turn
}
view Spin(mut Spinner spinner)
{
spinner.turn += Frame.dt * 4;
if (spinner.turn > Math.TAU) spinner.turn -= Math.TAU;
Draw.Circle(float2(Math.Cos(spinner.turn), Math.Sin(spinner.turn)), 0.1, Color.white);
}
```
What moves with the match, the same for every player, reads the match's time instead: a view takes `Time time` and reads `time.t`, [the seconds since the match started](#doc-game--entities--singletons), which it sees move every frame.
Views read `Frame.dt`, and so does the rest of [local code](#doc-game--local-state--time): the functions they call, local handlers and local tasks.
## Reading this machine's devices
Views take `Devices devices` to read this machine's input devices for the frame: `.down` and `.up` since the last frame, and the `delta` of the mouse, touches and the pointer, and the mouse's `scroll`, too. A view that wants the mouse for itself [locks the cursor](#doc-game--cameras--looking-around). What the GUI is using is hidden from them, and so is what another view [claimed](#doc-game--gui--widgets-of-your-own) for widgets of its own. They read [what's typed](#doc-game--input--typed-text) too, as `devices.keyboard.text`. Helpers take the devices or a part of them as an explicit parameter. A helper that reads `keyboard.text` needs the frame, so only views and the functions they call can call it.
---
Source: https://tide-engine.dev/game/views-and-the-match.md
What a Tide view reads of the match: other entities through a query, this machine's player's own with ownership filters, and what the server has confirmed with verified.
# Views and the match
A [view](#doc-game--views) runs for the entities its parameters pick, and reads the match as this machine predicts it, [blended](#doc-game--views--smooth-at-any-tick-rate) between its last two ticks. This page is what else it reads: entities other than its own, the ones this machine's player owns, and what the server has confirmed.
## Other entities
A view runs for its own entities, and often needs the others too: a shadow falls on the highest platform under a fighter, an aim line ends at whoever it would hit. A `query` parameter is that second set, as in a [system](#doc-game--systems--another-set-of-entities):
```csharp
// A fighter's shadow falls on the highest platform under it.
view DrawFighter(Body body, with Fighter, query (Platform box) platforms)
{
mut var ground = -10000.0;
foreach (var entry in platforms)
{
var top = entry.box.center.y + entry.box.half.y;
var over = Math.Abs(body.position.x - entry.box.center.x) < entry.box.half.x;
if (over && top <= body.position.y && top > ground) ground = top;
}
Draw.Ellipse(float2(body.position.x, ground), float2(body.radius, 2), Color(0, 0, 0, 0.5));
Draw.Circle(body.position, body.radius, Color.white);
}
```
The view's own parameters still pick the entities it runs for, and the query picks the ones it goes through for each: neither filters the other. Inside the `foreach`, `entry.box` is that platform's `Platform`, to read, and `entry.entity` is its handle. The syntax and the filters are a system's: bindings, `with` and `without`. A view with only queries runs once a frame.
- **Rows are what the view sees.** They're [blended](#doc-game--views--smooth-at-any-tick-rate) between the last two ticks like the view's own parameters, with corrections smoothed the same way: the row of the view's own entity has the values its parameters have. An entity that wasn't there last tick is as it is, and one that's gone is in no row.
- **`verified` works in a query** as it does on a view's own parameters (see [Confirmed state](#doc-game--views-and-the-match--confirmed-state)). `query (verified Health health) confirmed` goes through the confirmed world's entities, at the upper endpoint of its confirmed presentation interval. A query with bindings or filters of both worlds, `query (Body body, verified Health sure) both`, takes the entities that are in both: the same entity, and not only the same handle. `with verified Dead` and `without verified Dead` filter there too.
- **A query is all the match's or all this machine's.** A view goes through local entities too, like its own sparks: `query (Spark spark) sparks`. Those are as they are now, with what views earlier in the frame wrote, and `entry.entity` is a `LocalEntity`.
- **Match fields remain read-only.** A row can also read the entity's current [local fields](#doc-game--local-state--local-fields). Use `query (mut Fighter fighter) fighters` to write those local fields; the component's match fields and the row's entity handle stay read-only. This works with verified bindings too: local fields always use current local state. Queries over local-world components still have read-only bindings.
- **A view that queries the match only runs in a match**, like any view that reads it. What should go on outside one stays in a view of its own.
- **Going through a lot stays cheap.** A query's rows are made once a frame, however many entities the view runs for: a view over thousands of entities that goes through thousands of others blends those others once, not once for each.
The rest is as in a system: queries are iterated directly or [borrowed by synchronous helpers](#doc-language--functions--borrowing-a-query), which keep the view's blended or verified data. Queries and whole rows can't be stored or returned, and whole rows can't be passed on; a component value like `entry.box` can. The order is the ECS's, not by distance or by entity ID. The editor says what a view's queries read above the view and on hover, as it does for a system.
For example, mark the presentation of every dead fighter:
```csharp
component Fighter
{
int health;
local float flash;
}
view MarkDead(query (mut Fighter fighter) fighters)
{
foreach (var row in fighters)
if (row.fighter.health <= 0) row.fighter.flash = 1;
}
```
Passing `row.fighter` directly to a helper retains its local fields and the binding's write permission. Copying it into an ordinary variable copies only match data. A helper can borrow the whole query with a mutable binding when the source binding is mutable.
A view takes a `World` as a system does, to read another entity's component by its handle: `world.Get(follower.leader)` (see [Other entities](#doc-game--systems--other-entities-the-world)). It reads the match through it and never changes it, and what it gets is the component as of the latest tick, not blended between ticks.
## Your own entities
"My camera, my HUD, my health bar" is in every multiplayer game, so views have a filter for it. `with ownership` picks the entities this machine's player owns, and `without ownership` every other one:
```csharp
view RenderGame(Player player, with ownership)
{
Draw.SetCamera(player.pos, player.rot, 75);
}
// Everyone else's body: a first-person camera doesn't draw its own
view Bodies(Player player, Scenery scenery, without ownership)
{
Draw.Mesh(scenery.crate, scenery.faces, float4x4.TRS(player.pos, player.rot, float3(1)), scenery.wood);
}
```
- `with ownership`: the entity has an [`Owner`](#doc-game--input--who-gets-which-input), and its `player` is `Session.player`, this machine's player.
- `without ownership`: every other entity the view's parameters admit, which is another player's and those with no `Owner`. With `with Owner` beside it, only those whose owner is someone else.
They're filters, beside `with` and `without`: the view takes neither `Owner` nor `Session` for them, and `if (owner.player != session.player) return;` goes. A view that wants both kinds at once, like one that draws your player yellow and the others gray, still takes `Owner` and `Session` and compares.
Views have them, and so do [command handlers](#doc-game--commands--only-the-sender-s-own-entities), where the player is the command's sender. The rest of the match runs the same on every machine, so a system can't ask whose machine it's on: there it's an error, and `with Owner` picks the entities that any player owns. A local handler doesn't filter by them either: one of a match event takes `Owner owner` and `Session session`, and compares (see [Events](#doc-game--events--what-isn-t-there-yet)). `ownership` is a keyword only right after `with` and `without`, so it still names anything else.
## Confirmed state
In a match with other machines, a client runs ahead of the server: its views draw the world as this machine predicts it, and a prediction can be wrong for a moment, until the server says how the tick went (see [Networking](#doc-multiplayer--networking--prediction-and-rollback)). That suits what has to answer at once, like movement. What must not be wrong, like a health bar, a score or a death, is read `verified`: from the world the server has confirmed.
`verified` goes before a parameter's type, like `mut`:
```csharp
// Movement as predicted, the health bar only what's confirmed.
view DrawFighter(Body body, verified Health health)
{
Draw.Circle(body.position, 0.5, Color.white);
Draw.Rect(body.position + float2(0, 0.8), float2(health.value * 0.01, 0.1), Color.red);
}
// The same component twice: what's predicted, and what's confirmed so far.
view HealthBar(Body body, Health health, verified Health confirmed)
{
var at = body.position + float2(0, 1);
Draw.Rect(at, float2(confirmed.value * 0.01, 0.1), Color.gray);
Draw.Rect(at, float2(health.value * 0.01, 0.1), Color.red);
}
// A filter, and a singleton.
view Corpse(Body body, with verified Dead)
{
Draw.Circle(body.position, 0.5, Color.gray);
}
view Board(verified Duel duel)
{
Draw.SetScreen();
Draw.Text($"Round {duel.round}", float2(20, 20), 24, Color.white);
}
```
- **A view runs for an entity when each parameter exists in the world it names.** A view with components of both worlds needs the entity in both, so it skips one whose spawn isn't confirmed yet. A game that wants it drawn sooner splits the view in two: one that draws what's predicted, and one that adds what's confirmed.
- **A view whose components are all `verified`** runs for the confirmed world's entities, and draws them as they are there: `this` is the confirmed entity, and corrections aren't smoothed.
- **Filters take it**: `with verified Dead`, `without verified Dead`. Either asks for the entity in the confirmed world: `without verified Dead` is "confirmed, and not `Dead` there", so it skips an entity whose spawn isn't confirmed yet too.
- **Singletons take it**: `verified Duel duel`.
- **A `verified` value is whole.** Its text, lists, maps, sets and grids are the confirmed world's, and read like any other's: `sure.build.cards.count`, `foreach (var card in sure.build.cards)`, a copy of the value, a function it's passed to. They're to read, like everything a view takes of the match: to change one, take a copy.
- **A `verified` value interpolates between confirmed ticks.** Its presentation clock holds at the latest confirmation and never extrapolates. Floats and rotations follow the ordinary [interpolation rules](#doc-game--views--smooth-at-any-tick-rate), including custom `Interpolate` and `Snap()`. Entity membership, integers, tags and containers come from the upper confirmed endpoint.
- **`mut` goes with it.** `mut verified Health health` reads the confirmed `Health` and writes the entity's [local fields](#doc-game--local-state--local-fields), which are the entity's whichever world a parameter reads. A view that takes a component both ways reaches its local fields through the one that isn't `verified`.
- **The same entity** in both worlds is the entity, not only its handle: running a tick again can give a handle to another entity, which is then in one world only (see [After a rollback](#doc-game--local-state--after-a-rollback)).
- **It's the view's to say.** A function's parameter can't say `verified`: the view takes the value `verified` and passes it on. Nor can a [frag or vert](#doc-game--shaders), which reads what its view is given.
- **The match has no "confirmed".** It's the same on every machine, so `verified` in a system, a match handler or a task is an error, which points to views and local handlers.
Outside a match, a view with a `verified` parameter doesn't run, like any view that reads the match. A local handler takes `verified` on its event, to hear it once it's certain: see [Events](#doc-game--events--verified-handlers).
### Holding a death until it's confirmed
With a predicted `Body`, an entity is gone from a view the moment the prediction destroys it, whatever a `verified` parameter beside it says: the view needs the entity in both worlds. There are three ways to hold a death until the server has confirmed it:
- **Make the death a state of a living entity**, a field or a tag like `Dead`, and destroy the entity later. Views read the state `verified`, as `Corpse` does above.
- **Take everything `verified` in that view.** It then runs for the confirmed world's entities, so the entity is drawn, as the server last confirmed it, until the server says it's gone.
- **Show it from a local handler**: `local event(verified Destroyed) ...` hears the entity go once it's certain, with its components as they were (see [Events](#doc-game--events--verified-handlers)).
### What isn't there yet
- **`verified World world`**, which is an error that points to `verified` component parameters. A view's `World` is the world it draws.
---
Source: https://tide-engine.dev/game/draw-settings.md
Tide's draw settings: blending, alpha, tints, stencil, transforms and clipping, each around a block or set for the draws that follow, and how to draw what's see-through.
# Draw settings
A setting changes how everything drawn after it comes out: how it blends, what tints it, what it does with depth and stencil, which side of it shows, where it lands. Each has two forms, and its name says which.
The plain name wraps a block. It's set for the draws in the block, and when the block ends, what it found is back:
```csharp
Draw.Blend(Blend.Add)
{
Draw.Circle(spark.position, 2, spark.color);
}
```
The `Set` name is a statement. It stays for the draws that follow, in this view and the views after it, until it's set again or the frame ends, which is how a camera is set once for a frame:
```csharp
view Follow(Player player, with ownership)
{
Draw.SetCamera(player.position, 10);
}
```
| Around a block | For the draws that follow | What it sets |
|---|---|---|
| `Draw.Blend(mode)` | `Draw.SetBlend(mode)` | How colors go over what's there (see [Blending](#doc-game--draw-settings--blending)) |
| `Draw.Tint(color)` | `Draw.SetTint(color)` | A color everything is multiplied by (see [Tints](#doc-game--draw-settings--tints)) |
| `Draw.Stencil(test, value)`, `Draw.Stencil(test, value, operation)` | `Draw.SetStencil(test, value)`, `Draw.SetStencil(test, value, operation)` | The test draws pass, against a number kept for each pixel, and what becomes of that number where they draw (see [Stencil](#doc-game--draw-settings--stencil)) |
| `Draw.Transform(...)`, `Draw.Transform(transform)` | `Draw.SetTransform(...)`, `Draw.SetTransform(transform)` | Where draws land: moved, turned, scaled (see [Transforms](#doc-game--draw-settings--transforms)) |
| `Draw.Clip(rect)` | `Draw.SetClip(rect)` | The rectangle draws are kept inside (see [Clipping](#doc-game--draw-settings--clipping)) |
| `Draw.Camera(center, size)`, `Draw.Camera(...)` | `Draw.SetCamera(center, size)`, `Draw.SetCamera(...)` | The camera |
| `Draw.Screen()` | `Draw.SetScreen()` | The screen's pixels in the camera's place (see [On the screen](#doc-game--views--on-the-screen)) |
| `Draw.Depth(mode)` | `Draw.SetDepth(mode)` | What 3D meshes do with depth: whether they're hidden behind what's nearer, and whether they hide what's behind them (see [Depth](#doc-game--3d--depth)) |
| `Draw.DepthBias(constant, slope)` | `Draw.SetDepthBias(constant, slope)` | Pulls 3D draws nearer (negative) or pushes them farther (positive) against what has the same depth, like a decal on a floor (see [Depth bias](#doc-game--shaders--depth-bias)) |
| `Draw.Cull(side)` | `Draw.SetCull(side)` | Which side of a 3D mesh's triangles isn't drawn: the back, unless this says otherwise (see [Which side draws](#doc-game--3d--which-side-draws)) |
| `Draw.FrustumCulling(enabled)` | `Draw.SetFrustumCulling(enabled)` | Whether to skip 3D instances wholly outside the camera; enabled by default (see [Frustum culling](#doc-game--3d--frustum-culling)) |
| `Draw.Occlusion(enabled)` | `Draw.SetOcclusion(enabled)` | Whether to skip instances of 3D lists that what's drawn before them surely hides; off by default (see [Occlusion culling](#doc-game--3d--occlusion-culling)) |
| `Draw.Bounds(center, size)`, `Draw.Bounds()` | `Draw.SetBounds(center, size)`, `Draw.SetBounds()` | Conservative mesh-local culling bounds, with full size; no arguments restores automatic bounds |
| `Draw.LOD(level)`, `Draw.LOD()` | `Draw.SetLOD(level)`, `Draw.SetLOD()` | Which level of detail the meshes marked `[LOD]` draw at, in place of the one each picks; with no level, each picks again (see [Levels of detail](#doc-game--assets--levels-of-detail)) |
| `Draw.LODPixels(pixels)`, `Draw.LODPixels()` | `Draw.SetLODPixels(pixels)`, `Draw.SetLODPixels()` | Allowed estimated error for automatic LOD, in screen pixels; default 1, multiplied by the asset's optional `[LOD(multiplier)]` |
| `Draw.LODCamera(...)`, `Draw.LODCamera()` | `Draw.SetLODCamera(...)`, `Draw.SetLODCamera()` | The camera those meshes pick their level through, in place of the one they're drawn through; with nothing, their own again |
Every frame starts from the defaults, so a `Set` never outlives its frame, and the GUI and the stats are never drawn with what a game set. A `Set` with no arguments puts the default back early: `Draw.SetTint()`, `Draw.SetStencil()`, `Draw.SetClip()`, `Draw.SetDepth()`, `Draw.SetDepthBias()`, `Draw.SetCull()`, `Draw.SetFrustumCulling()`, `Draw.SetOcclusion()`, `Draw.SetBounds()`, `Draw.SetLOD()`, `Draw.SetLODPixels()`, `Draw.SetLODCamera()`; `Draw.SetCamera()` puts both cameras back, the 2D and the 3D, and `Draw.SetTransform()` both transforms. Bounds and the three for levels of detail have a block form with no arguments too, which does the same around some draws.
Writing one form as the other is a compile error that names the right one: `Draw.Blend(Blend.Add);` with no block says to write `Draw.SetBlend`, and `Draw.SetBlend(Blend.Add) { }` says `Draw.Blend`. Your editor offers the rename.
A block that's left early still puts back what it found, as a GUI container still closes:
```csharp
Draw.Tint(Color(1, 1, 1, 0.5))
{
if (!card.shown) return; // The tint is gone, here too
DrawCard(card);
}
```
Every setting belongs to the destination it's called on. `Draw`'s are the window's, and a [render target](#doc-game--render-targets) has its own, by the same names (`target.Blend(Blend.Add) { ... }`, `target.Clip(rect) { ... }`, `target.SetCamera(...)`, `target.Depth(mode) { ... }`): a blend or a tint set for the window doesn't reach a target's draws, and a target's doesn't reach the window's. Depth and cull are for 3D meshes alone: around 2D draws they change nothing, and that's no error.
**Info**
What a `Set` with no arguments does, how one setting nests in another, `Draw.Depth`'s name and its modes', `Cull`'s three names and which way round a triangle's front goes, how `Draw.Stencil` is written, its tests' and operations' names and each of its rules, and how `Draw.DepthBias` counts (its constant in the depth image's precision steps, truncated to a whole number, its slope, and the limits past which a factor becomes zero) are provisional: they're how it works today, and may still change.
## Several at once
Calls that take a block can be listed with commas before one block, so settings don't nest three deep:
```csharp
Draw.Blend(Blend.Add),
Draw.Tint(Color(1, 1, 1, shown)),
Draw.Clip(panel)
{
DrawGlow(panel);
}
```
It means the same as each inside the one before. That's the language's, not `Draw`'s: the [GUI](#doc-game--gui--guilayout-and-gui)'s containers and [your own functions that take a block](#doc-language--functions--actions) go in the same list.
## Blending
`Blend.Alpha` is the default: a color goes over what's there by its alpha. The others:
| Mode | What it does | For |
|---|---|---|
| `Blend.Add` | Adds the color to what's there, as light adds | Sparks, trails, glows, fire |
| `Blend.Multiply` | Multiplies what's there by the color: white changes nothing, black makes black | Shadows, stains, tinted glass |
| `Blend.Replace` | Puts the color and its alpha in place of what's there | Writing into a [render target](#doc-game--render-targets) exactly |
In each, a color's alpha is how much of it there is, so what's clear changes nothing: a shape's smooth edge and the gaps between a text's strokes stay clean when they're added or multiplied.
```csharp
view Trails(Bullet bullet)
{
Draw.Blend(Blend.Add)
{
// Where trails cross, they're brighter
Draw.Line(bullet.position - bullet.velocity * 0.05, bullet.position, 0.2, Color(1, 0.6, 0.2, 0.6));
}
}
```
`Draw.Clear`, and a target's `Clear`, fill with their color whatever the blend, and [`Draw.Blit`](#doc-game--render-targets--post-processing) takes a blend of its own (`Draw.Blit(source, destination, Blend.Add, frag)`).
## Alpha
A color's alpha is how much of it there is, and you write colors as they are everywhere: `Color(1, 0, 0, 0.5)` is red, half clear, in a draw, a tint, a grid's cell, a PNG and a frag. There's nothing to multiply yourself and no second kind of blend to pick.
See [Transparency](#doc-game--draw-settings--transparency) for drawing something see-through, fading it, and cutting holes in a 3D mesh.
What that buys:
- **No fringes.** A sprite's clear pixels have a color too in its file, often black or white, which never shows. Scaled or turned with `Filter.Bilinear`, a pixel at the sprite's edge is blended with its clear neighbor, and the neighbor counts for none of the color: a white sprite over a white wall has no gray rim, whatever the file kept in its clear pixels.
- **Layers.** What's drawn into a cleared [render target](#doc-game--render-targets), `target.Clear(Color.clear)`, and then drawn from it with `target.color` looks as it would drawn straight onto the window: a HUD, a minimap or a trail kept in a target goes over the game as it is.
A few things follow from how that's kept, which is each color times its alpha, in textures and in targets:
- **A pixel with no alpha has no color.** A frag that samples one gets `Color(0, 0, 0, 0)`, whatever the file or the cell said its color was. An image whose alpha is something other than how clear it is (a mask beside unrelated colors) would lose its colors where the alpha is 0: mark it [`[Raw]`](#doc-game--shaders--textures-that-are-numbers), and a frag reads its numbers as the file has them.
- **`Blend.Replace` with an alpha under 1** leaves the window, which has no alpha of its own, darker by that much, as if over black. Into a target it's exact: drawn from the target later, it's the color and the alpha that were written.
- **`Blend.Add` raises the alpha that's there** towards 1 by its own, and never past it, so light added into a clear target shows when the target is drawn over something.
- A dim color that's nearly clear keeps few of its 256 steps in an image of bytes. It doesn't show once it's blended; a [`Format.Rgba16f`](#doc-game--render-targets--what-a-target-holds) target keeps them all.
## Tints
A tint multiplies the color of everything drawn inside, alpha too. `Color(1, 1, 1, 0.5)` fades it to half, with no alpha to pass to every call:
```csharp
view Menu(MenuState menu)
{
Draw.Screen(),
Draw.Tint(Color(1, 1, 1, menu.shown))
{
Draw.RoundRect(float2(200, 120), float2(320, 160), 12, Color(0.1, 0.1, 0.15));
Draw.Text("Paused", float2(160, 80), 32, Color.white);
}
}
```
A tint in a tint's block multiplies it: a faded menu's faded button is fainter than either.
## Stencil
Beside its color and its depth, every pixel has a whole number from 0 to 255, its stencil. Nothing shows it. Draws store numbers there, and other draws are drawn only where the number passes a test, which is how one thing is cut to the shape of another: a view through a porthole, a map inside a round frame, a mirror that shows its reflection only where the glass is, an outline around whatever is selected.
`Draw.Stencil(test, value, operation)` says both things for the draws in its block: the test they pass to be drawn at a pixel, their `value` against the number stored there, and what becomes of the stored number where they are drawn. It usually takes two steps. Something stores a number where it is, then something else is drawn where that number is:
```csharp
view Porthole(Ship ship)
{
// The glass stores 1 where it is. It's drawn clear: it's there for what it stores
Draw.Stencil(StencilTest.Always, 1, StencilOp.Replace)
{
Draw.Circle(ship.window, 3, Color.clear);
}
// The sea is drawn where the number is 1, and nowhere else
Draw.Stencil(StencilTest.Equal, 1)
{
DrawSea(ship);
}
}
```
Move the lens below. The wall is drawn where the lens didn't store its number, and the pipes where it did:
**A lens, cut out of a wall** ([Run example](https://tide-engine.dev/examples/stencil/?stats))
```tide
settings { title = "Stencil"; }
local scene Main { }
local singleton Lens
{
float2 at = float2(188, 170);
float radius = 70;
bool outside; // Show what's behind everywhere but in the lens
float time;
}
// The wall: rows of bricks, each row half a brick along from the last.
void Wall()
{
Draw.Rect(float2(Screen.width, Screen.height) * 0.5, float2(Screen.width, Screen.height), Color(0.24, 0.25, 0.27));
for (var row = 0; row < 17; row++)
{
for (var column = -1; column < 8; column++)
{
var corner = float2(column * 56 + (row % 2) * 28, row * 24);
Draw.RoundRect(corner + float2(28, 12), float2(52, 20), 3, Color(0.13, 0.13, 0.15));
}
}
}
// What's behind it: pipes, and what flows through them.
void Pipes(float time)
{
Draw.Rect(float2(Screen.width, Screen.height) * 0.5, float2(Screen.width, Screen.height), Color(0.05, 0.05, 0.06));
for (var pipe = 0; pipe < 4; pipe++)
{
var y = 60 + pipe * 80;
var color = pipe % 2 == 0 ? Color(0.18, 0.83, 0.75) : Color(0.98, 0.44, 0.52);
Draw.Line(float2(0, y), float2(Screen.width, y), 18, Color(0.24, 0.25, 0.27));
for (var drop = 0; drop < 6; drop++)
{
var along = Math.Frac(time * (0.12 + pipe * 0.03) + drop / 6.0);
var x = pipe % 2 == 0 ? along * Screen.width : (1 - along) * Screen.width;
Draw.Circle(float2(x, y), 6, color);
}
}
}
view Show(mut Lens lens, Devices devices)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetScreen();
lens.time += Frame.dt;
var pointer = Screen.Flip(devices.pointer.position);
if (pointer.y < Screen.height - 64) lens.at = pointer;
// Every pixel has a number, 0 after a clear. The lens stores 1 where it is.
// It's drawn clear, so nothing of it shows: it's there for what it stores.
Draw.Stencil(StencilTest.Always, 1, StencilOp.Replace)
{
Draw.Circle(lens.at, lens.radius, Color.clear);
}
// The wall is drawn where the number isn't the lens's...
Draw.Stencil(lens.outside ? StencilTest.Equal : StencilTest.NotEqual, 1)
{
Wall();
}
// ...and the pipes where it is.
Draw.Stencil(lens.outside ? StencilTest.NotEqual : StencilTest.Equal, 1)
{
Pipes(lens.time);
}
// With no test again: the lens's rim, over both.
Draw.WireCircle(lens.at, lens.radius, 3, Color(0.98, 0.75, 0.14));
GUI.SetTheme(GUITheme { radius = 6 });
GUILayout.Area(Rect(12, Screen.height - 52, Screen.width - 24, 40))
{
GUILayout.Horizontal()
{
GUILayout.Slider("Lens", lens.radius, 20, 140);
GUILayout.Toggle("Outside", lens.outside);
}
}
}
```
The test is between the draw's `value`, on the left, and the stored number:
| Test | A pixel is drawn where |
|---|---|
| `StencilTest.Always` | Everywhere: no test, which is what every frame starts with |
| `StencilTest.Never` | Nowhere |
| `StencilTest.Equal` | The stored number is `value` |
| `StencilTest.NotEqual` | It's any other |
| `StencilTest.Less` | `value` is less than the stored number |
| `StencilTest.LessEqual` | `value` is less than it, or the same |
| `StencilTest.Greater` | `value` is greater than the stored number |
| `StencilTest.GreaterEqual` | `value` is greater than it, or the same |
The operation says what becomes of the stored number at each pixel the draw is drawn at. Without one it stays as it is, so `Draw.Stencil(test, value)` only tests:
| Operation | The stored number becomes |
|---|---|
| `StencilOp.Keep` | What it was: the draw only tests |
| `StencilOp.Replace` | `value` |
| `StencilOp.Increment` | One more, 255 at the most |
| `StencilOp.Decrement` | One less, 0 at the least |
| `StencilOp.Zero` | 0 |
| `StencilOp.Invert` | 255 less it: each of its 8 bits the other way |
- **Every pixel's number is 0 when a frame starts,** in the window. A [render target](#doc-game--render-targets) keeps its numbers from frame to frame, as it keeps its colors, until it's cleared.
- **A draw stores where it's drawn, whatever its color.** `Color.clear` stores and shows nothing, which is how to lay a mask down without painting anything. That's so under every [blend](#doc-game--draw-settings--blending) but `Blend.Replace`, which puts the clear color there.
- **Where it's drawn is every pixel it touches:** all of a rect, a circle out to its edge, a smooth shape to the pixels its edge only partly covers, text where its glyphs are (not the boxes around them), and all of a mesh's triangles, whatever its texture's alpha is there. For a mask the shape of a picture, draw it through a [frag](#doc-game--shaders) that leaves out what's clear with `this.Discard()`: a pixel a frag discards stores nothing.
- **It's cut along pixels.** A pixel is in a mask or it isn't, so what's drawn where a mask is has a stepped edge where the mask's shape is round, however smooth the shape itself would be drawn. Draw a rim over it with no test, as the example does, where that shows.
- **A draw that fails the test changes nothing,** and neither does a 3D mesh where it's hidden behind what's nearer: the number changes only where the draw is drawn.
- **It's for everything that draws:** shapes, text, meshes, 3D meshes and the [primitives](#doc-game--3d--primitives), with a frag or without. Draws in a row under the same stencil are still one draw.
- **`Draw.Clear`, and a target's `Clear`, set every number back to 0,** within the [clip](#doc-game--draw-settings--clipping), whatever is set, and are tested against nothing. [`Draw.Blit`](#doc-game--render-targets--post-processing) neither tests nor stores, whatever is set.
- **A render target has its own numbers, and its own setting:** `target.Stencil(StencilTest.Equal, 1) { target.Rect(...); }`. `Draw.Stencil` is the window's, and doesn't reach what's drawn into a target; a target's doesn't reach the window.
- **`value` is any `int`.** Under 0 it's 0, and over 255 it's 255. The test and the operation are values too: `Draw.Stencil(inside ? StencilTest.Equal : StencilTest.NotEqual, 1)`.
- **A block's stencil replaces the one it found,** and puts it back when it ends. `Draw.SetStencil()` puts back none: every pixel passes, and nothing is stored.
Counting is the other use. Each of these adds one where it's drawn, so afterwards a pixel's number is how many of them cover it, and a draw under `StencilTest.Less` with a `value` of 1 is drawn where more than one does:
```csharp
Draw.Stencil(StencilTest.Always, 0, StencilOp.Increment)
{
foreach (var zone in zones.list) Draw.Circle(zone.center, zone.radius, Color.clear);
}
Draw.Stencil(StencilTest.Less, 1) // Where 1 is less than the count: two zones or more
{
Draw.Rect(zones.middle, zones.size, Color(1, 0.2, 0.2, 0.5));
}
```
What a GPU's stencil has beyond this isn't here: a setting for each side of a triangle, one for what happens where a mesh is hidden, and masks over the number's bits.
## Transforms
A transform moves, turns and scales everything drawn inside, in the units the calls are in. `Draw.Transform` takes an offset, then a rotation in radians, then a scale, each optional after the first:
```csharp
view Cards(Card card)
{
// Scaled about the card's middle, then turned, then moved there
Draw.Transform(card.position, card.tilt, 1 + card.lift * 0.1)
{
Draw.RoundRect(float2(0, 0), float2(3, 4), 0.3, Color.white);
Draw.Text(card.name, float2(-1.2, 1.6), 0.5, Color.black);
}
}
```
What's inside is drawn around (0, 0), and the transform puts it in the world: scaled, then turned (from `+x` towards `+y`, as [smooth shapes](#doc-game--views--smooth-shapes) turn), then moved. The scale is a number, or a `float2` to stretch more one way than the other, and `Draw.Transform(matrix)` takes any `float3x3` instead. `Draw.Transform(transform)` does the same for 3D meshes with a `float4x4`. A transform in a transform's block is inside it, so a card's badge can have one of its own.
What's drawn through one:
- Shapes stay shapes, with their smooth edges: moved, turned and scaled, exactly. Stretched, a circle is the ellipse it becomes, and a rect follows its own sides; a skew is approximated. Rects that are only moved and scaled still fill whole pixels, so tiles under a transform leave no seams.
- Meshes go through any transform as they are.
- Text that's moved and scaled as much each way is text of that size, as sharp as any. Turned or stretched, it has no pixels to be fitted to, so it's a little softer than upright text: fine for a tilting card, and worth avoiding for text people read at length.
- A clip made inside one is the upright rectangle around what its `Rect` becomes: clips don't turn.
`Draw.WorldToScreen` and the other [conversions](#doc-game--cameras--screen-and-world-coordinates) are the camera's alone, whatever the transform. [`Draw.MeasureText`](#doc-game--views--measuring-text) answers in the units the transform takes, so inside one, text measures as it's drawn.
## Clipping
`Draw.Clip(rect) { ... }` keeps what's drawn in its block inside a rectangle: meshes, shapes, text, and `Draw.Clear`, which then fills the rectangle.
```csharp
view Panel()
{
Draw.Screen(),
Draw.Clip(Rect(20, 20, 200, 100))
{
Draw.Clear(Color.black); // The panel only
Draw.Text("A line too long for the panel is cut off at its edge", float2(28, 28), 18, Color.white);
}
}
```
The `Rect` goes from (x, y) to (x + width, y + height), in the units the calls are in: the world's under a camera, where `y` is up, and pixels on the screen. It stays where it is on the screen when the camera changes afterwards.
A clip in a clip's block only narrows it: what draws is inside both, which is what a list in a panel wants. `Draw.SetClip(rect)` is the [other form](#doc-game--draw-settings--draw-settings), for the draws that follow, and sets the rectangle outright; `Draw.SetClip()` draws everywhere again. Each frame starts with no clip, and a view's clip never clips the GUI.
## Transparency
Set a color's **alpha**, its fourth number, to the opacity you want: `0` is invisible, `0.5` is half opaque, and `1` is solid. `Color(r, g, b)` is solid. The default [`Blend.Alpha`](#doc-game--draw-settings--blending) blends the color over what's already drawn, so shapes and text need no extra setting:
```csharp
view Overlay()
{
Draw.Screen()
{
Draw.Rect(float2(160, 100), float2(240, 80), Color(0.18, 0.83, 0.75, 0.5));
Draw.Text("Half opaque", float2(40, 60), 20, Color(1, 1, 1, 0.5));
}
}
```
Draw the background first, then what goes over it. This is also how a **sprite with transparent pixels** works: give `Draw.Mesh` its PNG or texture, and the pixel's alpha supplies its opacity. A mesh's vertex colors multiply that alpha, and a [frag](#doc-game--shaders--a-frag) controls it through its `out Color`.
To **fade a whole set of draws**, wrap them in [`Draw.Tint(Color(1, 1, 1, opacity))`](#doc-game--draw-settings--tints). This keeps their colors and multiplies each draw's alpha by `opacity`. Each draw still blends separately: if overlapping elements should fade as one finished layer, draw them into a [render target](#doc-game--render-targets) cleared with `Color.clear`, then tint the draw of `target.color`. Colors stay as you wrote them; Tide handles [premultiplied alpha](#doc-game--draw-settings--alpha) internally.
### Transparent 3D
A 3D mesh also has depth. For glass, smoke and other translucent surfaces:
1. Draw solid geometry first with the default `Depth.ReadWrite`.
2. Draw translucent geometry inside `Draw.Depth(Depth.Read) { ... }`, with alpha below 1. It tests against the solid geometry's depth and writes no depth itself.
3. Draw the translucent surfaces **farthest first**, then the nearer ones, so they blend over what's behind them.
Change **Opacity** below. The amber cube is behind the panes and shows through them; the solid pillar in front hides them. The camera stays fixed, so the rose pane is always farther away and is drawn first. The bar above the scene uses the same opacity on a 2D shape.
**Opacity in 2D and 3D** ([Run example](https://tide-engine.dev/examples/transparency/?stats))
```tide
settings { title = "Transparency"; }
local scene Main { }
local singleton Glass
{
float opacity = 0.5;
List pane = [
Vertex3 { position = float3(-1.3, -1.4, 0) },
Vertex3 { position = float3(-1.3, 0.5, 0) },
Vertex3 { position = float3(1.3, 0.5, 0) },
Vertex3 { position = float3(1.3, -1.4, 0) }
];
List faces = [0, 1, 2, 0, 2, 3];
}
view Solid()
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float3(0, 0, -7), quaternion.identity, 50);
// Solid geometry comes first, with the default Depth.ReadWrite.
Draw.Cube(float3(-0.5, -0.35, 2), float3(1.5),
quaternion.Euler(float3(0, 0.35, 0)), Color(0.98, 0.75, 0.14));
Draw.Cube(float3(0.8, -0.45, -1), float3(0.5, 1.8, 0.5), Color(0.64, 0.64, 0.68));
}
view Panes(Glass glass)
{
// The camera is fixed: z = 1 is farther away than z = 0.
// Read opaque depth, but let later translucent draws show through.
Draw.Depth(Depth.Read)
{
Draw.Tint(Color(0.98, 0.44, 0.52, glass.opacity))
{
Draw.Mesh(glass.pane, glass.faces, float4x4.Translate(float3(-0.2, 0.15, 1)));
}
Draw.Tint(Color(0.18, 0.83, 0.75, glass.opacity))
{
Draw.Mesh(glass.pane, glass.faces, float4x4.Translate(float3(0.2, 0, 0)));
}
}
}
view Overlay(mut Glass glass)
{
Draw.SetScreen();
Draw.Text("2D: alpha blends over the background", float2(16, 16), 16, Color.white);
var width = (Screen.width - 32) / 8;
for (var i = 0; i < 8; i++)
{
var shade = i % 2 == 0 ? 0.2 : 0.35;
Draw.Rect(float2(16 + (i + 0.5) * width, 85), float2(width, 54), Color(shade, shade, shade));
}
Draw.Rect(float2(Screen.width * 0.5, 85), float2(Screen.width - 64, 36),
Color(0.98, 0.44, 0.52, glass.opacity));
Draw.Text("3D: solids, then panes from far to near", float2(16, 132), 16, Color.white);
Draw.Text("The pillar hides both panes", float2(16, Screen.height - 80), 14, Color(0.64, 0.64, 0.68));
GUI.SetTheme(GUITheme { radius = 6 });
GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Opacity", glass.opacity, 0, 1);
}
```
Tide draws in the order your views and calls give it; it **doesn't sort transparent entities or a mesh's triangles by distance**. For a moving camera, gather your transparent objects in a local list, [sort it](#doc-language--text-and-lists--sorting) from far to near for that camera, then draw them in that order. Intersecting transparent surfaces, or faces within one mesh, may need to be split and ordered too; sorting whole objects alone can't resolve every overlap.
- **Alpha doesn't turn depth writes off.** Even alpha 0 can hide later geometry under `Depth.ReadWrite`. Use `Depth.Read` for translucency, or discard the pixel for a hole.
- **`Depth.None` also stops testing depth,** so the mesh shows through solid walls. Use `Depth.Read` when walls should hide it.
- **A thin pane has a back too.** If it should show from either side, use [`Draw.Cull(Cull.None)`](#doc-game--3d--which-side-draws). On a closed mesh that also draws the far faces, whose alpha blends with the near ones.
- **A target has its own settings:** use `target.Depth(Depth.Read)` and `target.Tint(...)` for its draws. `Draw`'s settings reach the window alone.
### Cutout holes
Leaves, a fence or a sprite standing in a 3D world often want solid pixels with holes between them. A frag can discard pixels below an alpha threshold and keep the rest opaque:
```csharp
frag Cutout(Vertex3 vertex, out Color color, Texture image)
{
color = image.Sample(vertex.uv);
if (color.a < 0.5) this.Discard();
color.a = 1;
}
// Keep the default Depth.ReadWrite: only the surviving pixels hide what's behind.
Draw.Mesh(vertices, indices, transform, texture, Cutout);
```
[`this.Discard()`](#doc-game--shaders--where-the-pixel-is) ends the frag and writes no color, depth or stencil for that pixel. The surviving pixels can use the usual opaque draw order. The threshold gives a hard edge; use the translucent recipe above when you want partial opacity at the edge instead.
A frag that can discard is run for every pixel it covers, even one a nearer leaf hides. Where many cut-outs overlap and their lighting is expensive, draw their depth first with `Depth.Only` and light them with `Depth.Equal`: see [A depth pre-pass](#doc-game--3d--a-depth-pre-pass).
---
Source: https://tide-engine.dev/game/meshes-and-textures.md
Draw triangles in Tide with Draw.Mesh, and texture them from an asset, a render target or a grid you paint: filters, wraps, mipmaps, one-channel textures and sampling said once.
# Meshes and textures
A mesh is triangles, and a texture is an image they're drawn with. This page has the 2D mesh and everything about textures; [3D meshes](#doc-game--3d) are drawn with them the same way.
## Meshes
`Draw.Mesh(vertices, indices)` draws triangles, the shape every other one can be made of. `vertices` is a `List`, the corners, and `indices` a `List`: every three are a triangle, each a corner's place in `vertices`, so triangles share corners.
```csharp
struct Vertex // Built in
{
float2 position;
float2 uv; // Where in the texture: (0, 0) to (1, 1)
Color color = Color.white;
}
```
```csharp
view Arrows(Body body)
{
List corners = [
Vertex { position = body.position + float2(0, 1), color = Color.red },
Vertex { position = body.position + float2(-1, -1), color = Color.blue },
Vertex { position = body.position + float2(1, -1), color = Color.blue },
];
Draw.Mesh(corners, [0, 1, 2]);
}
```
Each pixel of a triangle is its corners' colors, blended across it, over what's behind it by its alpha. Triangles draw whichever way round their corners go (a 2D mesh has no back, where a [3D one](#doc-game--3d--which-side-draws) does), in the order they're given, among everything else a view draws. An index past the end of `vertices` leaves its triangle out.
A mesh is one call however many triangles it has, and meshes drawn one after another go to the GPU together, so thousands of triangles a frame are cheap.
A mesh's corners can be a struct of your own instead, with whatever fields the mesh needs, and a `vert` and a `frag` can run for its vertices and its pixels on the GPU: see [Frags and verts](#doc-game--shaders).
## Textures
A color `Texture` is what you draw with. It comes from an asset, `asset Texture hero = "art/hero.png";` (see [Assets](#doc-game--assets--images-to-draw-with)), from a render target, `target.color` (see [Targets](#doc-game--render-targets)), or from a grid you paint: an ordinary `Grid2` or a `Grid2` with a size (see [Grids](#doc-language--grids)) is a `Texture` wherever one is wanted. Numeric [`[Raw]` sources](#doc-game--shaders--textures-that-are-numbers) use Raw fields and shader sampling instead of ordinary color draws.
`Draw.Mesh` takes one after its indices. With no frag, each pixel is the triangle's color times the texture's at its `uv`: (0, 0) is the first pixel's outer corner, and (1, 1) the last pixel's outer corner.
```csharp
local singleton Art
{
Grid2 checker = Grid2(8, 8);
bool painted;
}
view Board(mut Art art)
{
if (!art.painted)
{
foreach (var at in art.checker)
{
art.checker[at] = (at.x + at.y) % 2 == 0 ? Color.white : Color.black;
}
art.painted = true;
}
List corners = [
Vertex { position = float2(-4, -4), uv = float2(0, 0) },
Vertex { position = float2(4, -4), uv = float2(1, 0) },
Vertex { position = float2(4, 4), uv = float2(1, 1) },
Vertex { position = float2(-4, 4), uv = float2(0, 1) },
];
Draw.Mesh(corners, [0, 1, 2, 0, 2, 3], art.checker, Filter.Point);
}
```
Drag over the grid below to set its cells, and the next frame draws them. The toggle switches between `Filter.Point` and `Filter.Bilinear`.
**A grid, drawn as a texture** ([Run example](https://tide-engine.dev/examples/textures/?stats))
```tide
settings { title = "Textures"; }
local scene Main { }
// A grid of colors is a texture. There's nothing to create, upload or free.
local singleton Canvas
{
Grid2 pixels = Grid2(16, 16);
bool ready;
bool point = true;
float hue;
}
view Paint(Devices devices, mut Canvas canvas)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0), 1.4);
if (!canvas.ready)
{
foreach (var at in canvas.pixels)
canvas.pixels[at] = (at.x + at.y) % 2 == 0 ? Color(0.13, 0.13, 0.15) : Color(0.17, 0.17, 0.19);
canvas.ready = true;
}
// The quad covers -1 to 1, and the grid's first row is its top one.
var pointer = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position));
if (devices.pointer.press.pressed && Math.Abs(pointer.x) < 1 && Math.Abs(pointer.y) < 1)
{
canvas.hue += Frame.dt * 2;
var cell = int2(Math.Floor((pointer + 1) * 8));
canvas.pixels[cell.x, 15 - cell.y] = Color(0.6 + 0.4 * Math.Sin(canvas.hue), 0.6 + 0.4 * Math.Sin(canvas.hue + 2),
0.6 + 0.4 * Math.Sin(canvas.hue + 4));
}
List corners = [
Vertex { position = float2(-1, 1), uv = float2(0, 0) },
Vertex { position = float2(1, 1), uv = float2(1, 0) },
Vertex { position = float2(1, -1), uv = float2(1, 1) },
Vertex { position = float2(-1, -1), uv = float2(0, 1) },
];
// The next frame draws whatever the cells hold by then.
Draw.Mesh(corners, [0, 1, 2, 0, 2, 3], canvas.pixels, canvas.point ? Filter.Point : Filter.Bilinear);
Draw.SetScreen();
Draw.Text("Drag on the grid to paint its cells", float2(16, 14), 16, Color.white);
GUI.SetTheme(GUITheme { radius = 6 });
GUILayout.Area(Rect(12, Screen.height - 52, Screen.width - 24, 40))
{
GUILayout.Horizontal()
{
GUILayout.Toggle("Filter.Point", canvas.point);
if (GUILayout.Button("Clear")) canvas.ready = false;
}
}
}
```
There's nothing to create, upload or free. The grid is ordinary state: change its cells whenever, with `[x, y]`, a loop or `Clear()`, and the next frame draws what it holds. The engine keeps a copy on the GPU while views draw with it, and sends only the cells that changed: a brush that paints a few cells of a big canvas costs those few, not the canvas.
The grid can be local state or the match's, like a canvas each player paints. Views read the match's grids as they are at the latest tick: cells aren't blended.
The argument after the texture says how it's read between pixels: `Filter.Bilinear` blends them, `Filter.Point` takes the nearest, for pixel art, `Filter.Trilinear` blends them and stays smooth where the texture is drawn smaller than it is (see [Drawn smaller](#doc-game--meshes-and-textures--drawn-smaller)), and `Filter.Anisotropic` is that for a surface seen at a shallow angle (see [Seen at a shallow angle](#doc-game--meshes-and-textures--seen-at-a-shallow-angle)). A call that leaves it out reads the texture as the texture says (see [Saying it once](#doc-game--meshes-and-textures--saying-it-once-on-the-texture)), which is blended unless something said otherwise.
- A grid with an open axis has no size, so it's no texture: the mesh draws with its colors alone. Neither is one past 16384 cells a side.
- How big a texture can be is the GPU's limit: at least 2048 by 2048 wherever Tide runs.
- What a grid costs is game state, 16 bytes a cell of colors and 4 a cell of floats, with a copy on the GPU at a byte a channel (values are clamped to 0 to 1) or 16 bits a float. An asset's `Texture` keeps a byte per channel as its fallback, with [automatic GPU compression](#doc-game--assets--gpu-compression) for eligible color images: for an image that's only drawn, a sprite or a tile sheet, declare it as one. A grid is for pixels code reads and writes.
A game's C can draw meshes too, with pixels of its own, like a font atlas a library made: see [Drawing from C](#doc-c--functions--drawing-from-c).
Use [`[Linear]`](#doc-game--shaders--linear-light-color) on Texture, TextureArray and Cubemap assets
and fields that hold display-encoded color for lighting. The GPU converts RGB to linear
light before filtering. Unmarked images keep their current behavior; neither the mark nor
`Math.ToLinear`/`Math.ToDisplay` changes alpha, frag output semantics or screen presentation.