---
title: The Tide language
description: "The Tide language reference: syntax, types, ECS components and
  systems, deterministic simulation, multiplayer, drawing and runtime APIs."
source_url: https://tide-engine.dev/spec
source_file: docs/spec.md
source_revision: 36904d8e07dd044bd665de823e6b8022ed4f4248
source_worktree: modified
documentation_sha256: ea38a553efadfaf8a016c33e947825b8c4d3d2005abcf32eb4f4a64094909e97
documentation_scope: Website source checkout; not matched to an installed Tide
  release. Check tide version and the project toolchain.
---

<a id="the-tide-language"></a>

# The Tide language

The language Tide games and the engine's built-in systems are written in. It transpiles to C (see AGENTS.md). This file is the source of truth for the language: only decisions the owner has approved go in **Decided**. Proposals and open questions go in **Open**.

<a id="decided"></a>

## Decided

<a id="depth-precision-2026-11-14"></a>

### Depth precision (2026-11-14)

Owner: "go with recommendations", approving the depth-precision investigation.
Depth images use reversed 32-bit floating depth with stencil: near is 1, far is 0,
clears write 0, and ordinary tests are greater-or-equal. `Depth.Equal` remains exact equality.
Only the final clip conversion reverses: `(w - z) / 2`, from the same OpenGL-convention
projection used by built-in placement and an explicit vert returning `this.clip`.

Game-facing conventions retain their meaning: clip outputs, `this.clip`, `WorldToClip`,
camera matrices and CPU screen/depth conversions use OpenGL clip space. `this.depth`,
DepthTexture Sample (including arrays) and Compare references remain forward, 0 near and
1 far, converted at the GPU boundary. `this.WriteDepth` also takes forward values;
its argument converts once when written. Forward values read this way do not retain the extra
far precision of reversed storage. A raw or precise linear-depth read remains open.

WebGPU requests `depth32float-stencil8` on every device creation, including recovery.
Devices without it use forward `depth24plus-stencil8`, retaining the previous precision
and the same public conventions. Vulkan prefers D32_SFLOAT_S8_UINT, with the same forward
fallback rule where that format cannot support the required use.

<a id="files-and-tools"></a>

### Files and tools

- Source files use the `.tide` extension.
- The compiler (transpiler) is `tidec`.
- A game is one or more `.tide` files: by default, every `.tide` file in the game's folder and its subfolders, but for hidden folders (a name starting with `.`, as tide's own `.tide/` and `.build/`), and those of the packages it lists (see Packages). Every declaration is visible from every file of the game; there are no imports between files.
- A game needs no C: the engine runs it. A custom C host is optional, for tests or special hosts. A game can call C of its own, from `.c` files, `.cpp` files and libraries in its folder (see C functions).

<a id="namespaces"></a>

### Namespaces

- A file can put its declarations in a namespace, and namespaces are how large games keep names apart.
- Code outside the namespace names its declarations with it (`Combat.Health`), or imports it with `using Combat;`.

<a id="type-aliases"></a>

### Type aliases

- `using Name = Type;` declares another name for a closed type. It goes at namespace scope: at the top level of a file, in that file's namespace (or the global namespace), or inside a namespace block. It is distinct from the namespace import `using Namespace;`.
- File-scoped namespace headers and namespace imports precede aliases, as they precede other declarations. Namespace blocks and aliases can appear among declarations.
- An alias follows ordinary namespace lookup: code can use its plain name in scope, qualify it (`Game.Point`), or import its namespace. Its target is resolved in the namespace context of the alias declaration.
- Targets include primitives, built-in vectors and matrices, structs, enums, components and closed containers, with qualified names and aliases allowed inside the type. An alias can name another alias; chains resolve to their underlying type. Cycles are errors.
- Aliases are transparent: an alias and its underlying type are the same type, including for assignments, overload signatures, container elements and component identity. They add no conversion, storage or distinct type identity, and retain the underlying type's members, defaults, capabilities and placement restrictions.
- An alias declares no type parameters: `using Points = List<float3>;` is valid; `using Points<T> = List<T>;` is not. Every type argument in its target must be supplied.

```csharp
namespace Game
{
    using Point = float3;
    using Points = List<Point>;
    using Matrix = float4x4;
    using Health = Combat.Health;
}
```

<a id="order-of-systems"></a>

### Order of systems

- Systems run in one deterministic order, the same on every platform. By default it follows the files, sorted by path, then the order of declarations in each file.
- Attributes change the order of a system relative to others.

<a id="style"></a>

### Style

- Tide is a language of its own, and isn't described as C#-like. C# inspired its syntax, and a rule below that follows C# says so.
- Types, systems and methods use PascalCase: `Transform`, `MovePlayer`, `Spawn(...)`.
- Fields, parameters and locals use camelCase: `trs.localPosition`, not `trs.Position`.
- Public properties use camelCase too, even static ones: `Color.red`, `quaternion.identity`. True constants use FULL_CASE: `Math.PI`, `Math.TAU`.
- Attributes (`[...]`) are only for metadata, such as when a system runs or the bounds of an input field, not for what code does. The engine may enforce what an attribute declares, as it clamps an input field to its `[Clamp]`.
- Braces go on lines of their own, as in C#, and so does an `else` after a block. A block that fits on one line can stay there (`scene Main { }`, `if (dead) { return; }`), and so do literals (`Body { position = p }`). The language server's formatter lays code out this way, indenting as the editor is set to (four spaces by default).

<a id="declarations"></a>

### Declarations

- `component` declares a component.
- `singleton` declares world-wide state (what other ECSs call a resource). There is exactly one instance **per world**, not per process.
- `struct` declares a value type for fields and locals (see Structs).
- `using Name = Type;` declares a transparent type alias (see Type aliases).
- `system` declares a system.
- `event` declares an event, and `event(...)` code that runs when one is sent (see Events).
- `enum` declares an enum (see Enums and switch).
- `scene` declares a scene (see Scenes).
- `local` in front of a declaration makes it belong to the machine instead of the match, and in front of a field of a match component or singleton, that field alone (see Local state).
- A function, `ReturnType Name(parameters) { ... }` with no keyword, declares code that other code calls (see Functions).
- `extern` declares a function written in C (see C functions).
- `virtual` in front of a declaration with code says another package can replace it, and `override` in front of one replaces it (see Mods).
- `const` declares a constant (see Constants).
- `settings` sets the engine's settings for the game (see Settings).

<a id="field-defaults"></a>

### Field defaults

- Fields of components, singletons, inputs and structs can declare a default value: `int value = 100;`.
- A default must be a constant expression: literals, constants, constructors of built-in types, struct values of constants (`Range { hi = 5 }`), `Math` functions, built-in constants like `quaternion.identity`, and operators, as in `float angle = Math.Radians(45);`. It can't read fields, singletons or `Time`.
  - Provisional: it can name an asset too, as it names a constant, `local Texture face = logo;` (see Assets, A field's default).
- Singletons start with their defaults when the world is created, before `Main` runs.
- Components get their defaults whenever a value is created without setting that field: `Spawn(Health)`, `e.Add(Health)`, and fields left out of `Health { max = 200 }`.
- Fields without a default start at zero. `Entity` fields always start as the null entity and can't have another default.

```csharp
singleton Physics
{
    int collisionCount = 69;
    float3 gravity = float3(0, -9.81, 0);
}

component Health
{
    int value = 100;
    int max = 2 * 2 * 25;
}
```

<a id="default-values"></a>

### Default values

- `default` is the default value of the type where it goes, as in C#: `Draw.Circle(default, 5, Color.yellow)` draws at `float2(0, 0)`.
- It's the value a field of that type starts at when it declares no default: zero for numbers, vectors, matrices, quaternions, colors and rects, `false`, empty text, an empty list, the null entity, no player, an enum's 0, and for a struct or component, its fields' defaults, as `Stats { }` makes them.
- Its type comes from where it goes: a typed local (`float2 center = default;`), an assignment, an argument, a `return`, a field in a value (`Range { lo = default }`), a field's default, a list's element, and the other side of `==`, `!=` or `?:` (`target == default`).

<a id="structs"></a>

### Structs

- A struct is plain data, copied when it's assigned, with no references. The world stays plain data, so copying it is still a snapshot.
- Structs are the types of fields (of components, singletons, inputs and other structs) and of locals. System parameters stay components, singletons, the input and `Devices`.
- A value is written like a component's: `Stats { armor = 2 }`. Fields left out take their default, and a struct field without one takes its struct's defaults.
- A struct's fields change through whatever holds it: `unit.stats.health -= 5` needs `mut Unit unit`, so a system's signature still says what it writes. A local copy changes with `mut var`.
- A struct can't contain itself, even through other structs: it would be infinitely big.
- Namespaces apply as to every declaration: another namespace names it `Combat.Stats`.
- `[Clamp]`, `[Min]` and `[Max]` on a struct's field are enforced where untrusted data enters the simulation: in an input that holds the struct, before `Sanitize`, as on the input's own fields. Elsewhere they only describe the field.
- `==` compares structs only if the struct declares it (see Operators).
- Structs have methods and operators (see Methods and Operators).

```csharp
struct Range
{
    float lo;
    float hi = 1;
}

struct Stats
{
    float health = 100;
    Range damage;                   // lo = 0, hi = 1: Range's defaults
    Range armor = Range { hi = 5 };
}

component Unit
{
    Stats stats;
}

system Hurt(mut Unit unit)
{
    unit.stats.health -= unit.stats.damage.hi;
}
```

<a id="methods"></a>

### Methods

- Structs, components and singletons can have methods. Their fields are in scope by name, and so are their other methods.
- A method only reads the fields, unless it's `mut`. Calling a `mut` method changes what it's called on, so it needs write access, like an assignment: `unit.stats.Hurt(5)` needs `mut Unit unit`, and the system's signature still says what it writes. A read-only method can't call a `mut` one.
- A method returns a value with `return value;`, on every path, unless it returns `void`.
- A method sees its fields, its parameters and `Math`. It can't draw: views do. It sends events, spawns and changes entities as a function does, for the code that calls it (see Functions).
- A component's method has `this`: the entity whose component it's called on. Attached component parameters and query bindings retain their owning entity/world through synchronous helper calls. Explicit copies and returned values are detached. A struct's methods and `Interpolate` have no `this`.
- Methods can share a name when their parameters differ, as functions can (see Default values, named arguments and overloads). A method can't share one with a field.
- Singleton methods operate on their explicit receiver, with no implicit world access or local sidecar fields. Like struct methods, they have no entity `this`. Inputs have only `Sample`, `Sanitize` and `Predict`.
- Parameters work as in functions: they can have default values, and calls can name them.

```csharp
struct Stats
{
    float health = 100;

    bool IsDead() { return health <= 0; }

    mut void Hurt(float amount)
    {
        health -= amount;
        if (IsDead()) health = 0;
    }
}

system Burn(mut Unit unit)
{
    unit.stats.Hurt(1);
}
```

<a id="properties"></a>

### Properties

- Structs, components and singletons support user-defined computed properties with C#-style `Type name { get { ... } set { ... } }` accessors. The engine uses the same facilities.
- Getters read the receiver; setters can change it and need a writable receiver. The assigned value is available as `value`. Properties add no stored component fields or runtime dispatch.
- An attached component can access its owning entity and world, subject to caller capabilities. Context remains transient and is passed only where needed; ordinary field access retains its existing cost.
- `Transform.position` exposes world position, including through an attached Transform passed to a helper. Setting it updates `localPosition` by converting through its parent and leaves the parent unchanged.

<a id="functions"></a>

### Functions

- **Callable shaders (agreed 2026-10-24).** Functions can be supplied to GPU
  code and forwarded through helpers. Frags and verts have explicit named
  binding initializers, `Shade { distance = Circle }`, with no positional
  binding shorthand. Configured stages can be kept in local component state.
  Instance records may select different functions in a shared draw through
  generated dispatch. Callable signatures can mark explicit arguments `mut`,
  as in `Func<mut Vertex, void>`; calls forward the caller's writable value
  through helpers, with ordinary access rules. Captures remain read-only.
  The initial representation and other restrictions
  are provisional under Callable shader values below.

- A function is code that other code calls: systems, views, the input's `Sample`, `Sanitize` and `Predict`, methods and other functions. The engine never runs one by itself.
- A plain value parameter is a copy, read-only. A `mut` parameter is the caller's variable itself, which the function changes: the caller passes something it can write, and its signature still shows the write, so `Heal(unit.stats, 5)` needs `mut Unit unit`. The argument's type matches exactly.
- Parameters are built-in types, structs, components and singletons. Return values are built-in types, structs and components; singleton return values aren't supported.
- Singleton parameters and method receivers are explicit values, with the same read-only copy and `mut` caller-variable rules as components. They bind no singleton from the world and grant no world access: a function reaches other entities through a `World` parameter, which its caller passes its own (see The World). Existing restrictions on copying or passing grids and rendering resources still apply.
- Caller access remains decisive, through helper chains: match systems and handlers can pass match state they can write; views can read match state and change local state; the input's `Sample` only reads local state. Helper reads and writes count toward the caller's access and scheduling. For a match component or singleton with local fields, only an actual bound parameter supplies them to an ordinary function, not a plain copy (see Local state). Match code can't call a helper that uses local fields, and local code can't call one that writes match fields. Methods don't receive local fields.
- Engine-owned singleton instances stay read-only through calls. A helper can read stored fields of `Time` or `Session`, but passing `Session` grants no session operations: a function makes session calls as the code that calls it could, with a `Session` or without (see Functions and blocks). Ordinary helpers can't read `session.room` or `session.invite`, or format a whole `Session` as text; pass the room code or the invite as a separate `string`.
- Functions follow the rules of methods: they see their parameters and `Math`, and return a value on every path unless they return `void`.
- Functions and methods can take and return event and command payload values, with the same copy and `mut` rules as other values. Passing or constructing a payload grants no sending, world or sender capability. Payloads cannot be stored fields.
- Ordinary synchronous functions and methods can borrow input with an ordinary parameter, such as `bool WantsJump(Controls controls)`. The caller passes its input parameter directly; current and previous tick stay together through forwarding, preserving the selected player, nested `.down`/`.up` edges and prediction/replay behavior. See Input for the borrow's lifetime and restrictions.
- **A function sends events, spawns and changes entities as the code that calls it could** (the owner, 2026-10-08, of `Send`, `Spawn` and `Destroy` in a function: "it should inherit their ability; if you say `Send` it should mean that what calls us can `Send` otherwise is a compiler error ONLY when its called from a place it can't"). `Send`, `entity.Send`, `Spawn`, `Add`, `Remove` and `Destroy` are written in a function or a method as in a system, with no parameter for it. The function is never wrong by itself: a call of it is an error where the calling code couldn't do the same thing itself, and that follows calls through other functions, as their reads and writes do. What was picked to build it is under Provisional, Functions and blocks.
- A function can draw and use the GUI. Then only views, and other functions like it, can call it, as with `Draw`.
- Namespaces apply: another namespace calls it `Combat.Heal(...)`. A function shares its name with nothing else in its namespace but other functions, whose parameters tell them apart (see Default values, named arguments and overloads).
- A parameter can have a default value, which a call can leave out, and a call can pass arguments by name: see the same section.
- A parameter can be `out`: the call gives the caller's variable its value, as in C# (see Out parameters).
- A function's last parameter can be an `Action`: code the caller writes in braces after the call, `Section("Audio") { ... }`. A function takes at most one, always last, and it's always written after the call, never inside the parentheses.
- The function runs the block by calling it, `content();`, as many times as it chooses, including none. The block runs as if it were written at the call: it sees the caller's locals and parameters, and what it reads and writes counts toward the caller's signature.
- A function that takes an `Action` is inlined where it's called, so blocks cost nothing and need no closures. It can't call itself, directly or through other functions, and a block can only be run, not stored.

```csharp
// A container of your own: runs its content only while open.
void Foldout(string title, mut bool open, Action content)
{
    GUILayout.Toggle(title, open);
    if (open) content();
}

view Options(mut Main menu, mut Settings settings)
{
    Foldout("Audio", menu.audioOpen)
    {
        GUILayout.Slider("Volume", settings.volume, 0, 1);
    }
}
```

```csharp
float Heal(mut Stats stats, float amount)
{
    stats.health = Math.Min(stats.health + amount, 100);
    return stats.health;
}

system Regenerate(mut Unit unit)
{
    Heal(unit.stats, 0.5);
}
```

<a id="calls-that-take-a-block"></a>

### Calls that take a block

- Some calls take a block, written in braces after them: the GUI's containers (`GUILayout.Horizontal() { ... }`), draw settings (`Draw.Blend(Blend.Add) { ... }`, see Views and drawing), a game's functions that take an `Action` (above), a list's `Sort(a, b) { ... }` (see Lists) and the World's `Edit<Health>(target, health) { ... }` (Provisional: see The World). The last two name what their block works with as arguments of their own.
- Calls that take a block can be listed with commas before one block, which they share, so they don't nest three deep:

```csharp
Draw.Blend(Blend.Add),
Draw.Tint(Fade(Color.white, shown)),
Draw.Clip(panel)
{
    ...
}

GUILayout.Area(Anchor.MiddleCenter),
GUI.Disabled(busy)
{
    ...
}
```

- A list means what nesting its calls in that order does: each call's block is the call after it, and the last one's is the block. The first is set up first and put back last.
- It's a rule of the language, not of `Draw`: the GUI's containers, the draw settings, a game's own functions with an `Action` and `World.Edit` (Provisional, see The World) go in one list, each beside the others.
- A call in the list that takes no block is an error at that call, which says so.
- The comma is what makes a list. With none, a call followed by another is still a missing `;`.
- The formatter puts a call a line, each starting where the first does, and the block's braces on lines of their own.

<a id="default-values-named-arguments-and-overloads"></a>

### Default values, named arguments and overloads

**Following C# here is agreed.** So is how a shared name is written where nothing calls it: with its parameters' types, and it has to be one declaration's. The points marked Provisional are picks the owner hasn't confirmed.

- **Default values.** A function's or method's parameter can have one: `float Damage(float base, float multiplier = 1, bool crit = false)`. A call can leave such a parameter out, and it gets the default.
  - They're the last parameters, as in C#: after one with a default, each has one. An `Action` still comes last: it isn't an argument.
  - Provisional: a default is a constant expression, as a field's is (see Field defaults), and `null` for a `T?`. It can't read another parameter.
  - Provisional: only plain values take one. A `mut` parameter is the caller's variable, a component or a singleton is the caller's own, and the devices, a `DrawList` and rendering resources are passed: none of them can be left out. An `Entity`'s only default is `default`, the null entity. Operators and `Interpolate` take none.
  - Parameters of systems, views, handlers, frags and verts take none: the engine supplies them, and nothing calls them.
  - An `extern` function's parameters take them too: C is passed the default like any argument.
- **Named arguments.** A call can pass an argument by its parameter's name, `Damage(10, crit: true)`, which lets it leave out the ones before. Struct values keep `=` (`Body { position = p }`), as in C#.
  - Arguments without a name come first, in the parameters' order. After a named one, each is named, in any order: `Damage(crit: true, base: 5)`.
  - Each parameter is given once, and every parameter without a default is given.
  - Arguments are worked out in the order written, whatever order the parameters are in (see Evaluation order).
  - Provisional: `default` as an argument stays the type's default, as in C#, not the parameter's.
  - The engine's functions take names too, where their parameters have names: `Draw.Circle(center: p, radius: 2, color: Color.red)`, `Session.Connect(address: host, port: 7001)`, `Debug.Assert(ok, message: "lost")`. What a call leaves out of them is at the end. Constructors (`float3(...)`), `Spawn`, `Send`, `Add`, `Remove`, a list's and a map's methods, the `World`'s methods, the component-wise `Math` functions and `Draw.Mesh` and its kin take their arguments in order.
- **Overloads.** Functions can share a name, and so can a type's methods, when their parameters differ: `Damage(float base, float multiplier = 1)` and `Damage(float base, Weapon weapon)`.
  - What tells them apart is their parameters' types, in order. Names, `mut` and defaults don't: two declarations that differ only in those are an error.
  - A call picks by its arguments, as in C#. Each one that could take them is a candidate. One is better than another when no argument goes to it worse and at least one goes better: an argument's own type is better than one it converts to, and of two types it converts to, the one that converts to the other (an `int` over a `float`, for a `byte`). When that leaves two the same, the one the call wrote every parameter of is better than one that fills defaults in. A call that fits none, or fits two equally, is an error that lists them.
  - `default`, `null`, `[a, b]` and a grid's size take their type from the parameter, so they don't pick: the other arguments do.
  - Provisional: `extern` functions that share a name each say which C function they are, with `[NativeName]`, since C has one function of a name.
  - A function still shares its name with nothing else in its namespace (a type, a system, a constant), and a method with no field.
- **Systems, views, handlers, frags and verts** can share a name the same way. Nothing calls them, so the name is written with its parameters where it's used:
  - `[After(Move(Position, Velocity, with Player))]`: the parameters' types in order, with the filters (`with`, `without`, `with ownership`, and a query as `query(Body, with Fighter)`) and a view's `verified` (`Bar(verified Health)`), and neither names nor `mut`. A handler's trigger isn't among them: it's written before the name.
  - A mesh's vert and frag are named the same way: `Draw.Mesh(vertices, indices, Tint(Vertex, Color))`.
  - A name alone is fine while only one declaration has it, as it always was. When several share it, the name alone is an error that lists them as they're written, and so is a parameter list that isn't exactly one's. A name written with parameters is checked against them even when it's the only one.
  - Tools show a shared name with its parameters: `tidec --schedule`, the profiler's rows, the language server.
- Provisional: in generated C, a declaration that shares its name goes on with its parameters' types (`tide_function_Damage_float_Weapon`). One alone keeps the name it had, so code that shares no names generates the C it always did.

```csharp
float Damage(float base, float multiplier = 1, bool crit = false)
{
    return crit ? base * multiplier * 2 : base * multiplier;
}

float Damage(float base, Weapon weapon)
{
    return base + weapon.power;
}

system Strike(mut Unit unit, Weapon weapon)
{
    unit.health -= Damage(10);              // multiplier 1, no crit
    unit.health -= Damage(10, crit: true);  // By name, past multiplier
    unit.health -= Damage(10, weapon);      // The other one
}
```

```csharp
system Move(mut Position position, Velocity velocity, with Player) { ... }
system Move(mut Position position, Velocity velocity, with Enemy) { ... }

[After(Move(Position, Velocity, with Player)), Before(Move(Position, Velocity, with Enemy))]
system Aim(mut Turret turret, Position position) { ... }
```

<a id="out-parameters"></a>

### Out parameters

**Following C# here is agreed**, and so is the pattern it's for: a function that returns whether it has something, and gives it through `out`, or the default. The points marked Provisional are picks the owner hasn't confirmed.

- **Declaring.** `out` before a parameter's type makes the call give the caller's variable its value: `bool TryHalf(int value, out int half)`. Functions, methods and `extern` functions have them. The word is a name like any other everywhere else, as `in` is.
  - What the engine calls itself takes none, since nothing would take what's made: systems, views, and event and command handlers. Neither do operators, `Interpolate` or, as in C#, async functions, whose call returns before the task has made anything: they return a struct instead.
  - A frag and a vert have them for what the GPU takes: a frag's color, and the structs a vert writes for its frag (see Views and drawing). What's said below of the code in the function holds there, with the GPU in the caller's place.
  - Provisional: an `out` parameter is of any type a parameter can be, but the devices and an `Action`.
  - It has no default, and `mut out` is an error that says to drop `mut`. A parameter after one with a default needs a default too, so `out` parameters come before those.
- **In the function.** An `out` parameter starts unassigned: what the caller's variable held isn't passed in. The code assigns it before it reads it, and on every path that returns. This is C#'s definite assignment:
  - A path is what the code can run through: an `if` assigns it when both sides do, `&&`, `||`, `?:` and `??` only run their right sides sometimes, a `while (true)` only ends at its breaks, and where a `return` or a `break` leaves, what follows isn't reached. A condition that's `true` or `false` as written counts as that.
  - A loop may run no rounds, so what its body assigns isn't assigned after it. Provisional: the same goes for a block written after a call (see Calls that take a block), which its call runs when it does.
  - Passing it on as another call's `out` argument assigns it, once that call has run.
  - Provisional: a struct is assigned whole, or a field at a time, as in C#: it has a value once each of its fields does, on every path, and a field is read once it's assigned. `pair.a = 1; pair.b = 2;` fills a `Pair`, a field can be another call's `out` argument (`Half(seed, out pair.a)`), and reading `pair.b`, or all of `pair`, before `pair.b` is assigned is an error that names the field. That's a struct's own fields: a field of a struct in it (`pair.inner.x = 1`) is a part of `pair.inner`, which is assigned whole first, and so is a component of a vector or a color (`v.x = 1` before `v = ...` reads a `v` with no value). It was whole assignment only until a vert's struct for its frag was built, whose agreed example fills it a field at a time: one rule for both.
  - `default` is how a path with nothing to give fills it: `health = default;`.
  - **Provisional: `fail` owes it nothing**, and neither does a `try` that passes an error on. C# has nothing to follow here. After a call that failed, each of its `out` variables is what the function assigned before it failed, or its type's default, never what the variable held before: nothing the code wrote is undone, and nothing is left unset.
- **At the call.** The argument for an `out` parameter says `out`, and no other argument does:
  - `out health` assigns a variable the code has: a `mut` local, a field of a component or singleton it takes as `mut`, its own `mut` or `out` parameter. The rules are a `mut` argument's: its type is the parameter's exactly, and a copy can't be one, which a list's element is, and a swizzle of several components (`v.xy`). (A swizzle passed to a `mut` parameter used to compile, and change a copy: it's the same error now.)
  - `out var health` and `out Health health` declare a local there, of the parameter's type. Provisional: it's read-only, as a `var` is, and `out mut var health` declares one the code changes later.
  - `out _` leaves what the call makes out. Provisional: as in C#, `_` is that only while nothing in scope is named `_`; `out var _` and `out int _` are too.
  - By name, the name comes first: `TryHalf(value: 8, half: out var h)`.
  - **Provisional: the word is written at every call, for an `extern` function's `out List<T>` too**, which took none before `out` was every function's (see C functions). `mut` and `in` still take none: `out` does because the argument can declare.
- **Scope**, as in C#: a local an `out` argument declares belongs to the block its statement is in, from the call on. Declared in an `if`'s condition, it's in scope in both branches and after the `if`. Declared in a `while`'s or a `for`'s condition, it's the loop's own. A statement that's a branch or a loop's body with no braces is a block of its own.
  - It's only read where the call that makes it has run, by the same rules as above: in `if (ready && TryHalf(8, out var half))`, `half` has a value inside the `if` and not after it.
  - One that nothing reads is a warning, like any local (see Mutability), whose note says to write `out _`.
- **Everything else treats an `out` argument as a write**, as a `mut` one: a system needs `mut` on the component or singleton the variable is in, a view can't make the match's, a parallel loop's step and a sort's comparison only make their own variables, and the call is one that writes, which keeps its turn among what's read beside it (see Evaluation order).
- **Overloads.** `out` doesn't tell functions that share a name apart, as `mut` doesn't: their parameters' types do. A call picks among them as ever, where an `out` argument only goes to an `out` parameter, and `out var` takes its type from the one picked.
- **`extern` functions.** `out T` is a `T *` in C, as `mut T` is: the difference is Tide's, which passes nothing in and takes it that C writes. `out List<T>` stays the list C makes through its writer. C can't make text, so `out string` is an error there (see C functions).
- **Code the GPU runs.** A function a frag or vert calls can have `out` parameters: a pointer in WGSL, as `mut` ones are. Provisional: a local an `out` argument declares can't be declared on a counting loop's own line there.
- **The engine's own.** `Map<K, V>` has `TryGet(key, out value)`, C#'s `TryGetValue` (see Maps and sets), the `World` has `TryGet<T>(entity, out value)` (see The World), and the GUI's `TextField`, `IntField` and `FloatField` each have a version with `out bool entered` (see GUI).
- In generated C an `out` parameter is a pointer, as a `mut` one is, and code that has none generates the C it always did.

```csharp
bool TryHalf(int value, out int half)
{
    if (value % 2 != 0)
    {
        half = default;
        return false;
    }
    half = value / 2;
    return true;
}

system Halve(mut Pile pile, mut Tally tally)
{
    if (TryHalf(pile.size, out var half))
    {
        pile.size = half;               // Declared in the condition: the call ran here
    }
    tally.last = half;                  // ...and it's the block's, so it's still there after the if

    TryHalf(pile.size, out pile.next);  // A field of a component taken as mut
    TryHalf(pile.size, out _);          // Not wanted

    if (tally.scores.TryGet(pile.owner, out var score)) tally.total += score;
}
```

A function that looks an entity's component up and gives it through `out` takes the `World` its caller passes it (see The World):

```csharp
bool TryFind(Entity target, World world, out Health health)
{
    if (!world.Has<Health>(target))
    {
        health = default;
        return false;
    }
    health = world.Get<Health>(target);
    return true;
}

system Heal(Healer healer, World world)
{
    if (TryFind(healer.patient, world, out var health))
    {
        // health is the patient's
    }
}
```

`world.TryGet<Health>(healer.patient, out var health)` is that function, built in.

<a id="operators"></a>

### Operators

- A struct can declare operators, in C#'s form: `Money operator +(Money a, Money b) { ... }`. They compile to plain function calls.
- The operators are `+ - * / % & | ^ << >>`, the comparisons `== != < <= > >=`, which return `bool`, and `-` (negation), `!` and `~` with one parameter.
- At least one parameter is the struct itself. Parameters are copies, and an operator has no fields in scope: it only sees its parameters.
- As in C#, `==` and `!=` come in pairs, and so do `<` and `>`, and `<=` and `>=`.
- A compound assignment uses its operator: `total += price` uses `+`.
- Several operators with the same symbol can take different types, like `Money * int` and `int * Money`. The one whose parameters match the operands exactly wins over one that needs `int` to `float`; if two match as well, it's an error.

```csharp
struct Money
{
    int cents;

    Money operator +(Money a, Money b) { return Money { cents = a.cents + b.cents }; }
    Money operator *(Money a, int times) { return Money { cents = a.cents * times }; }
    bool operator ==(Money a, Money b) { return a.cents == b.cents; }
    bool operator !=(Money a, Money b) { return !(a == b); }
}
```

<a id="mutability"></a>

### Mutability

- Everything is read-only by default. Mutability is opt-in with `mut`.
- This includes local variables. `var` infers the type, like C++ `auto`, and is read-only.
- An explicitly typed local can omit its initializer (`Animation current;`). Every path reaching a read must initialize it first. Without `mut`, each path initializes it once, through a whole-value assignment or an `out` argument. `mut Animation current;` permits later changes. `var` and `mut var` still need an initializer to infer the type. A declaration inside a loop creates a fresh local each iteration; initializing a read-only local declared outside on a repeating path is an error.
- A statement switch proves initialization through all its sections plus a `default` that assigns or ends the path. Covering only named enum members isn't exhaustive, because enums can hold unnamed numbers.

```csharp
var speed = player.speed * 2;    // read-only, type inferred
mut var total = 0.0;             // mutable, type inferred
float limit = 10;                // read-only, explicit type
mut float scale = 1;             // mutable, explicit type
```

- A local that's declared and never read is a warning, `local 'fwd' is never used`: a value worked out and then not used is a mistake more often than not, as when code computes `fwd` and then moves by `move`. Assigned but never read counts as never read.
- The warning's note says what to do: remove the local or use it. When its value is a call that does something (a `Spawn`, a call to C, a call that sends or changes state), the note says to keep the call, as a statement of its own. For a local an `out` argument declares (see Out parameters), it says to write `out _`.
- Parameters are apart: systems, views and handlers warn about theirs that are never used (see System parameters), and a plain function's or a method's stay quiet.

<a id="system-parameters"></a>

### System parameters

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      | Read access                                                             |
| `mut`     | Write access                                                            |
| `with`    | Entity must have this component. No data access, so no data dependency. |
| `without` | Entity must not have this component.                                    |

```csharp
system ClampPlayer(mut Transform trs, with Player)
{
    if (trs.localPosition.y < 0)
        trs.localPosition.y = 0;
}
```

- Views and local handlers of match events also filter by who owns the entity: `with ownership` and `without ownership` (see Views and drawing, and Events). So do command handlers, by whether the command's sender owns it (Provisional: see Commands). In the rest of match code they're errors.
- In code that runs for an entity, `this` is that entity: `if (health.value <= 0) this.Destroy();`. It's an `Entity`, or a `LocalEntity` in code that runs for local entities. In a frag, `this` is its pixel, and in a vert its vertex as the engine would place it (see Views and drawing). `this` is a keyword everywhere, and it can't be assigned.
- A system, view or handler has `this` when it runs once per entity: it takes a component or filters by one (`with Player`). A component's method has its entity too (see Methods), a frag has its pixel, and a vert its vertex. Other code has none, including ordinary functions; the error says why.
- The entity isn't a parameter: an `Entity` or `LocalEntity` parameter is an error that points to `this`.

<a id="read-only-entity-queries"></a>

### Read-only entity queries

A system, a view or a synchronous event or command handler can take another set of entities to inspect, using the same component binding and filter syntax inside a `query` parameter:

```csharp
system BulletHits(Body shot, Bullet bullet, query (Body body, with Fighter) fighters)
{
    foreach (var fighter in fighters)
    {
        // fighter.body is read-only Body data; fighter.entity is its Entity.
    }
}
```

- The outer parameters still select the entities the code runs for. `fighters` selects a separate set: its `Body` and `Fighter` requirements do not filter the bullet entity. A system with only query parameters runs once per tick, and a view with only query parameters once per frame.
- The nested list accepts named component bindings and `with`/`without` component filters. Match data remains read-only. In local code, `mut` on a binding permits writes to its attached local fields (below). Bindings follow ordinary parameter naming rules, with `entity` reserved for the row handle. It accepts no singleton, input, `World` or nested query. A system's is of the match's components; a view's and a local handler's are all the match's or all local (below).
- `foreach (var fighter in fighters)` yields a row whose `entity` handle and match component values are read-only. Code can copy a component value or pass it to an ordinary function. A method that uses `this` cannot be called on it. Queries and whole rows cannot be stored; whole rows cannot be passed to functions. Component copies omit attached local fields. Queries can be borrowed by synchronous functions and methods, below. Iteration stays outside parallel loops and callback blocks, except a parallel loop's own (below). Async handlers and tasks take none yet.
- Every query executed by match/simulation code traverses matching entities in ascending opaque logical identity order across archetypes, checking sparse component presence and filters per row (decided 2026-11-06). Physical rows, holes, allocator reuse and recipient projection loading do not change that order. An empty set performs no iterations. This is not distance or hit sorting; game code calculates intersections and chooses the earliest hit itself. Presentation/view queries and local-entity queries retain their existing traversal order.
- In a system, component bindings read the current world, with the same semantics as `World.Get`. Their reads participate in access analysis, system ordering, the schedule and editor hints as reads of any entity's component. Filters access no component data. If a system also writes a component it queries, it follows the existing `World` reads-own-writes rule: it runs on one thread and sees rows changed earlier in that run.
- `Send`, `Spawn`, `Add`, `Remove` and `Destroy` keep their deferred behavior. Recording one through a row's entity does not change query membership or component data during the code's run.
- **`parallel (var fighter in fighters)` goes through the same rows at once, on threads** (owner, 2026-11-05: parallel loops over a query's rows exist, and pairs of entities affect each other through `Send`). The rules below are Provisional (built 2026-11-05):

```csharp
system Hits(query (Body body, with Fighter) fighters, Settings settings)
{
    parallel (var f in fighters)
    {
        if (Math.Distance(f.body.position, settings.center) > settings.radius) continue;
        f.entity.Send(Hit { damage = 1 });
    }
}
```

  - The row is a foreach's: `f.entity` and the bindings, read-only, the variable declared `var`. The loop goes through its rows one by one, with no `by` or `offset`. It's in systems, views and handlers, as every parallel loop is, not in a function borrowing a query.
  - Its steps follow a parallel loop's rules (see Lists): they change only the variables they declare, can't end the loop, wait, spawn, add, remove, destroy or draw, and call no function that sends, spawns or changes entities. Unlike a list's or a grid's, they can `Send` the match's events, to the world or to an entity. Those are recorded in the order the foreach would record them, whatever threads the steps run on, so the results are the same. An event holding text or lists, a local event and a command can't be sent from a step: text can't be made on threads, and local code's sends stay in a foreach.
  - **Provisional (agent pick, 2026-11-12, from Mount & Rifle's crowd view): in local code a step reaches its own row's attached local fields.** It reads them through any binding and writes them through a `mut` binding, directly or through a function it hands the binding or a field to; the row's match fields stay read-only. Each row is one entity's, so no two steps share a cell. The cells are made ready in the rows' order before the steps start (a first write's storage, a reused identity's `Forgotten` reset), exactly as a foreach's row is at its start, so nothing of this machine's is made or reset on a thread. Refused, each with its own error: a step changing a local field that holds text or lists (this machine's one heap; reading it is fine), handing a `mut` binding whose local fields hold any to a function, and reading the local fields of the code's own outer parameter of a component the loop's rows write (another step may be writing that entity's).
  - **A frame's parallel loops run on the pool's threads** (2026-11-12; before, every parallel loop in a view ran on the frame's thread): a host hands a frame's views its pool (`tide_loops_enter`, the standard host does), and a loop worth a round of the pool's takes one, as a loop in a tick on one thread does. Results are the foreach's. Local handlers' loops, a sharded game's views and hosts that hand no pool (Unity's embedding) stay on one thread.
  - **A step that reads a variable made outside the loop holding text, a list, a map, a set or a grid keeps its loop on the thread that reached it**, in match code too: such values are that thread's scratch memory. (Before 2026-11-12 such a step on another thread read that thread's memory instead: a crash.) Fields of components and singletons are the world's and unaffected.
  - Each step's rolls are its row's: made from the code's generator and the row's place in the order, whichever thread runs it, as a list step's are its index's.
- **Match event and command handlers take queries too** (agreed 2026-10-18). Each `foreach` reads the current match at the handler's turn in the existing tick-end queue, including earlier handlers' completed writes and structural changes already applied. Queries do not select the event's target: a handler with only queries and singletons runs once per event or command and requires no entity target. Rows remain read-only; explicit `mut World` and its existing `Set` rules can change queried entities. Such writes are visible to later query reads. A handler's own `mut` component parameter keeps the ordinary copy/write-back rule: its unfinished changes are not in the stored component a query reads, and later handlers see the component after write-back. Query traversal adds no queue flush, snapshot or scheduling phase. `Spawned` queries include the new entity and `Destroyed` queries include the entity before removal.
- **`previous` on a binding reads the tick's start** (the owner, 2026-11-13). `query (previous Trooper other) others` reads every entity's `Trooper` as it was when this tick started, as the tick before left it, whatever has run since in the tick: other systems' changes, and the system's own. It's explicit: an unmarked binding reads the world as it is, as before. Decided: the word, that it goes on a query's binding beside `verified`, that it's explicit, and what it reads.

```csharp
system BotSense(mut Bot bot, mut Trooper t, query (previous Trooper other) others)
{
    foreach (var o in others)
    {
        if (Math.Distance(o.other.position, t.position) > BOT_SIGHT) continue;
        ...
    }
}
```

  Nothing in a tick can change what such a binding reads, so it's no part of the tick's schedule: the system doesn't wait for this tick's writers of the component, they don't wait for it, and a per-entity system that changes a component and reads everyone's `previous` keeps its entities across threads. Results are the same on one thread and many. Provisional (Claude's picks):
  - **Where.** Bindings of a system's or a match handler's queries, and the World (below). Each of these is an error that says what to write: a filter (`with previous X`), a system's or handler's own parameter, a view's or a local handler's query (they run between ticks, when nothing changes the match), a task (it goes on once the tick is done), `mut`, `previous` with `verified`, and a local component. A component can't be bound both ways in one query (`previous Body was, Body now` says it appears twice); two queries can.
  - **Through the World** (the owner, 2026-11-13: "a ReadPrevious variant of Read or whatever we have in there"; the names are picks): `world.GetPrevious<T>(entity)`, `world.HasPrevious<T>(entity)` and `world.TryGetPrevious<T>(entity, out var was)` are `Get`, `Has` and `TryGet` of the entity as the tick started: the component's zero value, `false`, or its default where the entity had none then. They read nothing the tick changes, so they're no access of the schedule's: a system that changes `Body` and calls `world.GetPrevious<Body>(target)` waits for no writer of `Body` and keeps its entities across threads, where `world.Get<Body>` would keep them on one. In systems, match handlers, and the functions and methods they hand their World to; a view, a local handler or a task that reaches one is an error. There is no `SetPrevious`.
  - **Which entities.** A query's are the world's as it is, filters included. While systems run those are the entities the tick started with: spawns, destroys, adds and removes wait for the tick's end, so an entity spawned this tick is in no query yet, and one destroyed this tick is still in every one, with its values of the tick's start. A query that mixes `previous` and unmarked bindings has those same entities, each binding read at its own time.
  - **In a match handler** the tick's changes are being applied, so the two differ: its query has the entities the world has at the handler's turn that also had every `previous`-bound component when the tick started. One spawned this tick, or given the component this tick, is no row; one destroyed before the handler's turn isn't in the world to be one. An entity that moved (a component added or removed) is found where it was. `HasPrevious` says which, and `GetPrevious` of an entity that wasn't there gives the zero value. What a handler changes this tick is never seen through `previous`: it's the tick's start for every handler of the tick. Outside a tick (the handlers of a match's start) nothing was there as the tick started: no rows, `false`, zero values.
  - **Text, lists, maps, sets and grids** of a `previous` component read as they were too. Copying one into the world (assigning it to a field, sending it in an event) copies what it was.
  - **A function handed the query** reads what the query reads: the word goes on the system's query, never on the function's.
  - **Loops.** An [indexed loop](https://tide-engine.dev/spec.md#indexed-loops) whose key is in a `previous` binding of a system's query is indexed whatever the system writes, the key's own field too, and its index is made at most once a tick, for every loop in the game that searches the same query by the same keys, on whatever threads. A handler's loop by such a key goes through every row (`indexed foreach` there says why). A `parallel` loop over such a query keeps its steps on one thread where a `previous` component holds a list or map of text or of lists.
  - **What it costs.** Only what some code reads of the tick's start is kept: the lanes its loops read of the components it marks, a component whole where it's read through the World or in a handler, and their heaps. They're kept by holding the pages they started the tick in while its systems run, and until its handlers have run in a game where a handler or a function reads the tick's start, which also keeps where every entity was. A system that changes a kept page that tick writes into a page of its own, as it does beside any snapshot. None of it is match state: a world's hash, its snapshots, a rollback and its packed bytes are what they'd be without it.
- **Views take `query` parameters as systems do**, read-only, with the same syntax and the same filters:

```csharp
// A fighter's shadow falls on the highest platform under it.
view DrawFighter(Body body, Fighter fighter, query (Platform box) platforms)
{
    foreach (var entry in platforms) { ... entry.box.center ... }
}
```

  - **Rows are what a view sees**: blended between ticks like the view's own parameters, over the entities of the world it draws. An entity that wasn't there last tick is as it is, as for a view's own entity.
  - **`verified` inside a query** follows the rule for views (see Views and drawing): a binding marked `verified` comes from the world the server has confirmed. `query (verified Health health) confirmed` loops over the confirmed world's entities; a query that mixes marked and unmarked bindings takes the entities that are in both, the same entity and not just the same handle. The filters `with verified X` and `without verified X` work in a query too.
  - **A query is all local or all the match's**, as a view is: a view may loop over local entities too, like its own sparks.
- **Local handlers take queries too** (`local event(Hit hit) Show(..., query (Body body, with Fighter) fighters)`): they're local code that reads the match as views do. Their rows are as the handler's own match parameters are: from the tick that sent the event.
- **Attached local fields through query rows** (agreed 2026-10-19). In local code, a binding reads its entity's current attached local fields. `query (mut Fighter fighter) fighters` can write those fields; match fields and the entity handle remain read-only. This applies to views, verified bindings and local match-event handlers: local fields have no predicted, verified or recorded history. A direct binding passed to a synchronous helper retains its local-field capability; an explicit component copy has none. Read-only borrows accept mutable sources; a helper requiring a mutable binding needs a mutable source. Helpers cannot acquire this access from match code or write a row's match fields. Mutable bindings currently require a match component with attached local fields; local-world component queries retain read-only bindings. Birth identity distinguishes replaced entities sharing a handle. Read-only default access creates no attached row; mutable access prepares owned storage when the fields are used. Active mutable outer parameters share storage with query access.

<a id="borrowed-queries-in-functions-and-methods"></a>

#### Borrowed queries in functions and methods

Decided (2026-10-18): an ordinary synchronous function or method borrows a query with the same parameter syntax, such as `float TotalMass(query (Body body) bodies)`. A caller passes its query directly, `TotalMass(enemies)`. The function receives that selection for the call; its signature does not create a new world query.

- A helper's bindings describe required row data. Each must match one unambiguous named binding of the same component type in the argument; binding names and order can differ. Extra bindings are allowed. A filter-only `with Body` does not grant a helper the right to read Body data: the caller must bind it. A helper's `with`/`without` filters require the caller's query to guarantee that presence/absence; they do not filter the argument again. Extra caller filters remain in effect. If a source binds the same component twice, such as predicted and verified Body, pass a separate query with the desired single binding.
- The source retains its traversal order and timing: live match/local queries remain live, views supply their blended/verified rows, and local handlers supply recorded rows. Borrowing creates no list, snapshot or whole-set copy. Forwarding through further helpers preserves the same source. Container fields read through a borrowed recorded query are included in its journal capture.
- Match and local entity domains stay distinct. A helper borrows local rows with local component bindings, such as `query (local Spark spark) sparks`; their handles are LocalEntity. `verified` stays on the source view's query, rather than a helper parameter: the helper reads the values it is passed.
- The borrow lasts for the synchronous call. The query parameter itself has no `mut`, `out` or default; a nested binding can be `mut` for attached local fields. Queries cannot be stored or returned, or captured by callback blocks, parallel steps or tasks. Whole rows cannot escape either; ordinary component value copies keep their existing rules. Ordinary helpers can still send events and start tasks with permitted ordinary arguments under the caller's capabilities.
- A query grants only its declared row access, without an implicit World, singleton lookup or entity `this`. Existing explicit World access and its write rules remain separate. Query reads and any explicit writes retain the caller's scheduling and evaluation-order rules, including observing completed earlier World.Set writes.
- Queries are CPU parameters of ordinary Tide functions and methods. Externs, operators, audio declarations, shaders and async routines take none.

<a id="the-world"></a>

### The World

- `World world` is a built-in parameter, like `Devices`: any entity's components, by its handle. It reads another entity's component in the same tick, where `Send` would wait for the tick's end. A signature has one at most, and it filters nothing.
- `world.Get<Health>(target)` is a copy of that entity's `Health` as it is, or its zero value when it has none. `world.Has<Health>(target)` tells whether it has one.
- Provisional: `world.TryGet<Health>(target, out var health)` is both in one, as C#'s `TryGetValue`: whether the entity has one, and through `out` (see Out parameters), a copy of it, or the component's `default` when it has none. A component with a grid in it can't be copied, so it has no `TryGet`.
- `world.Set<Health>(target, h)` puts one back, and needs `mut World`. Nothing happens when the entity has none. The component `Get` gives is a copy, as a list's element is: change it and put it back, or change it where it is with `world.Edit<Health>(target, health) { ... }` (below).

```csharp
system Attack(Attacker a, World world)
{
    var h = world.Get<Health>(a.target);
    if (world.Has<Health>(a.target)) { ... }
}

system Heal(Healer healer, mut World world)
{
    mut var h = world.Get<Health>(healer.target);
    h.value += 1;
    world.Set<Health>(healer.target, h);
}
```

- **The schedule goes by fields** (2026-11-13; nothing a game's code can observe, as parallelism never changes results; the granularity is Provisional). Two systems that take the same component or singleton wait for each other only where one writes a field the other reads or writes. A system's reads and writes of a parameter are its code's, through the functions it hands the value or a part of it to: a value read or copied whole, a method of its own called on it, or anything the compiler can't see into is every field. For a singleton it's by field (an array's elements, or a struct field's own fields, are one). For a component it's by the lanes its fields are stored in, four bytes each, so small fields that share one count together. What a system reaches through its `World` is all of the component; a query's rows are the fields its loops read of them, where the system does nothing else with the query. Text, lists, maps, sets and grids are still each owner's: two systems that change different list fields of one component or singleton wait for each other. A build for a debugger, which copies each row whole, goes by whole components. `tide schedule` and the editors name the field a wait is over.
- **A per-entity system that only adds to a singleton splits across threads** (2026-11-13, Provisional in what qualifies). Where every statement naming a singleton the system takes `mut` is an assignment into it or a call that changes it, taking from the entity only plain values (fields, variables, constants, operators, `Math`, constructors, and text written out or interpolated from those), and no other code of the system reads a field of that singleton the system writes, the system's entities run on threads and those statements run after them, on one thread, in the entities' order, with the values each entity's turn worked out. The singleton, its lists and text come out exactly as on one thread, `float` sums included. A function handed the singleton may read and change it freely, but not send, spawn, roll, start tasks, take the `World` or reach C; a system that calls C at all stays in order. Anything else keeps the system's entities in order on one thread, as before, and so does a system whose entities do little but add (the compiler's reckoning of the code: the entities keep at least as much work as is put off), where threads would have nothing to take. The one thing that can tell is the order of what a function handed the singleton prints, which comes after the entities' own.
- What a system reaches through its `World` is access to every entity's component, which the schedule takes from the calls in its body: `Get<T>` and `Has<T>` read every entity's `T`, and `Set<T>` writes every entity's `T` and keeps the system on one thread. A system that reads through its `World` a component it also changes through a parameter runs on one thread too, and reads the rows it changed earlier in the same run.
- `Set<T>` can target any entity beside a read-only `T` parameter, directly or through helpers (extended 2026-10-18). Each invocation takes the component as the code comes to that entity, including preceding invocations' writes. That parameter keeps its value until the invocation returns; a task gets it again when it resumes. `Set` changes the stored component immediately, so a following `Get` or query reads the new value. Snapshot sharing does not change these results. This also applies to local components in local code.
  - `Set<T>` also works beside `mut T` (agreed 2026-10-19). Setting the current entity replaces both its stored component and its active mutable parameter immediately, including through synchronous helper chains. Setting another entity leaves the current binding unchanged. For example, setting health to 20 and then incrementing its mutable parameter finishes at 21. This is a whole-value replacement: unfinished edits to the parameter are discarded, and its containers acquire the replacement value under the ordinary ownership rules. Subsequent parameter edits retain ordinary write-back timing; a `Get` or query sees the value published by `Set` until those edits are written back. Explicit copies and read-only parameters keep their captured values. An async handler establishes fresh bindings whenever it resumes; no active binding is retained across a wait.
- **`world.Edit<Health>(target, health) { ... }` changes an entity's component where it is** (built 2026-11-14 on the owner's approval of the recommendations: "go with your recommendations"; every point below is Provisional, Claude's picks). It's for what `Get`, change, `Set` did, which copied the component twice and lost the change wherever the `Set` was missed, on an early `return` or `continue`:

```csharp
system Heal(Healer healer, mut World world)
{
    world.Edit<Health>(healer.patient, health)
    {
        if (health.value >= 100) return; // Put back first, unchanged
        health.value += 1;
        health.lastHealer = this;
    }
}
```

  - **The form** is a call that takes a block (see Calls that take a block): the component in `<>`, as the World's other calls have it, the entity, and a new name, which the block calls the component by, as `items.Sort(a, b) { ... }` names the two elements its block compares. Nothing is written before the name: an argument takes no `mut`, and `out` says a call only gives its variable a value, where an Edit takes it back too. The name is in scope in the block alone, and can't be one that's in scope already. Edits are listed with commas like any calls that take a block: `world.Edit<Purse>(from, a), world.Edit<Purse>(to, b) { ... }`.
  - **The name is the entity's component itself**, as a `mut` component parameter is for the entity the code runs for: fields change where they are; its text, lists, maps, sets and grids are the component's own, changed in its memory with nothing copied; its methods run for its entity (`this` in one is the edited entity); a function's `mut` parameter can be handed it.
  - **It's put back as the block ends, however it's left**: at its end, by a `return`, by a `break` or `continue` of a loop around the Edit, by a `try` that passes an error on or a `fail`, and in an async handler as well as in synchronous code. Only the parts that changed are written (as a `mut` parameter's are).
  - **An entity that's gone, or has none of the component, skips the block**, as a `Set` does nothing then. There's no `else` and no result: the call is a statement, and `if (!world.Has<Health>(target))` is the other branch.
  - **What it needs is a `Set`'s**: `mut World`; a view edits only local components (a match component is the match's, which views don't change); not in a parallel loop's step or a sort's comparison. Inside the block, a task can't wait (`await`): the component is put back in the tick the block began in. A parallel loop's step and a sort's comparison in the block can't read the name, as they run as code of their own: copy what they need into a local before. A task can't be handed it, as a task gets its components again from the entity it belongs to.
  - **To the schedule it's a `Set`**: a read and a write of every entity's component, all of it, through the functions it's in too, which keeps a per-entity system on one thread. A system's own parameters go by fields (above); an Edit's name doesn't yet.
  - **A name the block never uses is a warning**, as the Edit changes nothing, and **so is one it only reads**: the Edit still counts as a write of every entity's component, so the warning says to read it with `TryGet`. Changing it counts however it's done: assigning it or a field, a `mut` method, a list's or text's change, handing it to a function's `mut` parameter.
  - **One component, two names.** Where the code can tell as written that two places are one entity's component, it's an error that says which name to use: an Edit of the entity the code runs for while it takes that component as a `mut` parameter (change the parameter), an Edit of `this` in that component's own method (change its fields), and a `Get`, `TryGet`, `Set` or another `Edit` in the block of the entity the Edit names, written the same way (`this`, or one read-only variable, or the same fields of one). Where it can't tell, the names are one component at run time: an Edit or a `Set` in a function the block calls, of the same entity, finds it as it finds a `mut` parameter's (a `Set` replaces it whole), an Edit inside the block of an entity that turns out to be the same one is the same component, and a helper's Edit of the entity the code runs for is the code's own `mut` parameter. Nothing is lost either way. A `Get` or a query of that entity's component in the block reads what's stored, as it does beside a `mut` parameter of that entity: the block's changes are written back as it ends. Beside a read-only parameter of that component, an Edit of the entity the code runs for is what a `Set` is there (above): the stored component changes, and the parameter keeps the value it was read with, its lists too.
  - **Prediction, rollback, snapshots and hashes** see nothing new: an Edit changes the world as the `Get` and `Set` it replaces did, in the same order, so a replayed tick does the same.
  - In generated C the name is a pointer at the code's own binding of that entity's component where there's one, and otherwise at a copy of its lanes, whose text and lists are the stored ones; the end of the block stores the lanes that differ. The binding is in the chain helpers' `Set`s and `Edit`s look in, for the block.
- The signature doesn't list those components, so tooling does: `tidec --schedule` says what each system reads and writes through its `World`, and so do the language server's hover and the line above each system.
- A `World` parameter that's never used is a warning, and so is a `mut World` that never calls `Set` or `Edit`.
- Views take `World` to read the match, never to change it: `Set` of the match's component in a view is an error.
- **Functions and methods take the World too** (agreed 2026-10-05: it's how the work is carried out, not what the language means), as their caller's, passed on: `bool TryFind(Entity target, World world, out Health health)`, called as `TryFind(healer.patient, world, out var health)`. A function has no World of its own: the argument is the `World` parameter of the system, view or handler that calls it, or of the function in between.
  - What a function reaches through it is what each of its callers reaches, through however many functions it's passed. So the schedule counts it as the system's own, on the same lines (`reads any entity's Health, through World`), a system that sets through a function runs on one thread, and one that reads through a function a component it also changes reads the rows it changed earlier in the same run.
  - `Set` needs `mut World` there as anywhere, and a caller passes a `mut World` to it: a read-only one is an error that says to declare it `mut`.
  - The rules that depend on who calls are said at the call: the match can't reach a local component, a local handler's World is this machine's, a view changes nothing of the match, and a parallel loop's step and a sort's comparison set nothing. Component parameters retain the captured-read or active-mutable-binding rules above through these calls.
  - Provisional: a function takes one World at most, with no default, and it's neither `out` nor a value to keep or return. Operators and `extern` functions take none, and neither do async functions yet: an async handler takes it itself.
  - In generated C the function is handed the worlds it reaches, where its World parameter is written: the match's, read-only unless it sets, and this machine's for local components.
- `World` is built in: a game can't declare a type of that name outside a namespace.
- `lookup` parameters (`lookup Health health`, read as `health[e]`) are gone. Writing one is an error that says what to write with `World` instead.

<a id="entities"></a>

### Entities

- `Spawn(...)`, `entity.Add(...)` and `entity.Remove(...)` take plain component lists. `with` and `without` only appear in queries.
- Component values are written without `new`. A bare type name means all fields get default values.
- An entity has at most one component of each type. `Add` on a component the entity already has replaces its value. `Remove` of a component the entity doesn't have does nothing.
- When an entity needs several of something, use a list inside one component, one entity per item pointing back at its owner, or separate component types.
- Structural changes (`Spawn`, `Add`, `Remove`) are deferred. They're applied together at the next fixed point in the tick, in a deterministic order. The entity handle `Spawn` returns is usable immediately, for example to store in a component. The entity's data becomes readable once the changes are applied.

```csharp
var e = Spawn(Transform { localScale = float3(1, 1, 1) }, Player);
e.Add(Stunned { duration = 2 });
e.Remove(Stunned);
```

<a id="entry-point"></a>

### Entry point

- Project startup can select an authored prefab or an ordinary scene (see Scenes). An authored prefab starts directly as a match scene, without a handwritten `Main`.
- Without a startup selection, the scene named `Main` is where the program starts. There must then be exactly one. A local startup scene starts outside a match, usually in a menu; a match startup starts a single-player match right away.
- The startup scene 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 { speed = float3(0, 0, 5) });
}
```

<a id="evaluation-order"></a>

### Evaluation order

- Expressions evaluate left to right, like C#: operands, arguments and field initializers run in source order, the same on every platform and in every build. `Spawn(Pair { a = Spawn(Thing), b = Spawn(Thing) })` spawns `a`'s Thing, then `b`'s, then the Pair.
- The order shows wherever an expression has side effects: `Spawn` and `Scene.Load` (entity IDs), a widget or a call that draws, a call to C (what C keeps), and a call that writes, which changes what it's given as `mut`, makes what it's given as `out`, or changes the value a `mut` method is called on (a `Random`'s methods are such calls: see Random numbers). So do the functions, methods and operators that make such calls. `Pack(Next(counter), Next(counter))` runs the first `Next` first.
- A value is read in its turn too: in `Pack(counter.n, Next(counter))`, `counter.n` is read before `Next` changes it, and in `Pack(Next(counter), counter.n)`, after.
- `cond ? a : b` runs the condition first, then only the side it picks, as in C#.

<a id="archetypes"></a>

### Archetypes

- There are no archetype declarations. The compiler derives every archetype from the code: the component set at each spawn site, plus every combination reachable through adding and removing components.
- Reachable means by the code as written: `this.Add(X)` in a system only reaches the entities its parameters, `with` and `without` admit; `e.Add(X)` on an `e` that a `Spawn` or `Scene.Load` in the same code made (a local that isn't `mut`) reaches that one; `Add` or `Remove` on an entity read from a field or a parameter may reach any entity. The changes recorded for an entity in one tick apply in any order, so every combination of the components those sites add and remove is reachable from it.

<a id="double-precision-values"></a>

### Double precision values

- `double`, `double2`, `double3` and `double4` are built-in 64-bit floating-point values (owner-approved 2026-10-20). Existing numeric defaults remain unchanged. Rendering continues to use floats; introducing these values does not change Transform, camera or physics coordinates.
- Simulation double arithmetic follows Tide's deterministic IEEE basic-operation, evaluation-order, noncontraction and denormal rules, as floats do.

<a id="provisional-implemented-in-v0-awaiting-approval"></a>

## Provisional: implemented in v0, awaiting approval

<a id="depth-storage-implementation-2026-11-14"></a>

### Depth storage implementation (2026-11-14)

The occlusion pyramid stays in forward depth: source samples convert before the existing
maximum reduction, including each MSAA sample. Existing box bounds and rounding slack
therefore remain conservative; forward conversion can reduce culling precision but cannot
make the stored farthest bound nearer than its conservatively expanded test.

Vulkan selects one combined sampled/attachment depth format for a device; requested sample
counts reduce to supported counts as before. Farthest raw resolves use MIN for reversed
storage and MAX for forward storage, only where the device advertises that mode. A private
shader constant uses SPIR-V SpecId 0; WebGPU substitutes the same constant at compilation.
The forced legacy test selects forward D24 on Vulkan and depth24plus on WebGPU.

tidec v0 needed answers to these to work end to end. They're implemented, but the owner hasn't approved them yet, so any of them can change.

<a id="types-and-values"></a>

### Types and values

- Built-in scalar types are `bool`, `byte` (unsigned 8-bit), `int` (32-bit), `long` (64-bit), `float` (32-bit), `double` (64-bit), `char` (one character of text: see Text), `Entity` and `LocalEntity` (see Local state). Vector types are under Vector math, `Color` under Views and drawing, `string` under Text and `List<T>` under Lists.
- `byte` holds 0 to 255 in one byte, aligned to one byte, including in structs, components, input, `List<byte>` and grid cells. `byte` widens implicitly to `int`, `long` and `float`. Arithmetic and bitwise operators promote a byte to `int`; unary `-` and `~` do too. `byte(x)` keeps an integer's low 8 bits; for a float it first uses `int(x)` (truncated, saturating, NaN to 0), then keeps those bits. An `int` constant from 0 to 255 fits where a byte is expected, including in a list literal; other integers require `byte(x)`. Compound assignments and `++`/`--` narrow their integer result back to byte, wrapping. Input sends a byte as 8 bits; deltas send whether it changed and its 8 bits when it did. Hot reload carries byte fields over to `int`, `long` or `float` fields of the same name.
- `1.5` is a `float`; the `f` suffix is optional. The zero before the point can be left out: `.5` and `.5f` are `0.5`. An `int` converts to `float` implicitly, never the other way.
- Double spelling and conversions for this first implementation: a decimal `d`/`D` suffix selects binary64 (`1d`, `.5D`, `1e100d`), while unsuffixed and `f`/`F` literals remain binary32 regardless of their destination. `byte`, `char`, `int`, `long` and `float` widen implicitly to double; matching int/float vectors widen to double vectors. Long conversion rounds to 53-bit integer precision where needed. Double operands promote numeric arithmetic to double, splatting a scalar beside a vector. Comparisons are scalar; floating remainder and bitwise operations remain unsupported.
- Narrowing is explicit through `float(x)`, `floatN(x)`, `int(x)`, `intN(x)`, `long(x)` or `byte(x)`. Double-to-int/long truncates, saturates and maps NaN to zero; byte applies the int conversion then keeps its low eight bits. Double-to-float rounds to nearest/even, overflows to signed infinity and canonicalizes NaN. Vector conversions apply the scalar rule to each component. Floating conversions do not change defaults or camera coordinates.
- Doubles occupy eight bytes per component with eight-byte alignment. They work in ordinary fields, arrays, list/map values, grid cells, optionals, tasks, C signatures, event/command payloads, snapshots, hashes and packing. Views interpolate them with double arithmetic and the frame's existing float fraction; `[Snap]` retains its usual meaning. `[Position]` supports double scalars/vectors as well as floats; `[Rotation]` remains limited to float radians and quaternion. Floating map/set keys remain unsupported.
- Input and command double components pack as 64 raw bits, low word first; an input delta sends one changed bit and the 64 bits when changed. Nonfinite input/command doubles repair to their declared defaults before bounds and, for input, Sanitize. Hot reload preserves double values and widens matching byte/int/long/float fields to double; narrowing resets the field to its new default.
- Double text uses shortest exact round-tripping digits, or `F0` through `F17`. `double.TryParse` and scalar JSON double fields round directly to binary64 with exact integer arithmetic, including subnormals and ties to even; overflow fails. JSON writes negative zero as `-0` and nonfinite values as `null`, as floats do. Vector JSON support remains unchanged.
- Double math includes the existing component-wise functions, including trigonometry, exponentials, logarithms and Pow, plus vector geometry. Portable binary64 kernels compile with Tide's strict arithmetic flags; no platform transcendental calls, FMA or excess precision enter their results. As with float math, correctly rounded results for every input are not promised. `Math.Hash` hashes binary64 bits with the existing xxHash32 convention. `double.PI`, `double.TAU` and `double.E` are binary64 constants; existing Math constants remain floats. Double noise and a double quaternion type remain unimplemented. GPU code rejects doubles and asks for a conversion in local code before drawing.
- `double2x2`, `double3x3` and `double4x4` (owner-requested 2026-10-20) have the same column storage, construction, operators and matrix math as float matrices, with eight-byte components and alignment. Matching float matrices widen implicitly; narrowing is explicit. `double3x3(quaternion)` widens components before matrix arithmetic; `double4x4(rotation, translation)` takes a double3x3 and double3. Transform/Rotate and the Translate/Scale/TRS/PerspectiveFov/Ortho constructors have double versions. Double TRS accepts a double3x3 or quaternion rotation. A quaternion retains its input float precision. Matrices participate in ordinary storage, input/command repair and packing, snapshots and view interpolation. Hot reload preserves the same matrix type; changing matrix precision resets to the new declared default, as a matrix type change did before.
- A decimal literal with the lowercase suffix `deg` is a `float` in radians: `180deg`, `.5deg`, `1e2deg` and `1_8_0deg`. The number is first read as a 32-bit float, then converted at compile time with the same bits as `Math.Radians` of that float. Unary minus works normally (`-90deg`). The suffix touches the number, cannot combine with `f` or `L`, and is not accepted on hex or binary literals. It introduces no new type or implicit conversion; `quaternion.Euler(0, 180deg, 0)` receives radians.
- `long` is a 64-bit integer, for counters, sums and hashes that outgrow an `int`: tick counts over months, scores, money, IDs from outside. An `int` converts to `long` implicitly, and `int` and `long` mix in arithmetic, comparisons and bitwise operators, giving a `long`. Apart from widening to `double`, nothing else converts by itself: `float(x)` makes a `long` a `float` (rounded to the nearest), `long(x)` a `float` a `long` (truncated toward zero, saturating, NaN to 0) and `int(x)` a `long` an `int` (its low 32 bits, as C#'s unchecked cast). A `long` with a `float` is an error that says which to write. There are no `long` vectors, and shift counts stay `int`s. `long` arithmetic wraps and divides by zero to 0 like `int`'s; shifts use the count's low 6 bits. A `long` literal has an `L` suffix (`5L`), and a literal past the `int` range is a `long` by itself: decimal up to 9223372036854775807, hex and binary up to 64 bits, read as the bit pattern (`0xFFFFFFFF` is the `int` -1; `0xFFFFFFFFL` is 4294967295). `Math.Abs`, `Sign`, `Min`, `Max`, `Clamp` and `Hash` take longs; `switch` works on them; text shows them with the same formats as ints (`X` up to `X16`). A `long` field is 8 bytes, aligned to 8, in components, inputs (sent as a 64-bit varint, and as a delta by how much it changed), lists and grid cells. On hot reload an `int` field carries over to a `long` of the same name, and a `long` to a `float`.
- In `cond ? a : b`, the condition is a `bool`, and the two sides have the same type or one converts to the other's, as in C#: `ready ? 1 : 0.5` is a `float`. It binds looser than every binary operator and groups to the right.
- Integer arithmetic wraps on overflow. Integer division and modulo by zero give 0, so no input can crash the simulation.
- Bitwise operators `& | ^ ~ << >>` work on `int` and `long`, with compound forms `&= |= ^= <<= >>=`. As in C#, shift counts use their low 5 bits (`1 << 33` is `2`; an `int` shift) or 6 (a `long` shift) and `>>` keeps the sign. Operator precedence follows C#.
- Integer literals can be decimal (`255`), hex (`0xFF`) or binary (`0b1010`). Decimal goes up to 2147483647 as an `int`, and beyond that is a `long`. Hex and binary can use all 32 bits and are read as the int's bit pattern: `0xFFFFFFFF` is `-1` and `0x80000000` is the lowest int; past 32 bits they're longs the same way.
- `_` separates digits in any number, as in C#: `1_000_000`, `0b1111_0000`, `0x_FF_FF`. It's allowed between digits and right after `0x` or `0b`, but not at the start or end or next to `.`.
- Local variables need an initial value.
- The warning for a local that's never read (see Mutability), in its details:
  - It's about the locals statements declare: `var`, a type, or `mut` in front of a name, in a `for`'s first part too (`for (var i = 0; ...)`, where the for's own condition reading it counts).
  - The names code needs whether it uses them or not are exempt, as in C#: a `foreach`'s and a `parallel` loop's variable (a loop that only counts), the name after `is`, and a `Sort`'s two elements.
  - No name opts out, `_` included: a value that isn't needed isn't given a name, and a call that's there for what it does is a statement.
  - A read is the local's name anywhere but where an assignment writes: `total = 5`, `total += hits`, `total++`, `stats.health = 3` and `seen[i] = 1` don't read `total`, `stats` or `seen`. A read on the right of its own assignment counts (`total = total + 1`), and so does passing it, as a `mut` argument too, and calling a method on it.
  - A function's or a method's call written as a statement, which gives a value and does nothing else, is a warning: `'SetHeader' gives a value that nothing takes, and does nothing else` (the owner, 2026-10-11: "its fair to warn"). `_ = value;` works a value out and drops it, which says it's meant (the owner's: "`_ = request.SetHeader(...)` to supress it and indicate they mean to discard the result"). Provisional: what "does nothing else" is, which is the rule below; a call that can fail keeps its own warning and gets no second one; `_ = ` takes any expression that has a value, and `_` there is no variable, so nothing reads it.
  - A call does something when it's a `Spawn`, `Scene.Load` or the like, a widget (`GUILayout.Button`), an `await`, a `try`, a list's or a map's change (`items.Remove(x)`), or a function or method that calls C, draws, is async, takes a `mut` or an `out` parameter or is a `mut` method. Any other call only gives a value, a function's too.
  - A local that's assigned later gets a note of its own: remove it and what assigns it, or use it.
  - Errors hide uses, so a local whose scope has an error in it waits: the warning comes once the code checks.
- `default` of a struct or component is its fields' defaults, not all zeros as in C#, where `default` skips field initializers: a Tide value never exists without them.
- As in C#, `default` is only compared: `default + 1` is an error. So is `var x = default;`, which says no type, and a place where nothing else does, like `if (default)`.
- In a built-in call, the other arguments pick the version, and `default` takes its parameter's type: `Math.Max(default, 1.5)` is a float. A call whose versions take different types there is an error, like `Math.Mul(q, default)` (a quaternion or a float3), and so is a `Math` function whose arguments are all `default`. Constructors like `float3(...)` don't take it.

<a id="systems"></a>

### Systems

- A system with no component parameters runs once per tick. Otherwise it runs once per matching entity.
- A parameter that's never used, or declared `mut` and never written, is a warning: it makes other systems wait for nothing. A component that's only there to filter entities belongs in `with`.
- **Where the World goes.** Systems, views and event handlers take `World`, async handlers too: their tasks keep it across their waits. Ordinary functions and methods can take the caller's `World` explicitly, and pass it through further helpers (see The World). Async functions and extern functions take none. Outside an argument to a `World` parameter it is only ever called: it can't be stored or compared, and `world.Get<Health>(e).value = 5` is an error, since `Get` gives a copy.
- **The World in local code.** A local component is reached the same way, with a `LocalEntity`: `world.Get<Spark>(e)`. A view or a local handler with `mut World` can `Set` one, as it can change local state. Match code's `World` only reaches the match's components, and a local handler's only local ones for now. A view that reads the match through its `World` only runs in a match, as one that takes a match component does, and what `Get` gives it is the component as of the latest tick, not blended between ticks.
- **A type in `<>`.** Only the `World`'s methods take one. A `<` after a method's name starts a type when a name, `>` and the call's `(` follow, as in C#: `a.b < c.d > (e)` would compare a `bool`, so no comparison reads that way.
- **`Set` and text.** `Set` of a component that holds text, lists or maps copies them into the world as the entity's own, as assigning the component does. A system that does it changes that component's heap, like any that writes its text (each component's, singleton's and event's text and collections are in a heap of its own, which one system changes at a time).
- **`Set` where code runs at once.** In a parallel loop's step and in a `Sort`'s block, `Get` and `Has` work and `Set` is an error, as writing anything outside the step is.
- **A game's own `World`.** A type named `World` in a namespace is what a plain `World` means in that namespace's code, and in files that `using` it, as with any name: the built-in one is hidden there. Elsewhere it's written with its namespace, `Game.World`, beside the built-in `World`.
- `return;` ends the system for the current entity.
- Locals can't reuse the name of another local or parameter in scope.
- Names starting with `tide_` are reserved for generated code.

<a id="entities-1"></a>

### Entities

- `Spawn`, `Add` and `Scene.Load`'s extra root components accept component values as well as type names and literals. Values are evaluated once in written order and copied when the change is recorded, retaining owned containers. Later edits to the source do not change the queued value. Local sidecar fields are not part of a copied component; new entities initialize their own local defaults. Scenes still load through their scene type or literal, and `Remove` takes types only.
- `e.Destroy()` destroys an entity. It's deferred like other structural changes.
- The "fixed point" where structural changes apply is the end of each tick (and the end of `Main`). Changes apply in the order they were recorded.
- `Add`, `Remove` and `Destroy` on an entity that was already destroyed do nothing.
- `Spawn` returns its final opaque logical identity immediately, including in code that runs across threads (decided 2026-11-06). Identity comes from the public simulation birth clock and causal execution: the system or handler, its entity, the written spawn/call site and that site's occurrence within the invocation. Query invocations fork by their row's logical identity; helpers, events, commands, prefabs and waiting tasks retain their causal path. Private allocator counts, table positions, worker numbers and private component values are not identity inputs. Physical registration and queued structural application retain their normal timing; `Has`/`Get` before application do not expose components that have not been installed.
- Matching causal execution produces the same entity after projection loading even if hidden entities allocate or destroy physical slots in between. A corrected initializer alone does not turn the same causal entity into a different entity or reset its local fields. Hidden-dependent gameplay can still produce different executions and require authority updates; stable identity does not simulate absent private state. Logical-key collisions or exhausted causal counters fail explicitly before identities can alias. Trusted C uses the same 128-bit identity; explicit keyed creation supports stable match spawns, while unkeyed C/local allocation is a separate namespace and is not visibility-stable.
- Provisional (2026-11-12): the entities one `Spawn` statement makes while one piece of code runs once (a handler's run, a system's run for one entity) come one after another, in the order they were made, wherever code goes through entities in their order. An identity is still made from the same things: the code that ran and what it ran for, the statement, and how many times that statement has run there. Entities of different statements, or of different runs, keep an order between them that is the same on every machine and otherwise arbitrary.
- `Spawn` can't appear on the right side of `&&` or `||`, or in a side of `?:`. Those parts only run sometimes, while spawns run first, in order (see Evaluation order). Spawn into a local before the condition, or use `if`/`else`.
- **Sparse components.** A component marked `[Sparse]` is kept as a presence bit and its value in every archetype it can reach, rather than making an archetype of its own with each combination: `Add` and `Remove` of it move no entity. Systems, views and handlers that take or filter on a sparse component skip the entities that haven't got it, row by row. Two systems can't meet the same entity when one needs a sparse component the other excludes, but their entities are rows of the same archetype, kept side by side: where one of them writes a component the other reads or writes, they wait for each other all the same. Only archetypes keep two systems apart. A status that flickers, gained and lost every few ticks by many entities at once, wants `[Sparse]`.
- **Tags that come and go.** Any other component's `Add` and `Remove`, a tag's included, move the entity to the archetype with or without it at the end of the tick, so systems that take or filter on it admit or skip whole archetypes: `without Sleeping` streams through the awake entities alone, and systems on either side of it don't wait for each other. Where tags that move entities would take a game past the archetype limit, tidec keeps some of them as presence bits instead, as if marked `[Sparse]`: first the tags an `Add` or `Remove` on an entity read from a field or a parameter names (which can reach every archetype), then the rest, each in the order declared, until the archetypes fit. Which tags those are depends on the code alone. A component with fields is never chosen that way: past the limit it's an error that says to mark it `[Sparse]`. Decided (the owner, 2026-10-29): toggled tags move entities by default, `[Sparse]` opts out. Provisional: the fallback's order.

<a id="built-ins"></a>

### Built-ins

- `Time` is a built-in singleton with `float dt` (the fixed tick length), `int tick` (starts at 0), `float t` (the seconds since the match started) and `int tickRate` (the ticks in a second). Systems can read it but not write it.
  - `t` is `tick * dt`, worked out from the tick each time and never added to, so it doesn't drift. Views see it blended between ticks like any float of the match, so it moves every frame, in the frags and verts they draw through too.
  - A float holds about 7 digits, so `t` gets coarser as the match goes on: after a day its steps are about 8 milliseconds. What has to be exact counts in `tick`.
  - `tickRate` is 1 / `dt` to the nearest whole number: the `tickRate` setting, or the rate the machine that runs the match gave it.
  - The match's seed is read as `Random.seed` (see Random numbers). Generated C keeps it in `Time` underneath; Tide code can't name `time.seed`.
- `Debug.Log(text)` prints a line for whoever runs the game: the terminal under `tide run`, the browser's console on the web, the system's log on Android, and Unity's Console for a game inside Unity (in the editor and in a desktop player's log; a WebGL player's page has it in the browser's console). A run with a window also keeps it in `Player.log` in the persistent data directory, with `Player-prev.log` for the run before and a folder for each crash in `Crashes` (Provisional: names, contents and limits are in docs/game/files.md, Logs and crashes). `Debug.Assert(condition)` and `Debug.Assert(condition, text)` stop the program when the condition is false, naming the file, the line and the source line, and the text. Shipping builds that strip diagnostic names replace the file path with an ID and omit the copied source line; they retain the check, line number and authored text, with a private build map for resolving the ID. Both go anywhere, and neither changes the match, so it stays the same on every machine with or without them. A tick a client runs again after a rollback logs again: a log of match state is best prefixed with `Time.tick`.

<a id="syntax"></a>

### Syntax

- Statements: blocks, `if`/`else`, `switch`, loops (see Loops), `break;`, `continue;`, `return;`, `fail error;` (see Errors), local declarations, assignments (`= += -= *= /= %= <<= >>= &= |= ^=`), `i++` and `i--`, and calls: of `Spawn`, `Add`, `Remove`, `Destroy`, `Send`, the `World`'s `Set`, the `Draw` and GUI functions, lists' methods, and methods and functions, with a block after the ones that take one (several of them can be listed with commas before one block: see Calls that take a block), and with `!` after or `try` before the ones that can fail.

<a id="evaluation-order-1"></a>

### Evaluation order

- A compound assignment reads its target before its value is worked out, as in C#: `counter.n += Next(counter)` adds to what `counter.n` was. An index in the target (`items[Next(counter)] += 5`) runs once, before the value.
- A method reads the value it's called on as it runs, once its arguments are worked out, as C# reads a struct variable: `stats.Plus(stats.Bump())` sees what `Bump` left. An element is read once its index is worked out: `items[Push(items, 7) - 1]` is the element `Push` added.
- A read-only argument is a copy made in its turn, a list's too: `Total(items, Push(items, 4))` totals the list as it was. A `mut` method given its own value's list (`bag.Absorb(bag.items)`) gets a copy as well.
- A read-only method's receiver follows the same copy rule: when a `mut` or `out` argument can change its lists or maps during the call, the method reads its own copy, made after its arguments are worked out.
- A list's, a map's and a set's changes that give a value (`items.Remove(x)`, `seen.Add(k)`) are calls that write, and so are widgets that change what they're given (`GUILayout.Toggle(title, open)`), C functions with a `mut` or an `out` parameter, and a map's `TryGet`.
- `++i` and `i++` as values are writes like those: `i + ++i` reads `i` before it changes, `++i + i` after, and `items[i++] + items[i++]` reads two elements in a row.
- A variable an `out` argument makes is read in its turn like any other: in `Count(tally, out var made) * 10 + made`, `made` is what the call gave, and in `seen * 100 + Count(tally, out seen)`, `seen` is read before the call makes it anew.
- A call whose value is read several times runs once: `float4(Corner(counter), 0, 1)` and `Corner(counter).yx` each call `Corner` once.
- Arguments passed by name are worked out in the order the call writes them, not the parameters': in `Pack(ones: Next(counter), tens: Next(counter))`, `ones` gets the first `Next`. A default the call leaves out is a constant, so it has no turn.

<a id="callable-shader-values"></a>

### Callable shader values

Initial implementation choices, 2026-10-24, provisional:

- `Func<A, B, R>` is a local value taking A and B and returning R. Zero to 16
  arguments are supported, read-only unless marked `mut`; the final type is the result, including
  `void`. Named synchronous non-extern, non-failable functions match exact
  parameter types/modes and result types. Typed expression lambdas take their
  signature from context and declare matching parameter modes. Generated
  dispatchers forward mutable parameters using ordinary mutable-call semantics;
  default/unknown targets leave those arguments unchanged. Results cannot be
  qualified `mut`; `out` callable parameters remain unsupported.
- Lambdas copy captured plain values at construction and own those copies.
  Their lifetime is independent of the source stack. Numeric structs and
  fixed arrays work; heap containers, rendering-resource captures, borrowed
  entity/component/world/input context, nested lambdas and recursive capture
  layouts are diagnosed. Explicit helper parameters and asset references
  retain their existing capabilities and GPU rules.
- Each Func signature has a closed set of targets. Stored values contain a
  target tag and typed capture fields, never native code pointers. CPU and
  GPU invocations use generated switches and ordinary calls. Default or
  unknown tags return the result's default, or do nothing for void. GPU
  reachability and resource/effect checks include the dispatcher and targets.
- A frag or vert's name also denotes its local configured-stage type.
  Initializers bind all function slots by name; other shader inputs retain
  existing draw binding rules. Locals, attached local fields, local-world
  components, singletons, helper arguments/results and local collections can
  retain these values. Function bindings cannot enter match state. A configured
  stage with a missing/unknown required target is skipped at draw submission.
- Instanced draws upload function tags and captures as ordinary instance data.
  Different targets share a shader and draw when its normal state and resource
  bindings allow it. Ordinary per-draw values stay shared uniforms. Captures
  reserve fields per target of a signature; GPU attribute/uniform limits remain.
- Named function identities derive from qualified names and signatures, and
  captures have named fields for normal local serialization/migration.
  Lambda identities also include their enclosing declaration and source
  location. Moving a lambda can invalidate old bindings; reconstruct those
  bindings after such a hot reload. Identity collisions are diagnosed for
  callable targets. Automatic specialization of constant targets and compact
  overlapping capture payloads remain optimizations to explore.

<a id="functions-and-blocks"></a>

### Functions and blocks

- A call with a block after it is a statement, and the block's braces go on lines of their own, like any other's. A function that takes an Action returns nothing, since its call is a statement: it changes what its caller passes as `mut` instead.
- Only functions take an Action, not methods, and an Action is never `mut`. An Action can't be stored in a field or a local.
- In the block, `return` ends the caller, as if the block were written there, and `break` ends the caller's switch, even if the function runs the block inside a switch of its own. `return` in the function's own code ends the function.
- A function that takes an Action is copied into each call in generated C, with its locals renamed, so its names never hide the caller's in the block.
- A `mut string` parameter is the caller's text, a local's or a field's, which the function changes.
- **Functions that send, spawn and change entities**, beyond what's decided (Functions): built 2026-10-08, each point a pick awaiting the owner.
  - **Which world** a function's `Send`, `Spawn`, `Add`, `Remove` or `Destroy` is in is told by what's written, as an async function's is: the event's own, an `Entity` or a `LocalEntity`, the components'. A command is this machine's to send. What's written has to agree with itself, which is the one error in the function: a `Spawn`'s, an `Add`'s and a `Remove`'s components are all of the entity's world, and an event goes to an entity of its own. A `Spawn` with no components is the match's.
  - **Who can call it:** what's the match's (a match event, the match's entities), match systems, event handlers, command handlers and the match's tasks; what's this machine's (a local event, a command, local entities), views, local handlers and this machine's tasks. An async function that calls one is of that world (see Tasks). A function that does both can be written, and nothing can call it.
  - **What never does, whoever calls it:** a `Sort`'s comparison and a parallel loop's step, the input's `Sample`, `Sanitize` and `Predict`, frags and verts, and an `audio` declaration: a call there of a function that does is the error. A struct's operators and a component's `Interpolate` are refused where the `Send` is written, or the call of what sends: an operator is handed its operands and nothing else, in a default's value too, and the engine calls `Interpolate` as views blend.
  - **Methods do as functions do**, though they still can't draw. A component's method reaches its entity as `this`; a function has none and takes an `Entity`.
  - **A function's spawn joins the scene of the entity its caller runs for**, through however many functions, when that entity is of the spawn's world, as the caller's own would.
  - **It's the caller's in the schedule too:** a system that calls a function that spawns records stable logical identities and applies their physical registration in deterministic order, once it's done, without waiting for other systems that spawn; and one whose function records text changes the heap of the component or event that holds it, as if the `Spawn` or the `Send` were written in the system. Sending makes nothing wait, there as anywhere. A foreach over a grid whose step calls one goes in order.
  - **Its calls keep their order:** what a function records goes where it's called among what the caller records itself, and a call that gives a value runs in its turn, like one that writes (see Evaluation order).
  - `Add` and `Remove` in a function are on an entity read from a parameter, so they may reach any entity (see Archetypes): a helper makes more combinations than `this.Add` in the system does.
  - **Session calls and `Clipboard.Copy` are a view's and a local handler's, so a function's that they call** (the owner, 2026-10-11, of functions that couldn't call them yet: "yes lets improve the session stuff"). `Session.Start`, `Open`, `Close`, `Join`, `Connect`, `Leave`, `Kick`, `KickAll`, `Ban`, `Unban` and `End`, `Clipboard.Copy` and `Application.Quit`, are written in a function or a method as in a view, and are this machine's: a call from the match is an error at that call, which names the function and the line it asks on, as is one from `Sample`, `Sanitize` or `Predict`, a parallel loop's step or a comparison. An operator and `Interpolate` still can't, where they're written. Provisional: `session.room`, `session.invite` and a whole `Session` as text stay the view's to read and pass, as the room is no part of the `Session` value a function is handed.
  - **Starting a task is a function's too, as the code that calls it could** (built 2026-10-11, on the owner's two rules: a function does what its caller could, with an error only at a call from code that can't, and no "not yet" where a feature could work; each point a pick awaiting the owner). An async function called as a statement in a function or a method starts a task, as in a system.
    - **Which world** is the task's own (see Tasks): a function that starts a task that changes the match is the match's to call, and one that starts a task that uses local state is a view's, a local handler's or a local task's. A call from the other side is an error at that call, which names the function, the task and the line that starts it. A task whose world nothing decides starts in the world of the code that calls the function, so one function serves both.
    - **Whom it belongs to:** the entity the calling code runs for, through however many functions, as a task that code started itself would: it ends with that entity, and what it spawns joins that entity's scene. Code that runs for no entity starts tasks that belong to its world.
    - **A task's singleton is the caller's own.** A task gets its components and singletons again each time it goes on, so a call that starts one passes a parameter of its own, never a copy. A function passes its own singleton parameter on, and then every call of that function passes its own too, through however many: an error at a call that passes a copy. A function's component parameter isn't passed on to a task: it may be any entity's, and the task gets the one of the entity it belongs to, so that start is written in the system, view or handler.
    - **It's the caller's in the schedule:** a system that calls a function that starts tasks runs on one thread and waits as one that starts them itself does (see Tasks). Its calls keep their order, as a function's sends do.
    - **What never does, whoever calls it,** is what never sends: a comparison, a parallel loop's step, `Sample`, `Sanitize` and `Predict`, a frag or a vert, and an `audio` declaration, each an error at the call; an operator and `Interpolate`, where the start is written.
  - **Loading, switching and unloading scenes are a function's too** (built 2026-11-14, after the owner found scenes awkward to deal with; each point a pick awaiting the owner). `Scene.Load`, `Scene.Switch` and `Scene.Unload` are written in a function or a method, and the code that calls it answers for them as it does for a `Spawn`: match code for the match's scenes, a view or a local handler for this machine's.
    - **Which world** is the scene's own for a load or a switch (`scene` or `local scene`), and the entity's for an unload (`Entity` or `LocalEntity`). A prefab has no side of its own: in a function it loads as the match's, and `local Scene.Load(Menu)` or `local Scene.Switch(Menu)` loads it as this machine's. `local` before a load in a view or a local handler says what was already so; before one in match code, before a match scene, or before `Scene.Unload`, it's an error.
    - It's the caller's in the schedule, as a function's spawn is, and `prepare` still can't load a scene through one.
    - An operator and `Interpolate` are refused where the call is written, as for a `Send`.
  - Not part of it: `Snap` stays the system's, view's or handler's own to write.
  - In generated C the function is handed the world it records in, as one that takes a `World` is, and the scene its spawns join. One that does none of this generates the C it did.
- Operators and their precedence follow C#. Comments are `//` and `/* */`.
- Source files are UTF-8, and a byte order mark at the start is skipped. Names are ASCII: other characters only go in comments and text.

<a id="limits"></a>

### Limits

- 256 components and 1024 archetypes.
- A world's heap, which keeps its text, lists, maps, sets and grids, grows with memory (its offsets are 64 bits; it stops at 64 TiB), in blocks of 128 MiB at most: a text it keeps is one block. The scratch area, where code makes text and lists along the way, grows with memory on each thread, and so does the asset pack. On the web, WebAssembly's 4 GiB of memory holds them all. Running out of memory ends the program, saying what couldn't be had and how much memory the program and the system had, in its crash report too. Where the system has no memory for a moment (Windows growing its page file, another program about to let go), the engine first waits for it, up to ten seconds, so the program stutters rather than ends (decided 2026-11-06, the owner: "if instead of a crash we have a stutter i think thats more acceptable"; the ten seconds are Claude's pick, Provisional); on the web it doesn't wait, as a page's memory has a most it grows to. A list stops growing at 2,147,483,647 elements (its count is an `int`). (Decided 2026-10-30, the owner: "Full 64-bit handles"; until then the heap and the scratch area held 1 GiB each and the pack 512 MiB.)
- `Json.Read` has bounds of its own, past which it gives nothing and the program goes on: arrays and objects 32 deep, 64 MiB of text, and 128 MiB of what one read makes (see JSON).
- Everything else grows as it needs, with no limit but memory: entities, entities per archetype, and structural changes and events per tick.

<a id="namespaces-1"></a>

### Namespaces

- `namespace Game.Combat;` at the top of a file puts everything in the file in that namespace. A file has at most one such line; files without one are in the global namespace. Namespaces can be dotted.
- `namespace Combat { ... }` puts the declarations between its braces in that namespace (agreed 2026-10-07, to separate concerns within one file; the rules under it are Provisional). It goes wherever a declaration does, so a file can have several, and one inside another.
  - A block's name is inside the namespace it's written in: in a file of `namespace Game;`, `namespace Combat { }` is `Game.Combat`, and a block inside it named `Rules` is `Game.Combat.Rules`. A block's name can be dotted too.
  - A namespace is a set of names, not a place: the same one can be a block twice in a file, a block in several files, and a file's own namespace in another. What any of them declares is one namespace's.
  - What's inside a block is declared as anywhere: its order among the file's declarations is where it's written, so a block changes no system's order.
  - Provisional: namespace imports (`using Physics;`) stay at the top of the file, and are every block's of the file. A namespace import inside a block is an error. Type aliases (`using Name = Type;`) are namespace declarations and can go inside a block (see Type aliases).
  - Provisional: the line form comes before any declaration, a block being one: a file says its own namespace first, and blocks after it are inside that.
  - Provisional: a block takes no attributes, `local`, `virtual` or `override`: they go before the declarations inside it.
  - Provisional: a qualified name is still exact, from the global namespace: inside `Combat`, the block `Rules`' function is `Combat.Rules.Cap`, not `Rules.Cap`. (C# also reads a qualified name's first part from the namespaces around the code. Not built.)
  - Provisional: a package's blocks are in its namespace or one inside it, as its files are: a package file with no namespace line can have everything in `namespace Package { ... }`.
  - Where a file is half typed, editors and the errors after a first one tell where a block's declarations start by their column: the first line's after the `{`, which the formatter makes one step in from the block's `namespace`.
- `using Physics;` at the top of a file lets it name Physics' declarations without the prefix. `namespace Name;` and namespace imports come before any declaration.
- A plain name is looked up in the namespace of the code that writes it (its block's, or its file's), then the namespaces around it out to the global namespace, then the `using` namespaces, as in C# (agreed 2026-10-05). So what a game declares itself is what its code means, whatever a namespace it imports also has by that name: a game with a `Body` of its own that says `using Physics;` means its own by `Body`, and writes `Physics.Body` for the other. If two `using` namespaces both have a name and nothing nearer does, it's ambiguous: write the namespace.
- Inside a namespace its own names win (the owner, 2026-10-30, from a game whose global names broke a package's code). In a namespace other than the global one, a declaration hides the same name further out wherever it's used as the same thing: a type (with prefabs and scenes) hides types, a system systems, and a value (a function, a constant, an asset, a frag or vert) values; a call is also an enum's conversion, so an enum hides a function of its name from a call. Inside `namespace Combat`, `Side(i)` converts to Combat's enum `Side` though the game has a global function `Side`. A command, a component or an event of a name hides no function of it.
- The global namespace has a name only as the kind of declaration it's used as there, so a game's own global code still finds a function by its call past a command handler of its name, and a frag past a function of its name, in a `using` namespace.
- In a package's code, the game's global declarations come after the package's `using` namespaces (the engine's own stay before them): nothing a game declares hides a package's names, or another package's, from a package's code. Where nothing else has the name, the game's is still found, as for a game's function a package's frag is handed as a `Func`.
- Qualified names work wherever a type is named: parameters (`mut Combat.Health health`), `with` and `without`, component values (`Combat.Health { value = 10 }`), `Spawn`, `Add` and `Remove`.
- The same name can be declared in different namespaces. Built-in names can't start a namespace (`namespace Math;` is an error).
- In generated C, namespaced declarations are prefixed with their namespace: `Combat.Health` is `Combat_Health`, read with `tide_get_Combat_Health`. Type aliases use their canonical underlying type.
- There can be at most one `scene Main` in a game, in any file or namespace; it is required only without an explicit startup selection. `namespace` and `using` are only keywords where a declaration can start: anywhere else they're names like any other.

```csharp
// combat.tide
namespace Combat;

component Health { int value = 100; }

// main.tide
using Combat;

scene Main { }

event(Spawned) Setup(with Main)
{
    Spawn(Health, Items.Health { value = 3 });
}
```

```csharp
// One file, two namespaces, and the global one around them
namespace Combat
{
    component Health { int value = 100; }

    namespace Rules
    {
        int Cap(int value) { return Math.Min(value, 100); }
    }

    system Heal(mut Health health)
    {
        health.value = Combat.Rules.Cap(health.value + 1);
    }
}

namespace Items
{
    component Bag { int coins; }
}

scene Main { }

event(Spawned) Setup(with Main)
{
    Spawn(Combat.Health, Items.Bag);
}
```

<a id="order-of-systems-1"></a>

### Order of systems

- Files compile in order of their paths, compared byte by byte. Systems run in that order, then in the order they're declared within a file. Views, which draw once per frame, follow the same rules among themselves; later views draw on top.
- `[Before(X)]` makes a system run before `X`, and `[After(X)]` after it. They take any number of systems (`[After(Gravity, Collisions)]`), with qualified names when needed (`[After(Physics.Gravity)]`).
- Where several systems share a name, it's written with the parameters of the one meant, as types: `[After(Move(Position, Velocity, with Player))]`. A shared name alone is an error that lists them (see Default values, named arguments and overloads).
- An enum can define named phases: `[Stage(TickStages.Simulation)]` assigns a declaration to a phase, and `[Stage(TickStages.Simulation, 10)]` gives it an offset within that phase. The offset is an `int` known while compiling, like an enum value: an integer literal, an integer constant, or integer operations on them. It defaults to 0 and can be negative. Each declaration has at most one `Stage`.
- Phases follow the enum members' declaration order, regardless of their numeric values. Lower offsets run before higher ones within a phase; offsets never move work into another phase. Equal offsets keep the default order unless declaration constraints change it.
- `Before` and `After` can name enum members too, mixed with declaration names: `[After(TickStages.Simulation, Gravity)]`. A phase reference means before all of that phase or after all of it, including every offset. Empty phases keep their place in the order. Different enums define independent phase orders; explicit declaration constraints can connect them.
- Named phases apply independently to systems, views, and the handlers of each event. Systems in a later phase wait for all earlier-phase systems, even if they share no data. Systems at the same offset can still run together when their data allows it. Declarations with no phase keep the default order wherever their constraints allow.
- Otherwise the default order holds: of the systems whose constraints are met, the earliest in the default order runs next.
- Constraints that form a loop are an error naming the loop. Systems and views are ordered separately, and `Main` isn't ordered: it runs once, before everything.
- The language server shows a system's place in the order when hovering it.
- Systems that share no data they write can run at the same time; the others wait, in this order. Above each system, the language server shows its stage, what it reaches through its `World` and why it waits ("stage 2 · World: reads Health", "after Move: both write Body", each wait a link to its system), and `tidec --schedule` prints the whole plan.

```csharp
[After(Physics.Gravity)]
system Move(mut Body body) { ... }
```

```csharp
enum RenderStages { Prepare, Objects, Effects, UI }

[Stage(RenderStages.Prepare)]
view ClearScene() { Draw.Clear(Color.black); }

[Stage(RenderStages.Objects, -10)]
view Background() { ... }

[Stage(RenderStages.Objects)]
view Objects(Body body) { ... }

[After(RenderStages.Objects), Before(RenderStages.UI)]
view Effects() { ... }
```

<a id="vector-math"></a>

## Vector math

Follows Unity.Mathematics, with Tide's naming. Everything in this section is decided.

- Types: `double2x2`, `double3x3`, `double4x4`, `double2`, `double3`, `double4`, `float2`, `float3`, `float4`, `int2`, `int3`, `int4`, `quaternion`, `float2x2`, `float3x3` and `float4x4`. They're lowercase built-in value types, like `float`.
- Math functions live on `Math` and follow the PascalCase method convention: `Math.Dot(a, b)`, `Math.Normalize(v)`, `Math.Mul(q, r)`. This overrides Unity.Mathematics' lowercase `math.dot`.
- Swizzles read any combination of components: `v.xz`, `v.zyx`, `v.xxyy`.
- Angles are in radians. A decimal degree literal (`180deg`) converts to an ordinary float in radians at compile time. `Math.Radians(degrees)` and `Math.Degrees(radians)` convert values.
- Math is forgiving with bad values, which can come from other players' input. `Math.Clamp` always returns a value in range: NaN gives the lower bound. `Math.Min` and `Math.Max` with one NaN argument return the other. `Math.Normalize` never gives NaN for a vector with no direction (next). Everywhere else, results match Unity.Mathematics.
- `Math.Normalize` gives zero for a vector too short to normalize, and the identity for a quaternion too short, where dividing by the length would give NaN. There's one `Normalize`, and it's the safe one: Unity.Mathematics splits it into `normalize` and `normalizesafe`, and here Tide's own rules win. NaN in the match is a determinism hazard (its bit patterns aren't portable), and normalizing a move that's zero while no key is held is the first thing every game writes.
  - Too short is a length squared at or under the smallest normal float (about 1.18e-38): a length of about 1e-19 or less, zero included. A vector with NaN in it gives zero too. Any longer vector gives exactly `v * (1 / Sqrt(Dot(v, v)))`, as it always did; that's zero for one so long its length squared overflows (past about 1.8e19), and still NaN in an infinite component (zero times infinity).
  - So vectors shorter than about 1e-19 give zero, where they gave a unit vector while `Normalize` wasn't safe.
  - It gives zero wherever it runs: in the match, in views, and in code compiled for the GPU, whose shader languages leave their own `normalize` of a zero vector undefined, so Tide's `Normalize` there is never just theirs.
  - `Math.NormalizeSafe` is gone: writing it is an error that points to `Math.Normalize`.

```csharp
quaternion spin = quaternion.AxisAngle(float3(0, 1, 0), input.turn * time.dt);
trs.rotation = Math.Mul(trs.rotation, spin);
float3 forward = Math.Rotate(trs.rotation, float3(0, 0, 1));
trs.localPosition += Math.Normalize(forward) * 5 * time.dt;
float2 flat = trs.localPosition.xz;
```

**Constructors**

- Vectors take any mix of scalars and vectors adding up to the right size (`float4(v.xy, 0, 1)`), or one scalar for every component (`float3(1)`).
- `float3(int3)` and `int3(float3)` convert between int and float vectors. `int(x)` and `float(x)` convert scalars. Float to int truncates toward zero, saturates at the int range, and turns NaN into 0, so no input is undefined.
- `quaternion(x, y, z, w)`, `quaternion(float4)` and `quaternion(float3x3)`.
- Matrices take one column vector per column (`float3x3(c0, c1, c2)`) or all numbers row by row (`float2x2(1, 2, 3, 4)`, where `1, 2` is the first row). Also `float3x3(quaternion)` and `float4x4(float3x3 rotation, float3 translation)`.

**Members and constants**

- Vectors have `x`, `y`, `z`, `w`. Swizzles can also be assigned (`v.xz = float2(1, 2)`), as long as no component repeats.
- `quaternion` has `value`, a `float4` with (x, y, z) as the vector part. Matrices are stored column by column and have columns `c0` to `c3`.
- `Math.PI`, `Math.TAU`, `Math.E`, `quaternion.identity`, `float2x2.identity`, `float3x3.identity`, `float4x4.identity`.
- `quaternion.AxisAngle(axis, angle)`, `quaternion.Euler(radians)` from a `float3` or `quaternion.Euler(x, y, z)` from three angles in radians (equivalent to `quaternion.Euler(float3(x, y, z))`; Z first, then X, then Y, Unity's default order), `float4x4.TRS(translation, rotation, scale)`, `float4x4.Translate(translation)`.
- `quaternion.LookRotation(float3 forward, float3 up)` gives the unit rotation taking +z to normalized `forward` and +y to the unit vector in the plane of `up` and `forward` that is perpendicular to `forward` on `up`'s side. Neither argument need be unit length; finite nonzero vectors across the float range are accepted. A zero or nonfinite `forward` gives identity. When normalized `up` crossed with normalized `forward` is shorter than 1e-5 (Unity's `Vector3.kEpsilon`), including a zero or nonfinite `up` and one along `forward` either way, the result is `quaternion.FromToRotation(float3(0, 0, 1), forward)`, as Unity's `Quaternion.LookRotation` falls back. This is decided behavior (2026-10-22).
- `quaternion.FromToRotation(float3 from, float3 to)` gives the shortest rotation between directions without requiring unit lengths. Finite nonzero directions across the float range are accepted; a zero or nonfinite direction gives identity. Exact opposite directions cross normalized `from` with its least-aligned cardinal axis and normalize the result, with X, Y, Z as the tie order. This is decided behavior (2026-10-18).
- `float4x4.Scale(float3 scale)` builds a diagonal scale matrix, with no rotation or translation; zero and negative scales are valid. This is decided behavior (2026-10-18).
- Projections, as Unity.Mathematics': `float4x4.PerspectiveFov(verticalFov, aspect, near, far)`, with the field of view in radians and `aspect` width over height, and `float4x4.Ortho(width, height, near, far)`. They take a view looking down -z, as OpenGL's and Unity's, to clip space, where z goes from -1 at `near` to 1 at `far`.

**Operators**

- `+ - * /` are component-wise on vectors, and `%` too on int vectors. A scalar widens to the vector's size, and int widens to float, so `v * 2 + 1` works.
- An int vector converts to a float vector of the same size implicitly, like `int` to `float`.
- Matrices support `+` and `-` with the same type, and `*` and `/` by a number. There's no `*` between matrices, or between a matrix and a vector; that's `Math.Mul`.
- Quaternions have no operators: combine rotations with `Math.Mul` and rotate vectors with `Math.Rotate`.
- `<`, `<=`, `>` and `>=` work on scalars only. `==` and `!=` work on scalars, and on two vectors or two colors whole (Provisional, below).

**Functions**

- Component-wise, on numbers, vectors and colors: `Abs`, `Sign`, `Min`, `Max`, `Clamp` (ints too); `Floor`, `Ceil`, `Round` (ties to even), `Trunc`, `Frac`, `Sqrt`, `Rsqrt`, `Saturate`, `Radians`, `Degrees`, `Sin`, `Cos`, `Tan`, `Asin`, `Acos`, `Atan`, `Atan2`, `Exp`, `Exp2`, `Log`, `Log2`, `Log10`, `Pow`, `Step`, `Lerp`, `Unlerp`, `SmoothStep`. A `Color` goes through them channel by channel, alpha too, with colors and with numbers (a number is that number in every channel), and gives a `Color`: `Math.Lerp(a, b, 0.5)`. A color and a vector in one call are an error. (That colors are taken is agreed, 2026-10-08: "Color is essentially a float4 anyways"; that it's every component-wise function, and that vectors don't mix in, are Provisional.)
- **Provisional (2026-11-14):** `Math.ToLinear` and `Math.ToDisplay` take `float`, `float3` or `Color`, converting between sRGB display-encoded RGB and linear light using the standard piecewise transfer curve (decode threshold 0.04045, encode threshold 0.0031308). RGB clamps to [0,1], NaN maps to zero; Color alpha is unchanged, including alpha outside [0,1]. CPU uses Tide's deterministic `Pow`; GPU follows the same formula with the GPU rounding tolerance of the other Math functions. Both ends are exact on the CPU and the GPU: 0 gives 0 and 1 (and anything above) gives exactly 1 from either function, so white is white through both. No double or float2/float4 overload is supplied: use float3 for RGB or Color to carry alpha.

- Vectors: `Dot`, `Cross`, `Length`, `LengthSq`, `Distance`, `DistanceSq`, `Normalize` (zero for a vector too short to normalize, never NaN), `Reflect`, `Csum`, `Cmin`, `Cmax`.
- Quaternions: `Mul` (two rotations, or a rotation and a `float3`, which it rotates), `Rotate`, `Inverse`, `Conjugate`, `Normalize` (the identity for a quaternion too short to normalize, like a field nothing set), `Dot`, `Slerp`, `Nlerp`, `Forward`, `Up`, `Right`, `Angle`.
- Matrices: `Mul` (two matrices, or a matrix and a vector of its size), `Transpose`, `Inverse`, `Determinant`, and for `float4x4`, `Transform` (a point) and `Rotate` (a direction).
- Everything is deterministic (see AGENTS.md). The transcendental functions are Tide's own, accurate to about 1 ulp but not correctly rounded.
- `Math.Hash(value)` on an `int`, `long`, `int2`, `int3`, `int4`, `float`, `float2`, `float3` or `float4` gives random numbers that keep no state: the same int for the same value on every machine, like `Math.Hash(int3(x, y, seed)) % 6`. Code the GPU runs gets the same numbers (GPU code, under Views and drawing).
- **Bit reinterpretation (conventional completion, 2026-10-20).** `Math.AsInt` maps float/float2/float3/float4 to their int equivalents without numeric conversion; `Math.AsFloat` is the inverse for int/int2/int3/int4. Each component preserves its 32 bits. Float/vector `Math.Hash` is exactly the existing integer hash of `Math.AsInt(value)`, so signed zeros differ. These operations work in CPU and GPU code; existing float arithmetic/determinism rules remain unchanged. Private CPU aggregate borrowing preserves ordinary value semantics and adds no source-level alias or reference behavior.
- Noise: `Math.Perlin(point[, seed])`, `Math.Simplex(point[, seed])` and `Math.Cellular(point[, seed])`, of a `float2` or a `float3`, which keep no state and give the same bits on every machine, so noise can be in the match. The owner asked for noise functions in `Math` that work on the GPU too (2026-10-07); which functions, their names and the rules below are picks.

<a id="provisional"></a>

### Provisional

Implemented, awaiting approval:

- Noise (2026-10-07; `engine/src/noise.c`, and the same lines in WGSL in `compiler/src/shader.c`):
  - Three kinds, in 2D and 3D: `Perlin` (gradient noise, Perlin's improved: a quintic fade, 8 unit gradients in 2D and the 12 edge directions of a cube in 3D), `Simplex` (Gustavson's, with the same gradients) and `Cellular` (Worley's: one feature point in each unit cell, placed by the cell's hash, and the distances to the nearest and the second nearest, Euclidean). Named by their kinds (Unity's are `noise.cnoise`, `snoise` and `cellular`), as explicit beats a plain `Noise` that would mean one of them. No 1D, no 4D, no periodic noise, no `float2` of derivatives, and no fractal sum: octaves are a line of the game's.
  - Each gradient or feature point is `Math.Hash` of the cell and the seed (`int3` in 2D, `int4` in 3D), never a permutation table: nothing repeats, the same cell is the same everywhere, and the GPU gets exactly the cells the CPU does. What's between them is floats, with the GPU's rounding.
  - A seed is an `int` a call can leave out, 0 then: `Math.Perlin(p)` is `Math.Perlin(p, 0)`. Another seed is another field of noise.
  - `Perlin` is from -1 to 1 exactly (its gradients keep it within `sqrt(n / 4)`, which the scale takes to 1; a GPU's rounding may go a millionth past), and 0 at every whole number. `Simplex` is scaled (99.2 in 2D, 32.5 in 3D) so that the greatest value found by a search is a hair under 1: about -1 to 1. `Cellular` is `float2(nearest, second)`, from 0 to about 1.4 in 2D and 1.3 in 3D, Unity's shape (`noise.cellular` gives F1 and F2 too).
  - The cell is the point's floor, as an int saturated past what an int holds, so a point past 2^31 is in the last cell, with no error. A NaN point gives NaN.
  - `tide_perlin_f2(p, seed)` and the five beside it in `tide/math.h` are C's.
- A value on its way to another, and angles (2026-11-14; every prototype had written its own, so these are conventional completions after Unity's `Mathf`, in radians):
  - `Math.MoveTowards(current, target, step)`, of floats and of `float2` and `float3` points: `current` at most `step` closer to `target`, never past it; a point moves along the straight line. A `step`, or a `current`, that isn't a number gives `target`; a step under 0 moves away, as Unity's.
  - `Math.Damp(current, target, rate, dt)`, of the same three: `current + (target - current) * Saturate(1 - Exp(-rate * dt))`, the frame-rate independent form of `Lerp(a, b, dt * rate)`. A `rate * dt` under 0, or that isn't a number, leaves `current`. No quaternion or Color form.
  - `Math.DeltaAngle(from, to)`: the shortest turn, over -PI and up to PI; an angle that isn't a number or is infinite gives 0. `Math.WrapAngle(angle)` is `DeltaAngle(0, angle)`. `Math.MoveTowardsAngle(current, target, step)` is `MoveTowards(current, current + DeltaAngle(current, target), step)`, which isn't wrapped.
  - All are IEEE basic operations and Tide's `Exp`, so they're in the match, and the same arithmetic on the GPU.
- `Math.Hash` gives an int from 0 to 2147483647, so `%` never goes negative. It's xxHash32 of the value's bytes (little-endian, seed 0) without the top bit: what Unity's `math.hash` gives for a block of memory. Unity's `math.hash` on vectors is a cheaper mix whose low bits follow the input's, so `& 3` of it makes stripes; Tide's differs from it on purpose.
- **`==` and `!=` on vectors** (2026-11-14; the owner approved the recommendation that day, "go with your recommendations"; every rule below is a pick):
  - Two vectors of one size (`int`, `float` or `double`, 2 to 4 components) compare whole and give one `bool`: `a == b` is true when every component is equal, `a != b` when any differs. This deliberately differs from Unity.Mathematics, whose vector `==` gives a vector of bools (`bool3`): a condition needs one answer, and games wrote `Same(int2, int2)` helpers and `a.x == b.x && a.y == b.y` for it.
  - Each component compares as C and IEEE compare floats: `-0` equals `0`, and a NaN equals nothing, itself included, so `v != v` is true for a vector with a NaN in it.
  - An int vector beside a float vector compares as a float vector, and either beside a double vector as a double vector, as `+` and `-` widen them.
  - Two `Color`s compare the same way, every channel and alpha. A quaternion has no `==` (an error that names `a.value == b.value` for its four numbers, and `Math.Abs(Math.Dot(a, b))` near 1 for the same rotation, as `q` and `-q` are one), nor does a matrix (compare columns) or a `Rect` (compare its `position` and `size`). A vector beside a number is an error that says to write the vector (`v == float3(0)`); vectors of two sizes are an error. `<`, `<=`, `>` and `>=` on vectors and colors stay errors, which name a component's or a length's comparison.
  - A list's `Contains`, `IndexOf` and `Remove` take vector and color elements, compared the same way.
  - It works wherever a scalar's `==` does: in constants and field defaults (as a value C works out, not one tidec folds for a `case` label or a setting), in frags and verts (WGSL's `all(a == b)` and `any(a != b)`), and in loop guards, where the index analysis takes `cell == target` for an equality on each component.

<a id="random-numbers"></a>

## Random numbers

The owner asked for these on 2026-10-05: random numbers whose state is ECS data ("we likely want it to be a component") and a seed for the match that's "random every time and new joiners get". On 2026-10-08 the owner found that inconvenient ("i need to either make my own singleton or hack together something local with the struct"), and that `Time.seed` "has nothing to do with time". Of a built-in singleton like `Time`, and of calls on the type that keep no state, the owner picked the calls.

<a id="decided-1"></a>

### Decided

- **`Random` rolls with no generator of the game's**: `Random.NextInt(6)`, `Random.NextFloat2Direction()` and the rest, called on the type, in a system with no parameter for it.
- **Rolling writes nothing**, so it costs the schedule nothing: a system that rolls waits for no other system over it, and still splits its entities across threads. A singleton that every rolling system would write was turned down for that.

<a id="provisional-1"></a>

### Provisional

Implemented, awaiting approval:

- **What a roll on the type is made from.** Each run of the match's code that rolls (a system for an entity, a system that runs once, a handler's run) has a generator of its own, a local of that run: made from the match's seed, the tick, the entity it runs for (none for code that runs once) and which system or handler it is, by its name. Its rolls step that generator, in the order they run. So a run's rolls are a sequence, two systems roll differently for one entity in one tick, each entity rolls for itself, a tick later it's all other numbers, and a tick run again rolls the same.
  - A handler's generator also takes the complete causal identity of its event, so repeated sends at one site roll differently while an absent hidden handler does not advance a public handler's generator. Queued handlers retain deterministic source order.
  - A system's rolls start over each tick. A sequence that goes on across ticks, or from a seed the game picks, is a `Random` value (below).
  - Adding a roll to a system changes its later rolls in that run, and nobody else's. Renaming a system changes its rolls.
- **The methods are the value's**, by the same names, with the same ranges.
- **Functions, methods and operators roll too**, with nothing passed: one that rolls, itself or through what it calls, is handed its caller's generator.
- **Local code** (views, local handlers, and the functions they call) rolls with a generator of this machine's local state, one for all of it, which is no part of the match. It takes in each frame's length as the host gives it, so no two runs with a window roll alike, and a run with no window, whose frames are made up, repeats.
- **It rolls wherever a roll can mean something** (the owner, 2026-10-08, of a first version that refused several of these: "if it could we should do the extra work to get it usable there"). How each is built is a pick:
  - **A parallel loop's steps**, and a foreach over a grid whose steps run at once: the code around the loop gives the loop a generator (two rolls of its own), and each step makes its own from that and its place, a grid's cell (a block's first) or a list's index. So a loop's numbers don't depend on threads, and a step's rolls are a sequence within the step.
  - **A sort's comparison** steps the generator of the code around it, in the order the sort compares, which is the same on every machine.
  - **A task** keeps a generator in its frame, so its rolls go on across its waits, and are the world's as the task is. It's made where the task starts, from the generator of the code that starts it; a task it awaits gets one from its own the same way; and a handler that's a task gets one as a handler does, from the tick, its entity and its turn.
  - **The input's `Sample`** rolls with this machine's generator, as local code does. A host that gives `tide_input_sample` no local state gets a generator of the program's.
  - **An `audio` declaration** keeps a generator after its own state, on the next 8 bytes of what its voice keeps for it (so its own state is 8 bytes less at the most), seeded the first time the voice runs by how many voices rolled before it. One thread renders, so a run with no window repeats.
  - **Frags and verts, on the GPU**, and the functions, methods and operators they call. These GPUs have no 64-bit integers, so it isn't the CPU's generator there:
    - **A generator each time the code runs**: a frag's for each pixel, a vert's for each vertex, made as it starts and gone when it ends. Its rolls step it in the order they run, statement by statement. Two rolls in one expression come in whichever order that GPU works the expression out, as its shader language leaves that open: where the order matters, a roll gets a statement of its own. (Each of `Random`'s own vectors is rolled x first everywhere.) A `?:` with a roll in it works both of its sides out, whichever it picks, on every GPU, so both rolls are made: WGSL has no other way to pick, and a pixel's rolls stay the same numbers everywhere.
    - **What it's made from**: for a frag, the pixel's place in the destination's own pixels (the window's or a render target's, from the top left, whatever the display's scale) and which instance of its draw the pixel is of; for a vert, which vertex of the mesh and which instance; and for both, a number of the frame's and which frag or vert is rolling, by its name. So no two pixels of a frame roll alike, two frags that draw over one pixel roll apart, and a function rolls with the generator of whichever stage runs it.
    - **The frame's number is one roll of this machine's local generator**, taken as the frame starts, before its views, and sent with every draw through a shader that rolls, among its uniforms. It's the same for every draw of a frame, so draws that roll still join into one draw call. So GPU rolls are other numbers every frame, the same every run where frames are made up (a run with no window) and no two runs alike with a window, as local code's rolls are. What has to hold still from frame to frame is `Math.Hash` and the noise functions.
    - **An instance is its place in its draw.** Instances of one draw roll apart. Two draws that don't join each start at their first instance, so where they cover one pixel through one frag, they roll the same there.
    - **Not the CPU's numbers.** These GPUs have no 64-bit integers, so the generator there has 32 bits of state: a linear congruential step and PCG's RXS-M-XS output. What's made of its 32 bits is the CPU's formulas: ints scaled down by multiply and shift (the high half of the product worked out in halves), floats 24 bits over 2^24, ranges that exclude their end, an empty range giving its start. The generator and the whole-number rolls are integer arithmetic, so a pixel rolls the same on every GPU for the same frame's number; what goes through sines, cosines and square roots is that GPU's rounding.
    - **Every method the type has.**
    - **`Random.seed` is read there too**: the seed of the match the frame draws, 0 with none, sent with the draw as another of its uniforms. So a frag draws noise from the match's seed, as the match computed it.
    - **A `Random` value stays the CPU's**: a field, a local or a parameter of that type, its methods and `Random(seed)` are errors in code the GPU runs, which say to roll on the type. Its state is 64 bits.
    - **A Sample that's `Filter.Trilinear` can't read at a place made of a roll**: the frag works that place out a first time as it starts, to ask how fast it changes, and a roll made twice is two numbers. An error that says to sample with `Filter.Bilinear`.
    - **A frag that rolls carries one more value from the mesh's corners** (which instance), of the 15 a draw has.
- **Where it never rolls**, each an error that says why: the input's `Sanitize` (the same repair on every machine, from the input alone), a type's `Interpolate` (the engine calls it itself, to blend the same two values the same way every frame), and constants and defaults, an operator in one included (no code runs).
- **`Random.seed`** is the match's seed, where it was `Time.seed`, which is an error that names it, with the rename as a quick fix. It's read with no parameter wherever code rolls, but in an `audio` declaration, whose thread has no match. A frag or a vert reads the seed of the match its frame draws, 0 with none, which its draw sends with it (above). The match's code reads its world's; local code (views, local handlers, local tasks, `Sample`) reads what its local state kept of the match the last frame drew, 0 with none; a function or method is handed it.
- **`Random` is also a built-in value, a struct with one field, `long state`.** It's a generator's whole state: 8 bytes, aligned to 8. It goes wherever a struct goes: a field of a component, a singleton, a struct, an event or local state, a local, a parameter, a list's element.
- **A value, not a built-in component.** A component's state can only be an entity's, and a game also needs a generator for the match (in a singleton) and for effects (in local state), so the value has to exist either way; a built-in component would be one more name for one of its homes. With the value, a game's own component is that home, and it says which systems share a sequence: `component Wanderer { Random random; }` and `system Wander(mut Wanderer wanderer)`. The built-in component would read `Spawn(Enemy { }, Random { })` and `system Wander(mut Random random, mut Body body)`, and every system that rolls for an entity would then write the same component, so none of them would run side by side.
- **Methods**, following Unity.Mathematics' `Random` with Tide's naming: `NextInt()`, `NextInt(max)`, `NextInt(min, max)`, `NextFloat()`, `NextFloat(max)`, `NextFloat(min, max)`, `NextBool()`, `NextFloat2()`, `NextFloat2(min, max)`, `NextFloat3()`, `NextFloat3(min, max)`, `NextFloat2Direction()`, `NextFloat3Direction()` and `NextQuaternionRotation()`. Ranges include their start and exclude their end.
  - Where Tide's differ from Unity's: `NextInt()` is from 0 to 2147483647, as `Math.Hash` is, where Unity's can be negative; a range with nothing in it gives its start (`NextInt(0)` is 0, `NextFloat(2, 1)` is 2); `NextFloat(min, max)` never gives `max`, where Unity's can by rounding; and any state works, where Unity's refuses 0.
  - Each call steps the generator once for each number it gives, whatever its arguments.
- **Each method changes the generator**, so it's called on one the code can change, by the rules of a struct's `mut` methods: a `mut` parameter's field, a `mut var`, a field of `this` in a `mut` method. Through a read-only parameter it's an error that offers `mut`. A list's element is a copy: take it out, roll, put it back. So a system that rolls says `mut` for the component or singleton the generator is in, and the schedule follows from that as for any write: no new rule. A roll is a call that writes, so it keeps its turn in an expression (see Evaluation order): in `float2(random.NextFloat(), random.NextFloat())`, x is rolled first.
- **`Random(seed)`** makes a generator for a seed, an `int` or a `long`. It's a constant expression when its seed is, so it's a field's default: `Random fixed = Random(42);`. Seeds are mixed, so neighbours (1, 2, 3) give unrelated sequences, and no seed gives state 0. `Random { state = n }` sets the state as it is.
- **The generator** is PCG32 (PCG-XSH-RR 64/32), which gives the 32 bits of the state it stepped to. Ints in a range are those 32 bits scaled down (multiply and shift), floats 24 bits of them over 2^24, and the directions go through `Math.Sin` and `Math.Cos`. Everything is integer arithmetic or exact float operations, so it's the same on every platform (`tide/random.h`).
- **A state of 0 is a generator nothing seeded.** It rolls like any other, but the same numbers as every other one at 0.
- **The engine seeds what the game left at 0**, in components and singletons, where they're fields or in a struct that's a field (not in lists, maps or grids):
  - A component's, as its entity spawns, and as the component is added: from the match's seed, the tick, the entity's handle and which field it is. The seeding happens as the spawn or the add applies, at the end of the tick, when a handle a split system gave is final. So a tick run again after a rollback seeds the same, twins spawned in one tick differ, and a component added twice rolls differently each time.
  - A match singleton's, as the match starts, from the match's seed and which field it is. Its ordinal counts match singletons only: adding or moving local singletons or attached local fields does not change its sequence.
  - In the local world there's no seed: a local component's is seeded from its entity's handle, a local singleton's from which field it is, and a `local Random` field of a match component from the match entity's handle. They're the same every run.
  - A generator code sets to 0 later isn't seeded again.
- **The match's seed** (`Random.seed`) is an `int` from 0 to 2147483647. The server picks it as it starts a match, from the system's random number generator, which its host gives it (`tide_session_desc.entropy`; the standard host passes `tide_platform_entropy`, but in a run with no window: `--capture`, `--frames`, `--script`). `--seed <n>` on the standard host's command line (`tide run --seed 7`) picks the seed instead, from 0 to 2147483647: every match that machine starts in the run has it (`tide_session_desc.seed`), with a window or without, on every platform. The owner asked for the flag on 2026-10-05; that it's every match of the run, and for runs with a window too, is how it was built. It's kept in the world: a joiner gets it with the world, snapshots, the hash, host migration and hot reload carry it, and clients never send it. A player who starts the match itself to have something to build the server's world from (`tide_game.pure_start`) is told the seed with how the match started. Where no host gives entropy (`tide_world_init`, tests, benchmarks, the standard host's runs with no window) it's 0, so a run repeats exactly.
- **A game that uses none of it is what it was.** The world only has the seed in a game that reads it, rolls with `Random` in the match's code, or has a `Random` in the match's components or singletons, and only such a game's header has `tide_world_start_seeded(w, dt, start, seed)` and includes `tide/random.h`. Other games' worlds, hashes, headers and traffic don't change. A game that only rolls in local state has no seed in its match either.
- **Hot reload**: a `Random` field is a struct with a `long`, so its state carries over by name like any field. One a reload adds starts at 0 on the entities that are there already, like any new field at its default: they roll alike until they're spawned again.
- **Every player can read Time.seed:** this match singleton remains public even when scenes or entities are hidden (see State visibility). A secret seed belongs in restricted scene or component state.

<a id="open"></a>

### Open

- **Precise GPU depth reads:** a raw or precise linear-depth read remains open. Existing forward depth reads do not preserve the extra far precision of reversed float storage (2026-11-14).

- Whether the engine should also offer the built-in component the owner leaned to, beside the value (`mut Random random` in a system, for games that want one sequence an entity).
- On the GPU: a way to hold a frag's rolls still across frames (today that's `Math.Hash` of `this.position`); rolls in one expression in a set order in every shader language Tide translates to (Unity's HLSL leaves it open), which would take hoisting them into statements as the CPU's code does; a per-draw number, so two draws that don't join roll apart where they overlap, at the cost of joining; and a `Random` value there, which would need a 32-bit generator of its own type.
- Whether local code's rolls should repeat in a run with a window too, on request.
- A seed the game picks for a match, like a world's seed a player types: `Session.Start(scene, seed)`. Today the game keeps it in a field of its own and seeds its generators with `Random(seed)`.
- What seeds a generator a hot reload adds to entities that exist.
- Vectors of ints (`NextInt2`...), a `long`, and picking from a list or shuffling one.

<a id="constants"></a>

## Constants

<a id="decided-2"></a>

### Decided

- `const` declares a constant at the top level of a file: `const int STARTING_LIVES = 3;`. The type is written out, as a field's is, and the value is a constant expression, by the rules of field defaults, which can name other constants.
- Constants are named in FULL_CASE, like `Math.PI`.
- A file's namespace is its constants' too: `Combat.CRIT_MULTIPLIER` from outside it, or `CRIT_MULTIPLIER` with `using Combat;`.
- Constants are part of the build, so every machine has the same values. Any code reads them (match code, local code, views and `Sample`), and reading one makes no system wait, as reading `Math.PI` doesn't.
- They go wherever a constant does: field defaults, the bounds of `[Clamp]`, `[Min]` and `[Max]`, settings, and other constants.
- Changing one under `tide run` reloads the game and keeps the match where it is: constants aren't part of its data layout.
- A game's own values are constants. `settings` only holds the engine's (see Settings).
- A constant can be computed by code that runs at build time (agreed and built 2026-11-03): see Build code.

```csharp
const int MAX_HEALTH = 100;
const float REGEN_PER_SECOND = MAX_HEALTH / 20.0;

component Health
{
    float value = MAX_HEALTH;
}

system Regenerate(mut Health health, Time time)
{
    health.value = Math.Min(health.value + REGEN_PER_SECOND * time.dt, MAX_HEALTH);
}
```

<a id="provisional-2"></a>

### Provisional

Implemented, awaiting approval:

- `const` is a keyword only at the start of a top-level declaration. One inside code, or inside a type, is an error that points to the top of the file; a local is read-only already.
- A constant is a number, vector, matrix, quaternion, `bool`, `Color`, `Rect`, `PlayerID`, text, struct or enum, or an array or a list of plain values (below): not a struct that holds a list, a map, a set or a grid, yet, and not an entity, which could only ever be the null one.
- **Array and list constants written out** (2026-11-14; the owner approved the recommendation that day, "go with your recommendations"; the rules below are picks): `const float[4] SIZES = [1.5, 2, 2.5, 4];` and `const List<int> QUAD = [0, 1, 2, 0, 2, 3];`.
  - What they hold is plain values: numbers, bools, chars, vectors, matrices, quaternions, colors, rects, enums, arrays and structs of those (no text, lists, maps, sets, grids, entities, resources or callables in them, each an error; text's names a switch expression on the index, a struct's names the field that holds it, and a resource's names assets and local fields). An array constant is any constant expression of its type: a literal of exactly its length, another array constant, `EnumType.Values()`. A list constant is a list literal of constants (`[]` too) or another list constant written out; any other expression is an error that names build code, which makes lists code works out (`const List<int> SQUARES = Squares(16);`, Build code), and naming a list constant build code made is the error another constant naming a built one gets. A list constant written out holds 4096 values at the most, all of its elements' lengths together, as an array does (`List<int[1024]>` of five is 5120), an error that names build code, which makes longer ones.
  - They're read where any constant is: match code, local code, views, handlers, functions, workers, field defaults, other constants, frags and verts. `T[i]` reads an element by an `int` (`SIZES[int(kind)]` by an enum's number), the element type's zero past either end, as arrays and lists do anywhere; `.count` is how many; `foreach` goes through them. A list constant is a `List<T>` wherever a list is read whole: an argument, `Contains`/`IndexOf`, `Draw.Mesh`'s lists, a field it's copied into, which then holds a list of its own in its world. Nothing can change one (`QUAD[0] = 1`, `QUAD.Add(4)`: the error constants give).
  - An element read by a constant index, and a count, are constants: `const int THIRD = QUAD[2];`, `case QUAD[5]:`, `int[QUAD.count] seen;`, a float setting (`maxRewind = WINDOWS[1];`). tidec works them out through the constants named, a constant that's `EnumType.Values()` (`case ALL[1]:`), an element of an element (`GRID[1][2]`), a `default` table's zeros, and a constant conditional or switch choosing the table. Indexing by an enum (`SIZES[kind]`) is an error whose note writes `SIZES[int(kind)]`. A character of text (`NAME[0]`) isn't a constant: a constant's value or a field's default that reads one is an error.
  - They're never world state: the build's values, the same on every machine, read like `Math.PI`, making no system wait.
  - In generated C an array constant is its value where it's read, as every constant is (`tide_arrayN_get(((tide_arrayN){{...}}), i)`, which C keeps as constant data in an optimized build). A list constant's element and count are read the same way, as an array of its values, so `QUAD[i]` makes no list; a whole read is its literal, a list made in the scratch area there. On the GPU both are `array<T, N>(...)` read through the arrays' bounds-checked `tide_el`; a list constant read whole (passed to a function) is an error that names `QUAD[i]`, `.count` and `foreach`, and an empty one is refused there.
- `case` labels and enum members' values can use int constants and operators on them (`case MAX_LEVEL + 1:`). The compiler works them out as they would be at run time: wrapping on overflow, and 0 for a division by zero.
- Constants can name each other in any order, across files, but not in a circle.
- A local, parameter or field in scope hides a constant of the same name, and a constant's name can't be another declaration's in its namespace.
- In generated C, a constant is its value, written wherever it's read: it has no C name, and nothing of it is in the header.

<a id="events"></a>

## Events

<a id="decided-3"></a>

### Decided

- An event is something that happened, sent from one part of the game to the rest: a hit, a pickup, a round ending. `event Hit { ... }` declares one, with fields like a struct's, which carry its context.
- `event(Hit hit) TakeHit(...)` declares a handler: code that runs when a `Hit` is sent. The same keyword declares both, and `event(` starts a handler. The first parentheses hold the trigger, exactly one event. The second list takes the same parameters as a system, including read-only queries in synchronous handlers (see Read-only entity queries).
- An event with no fields needs no name in the trigger: `event(Spawned) Arm(...)`.
- `entity.Send(Hit { ... })` sends an event to an entity. `Send(RoundOver { ... })` sends it to the whole world.
- A handler's components and `this` come from the entity the event was sent to, as a system's come from the entity it runs for. If that entity doesn't match the handler's parameters, the handler doesn't run for it.
- A handler that takes components needs that entity, so every `Send` of its event must name one. The compiler checks every `Send`: `Send(Hit { ... })` is an error when a `Hit` handler needs an entity, and says to write `entity.Send(...)`.
- A handler that takes no components runs once per event, whether it was sent to an entity or not, and has no `this`.
- The sender isn't recorded. When handlers need it, it goes in a field: the entity that sends is often not the one that matters, like a bomb sending a `Hit` for whoever threw it.
- Events are handled at the end of the tick, 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, as `Add` on a destroyed entity does nothing.
- 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 declaration order, and `[Before]` and `[After]` order them as they do systems.
- Handlers can't draw. Drawing happens every frame, in views.
- Events waiting to be handled are world state: a snapshot holds them, and re-simulating a tick sends and handles them again the same way.
- **Built-in events** are declared like any other, and cost nothing where no handler takes them:
  - `Spawned` and `Destroyed` are sent to an entity when it's spawned or destroyed. `Destroyed` handlers run while its components can still be read.
  - `PlayerJoined` and `PlayerLeft` are sent to the world when a player joins or leaves, with the player's `PlayerID` in `player`. The server picks the tick, so every machine handles them on the same one.
  - `Forgotten` is a local one: sent on this machine as an entity's local fields go, for local handlers to let go of what they hold (see Local state).

```csharp
event Hit
{
    Entity attacker;
    int damage;
}

system Explode(Bomb bomb)
{
    if (bomb.timer > 0) return;
    bomb.target.Send(Hit { attacker = bomb.owner, damage = 50 });
    this.Destroy();
}

// 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;
}

// Spawned has no fields, so it needs no name.
event(Spawned) Arm(with Player)
{
    Spawn(Weapon { owner = this });
}
```

- **Local handlers** hear the match's events on each machine, to show what happened: `local event(Hit hit) ShowHit(Body body, mut Fighter fighter, mut Fx fx)`. It's `local` and the same `event(...)`, with no keyword of its own.
  - It takes the event; the components of the entity the event was sent to, to read, where `mut` reaches only their local fields, as in a view; the match's singletons, to read; local singletons, which it changes; and queries, whose rows are the match as the tick that sent the event left it (see Read-only entity queries). One that takes no components runs once per event, as a match handler does.
  - It runs at the start of the frame, before the views, for each tick this machine simulated since the last frame, in order. It changes local state and can't draw, like every handler.
  - It sees what it takes of the match as the event's turn left it, even when the entity is gone by the frame: that's what makes `Destroyed` say where something ended. Only what handlers take is kept.
  - The engine's own events have them too: `Spawned`, `Destroyed`, `PlayerJoined` and `PlayerLeft`.
  - **Availability and lifetime are distinct** (agreed 2026-10-15). `local event(Shown)` initializes presentation when an entity or a handler's required components become available on this machine: an arrival, a reveal or a true spawn. `local event(Hidden)` handles loss of that availability using its last permitted state. They also have `verified` forms. `Spawned` and `Destroyed` describe genuine match lifetime; joining, revealing and state repair fabricate neither. A concealed entity's later destruction does not notify a recipient who could not see it then. This replaces the 2026-10-07 arrival-through-`Spawned` rule.
  - **Once, under rollback.** Each tick remembers the events it delivered locally. When a tick is run again, the same event (the same tick, event, entity and fields) stays silent; one only the corrected tick has is heard then, late; one the correction removed isn't taken back.
  - **Events only local code handles.** The match can send an event no match handler takes, purely for what's shown, like `Impact { float2 at; float2 normal; }`. It costs the match nothing: the world's bytes, hash, snapshots and what's sent are what they'd be without it, and a machine with nobody to show it to does no work for it.
  - **`verified`** before the event, `local event(verified Died died) ShowDeath(...)`, hears it once the server has confirmed the tick that sent it: late by the prediction's lead, never wrong, never taken back. What the handler takes of the match comes from that confirmed tick, as the event's turn left it, so nothing else is marked. A predicted handler and a verified one of the same event can both exist. See Views and drawing for `verified` in views.
  - **Ownership filters** (agreed 2026-10-19). `with ownership` and `without ownership` work in local handlers of match events, including verified handlers. They compare the entity's recorded `Owner.player` with this machine's `Session.player`, without requiring either parameter. Ownership is captured at the event's turn, after match handlers, before destruction; a later transfer or removal cannot redirect that event. `with ownership` requires a permitted Owner belonging to this player; `without ownership` is its complement, including entities with no permitted Owner. Other component filters retain their usual meaning. An ownership filter alone makes the handler entity-targeted and makes a local Spawned/Destroyed handler hear the match. Shown/Hidden compare ownership at their respective delivered availability endpoints, so gaining or losing ownership changes that handler's availability. Ordinary event replay retains occurrence deduplication; a correction changing only captured ownership does not repeat a predicted event, while verified delivery uses its confirmed recording. Local-world events, Forgotten and query filters don't accept ownership.
  - **Field changes** (agreed 2026-10-25): `local event(Changed<Health.value> change) Flash(...)` hears a field of the match that changed over a tick, with `change.old` and `change.value`, instead of a view keeping the last value to compare. Match handlers of a change were agreed 2026-11-16 (below): the owner asked for this over a separate event for edits made by dev tools, so what depends on a field follows it whoever set it.
  - **Recorded containers** (agreed 2026-10-19). Local handlers read the match's text, lists, maps, sets and grids with the same timing as other recorded fields: direct event/component/singleton parameters come from the event's turn, query rows from tick end, and verified delivery from the confirmed recording. Captured values remain valid after later writes or destruction. Match data is read-only; ordinary explicit copies into local state keep their existing value rules, including the restriction on copying grids. Only container fields a handler may read are captured, including reads through synchronous helpers and borrowed queries; unread containers add no capture cost. Conditional reads count as possible reads, and copying a whole value reads its fields. Handlers sharing a recorded query share its captured values. Attached local fields still use current local state.

```csharp
// The match sends Hit to the fighter, and handles it; each machine shows it.
local event(Hit hit) ShowHit(Body body, mut Fighter fighter, mut Fx fx)
{
    fighter.flash = 1;   // A local field
    Burst(fx, body.position, hit.impulse);
}

// Where a shot ended: its components as they were when it went
local event(Destroyed) ShotEnded(Body body, Bullet bullet, mut Fx fx) { ... }

// Nothing in the match handles Impact: it's sent for whoever shows it
event Impact
{
    float2 at;
    float2 normal;
}

local event(Impact impact) Spark(mut Fx fx) { ... }

// The spark as it's predicted, the death once it's certain
local event(verified Died died) ShowDeath(Body body, mut Fx fx) { ... }
```

<a id="provisional-3"></a>

### Provisional

- **Local handlers of the match's events**, beyond what's decided:
  - **The same event** is one of the same tick, event and fields, sent to the same entity. An entity is the same by what it was born as (see Local state, an entity after a rollback), where a machine knows that of both. Logical spawn identities are stable across physical allocation and projection loading. Changed initializer values alone preserve that entity's local identity; a different causal birth starts another. Presentation birth metadata derives only from the logical identity and never from private component values. Two alike in one tick are two: each is heard once.
  - `Spawned` and `Destroyed` come from 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 is `verified`; taking only local state, it's the local world's, as before. One that takes a local component and something of the match is an error.
  - What it takes of the match is a copy from the event's turn: after the match's handlers of that event ran, and for `Destroyed`, before the entity goes. `Time` is the tick the event was sent in. An event sent to an entity that's gone by its turn isn't heard, as it isn't handled.
  - The decided recorded-container rule above supersedes the earlier omission of heap fields. Journals own serialized values rather than match-heap handles. Event-payload container fields that local code may read contribute their captured contents to occurrence identity; unread containers remain omitted. Component/singleton/query data does not change occurrence identity. Recipient lifecycle records retain whole-component visibility restrictions.
  - It can't take the `World` (it's the match as it is now, not as the event left it), `Devices` or the input. It can't be `async` yet: it starts a task with what the task needs.
  - 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 at that frame (below), `Forgotten` first.
  - A frame runs them first: then the local fields of entities that are gone go, then the views run. What they spawn, change and send locally is handled at the end of the frame, like a view's. They send commands as views do.
  - An event's local handlers run in declaration order, and `[Before]` and `[After]` order them among themselves, apart from the match's handlers of the event. An event has 64 at most.
  - A machine hears what's sent from the tick it joins in: its own `PlayerJoined` and every later one. Ticks a world sent again skips (a client that went wrong) say nothing. A match that changes hands goes on from the new host's last confirmed tick, so the ticks after it are heard again on a machine that had heard them. Nothing is made up for events before a machine had the world. Availability uses `Shown` (Decided, above), in these details:
    - An entity that arrives is heard when its world does, at the start of the next frame, before anything a later tick sent. The handler sees the entity's components and the match's singletons as that world has them, not as the spawn left them, `Time` is that world's tick, and a query's rows are that world's. Both kinds of handler run, as the world is the server's.
    - Among the entities of one world, the order is the world's own storage's, not the order they were spawned in.
    - An entity arrives as it is. Each `Shown`/`Hidden` listener compares its complete required and excluded component set. Adding, removing or concealing a component can change one listener's availability while another remains available. Ordinary replay without an availability change emits nothing.
    - Which entities a machine had is told by their handles. For the first world of a match, none, but for a match that changed hands or a web build that was reloaded, whose last world's entities aren't new. For a world sent again: for the handlers that hear ticks as this machine runs them, those of its own world at that tick; for `verified` handlers, those of the last world the server had confirmed. Known birth identities distinguish corrected entities that reused a handle; otherwise comparison uses the handle.
    - Local fields kept for an entity's logical identity remain there when a handler hears it arrive again. A received world carries that identity directly; physical storage reuse cannot redirect those fields to another entity.
    - `Destroyed` is never inferred from absence in a replacement world. A permitted genuine lifecycle journal carries authoritative event-time state. `Hidden` reads the previous permitted world and its queries; `Shown` reads the new one. A known, permitted genuine destruction suppresses concealment for that entity. If earlier event history is unavailable, availability can end without inventing a death event.
  - `Shown` and `Hidden` are local notifications, cannot take local-world components, and cannot be sent by game code. Match components' local fields and local singletons remain writable. Provisional delivery reconciles complete handler availability at local presentation boundaries, separately for predicted and verified endpoints. Hidden reads the old endpoint and queries before local-field cleanup, then Shown prepares the new endpoint. Transient intra-tick/between-frame toggles coalesce; a canceled predicted conceal restores Shown, unchanged replay emits nothing, and a newly eligible listener initializes independently. A local rebuild clears private availability history and prepares existing entities again; preparation must safely reuse or replace retained local resources.
  - In visibility-enabled games only genuine `Spawned`/`Destroyed` are journaled authoritatively per recipient. Custom local/verified events still come from the client's permitted simulation; a generic server-to-audience event API remains open. So, as for any world sent again, a `verified` handler of a custom event hears nothing of the ticks a repair replaced. Repairs come whenever the client's run of a tick differs from the server's projection, for example as entities come into sight, so such handlers can miss most events in a game whose visibility changes often. Predicted handlers hear them as the client ran them.
  - A handler of an event nothing sends is a warning, like a match handler's, and `tidec --schedule` lists each event's local handlers after the match's.
  - **`Changed<...>`** (Claude's picks, 2026-10-25):
    - The path is a match component or singleton (the shortest start of the path that names one), then a field, through structs: `Changed<Unit.stats.level>`. Local fields, the engine's own components and singletons, and fields holding text, lists, maps, sets, grids or `Resident` state are errors. Each field watched is one built-in event, `old` and `value` of its type, which games can't send.
    - A change is the tick's: as it ends, after its events and changes settled, each entity that had the component as it began and has it now (by handle and generation) is compared, bit for bit, with its field then. Several writes are one change, and one written back is none. Spawns, destroys, adding or removing the component, arrival and visibility change nothing.
    - It's sent to that entity (a singleton's to the world), recorded after the tick's other events, in the order of the fields' first handlers, then of the world's storage. `Time` is that tick. Its handlers take the match as the tick left it; a singleton's take no components.
    - Rollback, `verified`, ownership filters and queries are as for any match event a local handler hears; the same change is the same tick, entity, field, old value and value. Only recording ticks compare, so the match's bytes, hash, snapshots and traffic are the same with handlers of changes or without.
    - **Match handlers** (agreed 2026-11-16): `event(Changed<Workshop.level> change) Load(mut Workshop workshop)`. They take the change as the tick ends, the same tick, after its events and changes are done, in the order above. A change a match handler makes to a field watched by match code is sent in another round of the same tick, its `old` the value after the round before, and rounds go on until one finds no change. Each round is one further down the tick's chain of events, so handlers that change each other's fields without end stop the program as an endless chain does. Every machine compares the fields match code watches on every tick, including ticks run again, so the match is the same everywhere. Local handlers of such a field hear each round's change as the match applies it.
    - Open: watching a whole component, and containers.
- `event` is only a keyword at the start of a declaration, like `input`.
- A trigger's name is optional for any event: a handler that doesn't read the event leaves it out.
- `Spawned` handlers run as the spawn is applied, and `Destroyed` handlers just before the entity goes, both in the queue's order. A spawn's `Spawned` handlers run before the next change in the queue.
- Structural changes and events share one queue per tick, which grows as it needs. What handlers record goes on its end. A chain of events that never ends (handlers that set each other off) stops the program once it's 100,000 deep in one tick, each event sent or entity spawned by a handler of the one before, with a message naming the event. `TIDE_MAX_CHAIN` sets the depth for a game that needs deeper chains.
- Event/command payloads can be locals (`var h = hit;`), ordinary function/method parameters and return values. Events can be sent on (`other.Send(hit)`); constructing or forwarding one sends nothing by itself. Payloads cannot be fields or ordinary system parameters.
- `[Before]` and `[After]` only order handlers of the same event. Handlers and systems are ordered separately.
- Games can't send the built-in events. The host sends `PlayerJoined` and `PlayerLeft` with `tide_world_player_joined` and `tide_world_player_left`: they're handled at the end of the next tick, before anything that tick sends. `tide/run.h` has player 0 join before the first tick.
- A handler of an event nothing sends is a warning, and so is declared access a handler doesn't use, as for systems.
- `tidec --schedule` lists each event's handlers in the order they run.

<a id="open-1"></a>

### Open

- Events for a component being added or removed.
- Queries in async handlers and tasks, including query-row lifetimes across waits. Synchronous handlers already iterate matching entities with ordinary query parameters.
- Local handlers: the `World` as an event left it; async ones; reading `verified` components in a handler that hears a tick as it's predicted; an event's local handler that follows the same entity when a replay gives it another handle on a machine that doesn't know what it was born as.

<a id="commands"></a>

## Commands

<a id="decided-4"></a>

### Decided

- `command Name { ... }` declares a typed player action entering the match. Commands hold plain scalar values, vectors, enums, entity and player IDs, strings, `List<byte>` (a file's bytes, for user content: see Assets), lists of other plain values (the owner asked for them 2026-11-04, from `command Enlist { List<int> attributes; }`), and structs of those. Maps, sets, grids, components and device records are not command payloads; which lists are is under Provisional.
- Local views and handlers send commands with `entity.Send(value)` or `Send(value)`, while connected to a match. The compiler distinguishes commands from events by their declaration. An entity target is required when the command handler takes components, or filters by ownership (Provisional); a handler with neither runs once for the command.
- Each command has one void handler: `command(Rename rename, PlayerID sender) RenamePlayer(Owner owner, mut Name name)`. The first parentheses contain the read-only payload and connection-derived sender. The second take the same match state as event handlers. Components and `this` come from the target. (A handler that takes `with ownership` may leave the sender unnamed: Provisional, below.)
- Guard clauses return normally. Match writes take effect normally. There is no acceptance operation, boolean result or transaction. The handler checks permissions and game rules, and can send events after acting.
- Sending copies the packed payload into a bounded local queue. Commands are independent of input ticks; repeated packets are identified by a per-player sequence. The server selects their tick and order, and handlers run in the existing deferred queue at tick end. Snapshots, hashes and migration include processed sequences, and replay executes recorded commands again in the same order.
- Initial limits are 1024 packed bytes per command, 32 pending per player and 16 commands scheduled per authoritative tick. Wire structure, UTF-8, finite values, enum values and declared bounds are checked before the match reads the payload. The handler remains responsible for authorization and game-specific rules.
- A command's ordering is its type's, per player (agreed 2026-10-06). Without an attribute a command is in the default channel: handled in the order sent, after every earlier command of that channel. `[Channel(Channels.Uploads)]`, with an enum of the game's, puts it in a channel of its own, ordered among that channel's commands and against nothing else, so a chat line never waits behind an upload. `[Unordered]` gives it no order at all: the server handles it in whichever tick it arrives, before or after commands sent earlier, still exactly once. Whatever the ordering, the server picks the tick and every handler runs in the tick's end queue in the server's order, so ordering only decides what the server holds back waiting for an earlier command.
- A command holds `List<byte>` too, so a player's file goes to the match as it is. One that doesn't fit a datagram goes as a numbered transfer in chunks, the way worlds go, paced under the input traffic so a transfer never delays a tick. It lands in a later tick, as any command may; a command was never tied to the tick it was sent in. What goes through the match goes player to server to everyone, so a host sends it once per player: a few megabytes is fine, and big media is a URL in the match, fetched by each machine (see Assets).

```csharp
enum Channels { Uploads }

command Rename { string name; }

[Channel(Channels.Uploads)]
command SetBackground { List<byte> png; }

[Unordered]
command Ping { int at; }


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;
}
```

<a id="provisional-4"></a>

### Provisional

Built 2026-10-06; the picks below await the owner.

- Sequence state is per player per channel, in the world as today's is: a channel's sequence counts that channel's commands alone, from 1. An unordered command has an id of its own, from 1, in place of a sequence, and the world keeps a window of the last 64 ids applied per player (the highest, and a bit for each of the 63 below it) to drop resends: an id older than the window is taken as applied. The 32 pending per player is per channel, the unordered commands counting as a channel of their own; 16 scheduled per tick stays one limit for all.
- A channel is an enum member of the game's, named by `[Channel(Enum.Member)]` on a `command` declaration; commands can share one, members of any enum can be channels, and a game has 63 channels of its own at most beside the default. `[Unordered]` takes nothing. Both on one command, either on anything but a command, and a name that isn't an enum member are errors. Whatever the ordering, each handler runs where it always did: in the tick's end queue, in the server's order.
- A command holds `List<byte>` as a field, or in a struct it holds. One with no list is still 1024 packed bytes at most. One with a list is 4 MiB at most (`TIDE_COMMAND_LIMIT`), its bytes on the wire whole, after a count. Over 1024 bytes it goes in chunks of 1000, 16 chunks an update each way (about a megabyte a second at 60 updates a second), each sent again once a round trip and a half has passed without it being acknowledged, as a world's chunks are. A machine sends one big command at a time, in the order they were sent; the server takes one at a time from each player.
- Lists of other values in a command (built 2026-11-04; the picks are Claude's, awaiting the owner): a `List<T>` field, in the command or in a struct, a `T?` or an array it holds, whose elements are of a fixed size: numbers, bools, chars, enums, vectors, matrices, quaternions, colors, rects, entity and player IDs, `T?` of those and structs of those. A list of text (`List<string>`, a struct with a string) or of lists, maps, sets or grids is an error ("a command's list can't hold text or other lists"), as text in an element has no bound its count can set; text goes in string fields or a fixed `string[N]`. Maps, sets and grids anywhere in a command stay errors ("a command can't hold a map, set or grid"). On the wire a list is its count, a varint, then each element as a field of its type is packed (a varint for an int, 32 bits for a float, a bit for a bool), with no padding to a byte; `List<byte>` keeps its whole bytes. A count is refused when the bits left can't hold that many elements at the fewest bits one takes, before any list is made. Each element read is repaired as a field is: a float that isn't finite, an enum value no member has, a char no character has become the element type's default (a struct's declared defaults; an enum with no member of 0, its first member). `[Clamp]`, `[Min]` and `[Max]` on a command's or a struct's `List<T>` field bound each element, as on an array, and a struct element's own fields are bounded too.
- A big command lands in a tick only once every player in the match has its bytes: the server sends them down to each player first, paced the same way under the frames, and the tick's frame names the transfer rather than carrying the bytes, so no player's tick waits for one. A player being sent the world, or catching up with one, doesn't hold it up: that player gets the transfer with the ticks it lacks. A player who joins with a world from a later tick needs nothing of it.
- The local state's outbox (what views sent and the session hasn't taken yet) is 32 a channel too, and a channel that's full at the session holds back only its own: the host hands each channel's commands over in turn.
- **`with ownership` on a command's handler: only for the sender's own entity** (built 2026-11-14 on the owner's approval of the recommendations: "go with your recommendations"; every point is Claude's pick). It's for the guard that opened most entity handlers, `if (sender != owner.player) return;`:

```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 other side, with the sender named: what the sender doesn't own, another player's or nobody's
command(Steal steal, PlayerID sender) Take(mut Purse purse, without ownership) { ... }
```

  - `with ownership` runs the handler only when the entity the command was sent to has an `Owner` whose `player` is the command's sender. A command for any other entity is dropped as that guard dropped it: it's handled, its sequence is used and a resend is refused, and nothing changes. `without ownership` is the other side: an entity with no `Owner`, or another player's.
  - **The word is the views'.** `ownership` says the entity is the player's that the code is for: a view's and a local handler's are this machine's player's, a command handler's the sender's, whom the connection names. The match has no machine of its own, but a command has its player, the same on every machine, so the one word has one meaning, and no other spelling is needed. In systems and the match's event handlers it's still an error, as nothing there is a player's. Beside it, `with Owner` is still "has any owner".
  - **A handler that filters by ownership may leave its sender unnamed**, `command(Rename rename)`, as the filter is the check; one that names it can read it as before. A handler that does neither is an error, a requirement rather than a check of what the handler does with its sender: it names the player who sent the command, so it can check what that player may do, or it filters. The error offers the filter only to a handler that runs for an entity; one that runs once for the command has no entity to filter.
  - It's a filter like the views': it creates no data dependency, and the handler takes neither `Owner` nor the sender for it. A sender is always a player, so an entity whose `Owner` names no player is never the sender's.

<a id="enums-and-switch"></a>

## Enums and switch

<a id="decided-5"></a>

### Decided

- Enums and `switch` follow C#'s syntax.
- Switch expressions choose a value: `value switch { Constant => result, _ => fallback }`. The selector runs once and only the selected arm runs. A final `_` arm is required, including for enums. Arm results have compatible types.

```csharp
Animation current = zombie.state switch
{
    ZombieState.Run => movementAnims.rootRun,
    ZombieState.Jump => movementAnims.rootJump,
    _ => movementAnims.rootRun,
};
```

- `EnumType.Count()` returns the number of declared members as a compile-time `int`. Members with the same numeric value each count; gaps and explicit values do not change the count. This is a static operation, not an enum member, and takes no arguments. A declared member named `Count` remains accessible as `EnumType.Count`.
- Explicit conversions use `int(value)` and `EnumType(number)`. Parenthesized cast syntax such as `(int)value` is rejected with guidance on the conversion to write.
- An enum member may omit its type with a leading dot when context supplies one unambiguous enum type: `zombie.state = .Idle;`. Typed initializers, fields, parameters, returns, container elements and switch cases supply their expected type; `==` and `!=` can use the other operand's enum type. A typed conditional supplies that type to both branches. This is the same value as `ZombieState.Idle`, including on the GPU. Without an expected enum type, or when overloads leave more than one possible enum, write the qualified member; member names do not choose between enum overloads.

```csharp
enum Phase
{
    Warmup,
    Playing = 5,
    Over,
}

system Advance(mut Match match)
{
    switch (match.phase)
    {
        case Phase.Warmup:
            match.phase = Phase.Playing;
            break;
        case Phase.Playing:
        case Phase.Over:
            break;
    }
}
```

<a id="provisional-5"></a>

### Provisional

- `enum Name { A, B = 5, C }` declares an enum. A member without a value is one more than the one before it, and the first is 0. A value is an int known while compiling: a literal, an int constant, or operators on them, worked out as they would be at run time. A comma after the last member is fine. `enum` is only a keyword at the start of a declaration.
- An enum is stored as an int, or as what it says after its name, as in C#: `enum Voxel : byte { ... }` takes one byte (0 to 255) and `: ushort` two (0 to 65535), for grids' cells and other data there's a lot of. A member out of that range is an error that gives the range. Anything else after the colon is an error that lists the three. Only the size changes: a value's number is still `int(...)`, and the value with a number `Voxel(...)`, which keeps the number's low bits (below).
- A qualified member is written `Phase.Playing`, or `Game.Phase.Playing` from another namespace; `.Playing` uses the context's enum type as decided above. In generated C, each spelling is `Phase_Playing`, a constant of the type `Phase`: an `int32_t`, or a `uint8_t` or `uint16_t` for `: byte` and `: ushort`.
- Enums are values, like structs: fields, locals, inputs, and functions' parameters and return values can hold them. A field without a default starts at 0, even if no member has that value, as in C#.
- `==` and `!=` compare two values of the same enum, and since 2026-11-14 `<`, `<=`, `>` and `>=` order them by their numbers (below).
- An enum and its number convert both ways, and neither way by itself: `int(phase)` (or `long(phase)`) is a value's number, and `Phase(5)` the value with that number, as `float3(i)` mirrors `int3(f)`. The enum's name is all there is to it: no keyword, and no attribute. An enum in a namespace converts by its qualified name too, `Combat.Stance(2)`.
- `Phase(...)` takes one int, or a byte, which is an int wherever one goes. A float or a long converts with `int(...)` first, and so does another enum's value: each is an error that says so. A mismatch the other way (`Phase p = 1;`, `int n = phase;`) names the conversion to write.
- As C#'s cast does, `Phase(n)` keeps a number none of the members has: the value is that number, and `int(...)` gives it back. Nothing checks it, so the conversion costs nothing. The rest of the language takes such a value as it takes a field that started at 0 with no member there: it equals no member, a `switch` on it runs its `default` (or no section), text shows its number, an input or a command that carries one from another machine gets the field's default instead (below, and Commands), and a hot reload that changes the layout carries enums by their member's name, so it goes back to the field's default. Code that needs a member bounds the number first (`Card(hash % CARDS)`), or handles the rest in a `default`.
- An enum stored as a byte or a ushort keeps the number's low 8 or 16 bits, as `byte(x)` keeps an int's low 8: `Voxel(300)` is `Voxel(44)`, and `Voxel(-1)` is `Voxel(255)`.
- With a constant number it's a constant: `const Card FIRST = Card(0);`, a field's default, a `case` label.
- It works in a frag or vert too, where an enum is an int whatever it's stored as: the number itself, cut to its low bits for a byte's or a ushort's enum, so the GPU and the CPU agree.
- An enum in an input that isn't one of its members, which only a bad client could send, becomes the field's default before `Sanitize`, like a NaN float.
- `switch` works on ints, longs, chars and enums. A case is an int known while compiling (a literal, an int constant, or operators on them), a char known the same way (see Text), or one of the enum's members, maybe through a constant of the enum. Labels in a row share a section, `default` handles the rest, and each value appears once.
- Every section ends with `break;` or `return;` on every path, so none runs into the next, as in C#. Outside a switch, `break` ends a loop (see Loops); anywhere else it's an error.
- Each section has its own scope for locals.
- A function returns on every path when a switch with a `default` returns in every section.
- `switch`, `case`, `default` and `break` are keywords.
- Built switch expressions accept constant labels of the same types as statement switches, with no duplicate values and an optional trailing comma. Each arm has its own scope for `out` locals. The expected result type supplies `default`, `null` and list-literal types; otherwise the compiler infers a common type from the arms. `switch` binds after unary operators and before arithmetic; parentheses switch on a compound expression. Constant selectors and arms work in constants and field defaults. CPU, async and GPU lowering preserve source evaluation order and lazy arm selection, within those contexts' existing type restrictions.

- **Ordering and every member** (2026-11-14; the owner approved the recommendation that day, "go with your recommendations"; the rules below are picks):
  - `<`, `<=`, `>` and `>=` compare two values of the same enum by their numbers, as `==` does: `Phase.Warmup < Phase.Playing` is `0 < 5`, so order is the numbers', not where the members are written. An enum stored as a byte or a ushort compares its stored number (`Voxel(-1)` is 255, after every smaller member). Two enums, or an enum and a number, are an error that names `int(a) < int(b)` or a member to compare with. `.Member` takes the other side's enum here too: `phase >= .Playing`. Constant operands fold, so these work in constants, field defaults and `if`s that are always one way. On the GPU, where an enum is its int, it's the same comparison.
  - `EnumType.Values()` gives every declared member once, in the order they're declared, as an array `EnumType[N]` of `N = EnumType.Count()` members: `foreach (var kind in TreeKind.Values())`, `TreeKind.Values()[i]`, `.count`. A member whose number an earlier member has (an alias, `enum E { A = 1, B = 1 }`) is in it at its own place, so that number is there twice, as `Count()` counts both. It's a static operation like `Count()`, takes no arguments, and a member named `Values` stays `EnumType.Values`; `kind.Values()` and `kind.Count()` of a value are an error whose note names `TreeKind.Values()`. It's a constant (`Direction[4] all = Direction.Values();` as a field's default), costs nothing at run time, and works in frags and verts (`array<i32, N>(...)`). An array, not a list: no heap, the same in match code, views, workers and the GPU, and an enum's members never change while it runs.
- **Members worked out from other enums** (2026-11-15, a fix): a member's value can read any member of another enum, wherever that enum is declared, directly, through constants and through `Values()`; that enum's members are numbered first, as they are for an array's length or a setting that reads them. Before, a member of an enum declared later read as 0. A member's value that reads a member of its own enum at or after it (itself, or `Values()[i]` of one), or two enums whose members are worked out from each other, is an error.

<a id="open-2"></a>

### Open

- A warning when a switch on an enum has no `default` and misses a member.
- Patterns and guards in switch expressions.

<a id="loops"></a>

## Loops

<a id="decided-6"></a>

### Decided

- `for`, `foreach` and `while`, with `break` and `continue`, as in C#.

<a id="provisional-6"></a>

### Provisional

- `for (var i = 0; i < n; i++) { ... }`: its start, condition and step are each optional. The variable it declares changes in its step, and is read-only in its body unless it's declared `mut var`.
- `foreach (var item in list) { ... }` goes through a list's elements in order; `foreach (Type item in list)` names their type. Each element is a copy, read-only. The list's `count` is read each round, so elements added along the way are reached too. A foreach over a grid goes through its cells' places, and `parallel` through them at once (see Grids); `parallel` goes through a list's elements at once too, by index (see Lists). A foreach over text goes through its characters (see Text).
- `i++`, `i--`, `++i` and `--i` are statements, on ints and floats, the same as `i += 1` and `i -= 1`.
- They're expressions too, as in C# (the owner, 2026-10-08, of `(++some.count % 2 == 0) ? logo : test`, which was a syntax error: "i feel like this should be possible?"; the rules are Claude's picks): `++i` and `--i` are the variable's value once it changed, `i++` and `i--` what it held before. They go on what an assignment's target can be (a local, a field, a list's or an array's element, a map's value), of an int, a long, a byte or a float, and are checked as that assignment is: `mut` where it's needed, a view never the match. Each is a write in its turn (see Evaluation order): `i + ++i` adds what `i` was to what it is then, and `Pack(i++, i++)` gets the two values in order. On the right of `&&` and `||` and on the sides of `?:` one only runs when its part does. In a `parallel` loop's step one changes what an assignment there can: the step's own variables, its own cell, its own element. In code the GPU runs (which has no `++` as a value in WGSL, and no promised order between operands in GLSL) each runs before its statement, into a variable, so its value is the CPU's; for that to hold, the statement names the variable nowhere else, and the `++` isn't on a side of `?:` or the right of `&&` or `||`, nor inside an expression on a loop's own line (a for's or a while's): each an error that says what to write. Not built: `x = y = 0`, as assignments are still statements.
- `break` ends the innermost loop or switch; `continue` goes on to the innermost loop's next round, from inside a switch too. In a block after a call, both are the caller's: they end or continue the caller's loop, even if the function runs the block inside a loop of its own.
- `Spawn`, `Scene.Load` and widgets can't be in a loop's condition or a for's step, which run again and again; they go in its body.
- `while (true)` and `for (;;)` with no `break` of their own never end, so nothing needs to follow them: a function can end with one, and so can a switch's section.
- `in` is only a keyword in a foreach or a parallel loop, and `by` and `offset` only in a parallel loop; `while`, `for`, `foreach`, `parallel`, `indexed` and `continue` are keywords everywhere.
- There's no `do ... while` yet.

<a id="indexed-loops"></a>

### Indexed loops

Decided (the owner, 2026-11-05):

- A loop over a query's rows or a list's elements visits only the rows that can pass its own guard, whenever the compiler can prove which ones those are. Nothing is declared: the compiler reads the guard. The game's check still runs on every row the index gives, and the rows are visited in the loop's normal order, so the results are the plain loop's, bit for bit.
- `indexed` written before a loop promises it: `indexed foreach (var o in others) { ... }` and `indexed parallel (...)`. `indexed` always comes first. It changes nothing about what the loop does: a loop that can't be indexed is an error that says why, where a plain loop would quietly visit every row. `indexed` alone, `indexed (...)`, is an error that says to add `foreach` or `parallel`.
- Lists are indexed as queries are.

```csharp
system Separate(mut Body body, Sight sight, query (Body other, with Boid) boids)
{
    indexed foreach (var b in boids)
    {
        if (Math.Distance(b.other.position, body.position) > sight.range) continue;
        body.velocity += Push(body, b.other);
    }
}
```

Provisional (Claude's picks, 2026-11-05):

- **The guard** is what the body starts with: read-only locals of pure values, then `if (condition) continue;` statements, or one last `if (condition) { ... }` holding the rest of the body with no `else`. A call that does something, a `break`, a `return` or anything else ends it: a guard after them doesn't count, since rows that fail it have already done something. Pure means arithmetic, comparisons, `?:`, fields, elements, `Math` functions, constructors, `World.Get`/`Has`/`TryGet`, and calls of functions whose body is read-only locals and a `return` of the same.
- **What a guard can bound**: a number of the row (a float, a double, an integer, an enum, a bool, or a vector's component) compared with a value the loop doesn't change; for floats and doubles, the number plus or minus such a value, and `Math.Abs` of their difference; the row's vector's `Math.Distance`, `DistanceSq`, `Length` or `LengthSq` of a difference, or `Dot` of a difference with itself, to such a place, and sums of squared differences (`dx * dx + dy * dy`); an equality of a vector the row has. `&&`, `||` and `!` combine them. A function whose body is a `return` is seen through, its arguments in place of its parameters.
- **A value the loop doesn't change** is a constant, or a parameter, local or field that nothing in the loop's body assigns, passes to be changed or sets through a World. It's worked out once before the loop.
- **Why not**: a loop that isn't indexed says why in `tidec --schedule`, under "Loops that skip rows": no guard, a bound that changes inside the loop, a bound the index can't work out before the loop (a call that does something, a property's getter), the loop setting the query's component through its World, changing its own list, or a list that could change between one run of the loop and the next (a component's, a `mut` singleton's, a parameter's, a local the code writes): its index would be made again each run, which costs more than going through every element, so only `indexed foreach` gets one there. A list's index is kept for a list of a singleton the code only reads, and for one in a local nothing writes after declaring it. A query is also not indexed when the code it's in changes the key's field of its own entity as it goes, as `body.position += body.velocity` beside a loop over `Body` positions does: rows the index was made from would change between one run of the loop and the next. Changing it in a system of its own fixes that.
- A loop in async code whose body waits (`await`) isn't indexed: the search can't be kept across a wait.
- **A component handed on to change its local fields alone** (Claude's picks, 2026-11-15): a call whose `mut` parameter takes a match component or singleton with local fields, and whose function (a task among them) changes none of its match fields, itself or through what it hands it to, changes no number a loop finds rows or bounds by, as no key or bound is a local field. So a view that starts a local task with its own `mut Chunk chunk` (Local state, Local tasks and local fields) still has its loop over the other chunks by `chunk.at` indexed. A loop over a list that is one of those local fields, `chunk.faces`, is changed by the call, as before, and so is a component whose function writes a match field of it, a task's after a wait too. So is one handed to C: an `extern` function's `mut` parameter, and one a function hands on to C itself or through others, changes the whole of it, as what C writes isn't the compiler's to know (review, 2026-11-15: a system that handed its own component to an `extern` was indexed by that component's own fields, which C changed).
- **Which keys**: two or three components of one float or double vector bounded both ways (a grid), else every equality of a whole number as one exact key (below), else an equality, else one number bounded both ways, else one bounded one way.
- **Exact keys** (Claude's picks, 2026-11-14): an equality of one of the row's whole numbers (an `int`, a `long`, a `byte`, a `char`, an enum, a bool, or a component of an `int2`, `int3` or `int4`) with a whole number the loop doesn't change is exact. The guard's equalities of them, up to eight, are one key, and the loop visits only the rows equal in every one of them, however many rows share some: `if (row.chunk.at.x != at.x || row.chunk.at.y != at.y || row.chunk.at.z != at.z) continue;` beside `if (row.chunk.dimension != dimension) continue;` visits the chunks at that place in that dimension, not every chunk with that `x`. A `long` is one the same way, so a place packed into one number is found as exactly as the place. Up to three of the guard's other bounds (`row.chunk.heat < limit`, `row.chunk.at.y >= floor`) go beside the key and narrow the rows further. An equality with a float or a double isn't exact (`row.kind == 2.0` with a byte `kind`: the two are compared as floats), nor one of whole numbers held as floats or doubles on the way (`double d = row.chunk.key;`, or a helper that returns a whole number as a `double`), and is bounded as any number is. A query's keys are all of bindings read `previous` or all of bindings that aren't: the first key's kind, with the others left to the guard. `tidec --schedule` names every number of the key: "indexed by row.chunk.at.x, row.chunk.at.y, row.chunk.at.z and row.chunk.dimension as one exact key".
- An index of a world's rows lasts while the rows it was made from are unchanged, across ticks too: an index of walls that never move is made once.
- **A key in a `previous` binding** (2026-11-13; Read-only entity queries): the loop finds rows by what they were when the tick started, which nothing changes while its systems run. So it's indexed whatever the system writes, the key's own field of its own entity too, and its index is made at most once a tick: every loop in the game that searches the same query by the same keys, in a system or in a function a system hands its query to, on whatever threads, shares one.
- **When most rows can pass** (2026-11-12): a search of a world's query that finds more than one row in six saves nothing, so the loop then goes through every row as a plain loop does, which costs less a row, and a loop whose searches keep finding that many leaves the search out for some of its runs. So does a loop over fewer than 32 rows. The results are the same either way; only the cost differs. `indexed` still means what it meant: the loop can be indexed.

<a id="text"></a>

## Text

<a id="decided-7"></a>

### Decided

- `string` is text, as a value: assigning copies it, and nothing is ever shared.
- A string's `length` counts characters (Unicode code points), not bytes.
- Components, singletons, structs and events can hold text. A world keeps it in its heap, part of the world, so snapshots have it too. The heap grows as it needs, with memory (see Limits).
- Nothing about text fails: past the end of a string, positions are clamped. Text that code makes can be as long as the scratch area it lives in has room for: the area grows as it needs, with memory (see Limits).
- Text turns into bytes, pieces and numbers by `text.ToBytes()`, `string.FromBytes(bytes)`, `text.Split(separator)`, `int.TryParse(text, out value)` and `float.TryParse(text, out value)` (the owner, 2026-10-11, of these names: "these are good to have anyways"). What each takes and gives beyond its name is Provisional, below.

<a id="provisional-7"></a>

### Provisional

- Text is UTF-8. Literals can hold any UTF-8 character, and `\"`, `\\` and `\n`.
- `$"score {score}"` puts values in text. After a value, a colon and a format, as in C#: `{x:F2}` for two decimals, `{n:D3}` for at least three digits (`007`), `{n:X}` for hex. Floats, vectors, quaternions, colors and rects take F, up to F9; ints, longs and int vectors take D (up to D32), X (up to X8, or X16 for a long) and F. The letter can be lowercase. `{{` and `}}` are braces, and `?:` in a value goes in parentheses: `{(won ? 1 : 0)}`.
- Text can show numbers, bools, enums (their member's name, or their number when no member has it), vectors and quaternions (`(1, 0.5)`), `Color` (`RGBA(1, 0, 0, 1)`), `Rect`, entities (their opaque logical identity: see Entities) and players (`PlayerID(0)`). Floats are written with the fewest digits that read back as the same float, plainly from 1e-7 to 1e21 and with an exponent beyond (`1.5E+21`), the same on every platform: computed exactly, never with the platform's printf.
- Text shows values with fields (structs, components, singletons, events and inputs) as C# shows records: `Stats { hp = 3, speed = 1.5 }`, `Nothing { }`, nested ones inside. Lists show as `[1, 2, 3]`. Text in them is in quotes, `name = "Bob"`, so `""` shows; it isn't escaped. Scenes show their own fields, not the engine's. `Session` shows its `room` last. The device records (`Devices` and the rest) don't show, nor does anything holding a matrix, which text can't show yet; the error names what's in the way.
- `+` joins text with anything it can show: `"score " + score`, `1 + "st"`. `==` and `!=` compare text byte by byte. There's no `<` for text.
- `length`, and the methods `Contains`, `StartsWith`, `EndsWith`, `IndexOf` (-1 if it's not there), `Substring(start)` and `Substring(start, length)`, `ToUpper` and `ToLower` (ASCII letters only, for now), `Trim` and `Replace(from, to)`.
- Text that code makes, joining and formatting, lives in a scratch area that's cleared once the system, view or handler that made it is done, for each entity. It's only ever copied into a world's heap.
- Heap text never changes once it's written: changing a field writes new text. What's released only goes back once the code running is done, so a copy of a field made before it changed still reads the old text, with no copying.
- An input can't hold text: what players send each tick is numbers, bools, chars and enums.
- **`char` is one character of text** (the owner, 2026-10-08, of three answers to what `text[i]` gives, a one-character `string`, the code point as an `int`, or a `char` type: "C; its the non-lazy approach". That there's a `char`, and that `text[i]` gives one, is theirs; each rule below is Claude's pick, C#'s where it has one):
  - **What it is.** A Unicode code point, as a text's `length` counts them (where C#'s is a UTF-16 unit, half of some characters), in four bytes: a plain value, which goes where an int does (fields of components, singletons, structs, events and commands, arrays, lists, a grid's cells, an input's fields, locals, parameters, constants, what a function returns, a C function's parameters as an `int32_t`). Its zero, `'\0'`, is no character, and its `default`.
  - **Literals.** `'a'`: one character between single quotes, any of UTF-8's, or one of the escapes `\'`, `\"`, `\\`, `\n`, `\r`, `\t` and `\0`. The last three aren't text's (which has `\"`, `\\` and `\n`): they're what text read from a file is compared with. None between the quotes, or more than one, is an error that says which of a char and text to write.
  - **A text's characters.** `text[i]` is the one at `i`, counted as `length` counts, and `'\0'` before the start and past the end, as nothing about text fails. (`Substring(-1, 1)`, whose start is clamped, gives the first character; an index names one place, so there's nothing to clamp it to.) It only reads: `name[0] = 'x'`, `name[0]++` and a `mut` or `out` argument of one are errors that say to make the new text of its pieces. `foreach (var c in text)` goes through them in order, of the text as the loop found it, whatever its variable becomes meanwhile (a list's foreach reads its count each round; text is a value that never changes in place). `foreach (char c in text)` names the type.
  - **Comparing.** `==`, `!=`, `<`, `<=`, `>` and `>=`, by code point. Never with text: `c == "a"` is an error that says to write `'a'`.
  - **To an operator, a char is its code point, an int** (C#'s rule): `c - '0'`, `c + 1`, `c == 65`, `'a' * 2`, `-c`. What comes of one is an int, never a char. A char converts to an `int`, a `long` or a `float` by itself where one goes (a variable, a field, an argument, an element, an index, `Math`'s functions), and `int(c)`, `long(c)` and `float(c)` say so. The other way is written: `char(n)` is the character with code point `n`, an int, and `'\0'` for a number none has (under 0, past `0x10FFFF`, or from `0xD800` to `0xDFFF`, the halves of UTF-16's pairs), so a char is always a character or none. No `++`, `--` or `+=` on one: `c = char(c + 1)`. Vector constructors take none.
  - **`switch`** works on a char, its cases chars: literals, char constants, `char(n)` of a constant. An int's or a long's switch takes chars as cases too, as their code points; a char's takes no int (`case char(65):`).
  - **Keys.** A map's and a set's key can be a char.
  - **In text.** `+` joins one as its character, and `$"{c}"` shows it; `'\0'` adds nothing, so what's read past a text's end joins as nothing. It takes no format (`{int(c):X4}` shows its number). Inside a value, text shows it in its quotes, as it shows text in its own: `Glyph { mark = 'a' }`, `['a', 'b']`, and `'\0'` for the one that's none.
  - **Text's members take one**: `Contains(c)`, `StartsWith(c)`, `EndsWith(c)`, `IndexOf(c)` and `Replace(from, to)`, where replacing with `'\0'` takes the character out. A call with text picks the text one.
  - **An input and a command carry one in 21 bits.** A number no character has, which only another machine could send, becomes the field's default before `Sanitize`, as an enum that's none of its members does.
  - **On the GPU** a char is an int, its code point: fields, arrays, lists, a map's keys, literals, `switch`, comparisons and `char(n)` work there. Text itself stays the CPU's.
  - **Bytes that are no character's.** Text from C or a file can hold bytes that aren't UTF-8. A character is a byte that starts one and the bytes that continue it, which is how `length` counts, and one whose bytes are no character's (too few or too many, a longer form than the shortest, half of a UTF-16 pair) reads as U+FFFD, the replacement character, the same on every machine.
  - **What it costs.** `foreach` reads each character once, on any text. `text[i]` is as quick for text of a byte a character, which a text's two counts (its bytes and its characters) say; for any other it counts its way from the start, so a `for` over a long one with `text[i]` is slow, and `foreach` is the loop to write. `Substring` gives a piece where its text is, with nothing copied.
- **Bytes, pieces and numbers** (built 2026-10-11; the names are the owner's, each rule Claude's pick, C#'s where it has one and stricter where C# reads a machine's settings):
  - **`text.ToBytes()`** is a `List<byte>` of the text's UTF-8, and **`string.FromBytes(bytes)`** a `string?`: the text a `List<byte>` is, a copy, or nothing when the bytes aren't UTF-8 through and through (a byte that starts no character, too few after one, a longer form than the shortest, half of a UTF-16 pair, past U+10FFFF). A NUL is a character like any other. `string.` has that one function: what a text has is called on the text.
  - **`text.Split(separator)`** is a `List<string>` of the pieces between each separator and the next, the separator text or a char. Empty pieces are kept, so joining the pieces with the separator gives the text back: `"a,,b".Split(",")` is three pieces and `"".Split(",")` one. Separators are found from the start, each after the one before (`"aaa".Split("aa")` is `""` and `"a"`). A separator that's empty, `'\0'`, or not in the text gives the whole text as one piece. (C#'s, without its options: no count, no trimming, no dropping of empty pieces.)
  - **`int.TryParse(text, out value)`, `long.TryParse` and `float.TryParse`** give whether the whole text is a number of that type, which goes to `value`, an `out` argument as a function's is (`out var n`, `out n`, `out _`); otherwise false, and `value` is 0. A call can stand as a statement of its own. An int and a long are digits, with `-` before them for a negative one, zeros before them allowed. A float is that with a point among the digits and an exponent after: `-12.5`, `.5`, `5.`, `1e-3`, `2.5E+10`. Nothing else is a number: no spaces before or after (`Trim` first), no `+` before it, no hex, no digit separators, no `f` or `deg` after it, no `NaN` or `Infinity`. A number the type doesn't hold is false too: an int past its range, a float past the biggest float (one too small to tell from zero is zero). There's no `byte.TryParse`, and no `Parse` that fails.
  - **A float read from text is the one nearest the number written**, a tie going to the even one, as IEEE 754 rounds, whatever the number of digits: worked out with exact integer arithmetic, never the platform's `strtof`, so the same text is the same bits on every machine, and the match can read numbers. What text shows of a float (its shortest digits, or with a format) reads back as that float.
  - They run in any CPU code, the match's too; code the GPU runs has no text. A `Split`'s list and a `ToBytes`'s are in the scratch area, like any list code makes.
- `GUILayout.TextField(label, mut text)` and `GUI.TextField(rect, label, mut text)`: a field the player types into, which changes the text as they type. Enter or Escape stop typing; caret, selection and editing keys are described under GUI. With `out bool entered` after the text, it also says whether Enter ended the typing (see GUI).
- Systems that change the match's text or lists wait for each other, as their heap is one: `tidec --schedule` says "both change text or lists".

<a id="open-3"></a>

### Open

- What a char is, as members: `IsDigit`, `IsLetter` and the like, and its case. For now `c >= '0' && c <= '9'`, and `ToUpper` and `ToLower` are text's.
- `Join`, `Split` by several separators or with a count, `byte.TryParse`, a `Parse` that fails with an error, and reading hex.
- The GUI's number fields (`GUILayout.FloatField`) still read what's typed with the platform's `strtof`: local code only, so no match depends on it, but they could read with `float.TryParse`'s code.
- `++`, `--` and `+=` on a char, and `\r`, `\t` and `\0` in text's literals, which a char's have.
- Grapheme-cluster caret movement, bidirectional editing and inline IME preedit in text fields.
- Case for letters past ASCII.

<a id="json"></a>

## JSON

<a id="decided-8"></a>

### Decided

- JSON is read and written as a game's own types, by code the compiler writes for each type: `Json.Read<LobbyInfo>(text)` gives a `LobbyInfo?`, nothing when the JSON is bad, and `Json.Write(info)` gives a `string` (the owner, 2026-10-11, of the static, struct-mapped way over a JSON value walked at run time: "yeah I like that static thing; makes it simple, straight forward"). There's no dynamic JSON value: that was explicitly not wanted now.

```csharp
struct LobbyInfo
{
    string id;
    string name;
    int players;
    List<string> tags;
    [Json("max_players")] int maxPlayers;
}

var info = Json.Read<LobbyInfo>(response.body);   // LobbyInfo? : empty when the JSON is bad
var text = Json.Write(info ?? LobbyInfo { });     // string
```

<a id="provisional-8"></a>

### Provisional

Built 2026-10-11. Beyond the two calls and that a struct's fields are an object's keys, each rule is Claude's pick, awaiting the owner:

- **The calls.** `Json.Read<T>(json)` takes a `string` or a `List<byte>` of UTF-8 (a response's body) and gives a `T?`, unwrapped as any is (`??`, `is`, `!`). `Json.Write(value)` takes the value and gives its JSON with no spaces. `T`, and what `Write` takes, is a struct, a `List<T>`, a `Set<T>` or a `Map<K, T>`: a value alone (`Json.Read<int>`) goes in a struct's field. Arguments go in order, without names. `Json` is a name of the language's, like `Math`: a game declares nothing called `Json`.
- **What JSON holds.** `bool` (`true`, `false`); `byte`, `int` and `long` (a number); `float` and `double` (a number); `string` (a string); `char` (a string of one character, `""` for `'\0'`); an enum (its member's name, as a string); a vector, a quaternion or a color (an array of its numbers, below); a struct of the game's (an object, a key for each field); `List<T>` and `T[N]` (an array); a set (an array of its keys, below); a map by a `string`, a `byte`, an `int`, a `long` or an enum (an object, a key for each entry, below). Anything else is a compile error at the call, naming the type and the field that holds it ("JSON has nothing for Entity, which 'Lobby.owner' holds"): entities and players, matrices, sets of entities or players, maps by a `char`, an entity or a player, grids, textures and the other resources, the engine's own structs (`Random`, `Sound`), and components, singletons, events and inputs, which aren't values of their own (copy what's needed into a struct).
- **Vectors, quaternions and colors as arrays** (built 2026-11-14; the owner approved arrays, "go with your recommendations", and each rule here is Claude's pick). `float2`-`float4`, `int2`-`int4` and `double2`-`double4` are an array of exactly their numbers in order (`[x, y, z]`), a `quaternion` is `[x, y, z, w]`, and a `Color` is `[r, g, b, a]`, written with all four and read from four or from three, `[r, g, b]`, with alpha 1. An array of any other length makes the read give nothing, unlike `T[N]`'s forgiving fill: a vector missing a number is more likely a mistake than a zero, and Color's three-or-four is the one exception. Each number reads as its field's kind would (an int's whole and fitting, a float's the nearest float), a `null` in place of one leaves that one at the place's default (the field's declared default's number, zero in a list), and so a float written as `null` (NaN, an infinity) reads back as that number's default. What's written reads back bit for bit. Matrices stay refused, with a note to keep their columns in vector fields or what they're made from.
- **Sets as arrays and maps by a number or an enum** (built 2026-11-14 with vectors, as they fell out of the same code; Claude's picks). A `Set<T>` of strings, chars, bytes, ints, longs or enums is an array of its keys, written in the order they were added; one read twice is in the set once, and a `null` element adds its type's default, as a list's `null` element is the default. A `Map<K, T>` by a `byte`, an `int`, a `long` or an enum is an object whose keys are the key's text: a number's digits (`"12"`, `"-3"`, written as `tide_str_add_long` writes them; read as `long.TryParse` reads, so `"007"` is 7 and `" 1"`, `"+1"`, `"1.5"`, `"1e2"` and `""` give nothing, as does one that doesn't fit `K`), an enum member's name (the first name a number has, or its digits where no member has it; read from any member's name, an alias's too, or from digits that fit its storage). A map by a `char` is still refused (Open).
- **Keys.** A field's key is its name, or the text of `[Json("key")]` before it: `[Json("max_players")] int maxPlayers;`. The attribute goes on a struct's field, takes one text literal of at most 120 bytes, and no two fields of a struct have one key. Keys match exactly, by their bytes, case and all.
- **`T?` fields** (built 2026-10-11, with fields that are a `T?`: see Errors, T? fields). A key the JSON leaves out keeps the field's declared default, which is no value unless it declares one; `null` is no value, whatever the default; anything else is read as its `T` would be, a struct's value from its fields' defaults. Written, a field with no value has no key, so a struct of `T?` fields says only what's set (a partial update), and what's written reads back as the same value unless a field with no value declares a default.
- **Reading is forgiving about what's there:** a key the JSON leaves out keeps its field's declared default; a `null` leaves what it's for as it is (a field's default, an element's or a value's default in a list or a map); a key no field has is skipped, its value read past (it still has to be JSON); a key written twice takes the last one, a struct's fields starting over from their defaults each time. An array for a `T[N]` fills the elements it has room for: fewer leave the rest, more are skipped. `null` as the whole text gives nothing.
- **And strict about what it is:** anything that isn't JSON (RFC 8259: no comments, no trailing commas, no single quotes, no `NaN`, nothing after the value but spaces) makes the read give nothing, and so does a value that isn't its field's kind. A whole number is one whose value is whole, however it's written (`3`, `3.0`, `300e-2`), and has to fit its type: `300` for a byte, `2147483648` for an int and `3.5` for either give nothing; nothing saturates or wraps. A float takes any number a float holds, rounded to the nearest one as `float.TryParse` rounds (see Text), and one past the biggest float gives nothing. An enum reads from a member's name, an alias's too, or from a number that fits its storage; a name no member has gives nothing. A `char` reads from a string of exactly one character, or `""`. Text has to be UTF-8 with JSON's escapes, `\uXXXX` among them, a pair of them for a character past U+FFFF; a pair's half alone gives nothing. A byte order mark before the JSON is skipped.
- **Writing.** Every field (but a `T?` field with no value, above), in the order the struct declares them; a map's entries in the order they were added; an array's every element. Text is escaped as JSON says (`\"`, `\\`, `\n`, `\r`, `\t`, `\b`, `\f`, and `\u00XX` for the other control characters), everything else as it is, in UTF-8; bytes in text that are no character's UTF-8 (text from C or a file) are written as U+FFFD, so what's written is always JSON. An enum is the first name its number has, or the number itself when no member has it. A float is the fewest digits that read back as the same float, as text shows one (`1.5E+21` past 1e21 and under 1e-7), `-0` for a negative zero, and `null` for NaN and the infinities, which JSON has no number for and which read back as the field's default. What `Write` gives, `Read` reads back as the same value, bit for bit, but for those.
- **The same on every machine.** Reading and writing use exact integer arithmetic for numbers and nothing of the platform's, so the calls are deterministic and run in any CPU code: systems, handlers, functions, views, tasks. Match code can read JSON a command or a file every machine has brought. Code the GPU runs has no text, so none there.
- **What a read is bounded by**, since its text can come from anyone: arrays and objects nest 32 deep at the most, in what's skipped too; text of 64 MiB or more isn't read (what a fetch gives at the most); and a read makes 128 MiB of elements, entries and text at the most. Past any of them the read gives nothing. Within them, a read never reads outside its text, and what it makes is in the scratch area, like any value code makes.
- **In generated C** a game has a reader and a writer only for the types it reads and writes, and for the types in those, each a function of its own (a struct with a list of itself reads as deep as the JSON goes, within the 32). A game that calls neither generates the C it did.

<a id="open-4"></a>

### Open

- A JSON value for shapes a struct doesn't say (the owner: not now), and with it reading one key out of a document.
- A way to write `null` for a `T?` field with no value, where a service wants the key (today the key is left out), and with it telling a key that's `null` from one that's missing where a field has a default.
- Maps by a `char` (an object whose keys are one-character strings), and matrices (as arrays of columns, or refused for good).
- Whether a key no field has, a number that doesn't fit and an unknown enum name should each be an error the game can tell apart, where today the read gives nothing whatever was wrong.
- Options: indented output, leaving out fields at their defaults, keys in another case (`snake_case` for every field at once).
- What a read gives when it runs out of the scratch area before its own bounds: the program stops, as any code that makes too much does (see Limits).

<a id="generics"></a>

## Generics

<a id="decided-9"></a>

### Decided

- Generics are a proper part of Tide, in three steps (the owner, 2026-10-06: "we clearly need generics and I don't like making them just an engine thing that you can't touch"): a type is read as a tree, containers nest by one rule (both built: see Lists, and `AGENTS.md`, Language), and games declare generic structs and functions of their own, below.
- **Generic functions, with type arguments inferred, and `has`** (the owner, 2026-11-02, approving Claude's recommendations for the Geometry package: generic functions and C#'s inference at least; a compile-time field test; a bundled package): a function takes type parameters in `<>` after its name, a call gives them in `<>` or leaves them to its arguments, and `T has float3 normal` is a constant that says whether type `T` has that field, so generic code writes the fields a type has.

```csharp
T Max<T>(T a, T b)
{
    return a > b ? a : b;
}

V Corner<V>(float3 position, float3 normal)
{
    mut var v = V { };
    v.position = position;
    if (V has float3 normal) v.normal = normal;
    return v;
}

int bigger = Max(3, 7);              // T is int
float half = Max<float>(2, 1.5);     // T written: the int converts to it
var corner = Corner<Vertex3>(p, n);  // Vertex3 has no normal: that line isn't there for it
```

<a id="provisional-9"></a>

### Provisional

Built 2026-11-02 on that; each point beyond it is Claude's pick, from the 2026-10-06 proposal (Open, below) unless it says otherwise.

- **Declaring.** `T Max<T>(T a, T b) { ... }`, at a namespace's level, with any number of parameters, each a name. A type parameter shadows nothing: a name a type already has is an error at the declaration. Not virtual or override, async or a worker, nor a method of a struct (those are errors that say so).
- **Using.** `Max<float>(a, b)`, as many types in `<>` as it has parameters, or `Max(a, b)` with them inferred. A type argument is a value, what a list's element can be: not a component, singleton, input, event, grid, World, Devices, Action or a `T?` (an error that names the parameter).
- **Inference**, as C#'s: each argument whose parameter's type mentions a parameter gives it, `T` against the argument's type and `List<T>`, `Set<T>`, `Map<K, V>`, `Grid2<T>`, `T[N]` and `T?` against their parts. Two arguments that give a parameter different types are an error, which says to write it in `<>` (no widening picks between `int` and `float`); a parameter no argument gives is an error that says to write the `<>`. A list literal, a lambda, `null` and `default` give nothing. The return type takes no part.
- **Overloads.** A generic and plain functions can share a name, and so can generics with different parameters. Each generic takes part as its instantiation, and a plain function wins where both take the arguments, as in C#. A call with `<>` picks only among the generics.
- **Instantiation.** Each set of type arguments is one function, checked as the generic's code with the parameters bound and generated once, however many calls make it: `Max<int>` is `tide_function_Max_int` in generated C (the generic's name, then its type arguments', and its parameters' types where generics share the name). An instantiation is made when a call picks it, so a generic nothing calls is parsed but not checked. Errors in an instantiation's code are said where the generic's code is, with a note at the call that made it ("in 'Max<Pair>', which this call instantiates"), through a chain of them. Instantiations one inside another stop at 8, with an error.
- **`has`.** `T has <type> <name>`: whether type `T` (a type parameter, or any type) has a field of that name and exactly that type. It's a constant `bool`. An `if` whose condition is `has` tests alone, with `!`, `&&` and `||`, keeps only the side that runs, which alone is checked, so the other side can name fields `T` hasn't got. Anywhere else it's a plain constant.
- **A generic as a value** (`Func<int, int, int> f = Max;`) is an error that says to call it in a lambda: which instantiation a name means isn't said by the name.

<a id="open-5"></a>

### Open

What's left of the proposal for the third step (Claude, 2026-10-06), for the owner to approve before it's built. Each point is a pick unless it says otherwise.

- **Generic structs and methods.** A struct or a method takes type parameters in `<>` after its name, as C#'s do:

```csharp
struct Pair<T>
{
    T a;
    T b;
}

struct Stack<T>
{
    List<T> items;

    mut void Push(T item) { items.Add(item); }

    T? Pop()
    {
        if (items.count == 0) return null;
        var top = items[items.count - 1];
        items.RemoveAt(items.count - 1);
        return top;
    }
}
```

  A method of a generic struct uses its struct's parameters, and can have parameters of its own, `U Map<U>(...)`. Not components, singletons, events, commands, inputs, scenes, systems, views or handlers: what the engine stores by name and schedules is concrete (a `component Slot<T>` would be an archetype for each instantiation, and a system over it a system for each: left for when a game asks). Not enums. `Pair<int>` and `Pair<float>` are two structs in generated C, `Pair_int`, and the game's layout has an instantiation as a struct of its name, so hot reloading carries a world over field by field as for any struct.
- **Checking a generic with no instantiation.** What doesn't depend on `T` (names, syntax, the shape of calls) checked once with the parameters unbound, so an error that's the generic's own is found with no call of it. Built: none of it; an uncalled generic is parsed only.
- **Constraints** (`where T : ...`) later, as a check at the declaration; Tide has nothing to constrain with yet but the built-in rules (`==`, `<`, hashable), which would be the first.
- **The GPU.** A generic function a frag or a vert reaches is instantiated like any function and written per instantiation, with its C name; a generic struct as a vertex or an instance struct is instantiated the same way. What the GPU refuses of a type it refuses of a type argument, where it's used. Not tested yet.
- **A generic as a `Func` value**, instantiated from the Func's types.
- **Text** shows an instantiation's value with its written name: `Pair<int> { a = 1, b = 2 }`.
- **Editors** (tidels): hover on a generic shows its declaration with `T`, on an instantiation the arguments bound; go to definition goes to the generic from any instantiation; rename renames the generic and every instantiation; completion offers `<` after a generic's name with its parameters as placeholders; the grammar colors a type parameter as a type. Built: none of it beyond what any function has.
- **Recursion of types.** `Pair<Pair<int>>` is fine, and `struct Node<T> { List<Node<T>> kids; }` too, as lists nest. `struct Node<T> { Node<T> next; }` isn't, as no struct holds itself.

<a id="pure-functions"></a>

## Pure functions

Agreed 2026-11-13 and built the same day. The owner asked for purity to be the compiler's to find, used to save repeated work, with remembering across calls something a function opts into. What he decided is under Decided; every other choice is the building agent's, under Provisional.

```csharp
// Pure, with nothing said: it reads what it's handed and gives a value
Box Bounds(Catalog catalog, int part)
{
    mut var box = Box { lo = float3(1000), hi = float3(-1000) };
    foreach (var corner in catalog.parts[part].corners)
    {
        box.lo = Math.Min(box.lo, corner);
        box.hi = Math.Max(box.hi, corner);
    }
    return box;
}

// Two calls with the same arguments in one body: the function runs once
float Width(Catalog catalog, int part)
{
    return Bounds(catalog, part).hi.x - Bounds(catalog, part).lo.x;
}

// Remembered from one call to the next: called again with equal arguments, it doesn't run
cached Box PartBox(Catalog catalog, int part)
{
    return Bounds(catalog, part);
}
```

<a id="decided-10"></a>

### Decided

- **The compiler works out which functions are pure. No keyword says it.** A function is pure when its result comes from its arguments alone and running it leaves nothing changed: it writes nothing outside itself (no `mut` or `out` parameter, no change to the world, no `Send`, `Spawn` or `Destroy`, no write to local state), rolls nothing, reads no `Time`, `Devices`, `Session` or other state that changes by itself, starts no task, and reaches no C (`extern`), in its own code and through everything it calls.
- **Purity is used to save work** (the owner: "If it gets called multiple times with the same inputs in one system, we can cache it once and just use that cached value instead"). Within one system, view, handler or function, repeated calls of a pure function with the same arguments run once.
- **Remembering across calls is opt-in, by a keyword on the function.** Called again with equal arguments, such a function gives the result it remembers without running. On a function that isn't pure the keyword is an error, which names the line that makes it impure.

<a id="provisional-10"></a>

### Provisional

**The word.** `cached`, before the function's type: `cached float4 Eyepiece(Catalog catalog, int def, Box box)`. The owner first floated `pure` for a keyword, then agreed that purity is inferred and remembering is what's opted into; the word itself awaits him. It's contextual, like `async`: a parameter or a local can still be named `cached`.

**What is pure, in detail.**

- A read-only parameter is an argument whatever its type: a number, text, a struct, a list, and a component or a singleton the caller hands over (the function reads the value it was given, not the world). `Time` and `Session` are the exception among singletons, and `Devices` among the rest: they're what the decision names as changing by themselves, so a function that takes one isn't pure.
- A function that takes the `World`, a query, an `Action`, a function value it calls, a texture, a render target, a GPU list or another of this machine's resources isn't pure. Nor is one that reads a local field of a component it was handed, `Frame.dt`, `Random.seed`, the cursor or the screen.
- Reading a constant or an asset is pure: they're the same for as long as the program runs (an asset changed while the game runs counts as a change, see below).
- `Random.NextInt(6)` on the type rolls the match's or the frame's dice, so it isn't pure. A generator of the function's own, `mut var dice = Random(seed)`, is: its rolls come from a seed the function was given.
- A function's own `mut` locals are its own: it can build a list, sort it, change a struct. A `mut` method called on one is fine, though the method itself isn't pure.
- `Debug.Assert` is allowed (it says nothing while it holds). `Debug.Log` isn't: it's something the function does besides giving a value.
- A function that calls only pure functions (and itself) is pure. One that calls a function that isn't, isn't, and the reason given is that function's.
- Methods are worked out the same way; a `mut` method isn't pure, and a component's method that reads its entity isn't. Operators and property getters are methods. `async` functions, workers, `audio` declarations and `extern` functions aren't pure.
- The rule is a list of what's known to be pure, not of what's known not to be: something added to the language later isn't pure until it's put on the list.

**Repeated calls in one body.**

- Two calls are the same when they're the same expression: the same function, and arguments that are the same code, however they're written (`Scaled(x)`, `Scaled(x, by: 2)` and `Scaled(by: 2, x: x)` are one, when 2 is the default).
- The arguments must be values nothing in that body can change: constants, read-only parameters, locals that aren't `mut`, a `foreach`'s variable, fields and elements of those, arithmetic and `Math` on them, struct and list literals of them, and pure calls of them. A `mut` local, a `for`'s own variable, a `mut` parameter and a query's row aren't. In code that sets through the `World`, calls C, starts a task or has a query whose rows it can write, only numbers, text and constants are.
- The first call is worked out into a hidden read-only local just before the statement it's in, and the later ones read it. So it runs where it would have, or a little earlier in its own statement, which changes nothing: it reads nothing the statement writes and does nothing but give its value. Evaluation order is as written for everything else (see Evaluation order).
- A call that may not run (on the right of `&&`, `||` or `??`, in a side of `?:`, in a switch expression, in a `while`'s condition, or a single statement after `if` with no braces) is never the one the others read; it can read one that ran before it.
- The later calls must be in the same block as the first one's statement, or in blocks inside it. A loop's body is a block: two calls in it are one a round. A call inside a loop isn't moved out of it.
- A parallel loop's body, a loop over a query's rows or a grid's cells, and a block passed to a call (a widget's, an `Action`'s) each start over: nothing is shared with the code around them.
- Not merged: calls of a function that `fails` or gives a `T?` (each is unwrapped where it's written), ones that give a grid or one of this machine's resources, and anything in `async` code, workers, build functions, or a function that takes an `Action`.
- **Not in GPU code.** A frag, a vert, a kernel and every function one of them reaches are left as written: the GPU's own compilers merge what they can, and the same function's tree is read for both.
- A debugger sees the hidden locals as `tide_same1`, `tide_same2`.

**`cached`.**

- Each cached function has a table of results, this program's own: in no world, snapshot, packed world or hash, and never sent. Every world in the program shares it (a server and its client, several matches of one dedicated server), which is sound because the function is pure: equal arguments give an equal result whoever asks. A match rolled back, a late joiner and a machine with an empty table all get the values the function would give.
- Arguments are equal when their bytes are: numbers, vectors and plain structs are compared exactly (so `0.0` and `-0.0` are different arguments, which only costs a call).
- Text is compared by two 64-bit hashes of its bytes and its length.
- A list, a map, a set, a grid or text held in a world (a component's or a singleton's, or the whole component or singleton) is compared by its place there and a version of its owner's memory: the hashes the engine keeps of each page of it while the page doesn't change. Nothing of the list is read. Any change to that component's or singleton's lists and text, on any entity, is a new version. Until a tick ends its changed pages have no hash, and a call that reads one runs the function as if it weren't cached.
- A list the code made on the spot (a list literal, a function's result, a `mut` local) has no version, so a call that passes one runs the function. So does a struct made on the spot that holds a list or text.
- This machine's state has no version either: a local singleton's or a local component's lists and text are never hashed, so a call that passes one runs the function. Its numbers are compared like any.
- Getting a version reads a number for each 16 KB the owner holds, so an argument out of a singleton that holds megabytes costs more to look up than one out of a small one.
- An asset's list is compared by its place in the pack and the pack's generation, which changes when an asset is replaced while the game runs.
- A table keeps up to 256 results, in 64 sets of 4 by the arguments' hash; where a set is full, the result used longest ago makes room. No setting changes it.
- A result that holds text or a list is kept in memory of the table's own, and each call that finds it gets a copy, as a call that ran the function would have made one: changing it changes nothing the next call sees. A table of such results lets go of all of them when one of its sets is full.
- Any thread can call a cached function; a set of results has a lock, held while a result is read or stored, never while the function runs. Two threads that ask for the same thing at once may both run it.
- A cached function gives a value (`void` is an error) and can't give a grid. It can't take the game's input, which is two ticks' worth. It can `fail`, give a `T?`, be generic, call itself, and take no arguments (then it runs once).
- A method can't be cached; a function that takes the value can.
- `cached` on a function GPU code calls means nothing there: the call is a plain call.
- Code loaded again (hot reload) starts with empty tables, so no result of the old code is given by the new.

**When it loses.** Looking a result up costs about what a few dozen arithmetic operations do, more for each list-holding argument (its owner's pages are counted) and for a result that's copied out. A function cheaper than that is slower cached. The user page has the measurements.

**Editors.** Hovering a function says whether it's pure, and if not, the first thing that keeps it from being and the line. `cached` shows in its signature.

<a id="open-6"></a>

### Open

- Merging calls that `fail` or give a `T?`, calls on a query's row, and moving a call out of a loop that's sure to run.
- A list made on the spot as a cached function's argument: comparing what's in it.
- Versions for this machine's state, so a cached function can take a local singleton's lists; and one number for a whole owner that says whether anything of it changed, so a big one costs no more to look up than a small one.
- Keeping list-holding results one by one, with the one used longest ago making room, as plain results are.
- `cached` on a method.
- What a table holds and how often it helped, in the stats drawer or `tide schedule`.

<a id="arrays"></a>

## Arrays

<a id="decided-11"></a>

### Decided

- `T[N]` is an array: `N` values of `T`, side by side, in the bytes of whatever holds it. `int[32] cells;` (the owner, 2026-10-06: fixed-length arrays, to avoid a list's indirection; `int[32]` over `Array<int, 32>`).

<a id="provisional-11"></a>

### Provisional

Built 2026-10-06 on that; each point beyond it is a pick, awaiting the owner.

- An array is a value, copied with its struct, and needs no heap: a component's array is lanes of the component, like its other fields, so a system's loop over rows runs with SIMD, and snapshots, hashes, deltas, the world as bytes and hot reloading see component data and nothing new. Hot reloading carries one over by its type's name, `int[32]`: another length is another type, and the field starts over.
- `N` is a constant: a literal, or a constant and operators on them (`int[CAP] cells`), from 1 to 4096; `int[4][8]` is 4 arrays of 8 (`a[i]` is an `int[8]`, `a.count` is 4), and all the lengths together stay under 4096 too. An `audio` declaration's state alone holds a longer one, a delay line, which nothing copies (Audio, A long array).
- Elements are any value but a grid (the owner, 2026-10-29: arrays of text and of lists, "behind the scenes we can have a special case for arrays that point at strings in the heap to not slow down arrays as they are right now. lists too"): numbers, bools, chars, enums, vectors, matrices, quaternions, `Color`, `Rect`, `Entity`, `LocalEntity`, `PlayerID`, text, lists, maps, sets, structs of any of those, and arrays. Not grids or ECS data. Clip and rendering handles, including Sound and structs holding them, are allowed in local collections (agreed 2026-10-30); their existing machine-local rules still apply. Provisional, built 2026-10-29: an array of plain values is unchanged, its holder's bytes alone (lanes, SIMD, inputs, the GPU); an array that holds text, lists, maps or sets keeps their handles in its elements, owned by its holder as a field's are, and copying, assigning, releasing and packing it handles each element. Inputs and GPU code still take no text or lists. No limit beyond arrays' own: generated helpers loop over the elements.
- Writing text or a list where it is (`a[i] = "x"`, `a[i].label = "x"`, `a[i] += "x"`, `a[i].Add(x)` on an array of lists) goes through arrays and struct fields alone; through a list's element or a map's value it's still taken out, changed and put back. A `mut` argument still can't be an array's element.
- An array goes where a plain value goes: fields of components, singletons, structs, events and scenes, locals, parameters and what functions return (copies), a list's elements and a map's values (`List<int[32]>`), a grid's cells. And an input's fields, which a bounded list could never be: `[Clamp]`, `[Min]` and `[Max]` on one apply to every element, and NaN and infinite floats in one are repaired element by element. Not a map's or a set's key. Since 2026-11-14 an array of plain values is a constant too (Constants).
- `a[i]` reads an element, or the element type's zero past the end; `a[i] = v` and `a[i] += v` write one, and past the end do nothing, as a list's do. `a.count` is `N`. `foreach (var x in a)` goes through the elements, each a copy. `a = b` copies the whole array, and `a = [1, 2, 3]` sets it from a literal of exactly `N` values (`default` is all zeros). An element that's an array is changed where it is, `a[i][j] = v`, and so is an array that's an element of a list or a map's value, `rows[i][j] = v`, `buckets[key][j] = v`, through any number of indexes, and a plain field of an element that's a struct, `a[i].x = 1`, `rings[b].cells[j] = v` (see Lists, Changing an element where it is).
- Text shows an array as it shows a list: `[1, 2, 3]`.
- Views don't blend arrays between ticks: an array is seen as it is at the latest tick, as `[Snap]` fields are.
- On the GPU an array is a value too (Views and drawing, Lists and arrays on the GPU). Not sorted, searched or compared with `==`.

<a id="open-7"></a>

### Open

- Blending arrays of floats in views.
- Array constants of text.

<a id="lists"></a>

## Lists

<a id="decided-12"></a>

### Decided

- `List<T>` is a list of values, as a value: assigning or passing one copies it, and changing a copy never changes the original.
- A world keeps its lists in its heap, like text.
- Nothing about lists fails: past the end, a read gives the element type's zero and a write does nothing. A world's lists grow with its heap, and a list that code makes grows with the scratch area, each as far as it goes; a list stops growing at 2,147,483,647 elements (see Limits).

<a id="provisional-12"></a>

### Provisional

- A list starts empty. `[a, b, c]` is a list where one goes, from what it goes into: `List<int> scores = [1, 2, 3];`, `scores = [];`, a field's default, an argument, a constant (`const List<int> QUAD = [0, 1, 2];`, since 2026-11-14: Constants). `var x = [1, 2]` is an error, as it doesn't say the type.
- `count`, `items[i]` to read, `items[i] = x` and `items[i] += x` to write, and the methods `Add(item)`, `Insert(index, item)` (the index clamped), `RemoveAt(index)`, `Clear()`, and for elements that `==` compares (numbers, bools, chars, enums, text, entities, players, and since 2026-11-14 vectors and colors) `Contains(item)`, `IndexOf(item)` (-1 if it's not there) and `Remove(item)`, which returns whether it found one.
- Provisional, awaiting the owner: `Resize(count)` makes the list `count` elements long in one call, as Unity's `NativeList.Resize` does. New elements are the element type's zero: zero bytes, empty text. With fewer, the rest go, and the text they held with them. A count under 0 is 0, and one past what a list holds (see Limits) leaves the list as it is. It changes the list as `Add` and `Clear` do, with their rules: something that can change, not in a parallel loop's step or a `Sort`'s comparison, and not on the GPU. Picked beyond that: its name and its one `int` argument; no `Capacity` or `Reserve` beside it; a list in a world gives back the room it no longer needs, where `Clear` keeps its room for what's added next.
- An element is a copy, as with C#'s List of structs, when it's taken out: a local, a foreach's variable, an argument. A `mut` parameter or a mut method can't change an element in place. But a plain field of an element that's a struct is changed where it is (below, Changing an element where it is).
- Changing a list needs it to be something that can change: a `mut` component or singleton, or a `mut` local.
- Elements are values: built-in types, text, enums and structs, not ECS data (keep an `Entity` instead).
- Components, singletons, structs and events can hold lists; inputs can't. A struct that holds a list, a map or text is a value like any other: a field of a component, a singleton, an event or another struct, a local, a parameter. Copying it copies what it holds.
- A list holds lists, maps and sets as elements, and structs that hold them, at any depth: `List<List<int>>`, `List<Bag>` where `Bag` has a `List<int>`, `Map<int, List<Entity>>`, `Map<string, List<List<int>>>`. Not grids, which are never copied (but in an asset, which is never written: see Assets). A key is still a plain value (see Maps and sets), and so is a grid's cell (see Grids). One rule says what each built-in type takes, the same in the parser and the checker (`generic_forms` in `compiler/src/types.c`): a list's element and a map's value take any value but a grid; a key takes a value with a hash and `==`, of a fixed size; a cell takes a plain value; a `T?` takes any value a function can return; `fails E` takes a value that isn't a `T?`. (Provisional, built 2026-10-06 as the second of the three steps generics take: the owner decided the steps, and that containers nest, 2026-10-06; the picks here await them.)
- An element that's a container is changed where it is: `rows[i].Add(x)`, `rows[i][j] = v`, `rows[i][j] += v`, `buckets[key].Add(e)`, through any number of indexes. `buckets[key].Add(e)` adds the key when it isn't there, as `buckets[key] = ...` does. Past the end of the list it's in, nothing happens, as any write past the end. Not through a struct element's field (`bags[i].parts.Add(x)`): the struct is a copy, taken out and put back, as before. An element isn't sorted in place either: a copy is sorted and put back. (Picked: a slot in the list it's in, where C#'s `rows[i].Add(x)` works because its lists are references.)
- Changing an element where it is (Provisional, built 2026-10-06 with arrays, so that `rings[b].cells[j] = v` costs what the write costs): a field of a struct that's a list's element, a map's value or an array's element is written where it is when what's written holds nothing of the heap (`rows[i].x = 1`, `rows[i].count++`, `rings[b].cells[j] = v`), through fields and arrays' indexes after the first container's. Generated code finds the element's slot and writes into it; past the end nothing happens, and a map's value is added when the key isn't there. A field that holds text or a list, anything in a list or a map inside the element, and a grid's cell are still copies, taken out and put back; a `mut` method on an element still is too. A field read through an element, `rows[i].x`, goes through a pointer at the element, never a copy of it.
- Whatever takes a whole element out of a list copies it, its lists too, so no copy ever reaches what it was copied from: a `foreach`'s variable, a local assigned from an element, an argument (unless a `mut` argument of the same call could change it, as for any list), a map's `Get` or `TryGet`. Reading `rows[i][j]` or `rows[i].count` copies nothing. What a copy costs is the implementation's (Provisional, 2026-11-04): a `foreach` whose body can't change the list or what its elements hold reads each element where it is, with nothing copied, as the variable is read-only and anything taking it elsewhere copies it then; one whose body could (a write to the list or into it, a `mut` call given what holds it, `World.Set`, C, a task's wait) copies each element as it comes to it. A map's or a set's foreach and an array's are decided the same way: a map entry's value, or the whole array as the loop found it, is copied only when the body could change it.
- Text shows them as it shows a list, inside out: `[[1, 2], [3]]`, `[{"a": 1}]`, `[{1, 2}]`.
- Not to C: an extern function's list holds plain values, and a list of lists is refused as a list of text is. Not in a parallel loop's list, whose elements are plain, as text is refused there. Not in an input, which holds no lists, nor a command, whose lists hold plain values (see Commands).
- A snapshot, a hash, a delta and the world as bytes see nothing new: an inner list is a block in the same heap, with its own pages, which they already cover block by block. Hot reloading carries the field over by its type's name (`List<List<int>>`) with the heap, as it carries any list.
- Taking a whole list out of a field or variable copies it; its elements, count, methods and `foreach` don't. A read-only list argument is passed without a copy unless a `mut` argument of the same call could change it.
- Lists in code (not in a world) live in the scratch area, like text.
- `parallel (var i in items) { ... }` goes through a list's elements at once, on threads, as it does a grid's cells (see Grids): its places are the elements' indices, so `i` is an `int`, and the step reads the element as `items[i]`. Each step reads the list as the loop found it and changes only its own element, `items[i]`, so the result is the same on any number of threads. `parallel (var i in items by 2 offset o)` gives each step a block of elements from `i` up to the block's size, which it changes as `items[i + 1]` and the like; blocks start at the offset plus any multiple of their size, and one that would go past the list's end is left out. The step's rules are a grid's: it changes nothing else (not the list's count either: no `Add`, `RemoveAt`, `Resize` or `Clear`), can't end the loop, wait, spawn or send, and so on. A parallel loop over a query's rows can send (see Read-only entity queries).
- A parallel loop goes through a list the world keeps, a component's or a singleton's, or an owned local list in a `local worker`. Its elements are plain values with no text or containers. Ordinary function-local lists retain their existing restriction.
- `items.Sort(a, b) { return a.x < b.x; }` sorts a list, stable, by a comparison written after the call: its two names are the elements it compares, read-only copies of the element type, and the block says whether the first goes before the second, as `return a.x < b.x;`, on every path. Elements the comparison doesn't order keep their order. It runs again and again as the list sorts, in an order nothing promises, so it changes nothing outside it (not the list, not a field, not an outer variable), and can't spawn, send, wait, draw, use the GUI, change scenes or the session, or call C; it reads what it likes: fields, the code's parameters and variables. `break`, `continue` and the comparison's `return` are its own, not the code's around it. It sorts in systems, views, handlers and plain functions, and not yet in methods, async code, functions that take an Action, blocks written after a call other than an Edit's (whose block runs where it's written, so a Sort works there), or the input's code. Merge sort, so the same comparisons in the same order on every machine.

<a id="open-8"></a>

### Open

- Searching with a condition, and sorting by a key.
- Changing a list inside a struct element where it is (`bags[i].parts.Add(x)`), and sorting an inner list in place.
- Blending arrays of floats in views (fixed-size arrays in components are implemented; see Arrays).

<a id="maps-and-sets"></a>

## Maps and sets

<a id="decided-13"></a>

### Decided

- `Map<K, V>` holds values by key, and `Set<K>` keys each once, as values: assigning or passing one copies it, and changing a copy never changes the original.
- A world keeps its maps and sets in its heap, like lists and text (see Lists).
- Nothing about them fails: a key that isn't there reads as the value type's zero, and removing it does nothing. They grow with the heap, as far as it goes (see Limits).
- Going through a map or a set gives its keys in the order they were added, the same on every machine.

<a id="provisional-13"></a>

### Provisional

- A map or set starts empty. `[a, b]` is a set where one goes, from what it goes into: `Set<int> ids = [1, 2];`, a field's default, an argument. `[]` is an empty map where its type is known, including field defaults, assignments, arguments and returns: `Map<int, Stats> scores = [];`. Nonempty map literals are unsupported; add entries one by one. `default` remains an empty map too.
- Keys are `byte`, `int`, `long`, `char`, enums, `Entity`, `LocalEntity`, `PlayerID` or `string`: values with a hash and `==`. Floats aren't keys (key by an int instead), nor are structs (key by one of their fields).
- Values are what a list's elements can be: built-in types, text, enums, structs, lists, maps and sets, and structs with any of them in them (see Lists), not ECS data and not grids. A value that's a container is changed where it is, `buckets[key].Add(e)`, which adds the key when it isn't there; a value read is a copy, as a list's element is (see Lists).
- A map: `count`, `scores[key]` to read (the value type's zero when the key isn't there), `scores[key] = value` and `scores[key] += x` to write (adding the key, or replacing its value), and the methods `Has(key)`, `Get(key)` (the value, or nothing, as a `V?`), `TryGet(key, out value)` (whether the key is there, and its value, or the value type's `default`: C#'s `TryGetValue`, see Out parameters), `Remove(key)` (whether it was there) and `Clear()`. A value read is a copy, as a list's element is, when it's taken out; a plain field of a struct value is changed where it is, `scores[k].x = 1`, which adds the key when it isn't there (see Lists, Changing an element where it is).
- A set: `count`, and the methods `Add(key)` (whether it was new), `Has(key)`, `Remove(key)` and `Clear()`. A set has no values to index.
- `foreach (var e in scores)` goes through a map's entries in the order their keys were added, each a copy with `key` and `value` (an `Entry<K, V>`, named by `var`); `foreach (var k in ids)` goes through a set's keys. Entries added while going through are reached too; removed ones aren't.
- Text shows maps as `{1: "a", 2: "b"}` and sets as `{1, 2}`, the keys in their order.
- Changing a map or a set needs something that can change: a `mut` component or singleton, or a `mut` local. Systems that change the same component's or singleton's maps wait for each other, as they do for its text and lists: each one's are in a heap of its own.
- Components, singletons, structs and events can hold maps and sets, and so can lists and other maps, as values (see Lists); inputs can't, nor grids' cells. They don't go to C.
- How they're kept (`tide/map.h`): a map is two lists in the heap. Its entries, each a live flag, the key and the value, in the order they were added, a removed one left dead in its place until more than half are dead, when adding a key packs the live ones together; and an index, a power of two of slots by the key's hash, kept under half full. So an entry's bytes depend on nothing but what's in it, and the same adds and removes give the same bytes on every machine.

<a id="open-9"></a>

### Open

- Map literals, `[1: "a", 2: "b"]`.
- Struct keys, and keys by several values.

<a id="grids"></a>

## Grids

<a id="decided-14"></a>

### Decided

- `Grid2<T>` and `Grid3<T>` hold cells at `int2` or `int3` positions. They're fields of components, singletons and scenes, so a world can have many: a dimension per scene, a canvas per player, a grid per ship.
- A grid keeps its cells in chunks, and a chunk only exists once a cell in it is set to something other than zero: everywhere else reads as zero, so an open grid costs what's in it, not the space it spans. A world and its snapshots share chunks until one of them changes one, and hashes cover each chunk on its own.
- A grid's size is given when it's made, `Grid2(1024, 1024)`. An axis given 0, or left out, is open: any int, negative ones too. Past its size, reads give zero and writes do nothing.
- `parallel (var at in cells) { ... }` goes through every cell of a grid at once, on threads. Each step reads the grid as the loop found it and changes only its own cell, so the result is the same on any number of threads, and the order the steps run in never shows. Code after the loop runs once every step is done.
- `parallel (var at in cells by 2 offset o) { ... }` goes through blocks instead: each step has the block of cells from `at` to `at + 1` on each axis (`by int2(2, 1)` sizes each axis), changes only those, and reads any cell. Blocks start at the offset, an int or an `int2`/`int3` given each time, and never overlap, so cells can move within a block: sand falls and slides in 2 by 2 blocks whose offset goes 0, 1, 0, 1, so each cell is in another block the tick after. A block that would go past a grid's size is left out, so along a sized edge, cells are only in the blocks of some offsets.
- `foreach (var at in cells) { ... }` goes through a grid's cells in order, in place, as C#'s would: rows from the first, each from its lowest x, and each step sees what the ones before it changed. When nothing a step does depends on the others (it changes only its own cell, and nothing outside the loop), its steps run at once instead, with the same result.
- `for` loops stay in order.
- There are no chunk systems: a system takes the grid's component or singleton like any other, and goes through the cells with a loop.

```csharp
singleton Field
{
    Grid2<int> cells = Grid2(512, 512);
}

// Ones fall a cell a tick, in blocks of a cell and the one above it, from
// even rows one tick and odd ones the next
system Fall(mut Field field, Time time)
{
    parallel (var at in field.cells by int2(1, 2) offset int2(0, time.tick % 2))
    {
        if (field.cells[at + int2(0, 1)] != 1 || field.cells[at] != 0) continue;
        field.cells[at] = 1;
        field.cells[at + int2(0, 1)] = 0;
    }
}
```

<a id="provisional-14"></a>

### Provisional

Implemented on the owner's go-ahead, to be revisited once games use them:

- Cells are plain values: numbers, bools, chars, enums, vectors, quaternions, matrices, `Color`, `Rect`, `Entity`, `PlayerID`, and structs of those. Not text, lists or grids, which say to keep them elsewhere and a number for them in the cell.
- `cells[x, y]` is `cells[int2(x, y)]`, and `cells[x, y, z]` is `cells[int3(x, y, z)]`. `cells.size` is the grid's size, 0 on open axes. `cells.Clear()` sets every cell back to zero and keeps the size; `cells = Grid2(...)` gives the field a new, empty grid; `cells.Copy()` is a grid of its own, with the same size and cells.
- A cell is a copy, like a list's element: `cells[p].heat = 1` is an error that says to take it out, change it and put it back. `cells[p] += 1` works on numbers. Setting a cell to zero where there's no chunk makes none.
- **Grids are values code owns, the same in all code** (the owner, 2026-11-03, with build code's rework: "yes" to grids working this way in all code, as `build` must not make code behave differently). A grid is never copied without saying so: a field, a local or what a function returns takes a grid of its own, never another's.
  - A local can hold a grid of its own: a new one (`Grid2(...)`), a copy (`cells.Copy()`), or what a call returns. `mut Grid2<int> made = Grid2(64, 64);` is written as a field's is; one that isn't `mut` is read-only. Assigning a local a grid another place has (`var copy = field.cells;`) is an error that says to copy it.
  - A function can return a grid: a new one, a copy, what a call returned, or a local of its own, which it's done with. Returning a parameter's or a field's grid is the same error. A task, an operator, C, a worker and code the GPU runs can't return one.
  - A field takes a new grid, what a function returns, or a copy: `terrain.heights = Ramp(64);` gives the field that grid's size and cells, the world's own. Its default is still a new grid.
  - A function can take a grid, `mut` or not, as any value: one it reads, and with `mut` one it changes where it is, a field's or a local's (`Border(terrain.heights, 9)`), whose writes count as the caller's, as any `mut` argument's do. A grid can't be an `out` parameter. A worker reads its grid parameters and code the GPU runs reads them where they are, as before; neither takes one `mut`.
  - `cells.Copy()` is a grid of its own with the same size and cells, of any grid: a field's, an asset's or a local's.
- **How a grid code owns is kept** (Claude's picks, 2026-11-03): in the scratch area, as a local's list is, gone when the system, view or handler that made it is done, and copied into the world when a field takes it. So a parallel loop goes through a world's grid, a component's or a singleton's, not a local's or a parameter's (an error that says so; a foreach over one goes in order), a lambda can't capture one, and a task keeps one across its waits as a copy of its own in its frame, as it keeps its text and lists (Provisional, Claude, 2026-11-14: Grids a task keeps across its waits). A worker still reads only its captured grid parameters: its code keeps no grid in a local.
- **Grids a task keeps across its waits** (Provisional, Claude, 2026-11-14, as the owner asked that every gap that can be closed is: "make sure everything we can add or validate we do"): a grid a task holds as it waits (a local's, a name `is` gives, a failable or `T?` local holding one, and a value an earlier `await` of the same statement gave, as in `(await a.Read())![0, 0] + (await b.Read())![0, 0]`) goes into its frame as a copy of its own, in the task's world's heap, as its text and lists do. After the wait the task reads the frame's copy where it is, and the first change it makes (a cell set, `Clear`, `Decode`, a `mut` argument) makes it a copy of the task's own again, so a grid kept unchanged across many waits is copied once. A grid the task didn't make (the pack's, as a `foreach` over an asset `List<Grid2<Color>>` gives, or a field's read before the wait) is copied whole, so the frame never holds the pack's memory, which a hot reload can take away. A value an `await` gave is the statement's: once the statement that awaited it is done (a `var r = await t.Read();`, an `if (await t.Read() is Grid2<Color> pixels)`'s condition) only the local or the name it went into is kept, so a read kept across later waits is one copy, never two. A `foreach` over an asset in a task reads the asset where it is each round, as an index loop does: after a pack loaded again while it waits (tide run loads one as a file is saved), it goes on through the new pack's, from the place it had reached (what it held as it waited, its loop variable, is its own copy of the old one's). A `foreach` over a list or a map of grids worked out from assets (`foreach (var frame in fast ? run : walk)`, a `switch` choosing one) keeps that list in its frame as it waits, a list of its own whose every grid is a copy of its own, and goes on through it. Weighed for the asset's: keeping a copy of the whole asset in the frame (every frame of an animation copied as the task first waits, for a loop that reads one a frame), and refusing a wait in such a loop (what the Mesh's rule does, for a Mesh the pack keeps). A match task's grids are in the match's heap: snapshots, packed worlds and the world's hash take them in with everything else. A grid no local in scope holds goes back to the heap at the next wait. Weighed: refusing every wait while a grid is held (what was built first, the same day; it refused a `foreach` over an asset's frames with a wait in it, and missed the grid of an earlier `await` in the statement and a failable local's, which then went through freed memory), and copying at every wait as lists are (which would copy a 4K read's 127 MiB once a frame for a task that waits a frame at a time).
- **Grids an async function takes** (Provisional, Claude's picks, 2026-11-15, for `bench/voxels`' mesher, which kept its neighbours' sides in lists for want of it): an async function takes `Grid2<T>` and `Grid3<T>` parameters, a local task's, a match task's and an async function's a task awaits alike. Each is a copy of the task's own in its frame, made where the call is, by the rules of the grids a task keeps across its waits (above): so what the caller changes after the call (a cell set, `Clear`, the field given another grid) isn't the task's; the task reads its copy where it is after each wait, however many, never copied again; a grid the caller didn't make (a world's, the pack's) is copied whole, so the frame holds none of the pack's memory; and a task it starts or awaits with the grid gets a copy of its own. A match task's copy is in the match's heap, so snapshots, packed worlds, the world's hash, rollback and a hot reload's migration hold it as they hold the frame's other grids; a local task's is in the local state's. The parameter is read-only: a task's `mut` parameters are its components and singletons alone (Tasks), so `mut Grid2<int> cells` on an async function is an error that says to drop `mut` or take the component or singleton the grid is in. A task still can't return a grid. Weighed: taking the caller's grid where it is, as a synchronous function does (a task's code after its first wait runs ticks or frames later, when the caller's grid can be gone or changed, and a match task would hold a handle the caller's field gives back); copying it at the first wait rather than the call (the code before the first wait runs inside the caller, so the two differ only where the task's first segment changes the caller's grid through its component, and the call's copy is what a reader expects).
- `Grid2(...)` takes its cell type from where it goes: a field, a local's type, a parameter or what a function returns; anywhere else it's an error that says so.
- A chunk is the engine's: 4096 cells (64 by 64, or 16 by 16 by 16 in 3D), or for cells bigger than four bytes, as many as fit in a page (16 KiB), a power of two along each axis, the first axes the most.
- A loop over a grid with a size on every axis goes through every cell within it. An open axis goes on forever, so there a loop goes through the cells of the chunks the grid has, where something was set: in blocks, every block that takes in part of one. A foreach over an open grid goes through them in the same order, rows from the first, skipping what has no chunk.
- A parallel loop's step changes only its own cell or block, `at` plus constants (`at + int2(1, 0)`, `int2(at.x + 1, at.y)`), and the variables it declares. Anything else it changes is an error that says why: a variable outside the loop (to add up, use a `for` loop or a foreach that goes in order), another cell, the whole grid (`Clear`), through a `mut` argument too. It can't `break` out of the loop (`continue` ends the step), return, wait, start tasks, spawn, send, add, remove or destroy, load scenes, draw, use the GUI, or hold another parallel loop. It can call functions, and C.
- A block is 1 to 64 cells along each axis, a size known while compiling: a constant int, or `int2`/`int3`. The offset can be any int: blocks start at it plus any multiple of their size, so with blocks of 2, an offset of 2 gives the same blocks as 0.
- An open axis ends where the ints do. A block that would go past the last int is left out, as one past a grid's size is, so no block's cells wrap around; a step that reads past that edge, `cells[at + int2(1, 0)]` at the last int, reads the cell its own arithmetic wraps to, as an int wraps anywhere else. A foreach reaches the cells at both ends. (Picked while testing that no loop can go wrong there: see Open, at the end.)
- A parallel loop goes in a system, a view, a synchronous event handler or a `local worker`: not in ordinary functions, methods, async code or an input's `Sample`. A grid foreach there whose steps are independent runs at once; anywhere else, it goes in order. Worker grid inputs are read-only; explicit parallel loops in workers write owned lists and may read those snapshots.
- A foreach over a grid can't wait inside it: it goes through the cells as they are.
- Each step writes into a copy of its chunk, made from the chunk as it was, and the loop's end puts the copies into the grid in order, chunk by chunk, so where the steps ran never shows. The schedule says how many parallel loops each system has: `(once, 2 parallel loops)`. A tick with one runs on threads, and the loop's steps spread across them when there are enough to be worth it.
- Hosts read a world's cells with `tide_grid_read(&w->heap, w->Field.cells, x, y, 0, &tide_shape_Grid2_int)`: the generated header names each grid type's shape.
- Text can't show a grid.
- **A per-entity system that changes its own entities' grids splits across threads** (Claude's picks, 2026-11-14; nothing a game's code can observe, as parallelism never changes results), as one that changes their text and lists does: cells set, set to zero, new chunks, a grid replaced (`= Grid3(16, 16, 16)`, `= other.Copy()`, a function's), `Clear`, and a parallel loop over the row's own grid. The world is the same bytes as on one thread on every machine, hashed, packed, in snapshots and deltas. What keeps one on one thread is what keeps text and lists there: an owner C can write, or a game with shards (a game with hidden state is as any other since 2026-11-14: State visibility, Provisional). Picks: a grid's directory and chunks stay in one heap, so a row that adds a chunk to a grid made while its entity was in another run moves the grid whole first (a copy of what it has, once); and a system in runs whose rows queue nothing (no spawn, send, add, remove or destroy) puts each entity in a run by its identity rather than by its place in the order, so entities spawned last (new chunks to make) are spread over the threads, and an entity's grids never move between such systems or ticks. One whose rows queue keeps runs that are shares of the order, as its queued changes go in that order. Where such a system starts with tests that return (`if (...) return;` on its own rows' fields) and they let at most a quarter of its entities through, its runs and its threads' shares are of the entities they let through, in the same order (Claude's pick, 2026-11-16): chunks spawned together are next to each other in the order, and would all be one thread's.
- **Grids as bytes** (Claude's picks, 2026-11-14, for the server's store, commands and files: `bench/voxels` wrote loops over every cell for it, slower and its own):
  - **The calls.** `cells.ToBytes()` is a `List<byte>` of any grid, a world's, a local's or an asset's: its size and its cells. `Grid3<Block>.FromBytes(bytes)` (and `Grid2<T>.FromBytes`), the grid type's own as `string.FromBytes` is text's and `Mesh<V>.Decode` a mesh's, gives `Grid3<Block> fails IOError`: the grid those bytes are, a grid of its own as `Grid3(...)` makes one, which a field takes, a local holds and a function returns, unwrapped as any result is (`??`, `is Grid3<Block> got`, `!`, `try`). An alias of a grid type takes it too (`Blocks.FromBytes(bytes)`). `Grid3.FromBytes` with no cell type, `FromBytes` on a grid value and another name on the type are errors that say what to write. No clash with `grid.Decode(bytes)`, which reads a PNG into a `Grid2<Color>` field where it is.
  - **Where.** Both are pure: any CPU code calls them, match code (the same bytes and cells on every machine) and local code alike; code the GPU runs can't (an error that says so). What they make is in the scratch area, as any list or grid code makes.
  - **The bytes** (format 1, `tide/grid.h`): `'G'`, `0x10 | dims`, then varints (unsigned LEB128): a cell's bytes, the size along each axis (0 where it's open), how many chunks follow; then each chunk: its place in chunks less the one before's, a zigzag varint along each axis, chunks in order (by z, then y, then x), and its cells in the order a chunk keeps them (x fastest) as tokens until the chunk's are all there: a varint `t` that says `(t >> 1) + 1` cells, with `t & 1` the one cell that follows that many times, else that many cells as they are. A cell is its bytes as every machine Tide runs on keeps them (little-endian); a chunk's geometry is the one a cell of that size has (Provisional, above).
  - **Compact.** Only the chunks with a cell that isn't zero are written, a cell outside a sized grid's size as zero, and runs of three cells or more of one byte (two or more of a bigger cell) as one token: a 16-cube of air is 7 bytes (the header), of one block 13, a layered chunk of ground a few hundred, one with no two cells alike for long about its cells.
  - **The same cells are the same bytes**, however the grid came to have them (in another order, with chunks set and set back to zero), on every machine and thread count: what `ToBytes` writes is a function of the cells alone, each written as `FromBytes` reads it (below), no padding as it was, and no pointer or heap offset. `FromBytes` then `ToBytes` gives the bytes back.
  - **Any bytes are safe.** `FromBytes` fails with `IOError.InvalidData`, the grid made of them dropped, for bytes that aren't a grid of that type's cells: another tag or dims, a cell of another size, a size past the ints, a varint too long, fewer bytes than they say or more after their end, more chunks than the bytes could hold or a sized grid has, a place outside a sized axis's chunks or past what an int can say, a chunk not after the one before (so no place twice), a run past a chunk's cells, and on an open axis places chosen to collide in the directory's hash (a chunk whose slot would be more than 256 past the one its place's hash gives, in a table at most half full: no other places come near). Nothing reads past the bytes or writes past what it made, and the work is the bytes' and the cells', bounded. A read makes `TIDE_GRID_BYTES_MOST` (256 MiB) of cells at the most, as `grid.Decode`'s limit is: bytes that say more are refused before any chunk is made, and the log names the limit (`tide: Grid3.FromBytes refused bytes: they have ... chunks, ...`). A chunk the bytes give that's all zeros isn't kept, nor a cell outside the size.
  - **What a cell's bytes say that no value is, is that part's zero**, as an input's NaN is its default: a float or a double that isn't finite, a bool's byte that's neither 0 nor 1, a char that's no character (past U+10FFFF, or half of a UTF-16 pair), an enum's number that's none of its members (a command's rule: an enum that kept such a number, `Block(200)`, is written as its zero too), padding, and a `T?` field whose `ok` is false (all zeros) or neither (taken as false). Everything else is what the bytes say, as any bytes are one of its values: numbers, vectors and matrices of ints, and **entities and players**: an `Entity` or a `LocalEntity` is its logical identity, which a lookup compares whole (one that's gone, or never was, is found nowhere), and a `PlayerID` is its number, as a command carries both.
  - **The bytes say a cell's size, not its type.** A grid's bytes read as another type with cells of the same size are that type's values of those bytes, repaired as above.

<a id="open-10"></a>

### Open

- Generating chunks as they're first needed, keeping the regions around players loaded, and sending each player only theirs: an endless voxel world. `bench/voxels` does it today with chunks as entities, a grid each: made as players come near, each player sent only theirs (State visibility), and kept in the server's store while nobody is near (The server's store, Provisional); farther off, far regions, entities of their own with a wider audience than the chunks', summarise what players built, a column's top at a time (2026-11-15). That's Claude's pick for the game, not a decision about grids; `notes/voxels.md` says what it measures.
- Functions that take grids; parallel steps that spawn and send.
- Skipping what's settled: a parallel loop that only runs where something near changed (what `[Sleeps]` did for chunk systems).
- `for` loops that run at once when nothing a step does depends on the others.
- Resizing a grid; drawing one.
- Grids as bytes: reading bytes of another chunk geometry (a future format's), and naming the cell type in the bytes, so a grid's bytes read as another type with cells of the same size fail rather than be reinterpreted. A field given what `FromBytes` read copies its cells a second time (into the scratch area, then the world).
- An open grid's directory finds chunks by a fixed hash of their places, so places chosen to collide make lookups walk the ones before. `FromBytes` refuses bytes that crowd one chunk's slot (above), and a world's own open grid doesn't refuse such places as code sets them, so the bytes of a grid filled at places a player chose can be refused when read back, though `ToBytes` wrote them: keep such a grid's places to what the game expects (a chunk's own few). Places can still be chosen to sit side by side in the table, each near its own slot, so that a lookup of a place with no chunk walks them all, and a game's own code can make either. A grid read from a player's bytes is best checked for the size the game expects (`got.size`) before it's kept. The places of a sized grid of up to 65,536 chunks are looked up by index.

<a id="errors"></a>

## Errors

<a id="decided-15"></a>

### Decided

- Errors are values, never exceptions. An error is any type: usually an enum, a struct when it needs to carry more.
- A function says it can fail with `fails`, and `fail` ends it with an error, as `return` does with a value. A function with no value works the same: `void Open() fails OpenError`.
- The combined type, a value or an error, is never written: `var` holds it.
- At the call: `var score = ParseScore(text) ?? 0;` falls back to a value, `if (ParseScore(text) is int score) { ... }` runs only on success, `if (ParseScore(text) is ParseError why) { ... }` only on failure, and `var score = try ParseScore(text);` passes the error on to the caller.
- `try` only works inside a function that `fails` with the same error type. In a system it's an error, since systems have no caller: handling happens at the call.
- `T?` is for lookups where absence isn't an error: a value or nothing, unwrapped the same way (`??`, `is`).
- A field can be a `T?` (the owner, 2026-10-11: "we have optional types or whatever but not fields which is very weird; so we need to add those for consistency"): `int? target;`. How one behaves in each place a field goes is under Provisional, T? fields.
- Postfix `!`, as in C#, after the expression (`ParseScore(t)!`), means: on failure, carry on with the type's default value (0 for int), never crash. It also silences the warning for ignoring an error.
- Using a failable call's value without unwrapping it is a compile error whose message says how to unwrap it (`??`, `is`, `!`, `try`). Calling a failable function as a statement and ignoring its error is a warning, which `!` silences.
- Forgiving defaults stay as they are for indexing, arithmetic and text. Asynchronous failures stay events (`Disconnected`).

```csharp
enum ParseError
{
    Empty,
    NotANumber,
}

int ParseScore(string text) fails ParseError
{
    if (text == "") fail ParseError.Empty;
    mut var score = 0;
    for (var i = 0; i < text.length; i++)
    {
        var digit = "0123456789".IndexOf(text.Substring(i, 1));
        if (digit < 0) fail ParseError.NotANumber;
        score = score * 10 + digit;
    }
    return score;
}

int Doubled(string text) fails ParseError
{
    var score = try ParseScore(text);
    return score * 2;
}

int? Find(List<int> items, int wanted)
{
    for (var i = 0; i < items.count; i++)
    {
        if (items[i] == wanted) return i;
    }
    return null;
}

system Score(mut Board board)
{
    board.points = ParseScore(board.typed) ?? 0;
    if (Doubled(board.typed) is ParseError.NotANumber) board.mistakes += 1;
    if (Find(board.picks, 3) is int at) board.last = at;
}
```

<a id="provisional-15"></a>

### Provisional

- `fail`, `try`, `is` and `null` are keywords everywhere; `fails` is one only right after a function's parameters.
- Methods can fail too. Operators, `Interpolate`, extern functions and functions that take an Action can't. Systems, views, handlers and the input's `Sample`, `Sanitize` and `Predict` can't fail, and can't `try`.
- An error's type is one a function can return. It can't be the type the function returns, which `is` couldn't tell apart, nor a `T?`, and a function that fails can't return a `T?` too.
- `try` binds like a unary operator, as C#'s `await` does: `try Parse(a) + 1` adds 1 to the value. It works on a variable that holds a result too, and as a statement: `try Open();`. It keeps its place in the evaluation order: what's before it in its statement runs first, and when it passes an error on, nothing after it runs. In a block written after a call, `try` and `fail` leave the function the block is written in, as `return` does. Leaving a function this way closes the GUI containers it opened.
- `??` binds and groups as in C#: looser than `||`, tighter than `?:`, to the right. Its right side only runs when the left fails or is nothing, so, like the right side of `&&` and `||`, it can't spawn, load scenes or draw widgets. The right side takes the value's type (`?? []`, `?? default`), an int widens to a float (`ParseScore(t) ?? 0.5` is a float), and it can be another failable call or `T?`, which is then what the whole gives: `a ?? b ?? 0`.
- `is` is relational, as in C#. After it goes the value's type (true when it succeeds, or a `T?` has one), the error's type (true when it fails), or one of an error enum's members, `is ParseError.Empty` (true when it fails with that one). Tide has no other type tests: `is` on a plain value is an error.
- A name after `is`'s type declares a read-only local. It goes in the condition of an `if`, `while` or `for`, alone or joined with `&&`, and is in scope in the rest of the condition and where it's true: the `if`'s body (not its `else`), or the loop's body and a for's step. Elsewhere `is` takes no name.
- `!` gives the type's default as `default` does: a struct's field defaults. A `T?` takes `!` too. `F()!;` and `try F();` are statements, for functions with no value.
- `var` holds a failable call's result or a `T?` as it is, and a `mut var` can take another of the same type. A result can't be passed, returned (that's `try`), shown in text or compared; it's unwrapped first.
- `T?` goes on functions' and methods' return types and parameters, on locals, `int? best = null;`, and on fields (below). Not on system parameters, and not as what a list, a map, a set, a grid or an array holds. `null` and `default` are nothing, and a value converts to a `T?` by itself, as in C# (an int to a `float?` too). `x == null` and `x != null` tell whether it's nothing. C functions can't take or return one.
- The warning for ignoring an error is on a statement that calls a failable function; `try` and `!` handle it.
- Editors show a failable call's result as `int fails ParseError`, and offer `fail` and `try` in functions that fail.
- In generated C, a failable call's result and a `T?` are a small struct, `tide_result<n>`: the value, the error and whether it succeeded, plain data with no padding the compiler adds. A zeroed one is nothing. Results never go in the world, so snapshots never hold one: a `T?` field is kept another way (below).

<a id="provisional-t-fields"></a>

### Provisional: T? fields

Built 2026-10-11. That a field can be a `T?` is the owner's (Decided, above); each rule here is Claude's pick, awaiting them:

- **Where.** A field of a struct, a component, a singleton (the match's and a local one), a scene, an event, a local event, a command and the input, and a `local` field of the match's: wherever a field of `T` goes, by the same rules. So an input's can't be a `string?` (an input holds no text), a command's can't be a `List<int>?`, and an array's or a grid's struct can't have a `string?` field: each says what it says of the `T`.
- **What `T` is.** Anything the field could be without the `?`, but a grid (always there, empty until a cell is set) and a rendering resource or a `Clip` (`default` is the one that's none), each an error that says to drop the `?`. A `List<T>?`, a `Map<K, V>?` and a struct that has `T?` fields of its own are fine: an empty list is not the same as none.
- **Nothing by default.** A field with no default starts with no value, whatever its type's defaults are, and so does one a struct's value leaves out (`Slot { }`). It takes a default as any field does, a constant of `T`, or `null`: `int? level = 3;`.
- **Written and read as any `T?`.** It's assigned a `T`, another `T?` or `null` (`default` too), in a statement and in a struct's value (`Slot { item = 3 }`), and read with `??`, `is`, `!`, `== null` and `!= null`, or into a `var`, which holds the `T?`. Used as a value without unwrapping it is the error it is for a local, which names the field. A method reads and writes its own by their names. What needs a variable to change doesn't take one: a `T?` field can't be a `mut` or an `out` argument (pass a local and assign it after), and has no compound assignment or `++`.
- **`T??` isn't a type** (there's one nothing), an error where it's written. Nor is a `T?` what a list, a map, a set, a grid or an array holds, `List<int?>`, each an error that says how: a struct with a `T?` field goes there, `struct Slot { int? item; }` and `List<Slot>`, and its field is read and written where the element is (`slots[i].item = 3`), as any field of an element.
- **As text**, a struct shows a `T?` field's value as it shows any, or `null`: `Slot { item = null, label = "one" }`. A `T?` itself isn't shown, as for locals: `$"{slot.item ?? 0}"`.
- **Its text and lists are its holder's own**, as a field's are: in the world's heap for a component's or a singleton's, the local world's for local state, and the scratch area for a value code made. Reading a field that holds a list (or a struct with one) gives a copy, as taking any such value out of a place does. A field left with no value keeps nothing: its text and lists go back to the heap.
- **Views** see a `T?` field as the later of the two ticks has it, a value or nothing: it snaps, where a float beside it blends. `[Position]`, `[Rotation]`, `[Clamp]`, `[Min]` and `[Max]` don't go on one.
- **In the match** a field with no value is all zeros, whatever it held before, padding included: two worlds that differ only in what a field held before it was taken away have the same bytes there, and where the value keeps nothing in the heap, the same hash. (A heap that gave text or a list out and took it back is as it is after any text or list.) Nothing else of the match changes: a game with no `T?` field generates the C it did, byte for byte.
- **On the wire.** A world's fields go as its bytes do, whole or as what changed. In a command, and in an input sent whole, a `T?` field is a bit, then its value only when there is one; in an input sent as what changed, its value's change and whether having one flipped, a bit each while nothing changes. An input that arrives with no value but bytes beside it is zeros before `Sanitize` sees it.
- **Hot reloading** carries a `T?` field over by its name as what it is, a value or nothing: one with no value isn't given its declared default again. A field that was a `T` and is now a `T?` (or the other way) starts over at its default, as any field whose kind changed does.
- **JSON** is under JSON: `null` and a key left out are no value, and a field with none is left out of what's written.
- **Code the GPU runs** has no values that may be missing. A component or a singleton with a `T?` field is read there for its other fields, the field itself is an error, and a struct that has one (or holds one that does) isn't a GPU value at all, nor a mesh's vertex: each an error that names the field.
- **C.** A struct with `T?` fields goes to an `extern` function as any struct does, by the same rules. In the generated header a `T?` field is a struct of its own, `tide_optional_<T>` (`tide_optional_int`, `tide_optional_float3`, `tide_optional_Combat_Stats`; text is `tide_optional_string`): `value`, as the field would be without the `?`, then `bool ok`, then padding written out. C that takes one `mut` keeps the rule the compiler does: with `ok` false, everything else is zeros.

<a id="open-11"></a>

### Open

- Built-in calls that fail, like `Session.Open()` when it can't take players: today Session calls are requests the host acts on after the frame, so their failures come later, as events.
- `is not`, as in C#'s `if (ParseScore(t) is not int score) return;`, which keeps the name in scope after the `if`.
- `T?` as what a list, a map, a set, a grid or an array holds (a struct with a `T?` field goes there today), and `??=`.
- A `T?` field as a `mut` or an `out` argument, and `cond ? value : null` where a `T?` goes (an `if` writes it today).
- Whether a view should blend a `T?` field's value between two ticks that both have one.
- A hot reload that carries a `T` field over to the `T?` it became.
- `switch` on an error, and functions that take an Action failing.

<a id="local-files"></a>

## Local files

- `File.Exists(path)` and `Directory.Exists(path)` return bool. `File.Create(path)`, `WriteAllText(path, text)`, `AppendAllText(path, text)`, `WriteAllBytes(path, List<byte>)`, `Copy(source, destination[, overwrite])`, `Move(source, destination[, overwrite])` and `Delete(path)` return void and fail with `IOError`. `File.ReadAllText(path)` returns string; `File.ReadAllBytes(path)` returns `List<byte>`, both failing with `IOError`.
- `Directory.CreateDirectory(path)` creates parents and succeeds if the directory already exists. `Directory.GetFiles(path[, recursive])` and `GetDirectories(path[, recursive])` return `List<string>` of full paths sorted by UTF-8 bytes. `Directory.Move(source, destination)` refuses an existing destination. `Directory.Delete(path[, recursive])` requires recursion for nonempty directories. All fail with `IOError`; recursion and file overwriting default to false. Native recursive traversal does not follow directory links.
- `IOError` is a built-in enum: `None`, `NotFound`, `AlreadyExists`, `AccessDenied`, `InvalidPath`, `NotDirectory`, `DirectoryNotEmpty`, `OutOfSpace`, `StorageUnavailable`, `InvalidData`, `Failed`, `TimedOut` (a request's own time limit; Provisional, below). Missing file deletion succeeds. Text is strict UTF-8; an empty file is successful, while invalid UTF-8 fails. File creation truncates contents, writes replace contents, and neither creates parent directories.
- `Application.title` is the game's `title` setting, or the program's name without one: text the same in every build of the game, which match code may read too. `Application.persistentDataPath` and `Application.temporaryCachePath` are read-only runtime strings. The standard host selects save locations using the stable `appId` setting, or its game name as the development fallback. Relative paths resolve under the persistent root. Native absolute paths follow OS permissions; web paths stay in this game's virtual persistent and temporary roots.
- File/directory calls and application paths are local only, including helpers that reach them. They cannot run in match code, input sampling, GPU code, sort comparisons or parallel steps. Pure `Path.Combine(a, b)`, `Path.GetFileName(path)`, `Path.GetDirectoryName(path)` and `Path.GetExtension(path)` work on text, recognize both path separators and can run in match code.
- `await Storage.Flush()` is a local async operation returning void and failing with `IOError`. It confirms that changes preceding the call have committed, without blocking the frame loop. Browser files are preloaded from IndexedDB before the game starts, and mutations commit in the background. Files and pending commits belong to the page across hot reloads; failures retain dirty changes for a later flush to retry. Unavailable persistence is an error, while temporary files remain usable. Browser saves are scoped to the origin/profile and may be cleared or evicted. Flush during play, never rely on page shutdown. Native flushes affected OS files and directories.
- `await request.Send()` sends a request built from `Web.Request(url)` (the owner, 2026-10-11: a general request primitive for Tide, "only makes us more capable", and its shape, a builder: "`request(url).SetBody(...).SetHeader(sss, sss)` etc. ... `SetMethod` etc"). Provisional, the rest:
  - `Web.Request(url)` gives a `WebRequest`, a struct of the language's own with `url`, `method` (`"GET"`), `headers` (a line each, `Name: value`) and `body` (`List<byte>`), and `SetMethod(method)`, `SetHeader(name, value)`, `SetBody(bytes)` and `SetTimeout(seconds)` each give the request with that changed. It's a value: nothing is changed where a call is written, so a kept request is built on by assigning, and its fields can be set directly.
  - `await request.Send()` is local and awaited, as `Web.Fetch` is, and gives a `WebResponse` (`int status`, `List<byte> body`) for an answer of any status. It fails with `IOError` only when no answer came: `InvalidPath` for a URL that isn't `http://` or `https://`, `InvalidData` for a request that can't be sent as written (a method that's no word of letters, or `CONNECT`, `TRACE` or `TRACK`; a header's name that's no token, or a value beyond printable ASCII and tabs; a body past 64 MiB), `Failed` for the rest. Answers have no headers yet.
  - **A time limit** (built 2026-10-11; the builder's shape is the owner's, the rest a pick): `SetTimeout(seconds)` sets the request's `timeout`, a `float`, the seconds its whole answer may take, from `Send` to the body's last byte, redirects among them. `Send` fails with `IOError.TimedOut`, a member added for it, when that passes first. It's a member in a program that has a request (one that names `Web.Request`, `WebRequest`, `WebResponse` or `IOError.TimedOut`), so a game with none is the game it was. 0 or less (and no number) is no limit, which is what a request has until it's set: nothing times out that didn't ask to, and nothing is tried again. Past 1,000,000 seconds is that long. The time is this machine's own, by a clock that never steps back, so a limit is local, like the request. What timed out is stopped: natively its thread ends wherever it was (connecting, the TLS handshake, sending, receiving; one inside the system's name lookup ends as that returns), and on the web the page aborts it. `Web.Fetch` has none: `Web.Request(url).SetTimeout(seconds)` is the fetch with one.
  - `Host`, `Content-Length`, `Connection` and `Transfer-Encoding` are the sender's, and left out of what a request says. A line break in a header's name or value is a space. Redirects follow a browser's rules (a 303, and a POST's 301 or 302, become a GET; a 307 or 308 repeats the request), 5 at the most.
  - The two types are Tide source that comes with the compiler, compiled with a program that names `Web.Request`, `WebRequest` or `WebResponse` and with no other: a program without them generates the C it did. A game's own type of either name clashes with it there.
- `await Web.Fetch(url)` is the other local async operation, giving a `List<byte>` and failing with `IOError` (see Assets, Provisional, Fetching): local only, as the file operations are, and awaited like `Storage.Flush`.

<a id="the-server-s-store"></a>

## The server's store

How a match keeps what it doesn't hold in memory: a chunk of blocks nobody is near, a player's things between visits, a world from one run of the server to the next. Built 2026-11-14 for an endless voxel world; every rule here is Provisional (Claude's picks: the owner hasn't chosen among them), and `notes/voxels.md` says what was built and measured.

<a id="provisional-16"></a>

### Provisional

- `Storage.Save(key, bytes)`, `Storage.Load(key)`, `Storage.Load(key, entity)`, `Storage.Delete(key)` and `Storage.List(prefix)` (below) are match code's: systems, match handlers, match tasks, and the functions they call. The key is text, the bytes a `List<byte>`. They ask the machine that runs the match to keep, find, forget or list bytes under keys. Nothing of the match changes when they're called, and nothing comes back from the call, but to a match task that awaits a load or a listing (below).
- **Only the server's own run of a tick asks.** A player's machine that predicts or confirms the same tick asks nothing: its machine has no store, and the same request twice would be two saves. So what a save keeps is the server's value, never a prediction's.
- **While servers run, the store's files are the store's to make** (Claude's pick, 2026-11-16; `notes/voxels.md`, section 3f). A process lists a provider's `saved/` once, at its first load, and keeps which files it has, adding each save's; a load of a key with no file among them is "not found" with nothing read, and every other load is read. A file put there by anything but the store while a server runs (the game's own file calls, a person, another process sharing the folder) may not be found until the process ends or its host says the files changed (`tide_storage_forget_files`). Open: whether that's the rule the owner wants, against a read for every load as before.
- **What a load finds comes back as an event,** `Loaded { string key; List<byte> bytes; bool found; bool failed; }`, in a later tick: sent to the entity the load named, or to the world. `found` is false and `bytes` empty where the store has nothing under the key. `failed` is true where something is kept there that couldn't be read (the disk refused it, or it's bigger than a value can be): not the same as nothing, so a game doesn't make it afresh and save over it. It's a tick's input, as a command is: the server gives it to a tick, the tick's frame carries it to every machine that has the whole match, the journal records it, and a replay takes it from there. So `Loaded` handlers run in the same tick on every machine, and the code that handles one is ordinary match code.
- **Which tick.** An answer goes to the first tick after it's ready. With the files the standard hosts keep, that's usually the next tick or the one after (they're read on a thread of the files' own: below). In a match that doesn't hide state, an answer of more than about 1 KiB (`TIDE_COMMAND_BYTES` with its key) goes to the players as a download, as a big command does: it reaches a tick once every player has it, and the answers after it wait behind it.
- `Loaded` is declared by the engine, as Tide code a program whose code has the words `Storage`, `.` and `Load` (comments aside) is compiled with; a program that doesn't has no such event, and a game's own `Loaded` clashes with it there. Its handlers follow the events' rule: one that takes components needs the entity every `Storage.Load` names, and a load that names none is then an error that says so. The engine sends it; a game's own `Send` of it is allowed, as of any event it could declare itself.
```csharp
// A chunk nobody has had for a while goes, one a player changed into the store first: in an event, which runs
// after the tick's moves, so a player who came back to it in this tick keeps it
system Idle(Seen seen, Time time)
{
    if (seen.audience == Audience.None && time.tick - seen.emptied >= LINGER) this.Send(Expire { });
}

event(Expire) Drop(Seen seen, Chunk chunk)
{
    if (seen.audience != Audience.None) return;
    if (chunk.edits != seen.saved) Storage.Save(SavedAs(chunk.dimension, chunk.at), chunk.blocks.ToBytes());
    this.Destroy();
}

// ...and comes back from there as someone next comes near
var made = Spawn(Chunk { at = at, dimension = dimension.number }, visibility, Seen { group = group });
Storage.Load(SavedAs(dimension.number, at), made);

event(Loaded loaded) Fill(mut Chunk chunk)
{
    if (loaded.failed) return;          // Kept but unreadable: not made afresh over it
    if (loaded.found) chunk.blocks = Grid3<Block>.FromBytes(loaded.bytes) ?? Grid3(16, 16, 16);
    else chunk.stage = Stage.Missing;   // Never saved: made from the seed
}
```

`ToBytes` and `FromBytes` are a grid's as bytes and back (Grids, Provisional, Grids as bytes).

- **Listing keys** (Claude's picks, 2026-11-15). `Storage.List(prefix)` asks for the keys the store has that start with `prefix` (an empty one: every key). `Storage.List(prefix, after)` goes on after a key, the last of the answer before: the keys past it. Either takes the entity its answer goes to last, as a load does: `Storage.List(prefix, entity)`, `Storage.List(prefix, after, entity)`; the second argument is `after` when it's a `string` and the entity when it's an `Entity`. The answer is a `Listed { string prefix; string after; List<string> keys; bool more; bool failed; }` event in a later tick, declared by the engine for a program whose code has `Storage`, `.` and `List`, as `Loaded` is for `Load`, with the same rule for handlers that take components. `keys` are sorted by their UTF-8 bytes (a key before the keys it starts), 1,024 at the most (`TIDE_STORAGE_LIST_MOST`; 1,024 keys of 256 bytes are 264 KiB, within a value's 32 MiB); `more` is true where there are keys past the last, which `Storage.List(listed.prefix, listed.keys[listed.keys.count - 1])` gets. `failed` is true where the store couldn't be listed (the disk refused a folder that could hold one of the answer's keys: one whose keys would all come after a full page's fails the page after instead), and `keys` is empty then; a store that has nothing under the prefix, and a host with nowhere to keep it, answer with no keys and `failed` false. `prefix` and `after` are the request's, so two pages of one prefix asked in one tick are told apart. A listing is answered as a load is, input to a tick with the same pacing, order and limits: a listing asked twice in a tick with one prefix, `after` and target is answered once, and one asked after a save in the same tick has the saved key.
- A listing has only keys a save could have made: a file in `saved/` that isn't one (a `.new` a save left as the server stopped, a file of another name or spelling someone put there) is never listed. A key too long for a file's name (kept by its SHA-256, below) lists too: its key is kept beside its value, and a value whose key isn't there, or a key whose file isn't its hash, lists nothing.

```csharp
// Every chunk a dimension has saved, a page at a time
Storage.List($"chunks/{dimension.number}/", this);

event(Listed listed) Count(mut Atlas atlas)
{
    if (listed.failed) return;
    foreach (var key in listed.keys) atlas.saved += 1;
    if (listed.more) Storage.List(listed.prefix, listed.keys[listed.keys.count - 1], this);
}
```

- **Awaiting a load or a listing** (Claude's picks, 2026-11-15). A match task (an async function whose world is the match, a match event's async handler, and the async functions they await) can wait for the answer and have it as a value: `var bytes = await Storage.Load(key);` gives the `List<byte>` kept under the key (`List<byte> fails IOError`), failing with `IOError.NotFound` where nothing is kept there and `IOError.Failed` where something is kept that couldn't be read (a `Loaded`'s `found` false, and its `failed`). `await Storage.List(prefix)` and `await Storage.List(prefix, after)` give a `StorageKeys { List<string> keys; bool more; }` (`StorageKeys fails IOError`), failing with `IOError.Failed` where a `Listed`'s `failed` would be true. `StorageKeys` is declared by the engine beside `Listed`, for a program whose code has `Storage`, `.` and `List`, and a game's own type of the name clashes with it there.
  - **The answer is input, as an event's is.** It's asked, carried out, paced and ordered with the event's requests: only the server's own run of a tick asks; it's carried out after the tick, in order; it's given to a later tick, 64 a tick (256 in a match that hides state), by download past about 1 KiB in a match that doesn't hide state; the frame carries it to every machine that has the whole match and the journal records it. The task goes on at the end of the tick it's given to, with the tasks whose time has come, in the order they started, on every machine: a player's machine predicting past it waits as the server's would have until the frame that has it comes. In a match that hides state players' frames don't carry it, as a match task's frame is the server's alone there.
  - **No entity, no handle.** An awaited load or listing names no entity (an error that says so): its answer is the task's. Without `await`, the call asks for a `Loaded` or `Listed` event, in a task too, so it gives no handle to keep: `var asked = Storage.Load(key);` is the error that a call with no value is, with a note to await it. `Storage.Save` and `Storage.Delete` give nothing to wait for (an error that says to call them as statements).
  - **The request is the task's.** Its frame keeps the key (a listing's prefix and `after`) and an identity of its own, the identity clock and a cause of the task's as a spawn's entity has, which the answer names. So a snapshot, the world's hash, a packed world, a joining player's world, rollback and a hot reload that carries the task over hold the wait, and two tasks that await one key in one tick are asked and answered apart, never as one.
  - **A key the store refuses** (Claude's pick, 2026-11-15, after review: before, such a task waited for ever). An awaited load of an empty key or one past 256 bytes, and an awaited listing of a prefix or an `after` past 256 bytes, asks nothing (the server's log says so, as for the event's) and fails at once with `IOError.InvalidPath`, in the tick it's awaited, on every machine: the task has all it takes to tell, so no answer needs to come. `InvalidPath` over `Failed`, which says something kept couldn't be read.
  - **A task that ends before its answer** (its owner is destroyed, it's cancelled, a hot reload drops it) is gone, and its answer finds no task and changes nothing.
  - **Asked again** (where the event's answer is lost): rewinding a match drops the answers on their way, as for events, and every task the rewound world has waiting asks again, from what its frame keeps, with the next tick, in the order the tasks started (`tide_game.stored_again`). So do the waiting tasks of a world a server is made with (`tide_server_desc.world`: a match taken up again, a shard started from a checkpoint), and a task whose entity moves to another shard, on the shard it comes to, as the answer to the shard it left finds no task there.
  - **Who can await it:** match code alone, as the store is the match's. A local task (one that uses local state) awaiting it is an error that says the store is the match's; `await` outside async code is the error it always is; a system can't wait, and starts a task that does.

```csharp
// Every chunk a dimension has saved, a page at a time, in a match task
async void Survey(mut Atlas atlas, string prefix)
{
    mut var after = "";
    mut var going = true;
    while (going)
    {
        var page = await Storage.List(prefix, 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; // IOError.Failed: the store couldn't be listed
    }
}

async void Fill(mut Chunk chunk, string key)
{
    var saved = await Storage.Load(key);
    if (saved is List<byte> bytes && Grid3<Block>.FromBytes(bytes) is Grid3<Block> blocks) chunk.blocks = blocks.Copy();
    else if (saved is IOError.NotFound) chunk.stage = Stage.Missing; // Never saved: made from the seed
}
```

- **In a match that hides state** (State visibility) nothing of a load reaches the players' machines but what its handlers change of what they may have, as with a command: the bytes stay on the server.
- **Order.** A tick's requests are carried out once it has ended, after those of the ticks before, in the order it made them: a save then a load of one key in one tick finds what was saved, and so does a load in a later tick. A load asked twice in a tick with one key and one target is answered once. Answers are given to a tick in the order their loads and listings were asked, 64 a tick at the most (more wait for the next), or 256 in a match that hides state, whose frames carry none of them (Provisional, Claude's pick, 2026-11-16: a game that does a lot for each answer, as one that makes a chunk of terrain does, spreads that over ticks itself), and their `Loaded` and `Listed` handlers run with that tick's other events, after its systems: a system that goes on from what a handler did runs the tick after. Each answer is its own cause: what two answers' handlers spawn in one tick are different entities.
- What the match's start (its `Spawned` handlers) and a scene's preparation ask is carried out with the first tick that ends after them, before what that tick asks; in a sharded world too, whose root runs its start before its server is made (2026-11-15: what it asked was dropped before).
- Code that uses the store keeps its place among code that does, as code that calls C does: a system that saves runs on one thread, in the order its entities come.
- **Keys and values.** A key is 1 to 256 bytes of any text, and a value at most 32 MiB; past either nothing is kept or asked, and the server's log says which key and what to do instead (an awaited load or listing fails then: above). Keys are the game's own: a save replaces what its key held.
- **Where it's kept.** The standard hosts keep each key as a file of its own in `saved/`, in the game's persistent data folder on the machine that runs the match: the hosting player's own, a dedicated server's (its `appId`'s folder, or for a game with none the one its player build has, `dev.tide.<name>`), a page's storage on the web. `/` between a key's parts makes folders. Every byte but small letters, digits, `-` and `_` is written out (`%XX`, capitals too), and `.` too except in the last part after its first byte; a part named as a Windows device is (`con`, `nul`, `com1`...) has its first byte written out. So any key is a file of its own, the same on every system, no folder is another key's file, no two keys are one file on a disk that doesn't tell capitals from small letters, and no key reaches outside the folder. A key with a part too long for a file's name once written out is kept as `saved/%%/` and its SHA-256 instead, with the key itself beside it, in the same name with `.key` for `.bin`, so a listing finds it. Every match a server hosts shares the folder, as every shard of a sharded world does, so a game that hosts several worlds says which in its keys.
- **A save is whole or not at all.** It's written beside the key's file and moved over it once written, so a server that stops while saving leaves the old value or the new one. What a tick saved and deleted is then flushed to the disk, with nothing waiting for it.
- **Off the tick's thread** (Claude's picks, 2026-11-15). The standard hosts read, write and list on a thread of the files' own, one for the process, a tick's requests at a time after the ticks' before: a tick never waits for the disk, and the server takes each answer at the first tick after it's ready. A host with no such thread (a page's files, which are the page's thread's; a test's or a benchmark's kept in memory) carries a tick's requests out as the tick ends, and its answers go to the next tick. So does the standard host's run with no window (`--frames`, `--capture`, `--script`), which has no clock and repeats: which tick an answer from the files' thread reached would depend on the disk. Answers are input either way, so every machine and a replay take each one in the same tick.
- **A server that stops** cleanly carries out what was asked before it's gone: what its ticks, its start and a preparation saved and deleted is written, though nothing waits for the disk to flush it. What loads and listings would find, which no tick will take, isn't read.
- **A match that uses the store doesn't migrate.** What it keeps, and the answers on their way, are the hosting machine's: `hostMigration` in a program that uses `Storage` is an error, and the server offers no handover.
- **Rewinding a match** (`tide/timeline.h`) drops the answers on their way, those still being read too: the rewound ticks ask again as they run. A load or a listing the rewound world asked before the point it went back to, whose answer hadn't come, is never answered as an event; one a task of the rewound world awaits is asked again (Awaiting a load or a listing, above). What the ticks let go saved and deleted stays saved and deleted.
- **A hosted match** (Claude's picks, 2026-11-15) keeps its store in the managed hosting service, as a dedicated server keeps it in its folder: the same keys, values, outcomes, order and pacing, the answers input to ticks in the order they were asked. The service reads and writes it while the match goes on, and answers when it has read what was asked, later than the tick that asked; a load after a save of its key finds it, as with files. It keeps each world's apart, on the storage it keeps saves on: a match's, which the match finds again when it's resumed or recovered from its save, or a sharded world's, which all its shards share. A save past the service's limits (a value's size, the disk a world, an account's worlds and the host take, what the account may store, what may wait to be written) isn't kept, the match's log says why, and the key keeps what it had; a value that isn't what was saved loads as `failed`. Every load and listing is answered, `failed` where the service couldn't read it or had no room for it, as a tick takes no answer past one still to come. A world's reads and writes are paced (a rate a second, after a world's worth at once), so a match that asks faster waits for its answers. The service records a match's save only once everything asked of its store before it is written, so a match recovered from its save may find its store newer than its world, never older. A match recovered from its save asks again what its tasks await (Awaiting a load or a listing, above), of the same store; what the start of the instance it's recovered in asked, before the save's world took its place, is never carried out, as it would write over what the match kept. How the reactor and the service talk is `tide/managed_run.h`'s (ABI 1, the store's calls offered by the service at a version of their own); a service older than the store leaves the match keeping nothing, as below.
- A host with nowhere to keep it (a test's, a benchmark's, C that gives its server no files: `tide_server_desc.io`; a managed service that offers no store) keeps nothing: saves go nowhere, every load finds nothing and every listing no keys, so the same match plays on.
- Local code can't use it: a view or a local handler keeps this machine's own files with `File` and `Directory` (Local files), and what a player wants saved of the match goes there as a command. Not input sampling, code the GPU runs or a parallel loop's step either. An argument of another type than the call takes is an error that says which one (`Storage.List takes its prefix as string, not int`).

<a id="open-12"></a>

### Open

- A handle of a load or a listing (`Task<List<byte> fails IOError> asked = ...`), to start several and await them later: without `await` the call is the event's now, so a handle needs a spelling of its own (a method, a word), which is the owner's to pick. `WhenAll` over tasks isn't decided either (Tasks, Open).
- Any value as bytes and back (a component or a struct, as a grid has `ToBytes` and `FromBytes`: Grids), where a game writes its own loops or JSON now.
- A listing that says more of each key than its name (its value's size, when it was saved), and one that goes backwards.
- A store for each match of a server that hosts several (`tide_hosting`'s matches share one folder now).
- Whether a hosted project's matches share one store, as a dedicated server's matches share its folder, rather than each world keeping its own: a project whose matches end when they're empty starts each with none now. And whether a sharded world's outlives a new release, which starts a new world.
- A load or a listing asked for and not yet answered when a server stops isn't asked again when its match goes on from a save, but for one a task awaits. A shard's checkpoint doesn't carry the answers it hasn't given a tick yet either, nor the requests its files' thread hasn't carried out: a shard started from one without its journal loses them.

<a id="assets"></a>

## Assets

<a id="decided-16"></a>

### Decided

Agreed 2026-10-06. An asset is a file a game is built with: an image, a text, some bytes. The language names it, the compiler checks it, and the build packs what's named and nothing else.

- `asset` declares a file's contents under a name, at the top level like a constant, resolving to an ordinary type: `asset Grid2<Color> hero = "art/hero.png";`, `asset string rules = "rules.txt";`, `asset List<byte> table = "data/table.bin";`. Code reads `hero` wherever it reads a value of that type. It's read-only, and never assigned.
- The path is relative to the `.tide` file that names it. There's no assets folder and no root: files are wherever the game keeps them, a package's beside its own code, and the path says where from here.
- A path can be a URL. tidec fetches it and packs what it was at build time, so it's a file kept elsewhere and nothing else: match code reads it, nothing is fetched when the game runs, and the game plays offline.
- A path can be a glob, which resolves to every file it matches, in order of their paths: `asset List<Grid2<Color>> run = "art/run/*.png";` gives the contents, and `asset Map<string, Grid2<Color>> run = "art/run/*.png";` the path of each with its contents, for a game that needs the names. A single file resolves to its contents alone: its path is on the line that declares it, and a `const string` can be that path where a game wants it twice.
- A path that names one file is valid where the type holds many (agreed 2026-10-08, of `asset List<Clip> shot = "sfx/shot.wav";` and `asset Map<string, Clip> shot = "sfx/shot.wav";`: "should still be valid, i know its only one entry but this allows to change the scope of the search without changing the signature"): a list of that one file, or a map of it. So a declaration's path goes from one file to a glob, and back, with its type and every line that reads it as they are. The other way round stays an error: a glob where the type holds one file.
- Anything wrong that can be known at compile time is an error at the declaration: a file that isn't there, a glob that matches nothing, a URL that can't be fetched, bytes that aren't what the type says (an image that doesn't decode, text that isn't UTF-8). The editor says the same as the game is written, with no build.
- A game ships the closure of its declarations: `tide build` packs the files `asset` names, and nothing else in the folder. A file in the pack is there once however many declarations name it or files have its bytes, and all of them are the same value.
- **Asset list value ownership** (agreed 2026-10-11): ordinary asset values, including `List<byte>` and animation/model backing lists, may share retained immutable storage until a write detaches that value. Assignment and mutation keep ordinary value semantics; changing a copy changes neither its source nor another field. Assigned values survive pack replacement/unload. Texture and Clip references keep their existing reload behavior.
- Match code reads packed assets, since every machine has them. What a machine loads as the game runs (a file of the player's, a URL) is local: it reaches the match as match data, through a command, as a game's own state, which the netcode sends like any other, to those in the match and to whoever joins.
- A user's content enters the match as the file's bytes, in the format it came in: a `Grid2<Color>` field decodes a PNG with `grid.Decode(bytes)`, with the engine's own decoder, so it's the same pixels on every machine.
- No GUIDs and no meta files: the engine owns none of a game's files and writes into none. References are in text, in the source, and all of them are constant, so moving a file is a refactor: the language server rewrites the references when a file is moved in the editor, and a file moved outside it is found again by its bytes, which the error names with a quick fix.
- **A model is a `Mesh<V>`** (agreed 2026-10-08. The owner, of the Tag sample: every 3D game of the repo was boxes, balls and cylinders made by loops, as a game couldn't use a model an artist made or a tool generated. Of the proposal's four points they picked: glTF and OBJ; `Mesh<V>` over the game's vertex struct, filled by its fields' names, its lists read by any code; both ways of drawing it; a file's parts as one mesh. FBX support was requested 2026-10-10). `asset Mesh<Corner> tree = "art/tree.glb";` reads a glTF (`.glb`, `.gltf`), FBX (`.fbx`, binary or ASCII) or Wavefront OBJ as one mesh, whose vertices are the struct in its `<>`:
  - The file fills the struct's fields by their names, `position`, `normal`, `uv`, `color` and the like, and a field of any other name keeps its default. `position`, `uv` and `color` already meant that on a vertex, so `Mesh<Vertex3>` draws with no frag.
  - `tree.vertices` and `tree.indices` are plain read-only lists, which any code reads, match code too, as every machine has the same pack.
  - `Draw.Mesh(tree, transform, ...)` and `Draw.Instanced(tree, instances, ...)` draw it, the mesh where its two lists go, and `Draw.Mesh(tree.vertices, tree.indices, ...)` is the same draw.
  - A file with several meshes or materials is one mesh: its nodes' transforms worked in, and each material's base color multiplied into its vertices' `color`. A game that needs parts apart exports them as files, and names them with a glob.
  - Static meshes: what's built, and each rule of it, are picks: see Mesh assets, under Provisional.
- **An image that's only drawn is a `Texture`** (agreed 2026-10-07, of `asset Texture hero = "art/hero.png";`: "ah yes lets add `Texture` there"). `Grid2<Color>` stays what an image is where code reads its cells, and it draws too; a `Texture` is the image as the GPU has it, which no code reads. Reading a `Texture`'s pixels back from the GPU isn't part of it. What's built, and each rule of it, are picks: see Texture assets, under Provisional.
- **Linear-light sampled color** (agreed 2026-11-14). A mark on Texture, TextureArray and Cubemap assets and resource fields says their display-encoded sRGB RGB is read as linear light on the GPU, through the sRGB form of the image format, so filtering and mipmaps operate in linear light. Math.ToLinear and Math.ToDisplay work in CPU and GPU code. Unmarked images retain their current behavior; no sRGB render-target format, fragment-output interpretation or screen-presentation change is introduced. The mark's name and remaining choices are Provisional below.
- **Ordinary color textures compress automatically** (agreed 2026-10-11: "Compress ordinary color textures automatically"). GPU compression is lossy and visual only, and unsupported devices decode the compressed image as they upload it. Eligibility and formats of the current implementation are recorded under Texture assets below.
- **`[Raw]` textures compress too, and `[Lossless]` keeps any Texture asset exact** (agreed 2026-11-04, from a game whose pack was 80% uncompressed normal/ARM maps: "Compress, opt-out", named `[Lossless]`). `[Raw]` says how channels are read (as numbers, no alpha worked in), not how they're stored: an eligible Raw image is block-compressed like a color one, its channels unpremultiplied, and lossy within the format's error. `[Lossless]`, before a `Texture` asset (one, or a glob's list or map; with or without `[Raw]`), keeps its pixels exactly, a byte per channel. It takes no arguments, appears once, and is an error on anything else but a `TextureArray` asset (whose layers compress the same way, 2026-11-05), including grids and cubemaps, which are never compressed.
- **PSD images are imported without Photoshop** (agreed 2026-10-08): an image asset reads the saved composite, the visible layers combined into one picture, through the same `Texture`, `Grid2<Color>` and cubemap declarations as PNGs. The build needs no external application. What's read, and its limits, are picks: see PSD images, under Provisional.

```csharp
asset Grid2<Color> hero = "art/hero.png";
asset Map<string, Grid2<Color>> tiles = "art/tiles/*.png";
asset string credits = "https://example.com/credits.txt";

view Hero(Body body)
{
    Draw.Sprite(hero, body.position, float2(1, 1));
}

command SetBackground { List<byte> png; }

command(SetBackground value, PlayerID sender) Apply(mut Arena arena)
{
    if (sender != arena.host) return;
    arena.background.Decode(value.png)!;
}
```

<a id="provisional-17"></a>

### Provisional

Picks made to build it, awaiting the owner.

- **Unused release assets.** Standalone release builds (`tide build --release`, and `--distribution`, which implies it) of Tide-only games omit asset declarations with no references in checked code, defaults or shaders. References in helpers and generated type defaults retain an asset even when that helper or type is unused; a referenced collection retains all its matched files. Every declaration is still validated before pruning. Debug, hot-reload and custom C-host builds retain all assets, as do games or packages with C/C++ sources or prebuilt libraries, whose uses may be outside Tide. The compiler's explicit `--strip-unused-assets` option enables pruning for callers that can account for those uses.
- **The types** an asset resolves to: `string` (UTF-8), `List<byte>` (any file) and `Grid2<Color>` (PNG, supported PSD, JPEG, TGA, BMP or RGBA8 DDS, decoded at build time into base-level pixels), each alone, as a `List<T>` of a glob's matches (or of the one file a path names), or as a `Map<string, T>` of their paths. The grid is sized as the image is, and read-only: a system takes it as it takes any read-only value, and a frag or vert samples it by name, as it samples a singleton's grid. Textures and cubemap faces accept the same images; audio and model assets are described below, and `Font` (a TrueType font file) under Views and drawing, Fonts.
- **Globs:** `*` matches within a name, `**` across folders, and `?` a character; matches are sorted by the UTF-8 bytes of their paths, relative to the declaring file; a map's keys are those paths. Matching nothing is an error.
- **One file for a list or a map** (picks made as it was built, 2026-10-08; that it's valid is decided, above): the map's key is the path as the declaration writes it (`shot["sfx/shot.wav"]`), which is the key a glob gives that file, so a lookup by key goes on working when the path becomes `"sfx/*.wav"`. A URL is taken the same way, a list or a map of the one file it names, keyed by the URL: the owner spoke of files, and a rule with an exception for URLs would be the odd one. A `Cubemap` is six files, so its path stays a glob, and `[Raw]` stays for one `Texture`, one `Grid2<Color>`, a `TextureArray` or a `Cubemap`, as a frag reads those by name.
- **URLs** are `http://` and `https://`. tidec keeps what it fetched in `.tide/` by URL with the server's ETag, asks whether it changed at each build and at each `tide run`'s start, and builds from the cache when the server can't be reached, so offline builds and reloads work; a run picks up a changed URL when it's started again. Pinning a URL to a hash is open, below.
- **Where the pack is:** in a file beside the program on desktop (`<game>.pack`), inside the self-contained page on the web, and in the APK's assets on Android. Under `tide run` there's no pack: the game reads the source files, and tide watches them, so a saved image is in the running game at once, with no rebuild, as it's data. A web build can keep the pack beside the page rather than inside it, so the page stays small and the pack is fetched from wherever it's hosted; the option's name is open.
- **Sharing** is by SHA-256 of the bytes, among declarations that read the file as the same thing. A `Grid2<Color>` of the pack lives in a read-only region every world can name, outside every heap, so no world copies, hashes or sends it, and it's the same memory to every reference. A file read as two things is in the pack as each where they're kept differently: an image as a `Grid2<Color>` and as a `Texture`, and a text with a character of several bytes as a `string` and as a `List<byte>` (text says how many characters it is, which isn't its bytes then; text that's all ASCII and its bytes are in the pack once).
- **Decoding:** `grid.Decode(bytes)` reads a PNG into a `Grid2<Color>` field of a component, singleton or scene, sizing the grid as the image is, and fails with `IOError.InvalidData`. It's pure, so it runs in match code, and it runs where it's called, which in a tick is on every machine. **Fetching:** `await Web.Fetch(url)` is a local async operation giving `List<byte>` and failing with `IOError`, like `File.ReadAllBytes`, which is the other way bytes come in at runtime; so loading a player's image is `grid.Decode(File.ReadAllBytes(path))`, and there's no asset handle type beside the plain ones. On the web it's `fetch`, so the server's CORS applies; on desktop it's the HTTPS the relay's connection uses; on Android, Java's.
  - Both are built (2026-10-06), with these picks. `Decode` reads every kind of PNG the specification has (gray, color, a palette, with and without alpha, 1 to 16 bits a sample, interlaced or not) with the engine's own reader (`tide/png.h`); a sample becomes a channel by one division, so the pixels are the same bits on every machine. A side past 16384 pixels, or more than 4096 × 4096 pixels in all (16,777,216, 256 MiB of cells, a quarter of a world's heap), is `InvalidData` before anything is made for it, as is compressed data that inflates to more than 1 MiB past the last row: bytes can come from anywhere, and deflate packs a run of one color about a thousand to one, so a file of a few kilobytes could otherwise end every machine's program or take each minutes (Provisional, 2026-10-26: the owner asked for limits that are clear and easy to change; the numbers are Claude's picks, one `#define` each in `tide/png.h`). A failed decode leaves the grid as it was. A pixel that's clear black is a cell that's zero, which takes no chunk. Rows go into the grid as they're decoded, so nothing the picture's size is made beside it; pictures within the limit that together fill the world's heap end the program as running out of memory does. `Web.Fetch` is a GET that follows up to 5 redirects; `NotFound` is a 404 and every other status outside 200 to 299 is `Failed`, as is a body past 64 MiB (read no further) and a certificate the system doesn't trust; nothing times out, as a browser's `fetch` doesn't. On Android it's the same client as desktop's over the TLS the relay's connection uses there (Java's `SSLEngine`), not `HttpsURLConnection`. A fetch still going when its task ends (a reload, the program's end) is forgotten, and stops.
- **Finding a moved file:** tide keeps the SHA-256 of every file an `asset` named in `.tide/`; when one is missing, the error says where a file with the same bytes is now in the game's folder (or packages), with a quick fix to the new path, and else lists files of the same name. The language server takes the editor's rename of a file or folder (`workspace/willRenameFiles`) and rewrites every reference to it.
- **An `asset` is a declaration** of its file's namespace, named like a constant, usable in every kind of code (match, local, GPU, C through a `List<byte>` or a grid as any value is passed), and never `mut`, assigned, or a parameter's default. A path has to be a constant expression; anything else is an error that says why: the dependency tree is static. An asset whose code makes it (see Build code) can leave its path out, and its name is that code's to change inside its body.

Picks made as the first slice was built (2026-10-06), awaiting the owner too:

- **`List<byte>` alone is one file's bytes**, never a glob of files; a glob of files as bytes is `List<List<byte>>` or `Map<string, List<byte>>`. These are the only places a list holds a list or a grid: an asset's type can, nothing else can, and a local can't hold one of them either (a grid is still never copied). `Map<K, ...>` with a key that isn't `string` is an error that says the keys are paths.
- **A frag or vert samples an asset by its bare name** (`hero.Sample(uv)`), never an element of a list of assets (`run[1].Sample(uv)` is an error that says to declare the one it samples): the GPU has no list to index.
- **A path's `\` is `/`**, and `>>` closes two generic types written inside each other (`List<Grid2<Color>>`), as it does in C#.
- **Under `tide run` the pack still exists**, in the run's own folder, written by tide (whose front end resolves the files) with each build and again when a file an asset names changes, and loaded by the host between frames: so a saved image is in the running game within a moment, with no compile or link, which is what "no pack" meant; a hot reload hands the new library the pack the host has. On the web tide serves it beside the program and the page fetches it. A C host of its own (`tide_add_game` with `HOST`) gets the pack as C (`tide_game_pack`) and loads it itself (`tide_assets_load`).
- **A pack from another build** of the game: a name it hasn't got, or has as another type, reads as empty, and the program says so once on stderr. A program whose pack is missing says so too and runs with every asset empty.
- **URLs** are fetched by tidec once a process (so once a build, and once as `tide run` starts), with curl, into `<game>/.tide/assets/urls/`, each under the SHA-256 of its URL with its ETag beside it; a `tidec` run with no game folder keeps them in a temporary folder. A URL with a character tide can't pass to curl (a quote, a backslash, a dollar sign, a percent) is an error.
- **What the pack holds of a grid** is the chunks that have a color in them: a clear black cell takes nothing, as in a world's grid a cell nothing wrote takes nothing. A texture drawn from an asset is told apart by the file's hash, so the draw list copies it once.
- **Where the pack is at runtime:** the top half of the scratch area's offsets (from 2^61), so an asset's handle is a scratch handle that every read path reads already, and a thread finds the region the first time it runs after a load. The pack's offsets are 64 bits in the file and in handles, so it holds what memory does (2026-10-30; it was 512 MiB).
- **The editor and the build say the same things** about a path: the checker reports a missing file (naming a file of the same bytes, or files of that name), a glob with no match, bytes that aren't the type's, and tidels attaches its fixes to those diagnostics.

Picks made as defaults that name assets were built (2026-10-07), awaiting the owner, who asked for the first of these to compile (`local Texture test = logo;` in a component: "I feel like this should be possible?"):

- **A field's default can name an asset**, where it could only be a constant expression: `local Texture face = logo;`, `string text = rules;`, a struct's `Texture image = logo;`. An asset is as good as a constant there: read-only, known as the game is built, the same on every machine.
  - **It counts as a constant anywhere in the default's expression**, by the rule for constants and no other: a struct's value (`Sprite { image = logo }`), a member (`table.count`), an operator, a `Math` function, a name through its namespace (`Art.logo`).
  - **The value is the pack's, read where the default is given**, not while compiling: as a spawn or an `Add` leaves the field out, as a match's or the local state's singletons start, for the local fields of an entity nothing wrote yet, and for a field a hot reload adds. Text, bytes and a glob's list or map are copied, into the world the field is in; a `Texture`, a `Clip` and a `Cubemap` are names of their declarations (above), so nothing is copied and a file saved under `tide run` shows through them.
  - **What a field can't be, a default doesn't make it**: a `Texture` field in the match is the error it was, and a `Grid2<Color>` field can't start as an asset's grid, as a grid is never copied (an error that says to read the asset by its name). A grid asset is a `Texture` field's default, by the conversion there is.
  - **One of a glob's isn't a default**: `frames[0]` and `icons["star.png"]` are no constant expressions, as indexing isn't one.
  - **Nothing else that takes a constant takes an asset**: a `const`'s value, a setting, a bound, an enum member's value, an array's length, an asset's path, a parameter's default. Those are worked out as the game is built, or name what the build reads, and an asset's value is the pack's. Through a namespace or a member (`Art.rules`, `rules.length`) an asset used to get past that check with no error, and an asset whose path was one had no file; it's an error that says a field's default is where one goes.
  - **A host loads the pack before it makes a world or the local state** (the standard host does; a hot reload hands a new build the pack before it carries anything over): a default given with no pack loaded reads the asset as empty, as any read does.

Picks made as `Texture` assets were built (2026-10-07), awaiting the owner. That an asset can be a `Texture` is decided, above:

- **Linear-light image sampling (owner-approved 2026-11-14).** `[Linear]` on `Texture`, `TextureArray` and `Cubemap` assets and resource fields means the source stores display-encoded sRGB color, and GPU reads give linear light through the corresponding sRGB image format. Filtering and generated mip levels operate on linear light. Unmarked images, fragment outputs, target formats and screen presentation are unchanged; there is no sRGB render-target `Format`.
- **Provisional picks for `[Linear]` (2026-11-14):**
  - The name is provisional (the owner's "fine for now"). Placement is before one asset, a glob's `List<Texture>` or `Map<string, Texture>` (2026-11-14: every image marked and packed for the reading, and the list's or map's pack entry says so), a resource field (including aliases and attached local fields), a read-only image parameter of a function or method, or a frag's Texture source. It takes no arguments and appears once. It is refused on locals, grid declarations and globs of grids, Texture3D, depth and other data types, and on mut, out, extern and async parameters. A declaration keeps the source's role known while a shader is specialized.
  - A marked field accepts a marked asset/field/parameter/glob element of its type, a Color grid conversion (`Grid2<Color>` for Texture, `Grid3<Color>` for TextureArray), a direct compatible RGBA8 constructor or target-color expression (through a local that isn't `mut` too), or `default`. Marked/unmarked texture assignment is refused in either direction. Whole structs containing declared fields retain those fields' roles. A marked source cannot escape into an unmarked CPU parameter, a `mut` local, a return or a direct draw texture of the engine's own shader. Read-only GPU helpers borrow it with an ordinary Texture/TextureArray/Cubemap parameter and retain the original source's mark; mutable/out resource borrowing is refused. CPU size/count and owned resource lifetime/destination operations remain available. Where the mark goes (Provisional, Claude, 2026-11-14, shared with `[Raw]`, below): a local that isn't `mut` keeps its initializer's; a `?:` or switch whose every arm is marked is marked, and one whose arms differ is an error naming both roles; `list[i]`, `map[key]`, a `foreach` variable and a map entry's `value` of a marked glob are marked; a `[Linear]` parameter's argument must be marked (a role is never added) and its uses keep it; a frag's `[Linear] Texture` source takes a marked image or a Color grid from its draw; a getter or a function's result carries no mark.
  - Only the RGBA8 color format has an sRGB counterpart among Tide's uncompressed image formats. The compiler follows constructor assignments, including later assignments to a target, and refuses float, single-channel, depth and numeric formats with the reason and a Format.Rgba8/remove-mark fix. An unknown or varying format is refused rather than selected at runtime: the origins followed are assignments and struct-literal initializers of the field, in generic functions as in others, and for a field given as an `out` or `mut` argument, what the called function assigns its parameter, through further `out` and `mut` calls too (2026-11-14). A field C, a built-in or a virtual function (which an override may replace) makes or changes has no known format, so reading it under the mark is an error that says to assign the image where the compiler sees it. Whatever the compiler could not see is refused where it is drawn: a marked read of an image that is not RGBA8 draws nothing, binds nothing and reports why. Marked storage-image writes are refused: write the original target with a frag, then sample its marked view.
  - Alpha is coverage and is never transfer-converted. Marked color storage is `sRGBEncode(sRGBDecode(straightRGB) * alphaByte / 255)`: coverage is rounded to its stored byte first, so a byte-zero alpha cannot retain nonzero light. The GPU decodes before filtering; the existing Sample unpremultiplication then gives a straight linear Color and correct soft edges. `[Raw, Linear]` is refused: Raw's independent stored numbers and Linear's color conversion have incompatible promises. `[Lossless]` remains independent of the sampling role.
  - Runtime Color grids keep their CPU cells as written and generate this representation only for the marked sampled image. A marked reference to a rendered RGBA8 image uses a converted sampled copy, leaving its original attachment, fragment output and CPU readback unchanged. This copy is rebuilt only when the source has been drawn into or recreated since it was made, so an image drawn once and read every frame is copied once; it holds color alone, with no depth of its own. Copies of references still share the original resource lifetime.
  - Compressed marked assets use the sRGB BC1/BC3 format where supported and keep the same linear-filtered levels when decoded for an unsupported device. Opaque and alpha marked/unmarked images retain distinct sampling identities even when their stored base bytes coincide. Small/lossless images generate mips through the sRGB GPU format. Marked DDS assets rebuild their chain from the base image in linear light, rather than trust authored levels whose filtering space is unknown; unmarked DDS chains remain as authored.
  - CPU reads never apply the mark. Grid cells and `grid.Decode` remain stored straight display values, and `target.Read()` reads the original target's straight values. Texture has no CPU pixel-read/Decode operation. Convert explicitly with Math.ToLinear/ToDisplay when CPU code needs the other space.
  - A field's Linear role participates in hot-reload layout identity. Compatible fields retain references, including across asset replacement; changing the role resets that field to its destination default rather than reinterpreting its old image. A pack records, for each Texture, TextureArray and Cubemap asset, whether it was packed for the mark; an image packed for the other reading (a pack that is not the code's own build's) is not drawn, and the mismatch is reported once with the fix (build again), rather than read with the wrong encoding.
  - Unity replays marked images in either Player Color Space (Claude, 2026-11-15, replacing the refusal of 2026-11-14). A Linear project uses Unity's sRGB formats. A Gamma project, where Unity silently replaces requested sRGB storage with UNORM, keeps the marked bytes as stored and samples a copy decoded to linear light in half floats (RGBA16F), made again when the image is written, its smaller images made from the decoded copy, and a pack's authored levels decoded one by one; the renderer's own sampling copies of a marked target are RGBA16F there too. Reads, filtering and smaller images give the same linear light as sRGB hardware to well within a byte. The cost is memory in Gamma projects alone: twice an RGBA8 image's, more for BC1/BC3. Weighed: refusing every marked image in Gamma (the 2026-11-14 pick: one error and nothing drawn, when switching an existing project to Linear changes the look of all its other content); decoding on the CPU into the copy (slower uploads, the same memory); sampling UNORM and decoding in the shader (wrong between pixels and between levels, which the mark exists to fix).


- **Texture assets.** `asset Texture hero = "art/hero.png";` is a PNG, supported PSD, JPEG, TGA, BMP or RGBA8 DDS, decoded as the game is built into pixels of a byte a channel (each channel the nearest of 0 to 255). Those exact pixels take a quarter of the same image as a `Grid2<Color>`; eligible color images are kept GPU-compressed instead, as described below. A glob's are `asset List<Texture> frames = "art/run/*.png";` and `asset Map<string, Texture> icons = "art/icons/*.png";`, also readable through borrowed helper parameters below; other supported formats use their corresponding suffixes.
- **Cubemap assets.** `asset Cubemap sky = "art/sky_??.png";` is six supported image files a glob matches, named for their faces, as a cube a frag reads by a direction: see Cubemaps, under Views and drawing's Provisional, for the file convention and each rule.
  - **It's a `Texture` like any other**, a value: a draw's texture (`Draw.Mesh(vertices, indices, hero)`, in 3D, instanced, into a target), the source a frag's `Texture` parameter is given, a `Draw.Blit`'s source, copied into a `Texture` field or a local, passed to a function. A frag or a vert samples one by its bare name, `hero.Sample(uv)`, as it samples a `Grid2<Color>` asset, and never one of a list's (`frames[1].Sample(uv)` is the same error): give the draw that one as the frag's `Texture` source.
  - **Metadata is readable:** `texture.size` gives its base-level dimensions as an `int2`, without uploading pixels. Pixel reads still require a `Grid2<Color>` declaration; declaring the same file both ways keeps separate values in the pack.
  - **It's local code's.** A `Texture` is this machine's, so match code can't name one (the error rendering resources always gave), where it reads a `Grid2<Color>` asset freely.
  - **A `Texture` names its declaration's image, not its pixels.** What a field keeps of `hero`, of `frames[2]` (the declaration and that place) or of `icons["coin"]` (the declaration and that key) is the file as the loaded pack has it: under `tide run`, a saved image shows through the copies a game kept as it does through the asset's own name. A copy whose declaration, place or key the pack no longer has draws as the default `Texture` does: no texture.
  - **Nothing copies its pixels**: the draw list borrows the pack's RGBA or its immutable mip chain. RGBA costs 4 bytes a pixel; an eligible image is its complete compressed mip chain alone. A supported GPU uploads the blocks; another decodes every level to RGBA for the upload, and frees that copy after it. A `Grid2<Color>` asset costs 16 a pixel in the pack, 4 in the draw list and the GPU's. Two names of one file with the same representation are one image, in the pack and on the GPU.
  - **Automatic GPU compression** (built 2026-10-11; implementation choices): ordinary color `Texture` assets, including lists/maps, compress when both dimensions are powers of two and at least 128 pixels. Opaque images use BC1, others BC3, after existing byte conversion and premultiplication. Since 2026-11-04 `[Raw]` images are eligible too (channels as the file has them, box-filtered mips of independent channels, BC1 when every alpha is 255, else BC3), and `[Lossless]` ones are not. Smaller/non-power-of-two images, `[Lossless]`, cubemaps, grids and targets remain uncompressed. OpenGL/WebGL select supported S3TC formats; WebGPU requests optional `texture-compression-bc`. Missing support decodes every compressed mip to RGBA during upload (2026-11-02), preserving the prepared chain instead of regenerating from its base. Compressed mips are prepared during the build, down to 1x1; Point/Bilinear still read the base level, Trilinear reads mips. Lossy colors need not equal the source or another backend's decoding. Only the compressed image is in the pack (2026-10-30; until then RGBA was kept beside it, which made a game's pack about four times its images' compressed size and ran large ones past the pack's 512 MiB, its limit then). No generated runtime call is added; `[Lossless]` (above) is the one attribute. **Unity** (2026-11-05, the owner's "work on the gaps"): the replay gets them too. The program Tide is in says which block formats its GPU samples (`tide_embed_render_formats`; Unity's are BC1 and BC3 where `SystemInfo` has DXT1 and DXT5), and the recorder sends a texture's or an array's blocks as they are, every level (`TEXTURE_BLOCKS`, `ARRAY_BLOCKS`), or, where it can't sample them, every level decoded to RGBA8, as a device without BC gets; until then Unity got each image's base decoded and made its own smaller images.
  - **Authored DDS mipmaps** (built 2026-11-02; asset-format support, no language change): legacy DDS headers can supply one tightly packed RGBA8/BGRA8 2D chain with both sides powers of two from 4 through 16384 and every level through 1x1. DX10, compressed DDS, cubes/arrays/volumes, padded rows and incomplete/extra mip data are refused. Source bytes and decoded base pixels plus retained mip bytes each stay within the 512 MiB image-import budget. A `Texture` retains these levels as RGBA8, including Raw textures; color levels are premultiplied independently from straight source RGB, and Raw levels retain independent channels. Grids and cubemap faces read only the base image. Native OpenGL/Vulkan and WebGL2/WebGPU upload the full chain, and Unity's draw recorder does too since 2026-11-05 (Automatic GPU compression, Unity). Existing Filter.Trilinear selects prepared mips without any new annotation or runtime call.
  - **A pack from another build**: a `Texture` it has no image for is the default one, as the other types read empty.
  - **Not there**: reading a `Texture`'s pixels (which would be a read back from the GPU for a target's color, and isn't offered for any `Texture`), WebP/TIFF, animated images, SVG, HDR/EXR image assets, compressed DDS/KTX imports, ETC2/ASTC variants, mip streaming and virtual textures.

Picks made as PSD images were built (2026-10-08), awaiting the owner. Reading a PSD's saved composite without Photoshop is decided, above:

- **PSD images.** `asset Texture hero = "art/hero.psd";` and `asset Grid2<Color> hero = "art/hero.psd";`, alone, as a list or map, and a `Cubemap`'s faces. The file is an ordinary PSD (version 1), RGB with 8 or 16 bits per channel, at most 16384 pixels per side and 8192 × 8192 in all (2026-10-26, Provisional, Claude's pick: a compressed composite under a megabyte could otherwise ask for 4 GiB), whose image data is uncompressed, RLE, ZIP or ZIP with prediction. The compiler's own reader decodes its saved composite, never its layers; saving with Photoshop's Maximize Compatibility includes that picture. A missing or damaged composite, PSB, other color modes (CMYK among them), 32-bit samples and unsupported compression are errors at the path. Color profiles aren't applied; sRGB art keeps matching display colors. Each sample becomes a float channel of a `Grid2<Color>` or the nearest byte of a `Texture`, and only the decoded pixels go in the pack, as with PNG. No Photoshop installation is needed at build time or runtime, and no PSD decoder is added to a game. `grid.Decode(bytes)` continues to read PNG only.

Picks made as `Mesh` assets were built (2026-10-08), awaiting the owner. That a model is a `Mesh<V>`, filled by field names, drawn both ways and one mesh a file, is decided, above:

- **Resource collections (Decided, 2026-10-30).** Lists, arrays and map values can hold `Clip`, `Texture`, `DepthTexture`, `Cubemap`, `RenderTarget`, `Sound` and structs containing them, nested with ordinary text and containers. They retain ordinary value-copy and mutation rules, and remain local state. Clip/texture lists and maps can be stored, returned and passed through ordinary helpers, including mutable and out parameters. An asset collection remains immutable; copying it into a local collection permits changing the copy. Sound voices in arrays/lists are identified by their field path and element positions; map voices use insertion order, surviving entry compaction. Resource rebinding follows every live element after reload.
- **Mesh values and collections (Decided, 2026-10-30).** An asset's `Mesh<V>` value is its checked identity, one hidden 64-bit ID. They can live in fields, lists, arrays, map values, optional fields, parameters, returns and task state. (That `Asset<Mesh<V>>` is the same type was superseded on 2026-11-02, below.) `.vertices` and `.indices` resolve and borrow the current pack's geometry; `.Value` preserves the handle. Collection copies follow ordinary value rules, sharing immutable ID storage until mutation where possible; no geometry is copied. Singular identities follow the qualified declaration name. Glob-element identities combine that declaration name with the written file key and remain stable across enumeration-order changes. Removed/unknown IDs resolve to empty geometry. References compare by ID. Asset collections and resolved geometry stay read-only; ordinary collection copies and handle variables can be reassigned. GPU code and workers do not resolve live mesh assets. Grids, ECS declarations, borrowed contexts and direct optional/result elements retain their existing collection restrictions.
- **Meshes the game makes (Decided, 2026-11-02).** `Mesh(vertices, indices)` makes a static `Mesh<V>` from a `List<V>` and a `List<int>`, and is the same type as an asset's mesh everywhere one goes: fields, collections beside assets' meshes, parameters, draws. The owner chose one type with two representations over a separate generated-mesh type, the split of `Asset<Mesh<V>>` back out as the ID-only type, match state as well as local state, and a runtime entry point that draws a mesh at a given version. The rules below are Claude's picks, Provisional:
  - **A value of an ID and two lists, 24 bytes:** an asset's mesh has its positive ID and no lists; a made mesh owns copies of its two lists, which nothing writes after, and its ID is a 64-bit hash of what they hold (counts, vertex size, vertex and index bytes) with its top bit set, so it's negative. Its lifetime is its value's: no handle, no Destroy. Ordinary ownership copies, snapshots, hashes and packs the lists; a copy of the value copies them.
  - **`Asset<Mesh<V>>` is the ID alone**, 8 bytes, for a reference that has to name an asset (component defaults, prefab overrides, the editor). It converts implicitly to `Mesh<V>`, never back; its `.Value` is that `Mesh<V>`.
  - **The vertex type comes from the vertices**, or from where the mesh goes for a list literal; a type alias makes one, `Model(vertices, indices)`. `V` has a `float3 position`: a 2D mesh draws from its two lists. Indices past the vertices leave their triangle out, as for any draw.
  - **Equality compares IDs**, so two meshes made of the same lists are `==`; a made mesh is never an asset's, nor `default`, even with no triangles.
  - **Match state** holds one as it holds any list (snapshots, per-tick hash, joins); match code makes it deterministically. **Local state** and views' temporaries hold one at no network or hash cost.
  - **Drawing one** tells the draw list its ID first (`tide_draw_mesh_key`), which the draw takes as the geometry's version with no list read; every copy is one mesh on the GPU, kept from frame to frame. A mesh made or returned by a call within a draw is made once.
  - **Levels of detail** come from the draw's `lod:`, as for any mesh a game makes; the draw list's version of a made mesh is its key with `lod:` mixed in.
  - **Not there:** a made `SkinnedMesh<V>`; GPU code and workers take no made mesh, as they take no asset's; JSON takes none.

- **Decoding a mesh (Decided, 2026-11-02).** `Mesh<V>.Decode(List<byte> bytes)` gives a `Mesh<V> fails IOError`, spelled as `SkinnedMesh<V>.Decode` is: a static mesh read from a file's bytes while the game runs, the same kind of value as a made mesh (above). It's pure, so match code decodes too; GPU code doesn't. The owner chose the method, a reader in the runtime shared with tidec's imports, and as many formats as practical, FBX left out for now (it would put the build's FBX reader in every game's runtime). The rules below are Claude's picks, Provisional:
  - **It reads a file as an asset of it does**, with the same code (`tide/mesh_data.h`), so the same bits on every machine and the same vertices as `asset Mesh<V>` of the file: the fields a file fills by their names (below), every other field its default, a `float4 tangent` generated where the file has none, and a vertex with `joints` or `weights` read as a mesh with bones, at rest. A `.glb`, a `.gltf` whose buffers are inside it, and an `.obj`, told by their first bytes (GLB's magic, else JSON's `{` after a byte order mark and spaces, else OBJ); a mesh with bones reads a `.glb`, as `SkinnedMesh<V>.Decode` does.
  - **`IOError.InvalidData`** for bytes that aren't such a mesh or have no triangles, a `.gltf` naming buffer files (nothing is fetched), an FBX (said as build-time only), a number a node's transform takes past what a float holds (NaN's bits aren't the same everywhere), and a file past a limit: 512 MiB, 1,048,576 vertices, 6,291,456 triangle corners, 4,194,304 JSON values and 67,108,864 numbers read (accessors as for an asset; an `.obj`'s `v` lines count six, `vn` three and `vt` two), `SkinnedMesh.Decode`'s numbers, one `#define` each in `tide/mesh_data.h`; refused from the counts the file says before what they ask for is made. A limit's refusal is said on the refusing machine's log, naming it (`tide: Mesh.Decode refused a mesh: it has ...`).
  - **What its vertex defaults read** is part of the game's identity, as for `SkinnedMesh<V>.Decode`, since the vertices can be match state.
  - **Its ID** is its contents' key, as a made mesh's: a decoded mesh and the same lists made with `Mesh(vertices, indices)` are `==`, and never an asset's.

- **Mesh assets.** `asset Mesh<V> name = "path";`, alone or as a glob's `List<Mesh<V>>` or `Map<string, Mesh<V>>` (one file where the type holds many is a list or a map of that one, as for any asset). `V` is a struct that can be a 3D mesh's vertex: a `float3 position`, and fields of floats, ints, their vectors and colors, 12 at the most.
  - **The fields a file fills, and their types:** `position` (`float3`), `normal` (`float3`), `uv` and `uv2` (`float2`), `color` (`Color`) and `tangent` (`float4`, its `w` the side the bitangent is on, or `float3` for the direction alone), `joints` (`int4`) and `weights` (`float4`). One of those names with another type is an error at the declaration. Names follow the built-in vertex and Unity's vertex attributes.
  - **A mesh with bones** (built 2026-10-30; the owner, of a crowd skinned on the GPU that needed its bones' weights, "if the engine is blocking you we should maybe target that"; each rule is Claude's pick, Provisional). A vertex with `joints` or `weights` reads its file as a skinned model, and the mesh is the model at rest: each vertex's `position` and `normal` where its bones' rest pose puts them (the sum of each bone's rest model matrix times its inverse bind, by weight), in the skeleton's space, as a `SkinnedMesh` of the file draws at rest; a vertex no bone moves stays where the file has it. `joints` are its four heaviest bones, heaviest first (a tie in the file's order), numbered as the file's `SkinnedMesh` numbers a `Bone` (`skeleton.bones.TryGetAt`); `weights` are theirs, summing to 1. A vertex with no bone has bone 0 and no weight. `[LOD]` makes its levels weighing the bones, as a skinned mesh's; the levels and the pack's mesh are another mesh than the same file's without bones.
  - **What a file hasn't got:** a `normal` is each triangle's own, the way its front faces, for vertices that triangle doesn't share (what glTF says a mesh with no normals is drawn as); `uv` and `uv2` are zeros; `color` is white. Only static `Mesh<V>` layouts declaring `float4 tangent` select a tangent-generation variant. Missing tangents in that variant are generated from triangle UV derivatives, with corner-angle weighting, normalized `xyz` orthogonal to the normal and handedness `w` of +1 or -1. Vertices shared by generated corners with opposite UV handedness split at that seam only in this variant. Missing or degenerate UVs use a finite fallback frame. This is not a MikkTSpace bake-compatibility guarantee. These generation details are provisional implementation choices (2026-10-25).
  - **Canonical imports are unchanged.** Layouts with no tangent or with `float3 tangent`, and skinned meshes, retain their prior streams, counts, indices and canonical hashes exactly; missing `float3` tangents remain zero. A generated variant is separate from the canonical import and cannot change another declaration's data. Metadata-only language-server checking uses canonical data and does not generate variants.
  - **Authored tangents** retain their existing coordinate/node-transform conversion, including authored zero and nonorthogonal values. The normalization and orthogonality guarantees above apply to generated tangents only. Within a static `float4 tangent` variant, authored tangents in one primitive do not prevent generation for another primitive that has none.
  - **A field of any other name is given its default as the pack is loaded**, by the game's own code, so it's exactly what a vertex made in code starts as, whatever expression the default is.
  - **Axes.** glTF is right-handed, `+y` up, its fronts counterclockwise; Tide follows Unity, left-handed with fronts clockwise. A file's `x` is negated (positions, normals, tangents, whose `w` turns too) and its triangles wound the other way, but under a node that mirrors, which has turned them already. So `+y` stays up, what faces `+z` in the file faces `+z` here, as Unity's glTF importer has it, and nothing is mirrored. An OBJ says nothing of its axes: it's read the same way, as tools write it.
  - **A uv is (0, 0) at a texture's top left**, as glTF's is and Tide's; an OBJ's counts from the bottom, so its second number is turned over.
  - **Colors.** glTF's vertex colors and base color factors are light, and a `Color` is what the screen shows: each channel goes through the sRGB curve, kept from 0 to 1, alpha as it is. An OBJ's colors after its positions, which have no standard, are taken as written.
  - **From a glTF:** the scene it opens with (or its first; with none, every node that's nobody's child; with no nodes, its meshes as they are), each node's matrix or translation, rotation and scale, every primitive of triangles, strips or fans (points and lines are left out), accessors of every component type, normalized or not (`KHR_mesh_quantization`), with a stride and sparse; a material's `baseColorFactor`. Buffers are the `.glb`'s own, a data URI's, or files beside a `.gltf` by the paths it writes, which `tide run` watches with the rest. Nothing else is read: textures, the rest of a material, skins (the mesh is as it stands), animation, morph targets, cameras, lights, extras. Geometry compressed with Draco or meshopt is an error that says to export it without, and so is glTF 1.0.
  - **From an OBJ:** `v`, `vt`, `vn` and `f`, places counted from the end (`-1`), faces of any number of corners as fans, and a color after a position (`v x y z r g b`). A vertex of the mesh is each combination of position, uv and normal a face uses. Its `.mtl`, groups, lines and smoothing are passed over.
  - **From an FBX:** polygon meshes triangulated during import, node transforms, normals, tangents, two uv sets, vertex colors and material base colors. The source's axes and units become right-handed Y-up meters before the existing Tide coordinate conversion. Geometry and inheritance transforms use unnamed helper nodes when needed. A static mesh takes the rest geometry and ignores animation and deformation. Textures and other material properties stay outside the import. The compiler's ufbx reader is build-time code only; generated C and the runtime use the existing mesh representation.
  - **The same bits whichever machine builds.** The pack's vertices are what match code reads, so everything that makes them is the basic float operations in a fixed order: a decimal number becomes a float by a reader of tidec's own (the C library's isn't promised to round the same everywhere), a node's matrices and the normals through them are plain arithmetic, and the sRGB curve is the engine's `pow`.
  - **Limits:** 16,777,216 vertices and 8,388,608 triangles a mesh, 4,194,304 JSON values in a glTF's description, and 536,870,912 numbers read from its accessors in all (an accessor counts again for each part naming it; one without a buffer view, which is zeros, counts like one with bytes). A file past one is refused from the counts it says, before what they ask for is made, since tidels reads a game's mesh files at every keystroke and a file can be anyone's URL; a mesh at every limit takes about 3 GiB to read (Provisional, 2026-10-26: the owner asked for limits that are clear and easy to change; the numbers are Claude's picks, one `#define` each in `compiler/src/mesh_files.h`).
  - **Where a `Mesh<V>` can be:** wherever an ordinary value goes (Mesh values and collections, above), except a constant, an `is` pattern, an `extern` function's (C takes the two lists), an operator's or an `audio` declaration's.
  - **Keeping a mesh:** an asset's keeps its stable ID and resolves current geometry when read, across pack replacement and task waits; a made mesh keeps its own lists.
  - **Read-only through whatever holds it:** `mesh.vertices` and `mesh.indices` of a `mut` local are the pack's too. A copy of a list is the code's own: `mut var mine = tree.vertices;`.
  - **A draw's Mesh is worked out once**, though it stands for two arguments: `Draw.Mesh(models[next++], ...)` steps once.
  - **In the pack** a mesh is two lists' blocks, its vertices laid out as the struct is, shared by what's in the file and how the struct lays it out: two declarations of one file and one struct are one mesh, in the pack and on the GPU; the same file as two structs is two. An entry says its vertices' layout as a number, and a pack another build made, of a struct that's changed since, hasn't got the mesh: it reads as empty, and the program says so once. The draw list tells a pack's mesh by what its file had, with no vertex read, so a pack loaded again with the file as it was draws the mesh the GPU has.
  - **Not there:** the textures inside a model file (declare each texture separately) and a material beyond its color; a file's parts or materials apart; skins, animation and morph targets; a 2D mesh from a file; and a frag or a vert reading `mesh.vertices` as a list, which is an error that says to copy what it needs into a singleton's list, and is a gap by the rule that GPU code refuses only what a GPU can't do.

- **JPEG, TGA and BMP images** (built 2026-10-10): build-time `Texture`, `Grid2<Color>`, their lists/maps and cubemap faces import these alongside PNG/PSD through the existing types. Maximum dimensions remain 16384 per side; new decoder/output allocations and source size are bounded to 512 MiB, and a progressive JPEG has at most 256 scans (2026-10-26, Provisional: each scan decodes the whole picture again; Claude's pick, `TIDE_IMAGE_MAX_JPEG_SCANS` in `compiler/src/image_files.h`). Only pixels enter the pack, and runtime `grid.Decode` remains PNG-only. Profiles and JPEG EXIF orientation are not applied. See [Assets](https://tide-engine.dev/game/assets.md#image-formats) for supported variants and source-format limits.

<a id="open-13"></a>

### Open

- A model's `Mesh<V>` (above), of which what's listed under Not there is open: the textures inside a file first, as most models that tools hand over have one.
- A pack kept beside a web page rather than inside it, fetched from wherever it's hosted (the option's name, and whether a page waits for it).
- Load order, streaming and lazy loading within the pack, and what a web page fetches first.
- Decoding off the frame's thread for what a machine loads at runtime (a 4K PNG takes a frame).
- Pinning a URL to a hash of its contents, so a build is reproducible when the server changes the file.
- Big media through the match: it goes player to server to everyone, so a host's upload is the file once per player. The docs say the number; a game with big files keeps a URL in the match and each machine fetches. Whether the engine should do more than say so.

<a id="checked-asset-references"></a>

## Checked asset references

<a id="decided-17"></a>

### Decided

Components may store checked references to named model assets. Prefab text assigns
the asset name; the compiler validates the referenced asset and its type. Game
views decide how to render it (owner, 2026-10-12).

References of the same canonical asset-reference type support `==` and `!=` by
stable declaration identity, independently of geometry reloads (owner, 2026-10-25).

`Asset<T>` supports static `Mesh<V>` and `SkinnedMesh<V>` model assets, including
transparent aliases (owner, 2026-10-25). Resolving a skinned reference preserves
the current packed model's borrowed geometry and skinning data.

A static `Asset<Mesh<V>>` is the asset's ID alone, which converts to an ordinary `Mesh<V>` (an ID, or a mesh the game made: owner, 2026-11-02, superseding their being one type on 2026-10-30). Both expose `.vertices` and `.indices` directly and can be stored in ordinary collections. Static `.Value` is the `Mesh<V>` the reference names; skinned `.Value` retains its existing model-value behavior. Glob elements carry their own stable identities.

<a id="provisional-18"></a>

### Provisional

Use `Asset<Mesh<V>>` or `Asset<SkinnedMesh<V>>`. A matching singular model asset
name converts to this reference where its expected type is known, including
component defaults, prefab overrides, arguments and list elements. Static Mesh
variables and collection elements carry that identity directly. References can
be stored in either world using ordinary placement rules.

`reference.Value` preserves a static mesh handle, whose geometry members resolve
the currently loaded model. Skinned resolution returns the
original pack handles, preserving palette sharing and imported LOD metadata.
Ordinary persistent assignment of that model still acquires its usual value
ownership. `default` is an empty reference and
reads an empty mesh; unknown received identities do too. The reference stores
only a stable numeric identity derived from the qualified asset name. Geometry
replacement preserves it; changing the declaration name changes it. Identity
collisions are compile errors. No pointer or runtime type registry enters a world.

`==` and `!=` compare references of the same canonical `Asset<T>` type by
that stable declaration identity. Geometry reloads do not change equality, and
different declarations remain different even when their geometry is identical.
Two empty references are equal. Unknown received identities compare by their
stored identity; resolving both to empty meshes does not make them equal.
Aliases preserve the canonical type. A matching named asset and `default` use
their existing conversions when the other operand supplies the reference type.
References to different vertex types do not compare. Ordering and direct access
to the stored identity are not supported.

References name singular model declarations and static-mesh collection elements.
Other resource types, JSON asset-name serialization and persistent
identity migration across declaration renames are not implemented.

<a id="build-code"></a>

## Build code

Agreed 2026-11-03 and built the same day. The owner proposed processing assets with Tide code as part of the build ("be it tweaking an animation, audio, image, whatever the case might be"), chose the points under Decided, and asked for it built with every other choice Provisional ("mark any decisions you have to make provisional"). Reworked the same day, the first version's block after an asset (`asset Texture hero = "art/hero.png" { ... }`) and its `mut` parameter replaced: the owner, "I feel like it should be a function instead of a custom syntax like that? it doesn't read well to me, i feel like i should return the value". That made grids values everywhere (see Grids), and a file code reads is declared as its data.

<a id="decided-18"></a>

### Decided

- **Assets and constants can be made by code that runs at build time.** The result goes into the build as a file's contents do, so every machine has the same value and the game pays nothing for it at runtime.
- **An `asset` or `const` initializer always runs at build time.** If something in it can't, for example a value known only at runtime, that's a compile error explaining why. It never quietly runs at runtime instead.
- **Ordinary functions can be called there, and `build` marks a function that only ever runs at build time.** Unmarked functions with no side effects are allowed in build code. A `build` function guarantees build-time evaluation: it can be called only from build code, and its body is checked as build code where it's declared.
- **The initializer is an ordinary expression, and code returns the value** (2026-11-03, replacing the block after an asset and a `mut` parameter it edited): `asset Texture board = Checker(64);`, `const List<float> CURVE = Curve(64);`. No syntax of its own: a function that makes or processes an asset is an ordinary function, which can still use `mut` helpers inside.
- **`build` doesn't make code behave differently** (the owner: "i dont like `build` making code behave in a different way, that is a nono from me"). Build code follows the rules all code does, so what it needs (returning grids, holding one in a local) is the language's everywhere (see Grids).
- **A file that code reads is declared as its data**: `asset Grid2<Color> heroSource = "art/hero.png";` for an image's pixels and `asset ClipData beepSource = "sfx/beep.wav";` for a sound's samples, rather than a `Texture` or a `Clip` reading as something else in build code. `ClipData` is an asset type for that.
- **Audio and animations get values that code can read and edit**, as images and meshes already have.
- **`[LOD]` stays as the shorthand, and a game can write its own levels instead.**
- **`const` gets the same mechanism**, so a constant can be a table or another value computed at build time.

```csharp
void Outline(mut Grid2<Color> image, Color color)
{
    for (int y = 0; y < image.size.y; y++)
    {
        image[int2(0, y)] = color;
    }
}

build Grid2<Color> Outlined(Grid2<Color> source, Color color)
{
    mut Grid2<Color> image = source.Copy();
    Outline(image, color);
    return image;
}

asset Grid2<Color> heroSource = "art/hero.png";
asset Texture hero = Outlined(heroSource, Color.red);

const List<float> CURVE = Curve(64);
```

<a id="provisional-19"></a>

### Provisional

Picks made to build it, awaiting the owner:

- **What's code and what's a path**: an asset's value that calls something (`Checker(64)`, `source.Copy()`, `rulesSource + Exclaim()`) is build code, as a constant's is; anything else is a path, a constant text, as before, and an error says so when it isn't one. A block after an asset or a constant is an error that says to call a function. An asset has a path or code, not both.
- **What each asset's code returns:**
  - Text (`string`), bytes (`List<byte>`), `Grid2<Color>`, `Mesh<V>` and `ClipData`: a value of that type.
  - `Texture`: its pixels, a `Grid2<Color>` (straight alpha), which are then made a texture as a file's are: premultiplied, `[Raw]` kept, compressed as any color texture is. It must have a size on both axes, at most what an image's file can be (16384 a side, 4096 by 4096 in all), and every channel must be a number.
  - `Clip`: a `ClipData`, a built-in struct of `int rate`, `int channels` (1 or 2) and `List<float> samples`, interleaved. It's packed as a 32-bit float WAV, so every sample must be a number.
  - `Mesh<V>`: `Mesh(vertices, indices)`, packed as the code made every field, so a field's default is the code's to keep; its triangles must name vertices the mesh has.
  - A list or a map of a glob's files, a `Cubemap`, a `SkinnedMesh<V>` and the animation types can't be made by code: that's an error naming what can.
- **`ClipData` as an asset**: `asset ClipData beep = "sfx/beep.wav";` is the file's samples, decoded (WAV, Vorbis, and MP3 or FLAC as a Clip imports them), read by any code: its `rate`, its `channels` and its `samples`, as a list of floats in the pack. One file each; a glob of them isn't there.
- **A file only build code reads** isn't in a game built without what nothing reads (`--strip-unused-assets`, as release builds are), as it was the source of something else; other builds pack every asset as before.
- **A constant's value is build code** when it calls a function that isn't a constant's (`const float HALF = Twice(0.25);`). A value of literals, other constants, `Math` and constructors is still worked out while compiling, as before, and a value that reads something no constant can (a field, `Time`) is the error it was. A constant build code makes can be anything a constant can be, an array or a `List<T>` of plain values included (numbers, vectors, colors, enums and structs of those; `const int[16] SQUARES = Squares();`); a list written out, `[1, 2, 3]`, needs no build code, and holds 4096 values at the most, where a built one can be as long as the pack holds (Constants, 2026-11-14).
- **Where a built constant goes:** where a value read as the game runs goes, as an asset does: code and field defaults. Where a value has to be known while compiling (a `case` label, a bound, a setting, an asset's path) it's an error that says the build makes it, and so is another constant naming it (`const List<float> SAME = CURVE;`, `const float FIRST = CURVE[1];`), whose error names code, field defaults, and build code making that constant too (`const float FIRST = Head(CURVE);`). GPU code can't read one yet: its value goes to the frag or vert in a draw's values. In generated C a plain constant is its bytes, which C reads as its type while compiling; text is a C string; a list is the pack's, as an asset's list is.
- **What build code can do** is what a function can, but nothing of a running game: no world (queries, `Spawn`, `Send`), no `Devices`, no drawing, audio or frame time, no files or network beyond the assets it names, no tasks, and not the match's random numbers (`Math.Hash`, or a `Random` it makes with a seed, work). It reads its parameters, assets, constants and what other build code made. Each is an error at the asset, constant or `build` function, with a note at the function that does it. A `build` function called from anything but build code is an error at the call, which a field's default, a system and a view are.
- **No C in build code yet**: a build function that calls `extern` C is an error. The program that runs build code is built from the game's Tide code alone, with the engine's sources: the game's own C and libraries aren't in it, and its C functions are stubs there that nothing calls.
- **Code reads what other code made**: an asset's or a constant's code can read another's value, and that one's code runs first. Code that reads, through others, what it makes itself is an error.
- **Levels of detail of its own:** `Mesh(vertices, indices, levels)` gives the mesh `levels`, a `List<MeshLevel>`: a built-in struct of `List<int> indices` (triangles of the mesh's own vertices) and `float error` (how far that level's surface is from the full mesh's, in the mesh's units, as `[LOD]`'s levels say). A draw picks among them as it picks among `[LOD]`'s, with the destination's tolerance, `Draw.LOD` and the rest, around a ball of the mesh's vertices. At most 7, each with triangles, each error positive and never less than the level's before it. `[LOD]` and levels from the code together is an error: `[LOD(n)]`'s tolerance is the code's to put in its errors. Only build code makes a mesh with levels of its own (a `build` function, or an asset's value): elsewhere it's an error that says a draw makes a made mesh's levels with `lod:`. In the build program a mesh made with levels keeps them by its id, which is what's in it, so a mesh made again from the same lists has them too.

  ```csharp
  asset Mesh<Corner> rockSource = "art/rock.glb";

  build Mesh<Corner> Leveled(Mesh<Corner> rock)
  {
      mut List<MeshLevel> levels = [];
      levels.Add(MeshLevel { indices = Simplify(rock, 0.5), error = 0.02 });
      return Mesh(rock.vertices, rock.indices, levels);
  }

  asset Mesh<Corner> rock = Leveled(rockSource);
  ```

- **Attributes stay attributes**: `[Filter]` and `[Wrap]` are how the GPU reads a texture each frame, and a custom filter is a `frag`; `[Raw]` and `[LOD]` keep their meanings on an asset code makes.
- **How it runs:** tidec generates the program that runs build code from the checked game (its C, every `build` function and each asset's and constant's code, and a main), compiles it with the build's clang and the engine's sources, and runs it on the build machine, for a web or Android build too: what it made is the same bytes for every machine, as it's in the pack and the game's C. `build` functions are left out of the game. `tide build` and `tide run` compile it with tide's own compiler; `tide_add_game` with the machine's clang (`TIDE_CLANG`); tidec on its own takes `--build-cc`, `--build-include` and `--build-engine`, and says it can't run build code without them.
- **What's made is kept**, by a key of everything that made it: the code, every function, type and constant it reaches, the files it reads (by their contents), other code's values it reads, and tidec's version. A build whose keys are all kept runs nothing, so editing a system, or an asset no build code reads, doesn't run build code. Under `tide run`, saving a file that code reads runs it again; one that a constant's code reads rebuilds the game, as the constant is in its C. What's made is kept in the game's `.tide/` (for `tide_add_game`, its output folder), and the engine's objects for the program beside it.
- **Build code that runs more than ten minutes** is stopped, and the build fails at the asset or constant it was making. What it says (`Debug.Log`) is said as the game builds.
- **It doesn't fail otherwise**: `!` gives a type's default in build code as everywhere, and a failable call's value is unwrapped as everywhere.

<a id="open-14"></a>

### Open

- The data form of an animation: its tracks, with each track's times and position, rotation and scale values. Then skinned meshes, cubemaps, and lists and maps of a glob's files, which code makes or processes.
- C in build code: building the game's own C (and its libraries, for the build machine) into the program.
- Built constants in GPU code.
- Which data-making steps become built-in build functions besides `[LOD]`'s, for example a texture's mip chain, so `[LOD]` is shorthand for a call the code could make itself.
- Limits on build code's time and memory: the ten minutes is a pick, and memory has no limit of its own.

<a id="skinned-meshes-and-animation"></a>

## Skinned meshes and animation

<a id="decided-19"></a>

### Decided

Agreed 2026-10-08 and implemented the same day. Static `Mesh<V>` retains its flattening behavior; `SkinnedMesh<V>` preserves skeletons and animations. Implementation choices beyond the agreed design are recorded under Provisional.

- **A skinned model is a `SkinnedMesh<V>`.** It provides geometry over the game's vertex struct, its skeleton and its animations. A mesh is shared independently of playback: several characters can use the same model with different poses.
- **A pose is separate from the mesh.** Animation produces a pose; game code can read and edit its bones, and drawing uses it to deform the mesh. Both match systems and views can sample and use poses, including for sockets, hitboxes and root motion. Sampling and blending are deterministic CPU operations using Tide's math. GPU deformation is for drawing and never supplies match results.
- **Humanoid retargeting belongs to the runtime Pose API** (agreed 2026-10-30). Tide works independently of tide-motion. Automatic role discovery supplies a useful initial mapping, with explicit typed-bone overrides, reusable editable reference poses, inspectable assignment status and configurable root/chain controls. `HumanoidRig.Auto(referencePose)`, `rig[HumanoidBone.LeftHand] = bone`, `RetargetMap.Create(actualSourceSkeleton, sourceRig, targetRig)` and mutable `pose.Retarget(sourcePose, mapping)` separate preparation from repeated transfer. The actual animation export's skeleton is distinct from its calibration reference; an export's first-frame defaults need not be its anatomical reference pose. Existing same-rig sampling/binding remains unchanged. Detailed preparation, error and settings rules are provisional below.
- **Imported humanoid motion can be retargeted at build time** (agreed 2026-10-30). `asset HumanoidRig sourceRig = "source.humanoid.json";` imports a reusable automatic/manual calibration profile. `[Retarget(sourceRig, targetRig)]` on an `Animation` or `AnimationCatalog` asset bakes ordinary target-skeleton clips using the same algorithm as runtime retargeting. Playback does no retarget work. Runtime preparation and pose transfer remain available for dynamically loaded assets.
- **Dynamically loaded motion can be baked once** (agreed 2026-10-30). A prepared map's `Bake(source, targetSkeleton[, sampleRate])` accepts an `Animation` or `AnimationCatalog`, returns the corresponding ordinary animation value, and `fails IOError`. The default rate is 60 Hz. The result owns its data independently of the source, map and target; playback performs ordinary sampling with no retarget work.
- **Drawing has its own call, `Draw.SkinnedMesh`.** Its pose is optional: omission uses the model's authored rest transforms. `model.defaultPose` returns those transforms as an editable Pose, including for a model with no animation clips (agreed 2026-10-10). The implemented argument list and pose operations are below.
- **Animation catalogs can be separate assets.** `asset AnimationCatalog movement = "art/movement.glb";` exposes the file's clips directly, such as `movement.run`. The editor offers checked names from a known file. Clips from separate exports of the same rig can be sampled into a character's pose or drawn with its model (agreed 2026-10-10); binding details are below.
- **Blend shapes are imported and baked on the CPU** (decided by the owner, 2026-10-27: "Import + bake: Skinned imports (FBX and glTF) keep morph targets; a CPU call returns the model with chosen shape weights applied, e.g. part.Shaped(weights). Draws unchanged. Body shape is set per character, as Synty's own tool bakes it. No GPU/shader changes."). GPU per-draw shape weights and shape-weight animation were not chosen and remain outside. The implemented API is under Provisional.
- **Catalog lookup uses bool/out methods.** The animation catalog type is `AnimationCatalog` (agreed 2026-10-11). Animation and bone catalogs expose `TryGetAt(index, out result)` and `TryGetByName(name, out result)`; skeletons also expose `TryGetByName`. Success assigns the selected value and returns true. Failure assigns `default` and returns false, including out-of-range indices and missing, empty or ambiguous names. Checked dot members remain available.
- **Contracts are optional.** `SkinnedMesh<V>` needs no empty contract. `SkinnedMesh<V, C>` declares required members through a contract `C`. A contract specifies a required subset of the model's content: extra clips and bones remain available for dynamic discovery and lookup. A known asset is checked during compilation; a runtime-loaded value with a contract is checked before that value is successfully made available.
- **A known asset provides checked members without a written contract.** For a single asset declared without a contract, the compiler reads its animation and bone names and exposes them as members, such as `hero.animations.idle` and `hero.skeleton.bones.head`. A missing member is a compile error. An `asset` URL is known this way too, since it is fetched during compilation as other asset URLs are. A contracted value guarantees its declared requirements.
- **Dynamic lookup remains available in every case.** `hero.animations.TryGetByName(name, out result)` returns a bool and assigns an `Animation` result; bone lookup follows the same pattern with a `Bone` result. A runtime-loaded model with no contract uses lookup and enumeration. A model with inferred or declared members supports those operations as well. A clip obtained through a checked member and one found dynamically are ordinary animation values used by the same sampling and blending operations.
- **A bone member produces a typed reference.** The reference identifies the bone within its skeleton and lets a pose reach that bone without looking up text at every edit. Name lookup resolves such a reference. The implemented type is `Bone`, used as `pose[head]`, below. Skeleton compatibility is distinct from the presence of names: two models both having an animation named `run` does not establish compatible skeletons.
- **Inference retains known members.** `var character = hero;` keeps a known asset's inferred members. A general parameter written as `SkinnedMesh<V>` promises the common dynamic API; a helper requiring checked members declares a contract or receives the selected `Animation` or `Bone` directly. A declared contract keeps its guarantees when the model passes through helpers and collections.
- **Names have explicit rules.** Inferred identifiers keep ASCII letters, digits and underscores, lowercasing an initial uppercase letter and capitalizing a lowercase letter after a separator: `Idle` becomes `idle`, `Root|Run` becomes `rootRun`, and `Right Hand` becomes `rightHand`. Leading digits, keywords, reserved `tide_` names and catalog operation/internal field names receive an underscore prefix. Nonempty punctuation-only names become `_`; unnamed entries have no dot member. Collisions receive a one-based source ordinal suffix, adding underscores to avoid authored aliases. Original duplicate animation names remain accessible through distinct checked members; original duplicate bone names require enumeration. `[Name("original name")]` on a contract field supplies an exact source alias; unaliased contracts retain their first-letter-only matching. `TryGetByName` uses the exact original spelling and returns false for duplicates, assigning `default` to its output.
- **The editor understands these members.** Completion and hover expose inferred and contracted animations and bones, and member diagnostics agree with the compiler. Reading model metadata must keep editing responsive; ordinary completion must not wait for a full geometry import or a URL download. Cache and refresh details are below.
- **Runtime fetching follows the existing local/match boundary.** A URL fetched while playing is local, unlike an `asset` URL. Content that affects match bones or root motion must enter through synchronized match data, as other runtime files do; a system does not fetch its own copy independently.

There are three forms of member access:

| Model | Checked members | Dynamic access |
|---|---|---|
| Compile-time asset, no explicit contract | Inferred from the file | `TryGetByName` and enumeration |
| Runtime-loaded model, no contract | None inferred from its unknown contents | `TryGetByName` and enumeration |
| Model with an explicit contract | The declared requirements, validated before use | `TryGetByName` and enumeration, including extra content |

These examples use source names `Idle`, `Run` and `Head`, exposed as `idle`, `run` and `head`.

```csharp
asset SkinnedMesh<Corner> hero = "art/hero.glb";

// No written contract is needed for the known asset.
var idle = hero.animations.idle;
var head = hero.skeleton.bones.head;

var character = hero;
var run = character.animations.run;

// Lookup is also available for names chosen while playing.
if (hero.animations.TryGetByName(emoteName, out var emote))
{
    var pose = emote.Sample(0);
    Draw.SkinnedMesh(hero, float4x4.identity, pose);
}
```

<a id="provisional-20"></a>

### Provisional

The following API and failure behavior are implemented. These detailed choices remain provisional where the owner's agreed points above do not settle them. A contract is an ordinary struct whose required fields are `Animation` or `Bone`, without defaults or local fields:

```csharp
struct Locomotion
{
    Animation idle;
    Animation run;
    [Name("Right Hand")] Bone hand;
}

asset SkinnedMesh<Corner, Locomotion> hero = "art/hero.glb";
```

`Locomotion` requires animations whose normalized identifiers are `idle` and `run`, and a bone whose exact source name is `Right Hand`. Extra content remains available through dynamic lookup and enumeration. Checked contract catalogs expose the required fields; they do not additionally infer other dot members. `count`, `TryGetByName` and `TryGetAt` are reserved catalog operation names. A duplicate exact source name makes `TryGetByName` return false and assign `default` and cannot satisfy an exact contract alias. A `Name` alias cannot be empty, including on a contract used only by a helper parameter. Unnamed entries are accessible through `TryGetAt`; `TryGetByName("", out result)` returns false and assigns `default`.

The CPU operations are:

| Value | Operation | Result |
|---|---|---|
| `model` | `.vertices`, `.indices` | Read-only geometry lists |
| `model` | `.animations`, `.skeleton` | Immutable catalogs and hierarchy |
| `model` | `.defaultPose` | A new authored-rest `Pose` |
| `model` | `.blendShapes` | The model's blend shapes, in order |
| `model` | `.Shaped(List<float> weights)` | The same model type with those weights applied |
| `model.blendShapes` | `.count`, `.TryGetAt(int index, out BlendShape result)`, `.TryGetByName(string name, out BlendShape result)` | `int`, `bool`, `bool` |
| `blendShape` | `.name`, `.weight` | Original name as `string`, the file's default weight as `float` |
| `model.animations` or `AnimationCatalog` | `.count`, `.TryGetAt(int index, out Animation result)`, `.TryGetByName(string name, out Animation result)` | `int`, `bool`, `bool` |
| `skeleton.bones` | `.count`, `.TryGetAt(int index, out Bone result)`, `.TryGetByName(string name, out Bone result)` | `int`, `bool`, `bool` |
| `skeleton` or `skeleton.bones` | `.NameOf(Bone bone)` | The bone's source name as `string`; empty for a default `Bone` or one of another skeleton |
| `skeleton` | `.TryGetByName(string name, out Bone result)`, `.RestPose()` | `bool`, `Pose` |
| `bone` | `.index`; `a == b`, `a != b` | Read-only place in its skeleton as `int`; the same bone of the same skeleton (Provisional, 2026-10-30: Claude's picks for the bannerlord-duel gaps) |
| `animation` | `.name`, `.duration` | Original name as `string`, seconds as `float` |
| `animation` | `.Sample(float seconds[, Playback playback])` | A new `Pose` |
| `animation` or `pose` | `.skeleton` | The original `Skeleton`, with dynamic bone lookup |
| Mutable `pose` | `.Sample(Animation animation, float seconds[, Playback playback])` | Reuses the pose's transforms |
| Mutable `pose` | `.Blend(Pose other, float weight)` | Blends toward `other` in place |
| `pose` | `[Bone bone]` | Parent-local `BoneTransform` |
| `pose` | `.Model(Bone bone)` | Accumulated model-space `float4x4` |
| `pose` | `.Models()` | `List<float4x4>`: every bone's `Model`, by `bone.index`, bit for bit, in one pass (2026-10-31, the owner's "OK" to the proposal; Provisional); empty for a pose of no model |
| `HumanoidRig` | `.Auto(Pose referencePose)` | A partially or fully discovered `HumanoidRig` |
| Mutable `rig` | `.referencePose`, `[HumanoidBone bone]` | Editable calibration `Pose`, typed `Bone` assignments |
| `rig` | `.GetStatus(HumanoidBone bone)` | `HumanoidBoneStatus` |
| `RetargetMap` | `.Create(Skeleton source, HumanoidRig sourceRig, HumanoidRig targetRig)` | `RetargetMap fails RetargetError` |
| `mapping` | `.Bake(Animation source, Skeleton target[, float sampleRate])` | `Animation fails IOError`; default rate 60 Hz |
| `mapping` | `.Bake(AnimationCatalog source, Skeleton target[, float sampleRate])` | Plain `AnimationCatalog fails IOError`; default rate 60 Hz |
| Mutable `pose` | `.Retarget(Pose source, RetargetMap mapping)` | `bool`, replacing target transforms only on success |

`BoneTransform` has `float3 position`, `quaternion rotation` and `float3 scale`; its default rotation is identity and default scale is one. `Playback.Clamp` is the default; `Playback.Loop` wraps positive and negative times over the clip duration, with an exact endpoint wrapping to zero. Unanimated properties begin from authored rest transforms on every sample. Blending clamps weight to zero through one and interpolates local transforms with shortest-path quaternion interpolation. A bone includes its skeleton identity; an invalid or incompatible bone reads the identity transform, and its writes do nothing. In-place sampling binds a compatible separate export to the destination skeleton; blending requires identical skeleton fingerprints. Failed in-place sample or blend leaves the destination unchanged; an unbindable pose records no skinned draw.

Pose use:

```csharp
mut var pose = hero.animations.idle.Sample(seconds, Playback.Loop);
var running = hero.animations.run.Sample(runSeconds, Playback.Loop);
pose.Blend(running, moving);

var head = hero.skeleton.bones.head;
pose[head].rotation = Math.Mul(pose[head].rotation, lookRotation);

Draw.SkinnedMesh(hero, transform, pose);
var weaponTransform = Math.Mul(transform, pose.Model(rightHand));
Draw.Mesh(sword, weaponTransform);
```

Separate animation files:

```csharp
asset AnimationCatalog movement = "art/movement.glb";

Draw.SkinnedMesh(hero, transform); // Authored rest, even with no clips.
mut var pose = hero.defaultPose;
pose.Sample(movement.run, seconds, Playback.Loop);
Draw.SkinnedMesh(hero, transform, pose);
```

- **Blend shapes** (built 2026-10-27; names and rules beyond the owner's decision are Claude's picks). `model.blendShapes` is a catalog with `count`, `TryGetAt` and `TryGetByName` (exact original names; missing, empty and unnamed names return false and assign `default`); it has no checked dot members. `BlendShape` has `name` and `weight`, the file's default, which the model's vertices already have. `model.Shaped(weights)` returns the receiver's type with the same skeleton, animations, indices and model data and a new vertex list: weight `i` is shape `i`'s absolute weight, glTF's convention (0..1 authored, other values extrapolate); a missing or non-finite weight is the default. Each shape whose weight differs from its default adds `(weight - default) * delta` to the `position`, `normal` and `tangent` fields (by the mesh field-name rules, a float3 tangent or a float4's xyz) of the vertices it moves, in shape order with basic IEEE operations; an addition that would leave float range leaves that number unchanged, and normals are not renormalized. Other fields are copied. The result is deterministic and usable in match code and views; with no weight differing from its default the original vertices are returned. glTF targets of one name in `extras.targetNames` form one shape across meshes and must share their `weights` default; unnamed targets are separate shapes; POSITION, NORMAL and TANGENT targets are read, other attributes ignored; animation channels targeting `weights` are skipped. FBX blend channels become shapes named after their target shape with the channel's default percentage; a channel with in-between shapes is refused. Static `Mesh<V>` imports keep rest geometry. Shapes are limited to 4,096 per model and 2,097,152 moved vertices across all shapes.
- **Choosing parts to import** (the owner took Claude's recommendation, 2026-10-30, for packs with every outfit piece on one skeleton in one file; the name and rules are Claude's picks, Provisional). `[Parts(pattern, ...)]` before a `SkinnedMesh<V>` asset (single, list, map, glob) keeps only the parts whose name matches one of the constant text patterns, `*` matching any run of characters as in `[BlendShapes]`. A part is a node holding a mesh; an FBX geometry helper's (an unnamed node the importer adds for a geometric transform) is its parent's. The others' meshes, and skins only they use, are left out before their data is read or checked, so a file past the decoder's limits imports as the parts chosen. A node is left out with them when it holds a part left out or is a group whose children all are, and neither it nor anything under it is a part kept or a skin's joint (FBX: or a bone); every node it leaves out has every child left out, and animation channels of those nodes are dropped. Bones, sockets and empty nodes holding no part stay. No part matched is an error naming some of the file's parts; at least one pattern is required, and the attribute on any other declaration is an error. A humanoid profile's `reference` takes the same list as `"parts"`.
- **Choosing blend shapes to import** (decided by the owner, 2026-10-27: "An asset attribute keeps only some shapes, e.g. [BlendShapes("masculineFeminine", "default*")] (names, * patterns)."). `[BlendShapes(pattern, ...)]` before a `SkinnedMesh<V>` asset (single, list, map, glob) keeps only the shapes whose exact source name matches one of the constant text patterns, where `*` matches any run of characters (none included) and every other character itself; the rest are dropped from the canonical model, which is written as the decoder writes one, so keeping every shape gives the same bytes and keeping none a version 1 model. The vertices keep every shape at its file default. No attribute keeps every shape. `[BlendShapes()]` keeps none, a pattern matching nothing in a file is not an error, an unnamed shape is kept only by a pattern that matches the empty name (`*`), and the attribute on any other declaration is an error (Provisional, Claude's picks).
- **Explicit skinned instances** (agreed 2026-10-20). `Draw.Instanced(model, instances[, texture[, filter[, wrap]]...][, vert][, frag][, values])` and a render target's `Instanced` accept `SkinnedMesh<V>`. Instance structs use the existing optional `float4x4 transform` field, with identity when absent, and an optional `Pose pose` field. If present, `pose` must be a Pose; an invalid or incompatible value skips only that item. If absent, the item uses authored rest, including models without clips. `List<float4x4>` draws rest instances. Ordinary instance shader fields retain their existing read-only binding and selective upload; Pose remains CPU-only. Each item captures its pose before return, including separate-file binding through the same rules as `SkinnedMesh`. Compatible captures use the existing palette batching and attribute-limit fallback.
- **Separate-file binding** (name/hierarchy rule agreed 2026-10-11). Required nodes match by unique exact source names and their parent chains. Node order, authored default poses and unrelated unanimated branches may differ. Required source local transforms are copied directly, including unanimated required ancestors; no adaptation of proportions or coordinate spaces is performed. An unnamed identity scene wrapper directly under the canonical root is transparent only while its source pose and relevant clip channels remain at rest; animated wrappers and deeper unnamed ancestors are rejected. A named top-level node (under the root or that wrapper) whose name is absent from the other hierarchy is folded (2026-10-27, Provisional): a source node's local transform, sampled with its clip or taken from the source Pose, is composed into its bound children's locals, and a target node's rest transform is divided out of them. This binds the armature-object node that Blender's FBX and glTF exporters write above the skeleton. Folded scales must be uniform within a relative 1e-5, otherwise binding is rejected; a top-level source node with no bound child is skipped (below). A rejected binding reports its reason on the console once per model pair and clip. In-place sampling binds the selected clip's animated nodes and their ancestors, and starts other target nodes at rest. Drawing a source Pose also binds procedurally changed nodes and every source clip's channel targets and ancestors, since a Pose does not retain its selected clip. **Nodes the target lacks are skipped** (decided by the owner, 2026-10-27: "A clip may animate nodes the model lacks; those are skipped instead of refusing the whole pose (as Unity does). Parent chains and names that ARE present must still match."): a required source node with no same-named target node (other than a folded top-level node above bound bones) is left out with its channels. A node present in both must have its source parent bound to its target parent (after the wrapper and fold rules), so a present node below a skipped one is rejected, never re-parented (Provisional, Claude's pick). Ambiguous required names, unnamed required nodes, changed parents, and a clip or pose whose named required nodes are all absent from the target reject binding. Exact skeleton compatibility, Bone identity and blending still include authored rest transforms. Sampling into `hero.defaultPose` gives a Pose that can use `hero.skeleton.bones` for edits and sockets. Direct drawing of `movement.run.Sample(seconds)` is also supported, but its Pose retains the animation file's skeleton identity.
- **Standalone catalogs.** `AnimationCatalog` assets accept animation-only or model-containing glTF 2.0 (`.gltf`, `.glb`) or binary/ASCII FBX (`.fbx`) files and expose `count`, `TryGetAt`, `TryGetByName` and inferred direct clip members. A plain `asset AnimationCatalog movement` accepts one path, a glob or a nonempty list of constant string paths/globs, producing one combined catalog (agreed 2026-10-11). Files follow list order, each glob follows path-byte order, repeated resolved files occur once, and clips retain source order. When cleaned names collide across combined sources, cleaned filename stems prefix those aliases (`walkRoot0TargetingPose`); remaining collisions receive flattened source ordinals. `TryGetAt` uses flattened clip order; `TryGetByName` searches exact original names across all sources and returns false for ambiguity, assigning `default` to its output. Each clip retains its original source skeleton; no merged rig is constructed. These are build-time imports, with no runtime `AnimationCatalog.Decode`. `var` retains checked members; explicit `AnimationCatalog` annotations and list/map asset elements expose the dynamic API. An `asset Animation run = "run.fbx"` requires exactly one source clip; `[Name("Root|Run")]` selects a unique exact original clip from one file. Missing, ambiguous and implicit zero/multiple-clip selections are errors; singular Animation assets do not accept globs or file lists.
- **Import and runtime loading.** Assets accept glTF 2.0 `.gltf` and `.glb`, and binary or ASCII `.fbx`. Node hierarchy and authored local transforms are preserved, including animated non-joint parents; the skeleton contains all source nodes and a synthetic identity root. Several skins keep their own inverse-bind palettes; glTF's supplied consecutive joint/weight sets are preserved and positive weights are normalized in a fixed order. glTF animation channels support STEP, LINEAR and CUBICSPLINE. FBX imports linear or rigid skin weights and converts declared axes and units to Y-up meters. Animation stacks become clips shifted to zero with their authored duration; nonlinear transform curves are resampled at 60 samples per second into LINEAR channels, retaining source keys within the clip and stepped changes; Euler rotation keys are first unwrapped to within half a turn of the key before and, where all three axes share key times, written as whichever equivalent triple is nearer it (2026-10-27, a bug fix). LINEAR rotation keys are sampled the shorter way whatever their signs. Geometry and inheritance transforms can add unnamed helper nodes. Skinned FBX rejects dual-quaternion skinning (a `Blend` skin whose vertices' dual-quaternion weights are all zero is linear, and imports; 2026-10-30, a bug fix), several skin deformers on one mesh and external vertex caches. Morph targets are kept as blend shapes (above); an FBX channel repeating an earlier one of its mesh exactly (name, offsets, default weight 0) is left out, as it moves nothing more (Provisional, 2026-10-30). Vertex fields follow the static mesh's naming/default rules. `SkinnedMesh<V>.Decode(List<byte> bytes)` and the contracted form return a model `fails IOError`, accepting self-contained GLB bytes and returning `IOError.InvalidData` for malformed data, external resources or unmet contracts. A file past a decode limit is also `InvalidData`, refused from the counts it says before what they ask for is made: 1,048,576 vertices, 6,291,456 triangle corners, 65,536 nodes, animations and buffers, 4,096 skins, 262,144 inverse binds, 8,388,608 vertex influences (each joint/weight set counts four a vertex), 262,144 channels, 16,777,216 key numbers, 4,096 blend shapes and 2,097,152 vertices moved by them, 67,108,864 numbers read from accessors over the decode (an accessor counts again for each part naming it; one without a buffer view counts like one with bytes), 4,194,304 JSON values and 512 MiB of file or decoded model, so a model at every limit takes about 600 MiB to decode and a small hostile file can't take every machine's memory or minutes. Build-time `SkinnedMesh` and `Animations` imports use the same decoder and limits (Provisional, 2026-10-26: the owner asked for limits that are clear and easy to change; the numbers are Claude's picks, one `#define` each in `tide/skinned_data.h`). Fetching remains separate. Model bytes, animation values and mutable poses use ordinary list/struct ownership and can be stored in match or local fields.
- **Type boundaries.** `var` retains a single known asset's catalog. Explicit plain generic types expose dynamic catalogs; contracted helper parameters and list/map elements expose their common contract. Inferred or contracted model conversions are checked against the destination requirements. Collection asset imports provide their common type rather than per-item inferred dot members; selection does not invent a union of unrelated catalogs.
- **Drawing and shaders.** `Draw.SkinnedMesh(mesh, transform[, pose][, texture[, filter[, wrap]]...][, vert][, frag][, values])` has the same form on a render target. Omission supplies authored rest; an explicit invalid Pose remains invalid. Skinning precedes the user `vert`, providing mesh-local positions, normals and tangents before the draw transform and camera. Inverse-bind offsets apply to deformation, not to `pose.Model(bone)`, which is suitable for sockets. The renderer supports nonuniform scale and tangent handedness. A draw captures its current pose; later edits and samples cannot change that capture. Consecutive compatible draws of an imported model can batch even with different poses; shader, texture, uniform and draw-setting differences still separate batches. Pose lists use ordinary copy/snapshot rules and have no automatic view interpolation; a view can sample from its chosen playback time. Sampling does not move entities or send animation events.
- **Responsive editor metadata.** A dedicated cached reader extracts catalogs and hierarchy from `.gltf` JSON or a `.glb` JSON chunk without reading geometry, sample buffers, side files or the BIN chunk. FBX inspection reads its source while skipping geometry, animation curves and embedded content. Watched changes invalidate metadata even with unchanged size/time; source and contract edits reuse unchanged metadata. URLs use an existing local cache without fetching, retaining the original URL's source extension for format detection. Invalid and unavailable imports are diagnosed separately from missing checked members, and contract completion remains available. Cold inspection is synchronous: 16 MiB of glTF JSON, or 64 MiB of FBX source with 128 MiB each for temporary and result parser allocations. No asynchronous indexing protocol is built. Full builds perform authoritative import validation. Details and measurements are in `notes/editors.md`.
- **Imported match content.** Canonical skeleton, animation and model data and the vertex layout participate in the generated game's compatibility identity, including standalone `AnimationCatalog` assets and their collection keys. Loading a pack checks each declaration's expected content and shape before replacing the current pack; changed content requires its matching game build. A rejected replacement leaves the old pack available. This is separate from a Pose/Bone skeleton fingerprint, which checks structural pose compatibility rather than peer admission.

<a id="humanoid-retargeting-details"></a>

#### Humanoid retargeting details

Implemented 2026-10-30. The owner agreed the workflow above; detailed discovery
thresholds, required roles, error members and distribution behavior are
provisional implementation choices.

`HumanoidBone` uses Unity's `HumanBodyBones` names and order: `Hips`, left/right
upper legs, lower legs, feet, `Spine`, `Chest`, `Neck`, `Head`, left/right
shoulders, upper arms, lower arms, hands, toes, eyes, `Jaw`, left fingers then
right fingers (thumb, index, middle, ring, little, each proximal, intermediate,
distal), then `UpperChest`. There are 55 roles and the usual enum `Count()`;
there is no sentinel member. `HumanoidBoneStatus` is `Missing`, `Automatic`,
`Uncertain`, `Manual` in that order. Discovery uses names, hierarchy and
reference geometry; ambiguity stays inspectable. Hips, head, upper/lower arms
and legs, hands and feet are required by preparation. Other roles are optional.

A profile owns its reference pose and role lists. A typed assignment must
identify a bone in its original reference skeleton; a mismatched bone is ignored.
`default` unmaps the role. Either valid edit records `Manual`. Missing and
out-of-range roles read as `default` Bone; out-of-range status reads as `Missing`
and assignment does nothing. `HumanoidRig { referencePose = pose }` supports fully
manual mapping. Assignments initialize other roles as missing. Changing reference
transforms does not rerun discovery. Replacing the reference with a different
skeleton makes preparation fail; use a new profile for that skeleton. A role
assignment is a value and cannot be passed by `mut` or `out`; collection elements
follow the existing copy/edit/replace rule.

`RetargetMap.Create` resolves the actual source export against the calibrated
source rig once, including node order, supported wrappers and changed defaults,
then freezes both references, anatomical frames and correspondence into owned
pointer-free data. Existing maps do not change when their profiles are edited.
Failure is a `RetargetError`: `InvalidRig` (1), `MissingBone` (2),
`AmbiguousBone` (3), `InvalidReferencePose` (4), `IncompatibleSkeleton` (5),
`UnsupportedScale` (6). Required uncertain roles require a manual assignment.
Reference transforms must be finite with positive local scale. Non-uniform scale
is accepted where the transfer neither reads nor writes anything at or below it:
a required role there is `UnsupportedScale`, an optional one is unmapped for the
map, and Auto still names what it matches (Provisional, 2026-10-30: the owner took
Claude's recommendation to ignore bones no role uses; before, any non-uniform node
refused the rig). Invalid hierarchy, ambiguous correspondence and unsupported
scale are rejected. Runtime
diagnostics describe the failing role or correspondence.

Prepared maps expose mutable `float rootScale` (initial target/source leg-length
ratio), `float3 rootOffset` (model-space metres, initially zero),
`float headingDegrees` (initially zero), `float spineDistribution` and
`float twistDistribution` (both initially one). `rootScale = 0` removes travel.
Heading rotates about the target reference hips and up axis. Distribution values
range from zero to one: the first controls interpolation along extra spine/neck
nodes, the second longitudinal twist in helper bones; limb swing stays at its
mapped joint. A default map has unit scale/distributions but no prepared data.

`Retarget` preserves target calibration lengths, scales and skeleton identity.
It applies source motion relative to the reference's anatomical frames, leaving
normal target-bone edits, sockets, blending and drawing available. Artistic
per-bone rotation offsets are ordinary pose edits after transfer; calibration
describes reference anatomy. Transfer covers rotations and hips translation;
animated local translations on other nodes are not copied. Palm/leaf roll with
insufficient anatomical rays may need calibration or a post-transfer edit.
Invalid input, incompatible source/target skeletons,
invalid settings or unsupported source scale animation return `false` without
changing the destination. Source/output aliasing is supported. Profiles, maps
and poses use ordinary owned-value, match snapshot and serialization rules.
`Animation.skeleton` and `Pose.skeleton` expose dynamic catalogs; inferred model
catalogs retain their checked members and can pass to a plain `Skeleton` parameter.
No per-frame name resolution, IK/contact correction, foot planting or automatic
entity movement is added.

`mapping.Bake` uses the prepared correspondence and the map's current settings.
It retains source names/durations and the target's original skeleton identity,
names, order and rest transforms, excluding geometry and unrelated source clips.
The single-animation overload bakes only the selected clip. The catalog overload
bakes every source in catalog order, preserving duplicate names and ordinary
ambiguous-name lookup rules; it returns a plain catalog with dynamic lookup.
Every source must match the actual source skeleton used to prepare the map, and
`target` must match its target skeleton. Changing a map afterward does not change
an existing baked result.

Baking is a CPU operation. Invalid/default maps or clips, empty catalogs,
incompatible skeletons, invalid settings, unsupported scale animation and work
limit refusals return `IOError.InvalidData`; the runtime diagnostic explains the
reason. Catalog failure returns no partial output. `sampleRate` must be finite
and positive, with zero also selecting the default 60 Hz. The shared baker uses
the sample/interpolation rules below and bounds total work across catalog
sources. Results can be stored, copied, snapshotted and serialized independently
of all input values and loaded asset packs. Store the successful result once and
sample it during playback.

<a id="imported-humanoid-profiles-and-baked-clips"></a>

#### Imported humanoid profiles and baked clips

Implemented schema and bake controls are provisional details of the approved
profile/attribute design. A `HumanoidRig` asset names one JSON document. Its
`reference` object requires `file` plus either `pose: "rest"` or an exact unique
`clip` name and finite `seconds` within the clip duration, and optionally `parts`,
a non-empty list of `[Parts]` patterns its model is read with (Provisional,
2026-10-30). Files resolve relative
to the profile through ordinary glTF/FBX import, including external buffers.
The referenced model's original skeleton identity is retained even when a
sampled clip or edits supply different reference transforms.

Optional `bones` maps `HumanoidBone` names to unique exact reference bone names
or `null` to unmap them. Optional `referenceEdits` maps exact bone names to local
`positionOffset` (three metres), `rotationOffsetDegrees` (X/Y/Z degrees, applied
Z then X then Y as quaternion.Euler, postmultiplied) and positive uniform
`scaleMultiplier`. Calibration edits precede
automatic discovery; explicit mappings follow it and have `Manual` status.
Unknown keys, duplicates, invalid values and missing/ambiguous explicit bones
are errors. Partial discovered profiles are valid values; preparing a bake still
requires a valid complete mapping for every required role.

`[Retarget(sourceRig, targetRig)]` takes two profile asset names, followed by
optional named numeric constants `rootScale`, `headingDegrees`,
`spineDistribution`, `twistDistribution`, `sampleRate`, and a constant
`float3(...)` `rootOffset`. Settings use the runtime map's validation/defaults;
omitted root scale is automatic and the default sample rate is 60 Hz. A selected
`Animation` bakes its selected clip; catalogs bake every clip and retain names,
source order and inferred members. Target clips preserve the original target
skeleton names/order/rest/hash and source duration. Sampling includes regular
grid samples, authored keys, endpoints and adjacent float times around STEP
changes; ordinary interpolation between samples approximates the live transfer.
Geometry and unrelated animations are excluded from profile/bake payloads.

Profiles, reference files and their side buffers are transitive build/watch
dependencies. Derived clip caches are keyed by canonical source bytes, both
calibrated profiles, options and baker version; raw imports are never mutated.
Profile assets can be read/copied/edited with the runtime API and use ordinary
owned-list snapshots and serialization. Whole compiled profile payloads are
authenticated before replacing a loaded pack. Profiles used only during baking
can be omitted from a stripped runtime pack.

- **Baked poses for crowds** (2026-10-31; asked for by a game that had built GPU crowd animation by hand twice: the owner, "would it make sense to put this GPU accelerated skinning stuff in Tide?", with the API's shape, its names and its storage left to the engine; every rule is Claude's pick, Provisional). Tide code that comes with the compiler (`<tide>/baked.tide`, compiled with a game that names one of its types):
  - `BakedPoses.Of(model.defaultPose)` makes an empty table for a model's skeleton; `poses.Add(pose)` adds a row (one pose's skinning: each bone's model matrix times its rest one inverted, kept as the top three rows, 48 bytes a bone) and returns its number, or -1 for another skeleton's pose or past what the GPU's list holds (699,050 bone-rows); `poses.AddClip(clip, rate[, playback])` adds a clip's rows, whole steps over its duration at about `rate` a second, sampling it onto the model (`pose.Sample`'s binding), and returns a `BakedClip` (`first`, `count`, `duration`, `loops`). A looping clip has no row at its end. Rows are built on the CPU, once, where the game says; the GPU keeps the list while it doesn't change.
  - A `BakedFrame` is what an instance shows: `rows` (an `int4`: a row, the row it goes on to, and the same of the frame it fades from) and `blend` (how far on to each next, how much of the first pair shows, and 1 for each corner to follow its heaviest bone alone). `clip.At(seconds)` gives one, held at the ends or round where it loops, the row before 0 its first and NaN its first; `BakedFrame.Row(row)`, `BakedFrame.Between(row, next, t)`, `frame.FadedFrom(from, shown)` and `frame.HeaviestBone(alone)` make or change one.
  - `poses.SkinRows(frame, joints, weights)` is a corner's skinning as its matrix's top three rows (a `BakedBone`, with `Point` and `Direction`), `poses.Skin` the same as a `float4x4`, `poses.BoneSkin(frame, bone)` one bone's, and `poses.Socket(frame, socket)` where a socket (`poses.AddSocket(bone[, offset])`) is in the model: the same methods on the CPU and the GPU. A corner reads all four of its bones whatever their weights (a branch costs the GPU more than the reads). Between rows the matrices blend linearly, so a joint turning fast between two rows comes out short of its length (the rate is the remedy). `BoneSkin` and `Socket` of a bone or socket that isn't there are the identity; a corner's joint past the skeleton reads another bone's row or zeros.
  - `BakedSkin` is a vert for a `BakedVertex` (`position`, `normal`, `uv`, `joints`, `weights`) and a `BakedInstance` (`transform`, `frame`, `tint`): `Draw.Instanced(mesh, items, [texture,] BakedSkin, frag, poses)`. A game's own vertex or instance struct takes a vert of its own that calls `poses.Skin`. The mesh is a `Mesh<V>` with bones, the model at rest, so rows are only right where the rest pose is the bind pose.
  - `BakedFader` (`Play(clip, seconds, dt)`, `Show(frame, kind, dt)`, `Cut()`, `fadeSeconds` 0.2) keeps what an instance showed, so a jump to another clip (or another `kind`) fades from what it showed, eased; a jump in a fade's first half fades from what it was fading from.
  - Open: per-bone layers (lower body from one row, upper from another, joined at a bone), baking at build time, quaternion storage, a choice of the heaviest bone by distance in the vert, and automatic culling bounds for its draws.

<a id="open-15"></a>

### Open

- **Playback and interpolation.** Transitions, masks, additive layers, automatic `Play`/`Update` state, long-running clock precision and a convenience rule for view interpolation. A wrapped clock must not interpolate through the wrong part of a clip.
- **Root motion and events.** An explicit root-motion delta over a time interval, including loop crossings, for a system to apply through its own movement rules; removal of extracted motion from the displayed pose. Root selection, translation/rotation/scale behavior and animation markers or event queries remain open. Sampling must not implicitly move entities or send events.
- **Further model APIs.** Non-humanoid retargeting, hierarchy-path lookup and pre-skin vertex access.
- **Further match-content policy.** Admission of arbitrary runtime content and convenience rules for replacing a rig while retaining older rollback history. Imported content already participates in build compatibility; runtime content reaches the match through synchronized state.
- **Further behavior.** IK, GPU blend shapes and shape-weight animation, and an automatic animation controller are outside the current implementation. Background metadata indexing and explicit editor URL refresh remain open.

<a id="levels-of-detail"></a>

## Levels of detail

Agreed 2026-10-11 and built the same day. The owner's decisions are under Decided; how each is built is under Provisional.

<a id="decided-20"></a>

### Decided

- **A mesh asset opts in with `[LOD]` on its declaration:** `[LOD] asset Mesh<Corner> rock = "art/rock.glb";`. A mesh without it is drawn as it always was, with nothing made for it and nothing picked. The owner chose opt-in over opt-out: "that way no surprises for the user".
- **Everything after that is automatic.** The build makes simpler versions of the mesh from the file, and keeps them for later builds. A draw of the mesh picks one by how the mesh shows on screen. A game writes no distances, authors no levels and passes no draw argument.
- **`Draw.Instanced` picks for each instance**, not once for the call.
- **Skinned meshes have it too:** `[LOD] asset SkinnedMesh<Corner> hero = "art/hero.glb";`.
- **A game can raise the screen error tolerance for performance** (2026-10-31): `Draw.LODPixels(pixels) { ... }` and `Draw.SetLODPixels(pixels);`, also on render targets. The default remains 1 pixel; higher values allow coarser meshes at the same distance. This adjusts automatic selection among the existing levels.
- **An asset may multiply that tolerance** (2026-10-31): `[LOD(2)]` allows twice the destination's pixel error. `[LOD]` means multiplier 1. The asset and destination multiply, so `[LOD(2)]` with `shadow.SetLODPixels(4)` allows 8 pixels. A forced level still wins.
- **Meshes a game makes get levels too** (2026-11-02; the owner took Claude's recommendations: "go with you recommendations"): opt in on the draw, `Draw.Mesh(vertices, indices, transform, lod: 1)` and `Draw.Instanced(..., lod: 2)`, the number the multiplier `[LOD(...)]` takes; the levels are the same code's as an asset's, made in the background while the game runs, never blocking a frame (the mesh draws whole until they're there, and wherever there's no background to make them), and kept by what's in the mesh. Once runtime `Mesh<V>` values exist, `mesh.WithLOD()` and `mesh.WithLOD(multiplier)` are the opt-in on the value, with the same levels.
- **A game can write its own levels** (2026-11-03, built): `[LOD]` stays as the shorthand, and an asset's build code can make the levels instead (see Build code).
- **A game can override the pick two ways** (the owner, of a shadow map, whose lamp would pick another level than the one the mesh shows as: "they probably want it to match the visuals the main camera rendered"):
  - **The level itself**, for some draws.
  - **The camera the pick is made through**, for a target, in place of the camera the target draws with.

```csharp
[LOD] asset Mesh<Corner> rock = "art/rock.glb";

view Rocks(Scenery scenery)
{
    Draw.Instanced(rock, scenery.transforms);
}
```

<a id="provisional-21"></a>

### Provisional

Picks made to build it, awaiting the owner.

- **Where `[LOD]` goes:** an `asset Mesh<V>` or `asset SkinnedMesh<V>` (with or without a contract), alone or as a glob's list or map, where it applies to every file. Its optional argument is a positive finite constant float or int expression; fractions below 1 retain more detail. No argument (including `[LOD()]`) means 1. Invalid, nonconstant or extra arguments are errors. It changes selection, not the generated chain. On any other asset, and on any other declaration, it's an error that says what it's for. `[Lod]` is an unknown attribute, with `LOD` suggested.
- **A level is a shorter index list over the mesh's own vertices.** No vertex is added, moved or copied, so the pack grows by index data only, about as much again as the mesh's indices for a full chain. Each level has about half the triangles of the one before, and there are 7 at the most. The chain ends where a step can't remove a quarter of what's left without opening a hole or tearing a seam, and where a level would be off by more than half the mesh's own reach, which is a mesh a few pixels across wherever it's picked. A mesh that's simple already gets no levels, and draws as if it had no `[LOD]`.
  - **A fixed floor** (the owner, 2026-10-11, after measuring: "fixed floor is fine"; the numbers are picks, the second changed 2026-10-30). Levels pay by the triangles they take off a draw, against what picking costs each instance and a draw call more for each level in use: a ball of 960 triangles drawn 40,000 times was slower picked than whole, up close. So a mesh of under 1,000 triangles has no levels and nothing picked. A bigger mesh's chain stops before a level of under 64 triangles: the first floor, 500 for every level, kept a crowd of 10,000 skinned figures 30 to 150 m off at 611 triangles each, where each was 20 to 60 pixels tall.
  - Triangles go by collapsing an edge onto one of its ends, the cheapest first. What's weighed: positions, and the fields a file fills (`normal`, `uv`, `uv2`, `color`), so a level's error is how far its surface and what's on it are from the full mesh's. A field off by some amount over a patch counts as a surface off by that amount times the patch's size, so a bevel's or a buckle's normals turning make a level off by the bevel's size, not the whole mesh's; a normal 30 degrees off, or a color off by half, over a pixel is a pixel off. Tangent `xyz` and fields of other names aren't weighed. Only static vertex layouts containing `float4 tangent` add its handedness sign to chart identity, preserving opposite signs as separate seams without a new tangent-direction error metric. Other vertex layouts and skinned LOD behavior are unchanged by this sign preservation.
  - An open edge only collapses along itself, so the mesh's outline keeps its shape. A position with two uvs or two colors is a seam, which only collapses along itself too. Vertices at one position that differ by their normals alone (a mesh shaded flat, each triangle with corners of its own) are one position, so such a mesh loses triangles as a smooth one does.
  - Edges more than two triangles share, and surfaces whose triangles don't agree on their front, stay as they are.
- **A draw picks by error on screen, not by distance.** Each level records how far it's off. A draw takes the simplest level whose error, as big as the draw's transform makes it, covers no more than the pixel tolerance at the nearest point of the mesh's bounds to the camera. The default is one pixel, and a mesh drawn large keeps more detail at any distance.
  - The bounds are a ball around the file's vertices, through the draw's transform (and the destination's `Draw.Transform`), by the way the transform makes the mesh biggest.
  - A pixel is a logical pixel of the window, and of a target that follows the window or the display's scale; a target with a scale of its own counts its own pixels.
  - A mesh around the camera draws whole. So does every mesh where the host never said the window's size (the standard host does; a C host calls `tide_draw_screen_size`).
  - **Out of the camera's view** (Provisional, Claude's pick, 2026-11-04): a mesh beside the camera or behind it, where its depth says nothing of how big it is, picks by how far out it is in the view's own measure, the most of its clip coordinates' `w`, `-w`, `|x|` and `|y|` (each lessened by the ball), so the tolerance coarsens it there as anywhere. A mesh the camera could show still goes by its depth alone. This is what a shadow map picking through the viewer's camera draws most of; until then such meshes drew whole, at any tolerance.
  - Picking keeps no memory of the frame before: the same draw through the same camera picks the same level.
- **Each destination picks with its own camera:** the window, and each render target a mesh is drawn into, unless it's told otherwise (below).
- **`LODPixels` and `SetLODPixels` set the allowed screen error**, a float belonging to the destination, as the other draw settings do. Positive finite values below 1 retain more detail; nonpositive or nonfinite values restore 1. With no arguments, both forms use 1. A block restores the preceding tolerance on every exit. Each frame and drawing defaults restore 1 for every destination. It uses the same pixel units and camera as the pick, including `LODCamera`; an explicitly named level wins. Triangle density is not a selection criterion.
- **`LOD` and `SetLOD` name the level**, a draw setting with the two forms the others have, on `Draw` and on a render target: `Draw.LOD(0) { ... }` around some draws, `shadow.SetLOD(0);` for the draws that follow. `0` is the full mesh, `1` the first level after it, and a number past a mesh's last level is its last, as meshes have chains of different lengths. A number under 0 is 0. Around a mesh with no `[LOD]`, or one that got no levels, it changes nothing, and that's no error.
  - Every instance of an instanced draw has that level, so the draw is one GPU draw in list order again.
  - `Draw.LOD() { ... }` and `Draw.SetLOD();`, with no number, go back to picking.
- **`LODCamera` and `SetLODCamera` name the camera the pick is made through**, the same two forms on `Draw` and on a render target, taking what `Camera` and `SetCamera` take for a 3D camera: `shadow.SetLODCamera(viewer.position, viewer.rotation, 60);`, or a transform and a projection. The draws still go through the destination's own camera; only the pick uses the other. So a shadow map picks, for each mesh, the level the player's view shows it as. With no arguments, the pick is the destination's own camera's again.
  - The pick counts pixels of the window, which is where a game's main view is drawn or ends up. A main view drawn into a target of another size is open, below.
  - A named level wins over a named camera, where both are around a draw.
  - A camera that's no camera (a projection of zeros, as `Draw.CameraProjection()` gives with no window) picks nothing: the meshes draw whole.
- **Instances are grouped by level.** An instanced draw of an `[LOD]` mesh is one GPU draw for each level in use, finest first, with items in list order within a level. Each instance picks from its `float4x4` (the list's, or its struct's `transform`; an instance with no transform is where the destination's transform puts it). Meshes drawn in a row by a view that runs for each entity, which join into one draw, are grouped the same way, as long as nothing else is drawn between them and they draw with the same of everything. Only `[LOD]` meshes pay for the picking.
- **Code reads the full mesh.** `rock.vertices` and `rock.indices` are what they are without `[LOD]`, for match code and every other reader. No code reads a level or counts them; a draw setting names one by its number, and that's all. So nothing of the simulation depends on them, and they aren't part of what makes two builds the same game.
- **`Draw.Mesh(rock.vertices, rock.indices, ...)` stays the same draw as `Draw.Mesh(rock, ...)`**, levels and all, and so does a mesh named by its place in a list or its key in a map. A copy of either list is the code's own, and draws as written.
- **The same file with and without `[LOD]` is two meshes**, in the pack and on the GPU. Different multipliers also have distinct mesh identities where levels exist; `[LOD]` and `[LOD(1)]` share. Multipliers reuse the same generated chain and simplification cache. They follow the packed indices, including draws through the asset's vertex/index lists.
- **A game's vert isn't known to the pick.** The bounds are the mesh's as the file has it, through 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. That's the game's to know, which is what opting in is for.
- **A skinned mesh's levels are made from its rest geometry**, and a pose deforms a level as it deforms the full mesh, since the vertices and their weights are the same ones. Moving a vertex onto one that follows its bones differently costs the edge's length times how differently, so the vertices around a joint outlast the ones along a limb. Its bounds for the pick are the rest pose's.
- **The GPU has each vertex once.** A level is drawn with the full mesh's vertex buffer and an index buffer of its own, made when a frame first draws it and let go when none does.
- **The cache** is in the game's `.tide/assets/lod/`, by what's in the file (and a skinned model's bytes) and the version of what makes the levels. Only static `float4 tangent` variants use the sign-preserving version-3 keys; layouts without tangents, `float3 tangent` layouts and skinned meshes retain their exact prior version-2 keys. A file there that's cut, or names vertices the mesh hasn't got, is made again. With no game folder, a build makes them each time. Under `tide run`, a saved model has its levels made again with the pack.
- **A mesh a game makes, drawn with `lod:`** (Claude's picks, 2026-11-02):
  - `lod:` is written last, by name, on a 3D `Draw.Mesh` or `Draw.Instanced` of lists or of a `Mesh<V>`, and on `Draw.SkinnedMesh` and `Draw.Instanced` of a `SkinnedMesh<V>`, alone or through a vert and a frag, a target's too. Its value is a float expression, not only a constant, as a draw's other values are; nonpositive and nonfinite ones are 1, as `LODPixels` takes them. On a 2D mesh it's an error that says so, and so is any other name written on a mesh draw's argument.
  - The draw asks for levels of the mesh the draw list copied. The same lists drawn without `lod:`, or with another multiplier, are another mesh. A mesh of an asset with levels already keeps the asset's.
  - What's weighed: the vertex's `float3 position`, and its `float3 normal`, `float2 uv` and `uv2`, `Color color` and `float4 tangent` (its sign as a seam) where it has fields of those names and types, the fields an asset's file fills. The levels are those `[LOD]` makes of the same vertices and triangles, by the same code, with the same floors, so they're the same on every machine.
  - They're made in the background: the host's jobs (`tide_draw_prepare`'s), two meshes at a time, at most 256 waiting, past which a mesh draws whole until it's copied again. Where there are none (a web build without threads), meshes draw whole.
  - They're kept by what's in the mesh, its vertices and triangles as the list copied them and what's weighed, never by where its lists are, in the draw list, 64 MiB of them at the most, the least lately used going first. Lists a world keeps that are copied again with other contents stop what was being made of them before; lists made along the way in the scratch area are told apart by their contents alone. A mesh of more than 2^26 vertices or triangles gets none.
  - What the code reads, and the simulation, are as they were: the levels are the draw list's alone.
  - A model with bones weighs them as `[LOD]` does (how differently two vertices follow their bones, read from the model's bytes), so a model decoded while the game runs (`SkinnedMesh<V>.Decode`), which has no declaration to mark, gets with `lod:` the levels its file would get with `[LOD]`, bit for bit. A model of an asset marked `[LOD]` keeps the asset's.
- **Not there:** levels an artist made, read from a file; blending or dithering between two levels; a flat picture in place of a far mesh; `mesh.WithLOD()`, until runtime `Mesh<V>` values exist; and leaving out what the camera can't see, which is a separate matter.

<a id="open-16"></a>

### Open

- `LODCamera` counts the window's pixels. A game whose main view is drawn into a target of another size, then put on the screen, picks as if it were the window's size.
- Instances drawn with a blend and no depth depend on their order, which grouping by level changes. A named level puts them back in list order; whether picking should refuse to group them is open.
- A skinned mesh whose clips carry it far from its rest pose (a jump baked into the animation) is measured where it rests.
- A profiler hint for a mesh without `[LOD]` that keeps drawing many more triangles than the pixels it covers.
- The fewest triangles a level has, 500, was set from one desktop GPU. A phone or a browser pays more for a triangle, where a lower number would still gain.

<a id="tasks"></a>

## Tasks

<a id="decided-21"></a>

### Decided

- `async` and `await`, as in C#. `async` before a function lets it wait and pick up where it stopped. Declarations name their completion value, `async int Doubled(int x)`, and `await Doubled(3)` gives it. The approved first-class handle model below extends how calls can be kept and awaited.
- A call of an async function that isn't awaited starts a task, which goes on by itself.
- Tasks run in the match as well as in local code. A match task is part of the match: snapshots, hashes and rollback hold it, players who join get it, and it carries on when the match changes hands. Match code only waits for what's the same on every machine (ticks, time, events); a service's answer reaches the match through input.
- A task ends when whatever started it does.

```csharp
singleton Round
{
    int count;
}

event RoundStarted { }

async event(RoundStarted) Countdown(mut Round round)
{
    for (var i = 3; i > 0; i--)
    {
        round.count = i;
        await Wait.Seconds(1);
    }
    round.count = 0;
}

async int Doubled(int x)
{
    await Wait.Ticks(1);
    return x * 2;
}

system Start(Round round)
{
    if (round.count == 0) Doubled(2); // Starts a task; its value is dropped
}
```

<a id="provisional-22"></a>

### Provisional

Implemented, awaiting approval:

- `async` goes before a function or an event handler, before or after `local` if it has one (`local async event(...)`); before anything else it's an error that says where it goes. Methods can't be async yet, nor extern functions or functions that take an Action. `await` is a keyword, and binds like `try`: `await Doubled(3) + 1` adds 1 to the value. A `!` after an awaited call is the awaited value's: `await Fetch(name)!`.
- An async call returns a started handle, as specified below. Systems, views, handlers and async code start tasks, and so does a plain function or method, as the code that calls it could (see Functions and blocks): the input's `Sample`, `Sanitize` and `Predict`, code the GPU runs, operators and `Interpolate` start none. A discarded ordinary async call continues without retaining its result.
- `await` waits for a handle or immediate async call. `Wait.Ticks(n)` starts a match timer, `Wait.Frames(n)` a local timer, and `Wait.Seconds(s)` a timer in its caller's world: in the match, the nearest whole number of ticks, at least one; in local code, this machine's time, which hosts give each frame (`tide_local_frame_time`) and a task counts down frame by frame, within a tenth of a millisecond. A wait of 0 or less doesn't wait. `await` isn't allowed in a block written after a call.
- (Claude's picks, 2026-11-15) `await Storage.Load(key)` and `await Storage.List(prefix[, after])` wait in a match task for the server's store, an outside answer that reaches the match as input, so the task goes on in the same tick on every machine (The server's store, Awaiting a load or a listing). They make an async function match code, and have no handle of their own.
- Async code is a state machine, as in C#: a call of an async function runs until it first waits, inside the code that calls it. A directly awaited call can share its caller's private frame; kept handles identify separate started operations. An async function can't directly await itself through that private frame; it can start itself again and keep the resulting handle.
- A task keeps its parameters and locals while it waits, copied, with their text, lists and grids in its world's heap (a grid parameter since 2026-11-15, Claude's pick: Grids, Grids an async function takes). An async function's component and singleton parameters aren't kept: it gets them again each time it goes on, as they are then, from the entity it belongs to, so the caller passes its own (a parameter), and a task whose entity lost one ends. Its `mut` parameters are only components and singletons; it can't keep the caller's other variables, and it has no `out` parameters: its call returns before it has made anything, so it returns a struct instead.
- An async handler is a task per event: its event is copied into the task, and its components are the entity's, got again after each wait.
- A plain function an async function calls counts too: one that sends a match event makes it match code, and one that sends a local event or a command makes it local (see Functions).
- An async function's world comes from what it does: changing the match (spawning, `mut` match components and singletons, sending match events, entity changes, `Snap`, `Wait.Ticks`) makes it match code, and local state (local components and singletons, `Session` calls, `Wait.Frames`, `Frame.dt`) makes it local. What it awaits or starts decides it too. One that does neither runs in whichever world starts it, and tidec makes it for each. Doing both is an error, as is starting or awaiting one from the other world. Tasks can't draw or read this frame's `Devices`.
  - (Claude's picks, 2026-11-14) `mut` on a match component or singleton that has [local fields](https://tide-engine.dev/spec.md#local-state) decides nothing by itself: writing one of its match fields makes the task the match's, and using its local fields makes it local (see Local state, Local tasks and local fields). `mut` on one without local fields makes it the match's, as before.
- A task belongs to the entity the code that started it runs for, or with a task, to that task's entity, and ends when it's destroyed; code that runs for no entity starts tasks that belong to their world. A function or method that starts one starts it for the code that calls it. A local task can belong to a match entity (a view of the match's entities started it), and ends with it, or when there's no match.
  - (Claude's picks, 2026-11-14) For a local task, "ends with it" is this machine's view of it: once the entity is gone from the world views draw, the predicted one, at the frame's task pass, whether the server has confirmed the destroy or not. And it ends with the match it was started in: once this machine leaves that match (it left, was dropped, or the match ended), its local tasks of that match's entities, and those of the local world that take that match's components or singletons, end at the next frame's task pass, even where the next match has an entity with the same handle (`tide_local_disconnected`). Tasks a view starts in that frame, for the next match, go on.
- Tasks go on at the end of the tick, after its changes and events, one after another in the order they started, those whose time has come; what they change applies after them, and their handlers can start more. Local tasks do the same at the end of the frame. A world keeps its waiting tasks in a table for each async function and handler, a row each: when it started, when it looks again, its owner and its frame.
- A system that starts tasks runs on one thread, and waits for the systems before it that start tasks, spawn or change text, as the code its tasks run until they first wait can do those. `--schedule` names it.
- Under `tide run`, a waiting task carries over to a build where its function's code, the code of what it awaits, and its frame's layout are the same; otherwise it's dropped, and tide says how many were.

<a id="open-17"></a>

### Open

- Awaiting an event: `await Hit` on an entity, which a task would wake for in the event's turn.
- Async C functions, which C finishes later (a service's answer), for local code.
- Combining task completions (`WhenAll`, `WhenAny`): no API is decided. Keeping and awaiting individual calls is covered by the approved handle model below.
- Cancelling an underlying external request independently of its task. Task-handle cancellation is covered below; an external C/provider operation may still need its own protocol.
- Methods and functions that take an Action being async, and `await` inside a block written after a call.
- Local handlers of match events (see Events), which a local task awaiting a match event would need too.
- Whether what's written before an `await` in its statement is read before the wait, as in C#: `score.value + await Bonus()` reads `score.value` once the task goes on today, unless a call that writes comes after it in the statement (see Evaluation order).

<a id="started-task-handles-decided-2026-10-25"></a>

### Started task handles (decided 2026-10-25)

Async functions, local workers and engine awaitables share a started-operation
model. Declarations name completion types; calls return handles.

- Declarations keep their completion types: `async T F(...)` and
  `local worker T F(...)`. A call returns a started handle; awaiting it gives
  the declared result. Calling and awaiting immediately is the same operation
  as keeping that handle and awaiting it later.
- Match async calls produce `Task<T>`, local async and local worker calls
  produce `LocalTask<T>`. `Task` and `LocalTask` are the void forms. World
  placement follows the existing caller-capability rules. Bare match workers
  remain reserved; this decision introduces no cross-tick match computation.
  First-class match handles are currently rejected in sharded games; distributed
  identity, result retention and cancellation are a separate pass. Existing
  directly awaited/discarded match async calls and local handles remain supported.
- Preserve the complete result type: `Task<T fails E>` and
  `LocalTask<T fails E>` retain their declared error type, and optional results
  retain their optionality. `await handle` has the same value/failure type as
  `await F(...)`; failures remain values, not exceptions.
- Handles copied or stored refer to the same operation. Awaiting does not
  restart it. Repeated/multiple awaits obtain the same logical result using
  ordinary Tide value-copy rules, so one recipient's edits cannot change
  another recipient's result.
- `handle.Cancel()` cancels that operation; cancelling a completed operation
  has no effect. Default/stale handles are harmless and never refer to a
  subsequently created operation. `isRunning` reports whether it is pending
  or running. `isCompleted` includes cancellation, and `isCancelled` is true for
  cancelled, default and stale handles. Equality compares operation identity.
- Cancellation propagates through an ordinary await by ending that awaiting
  task's continuation. Cancelling one awaiting task does not cancel a shared
  operation that still has another consumer. An unused directly awaited
  worker can be abandoned automatically; a queued callback is skipped and a
  running calculation stops at generated Tide safe points. An extern C call
  finishes normally.
- Discarding the return of an ordinary async call retains fire-and-forget
  behavior. Entity/world ownership still ends tasks with their existing
  owners. Match task identities, results and cancellation are match state;
  local ones remain outside match snapshots, hashes and networking.
  Per-recipient visibility preserves authoritative server task execution:
  registries, continuations and cached results are private. A projected client
  cannot start a retained match operation; a published handle whose operation
  is absent there is stale. Publish ordinary permitted progress/results for views.
- A compatible local save/reload preserves the logical connection between a
  stored handle and its surviving task. Provider pointers, native callbacks
  and live worker execution never enter saved state; pending local workers
  still restart after restoration/reload.
- `Wait` timers, `Storage.Flush`, `Web.Fetch` and request `Send` return the same
  handle types with their complete declared results. Awaiting a retained timer
  waits for its original deadline; it does not start a new delay or request.

Result reclamation, operation indexing, continuation scheduling and worker
admission are internal implementation choices. Cached results remain available
to reachable consumers and unreachable cycles are reclaimed. Preserve observable
ordering and serial results. No public shared-result mutation, multiple-result
stream, explicit cancellation outcome API or `WhenAll` syntax is decided here.

<a id="local-workers"></a>

### Local workers

**Decided (2026-10-24).** `local worker Result Build(Input input) { ... }`
declares a CPU calculation whose scheduling belongs to this machine. A local
async function or handler awaits it with `await Build(input)`. Inputs and results
are owned values, independent of live worlds and frame storage. The calling
task publishes results in local state. Worker completion never enters match
state, tick order, snapshots, hashes or networking. Bare `worker` is reserved
for a future match contract and is currently rejected.

Workers share the bounded host pool, and can distribute independent loop work
through the same pool. Existing loop ordering and independence rules remain.
Explicit `parallel` loops also accept a worker's owned local list. A step cannot
append to a shared list or write another step's output.

**Decided (2026-10-24, grid extension).** Read-only `Grid2<T>` and `Grid3<T>`
worker inputs capture independent snapshots before dispatch. Both grid fields
and grid assets can supply a snapshot. Synchronous helpers can read and forward
it through explicit grid parameters without obtaining live-world access.
Existing grid foreach independence and ordering rules apply within workers.
Grid locals, returns and writable worker grid parameters remain unsupported;
ordinary CPU callers cannot pass grids to helpers. GPU sampling remains GPU-only.

**Implemented choices, provisional.** Workers are synchronous function bodies,
without `async`, `mut`/`out` parameters, bindings, World, queries, devices,
resource/asset references or borrows, or callable/shader bindings. Owned CPU values
include text, nested lists/maps/sets, ordinary structs, fixed arrays, optionals
and failable results.
Reachable helpers have no world, frame, drawing/audio, file/network, task-start
or implicit match-randomness capabilities. Explicit Random values retain their
ordinary calculation rules. Extern C remains trusted. A call returns a started
`LocalTask<T>`; local async code awaits its result.

Captures are fully materialized, including packed geometry lists, before
dispatch. Results are acquired on the frame thread. Owner loss drops the
continuation and discards pending output; abandoned queued calculations are
skipped, while a running calculation stops at generated Tide safe points.
Trusted extern C finishes its current call. Local state disposal
and retained reload drain jobs before their callbacks can be unloaded.
Restored/retained tasks restart a pending worker
from their current saved arguments and component bindings.

A custom host supplies optional background/help callbacks through `gui.jobs`;
the standard host uses its platform pool. Parallel waiters execute queued loop
helpers to avoid requiring a free thread. No provider means synchronous
execution when the task polls its worker, which can stall that frame. List
foreach and ordinary for loops retain their ordered semantics. Grid foreach
uses the existing independence analysis in workers, with ordered reductions.
Snapshot capture copies the directory and existing chunks on the calling thread.
Capture follows written argument order. An earlier grid capture survives later
argument mutations or waits as privately owned task state until dispatch.

**Priorities (Provisional, Claude's picks, 2026-11-15; the owner said to go with
the recommendations).** A local worker's call says when it starts among the
calls that wait for a thread: `await Faces(blocks, priority: WorkerPriority.Background)`,
and the same on a call that gives a handle.

- **The spelling is a named argument, written last**, as `samples:` is on a
  render target and `lod:` on a mesh draw: the engine's one name on a call that
  otherwise takes its own arguments. Argued: a method on the handle
  (`Faces(...).Background()`) would change a call that has already started, and
  a directly awaited call has no handle to write it on; an attribute or a second
  declaration would put it on the worker, when the point is one mesher for the
  chunk underfoot and the horizon; a word before the call would be a new
  keyword. A worker can't name a parameter `priority` (an error at the
  parameter); a function that isn't a worker keeps one of its own, and
  `priority:` on its call is that parameter or the usual error.
- **`WorkerPriority` is a built-in enum: `Normal`, `Urgent`, `Background`.**
  `Normal` is its zero, what `default` and a call that says nothing have. The
  name is the game's no longer; `Priority` alone was left to games. The value is
  any expression of the type but one that awaits.
- **Which starts.** The urgent calls first, then the normal ones, then the
  background ones, each level in the order its calls came. A waiting normal call
  starts after four urgent starts and a waiting background call after sixteen
  starts of the others, so none waits for ever: under a steady stream of urgent
  calls, every fifth start is a normal call and every seventeenth a background
  one. A priority is read when a thread is free: it interrupts nothing that
  runs, takes nothing back from a thread, and doesn't lessen what copying a
  call's inputs costs. A match's ticks keep their precedence over all of it.
- **Room.** The limits on waiting calls and kept inputs (Implemented choices,
  above) count each priority apart: they're the normal calls', urgent calls
  have as much again and background calls half as much. So no level keeps
  another from being admitted, and local state can hold two and a half times
  the limits when all three are full. A frame's transfer limit is one for all.
- **When it's read.** Once, as the call begins: before the call waits for room,
  which is the priority's, and before its arguments. What in it has effects
  keeps its written place among the statement's other effects.
- **Unchanged:** a call that says nothing is a normal call, generated C for a
  game that names no priority is what it was, and a host with no threads runs a
  call where it's polled, whatever its priority. It's this machine's alone:
  nothing of it is match state.
- **Not built:** changing the priority of a call that waits (a chunk the player
  walked up to); a share of threads kept for urgent work while long background
  calculations run on all of them (a free thread is the only time a priority
  is read); priorities for a worker's own parallel loops, whose helpers still
  go first; a match's workers, which stay reserved.

**Open:** deterministic match workers, distributed match task handles and
explicit cancellation outcomes beyond status properties.

<a id="proposed-worker-extensions-not-implemented"></a>

### Proposed worker extensions (not implemented)

These are recommendations for the owner's review, not approved requirements.
No new syntax or runtime behavior below is part of the current implementation.

- **Priorities:** built 2026-11-15 (Local workers, Priorities). Left of the
  proposal: a share of threads kept for urgent work.
- **Explicit cancellation outcomes:** ordinary await cancellation ends its
  continuation. If game code needs to continue after cancellation, consider a
  separate outcome-returning await API that preserves success, declared failure
  and cancellation as distinct cases. Its spelling is undecided; no cancellation
  value is injected into `T fails E`.
- **Distributed match handles:** retain the current compiler restriction until
  operation identity, result ownership, cross-shard waits/cancellation and handoff
  are designed together. Local workers remain machine-local.
- **Match workers:** keep bare `worker` reserved. The existing ECS scheduler
  already distributes same-tick work deterministically. A worker that finishes
  before the tick's dependency barrier is straightforward but cannot advance
  simulation while unfinished. Work spanning ticks needs explicit resumable
  progress and a deterministic work-unit budget; inputs, cursor, result and
  cancellation enter snapshots/hashes, and thread speed cannot choose its
  completion tick or entity/event order. Recommend that model only for a
  concrete workload that needs it. Outside-service answers still enter as input;
  local completion timing must never become match state directly.

<a id="input"></a>

## Input

<a id="decided-22"></a>

### Decided

- One `input` declaration per game describes one player's input for one tick. It's what the network sends.
- Input is one value per player per tick. The engine writes it, and the simulation can only read it.
- `Owner` is a built-in component that ties an entity to a player. It's a normal component: it can be read, written, added and removed. Writing it hands control over. Views and local handlers of match events use `with ownership` to filter for this machine's player (see Views and drawing, and Events), and command handlers for the command's sender (Provisional: see Commands).
- Players are identified by a built-in `PlayerID` type, not an `int`. Like `Entity`, it's opaque, comparable with `==`, and has a null value. The simulation only sees `PlayerID`s and never connections, so a player who reconnects and gets their `PlayerID` back keeps everything they owned. `PlayerID(0)` names a player by index, for local play and tests.
- **Sampling is Tide code:** the input's `Sample(Devices devices)` method. The engine calls it on the client once per tick. Fields start at their defaults, and `Sample` assigns them by name, without `mut`. It runs outside the simulation: it reads this machine's `Devices`, and the local singletons it takes, but not the match.
- **Device access always takes a parameter**, `Devices devices`. Views and the input's `Sample` receive this machine's devices; match code receives the devices of the player who owns the entity, or the server's, as with an input parameter. The input sends what match code reads of them, and nothing else, and the engine repairs them, since it knows their ranges.
- The input stays, for what's worked out on the player's machine: an aim direction from the mouse, or anything that depends on local state. The match can't read positions on the screen (the mouse's, a touch's, the pointer's), which are in this machine's window; `Sample` works out what the match needs from them.
- Singletons stay parameters, in `Sample` too: `Sample(Settings settings)`.
- **Input carries whether buttons are held, not whether they just went down,** because a missing remote input is guessed by repeating the last one. On a device, `.pressed` means down at any point since the last sample, so a quick tap between ticks is never lost. That's between the ticks of a match this machine is in: with no match, or before this machine is in it, nothing is kept for a sample, so a match's first tick reads what's held as it starts, not what was pressed in a menu before it, nor how far the mouse moved there. In the simulation, `bool` input fields get `.down` and `.up`, computed against the previous tick, inside structs too (`input.aim.fire.down`).
- **A guess lets go after a while** (the owner asked for the limit, 2026-10-05: at a ping of 500 ms, corrections were wild; and agreed to what follows, 2026-10-06). A machine predicts other players' inputs, and the server's, by their last ones for 0.15 seconds past the last tick the server confirmed to it. In the ticks it predicts past that, each of those inputs is back at the input's defaults, as if its player had let go. So a guess that was wrong moves things by what a player does in 0.15 seconds at most, however far ahead a slow connection has a machine run.
  - Fields are let go unless they say otherwise. `[Absolute]` on a field says its default isn't rest, as it says where something is or which (an aim, a pointer's cell, a weapon chosen): a guess keeps it for as long as it goes on. A field that should have had it and doesn't shows at its default on machines that run further ahead than that.
  - `[Absolute]` takes no arguments and goes on the input's own fields, never a struct's, a component's or a singleton's. The name is the owner's, over `[Hold]`: it says what the field is, where `[Hold] bool fire` would read as a button that's held.
  - The 0.15 seconds are the engine's, with no setting for now. Hosts written in C have `tide_client_desc.guess_seconds`.
- An input parameter in a system gives the input of the player who owns the entity, and so does a `Devices` parameter. Entities without an `Owner`, or whose owner isn't a known player, get the **server's input**, and so do systems that run once per tick. This is how the server controls what no player owns. An input parameter doesn't filter entities: add `with Owner` to only run on owned ones.
- **Input borrowing in helpers (Decided, 2026-10-18).** An ordinary synchronous function or method takes the declared input type as a read-only borrowed parameter. Its argument is a direct input parameter of the caller, including a further helper's borrow. It supplies the same current/previous input pair, not a new owner lookup, so helper reads, including bool edges inside structs, behave as in the caller. Multiple borrowed parameters, named arguments, overloads and ordinary defaulted value parameters follow the existing call rules. Borrowing makes no full input copy and grants no implicit World, entity, singleton or authenticated sender. Input has no `mut`, `out`, `in` or default; a borrow cannot be stored, returned, optional, or retained by tasks. Synchronous callback blocks, comparisons and parallel steps can read/forward it under their existing rules. Externs, operators, audio declarations, shaders and async declarations take no input borrow; async handlers take none either. Copy individual fields when a task or stored value needs them. Sample/Sanitize/Predict pass their ordinary field values to helpers, with no implicit whole-input borrow. Custom input fields retain their existing serialization; forwarding changes no wire representation or device-use filtering.
- An input can have a `Predict()` method to adjust guessed future input. `[DontPredict]` on a field resets it immediately on guessed ticks. Neither changes real sampled input.
- An input can have a `Sanitize()` method. Every input passes through it before the simulation reads it, including input from other players, so systems can rely on what it guarantees without checking again. It assigns the input's fields by name, like `Sample`, and reads nothing else.
- Input fields can declare bounds: `[Clamp(lo, hi)]`, `[Min(x)]` and `[Max(x)]`, and so can the fields of structs an input holds. The engine applies them to every input before `Sanitize`, so `Sanitize` only handles what they can't express. Bounds are constants; a number bounds every component of a vector. They go on input and struct fields only, for now: on a component's or singleton's field, they're an error.
- **Input is an attack point,** so the engine is forgiving with it. Before `Sanitize` runs, NaN and infinite floats become the field's default. Nothing a client sends can put NaN in the simulation, and `Sanitize` only deals with values that are merely out of range.
- `Devices` has a keyboard, a mouse, a gamepad, a touchscreen and the pointer; pen, joysticks and sensors come later. Every button has `.pressed` (held), `.down` (went down since the last sample) and `.up` (went up), named as in Unity: the Input System's `isPressed`, and the old `GetKeyDown` and `GetKeyUp`.
  - **Keyboard:** every key by physical position, named after the US layout (`keys.w`, `keys.space`, `keys.leftShift`, `keys.digit1`, `keys.upArrow`, `keys.f1`). WASD works on AZERTY. `text` is what was typed since the last frame, a `string`, which follows the keyboard's layout as keys don't. It's a frame's: views read it, and the functions they call. `Sample` and the match can't, and the input never sends it.
  - **Mouse:** `position`, `delta` and `scroll` (`float2`), and buttons `left`, `right` and `middle`. While its cursor is locked (see Views and drawing), `position` stays and `delta` is the mouse's own movement.
  - **Gamepad:** `connected`; `leftStick` and `rightStick` (`float2`); `leftTrigger` and `rightTrigger` (`float`, 0 to 1); face buttons by position (`buttonSouth`, `buttonEast`, `buttonWest`, `buttonNorth`); `dpad.up` and the other directions; `leftShoulder`, `rightShoulder`, `start` and `select`.
  - **Touchscreen:** `connected`, `primaryTouch`, and `touches`, a slot for each of 10 fingers, as Unity's. A `Touch` has `press` (a button: `.down` when the finger touched, Unity's Began, and `.up` when it lifted, Ended), `id` (Unity's `touchId`: the same while the finger touches, a new one for each touch), and `position`, `delta` and `startPosition` (`float2`). A finger keeps its slot while it touches, and one that touches while ten do is left out. `primaryTouch` is the finger that touched while no other was the primary one, until it lifts. A finger that touches and lifts between two samples reads as held for one, so no tap is lost. A finger is never the mouse, as in Unity's Input System.
  - **Pointer:** `position`, `delta` and `press`: the mouse, with its left button, or the primary touch, whichever was used last, as Unity's `Pointer.current`. Code that reads it works with a mouse and a finger alike.
  - **Axes follow Unity:** `y` is positive up for sticks, the mouse, touches and the pointer. Their positions are in window pixels from the bottom left; in a view, `Screen.Flip` gives them from the top left, as the screen and the GUI count (see GUI). `scroll.y` is positive when scrolling away from the user.

```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;
}

// The same without an input: the player's devices, as they read them.
system Hop(Devices devices, mut Velocity velocity)
{
    if (devices.keyboard.space.down || devices.gamepad.buttonSouth.down)
        velocity.value.y = 5;
}
```

```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;
    }
}
```

<a id="provisional-23"></a>

### Provisional

- `input` is only a keyword at the start of a declaration, so it can still name parameters and locals.
- A player, or the server, whose input isn't set for a tick keeps their last one. Until then, inputs are the defaults.
- The input's defaults go through the same steps as any input: NaN repair, bounds, then `Sanitize`.
- The world keeps an input for each player a match can take: the game's `maxPlayers` setting, 16 without one (see Settings). A `PlayerID` past that is no one's: its input is the server's.
- A system can have one input parameter.
- Extra device members beyond the list above: mouse `back` and `forward`, gamepad `leftStickButton` and `rightStickButton`, and the full key list in `engine/include/tide/devices.h`.
- The types inside `Devices` are `Keyboard`, `Mouse`, `Gamepad`, `Dpad`, `Touchscreen`, `Touch`, `Pointer` and `Button`. Functions take them and `Devices` as parameters, read-only, passed without a copy: `float2 Steer(Gamepad pad)`.
- `touches` is a fixed-size device array, read-only, shown by tools as `Touch[10]`: `touches[i]` (an empty touch past the last, as forgiving as a list), `touches.count` (10: every slot, touching or not) and `foreach`, which goes through every slot. Ordinary fixed-size value arrays are implemented separately (see Arrays); device records remain read-only.
- `Sample` takes `Devices` and local singletons, read-only: `Sample(Devices devices, Settings settings)`. Either can be omitted when unused. Hosts pass the local state to `tide_input_sample`.
- `Devices` in views is this frame's: `.down` and `.up` since the last frame, and the `delta` of the mouse, touches and the pointer, and the mouse's `scroll`, too. What the GUI is using is hidden from views, as from `Sample`, and so is what another view claimed (see GUI). Helpers take the devices or a part of them explicitly; reading `keyboard.text` still requires a frame.
- `keyboard.text` is the characters typed since the last frame, with Shift, dead keys and a phone's keyboard applied, and what's pasted too, but for newlines and tabs. Backspace, Enter and the arrows are keys, not characters. It holds up to 32 characters a frame: the platform keeps the rest for the frames after, up to 1024, so a long paste comes over a few frames, as it does into the GUI's fields. It's empty while the GUI has the keyboard (a widget with the focus, a field being typed into, a modal). A function that reads it through a `Keyboard` or `Devices` parameter needs the frame, so `Sample` and systems can't call it. It can't be written, like the rest of the devices.
- A `Devices` parameter goes in `Sample`, views, systems and match event handlers, at most one per declaration. Functions and methods take the devices or their parts as explicit parameters. Bare `Devices` is a type, never a value. Local event handlers and tasks can't take devices.
- What the input sends of the devices comes from the whole program: each value read through a `Devices` parameter, in systems and handlers and in the functions and methods they call, and every value of a part used whole, like `var pad = devices.gamepad;`, but its positions in the window, which count once they're read. A `Touch` read through a function's parameter or a copy (a `foreach` over `touches`, `touches[i]` at an index that isn't a number) is sent for every place it could be: the primary touch, every slot, or both. A game without an `input` declaration gets one that only sends the devices.
- Buttons are sent as held (`.pressed`), like bool input fields: `.down` and `.up` in match code are against last tick's input, so a guessed input that repeats the last one doesn't press them again. A button let go and pressed again between two ticks is one press.
- Repairs: sticks -1 to 1 on each axis, with NaN 0; triggers 0 to 1; the `delta` and `scroll` of the mouse, and the `delta` of touches and the pointer, finite, or 0.
- On the server's machine, its own player's input is the server's too, so entities without an owner read it. A server with no player of its own keeps the defaults.
- Custom input prediction, first implementation:
  - Before each predicted client tick, other players' and remote server inputs start from their previous tick's values. `[DontPredict]` fields reset to their declared defaults, then `Predict()` runs, followed by ordinary repair, bounds and `Sanitize`. Untouched fields keep their previous values; computations can accumulate across guessed ticks.
  - `Predict()` takes no parameters, returns no value, and assigns fields by name. It reads only the input, with the same capabilities as `Sanitize`: pure helpers are allowed, but match/local state, devices, frame time, random rolls/seed, sending, spawning and tasks are unavailable. The enabled engine-owned `viewTime` remains read-only.
  - `[DontPredict]` takes no arguments and belongs on the input's own fields, of any supported input type. It resets a whole struct/array field, including its defaults. Duplicate attributes and combination with `[Absolute]` are errors. `Predict()` can explicitly replace an attribute's default.
  - Changing a guess creates no `.down` or `.up` edges, including nested bool fields. Real samples retain their normal edges. These hooks never run on authoritative server ticks or confirmed replay, and never change this machine's own sampled input.
  - The existing 0.15-second guess limit still applies after custom prediction: non-`[Absolute]` fields return to their sanitized defaults beyond it, while absolute fields retain the custom guess. A custom guess that changes input requires authoritative replay when confirmed, even if that frame carries no input delta.
- What a guess is once it lets go (see Decided), in its details:
  - The 0.15 seconds are to the nearest tick. Past them, each guessed input is the input's defaults through the steps any input takes (repair, bounds, `Sanitize`), and the tick before is taken to have had the same, so no `.down` or `.up` is true for it, of a `bool` field or of a device's button.
  - The devices match code reads are let go with the rest: nothing of them is `[Absolute]`.
  - `[Absolute]` goes on a field of any type.
  - Only predicted ticks are guessed. The rule above stands for what the match is: a slot whose input isn't set for a tick keeps its last one, on the server and in every tick it confirms.
  - This machine's own input is never guessed, nor the server's on the machine that runs it.
  - Not picked yet: a limit of its own for a field, and anything between keeping and letting go, like an axis that fades.
<a id="open-18"></a>

### Open

- Pairing devices with players, for local multiplayer.
- Compact input types (bytes, quantized floats) to save bandwidth.
- The server's input computed from the game's state (AI) rather than from devices.

<a id="views-and-drawing"></a>

## Views and drawing

<a id="decided-23"></a>

### Decided

- **Numeric frag outputs and image formats** (owner, 2026-11-13: "these make sense, lets do all of these";
  built 2026-11-14): a frag can write `out float`, `out float2`,
  `out float4` and `out int` beside `out Color`. Number outputs are neither tinted nor premultiplied and replace
  the stored value regardless of the draw's blend; Color keeps its existing behavior. The added formats are
  `R8`, `Rg8`, `R16f`, `Rg16f`, `R32f`, `Rgba32f` and `R32i`. An incompatible output is a compile error at the
  draw, explaining the type the format takes. Sample returns an image's own numeric type. Each image has its
  own clear value, including values past one for float images. A blend for each output remains open.

- Drawing is immediate mode: code records drawing commands every frame.
- Views never change the match. They can change local state (see Local state).
- 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. They draw up to a tick late for it.
- Floats are blended by default: every float, vector, quaternion and color a view reads of the match, `Time.t` among them. Ints, bools, enums, entities and text are as they are at the latest tick. `[Snap]` on a field keeps it 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
}
```

- 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.
- One field that jumps says so the same way, `f.since.Snap()` (decided 2026-10-27): the per-field counterpart of `entity.Snap()`. Between the tick it happens in and the one before, views draw that field as it is at the newer tick; from the next interval it blends again. The rest of the component or singleton keeps blending. A timer reset along with an enum is the case it is for: without it, views see the new enum with the timer blended from its old value down to 0.

```csharp
mut void Enter(Stance next)
{
    stance = next;
    since = 0;
    since.Snap(); // Drawn from 0 with the new stance, not running backwards
}
```

- **Provisional** rules of `field.Snap()`:
  - It goes on a field of a match component or singleton, by name in its methods. A struct-typed field snaps the whole struct; a field of a struct (`f.pose.angle.Snap()`) is an error that says to snap the component's field that holds it.
  - It is an error on a field views never blend (ints, enums, bools, entities, text, arrays), on a `[Snap]` field, on a `[Position]` or `[Rotation]` field or a struct holding one (snap the entity or singleton, which clears the correction error), on a field of a type with its own `Interpolate`, and on local state.
  - It is a write of the field: allowed wherever the field may be written, which is systems, match event handlers, match tasks, and the functions and methods they pass it to `mut`. Views, local handlers and the input's methods can't.
  - Each field that something snaps gets a hidden int counting its snaps, after the type's fields, which `Snap()` increments (wrapping). Views blend the field only between two ticks with the same count. The counter is ordinary match data: snapshots, rollback, packing, the match hash, host migration and hot reload carry it, and it changes the type's layout, and so the match's compatibility, only in a game that snaps that field. It costs nothing for fields never snapped and next to nothing in network bytes, as it rarely changes.
  - `verified` views and view queries follow the same rule over their own endpoints.

<a id="provisional-correction-smoothing"></a>

#### Provisional correction smoothing

**Provisional.** `[Position]` and `[Rotation]` describe how a match field is presented when prediction is corrected. The names and contract may change as games test them.

```csharp
component Body
{
    [Position] float2 position;
    [Rotation] float heading; // Radians, for 2D
    float2 velocity;          // Ordinary tick interpolation
}

component Pose
{
    [Position] float3 position;
    [Rotation] quaternion rotation;
}
```

- `[Position]` applies to `float`, `double` and their vector types. Tick interpolation stays linear. A correction accumulates the additive difference needed to preserve the displayed value, and the presentation removes that error over time. Double positions, differences and retained errors use binary64 arithmetic; the frame fraction and shared decay factor remain floats, widened when used with a double field. Matrices and optional/array fields are not supported by this attribute.
- `[Rotation]` applies to a float in radians or a quaternion. A float interpolates and corrects through the shortest wrapped angular difference; a quaternion uses the shortest relative rotation. Its correction error decays toward zero angle or the identity rotation.
- Error is local to presentation and decays exponentially with frame time, with a provisional half-life of 75 ms. Further corrections accumulate with the error still present. Ordinary motion follows the corrected simulation; it is not low-passed along with the correction.
- Untagged fields keep ordinary tick interpolation. An ordinary struct can contain annotated built-in fields, including through nested ordinary structs. Correction smoothing through a type with its own `Interpolate` remains deferred; no companion custom-type method is agreed.
- `entity.Snap()` and `singleton.Snap()` remain immediate and clear the accumulated correction error. The retained errors change neither simulation values nor collisions, the simulation hash or serialized match state. No new correction-rate setting is agreed.
- The tags take no arguments and cannot be combined with each other or `[Snap]` on the same field. They describe match component and singleton fields, or ordinary struct fields held by them, not local state, inputs or events.
- A new match, a hot reload or a replacement world with no comparable presentation history clears the error. Host migration retains the frozen presentation while reconnecting, then clears the error when the new network timeline begins.

<a id="other-view-rules"></a>

#### Other view rules

- A view filters its entities by whether this machine's player owns them, with `with ownership` and `without ownership`, beside `with` and `without`:

```csharp
view RenderGame(Player player, with ownership)
{
    Draw.SetCamera(player.pos, player.rot, 75);
}

view Nameplates(Player player, without ownership) { ... }
```

  - `with ownership`: the view runs only for entities that have the built-in `Owner` component and whose `Owner.player` equals `Session.player`, this machine's player.
  - `without ownership`: every other entity the view's other parameters and filters admit: entities with no `Owner`, and entities another player owns.
  - They're filters: they create no data dependency, and the view needs no `Owner` or `Session` parameter for them. It can still take either, and `with Owner` still means "has any owner": `with Owner, without ownership` is the entities whose `Owner` isn't this machine's player: another player's, or no player's. A view that takes both `with ownership` and `without ownership`, or `with ownership` and `without Owner`, is an error, as no entity is both.
  - A view with no component parameter runs once per entity through them, as through `with Player`: `view Hud(with ownership)`.
  - Only views and command handlers have them: a view's are of this machine's player, a command handler's of the command's sender (Provisional: see Commands). In other match code (systems, the match's event handlers, tasks) they're errors, since the match has no "this machine": the message points to `with Owner`, the entities that have any owner, or `without Owner`. A local handler doesn't filter by them either: one of a match event takes `Owner owner` and `Session session` and compares them, and local entities have no owner.
  - Outside a match, a view with either doesn't run, like any view that reads the match.
  - `ownership` is a keyword only right after `with` or `without`, where it's never a component's name. Anywhere else it's a name like any other: a field, a local, a parameter or a declaration can be called `ownership`, and a qualified name starts with it as with any namespace (`with ownership.Flag`).
- **`verified`** before a parameter's type means "from the world the server has confirmed": one word with one meaning everywhere, a modifier like `mut`, and a keyword only there. A client's views draw the world as it predicts it, which can be wrong for a moment; what must not be wrong, like a health bar, a score or a death, is read `verified`.

```csharp
// Movement as predicted, the health bar only what's confirmed.
view DrawFighter(Body body, verified Health health) { ... }

// The same component twice: what's predicted, and what's confirmed so far.
view HealthBar(Health health, verified Health confirmed) { ... }

// A filter, and a singleton.
view Corpse(Body body, with verified Dead) { ... }
view Board(verified Duel duel) { ... }
```

  - 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. A view whose components are all `verified` runs for the confirmed world's entities.
  - "The same entity" in both worlds is the same entity, not only the same handle: a rollback can give a handle to another entity (see Local state, an entity after a rollback).
  - Filters take it too: `with verified Dead`, `without verified Dead`. So do singletons: `verified Duel duel`.
  - A `verified` view value interpolates between confirmed endpoints on a separate presentation clock, holds at the latest confirmation, and never extrapolates. Entity membership and discrete fields use the upper endpoint; ordinary interpolation, `[Snap]`, `Snap()` and custom `Interpolate` rules apply. Verified event handlers still receive exact confirmed event state.
  - In match code it's an error: the match is the same on every machine and has no "confirmed". Systems, match handlers, tasks and their queries say so, and point to views and local handlers.
  - With a predicted `Body`, an entity is gone from a view the moment the prediction destroys it, whatever a `verified` parameter beside it says. To hold a death until it's confirmed, a game makes the death a state of a living entity (a field or a tag), takes everything `verified` in that view, or shows it from `local event(verified Destroyed)`.
  - A local handler takes it on its event: `local event(verified Died died)` (see Events).
- Meshes are the general shape: `Draw.Mesh(vertices, indices)` draws triangles with a position, a texture coordinate and a color at each corner, three indices each, in order with other drawing calls. `Draw` also supplies cube, sphere, cylinder and plane helpers.
- `Texture` is a local, read-only image reference. `RenderTarget` is a local drawing destination whose `.color` is a `Texture`, whose other color images are `.colors[i]` where it holds several, and whose `.depth` a frag reads too (below). Target receiver methods (`scene.Clear`, `scene.SetCamera`, `scene.Mesh` and the other drawing methods) make the destination explicit: a target has every method `Draw` has, and nothing else. Ordinary `Draw` calls draw into `Draw.window`; the window has no sampleable `.color`. Each target has every setting of its own, shared across views, and switching passes preserves color and depth. A clear resets both within its clip.
- A render target's size is in logical pixels, like the window's, and its image is made at the display's scale: `RenderTarget(width, height)` creates one in local code, of a positive width and height. Drawing into a target is then the same as drawing into the window: `target.Screen()` is in logical pixels, text is fitted to the image's real pixels, shapes' edges are smooth over one of them, and conversions (`WorldToScreen` and the others), clips and a frag's `this.position` are in logical pixels.
  - A third argument is its pixels per unit, the display's scale when left out: `RenderTarget(320, 180, 1)` is exactly 320 by 180 pixels whatever the display, for pixel art and anything that must not depend on the display.
  - `RenderTarget.Window()` is a target that's always the window's size, and `RenderTarget.Window(factor)` one that's always that part of it: `RenderTarget.Window(0.5)` is half as wide and half as high. The engine makes it again when the window's size or the display's scale changes, and the game never calls `Resize` on it. What was drawn in it is lost then, which doesn't matter for a target a game draws again every frame.
  - When the display's scale changes (the window moves to another monitor, a browser zooms), targets at the display's scale are made again and lose their contents, as with a lost device. Targets with pixels per unit of their own aren't touched.
  - `Screen.scale` is read-only float2 frame metadata (conventional completion, 2026-10-20): current window physical pixels per logical pixel independently on x/y. Views and their helpers read it; match/GPU code and assignments are refused like other Screen measurements. A zeroed custom-host axis defaults to 1. It does not report render-target contents or validity.
  - A target's color and depth persist across frames otherwise. Copies, including `.color` references, share the image. `target.Resize(width, height)` changes the size of a target that isn't the window's to size, and discards its contents, even at the same size. `target.Dispose()` invalidates all aliases and releases its attachments; repeated disposal is harmless. A default target is invalid. These operations cannot run in field defaults or the match. Invalid destinations and disposed sources skip drawing with a diagnostic, including already-recorded uses of an image disposed in the frame. `Draw.window` cannot be resized or disposed. Hot reload retains managed sizes, pixels per unit, whether a target follows the window, and shared aliases, adopting their state natively and recreating their images on the web; borrowed references are cleared and rendered contents are discarded. Device loss discards GPU contents.
- **`Texture` is the one name a draw and a `Sample` take** (agreed 2026-10-07, item 3 of the reshaping of the drawing surface; built the same day). A `Grid2<Color>` converts to one implicitly where a draw or a `Sample` wants one, and so does a `Grid2<float>`, a texture of one channel (a heightmap, a lookup table). A `Texture` value carries its filter and its wrap, so `art.sprite = tiles` draws as `tiles` declared: the `[Filter]` and `[Wrap]` attributes are the sampling a `Texture` is born with, and a draw's or a `Sample`'s arguments an override, which leaves two places to say it where there were three. No fourth CPU image type. What was picked to build it is under Provisional, Textures.
- A grid stays the CPU's pixels: its cells can be local or match state, the ones that changed are uploaded again when they change (those cells, not the grid: see What's sent, under Lists and arrays on the GPU), and the texture it converts to is the grid, not a copy. Rendering into a target never writes a grid's cells.
- `Draw.Blit(source[, textures...], destination[, blend], frag[, values])` has explicit source and destination; `values` is a struct the frag reads, this blit's own (see Provisional, A draw's values). It runs a frag taking `Vertex` and read-only `Texture` parameters, the first its source and each after it the texture given after the source, before the destination (Provisional: Several textures a draw gives), over a full destination quad, replacing color and alpha (of as many of the destination's color images as the frag has outputs, where it holds several), preserving depth, and temporarily ignoring camera and clip (and the other draw settings, below, where it also takes a blend of its own). The source is a `Texture`, which a grid of colors or of floats is there. Sampling the destination's own image is an error. GUI and stats stay on the window. Target storage is recreated after resize, hot reload and device loss; its previous rendered contents are lost.
- **A target says what it holds when it's made** (agreed 2026-10-07), and never changes it. Every target has depth, which its 3D meshes read and write, and its format says what color image is beside it, if any: the color there always was, or none, for a target of depth alone. `RenderTarget(1024, 1024, 1, Format.Depth)` is one (the enum, its members' names and where the format goes are picks: see Provisional).
  - A target of depth alone is drawn into like any other: its `Clear`, its cameras, its clip and its `Mesh` are a target's. A color has nowhere to go there, so only what writes depth leaves anything: a clear, which sets it back to the far limit, and a 3D mesh that writes depth, with a frag or without. A mesh's frag still runs there, as it may leave pixels out (`this.Discard()`); what it writes to its color is dropped.
  - A draw with no frag keeps the engine's default look, and never means "depth only": what a draw writes is said, never implied. Here it's said by where it's drawn.
  - There's no setting for whether a draw writes color: a target of depth alone covers it.
- **A target holds several color images, a format for each** (agreed 2026-10-07): the formats are written after its size where it's made, one for each color image, four at the most, `RenderTarget(1024, 1024, Format.Rgba8, Format.Rgba16f)` and `RenderTarget.Window(Format.Rgba8, Format.Rgba16f)`. With none it holds one color image, as ever, and `Format.Depth`, by itself, none.
  - Each is read as a `Texture`: `target.colors[i]`, counted from 0 in the order of the formats, and `target.color` is the first.
  - A frag's outputs go to them in the order they're written (see Code the GPU runs, below). An output with no image in its place is dropped, as a color is in a target of depth alone, and an image past a frag's outputs is left as it was.
- **A color image can be floats** (agreed 2026-10-07): `Format.Rgba16f`, which keeps any number where `Format.Rgba8` keeps each channel from 0 to 1. It's what light that adds up past white wants, and numbers that aren't colors (a normal, a place).
  - Every backend draws into floats (Vulkan, WebGPU, Unity's compute-capable APIs). Until 2026-11-05 a GL fallback without the extension made a float image 4 bytes a pixel and said so once; that fallback went with the GL backends (Compute on the GPU, Backends).
- **A frag reads a target's depth,** as it reads its color: `target.depth` beside `target.color` (agreed 2026-10-07). Every target has it, with color or without, and `Draw.window` has none to read.
  - Read plainly, it's a number: how far the nearest thing drawn there is, from 0 at the camera's near plane to 1 at its far limit, as `this.depth` is, and 1 where nothing was drawn since a clear.
  - Read the second way, it's compared with a number of the frag's, which gives how much of what's stored there is further, from 0 to 1, filtered by the GPU: what a shadow's edge wants.
  - It's the same way up as the target's color, with the same `uv`, and the same number on every backend (to the GPU's own rounding, as everything a frag computes is).

```csharp
local singleton Lamp
{
    RenderTarget map;      // What's nearest the lamp: depth alone
    DepthTexture shadow;   // ...as frags read it
    float4x4 toLamp;       // From the world to the lamp's clip space
}

frag Lit(BoxVertex vertex, out Color color, Lamp lamp)
{
    float4 seen = Math.Mul(lamp.toLamp, float4(this.world, 1));
    float2 uv = float2(seen.x * 0.5 + 0.5, 0.5 - seen.y * 0.5);
    // 1 where nothing is nearer the lamp than this pixel, 0 in shadow, and between the two along a shadow's edge
    float lit = lamp.shadow.Compare(uv, seen.z * 0.5 + 0.5 - 0.01);
    color = Color(lit, lit, lit);
}

view Casters(Box box, Models models, mut Lamp lamp)
{
    // No frag, and the engine's own look: in a target of depth alone, its depth is what's kept
    lamp.map.Mesh(models.crate, models.faces, float4x4.Translate(box.pos));
}
```

- Filtering is how a draw reads the pixels, not part of them: `Draw.Mesh(vertices, indices, texture, Filter.Point)`. Left out, it's `Filter.Bilinear`, as Unity's default. `Filter.Trilinear` is the third (Provisional: see Mipmaps) and `Filter.Anisotropic` the fourth (Provisional: see Anisotropic filtering).
- **What a `uv` past 0 and 1 reads is chosen where a texture is sampled, as the filter is** (agreed 2026-10-07): it's how a draw reads the pixels too, so one texture is read one way in one draw and another way in the next, or both ways in one frag. How it's written, and each rule of it, are picks: see `Wrap`, under Provisional.
- **A texture's declaration can say how it's sampled, for wherever nothing else does** (agreed 2026-10-07, of `[Filter(Filter.Point), Wrap(Wrap.Repeat)]` before an `asset Texture` and an `asset Grid2<Color>`: "also add those attributes for both"). It's a default: a draw or a `Sample` that says its filter or its wrap still has what it says. It's the sampling the `Texture` made there is born with, which the value carries (agreed the same day, above). Where else the attributes go is a pick: see Declared sampling, under Provisional.
- **Code the GPU runs is written in Tide: `frag` and `vert`.** They're declaration kinds, like `view`: a `frag` runs once for each pixel a mesh covers, and a `vert` once for each of its vertices. Their signature says what they read, and the engine supplies it. Neither returns a value. A `Draw.Mesh`, or a target's `Mesh`, names them after its other arguments, the vert first, and both are optional.

```csharp
struct BoxVertex
{
    float3 position;
    float3 normal;
    float2 uv;
}

// Once per vertex: changes it in place, as a system changes a component
vert Wave(mut BoxVertex vertex, Time time)
{
    vertex.position.y += Math.Sin(time.t * 2 + vertex.position.x) * 0.1;
}

// Once per pixel: the triangle's three vertices blended at that pixel, and the pixel's color, which it writes
frag Shade(BoxVertex vertex, out Color color, Box box, Sun sun, Models models)
{
    float light = Math.Max(Math.Dot(Math.Normalize(vertex.normal), -sun.direction), 0.1);
    color = models.wood.Sample(vertex.uv) * box.tint * light;
}

view DrawBox(Box box, Models models)
{
    Draw.Mesh(models.crate, models.faces, float4x4.Translate(box.pos), Wave, Shade);
}
```

  - The first parameter is the vertex: a struct of the game's, or the built-in `Vertex` or `Vertex3`, which is what the mesh's list holds. A mesh draw that names a frag or vert whose vertex isn't its list's is an error. A vert takes it `mut` and changes it in place; the engine then applies the transform and the camera, unless the vert puts its vertex itself (below). A frag gets it blended across the triangle, and can't change it.
  - **A frag's outputs are `out` parameters, its color among them** (agreed 2026-10-07, the owner's idea): `out Color color` is the pixel's color. It starts with no value, as any `out` parameter does (see Out parameters): the frag writes it before it reads it, and on every path that ends, so a frag that leaves a path without writing its color is an error. A frag takes up to four outputs (`Color`, `float`, `float2`, `float4` or `int`, owner-approved 2026-11-13), for a target that holds as many images: they go to them in the order they're written, and each is owed on every path that ends, as the first is (agreed 2026-10-07). A numeric output must fit its image's format; it replaces the stored value with no tint or alpha multiplication. A Color output is blended over what's behind it by its alpha, as meshes are: the frag writes the color itself, and the engine does what its blend needs of it (see Alpha and color space) (or as `Draw.Blend` says, times `Draw.Tint`: see Draw settings).
    - `mut Color color`, which is what a frag's color was, and which started as `Color.white`, is an error that names `out`, with the change as a quick fix. A frag that leaned on the white writes it: the editor offers `color = Color.white;` where a path writes nothing, and where the color is read first.
    - A vert's vertex stays `mut`: it's handed a vertex and changes it. `out` there is an error that says so.
  - **A vert hands its frag a struct of its own** (agreed 2026-10-07): an `out` parameter of the vert's, a struct, which the GPU blends across the triangle and the frag it's drawn with reads as a read-only parameter, so what a vert works out needs no field in every vertex of the mesh. Verts and frags stay declarations of their own, paired where a draw names them, and a frag that reads a struct the draw's vert doesn't write, or in a draw with no vert, is an error at the draw.

```csharp
struct FromLamp { float3 place; }

vert Place(mut Corner corner, out FromLamp lamp, Sun sun)
{
    lamp.place = corner.position - sun.at;
}

frag Look(Corner corner, FromLamp lamp, out Color color)
{
    color = Color.white * Math.Saturate(1 - Math.Length(lamp.place) * 0.1);
}
```

  - **A vert can put its vertex itself** (agreed 2026-10-08). The gap was found writing a sample that moves each corner onto the nearest pixel of a small frame, as a console of the nineties drew: a vert only changed its vertex in the mesh's space, so the sample went to the frame and back by hand, through two matrices a view kept and the inverse of the draw's transform at every vertex. Of three ways offered (a vert that says where its vertex lands, a draw setting that snaps, or the workaround documented), the owner took the first as recommended: "i trust your recommendation". A vert takes where its vertex goes as an `out float4`, in clip space, and `this.clip` is where the engine would have put it. With none, the engine places the vertex, as ever. Each rule of it is a pick: see Where a vert puts its vertex, under Provisional.

```csharp
// Each corner onto the nearest pixel of a frame of `lens.size` pixels
vert Snap(mut Corner corner, out float4 clip, Lens lens)
{
    float4 at = this.clip;
    float2 half = lens.size * 0.5;
    clip = float4(Math.Round(at.xy / at.w * half) / half * at.w, at.z, at.w);
}
```

  - The other parameters are bound as a view's are: components are those of the entity the view that draws runs for, and it's an error at the `Draw.Mesh` when that view doesn't guarantee its entity has one; singletons, the match's or local ones, and `Time`. None is `mut` or `out`. Read-only `Texture` parameters receive the draw's explicit textures, in order: the frag's, then the vert's own, a vert's and a frag's of one name being the one texture (Provisional: Several textures a draw gives).
  - There are no individual plain value arguments to bind: what a frag or vert reads lives in a component, a singleton (local ones included), the ordinary instance struct supplied by `Draw.Instanced`, or the struct a draw gives after its vert and frag (agreed 2026-10-07: "a per-draw parameter struct for `Mesh` and `Blit`, bound as an `Instanced` draw's struct is, so a blur's direction isn't a singleton field written between two blits"; the rest is under Provisional, A draw's values).
  - A grid in what they take is a texture: `models.wood.Sample(uv)` on a `Grid2<Color>`.
  - With no vert, the vertices are used as they are. With no frag, a pixel is its vertex's `color` times the texture's at its `uv`, where the vertex struct has them: white, and untextured, where it doesn't. So a struct with only a `position` draws with no code of the game's, at 12 bytes a vertex.
  - 2D meshes take them too: a vertex struct whose `position` is a `float2` is drawn through the 2D camera or the screen, in order with the other 2D calls.
  - They call ordinary Tide functions, which then have to stay within what the GPU runs.
  - What the GPU computes differs between machines, so it never reaches the match: frags and verts are local code, as views are, and what `Math` makes of floats there is the GPU's own rounding, not Tide's deterministic functions. Only its integers, `Math.Hash`, are the same there as in the match.
- Draw settings (below) say how what's drawn comes out and where it lands: how it blends, what tints it, what moves it, the clip, the camera, and the screen's pixels in the camera's place.
- **The mouse's cursor is locked by asking, frame by frame.** `Cursor.Lock()` asks for the cursor's lock, for a camera that looks around. A view, or a function it calls, calls it every frame it wants the mouse, as with `GUI.ShowKeyboard()`: the lock is held while some view asked in the frame that just ended. When no view asks (a pause menu is up, the match ended), the cursor comes back on its own. There's no `Unlock`.
- `Cursor.locked` is whether the lock holds right now, a `bool`. It's what the platform says, not what was asked, since a platform may refuse the lock or drop it.
- While the cursor is locked, it's hidden, `devices.mouse.position` and the pointer's stay where they were, `devices.mouse.delta` keeps coming with no screen's edge to stop at (the mouse's own movement, without acceleration, where the system gives it), and the GUI sees no pointer: nothing hovers, and a click presses no widget.
- The match never calls `Cursor.Lock()` or reads `Cursor.locked`: the cursor is this machine's.
- Platforms differ, and games read `Cursor.locked` rather than assume. The usual pattern shows the pause menu when the lock goes away:
  - **The web** only gives the lock when it's asked for from a click or a key press, so the page asks at the next one while the game wants it, and at once when the game starts wanting it, which works shortly after one (a Resume button's click). The browser lets the cursor go itself when the player presses Escape, which a page can't prevent and may never see the key of, and when the page loses the focus or is hidden. For a moment after Escape it refuses the lock. Nothing asks again on its own: the player's next click or key press does.
  - **Desktop** windows hold the cursor while they have the focus. Alt+Tab lets it go, `Cursor.locked` is false meanwhile, and the lock returns with the focus if the game still asks. Escape lets it go too, as on the web, though the game still gets the key: while the game goes on asking, the player's next click on the window or press of another key locks it again, and Escape never does. Once a frame goes by without the game asking, that's over: its next ask locks at once.
  - **Android** never locks it, for now: `Cursor.locked` stays false.

```csharp
input PlayerInput
{
    float2 look;

    Sample(Devices devices)
    {
        if (Cursor.locked) look = devices.mouse.delta * 0.003;
    }
}

local singleton Menu
{
    bool paused;
    bool looking; // The window held the cursor last frame
}

view Look(Devices devices, Viewer viewer, mut Menu menu)
{
    Draw.SetCamera(viewer.position, viewer.rotation, 75);
    if (devices.keyboard.escape.down) menu.paused = true;
    if (!menu.paused) Cursor.Lock();
    // The lock went away on its own, as it does at Escape: the pause menu
    if (menu.looking && !Cursor.locked) menu.paused = true;
    menu.looking = Cursor.locked;
}
```

- A struct or component can say how it blends with an `Interpolate` override: `T Interpolate(T from, T to, float t)`, declared in it like an operator, with no value of its own. 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
}

event(Died dead) Respawn(mut Body body, Arena arena)
{
    body.position = arena.start;
    this.Snap(); // No sliding from where it died
}
```

<a id="draw-settings"></a>

#### Draw settings

- Frustum culling is automatic for ordinary 3D draws with trustworthy geometry bounds, separately for each destination's camera and each instance. It preserves surviving draw order and never changes match simulation, view execution or operand evaluation. Skinned meshes and custom vertex shaders require explicit conservative bounds; otherwise they remain drawn. Camera-frustum rejection is separate from triangle-face culling and occlusion. The control names and detailed bounds rules are provisional below.

- A setting changes how everything drawn after it comes out. Each has two forms, told apart by name. The plain name wraps a block, and puts back what it found when the block ends. The `Set` name stays for the draws that follow, in this view and the views after it, until it's set again or the frame ends:

```csharp
Draw.Blend(Blend.Add) { ... }      // Around some draws
Draw.SetBlend(Blend.Add);          // For the views that follow, as a camera is set for a frame
```

- The settings, all with the same two forms:
  - `Blend` and `SetBlend`: how colors go over what's there. `Blend.Alpha` (the default: by their alpha), `Blend.Add`, `Blend.Multiply` and `Blend.Replace`.
  - `Tint` and `SetTint`: fades or colors everything inside, multiplying its color and its alpha.
  - `Depth` and `SetDepth`: what 3D meshes do with depth: whether they're hidden behind what's nearer, and whether they hide what's drawn behind them. Only 3D meshes have depth: around 2D draws it changes nothing, and that's no error. Its modes' names and what each means aren't decided yet (see Provisional).
  - `Cull` and `SetCull`: which side of a 3D mesh's triangles isn't drawn. Each frame starts with the back of a triangle not drawn, as game engines have it. Only 3D meshes' triangles have a back: around 2D draws it changes nothing. Which side is the front, and the sides' names, aren't decided yet (see Provisional).
  - `Transform` and `SetTransform`: moves, turns and scales everything inside.
  - `Clip` and `SetClip`: only what's inside a rectangle draws.
  - `Camera` and `SetCamera`: the camera the draws go through.
  - `Screen` and `SetScreen`: the draws are in the screen's pixels, from the top left with `y` down, as the GUI's are. `Draw.Screen() { ... }` lets a view of the world draw a label in pixels, and leaves the camera as it was for the views after it. What views draw on the screen is under the GUI's widgets.
  - `Stencil` and `SetStencil`: what draws do with stencil, a whole number from 0 to 255 for each pixel, beside its depth. A draw compares the stored number with a number of its own, by a test it names, and isn't drawn where that fails; and it says what becomes of the stored number where it is drawn. It's there as it is on a GPU, and with none of a GPU's other stencil state: no separate state for each side of a triangle, nothing for what a failed depth test does, no bit masks. How it's written, its tests' and operations' names, whose it is and each rule beyond these aren't decided yet (see Provisional).
  - `LOD` and `SetLOD`, `LODPixels` and `SetLODPixels`, `LODCamera` and `SetLODCamera`: which level of detail the meshes marked `[LOD]` draw at, the allowed screen error for automatic selection, and the camera they pick one through (see Levels of detail).
- A form written as the other is a compile error, whose message names the other: `Draw.Blend(x);` with no block points to `Draw.SetBlend`, and `Draw.SetBlend(x) { }` to `Draw.Blend`. The spellings from before settings had two forms are errors the same way: `Draw.Camera(...);`, `Draw.Camera(...);`, `Draw.Clip(rect);`, `Draw.Clip();` and `Draw.Screen();`, and each on a render target. The language server offers the rename as a quick fix.
- Every frame starts from the defaults. The GUI and the stats overlay are never drawn with a game's settings.
- A block that's left early (`return`, `try`, `fail`, `break`, `continue`) still puts back what it found, as a GUI container is still closed.
- Settings can be listed with commas before one block, with each other and with any other call that takes one (see Calls that take a block).

```csharp
view Sparks(Spark spark, Hud hud)
{
    Draw.Blend(Blend.Add),
    Draw.Tint(Color(1, 1, 1, spark.life))
    {
        Draw.Circle(spark.position, spark.radius, spark.color);
    }
    Draw.Screen()
    {
        Draw.Text(spark.name, Draw.WorldToScreen(spark.position), 14, Color.white);
    }
}
```

<a id="integral-values-from-vert-to-frag-decided-2026-11-13"></a>

#### Integral values from vert to frag (decided 2026-11-13)

Owner: "these make sense, lets do all of these". A struct a vert hands its frag may
hold ints and int vectors, carried unblended from the triangle's first corner. A float
field stays blended, and all read fields count toward the existing 15 carried values.

<a id="pixel-readback-decided-2026-11-13"></a>

#### Pixel readback (decided 2026-11-13)

The owner: "these make sense, lets do all of these". `await target.Read()` in local async code gives an owned
`Grid2<Color>` with `fails IOError`, by the same asynchronous rules as GPUList.Read. It never enters match code.
It captures the frame drawn after the request, a frame or more later, and fails when the device is lost.
Colors are straight Color values, as Sample returns, rather than multiplied by alpha.
The grid `is` names is a local's grid, which a task keeps across its later waits as it keeps its lists, a copy of
its own in its frame (Provisional, Claude, 2026-11-14: Grids a task keeps across its waits).
A target's other color images, images of numbers as their own types, its depth, a cube's faces and an array's
layers are read too since 2026-11-14 (`Read(image)`, `Read<T>()`, `ReadDepth()`), and `target.colors.count`
says how many images it holds: their rules are picks, under Provisional (which image a read is of, and as what).

<a id="depth-bias-decided-2026-11-13"></a>

#### Depth bias (decided 2026-11-13)

The owner: "these make sense, lets do all of these". `Draw.DepthBias(constant, slope) { ... }` and
`Draw.SetDepthBias(constant, slope)` are destination-owned draw settings, also methods on render targets.
Blocks restore the preceding setting; `Draw.SetDepthBias()` restores none. They change only 3D draws.
Positive bias pushes away from the camera, including when the depth image uses reversed storage.

<a id="a-frag-writes-depth-decided-2026-11-13"></a>

#### A frag writes depth (decided 2026-11-13)

The owner: "these make sense, lets do all of these". `this.WriteDepth(value)` replaces a pixel's depth,
with the forward 0-near, 1-far value read by `this.depth` and DepthTexture.Sample.

<a id="explicit-mip-level-decided-2026-11-13"></a>

#### Explicit mip level (decided 2026-11-13)

The owner: "these make sense, lets do all of these". `Texture.SampleLevel(uv, level[, filter[, wrap]])`
reads a float mip level the game chooses. `Cubemap.SampleLevel(direction, level[, filter])` reads a direction.
These calls run in frags, verts, kernels and their GPU helpers. Texture3D has no mipmaps: use Sample there.

<a id="triangle-side-decided-2026-11-13"></a>

#### Triangle side (decided 2026-11-13)

Owner: "these make sense, lets do all of these". A frag reads `this.front`, a read-only bool:
whether its pixel is on the triangle's front by the winding `Draw.Cull` uses, including
mirrored instance and camera transforms. It does not require culling to be enabled.

<a id="what-the-gpu-side-gains-agreed-built-in-part"></a>

#### What the GPU side gains (agreed, built in part)

Agreed 2026-10-07. The aim is a complete set of raw pieces, so a game can build any technique itself (shadow maps were what started it), with no lighting or shadows of the engine's own. Nearly every technique draws into an image and reads that image in a later frag, so the pieces are what an image holds, what a draw's state is, what a frag reads and what it writes.

- **Built, where the rest of this list isn't yet:** a target says what it holds when it's made, a target of depth alone among them, and a frag reads a target's depth, plainly or compared with a number. Their rules are with the render targets' above (Views and drawing), and what was picked to build them is under Provisional (Target formats and depth).
- How `uv` wraps was agreed with these, and is built: see Decided above, and `Wrap` under Provisional.
- **A frag has more outputs than one color,** each an `out` parameter, into a target made to hold as many. Built: its rules are with the render targets' and with Code the GPU runs, above, and what was picked to build it is under Provisional (Several colors and float images).
- **A target's samples** (multisampling, agreed 2026-10-07 as item 8 of the drawing surface's reshaping: "MSAA on render targets, a `samples` argument", as 3D mesh edges have no antialiasing). Built: what was picked to build it is under Provisional (A target's samples).
- **Float color formats** were agreed as wanted with these (light past white, and positions and normals for deferred shading), and what the OpenGL fallback did about them was decided as they were built (history since the GL backends went): see A color image can be floats, above.
- Built since: a frag's color as `out Color color` and a vert's struct for its frag, which are in the rules above (Code the GPU runs), which side of a triangle draws, which is among the Draw settings, above (`Draw.Cull`), and stencil, which is among them too (`Draw.Stencil`). Their picks are under Provisional.
- Built since: mipmaps, as a filter, `Filter.Trilinear`, with the level's derivatives asked as a frag starts so that code still samples in any branch. What was picked to build it is under Provisional (Mipmaps).
- Built since: cube maps, as a type of their own, `Cubemap`: an asset's six files, or six faces a view draws into, read by a direction. It was item 9 of the drawing surface's reshaping, the last. What was picked to build it is under Provisional (Cubemaps).
- Built since: asynchronous pixel readback with `await target.Read()`, described above.
- Open: a `shader Name { ... }` block that groups a vert and a frag under one name, maybe with the two unnamed inside. It would only add a name for a pair that's checked already, so it can come once naming two at a draw gets tedious.

<a id="provisional-24"></a>

### Provisional

<a id="provisional-pixel-readback-2026-11-14"></a>

#### Provisional: pixel readback (2026-11-14)

`Read()` reads color image zero, including its resolved image for multisampling; the other reads are below
(Which image and as what, 2026-11-14).
RGBA8 preserves its stored quantization; RGBA16f preserves HDR values above one. Transparent pixels give zero.
Grid dimensions are physical pixels, with x right and y down. A copied grid uses `.Copy()` under ordinary grid
ownership rules; a directly awaited return is fresh. `is Grid2<Color> pixels` can unwrap this failable result.
There are 64 read slots shared with list reads, and 512 MiB of outstanding pixel results; an image of any size is read
(Reads of any size, of parts and of volumes, below). Exceeding the byte limit fails; occupied slots wait, as list reads do. Headless native runs
wait at the next frame's start. Hidden fixed-size web test frames wait between WASM frames for pending mappings,
so scripted frame counts agree without blocking the browser thread. Ordinary resizable web games remain async.
Unsupported formats fail before binding a shader. `Read()` accepts Rgba8/Rgba16f as Color and always
unpremultiplies; an Rgba16f image's format alone does not record a numeric role.

<a id="provisional-which-image-a-read-is-of-and-as-what-2026-11-14"></a>

#### Provisional: which image a read is of, and as what (2026-11-14)

The owner asked that every read that can work does (2026-11-14: "make sure everything we can add or validate
we do"). What was built, each a pick with what it was weighed against:

- **`await target.Read(image)` reads color image `image`,** counted from 0 as `target.colors[image]` is. It is a
  constant int (a literal, or a `const` of literals, other constants and operators), from 0 to 3: the image is part of what the read gives, which the
  compiler has to know. An index that's only known as the game runs was weighed and refused for that reason,
  not left to fail as it runs; `target.colors[i].Read()` was weighed too, and would have made every `Texture`
  look readable where only a target's image is.
- **An image of numbers is read as its own type, written at the read:** `Read<float>()` for R8, R16f and R32f,
  `Read<float2>()` for Rg8 and Rg16f, `Read<float4>()` for Rgba32f, `Read<int>()` for R32i, each giving a
  `Grid2` of that type, `fails IOError`; `Read<Color>()` is `Read()`. R32f, Rgba32f and R32i come back bit for
  bit, R16f and Rg16f as the half float stored, R8 and Rg8 as the stored byte over 255. Nothing is clamped,
  multiplied by an alpha or divided by one. `Read<float4>()` also reads an Rgba16f image, as its four stored
  numbers (what a `float4` output wrote), where `Read()` gives the same image as a Color.
  - **How the type is known:** the game writes it, and the compiler holds it against the format the target was
    made with, by the same record of constructor assignments that checks a numeric frag's outputs and a typed
    clear. A mismatch is an error that names the image's format and the read that fits it. A format that isn't
    fixed (a `RenderTarget` parameter, a field made with one format here and another there, a format that's a
    variable) is an error for a number read, with the fix: make the target one way wherever it's assigned and
    read the field or local it's kept in. Inferring the grid's type from the format, with nothing written, was
    weighed: a field's formats are settled only once every body is checked, so an expression's type would
    depend on distant assignments, and change with them silently. One `Read()` returning a tagged value was
    weighed and refused: every use would have to ask what it got.
  - **A Color read of a target whose formats aren't known** (`Read()` of a parameter) still compiles, as it
    did: it's checked as it runs, and fails with `IOError` where the image isn't an Rgba8 or Rgba16f one.
  - The engine checks every read again as it's asked and as it begins: an image the target hasn't got, a kind
    that isn't the image's, a target disposed meanwhile, and a result of another size than its grid's cells
    all fail the read and write nothing.
- **`await target.ReadDepth()` gives a `Grid2<float>` of the target's depth,** in the forward terms `this.depth`
  and `DepthTexture.Sample` use (0 near, 1 far), under reversed float storage and under the forward 24-bit
  fallback alike: the read converts as a depth's `Sample` does. A target of depth alone is read this way, and
  a multisampled target gives one depth a pixel, by the resolve a frag's read of it gets (A target's samples).
  Under float storage a depth a frag wrote with `WriteDepth` comes back exactly where `1 - depth` is exact
  (every multiple of 2^-24 is); under 24 bits, to the nearest step. `target.depth.Read()` was weighed, and
  `Read<float>()` of a `Format.Depth` target: a method beside `ClearDepth` says what's read for every target,
  with color beside it or not, and keeps `DepthTexture` a GPU reference with no CPU read of its own. A raw or
  linear depth read isn't offered, as none is to a frag.
- **A cube's face and an array's layer are read as the targets they are:** `await cube.faces[i].Read()`,
  `await array.layers[i].Read()` and `ReadDepth()` of either, rows from the top as they were drawn. Each holds
  one image, of the format its cube or array was made with, so an image number is an error there, and the read's
  type is checked against that format as a target's is: `Read()` for Rgba8 and Rgba16f, `Read<float>()` for R8
  and R16f, `Read<float2>()` for Rg8 and Rg16f, `Read<float4>()` for an Rgba16f one's stored numbers (Number
  images as array layers and cube faces, below; they hold no R32f, Rgba32f or R32i). A face's and a layer's
  numbers are read as all four channels and the grid keeps its type's: one kernel for faces and one for layers,
  at four words a pixel while the read is pending, was picked over a kernel for each type. A layer past
  the array's fails as it runs, and an asset's cube or array has no faces or layers to read. A whole cube or array in one
  read (a `Grid3`, or six grids) was weighed: one face is the unit they're drawn in, and a whole array can pass
  the pixel limit that a layer doesn't.
- **`target.colors.count` is how many color images a target holds:** 0 for a target of depth alone, for a
  default one and for a disposed one, 1 for a face or a color layer. `target.colors` is otherwise still read one at a
  time. `target.colorCount` was weighed: `colors.count` is what a list's is called, and needs no new name.
- **The window can't be read,** and that's a compile error as before (`Draw.window.Read()`, `ReadDepth()`). It
  isn't the same path: a read runs a kernel that samples the image, and the window's image is the swapchain's
  (Vulkan) or the canvas's (WebGPU), which Tide makes as an attachment only. Vulkan surfaces needn't offer
  sampled swapchain images, a canvas texture is gone once the frame is presented, the window's format is the
  display's (BGRA on many), and under Unity the window is Unity's camera target, which Tide never holds. Reading
  it would mean drawing every frame of any game that might read into a target of Tide's first and copying that
  to the display, a cost for all frames to serve one. A game that wants its frame draws into
  `RenderTarget.Window()`, reads that, and `Draw.Blit`s it to the window.
- **Limits are the Color read's:** 64 read slots shared with list reads, and 512 MiB of outstanding results (a float
  or int image is 4 bytes a pixel of it, a float2 one 8, the others 16, and so is any read of a face or a layer).

<a id="provisional-reads-of-any-size-of-parts-and-of-volumes-2026-11-14"></a>

#### Provisional: reads of any size, of parts and of volumes (2026-11-14)

The owner asked that every read that can work does ("make sure everything we can add or validate we do"). Each a pick:

- **An image of any size is read.** The 4,000,000-pixel limit was the one dispatch's (65,535 groups of 64); a read now
  runs its kernel over a band of rows at a time, each band a buffer of its own of at most 32 MiB and 65,535 rows, all
  of them from the same frame's image and read back on their own, so a 4K or 5K `RenderTarget.Window()` is read whole
  whatever one buffer a device binds (128 MiB on every WebGPU device). What reads hold together, from when their
  kernels run until they're let go of, is at most 512 MiB (a 5K window's Color, 225 MiB, fits; an 8K one's alone):
  past that a read fails with `IOError`. Weighed: tiles a game asks for itself (the rectangle below does that, where a
  read of the whole image would hold too much), and a whole image in one buffer (past what devices bind).
- **A part of an image: `Read(int2 from, int2 size)`**, after the image's number where it has one (`Read(1, from,
  size)`, `Read<float>(from, size)`) and the same for `ReadDepth(from, size)` and a face's and a layer's reads: its
  first pixel and how many pixels across and down, in the image's own pixels (as the grid is), x right and y down.
  It's clamped to the image: the grid is the part inside it, its cell (0, 0) that part's first pixel, and a part with
  none of the image in it, or a size of 0 or less, fails. The limits are the part's, so a tile of an image too big to
  hold whole reads, and picking one pixel copies one. Weighed: a `Rect` (it's floats, for the GUI, where a read's
  pixels are whole), a type of int rectangles (one more type for a pair of int2s), and a grid of the size asked for
  with zeros outside the image (a read past the edge would look like pixels of zero).
- **A `Texture3D`'s cells: `await volume.Read()`, `Read<T>()` and a box, `Read(int3 from, int3 size)`,** an owned
  `Grid3` of the volume's format's type, `fails IOError`, as an image's read is: `Read()` of an Rgba8 or Rgba16f volume
  (straight Colors), `Read<float>()` of R32f, `Read<float4>()` of Rgba32f (and an Rgba16f volume's numbers),
  `Read<int>()` of R32i, each cell exactly as a kernel's `volume[at]` reads it. The type is checked against the format
  the volume was made with, as a target's is. The box is clamped as a part is. A volume nothing wrote yet reads zeros;
  one made from a `Grid3` is that grid's, which the CPU has: reading it is a compile error that says to read the grid
  where the compiler sees the volume made so, and fails as it runs where it can't (a `Texture3D` parameter handed one).
  A volume's cells are a `Color`, a `float`, a `float4` or an `int`, its formats' (no `Read<float2>`: no `Texture3D`
  format holds two numbers).
- **Not there:** a `Texture` asset's pixels back. The same pixels, exactly, are a `Grid2<Color>` asset of the same file
  on the CPU with no wait (`asset Grid2<Color> map = "art/map.png";`), where the GPU's copy can be block-compressed
  (BC1, BC3, BC7: a device's decoding of the blocks, not the file's pixels) and is made only for a frame that draws
  with it. Also not there: a number read of a target whose format is only known as the game runs.

<a id="provisional-depth-bias-2026-11-14"></a>

#### Provisional: depth bias (2026-11-14)

Constant is a number of GPU depth precision steps, truncated toward zero to match WebGPU's integer factor.
With integer depth a step is its smallest representable interval. With floating depth it follows the
primitive's largest stored-depth exponent; it is not a fixed fraction of the forward range. Slope multiplies
the largest absolute pixel-depth slope. Positive pushes away; negative pulls nearer. Bias is GPU raster state,
so WriteDepth replaces it. Magnitudes can differ across depth formats; the visibility direction is portable.
A fixed forward interval was considered, but core WebGPU exposes precision-scaled constant bias rather than
that interval; doing it in shaders would change depth testing and add fragment work to every affected draw.
Constants outside [-65536,65536], slopes outside [-16,16], NaN and infinities restore zero for that factor.
No depth-bias clamp is exposed. Vulkan uses dynamic state; WebGPU keeps at most 32 bias variants per logical
pipeline, evicting the least recently used, with zero bias reusing the original. Logical renderer pipeline
counts are unchanged; these device pipeline variants are additional. Occlusion tests of biased instances
are disabled because their geometric depth is not the rasterized depth. Draws under different biases never
share a command, a culled set, a level's gathered run or a GPU call, so a decal drawn right after its base keeps
its own (the gathering of a mesh's levels on the CPU's path didn't compare it until 2026-11-14).

<a id="provisional-a-frag-writes-depth-2026-11-14"></a>

#### Provisional: a frag writes depth (2026-11-14)

WriteDepth is a statement in the frag itself, following Discard's implicit-this rule. A helper returns its
computed depth for the frag to write. The last write on the path wins; a path without a write keeps triangle
depth. Values clamp to [0, 1], with NaN becoming zero. `this.depth` continues to report rasterized depth.
Depth tests use the replacement: Equal compares it, Only writes it without color, and multisampling applies
it to each covered sample. The shader makes no early-test promise, allowing the device to test after writing.
Automatic geometry-bound culling is disabled for these shaders: their triangle bounds cannot predict their
depth. Explicit Bounds can describe geometric clipping, but never re-enable occlusion testing for a depth-writing
frag. Actual stored depth still contributes to occlusion of later ordinary draws. A matching prepass must
run the same depth-writing frag. Chosen over conservative-depth restrictions, which would limit the feature,
and over an error under Equal/Only, which would prevent useful prepasses.

<a id="provisional-explicit-mip-level-2026-11-14"></a>

#### Provisional: explicit mip level (2026-11-14)

NaN levels become zero; negative infinity clamps to zero and positive infinity to the last image.
Level zero is the original image, one halves each dimension, and fractional levels blend with Trilinear or
Anisotropic. Point and Bilinear retain their base-image sampler contract. A SampleLevel that names no filter is
Trilinear (Provisional, Claude, 2026-11-14), on a Color texture, a cube and an array as on a typed image, whatever
filter the texture says: a level read through a filter that reads none would be the base image's, which the
editors' two-argument `SampleLevel(uv, level)` silently was. Weighed: the texture's own filter, as `Sample`'s is (a
cube's Bilinear), with a warning where it's known to read no levels; and an error asking for the filter; chosen the
filter the call means. SampleGrad keeps the texture's own filter, as its gradients are how Anisotropic is reached.
A level written as a number of 0 or less (`SampleLevel(uv, 0)`, `-1`) with no filter named reads as Bilinear
(Provisional, Claude, 2026-11-15): Trilinear there reads the base image alone, the same pixels, and a target read so
would otherwise have its whole chain of smaller images made again after every pass that draws into it, a
post-process's cost every frame for nothing it reads. It's why an `R32f` or `Rgba32f` image, which has no levels,
takes `SampleLevel(uv, 0)`: four exact loads, as `Filter.Bilinear`. A cube's `R32f` or `Rgba32f` faces are read
only at their nearest pixel, so a cube's `SampleLevel` takes them only naming `Filter.Point`, at level 0 too. Weighed: Trilinear as written, with the cost
noted; and any level the compiler can work out to 0, which takes constant folding of every expression for a rare
spelling. A level known only as the game runs is Trilinear, and makes the chain.
Levels clamp to 0..31 and the sampler's
available chain; an image with no smaller images reads level zero. TextureArray uses
`SampleLevel(uv, layer, level[, filter[, wrap]])`: layer precedes level to keep Sample's argument order.
Chosen over level-before-layer, which would make a positional float level look like the existing integer layer.
Cubemaps have no Wrap, as faces continue into one another. Drawing into a chosen mip level is not provided.
No new backend API or recorder packet is needed: WGSL explicit-level sampling already translates to SPIR-V and HLSL.


- Integral handed fields (built 2026-11-14): bytes, bools and enums use the same flat
  path as ints and int vectors. Bools travel as integer 0/1. The first corner is the
  first index of each triangle. Unity OpenGL Core is the exception: it uses the last
  corner; the replay has no provoking-vertex control. Direct3D 11/12, Vulkan and
  Metal use the first. Floats have no flat annotation.
- A frag reads its vertex's ints and int vectors itself (built 2026-11-14, Provisional, Claude): from the
  triangle's first corner, flat, as handed ints are, each read field one of the 15 carried values, with the same
  Unity OpenGL Core exception. A frag that reads its whole vertex as a value gets its ints the same way (they were
  zeros before). This replaced the refusal that sent games to a vert to hand the int on, which was a pick rather
  than a GPU limit: every backend carries a flat vertex attribute through the same `@interpolate(flat)`, SPIR-V
  Flat and HLSL nointerpolation path. Weighed: keeping the refusal (an explicit vert says where the int comes
  from, but costs a vert for every per-face ID, and its old fix, a float in the vertex, interpolated three equal
  values into a number `int()` can truncate); an attribute marking a field flat (floats stay blended without
  one, so ints need none).

- Triangle side (built 2026-11-14): in 3D, the GPU's side is corrected by the signs of the
  instance and camera determinants, even when `Cull.None` mixes mirrored instances in one draw.
  This costs one flat varying, included in the existing 15-value limit. In 2D, `this.front`
  reports the rasterized winding; `Draw.Cull` still changes nothing around 2D draws.
  A helper cannot read a frag's implicit `this`, as with `Discard`; pass the bool to it.

- Alpha and color space (the owner picked both 2026-10-07, from a proposal with pictures: "go with your recommendations, we will polish if we find out it wasnt ideal after all"; built the same day). Decided: colors are premultiplied under the hood, with everything a game writes staying a color as it is; and unmarked colors are the display's values, blended as such. The opt-in Linear image mark above changes only those images' sampled space. The rules below are picks made to build it, to confirm:
  - **A game never multiplies.** A `Color` is its color and how much of it there is, in a draw, a tint, a vertex, a grid's cell, a PNG, C's pixels and what a frag writes. The engine works the alpha into the color on the way to the GPU: in a texture's bytes (an asset `Texture`'s as the pack is built, a grid's and C's pixels as they're copied for the GPU), and in every pixel a shader writes, after its tint.
  - **`Blend.Alpha`** is the color, and what's there less the color's alpha; the alpha that's there becomes `a + d * (1 - a)`. **`Blend.Add`** adds the color, and raises the alpha that's there by its own of what was left to 1, so it never passes 1, in a float image either (an image whose alpha grew past 1 would read back darker than what was added). **`Blend.Multiply`** is as it was. **`Blend.Replace`** puts the color and its alpha in place of what's there, as an image keeps them: it isn't a way to write numbers with an alpha other than 1.
  - **`Sample` gives the color itself:** what the texture holds, blended between its pixels, divided by its alpha. A pixel with no alpha is `Color(0, 0, 0, 0)`. So a frag reads and writes colors as they are, and what's blended between an opaque pixel and a clear one is the opaque one's color with less alpha. A depth and a `Grid2<float>` are read as they were.
  - **A target holds each color times its alpha.** Drawn from (`target.color` in a draw), it goes over what's there as what was drawn into it would have. Onto the window, which has no alpha, a color replaced with an alpha under 1 shows darker by that much.
  - **What's lost:** the color of a pixel whose alpha is 0, and, in an image of bytes, the finer steps of a color that's nearly clear. An image whose alpha isn't how clear it is says so with `[Raw]` (below).
  - **`[Raw]` marks a texture as numbers** (built 2026-10-07; extending it to `Texture` fields following raw grid fields is owner-approved, 2026-10-25). Before an asset that's one `Texture` or one `Grid2<Color>`, or on a field of either type (and since 2026-11-05, the owner's "work on the gaps", before a `TextureArray` or `Cubemap` asset and on a `TextureArray`, `Cubemap` or `Grid3<Color>` field, whose roles follow the same rules: a `[Raw] TextureArray` field takes a `[Raw]` array asset or field or a `[Raw] Grid3<Color>`, a `[Raw] Cubemap` field a `[Raw]` cube asset or field; a cube's faces are packed raw and never compressed): pixels are kept as the file or cells have them, with no alpha worked in, and `Sample` gives them as numbers. A large enough Raw `Texture` asset is block-compressed like a color one, lossy but never premultiplied; `[Lossless]` keeps it exact (see Assets, `[Raw]` textures compress too). A `[Raw] Texture` field keeps an ordinary reference with a statically declared numeric role, including attached local fields and fields reached through type aliases. Its initializer or assignment accepts a singular `[Raw] Texture` asset, another `[Raw] Texture` field, a `[Raw] Grid2<Color>` asset/field, or `default`. Ordinary color sources cannot initialize it. Whole values containing annotated fields preserve their roles. Direct `.size` reads remain valid on CPU/GPU, including zero dimensions for missing resources. Raw grid references retain the ordinary borrowed lifetime and bounds checks.
  - Raw sources sample by name or through read-only GPU helper parameters, whose shader specialization retains the original source and its role. They cannot escape into an unannotated `Texture` field, a `mut` local, a return, an unmarked CPU Texture parameter, a mutable/out Texture parameter, or the engine's own draw (a draw or blit with no frag whose source is `[Raw]`). There is no new `RawTexture` type or runtime sampling bit. `[Raw]` remains invalid on `Grid2<float>` (already numeric without alpha), `RenderTarget`, and a glob of grids (whose cells code reads).
  - **Where a role goes** (built 2026-11-14 after an audit; Provisional, Claude): `[Raw]` goes before a glob's `List<Texture>` or `Map<string, Texture>` too, every image packed as numbers, and `[Raw]` (or `[Linear]`, above) before a read-only image parameter of a function, a `List<Texture>`/`Map<string, Texture>` parameter (its elements marked), and a frag's Texture source. The role follows the value statically: a glob's element (`maps[i]`, `maps["a.png"]`, a `foreach` variable, an entry's `value`), a local that isn't `mut` (its initializer's, a `[Raw]` grid's too), a `?:` or switch whose every arm has it, and a marked parameter (whose every call's argument must have it, as no role is added). Each such value is a use that must reach a place that keeps the role (a field of the role, a marked parameter, a frag's marked source, a GPU helper, `.size`), or it's the existing escape error naming it; a choice whose arms differ is one error naming the two roles, where it was two contradictory ones (2026-11-15: a `[Raw]` side and a `[Linear]` one too, which was three errors, and two typed sides of different types). A marked glob is read by element, `count`, `Has` or `foreach`; handed on whole it's an error naming the `[Raw] List<Texture>` parameter. Typed `[Raw(T)]` values go through locals that aren't `mut` the same way, and are a typed frag source through one (Provisional, Claude, 2026-11-15, as every other role through a local). Each typed role is its own (Provisional, Claude, 2026-11-15): a `[Raw(T)]` parameter takes an image of that role, a CPU function's too (as it took a grid of those numbers and refused a typed field), and a bare `[Raw]` parameter refuses a typed one rather than read its numbers as colors; weighed: letting `[Raw]` take every typed role, which drops the type a draw checks formats by. A `?:` or switch whose result is a `Texture` holds a grid of numbers on any side to the `[Raw(T)]` the choice goes to, as a grid alone is (it took one with no check, which drew its numbers as colors). Each texture a draw gives is held to the role of the frag parameter that reads it, not to every marked parameter the frag has (with several textures to a frag, 2026-11-15); a vert's Texture and a frag's of one name are one image, so a frag's `[Raw]` or `[Linear]` there, which a vert's can't have, is the two-roles error. Weighed: a role bit carried at run time on every `Texture` (beside its filter and wrap), which the shader would read from the draw's uniforms to skip the unpremultiply and the renderer to pick the sRGB image. It would let a plain `Texture` parameter, local or return carry either role, but a reference's 64 version bits have no bit free beside a pack name's, a grid's handle and sampling, Linear images are packed for their reading (so a run-time bit couldn't make an unmarked image linear anyway), and every shader reading a carried texture would pay a branch and a uniform. The static role covers globs, choices, locals and helpers with no ABI or shader change; a function's result stays unmarked, so a helper that picks an image assigns it to a marked field or hands it on as a marked parameter. The same file declared both ways is two textures to code, and one image in the pack and on the GPU where both come out the same bytes, as an opaque file's do (2026-11-04: a pack's texture blocks are shared by what they store); code reads raw grid cells as any grid's. Changing a Texture field's role on hot reload resets it to the destination default; compatible Raw fields retain their references. Each typed role (`[Raw(float)]`, `[Raw(float2)]`, `[Raw(float4)]`, `[Raw(int)]`) is a role of its own there, on Texture, Texture3D, TextureArray and Cubemap fields alike (2026-11-14), so an edit from one to another resets the field too, rather than handing its old image to a read of another type; the renderer also gives an integer read no image but an integer one, whatever the draw list says.
  - **Not built:** a role carried at run time by a plain `Texture` value (weighed above), so a function's result is unmarked; C's own pixels as numbers. There is no sRGB render-target `Format`; the opt-in Linear sampled-image mark and Math transfer helpers are described above.
- What a frag and a vert write, where the agreed rules leave a choice (built 2026-10-07, to confirm):
  - **By type.** A vert's struct and the frag's parameter are matched by type, as a system finds a component: `out FromLamp lamp` in the vert, `FromLamp lamp` in the frag, whatever each names it. So a frag and a vert each take a struct type once.
  - **A vert can write several structs,** each its own `out` parameter, and a frag take any of them: nothing limits it to one but the 15 values a GPU carries from a mesh's corners to its pixels, which the draw checks. Only the fields a frag reads are carried, each one value: a field no frag reads costs nothing, and neither does a struct the draw's frag doesn't take, or a draw with no frag.
  - **What the struct holds:** floats, their vectors and colors blend; ints, int vectors, bytes, bools and enums are flat (decided 2026-11-13, details above). Matrices, quaternions and nested structs remain errors at the vert's `out` parameter. A frag reads its vertex's own ints flat too, with no vert (above).
  - **The vert writes all of it:** each field, on every path that ends, a field at a time or the whole struct at once, before reading it (see Out parameters). `lamp = default;` fills it where there's nothing to give.
  - **A path that ends in `this.Discard()` owes the frag's color nothing,** as `fail` owes an `out` parameter nothing: no pixel is drawn.
  - **A frag's struct is the vert's or the instances'** (or, since, the draw's values: below). A frag's read-only struct was an element of the list `Instanced` draws; it's now that, or what the draw's vert writes, by its type, and a frag can take one of each. A draw whose vert writes a struct of the type its instances are is an error at the draw, as a frag couldn't tell them apart. A vert's read-only struct is an instance's or the draw's values.
- **A sprite in one call** (the owner's "yes do it", 2026-10-20, to a call for sprites; built 2026-10-21; each rule here is Claude's pick, to confirm): `Draw.Sprite(texture, center, size, color)` draws a texture upright over a box, where a mesh takes four corners and six indices.
  - **Its box is a rect's.** `center` and `size` are `Draw.Rect`'s, and the texture's top left corner is at the box's top left. The top is towards the top of the screen, up the world's y under a camera and down the screen's in `Screen`, as text's is. A negative width or height mirrors it.
  - **Its forms:** `Draw.Sprite(texture, center, size)`, white; `(texture, center, size, color)`; `(texture, center, size, rotation, color)`; `(texture, center, size, part, color)`; and `(texture, center, size, part, rotation, color)`. The texture is first, as text's string is. `part` is a `Rect` of uvs, (0, 0) the texture's top left corner and (1, 1) its bottom right, as Unity's `Graphics.DrawTexture` takes its source rectangle in uvs (with y up there): a sheet's frame or an atlas's picture. `rotation` turns it about its center, in radians from +x towards +y, as `Draw.Rect`'s does.
  - **It's read as a mesh's texture is:** a filter and a wrap after the rest, the texture's own where the call leaves them out. A render target has it as a method, `target.Sprite(...)`.
  - **It's the quad it is.** Unturned, and where no tint or transform changes it, it's the record a mesh of one quad is kept as, more of the last command's run where that has the same texture, filter, wrap and blend, whatever their colors. Otherwise it's four corners and two triangles from its top left round, which a tint or a transform changes as a mesh's. Either way, it's the same pixels as the mesh of those corners.
  - Not built: a pivot other than the center, and a part in the texture's pixels.
- **A clear of depth alone** (built 2026-10-13; the owner asked for the engine to be fixed where a game had worked around there being none, and each rule is Claude's pick, to confirm): `Draw.ClearDepth()`, and a target's `target.ClearDepth()`, with no arguments.
  - **It sets depth back to the far side and leaves everything else:** every color image as it is, and stencil too, where `Clear` fills the colors and sets stencil to 0. So the 3D meshes drawn after it are in front of everything drawn before.
  - **It's a clear in every other way:** over the whole destination or what the clip leaves of it, whatever blend, tint, transform, depth, cull and stencil are set, and in a target of depth alone too.
  - Not there: a clear of stencil alone, and a depth other than the far one.
- Where a vert puts its vertex (built 2026-10-08; that a vert can say where its vertex lands is decided, above, and the owner took the form recommended; every rule here is Claude's pick, to confirm):
  - **`out float4` is the place, by its type,** as a frag's `out Color` is its color: one a vert, whatever it's called, anywhere after the vertex. A second is an error. `mut float4` is an error that names `out`, with the change as a quick fix. An `out` of another plain type is the error it was (a vert hands its frag a struct), which for a float vector also names this.
  - **It replaces the engine's placing.** What the vert leaves in it is where the vertex is drawn, as it is: neither the draw's transform nor the camera is applied to it. A vert with none is placed by the engine.
  - **It starts with no value, and the vert writes it on every path that ends,** as a frag writes its color (see Out parameters): whole first, then a component at a time if it likes (`clip = this.clip; clip.z = clip.w;`). The editor's fix for a path that writes nothing is `clip = this.clip;`, which leaves the vertex where the engine would have put it.
  - **A vert's `this` is its vertex as the engine would place it,** as a frag's is its pixel. It has one field, `this.clip`, a `float4`: the camera times the draw's transform times the vertex's `position` as the vert has it at that line, so a vert that changes its vertex and then reads it gets the changed place. For a 2D mesh it's through the 2D camera or the screen, with `Draw.Transform` in it. It's read-only: assigning it, or a part of it, is an error that says to take `out float4`. `this` there has no methods, and none of a pixel's fields, each an error that says what it has; like a frag's, it can't be kept or passed whole, and a function a vert calls has none.
  - **A vert that only reads `this.clip`** (to hand its frag a depth, say) is placed by the engine.
  - **Clip space is `WorldToClip()`'s** (see The cameras as matrices, below): OpenGL's on every backend. `x / w` and `y / w` from -1 to 1 across the destination, y up, and `z / w` from -1 at the near plane to 1 at the far limit; tidec writes the conversion for WebGPU, as it does for the engine's own placing.
  - **A frag's `this.world` is still the vertex's own place in the world,** the draw's transform of its `position`, wherever its vert put it in the frame: light and shadows worked out from it don't move with the vertex. `this.position` and `this.depth` are where the pixel was drawn.
  - **Nothing more is sent,** as the camera and the transform are in the shader already, and a game with no such vert generates the C and the shaders it did.
  - **Argued:** writing it through `this` (`this.clip.xy = ...`) is shorter and is what one tries first. It was left an error: what a frag and a vert write is `out`, which their signatures then say; `this`'s fields are read-only everywhere else; and a field that's both the engine's place and the vert's own needs a rule for a vertex changed after it was written. A named type in the place of `float4` would say more, at the cost of a type for one value.
  - **Not there:** the place in the destination's pixels, as a frag's `this.position` and `this.depth` (it would make the snap `Math.Round` of a position, and needs the destination's size sent with the draw; a vertex behind the camera has no pixel); `this.world` in a vert, which is `Math.Transform(instance.transform, vertex.position)`; a setting that snaps every draw, which was the second way offered; a vert that drops its vertex.
- A draw's values, where the agreed sentence leaves a choice (built 2026-10-07, card 4 of the drawing surface's reshaping, to confirm):
  - **Where it's written: last, after the vert and the frag.** `Draw.Mesh(vertices, indices[, transform][, texture[, filter[, wrap]]...][, vert][, frag][, values])`, `Draw.Instanced(..., instances[, ...][, vert][, frag][, values])`, a target's `Mesh` and `Instanced`, and `Draw.Blit(source[, textures...], destination[, blend], frag[, values])`. After the names, as the owner's example has it, because the values are those names' arguments: an `Instanced` draw's list is before the texture because it's the mesh's (how many, and where), and the values are nothing to a draw that names no vert and no frag. A struct written before the names, or with no name at all, is an error that says where it goes.
  - **Any expression of a struct's type**: a literal, a local, a field, a call's result. Not `default`, and not a component's or a singleton's value.
  - **One struct a draw**, found by its type, as an instance's is: the vert takes it, the frag takes it, or both, each as a read-only parameter of that type, whatever they call it.
  - **It's sent once for the draw**, in the uniform block with what the code reads of singletons, and only the fields the vert and the frag read (each top-level field whole, as a component's). Unread fields can have types the GPU can't use. They count in the 3984 bytes a 2D draw's uniforms hold, or 3968 bytes for a 3D draw.
  - **Draws join as they did**: the same mesh, shader and textures in a row with the same values (the bytes that are sent) are one run, so two draws that differ only in a field nothing reads are one, and other values start another. A Blit is always a draw of its own.
  - **Three sources, told apart by type, and never two of one type.** A frag's read-only struct is what the draw's vert writes, an element of the list an `Instanced` draw is given, or the draw's values; a vert's is one of the last two. A draw whose values are of the type its vert writes, or of the type its instances are, is an error at the draw. A frag or vert that takes a struct none of the three supplies is an error at the draw whose note names all three. So is a draw that gives a struct neither its vert nor its frag takes: the value would go nowhere.
  - **A vert takes any number of read-only structs** now, where it took one (the instances'): which of them a draw supplies is checked at the draw, as a frag's are. The declaration's own error ("a vert takes one instance struct") is gone.
  - **No texture in it.** A `Texture`, a `Grid2<Color>` or a `DepthTexture` field of a draw's values can't be sampled, as an instance's can't: an error that says to keep it in a component or a singleton. A draw's images are its `Texture` arguments (Several textures a draw gives, below).
  - **Not there:** values for a draw with no vert and no frag (nothing would read them); several structs a draw; a value that isn't a struct (`Draw.Blit(..., Blur, float2(1, 0))`), which would bind by position where everything else binds by type.
  - **In the shaders,** a frag's color still starts as white where the GPU's compiler sees it, so the text tidec writes is what it was: the checker is what knows it's written first.
  - `mut` on a vert's struct is an error that names `out`, with the quick fix, and so is `mut out` in either.
- Several textures a draw gives (approved 2026-11-14, the owner: "go with your recommendations", after Mount & Rifle generated a frag a material, wrote frags differing in asset names alone and packed colour, normal and ORM into one sheet; every rule here is Claude's pick, Provisional):
  - **A frag and a vert take as many read-only `Texture` parameters as they like**, where a frag took one ("a frag takes one explicit Texture source, and this names two" is gone). `frag Lit(PartVertex vertex, out Color color, Texture colour, Texture normal, Texture orm, Look look)` is drawn with `target.Mesh(mesh, transform, colour, normal, orm, Lit, look)`.
  - **The draw gives them in order after the mesh's arguments** (a 3D mesh's transform, an `Instanced` draw's list, a skinned mesh's pose), and a blit after its source and before its destination: `Draw.Blit(source, lut, destination[, blend], Grade[, values])`. Every draw form that took one takes several: `Mesh`, `Instanced`, `SkinnedMesh`, a target's, over the CPU's lists or GPU lists (indirect), and listed instancing.
  - **The order is the frag's, then the vert's own.** A vert's and a frag's `Texture` parameter of the same name are the one texture, read with one `[Raw(T)]` role (two roles are an error); a vert's of another name comes after all the frag's, in the vert's order. With no frag, the vert's are the draw's, and the first is also what the pixels are drawn with, as the one texture of such a draw was. Argued against the vert's first, though it's the order the names are written in: a vert that displaces by the frag's height map would put that first, and the frag's signature is the one a material reads like. Argued against binding by position in each stage: a vert's `height` and a frag's `colour` would be the one texture.
  - **A filter and a wrap after a texture are that texture's alone**, for that draw (`colour, normal, Filter.Point, Wrap.Repeat, orm`), as the one texture's were: each `Texture` carries how it's read, and a `Sample` that leaves its filter or wrap out reads it so. A blit takes none, as before.
  - **Each is a texture of the draw's own**, among its 16, with samplers of its own where a `Sample` leaves the filter or wrap to it. A draw that gives fewer or more textures than its frag and vert take is an error naming theirs, in order ("this draw gives 2 textures, and its frag takes 3: 'colour', 'normal' and 'orm'"), and so is a second texture for a draw with no frag that takes none.
  - **Only `Texture`** (a `Grid2<Color>` or `Grid2<float>` is one there): a `DepthTexture`, `TextureArray`, `Cubemap`, `DepthCubemap` or `Texture3D` a frag reads is a field of a component or singleton, or an asset, as before, and a function is handed that whole now (A function samples the textures of a singleton or a component it's handed). Argued against textures in a draw's values struct: they'd bind by field where a draw's other inputs bind by type, a values struct that changes per draw would split runs by its textures as well as its bytes, and the per-texture filter and wrap would need fields of their own; parameters keep a material's images where its frag says them.
  - **A `[Linear]` image goes to a `[Linear] Texture` parameter** (built 2026-11-14, Provisional with Where the mark goes, Linear-light image sampling): a frag's or vert's parameter marked `[Linear]` takes the draw's marked asset or field, or a Color grid, so a material's albedo can be one of the textures a draw gives beside its unmarked normal and ORM maps. A marked image given to an unmarked parameter is the error that says it would lose its mark, and an unmarked one given to a marked parameter is refused, as a role is never added. A `[Linear]` field of a component or singleton the frag takes still works as before.
- Frustum culling (built 2026-10-15; the automatic ordinary-mesh behavior and developer control are agreed; these API and numerical choices are provisional):
  - `Draw.FrustumCulling(enabled) { ... }` and `Draw.SetFrustumCulling(enabled)` control rejection. `SetFrustumCulling()` enables it again. `Draw.Bounds(center, size) { ... }` and `Draw.SetBounds(center, size)` supply a conservative mesh-local box with full size, before the instance transform and destination's `Transform`. `Bounds() { ... }` and `SetBounds()` restore automatic bounds. Every destination starts each frame enabled with automatic bounds. The same methods belong to render targets; 2D draws ignore them.
  - **`Occlusion`** (Provisional, 2026-11-05: Claude's picks under the owner's go-ahead for Hi-Z occlusion; to confirm, each rule here). `Draw.Occlusion(enabled) { ... }` and `Draw.SetOcclusion(enabled)`, with `Draw.SetOcclusion()` putting back what each frame starts with: off. A destination's own, as every setting is (`target.Occlusion`, `target.SetOcclusion`). With it on, an instance of a 3D `Draw.Instanced` over a list that the depth drawn into that destination before it in the frame (since the frame began or its depth was cleared) surely hides isn't drawn: every pixel it could cover holds something nearer, so it would fail the depth test, and the frame's pixels are the same as without it, whatever was drawn before and however things move. It applies where frustum culling does (a list drawn instanced through a shader, bounds known, frustum culling on), and is the GPU's: draws the GPU doesn't cull (the Unity recorder's, those the CPU decides) are drawn whole. Draws with it on don't hide each other: what hides them is what was drawn before the first of a run of them (a run ends at a list drawn without it, one into another destination, or a clear), or before an earlier point after the destination's last clear where its pass had ended for something else (so measuring splits no pass), and nothing where nothing was drawn since that clear. Off by default because measuring the depth costs GPU time (and may split the destination's pass), which pays only where much is hidden. It changes the work drawn, never views, operand evaluation or the match. How it's built: notes/drawing.md, Occlusion culling from a depth pyramid.
  - Geometry bounds are cached per retained mesh version, including primitives, list meshes and assets. A fragment shader alone preserves automatic bounds; any custom vert or skinning requires explicit bounds. The declared box must include every posed/displaced vertex, including any custom clip placement. Negative sizes, NaN/infinite bounds, unknown geometry, nonfinite/projective instance transforms and unknown destination sizes keep the draw. Zero-size boxes are valid. Intersecting/touching boxes stay drawn, with conservative allowance for floating-point rounding and shear.
  - Rejection occurs while recording a draw, using the current destination size and camera. `LODCamera` affects only detail selection. Views and draw operands still run; sampling and palette capture may precede rejection. C hosts supply window size through `tide_draw_screen_size` before recording; a retained list appended elsewhere copies its already filtered draws, without testing them again. To reuse one recorded list across different camera aspects, disable recording-time culling for that list. There is no occlusion test while recording (the GPU's is `Occlusion`, above) and no automatic spatial index.
- One `Draw` (built 2026-10-07; that there's one `Draw` with every method a render target has and nothing else, that the 2D and 3D forms are overloads told apart by their arguments, that the window is the same object a target is, that every setting belongs to the destination it's called on, blend and tint too, that depth and cull are for 3D meshes alone, and that the old spellings are errors with the rename as a quick fix are decided, above; what follows was picked to build it, to confirm):
  - **A mesh's dimension is its vertices'.** A `List<Vertex>`, or of a struct with a `float2 position`, is a 2D mesh's, drawn where its vertices are through the 2D camera; a `List<Vertex3>`, or of a struct with a `float3 position`, is a 3D mesh's, which takes its transform after its indices. A 3D mesh with no transform, and a 2D mesh with one, are errors that say so. An empty list literal, `[]`, says nothing: it's a 2D mesh's, unless a transform follows its indices.
  - **`Draw.SetCamera()` puts both cameras back**, the 2D and the 3D, and `Draw.SetTransform()` both transforms, as a target's always did: with one name for both, nothing says which. One alone goes back by setting it: `Draw.SetCamera(float2(0, 0), 0)` is a pixel a unit again, and `Draw.SetTransform(float4x4.identity)` no 3D transform.
  - **Every `Draw` call selects the window**, as a target's methods select the target: `Draw.Blend` and `Draw.Tint` too, which selected no destination while they were global. That's the one change to the C generated for a game that was only respelled: those two calls (and their `Set` forms) are made on the window's list.
  - **What the window has that a target hasn't** is `Blit`, which names the target it goes into (`target.Blit` is an error that says so), and the members `window` and `list`. A target has everything else of `Draw`'s, and nothing else.
  - **Depth and cull around 2D draws alone change nothing, and are no error** (decided): the setting is recorded and reaches no command. Only 3D meshes have depth or a back.
  - **`Draw2D` and `Draw3D` stay reserved names**, which a game can't declare: that's what lets `Draw2D.Circle(...)` be the error "Draw2D.Circle is 'Draw.Circle' now", with the quick fix on the owner's name, and `Draw2D.list` the same for `Draw.list`.
  - **Editors list every version of an overloaded function** on hover, with each one's doc once: `Draw.SetCamera` shows its four forms.
- The cameras as matrices (built 2026-10-07, card 5 of the reshaping of the drawing surface. That a view reads the matrices of the camera a destination has, the window's and a target's, so a shadow map's frag isn't handed a matrix the game built by hand, is the owner's; the shape, the names and each rule are Claude's picks, not yet confirmed):
  - **Four functions of `Draw`, and so of a render target**, with no arguments, beside the conversions they belong with: `Draw.WorldToClip()`, `Draw.CameraTransform()` and `Draw.CameraProjection()`, each a `float4x4`, for the 3D camera, and `Draw.WorldToScreenMatrix()`, a `float3x3`, for the 2D one. Functions, and not a built-in struct read as a member (`Draw.camera3D`): a target has every function `Draw` has and none of its members, so a function is on both with no rule of its own, and a struct of three matrices would be worked out whole for the one that's read.
  - **They read the destination's camera as it's set when they're called**, in this frame: what a `SetCamera` left, or the block they're in, or the camera each frame starts with. Nothing is recorded for the asking.
  - **`WorldToClip()` describes the world-to-clip mapping**: the camera's transform undone, z turned around, the projection, and for a camera set with a field of view, the fitting to the destination's shape (x divided by its width over its height). Clip space is OpenGL's on every backend: `z / w` from -1 at the near plane to 1 at the far limit, so a depth as a target stores it is `z / w * 0.5 + 0.5`. The fitting is one function the renderer and these share. Automatic 3D placement and `this.clip` preserve the camera origin separately for built-in and invertible affine custom cameras, subtracting it from model columns before local geometry is transformed and projected. CPU matrix/conversion results retain the combined world-space float arithmetic and may round differently. Fragment world coordinates and instance transforms remain world-space; explicit clip outputs and projective custom camera transforms retain their existing mapping. Genuine coincident surfaces and depth-buffer resolution are unchanged.
  - **`CameraTransform()` and `CameraProjection()` are the arguments of `Camera(transform, projection)`**: given back to it, they set the same camera. A camera set that way gives them back bit for bit. One set with a position, a rotation and a field of view gives its position and its rotation, normalized, as a matrix with no scale, and the engine's projection (from 0.3 units on, with no far side), fitted to the destination's shape as `WorldToClip()` is.
  - **`WorldToScreenMatrix()`** does to `(x, y, 1)` what `WorldToScreen(float2)` does: into logical pixels from the top left, y down, so it has the destination's size in it. The identity inside `Screen`. A `float3x3`, as `Draw.Transform` takes one.
  - **A transform is no part of them**, as it's none of the conversions.
  - **A destination with no size** (a target that was disposed) has zeros for `WorldToClip()`, `CameraProjection()` and `WorldToScreenMatrix()`, as the conversions give zeros there. A camera that's singular or not finite is given as it is: it's what the renderer would draw through.
  - **Local code only, as the conversions are**, and not in code the GPU runs: a view works a matrix out and keeps it where its frag reads it.
- One word for the window, and formats by what they store (built 2026-10-07; that the target which follows the window is `RenderTarget.Window()` and `RenderTarget.Window(factor)`, that drawing in the screen's pixels is `Draw.Screen() { ... }` and `Draw.SetScreen()`, that `Screen` is the window's measurements alone (`Screen.width`, `Screen.height`, `Screen.Flip`), that `Draw.window` stays, that depth alone is `Format.Depth`, and that formats are named by what they store are decided; what follows was picked to build it, to confirm):
  - **The formats are `Format.Rgba8`, `Format.Depth`, `Format.Rgba16f`, `Format.R8`, `Format.Rg8`, `Format.R16f`, `Format.Rg16f`, `Format.R32f`, `Format.Rgba32f` and `Format.R32i`.** A color format's name is its channels, the bits of each, and `f` where they're floats: four channels of a byte each, and four floats of 16 bits. The numeric formats added 2026-11-14 follow the same names, with `i` for a signed integer. `Depth` says no bits: the preferred storage is reversed 32-bit float with 8-bit stencil, with the legacy forward 24-bit path where needed (Depth precision below); public reads remain forward values.
  - **No `Format.Color` beside `Format.Rgba8`.** One name for one thing: an alias would be a second spelling of the same number in every example, and the question of which to write. What it would have been friendlier for is the first target someone makes, and that one says no format at all: `RenderTarget(width, height)` holds one `Rgba8` image.
  - **The members' numbers are what they were** (`Rgba8` 0, `Depth` 1, `Rgba16f` 2): they're in a target's id, so a target made by a build from before is the same format to a build from after.
  - **The old spellings are errors that name the new one**, with the rename as the editors' quick fix: `RenderTarget.Screen`, and `Format.Color`, `Format.DepthOnly` and `Format.Float`; and `Draw.Pixels` and `Draw.SetPixels` (a target's own too), the names this card gave the screen's pixel space for an afternoon. They went back to `Screen` and `SetScreen` the same day (the owner having left the review's follow-ups to Claude): with the target named `Window`, `Screen` means one thing, the screen's pixel space, as `Screen.width` and `Screen.Flip` do; and `Pixels` sat beside a frag's `Pixel` parameter as two names that read as one.
  - **A target's own pixel space is `target.Screen()` and `target.SetScreen()`**, as every setting of `Draw`'s is a target's method: the target's logical pixels, from its top left.
  - **In C the formats are `TIDE_TARGET_RGBA8`, `TIDE_TARGET_DEPTH` and `TIDE_TARGET_RGBA16F`** (`tide/draw.h`), renamed with them. The functions keep their names (`tide_render_target_window`, `tide_render_target_screen` for a part of it, `tide_draw_set_screen`), so a game that was only respelled generates the C it did, but for the enum's members in a game that names `Format`.
- Draw settings, where the decided rules above leave a choice (to confirm):
  - **Where each lives.** Every setting belongs to the destination it's called on (decided, with one `Draw`): `Draw.Blend`, `Draw.Tint`, `Draw.Transform`, `Draw.Clip`, `Draw.Camera`, `Draw.Screen`, `Draw.Depth`, `Draw.Cull` and `Draw.Stencil` are the window's, and a render target has each as a method, in both forms (`target.Blend(Blend.Add) { ... }`, `target.Clip(rect) { ... }`, `target.SetCamera(...)`), its own for the frame. So a blend or a tint set for the window doesn't reach a target's draws, nor a target's the window's, as a clip or a transform never did. The 2D and 3D forms are told apart by their arguments, on the window as on a target.
  - **Putting a `Set` back.** A `Set` with no arguments sets what each frame starts with: `Draw.SetBlend()` is `Blend.Alpha`, `Draw.SetTint()` no tint, `Draw.SetStencil()` no stencil test, with nothing stored, `Draw.SetDepth()` is `Depth.ReadWrite`, `Draw.SetCull()` is `Cull.Back`, `Draw.SetClip()` no clip, `Draw.SetTransform()` no transform, 2D or 3D, and `Draw.SetCamera()` both first cameras: the 2D one with the origin at the middle of the screen, a world unit a pixel (which is also how to leave the screen's pixels), and the first 3D one. A target's are the same, each the target's own. `Draw.NoClip()` is gone: it's `Draw.SetClip()`.
  - **Nesting.** A block's setting is inside the one it found, where that means something: a clip in a clip is what of its rect is inside the outer one, a tint multiplies the tint there is, and a transform is inside the transform there is. A blend, a depth, a cull, a stencil, a camera and the screen have nothing to be inside, and replace what's there. A `Set` sets outright, in a block too: `Draw.SetClip(rect)` inside a `Draw.Clip` block isn't inside its clip, and the block still puts back what it found when it ends.
  - **`Blend`** is a built-in enum: `Alpha`, `Add`, `Multiply`, `Replace`. A game can't declare the name outside a namespace. In each, a color's alpha is how much of it there is: `Add` adds the color times its alpha, as light adds, and `Multiply` multiplies what's there by the color, by less as its alpha goes to 0, so what's clear (a shape's smooth edge, the gaps in text) changes nothing. `Replace` writes the color and its alpha as they are. In a render target, `Add` also adds its alpha to the one there, and `Multiply` leaves that one alone.
  - **`Tint`** takes a `Color`. It multiplies shapes' and text's colors, a mesh's corners', a 3D mesh's, and what a `frag` wrote, alpha included.
  - **`Depth`** (to confirm: the enum's name and its members', and each rule here; that it's a draw setting for 3D meshes alone is decided). `Draw.Depth(mode) { ... }` and `Draw.SetDepth(mode);` say what the 3D meshes drawn inside, or after, do with depth. `Depth` is a built-in enum with five members, and a game can't declare the name outside a namespace:
    - `Depth.ReadWrite`: a mesh is hidden behind what's nearer, and hides what's drawn behind it later, whatever the order. It's what each frame starts with, what `Draw.SetDepth()` puts back, and what 3D meshes always did.
    - `Depth.Read`: a mesh is hidden behind what's nearer and already drawn, and writes no depth, so it hides nothing: for what's see-through (glass, smoke, a shadow or a mark lying on a surface). Meshes drawn so go over each other in the order they're drawn, as 2D calls do, and are drawn after what's solid.
    - `Depth.None`: a mesh neither reads nor writes depth: it draws over whatever is there, and hides nothing drawn after it.
    - `Depth.Only` (built 2026-11-06, asked for by a game whose cut-out foliage was lit where it was hidden; the names and each rule of the two are Claude's picks, to confirm): read and written as `Depth.ReadWrite` is, stencil too, and no color in any of the destination's images. Its frag still runs, so `this.Discard()`, `this.Cutout` and `this.Coverage` cut its depth as they would anything's: a depth pre-pass.
    - `Depth.Equal`: drawn only at the samples whose depth is exactly its own, writing none: lit after a pre-pass, each sample the pre-pass left drawn once (each time it's drawn), through a frag that needn't discard, and anything the pre-pass didn't draw hidden. With samples, it's each sample's depth, so the lit draw is drawn at the samples a cut-out's edge covered in the pre-pass.
    - **Two draws of a mesh land on the same depth** wherever they're drawn the same way (the same mesh, transforms, camera and vert, or none), through any two frags and the engine's own mesh drawing: every 3D shader's position is invariant (WGSL's `@invariant`, SPIR-V's `Invariant`, HLSL's `precise`). A vert that moves corners differently in the two, or another level of detail, isn't the same depth.
    - Draws under `Depth.Equal` aren't ordered as see-through ones are: they're GPU-culled and gathered as solid ones are.
    - There's no mode that writes depth without reading it.
    - **It's a destination's own**, as every setting is: `Draw.Depth` and `Draw.SetDepth` are the window's, and a render target has `target.Depth(mode) { ... }` and `target.SetDepth(mode);` for its meshes, each target's its own for the frame. So `Draw.Depth(Depth.Read) { target.Mesh(...); }` leaves the target's mesh as the target has it, and `target.SetDepth()` puts the target's back. Each target has its own depth, as before, which a mesh drawn into it reads and writes as its setting says.
    - **It's for 3D meshes of every kind**: `Draw.Mesh`, the primitives, a mesh through a `frag` or a `vert` whose vertex has a `float3 position`, and `Draw.Instanced`, and a target's.
    - **The 2D calls have no depth**, whatever is set: shapes, text, 2D meshes, and 2D meshes through a `frag` neither read nor write it, and draw over what's there in order. Nothing gives a 2D call a depth; that would come with layers (see Open). `Draw.Depth` around 2D draws alone changes nothing, and isn't an error.
    - **`Draw.Clear`, and a target's `Clear`,** clear depth whatever is set, within the clip. **`Draw.Blit`** leaves depth as it is, whatever is set.
    - A block's depth replaces the one it found, and puts it back when it ends.
    - Instances drawn in a row with the same depth are still one draw, with the setting around each or around them all; another depth is another draw.
    - A `Depth` is a value like any enum's: a field, a local, a parameter. One made of a number that's none of its members' (`Depth(40)`) is `Depth.ReadWrite`.
    - In generated C the enum is `Depth`, with `Depth_ReadWrite`, `Depth_Read`, `Depth_None`, `Depth_Only` and `Depth_Equal`, only in a game whose code names it: the others' headers, and so their layout's hash, are what they were.
  - **`Cull`** (to confirm: which side is the front, the enum's name and its members', and each rule here; that it's a setting for 3D meshes alone whose default leaves the back out, and that nothing in 2D culls, are decided). `Draw.Cull(side) { ... }` and `Draw.SetCull(side);` say which side of the triangles of the 3D meshes drawn inside, or after, isn't drawn. `Cull` is a built-in enum with three members, and a game can't declare the name outside a namespace:
    - `Cull.Back`: a triangle seen from the back isn't drawn. It's what each frame starts with, and what `Draw.SetCull()` puts back.
    - `Cull.Front`: a triangle seen from the front isn't: for the inside of a shell.
    - `Cull.None`: both sides are drawn: for what's flat, or see-through.
    - **The front of a triangle is the side its corners go clockwise on,** in the order its indices list them, as Unity's. Seen by a camera that looks along `+z`, with `+x` to its right and `+y` up, a triangle whose corners go clockwise on the screen shows its front.
    - **It's the mesh's own, whatever it's drawn through.** A transform that mirrors a mesh (its determinant is under 0) turns its triangles round on the screen, and its front is still its front: the mesh's or the instance's own transform, `Draw.Transform`'s, and a camera that shows the world mirrored. A camera given as matrices is one when its `transform` mirrors, or its `projection` isn't the way round OpenGL's are (the identity's looks back along `z`), and not both.
    - Instances that are mirrored and ones that aren't, drawn in a row, are draws apart: with `Cull.None` they're one. Instances drawn in a row with the same cull are still one draw, with the setting around each or around them all.
    - **A transform that flattens a mesh** (its determinant is 0) leaves it no front: the triangles of both of its sides land on one plane, wound opposite ways, and each is still drawn or not by which way it's wound there. A game draws such a mesh inside `Cull.None`.
    - **A `vert` that turns triangles round itself** (it mirrors its mesh, or turns it inside out) is the game's to draw for: the engine goes by the transforms it's given. Such a mesh is drawn inside `Cull.Front`.
    - **It's a destination's own**, as depth is: `Draw.Cull` and `Draw.SetCull` are the window's, and a render target has `target.Cull(side) { ... }` and `target.SetCull(side);`. A triangle's front is the same side in a target as in the window.
    - **It's for 3D meshes of every kind**: `Draw.Mesh`, the primitives, a mesh through a `frag` or a `vert` whose vertex has a `float3 position`, and `Draw.Instanced`, and a target's.
    - **The primitives are solid**: a cube's, a sphere's and a cylinder's fronts are outside, and a plane's is its top, its local `+y`. A plane seen from below isn't drawn.
    - **Nothing in 2D has a back**, whatever is set: shapes, text, 2D meshes, 2D meshes through a `frag`, `Draw.Clear` and `Draw.Blit` draw whichever way their triangles are wound. `Draw.Cull` around 2D draws alone changes nothing, and isn't an error.
    - A `Cull` is a value like any enum's. One made of a number that's none of the three (`Cull(40)`) is `Cull.Back`.
    - In generated C the enum is `Cull`, with `Cull_Back`, `Cull_Front` and `Cull_None`, only in a game whose code names it, as `Depth` is.
  - **Stencil** (built 2026-10-07; to confirm: how it's written, the two enums' names and their members', whose it is, and each rule here. That it's there as on a GPU, that it's a draw setting with both forms, and that it has none of a GPU's other stencil state are decided). `Draw.Stencil(test, value) { ... }`, `Draw.Stencil(test, value, operation) { ... }` and `Draw.SetStencil(...)` with the same arguments say what the draws inside, or after, do with stencil:
    - **`StencilTest`** is a built-in enum of the test a draw passes to be drawn at a pixel: `Always` (no test: what each frame starts with), `Never`, `Less`, `Equal`, `LessEqual`, `Greater`, `NotEqual`, `GreaterEqual`. **The draw's `value` is on the left and the stored number on the right,** as a GPU has it and as Unity's `Comp` does: `StencilTest.Less` draws where `value` is less than the stored number.
    - **`StencilOp`** is a built-in enum of what becomes of the stored number at each pixel the draw is drawn at: `Keep` (what a call that names none has), `Replace` (the draw's `value`), `Increment` (one more, staying at 255), `Decrement` (one less, staying at 0), `Zero` and `Invert` (255 less it: each of its 8 bits the other way). The two that count don't wrap round; a GPU's wrapping ones are left out.
    - A game can't declare either name outside a namespace.
    - **`value` is an `int`,** any expression: under 0 it's 0, and over 255 it's 255. The test and the operation are values like any enum's: a field, `inside ? StencilTest.Equal : StencilTest.NotEqual`. One made of a number that's no member's is its first (`Always`, `Keep`). The arguments take names (`test:`, `value:`, `operation:`).
    - **It's a destination's own,** as every setting is: `Draw.Stencil` and `Draw.SetStencil` are the window's, and a render target has `target.Stencil(...) { ... }` and `target.SetStencil(...)`. `Draw.Stencil(...) { target.Rect(...); }` leaves the target's rect as the target has it. Shapes, text, 2D meshes and 3D meshes all take it.
    - **What each frame starts with:** no test, and nothing stored (`StencilTest.Always` with `StencilOp.Keep`), which is what `Draw.SetStencil()` puts back. The window's stored numbers are all 0 as a frame starts. A render target keeps its own from frame to frame, as it keeps its color and its depth, and a new one's are 0.
    - **A draw is drawn, and stores, at the pixels it touches, whatever its color.** A clear color (`Color.clear`) stores and leaves the colors there as they are, under every blend but `Blend.Replace`: that's how a mask is laid down with nothing painted, as there's no setting for whether a draw writes color. What a draw touches: all of a rect, a circle and a smooth shape out to the pixels their edges cover any part of, text where its glyphs are and not the rest of their boxes, all of a mesh's triangles whatever its texture's or its corners' alpha, and for a mesh through a frag, the pixels the frag doesn't discard.
    - **Stencil has no part pixels:** a pixel is in a mask or isn't. So what's drawn where a mask is has a stepped edge where the mask's is round. Where a draw only tests (`StencilOp.Keep`), its own edges are as smooth as ever.
    - **Where a draw isn't drawn, nothing is stored:** where its test fails, and for a 3D mesh, where it's hidden behind what's nearer.
    - **It's for everything that draws:** shapes, text, 2D meshes, 3D meshes and the primitives, with a frag or a vert or without, and `Instanced`.
    - **`Draw.Clear`, and a target's `Clear`,** set the stored numbers back to 0, within the clip, whatever is set, and nothing tests them: a clear under `StencilTest.Never` still clears. **`Draw.Blit`** neither tests nor stores, whatever is set.
    - A block's stencil replaces the one it found, and puts it back when it ends.
    - Draws in a row under the same stencil are still one draw, with the setting around each or around them all; another stencil is another draw. A test and a number nothing reads are no stencil at all: `Draw.Stencil(StencilTest.Always, 9)` is none, and costs nothing.
    - **A target of depth alone has stencil too.** What stores it is drawn there, shapes, text and 2D meshes among it, though their colors go nowhere; what only tests it and writes no depth still leaves nothing.
    - **The same pixels on every backend.**
    - In generated C the enums are `StencilTest` and `StencilOp`, with `StencilTest_Always`, `StencilOp_Keep` and the rest, only in a game whose code names them, as `Depth` is: the others' headers, and so their layout's hash, are what they were.
    - Not there: reading a pixel's stencil in a frag or back into Tide; clearing stencil alone (a draw under `StencilOp.Zero` does); the counting operations that wrap; and the GPU state that's decided against (above).
  - **`Wrap`** (to confirm: the enum's name and its members', and each rule here; that how `uv` wraps is chosen where a texture is sampled, as the filter is, is decided). `Wrap` is a built-in enum of what a `uv` past 0 and 1 reads, and a game can't declare the name outside a namespace, for a type or for a function:
    - `Wrap.Clamp`: the cells at the texture's edge. It's what a draw or a `Sample` that says no wrap has, and what every one did.
    - `Wrap.Repeat`: the texture again, so 1.25 reads what 0.25 does, and -0.25 what 0.75 does: tiles, and what scrolls.
    - `Wrap.Mirror`: the texture again, the other way round each time, so 1.25 reads what 0.75 does and 2.25 what 0.25 does: no seam where its edges don't match.
    - **It's an argument after the filter, wherever the filter is one**: `Draw.Mesh(vertices, indices, texture, Filter.Point, Wrap.Repeat)`, `Draw.Mesh(vertices, indices, transform, texture, filter, wrap)`, `Draw.Instanced(vertices, indices, instances, texture, filter, wrap)`, a render target's `Mesh` and `Instanced`, and in a frag or a vert `source.Sample(uv, Filter.Point, Wrap.Repeat)`.
    - **A wrap is written with its filter**: what a call leaves out is at its end, so `Draw.Mesh(vertices, indices, texture, Wrap.Repeat)` and `Sample(uv, Wrap.Repeat)` are errors that say to write the filter before it, and that a texture which only wraps another way says so where it's declared (`[Wrap(Wrap.Repeat)]`). `Sample` takes its arguments by name too (`uv:`, `filter:`, `wrap:`), with none left out before one that's given.
    - **One wrap for both axes.** A second is an error.
    - **In a mesh draw it's a value, as the filter is**: a field, a local, `tiled ? Wrap.Repeat : Wrap.Clamp`. One made of a number that's none of the three (`Wrap(7)`) is `Wrap.Clamp`. **In `Sample` it's written there, as the filter is** (`Wrap.Repeat`, never a variable): the GPU is told how a texture is read before any pixel runs.
    - **A draw's filter and wrap are its texture's for that draw**, whichever way the mesh is drawn: the engine's own vertices, a vertex struct of the game's with no frag, and a frag or a vert that takes the texture as its `Texture` parameter, whose `Sample`s that say nothing then read it so (until 2026-10-07 a draw through a frag took neither, an error).
    - **A draw reads 16 textures and has 16 samplers** (Provisional, 2026-11-05: needs the owner's confirmation, as it changes what counts). Each texture a frag or a vert reads is one of the 16 however many ways it's read: one image on the GPU. Each way textures are read is a sampler: a filter and a wrap, a depth read as a number or compared, a cube's filter. Textures every draw reads the same way, as the code or their declaration says, share one sampler, and the same way twice is one. A `Texture` parameter or field whose `Sample` leaves its filter or its wrap to it has a sampler of its own for that way, as the texture says how at each draw: so a `Sample` that says nothing and one that says the default are two samplers there. (16 since 2026-11-05, the owner's "not cap ourselves to arbitrary limits": what every backend takes in a stage, images and samplers alike. Until the same day each way a texture was read counted as a texture of its own, one image bound again for each; 12 before that, which was one layout's descriptors.)
    - **It's for every texture**: a `Grid2<Color>`, an asset's, a `Texture`, a render target's color, of any size (not only powers of two). A grid with no size still samples white.
    - **Blended** (`Filter.Bilinear`), a cell at the texture's edge is blended with what the wrap says is past it: with `Wrap.Repeat` the cell at the opposite edge, and with `Wrap.Clamp` and `Wrap.Mirror` itself.
    - **The same pixels on every backend.**
    - Meshes drawn in a row with the same texture, filter and wrap are still one draw; another wrap is another draw.
    - Text and shapes sample nothing a game gives them, and have no wrap. `Draw.Blit` takes none: its frag samples its source as the source says, and as the frag says where it does.
    - In generated C the enum is `Wrap`, with `Wrap_Clamp`, `Wrap_Repeat` and `Wrap_Mirror`, only in a game whose code names it: the others' headers, and so their layout's hash, are what they were.
    - Not there: a wrap for each axis, a color for what's past the edges (a border), and a texture that mirrors once and then clamps.
  - **Declared sampling** (to confirm: each rule here; that a texture's declaration can say its filter and its wrap, with attributes, for a `Texture` asset and a `Grid2<Color>` asset, is decided). `[Filter(Filter.Point)]` and `[Wrap(Wrap.Repeat)]`, each alone or both in one pair of brackets, say how the texture made there is sampled wherever a draw or a `Sample` leaves that out:
    - **Where they go**: before an asset that's a `Texture` or a `Grid2<Color>`, alone or a glob's list or map of them, whose every image they're for; before a field of a component or a singleton that's a `Grid2<Color>` or a `Grid2<float>` (not asked for: a grid that's drawn is a texture declared in a field, and it would have been the one texture that couldn't say); and before a `RenderTarget` field, for the target's color images, `target.color` and `target.colors[i]` (not asked for either, by the same reasoning: it's the third place a texture is made). Anywhere else is an error that says where they go: another declaration, an asset that's text or bytes, a field that's none of those, the same one twice.
    - **Not on a `Texture` field**, which is an error of its own: such a field holds whichever texture it's given, which says how it's sampled itself.
    - **Each takes one member of its enum, written there**: `[Filter(Filter.Point)]`, `[Wrap(Wrap.Mirror)]`. Not a variable, as it's a declaration's.
    - **A call that says still decides, each of the two apart**: `Draw.Mesh(vertices, indices, tiles, Filter.Bilinear)` is blended, with the declaration's wrap. Without an attribute a texture is sampled as it always was: `Filter.Bilinear`, `Wrap.Clamp`.
    - **It's what the `Texture` made there is born with, and the value carries it** (decided, above; until 2026-10-07 it was the declaration's say only where the declaration was named, and a `Texture` in a field had none). So it holds by the declaration's name (`tiles`), as one of its list or map (`frames[2]`, `icons["coin"]`), as the variable of a `foreach` over it, as a grid's field (`art.paint`) and as a target's color (`art.small.color`), and just as much in a `Texture` field or local given one of those, a function's `Texture` parameter, and what a function returns: `art.kept = tiles;` and then `Draw.Mesh(vertices, indices, art.kept)` draws as `Draw.Mesh(vertices, indices, tiles)` does. In a mesh draw's texture, in 2D, in 3D and instanced, into the window and into a target; in a frag's or vert's `Sample`; and for the source a draw or a `Draw.Blit` gives a frag's `Texture` parameter.
    - **`[Filter(Filter.Bilinear)]` and `[Wrap(Wrap.Clamp)]` say what a texture with neither has**: there's no "said to be blended" that a later default could differ from.
    - Mipmaps are said the same way since (`Filter.Trilinear`: see Mipmaps, below), and anisotropy (`Filter.Anisotropic`: see Anisotropic filtering, below).
  - **Textures** (built 2026-10-07; that `Texture` is the one name, that grids of colors and of floats convert, that the value carries its sampling and that the attributes are what it's born with are decided, above; each rule here was picked to build it, to confirm):
    - **Where a grid converts**: wherever a value of one type goes where another is wanted, as an `int` goes where a `float` is: a draw's texture (`Mesh`, `Instanced`, a target's own), a `Draw.Blit`'s source, an assignment to a `Texture` field or local, a `Texture` parameter's argument, a function's `return`. A `Grid2<Color>` and a `Grid2<float>` go wherever a `Texture` does; a grid of other numbers goes only where the typed role of its numbers takes it (below); any other grid where a texture goes is an error that says which are. It's local code's alone with no rule of its own, as only local code has anywhere a `Texture` goes.
    - **Grids of other numbers** (built 2026-11-14; Provisional, Claude, after an audit found float2, float4 and int grids could be no texture even through the typed roles that read those numbers): a `Grid2<float2>` is a `[Raw(float2)] Texture`, a `Grid2<float4>` a `[Raw(float4)] Texture`, and a `Grid2<int>` or a `Grid2<byte>` a `[Raw(int)] Texture`: a field's value of that role, the argument of a GPU helper's parameter of that role, and the source a draw or a blit gives a frag whose `Texture` has it. A frag or vert samples one by its name too, as those numbers (`Sample` alone, as a `Grid2<float>`'s by name; a field of its role takes `SampleLevel` and `SampleGrad`). Anywhere else (a plain `Texture` field, local, parameter or return, a draw with no frag) it's an error naming the role, since a plain `Texture` would read it as colors; a grid in a field of another role is an error naming the role that reads it. On the GPU, float2 and float4 cells are 16-bit floats (Rg16f, Rgba16f), which every backend blends and makes smaller images of, as a `Grid2<float>`'s R16f is; int and byte cells are one 32-bit int each (R32i), read at the nearest cell, a byte as its 0 to 255. Only changed chunks are copied and only changed cells sent, as for grids of colors. Weighed: exact 32-bit floats (Rg32f does not exist among Tide's formats, and 32-bit floats blend only with an optional WebGPU feature, so a blended read would differ by device or be refused); four floats of a `Grid2<float2>` in an Rgba16f image (twice the memory for no gain, where Rg16f is in core WebGPU, Vulkan's required formats and Unity); a byte grid as an R8 image read through `[Raw(float)]` as value/255 (a quarter of the memory and blendable, but not the number code reads, and R8Uint would need an unsigned image role no `[Raw(T)]` has). A Texture value says which cells its grid has (`TIDE_TEXTURE_CELLS_*` in the reference's version bits), as a grid's shape alone doesn't tell a float4 cell from a Color or an int from a float. `Grid3`s of numbers are not textures (a `Grid3<Color>` and a `Grid3<float>` are a `TextureArray` or a `Texture3D`).
    - **The texture is the grid, not a copy**: a small value that names where the grid is, as the grid's own draws always did underneath, so it draws what the grid holds when it's drawn, and it's how a grid's pixels reach a function, which can't take the grid. Nothing ties their lifetimes: a `Texture` kept past its grid (its entity destroyed, the match another) names whatever is there, and draws nothing or anything. It never reads outside the world's own memory: everything the draw list reads through one is checked to be within the heap's pages first, as a list's index is checked where it's used. No error says a texture outlived its grid.
    - **A `Grid2<float>` reads as `(r, 0, 0, 1)`**: the cell's number as red, green and blue 0, alpha 1. That's what every GPU gives for a texture of one channel with nothing asked, so a frag's text doesn't depend on what kind of texture it's given; `(r, r, r, 1)` would need a swizzle on the texture, which WebGL 2 and WebGPU have none of, or a shader for each kind. The numbers aren't clamped to 0 to 1. Drawn with no frag it's the vertex's color times that, so red.
    - **On the GPU it's a float of 16 bits a cell** (IEEE 754's half): the one float format every backend samples blended between pixels with nothing asked of the device. One of 32 bits is only blended with a feature on WebGPU (`float32-filterable`) that a device may lack, and on WebGPU a pipeline's layout says whether a texture can be blended, so a frag's pipeline would depend on the texture it was given. So no device does anything else, at the cost of precision: about three digits, up to 65504 either way; a bigger number is that, an infinity too, and NaN is 0, so no filter makes a NaN of a neighbour. The grid keeps its 32 bits for code.
    - **A grid is no texture past 16384 cells a side**, which is more than a GPU's largest texture on most devices. (It also keeps a `Texture` that outlived its grid from asking for memory by a size that's no grid's.)
    - **Sampling is two things, the filter and the wrap, each the texture's own until a draw or a `Sample` says it.** A texture with nothing said is blended and clamped. There's nothing in Tide that changes a `Texture` value's sampling but giving it to a draw with a filter and a wrap.
    - **In a frag or a vert**, a `Sample` of a grid's field or of an asset by its name that leaves its filter or its wrap out has its declaration's, known as the game is compiled. One of the frag's own `Texture` parameter, or of a `Texture` field, has whatever texture it's given, which isn't: the engine says it with each draw, so the same frag draws one texture repeated and the next clamped, as two runs of one shader. A shader's text, and the pipeline made of it, are the same whatever its textures say.
    - **A draw gives a grid to a frag's `Texture` parameter**, as it gives any texture. A draw that gives a texture to a frag with no `Texture` parameter is the error it was for a `Texture`, for a grid too (it used to say the frag samples the grids it takes itself).
    - **One textured `Mesh` for each dimension**, where there were two (a grid's and a `Texture`'s). Editors show its filter and its wrap as `Filter filter = the texture's`.
    - **Hot reloading keeps a `Texture` of the pack's or of a grid's**, with its sampling, as it keeps one of a target's color. (One of the pack's in a field was dropped by a reload before.) After a reload that changed the game's data layout, a grid's texture may name another place, and draws as one that outlived its grid does.
    - In generated C a game with no texture is what it was. One with textures differs in its `.c` alone, never its header, so no game's layout hash moved: a textured draw converts its grid at the argument and calls the one function, a shader's function takes one `Texture` and works its run's sampling out of what it's given, and a reload carries sampling over.
    - **`texture.size`** is a read-only `int2`: base-level width and height in physical pixels. Local CPU code and shaders read the same metadata, without copying pixels, uploading an image or consuming a shader texture binding. Assets follow the currently loaded pack; grids use their current bounded image dimensions; missing, unloaded, invalid or disposed images give `(0, 0)`. A render-target alias follows resize and uses the frame host's current display scale, window size and device limit. A custom C host supplies `tide_draw_list.target_pixels` before `tide_frame`; without a resolver target dimensions are `(0, 0)`. A shader reads the same named textures and helper parameters that `Sample` accepts. CPU queries retain source order beside resize/dispose and stay on the frame thread: explicit parallel steps use a size read before the loop, and automatic grid loops with metadata reads remain ordered. Texture metadata stays machine-local.
    - Not there: a `Texture`'s pixels; a way to make a `Texture` sampled otherwise outside a draw; grids of cells other than colors and numbers (bools, longs, structs) as textures, and `Grid3`s of float2s, float4s, ints and bytes (a `Grid3<Color>` or `Grid3<float>` converts to a `TextureArray` or a `Texture3D`, below); a `Grid2<float>` asset; a float of 32 bits where a device can blend one.
  - **Mipmaps** (built 2026-10-07, card 6 of the reshaping; that the drawing side gets mipmaps, and that the card designs how a mipmapped sample is written where code samples in a branch, are agreed; every rule here was picked to build it, to confirm):
    - **A filter, `Filter.Trilinear`, the enum's third member**: the texture is blended between its pixels and between its smaller images (each half the last one's size, down to one pixel), by how much smaller than itself it's drawn. Drawn its own size or bigger it's `Filter.Bilinear`. It's said wherever a filter is: a mesh draw's argument, a `Sample`'s, a declaration's `[Filter(Filter.Trilinear)]`, and what a `Texture` carries from there.
    - **`Filter.Bilinear` is as it was**, where Unity's reads a texture's mipmaps when it has them. Argued both ways: mipmapped by default is what most 3D wants, and one word less. But here a texture has no import setting that says whether it has mipmaps: the filter is the only place it's said, so "Bilinear reads them when they're there" would mean every texture has them, which is a third more GPU memory for each, levels made again for every grid a game repaints (Sand's, Sumo's floor), and other pixels than today's for everything drawn smaller than it is, in every game and every pinned picture. A new member moves no pixel and costs nothing where it isn't named.
    - **Nothing declares a texture's mipmaps**: an uncompressed texture's smaller images are made the first time a draw reads it with `Filter.Trilinear`, and again when its pixels changed since (a grid or C's pixels by their version, a pack's image never, a render target's color when a pass has drawn into the target since). An uncompressed texture no draw reads so has none. So they're a third more GPU memory for the textures read so, and the work of making them: OpenGL's `glGenerateMipmap`, and on WebGPU, which has none, a pass for each level that draws it from the one before. Automatically compressed assets instead upload a complete build-time mip chain, even when initially read with Point or Bilinear; those filters continue to read only the base level.
    - **A pixel of a smaller image is the mean of the four it's made of**, which is exact for sizes that halve evenly. An image whose side is odd loses its last row or column a level, as GPUs' own generation does.
    - **In a frag, the GPU picks the level from how fast the `uv` changes from one pixel to the next, and tidec asks that as the frag starts.** A GPU only answers that outside branches and loops (what it says inside one is undefined in GLSL, and an error in WGSL), and Tide's code samples anywhere. Three ways were weighed:
      - *Let the GPU pick where the Sample is, and only where that's allowed* (`texture()`, `textureSample`), falling back to the texture's own pixels elsewhere. It costs nothing, but tidec would need the shader languages' own analysis of which control flow counts, a Sample would read differently for being moved into an `if`, and a mistake there is an error from a shader compiler, which nobody is to see.
      - *Work the level out by hand as the frag starts* (`textureLod` with a level computed from the uv's derivatives and the texture's size). It needs the texture's size in the shader and gives up what a GPU does with the two derivatives apart.
      - *Ask for the derivatives as the frag starts, and hand them to the read* (`textureGrad`, `textureSampleGrad`), which is allowed anywhere and is what the GPU would have used. **Picked.** For each such Sample the frag's function begins with the uv worked out a first time, and its `dFdx` and `dFdy`; the Sample, wherever it is, reads with those. It costs working that uv out twice (once as the frag starts, on pixels a branch would have skipped too) and two derivatives a Sample.
    - **So the `uv` of a Trilinear Sample has to be one the frag can work out as it starts**: made of the frag's parameters, the pixel's fields through `this`, constants, `Math`, constructors, operators, functions and methods of the game's that take everything by value, a texture read with another filter, and locals declared with `var` that are never assigned again and are made of the same. One made of a `mut` local or a loop's counter isn't. Where the Sample's filter is known to be Trilinear (written there, or its grid's or asset's declaration's), that's an error at the `uv`, whose note says what it can be made of and that `Filter.Bilinear` there is the other way out. Where the filter is the texture's to say (a frag's `Texture` parameter, a `Texture` field), it can't be an error, as the texture is only known when the draw runs: the Sample reads the texture's own pixels, as `Filter.Bilinear`, and tidec warns there, in a game that names `Filter.Trilinear` at all (2026-10-07, after the review: a downgrade nothing says comes back as a shimmer nobody can place). The note says to make the uv one the frag can work out, or to write `Filter.Bilinear` at the Sample, which is what's read anyway.
    - **A vert reads the texture's own pixels**, whatever the filter: it has no pixels to compare. It's no error, as a Texture that says Trilinear is given to verts too.
    - **A mesh with no frag** (the engine's own shader, or the one tidec writes for a vert alone) lets the GPU pick, as its one read is before any branch.
    - **How a texture is read is still no part of a shader's text, with one exception**: whether a Sample *can* read between smaller images is, as it's written with the derivatives then. A Sample that says Trilinear is; one that says another filter isn't; and one that leaves it to the Texture it's given is in a game whose code names `Filter.Trilinear` anywhere, and isn't in a game that never does. So a game that names no new filter has the shaders, the generated C and the header it had, byte for byte (the enum's third member is in generated C only for a game that names it), and one frag still draws a texture that says Trilinear and one that says Point with one shader, in two runs.
    - **A `Filter` made of the number 2** is `Filter.Trilinear` for a mesh draw. In a game that never names the member, a frag's Sample that takes its filter from such a Texture reads its own pixels.
    - **A `Grid2<float>`** has smaller images on every device (they're made by drawing into floats, which every backend does).
    - **A target's color** is read between its smaller images as any texture, made of what was last drawn into it: a blur can read a big target small in one step. A target's depth has none.
    - In C, `tide_filter` has `TIDE_FILTER_TRILINEAR`, a texture reference's sampling a bit for it, and a shader run's `sampling` a bit a texture (`TIDE_SAMPLING_MIPS`).
  - **Anisotropic filtering** (built 2026-11-10; the owner asked for the filter, wherever the others are, on every backend, at a fixed level unless there's a reason for a parameter, and falling back without complaint; the name, the level and each rule here were picked to build it, to confirm):
    - **A filter, `Filter.Anisotropic`, the enum's fourth member**: `Filter.Trilinear`, and where a pixel covers more of the texture one way than the other (a surface seen at a shallow angle), several reads along the longer way with the smaller image picked by the shorter. Where a pixel covers as much each way it's `Filter.Trilinear`'s pixels. It's said wherever a filter is: a mesh draw's argument, a `Sample`'s (a `Texture`'s, a grid's, a `TextureArray`'s, a `Cubemap`'s), a `SampleGrad`'s, a declaration's `[Filter(Filter.Anisotropic)]`, and what a `Texture` carries from there.
    - **One level, 8, and no parameter**: the most reads along what a pixel covers; a device that takes fewer makes fewer, and one that takes none reads `Filter.Trilinear`, with no error, warning or way to ask. 8 and not 16 by measurement on the game it was asked for (ground of scanned photographs at 5 to 15 degrees, 1920 by 1080, an RTX 4080 SUPER, eleven textures changed): 8 has 99.9% of the detail 16 adds over Trilinear (edge energy of the ground 26.3 Trilinear, 32.0 at 4, 32.65 at 8, 32.69 at 16) for about half the GPU time (the scene's pass +0.10 ms at 8 and +0.21 ms at 16, of 4.8 ms; 4 was within the runs' noise). A level a game picks was weighed and left out: it would be a number few can choose by eye, and a cheaper read for one texture is already `Filter.Trilinear` on it. `Filter.Anisotropic` stays the plain spelling if one is added.
    - **Every rule of Mipmaps holds for it**: the smaller images are made and kept as Trilinear's; in a frag the `uv` is worked out as the frag starts and the read is made with its two derivatives, which are what the GPU reads along, so the errors and the warning for a `uv` that can't be worked out there name `Filter.Anisotropic` as they name `Filter.Trilinear`; a vert and a function's `Sample` read the texture's own pixels; a mesh with no frag lets the GPU pick. With `SampleGrad` the two derivatives given are what a pixel covers.
    - **A sampler's, no part of a shader's text**: a frag reads a texture that says Anisotropic and one that says Trilinear with one shader, in two runs. A `Sample` that leaves its filter to its Texture is written with the derivatives in a game that names either filter. A game that names neither has the shaders, the generated C and the header it had (the enum's fourth member is in generated C only for a game that names it).
    - **An asset's `Texture` is born as its declaration says, `Filter.Trilinear` too**: until this was built, an asset declared `[Filter(Filter.Trilinear)]` carried Bilinear in its value, so a draw of it with the engine's vertices, or a frag given it as its source, read its own pixels (a `Sample` of it by name was right).
    - **A `Filter` made of the number 3** is `Filter.Anisotropic` for a mesh draw.
    - In C, `tide_filter` has `TIDE_FILTER_ANISOTROPIC`; a texture reference's sampling says it with both of its filter bits, and a shader run's `sampling` with a texture's `TIDE_SAMPLING_MIPS` bit and without its blended one (`tide_sampling_blended` is true of it all the same).
    - Not there: a level a game picks, a setting a player picks it by (a game can't swap a declaration's filter by a setting; it can say the filter at a draw or carry it on a `Texture`), and a way to ask what the device makes of it.
    - **Explicit Texture gradients** (API completion, 2026-11-02): `source.SampleGrad(float2 uv, float2 dx, float2 dy[, Filter filter[, Wrap wrap]])` reads a `Texture` using the UV change per destination pixel to the right and down. Its UV and both derivatives are ordinary evaluated arguments; no implicit UV reconstruction or derivative lifting is performed for this read. A frag and the GPU functions or methods it calls can sample this way, including in varying branches and loops with changing UVs. CPU code and verts, including helpers reached from a vert, reject it. Grids, `Cubemap` and `DepthTexture` do not expose the method. Source-name restrictions, Raw specialization, fixed Filter/Wrap members, their argument order, carried defaults and sampler-binding deduplication are the same as `Sample`. Point and Bilinear retain base-level sampling; Trilinear chooses mip levels from the explicit derivatives. A helper takes UV derivatives as ordinary numeric parameters; a frag can obtain them with `this.Ddx` and `this.Ddy`.
    - Not there: a bias on the level (`SampleLevel` chooses it, and `Filter.Anisotropic` is built: see Anisotropic filtering, above); the nearest smaller image without blending between two; saying a texture never changes, so that its smaller images are made as the game is built.
  - **Cubemaps** (built 2026-10-07, card 9 of the reshaping, the last; that the drawing side gets cube maps, for skyboxes and reflections, is agreed; every rule here was picked to build it, to confirm):
    - **A type of its own, `Cubemap`,** and not a `Texture` with a cube inside. Argued both ways: one type fewer, and a `Texture` already is several kinds of thing (C's pixels, a pack's image, a grid, a target's color). But every place a `Texture` goes would have to refuse one: a mesh's texture, a blit's source and a `Sample(uv)` are all read by a `float2`, and a cube is read by a `float3`, through another kind of sampler in both shader languages, so the compiler has to know which it is where it's read, as it does for a `DepthTexture`. A type says it once.
    - **`cube.Sample(direction)`** gives a `Color`: what the cube has towards `direction` from its middle, a `float3` of any length, in the axes the faces are named by. A zero direction reads nothing in particular.
    - **`cube.Sample(direction, filter)`**: the filter is written there, a member of `Filter`, as a texture's is. Left out, it's `Filter.Bilinear`. A cube has no wrap: one face goes on in the next, and a read at an edge is blended across it. `[Filter]` and `[Wrap]` on a `Cubemap` (an asset, a field) are errors, and a `Cubemap` value carries no sampling, where a `Texture` carries its own: the one thing there'd be to carry is the filter, and saying it at the `Sample` keeps it known as the game is compiled.
    - **`Filter.Trilinear`** reads between a cube's smaller images, by how fast the direction changes from one pixel to the next, with the rule a texture's has (Mipmaps, above): in a frag, of a direction the frag can work out as it starts, which is an error otherwise; a vert reads the cube's own pixels.
    - **A frag or a vert reads one where it's an asset by its name, or a field of a component or a singleton it takes,** as it reads a `DepthTexture`. Not a parameter of the frag's own, a local, or a field of a struct a draw supplies: each is an error that says where it goes. A function they call takes one as a parameter, and samples the cube its call names, or an asset's by its name (Code the GPU runs, A function samples the textures it takes).
    - **Its faces are six, in the order `+x`, `-x`, `+y`, `-y`, `+z`, `-z`,** each as it's seen from the cube's middle, the way a picture is, rows from the top: `+y` is up for the four around, with `+x` to the right of `+z` (the world is left-handed, as the cameras are); the one above has `-z` at its top and the one below `+z`. That's the layout OpenGL, WebGPU and Direct3D have, so six faces from another tool go in as they are.
    - **An asset's is `asset Cubemap sky = "art/sky_??.png";`:** a glob that matches exactly the six files, each a supported PNG, PSD, JPEG, TGA, BMP or RGBA8 DDS image (only its base image is used). Argued: six named arguments, or six `asset Texture`s put together in code, say the faces outright; but an asset's path is one constant text, and a glob over files named by a convention is what a list of textures already is. **Each file is named for its face by how its name ends before its extension: `px`, `nx`, `py`, `ny`, `pz`, `nz`,** in any case. Picked over `+x` and `-x`, which are awkward in file names, shells and URLs, and over `right`, `left`, `top`, which don't say which way is which; it's the convention the tools that write cube maps mostly use. A file that ends in none of them, a face that's missing or there twice, a face that isn't square and faces of different sizes are errors at the path, which name the file. One file, or a URL, is an error that says to write a glob.
    - **A list or a map of cubes isn't there:** `List<Cubemap>` and `Map<string, Cubemap>` are errors, as the glob is already the cube's own.
    - **In the pack, a cube is six images, each there once** (shared by its file's hash, with a `Texture` of the same file too), and a block that names them in order. A `Cubemap` of the pack's is a name, as a `Texture` of the pack's is: what a field keeps of `sky` is the cube as the files are now.
    - **`Cubemap(size)` makes a `Cubemap` that's drawn into** (a constructor, as `RenderTarget(width, height)` is; it was `RenderTarget.Cube(size)` for an afternoon, and a static of one type that makes another read oddly: `RenderTarget.Cube` is an error that names the constructor), and `Cubemap(size, format)` one whose faces hold `format`: `Format.Rgba8`, when left out, `Format.Rgba16f`, a number format (Number images as array layers and cube faces, below), or `Format.Depth`, six faces of depth alone (Depth cubes, below). It's made in local code, as a target is. Its name is the card's; that it gives a `Cubemap`, and not a `RenderTarget` with six of everything, is a pick: a cube is no destination by itself, and every method a target has would have to refuse it.
    - **Its size is in pixels,** whatever the display, where a target's is in logical pixels at the display's scale: a cube's faces aren't laid over the window. `cube.Resize(size)` gives it another and empty images, and `cube.Dispose()` lets it go for every copy. Neither is for an asset's cube, which is an error where it's known and a line on the game's output otherwise.
    - **`cube.faces[i]` is a `RenderTarget`,** with an int that's any expression: the face `i`, from 0, in the faces' order. `cube.faces` is only read one at a time, as `target.colors` is, and can't be assigned. A constant index past 5 is an error; one that's only known as the game runs, and a face of a cube that isn't drawn into (an asset's, or one never made), is no destination, and draws into it are passed by.
    - **A face is a destination like any other:** its own camera, clip, transform, blend, tint, depth, cull and stencil, every draw a target has, and depth and stencil of its own, kept from frame to frame. Six faces are six sets of depth. Its color and its depth aren't handed out (`face.color` and `face.depth` name no image, and a draw that samples one is passed by): the cube is what's read. `face.Resize` and `face.Dispose` change nothing, having said so: they're the cube's.
    - **What a face holds is what a camera at the cube's middle sees along the face's axis with a field of view of 90,** with the up the faces' layout says. The engine has no call that draws all six, and none that gives the six rotations: a game writes them (six `quaternion.LookRotation`s), as it works out a shadow map's matrix.
    - **A draw into a face that reads that face's cube is passed by,** with a line that says so, as a draw into a target that reads the target is, and `Draw.Blit` refuses it as it's recorded.
    - **A cube that was never set reads as black,** opaque. One that was disposed is passed by, with a line.
    - **A cube that's drawn into starts black,** and is black again after `Resize`, after a hot reload and after a lost device, as a target is.
    - **Its smaller images** are made when a draw reads it with `Filter.Trilinear` and a pass has drawn into any of its faces since, each face's from that face alone: at the smallest of them a face is one pixel, which a read off its middle blends with the faces beside it.
    - **`Format.Rgba16f`** is floats on every backend (the bytes fallback went with the GL backends, 2026-11-05).
    - **A game with no `Cubemap` generates the C it did,** and no shader's text moved.
    - In C: `tide_cubemap_ref`, `tide_cubemap_make`, `tide_cubemap_make_as`, `tide_cubemap_face`, `tide_cubemap_resize`, `tide_cubemap_dispose`, `tide_draw_cube_source`, and `TIDE_SHADER_READ_CUBE` for how a shader reads that texture; in the pack, `TIDE_PACK_CUBEMAP`, `tide_pack_cubemap_of` and `tide_pack_cubemap_find`.
    - **Depth cubes** (Provisional, Claude, 2026-11-14; the owner asked for the "isn't there yet" refusal to go: "make sure everything we can add or validate we do"): `Cubemap(size, Format.Depth)` is six faces of depth alone, each a destination of depth alone as a `RenderTarget(w, h, Format.Depth)` is, at the far limit until drawn into. `cube.depth` is its `DepthCubemap`, a type of its own (a `DepthTexture` is read by a uv; this by a direction), kept in local state as a `DepthTexture` is and read in a frag or a vert where it's a field of a component or singleton the code takes, or a GPU helper's parameter: `Sample(direction)` gives the nearest thing's depth that way from the cube's middle, forward, 0 at the near plane to 1 at the far limit; `Compare(direction, value)` how much of what's stored around there isn't nearer than `value`, 0 to 1, blended as a `DepthTexture`'s compare is. A direction of any length; `value` is kept between 0 and 1. A default one is no cube's and reads as the far limit. `cube.depth` of a cube of colors is a compile error at the draw where its format is known (each of its faces draws with a depth of its own, which isn't kept to be read); where it isn't, it's no image, and a draw that reads it is passed by with a line, as one reading a disposed target's depth is.
      - **How it's held and read: six layers of a depth array,** the faces' targets its layers, and tidec works out the face the direction points at and the place on it (the longest axis, x before y before z where two are as long) and reads that layer as a `DepthTextureArray` is, through the same sampler, under either depth storage (reversed floats, or the forward fallback). Weighed: a cube texture of depth with its own view (`texture_depth_cube`, a cube-compatible depth image), whose comparisons a GPU blends across a face's edge; Unity's replay compares a cube nearest-only where its 2D and array compares blend four comparisons, so the pictures would differ there, and it needs a new depth-cube image on every backend and in the recorder. Chosen six layers, the same picture everywhere with no new backend or recorder image: a compare at a face's very edge blends within that face, its last pixels standing for the next face's.
      - Its faces read back with `ReadDepth()`; `face.depth` and `face.color` still name no image.
      - Not there: a cube of colors' depth (draw it into a depth cube too); `cube.depth.size`.
    - Not there: a face's depth as a `DepthTexture`, or its color as a `Texture`; several color images or samples on a cube; a cube as a draw's own texture or a frag's own parameter; a cube made of six `Texture`s or grids as the game runs; image formats other than PNG, PSD, JPEG, TGA, BMP and RGBA8 DDS, and the layouts that put six faces in one file (a cross, a strip, a panorama); float files; lists, maps and arrays of cubes; drawing all six faces in one pass; `[Filter]` on a cube.
  - **Texture arrays** (2026-11-05: the owner asked for them, "just cause nothing needs [it] isn't an excuse", and picked from a proposal that they are types of their own, `TextureArray` and `DepthTextureArray`; that an asset's is a glob's images or a list of paths; that one a view draws into is `TextureArray(width, height, layers, ...)`, whose `layers[i]` are targets and whose `depth` is its depth array; and that a frag reads one with `Sample(uv, layer)`, an int layer, clamped. Every rule below beyond those was picked to build it, Provisional):
    - **A type of its own, `TextureArray`,** for the same reason a `Cubemap` is one: every place a `Texture` goes reads it by a `float2`, and an array is read by a `float2` and a layer. Its depth, each layer's, is a `DepthTextureArray`. An array is one of a draw's 16 textures, however many layers it has, and each way it's read one of its samplers.
    - **An asset's is images of one size,** a glob's, as its layers in the order a glob's list has them (by path), `asset TextureArray ground = "art/ground/*.png";`, or a list of paths in its order, `asset TextureArray ground = ["art/grass.png", "art/rock.png"];`, each a file or a glob, the same file twice being two layers of one image in the pack. 1 to 256 of them; one of another size is an error that names both. `[Filter]` and `[Wrap]` say how a `Sample` that says none reads it. Its layers compress as a `Texture` asset's do (built 2026-11-05): each layer of 128 pixels or more, a power of two a side, is BC1 where every alpha is 255 and BC3 otherwise, and an array with both is BC3 throughout on the GPU (an opaque layer's BC1 blocks turned to BC3 losslessly), its smaller images prepared in the build; `[Lossless]` keeps every layer exact, and a device without BC decodes every level. A list or a map of arrays isn't there (the glob is the array's own).
    - **`TextureArray(width, height, layers[, pixelsPerUnit][, format])` is one a view draws into:** its size is a target's (logical pixels at the display's scale, or its own pixels a unit), `layers` an int from 1 to 256 (a constant past them is an error; at run time, a line and no array), and `format` what each layer holds, `Format.Rgba8` when left out, `Format.Rgba16f`, a number format (`R8`, `Rg8`, `R16f`, `Rg16f`, `R32f`, `Rgba32f`, `R32i`: Number images as array layers and cube faces, below), or `Format.Depth` for depth alone, as a shadow's cascades want. One color image a layer, and one sample a pixel. It's made in local code, as a target is.
    - **`array.layers[i]` is a `RenderTarget`,** a destination as a cube's face is: its own camera, clip and settings, drawing into layer `i` of the array's colors and of its depth. Read one at a time; one past its layers, or of an asset's array, is no destination, and draws into it are passed by. A layer can't be resized or disposed by itself: `array.Resize(width, height)` and `array.Dispose()` are the whole array's. A new or resized array is black, its depth at the far limit.
    - **`array.depth` is its `DepthTextureArray`.** `array.size` (a layer's pixels, an `int2`) and `array.count` (its layers) are read in local code, as a `Texture`'s size is, and in a frag or a vert (built 2026-11-05: the GPU's own `textureDimensions` and `textureNumLayers`); a `DepthTextureArray` has both too. Zeros for none.
    - **A `Grid3<Color>` or a `Grid3<float>` converts to a `TextureArray`** (built 2026-11-05) wherever a `Grid2` of them converts to a `Texture`: its z its layers, each `size.x` by `size.y`, 1 to 256 of them and at most 16,384 a side, or the array is none. It names the grid, as a grid's `Texture` does: what's drawn is the grid as it is then, and the GPU gets only the parts of the layers whose chunks changed. Colors are a byte a channel, floats a half each, read in `.r`. A `Grid3` of anything else where an array goes is an error that says which are.
    - **In a frag or a vert:** `array.Sample(uv, layer[, filter[, wrap]])` and `array.SampleGrad(uv, dx, dy, layer[, filter[, wrap]])` give a `Color`; `depths.Sample(uv, layer)` gives a depth and `depths.Compare(uv, layer, value)` compares, as a `DepthTexture`'s do. The array is an asset by its name or a field of a component or a singleton the code takes; a function they call takes one as a parameter. The layer is an int of any expression, so it can differ from pixel to pixel; one past its layers reads the nearest (the GPU leaves that undefined, so tidec clamps it). The filter and the wrap are written there, members of their enums, as a cube's filter is: an array carries no sampling of its own, and one that says none is its declaration's or blended and clamped. They're the whole array's for that read: a sampler is how a texture is read, never a layer's own. `Filter.Trilinear` reads between a layer's smaller images as a texture's does, its uv worked out as the frag starts; they're made for every layer.
    - **One that was never set** reads as white, and its depth as the far limit.
    - **On Unity** it's a `Texture2DArray` or a `RenderTexture` of `Tex2DArray`, read as `Texture2DArray`; an asset's compressed layers stay BC1 or BC3 where Unity's GPU samples them (Assets, Automatic GPU compression).
    - **On Unity's OpenGL Core** (2026-11-05), where a texture samples itself, a texture's filter and wrap for a frame are what the frame's first draw of it asks, and a read another way is filtered and wrapped by the shader from the texture's pixels, fetched at their centers: exact for a texture or an array; a cube's filter is emulated on the face the direction points at, its edges its own last pixels rather than the next face's.
    - Not there: cube arrays (WebGPU's core has none), a layer as a `Texture` of its own, an array of several color images or samples, and an array as a draw's own texture. `[Raw]` arrays were built later the same day (see `[Raw]`).
  - **Volumes:** `Texture3D` blends continuously on all three axes and accepts Grid3<Color>/Grid3<float> conversions.
    It is local, made with a size and format, and written by kernels. The owner decisions dated 2026-11-13 and
    all Provisional constructor, sampling, lifetime and storage rules are under Compute on the GPU.
  - **`Draw.Transform`** takes `(offset)`, `(offset, rotation)`, `(offset, rotation, scale)` with a `float` or a `float2` scale, or a `float3x3` matrix. `offset` is a `float2` in the units the calls are in, `rotation` is in radians from `+x` towards `+y`, as shapes' are, and the draws are scaled, then turned, then moved, all about (0, 0). The matrix's first two columns are where (1, 0) and (0, 1) go, and its third where (0, 0) does. **`Draw.Transform`** takes a `float4x4`, which each mesh's own transform goes through on its way to the world.
  - A transform is no part of the conversions: `Draw.WorldToScreen` and the others are the camera's alone. `Draw.MeasureText` is in the units the transform takes, so inside one, text measures as it's drawn.
  - **Shapes under a transform** stay shapes. Moved, turned, mirrored and scaled as much each way, they're exactly that, and rects that are only moved and scaled still fill whole pixels, so tiles under one leave no seams. A transform that stretches (more one way than the other) or skews gives the nearest shape: a circle or an ellipse is the ellipse it becomes, a rect's sides follow its own axes, and what has no direction (a corner's radius, an outline's width, how far an edge fades, a ring's radius) is scaled by the transform's mean. A `WireRect` or `WireCircle` that's turned or stretched keeps an outline a pixel wide. Meshes go through any transform as they are, corner by corner.
  - **Text under a transform**: moved, and scaled as much each way, it's text of that size, fitted to the display's pixels as any text (so as a scale changes, it steps from one whole size to the next, as it does under a camera that zooms). Turned, stretched or mirrored, it has no pixels to fit: it's laid out as it would be upright, at the size the transform's mean scale makes it, and drawn through the transform, softer than upright text. Either way its anchor's place is its `position` through the transform, and its box is against it as it is upright, then turned with it.
  - **A clip under a transform** is the upright rect around what its rect becomes: clips don't turn.
  - **`frag` and `vert`**: a mesh drawn through them blends as the setting says, its frag's color is multiplied by the tint, and a 2D one's vertices go through the transform after its vert, before the camera. A 3D one's `instance.transform` is its own through `Draw.Transform`, and `instance.Normal` goes by both.
  - A draw's singletons' fields are 3984 bytes at most in 2D and 3968 in 3D (the owner approved reserving another float4 for the camera origin, 2026-11-02), where they were originally 4000: the tint is sent with them, and with it 4000 would make a block of uniforms that some OpenGL ES drivers don't link (Android's emulator takes 255 float4s in a vertex shader's block, and not 256).
  - **`Draw.Clear`, and a target's `Clear`,** fill what the clip leaves with their color as it is: no blend, tint, stencil or transform changes a clear.
  - **`Draw.Blit`** is its destination's, whatever is set: no blend, tint, depth, cull, stencil, transform, camera or clip changes it. It takes a blend of its own before its frag, `Draw.Blit(source, destination, Blend.Add, frag)`, and replaces what's there without one. So a pass over the screen doesn't change with what an earlier view left set.
  - A setting that's set to what it was, or set and put back with nothing drawn, costs nothing: what's drawn on either side of it is still drawn at once. A tint and a 2D transform are worked into shapes and text as they're recorded, so shapes with a tint or a transform each are still one draw call. A mesh through a `frag` gets its tint and its 2D transform with its draw, so instances with different ones are different draws.
  - In C (`tide/draw.h`), `tide_draw_set_*` are the `Set` forms (`tide_draw_set_camera`, `tide_draw_set_clip`, `tide_draw_set_screen`, `tide_draw_set_blend`, `tide_draw_set_depth`, `tide_draw_set_cull`, `tide_draw_set_stencil`...), `tide_draw_unset_*` the ones with no arguments, and `tide_draw_push_*` with `tide_draw_pop(list, mark)` the blocks. The former `tide_draw_camera`, `tide_draw_camera_3d`, `tide_draw_camera_matrices`, `tide_draw_clip`, `tide_draw_no_clip` and `tide_draw_screen` were renamed to match.
- **Numeric attachment samples** (Provisional, backend foundation 2026-11-14): R32f, Rgba32f and R32i
  attachments use one sample. Optional float32 multisampling and resolving integer sample zero were considered;
  a single-sample baseline keeps attachment support independent of optional WebGPU features and avoids an
  integer mean. The authored API and its diagnostic are built since: a `samples` other than 1 on these formats is an error where the target is made (Numeric images and outputs, Multisampling, below).

- **Target formats and depth** (built 2026-10-07; that a target says what it holds when it's made, that one can hold depth alone, and that a frag reads a target's depth plainly or compared are decided, above; everything here is a pick, to confirm):
  - **`Format`** is a built-in enum, with two members when this was built: `Format.Rgba8`, a color image beside the depth, which is what a target holds when nothing is said and the name for what targets always were, and `Format.Depth`. (They were `Format.Color` and `Format.DepthOnly` until the formats were named by what they store: see One word for the window, and formats by what they store, above.) (`Format.Rgba16f` joined them with several colors: see Several colors and float images, below.) A game can't declare the name outside a namespace. It's a value like any enum's: a variable or a function's parameter says it too.
  - **It's the last argument where a target is made:** `RenderTarget(width, height, format)`, `RenderTarget(width, height, pixelsPerUnit, format)`, `RenderTarget.Window(format)` and `RenderTarget.Window(factor, format)`. Anywhere else among them is an error that says it comes last. `Resize` keeps it, and so does a hot reload, with the target's size and scale. (That a target's formats are after its size, one for each color image, is decided since.)
  - **What draws into depth alone.** A clear, a 3D mesh under `Depth.ReadWrite` or `Depth.Only` (`target.Mesh`, the primitives, `target.Instanced`, through a frag or not), and whatever stores stencil (see Stencil, above). Shapes, text, 2D meshes, a `Draw.Blit` into it, and 3D meshes under `Depth.Read` or `Depth.None` draw nothing there otherwise, and say nothing: it's what the target is for. Its `Clear` takes a color like any target's, which goes nowhere.
  - **`target.depth` is a `DepthTexture`,** a type of its own, as the code the GPU runs differs for it and the compiler has to know which it's writing. It's a local reference like `Texture`: kept only in local state (a local component's or singleton's field, a match one's `local` field, a struct of those, a local), copied freely, with no constructor. A default one is no target's, and reads as the far limit: `Sample` gives 1, and `Compare` 1.
  - **`depth.size` is a read-only `int2` of physical pixels**, in local CPU code and shaders, with the same metadata, ordering and frame-thread rules as `Texture.size`. It follows the target's live resize, display scale and device limit, for depth-only targets and targets with color alike; missing, invalid or disposed depth gives `(0, 0)`. It uses the host's existing `target_pixels` resolver, with zero dimensions when none is supplied. Metadata does not allocate an image, resolve multisampled depth, copy pixels or consume a shader texture binding. Shader reads use the same named fields and helper parameters as depth sampling; CPU helpers may also take depth parameters and read only their dimensions.
  - **A frag or a vert reads one where it's a field of a component or a singleton it takes,** `lamp.shadow.Compare(uv, depth)`, as it reads a `Grid2<Color>` or a `Texture` field: a view puts a target's depth there, `lamp.shadow = lamp.map.depth;`. It isn't a parameter of the frag's own, and no draw supplies one as its texture (`Draw.Mesh`'s, or `Draw.Blit`'s source): those are a color's. Reading it through the target, `lamp.map.depth.Sample(uv)`, is an error, as a frag doesn't read a `RenderTarget`. A function they call takes one as a parameter, `float Lit(DepthTexture shadow, float3 at)`, and reads the depth its call names, `Lit(lamp.shadow, at)`, both ways (Code the GPU runs, A function samples the textures it takes).
  - **`depth.Sample(uv)`** gives a `float`, the nearest pixel's. It takes no `Filter`: a depth blended between two pixels is neither's.
  - **`depth.Compare(uv, value)`** gives a `float` from 0 to 1. At each of the pixels around `uv` it's 1 where what's stored isn't nearer than `value`, the test a mesh passes to be drawn there, so a pixel compared with its own depth passes; what that gives at each is blended by how near `uv` is to it. `value` is kept between 0 and 1 first: past the far limit is the far limit. A frag takes its own bias off `value`; there's none as state.
  - `uv` is a color's: (0, 0) at the target's top left corner, (1, 1) at its bottom right, and past them, the pixels at the edge: neither read takes a `Wrap`.
  - **A draw into a target that reads that target's depth is passed by,** with a line that says so, when it's drawn: what a frag reads comes through a field, which the compiler can't follow to a target. It's what a draw that samples its own destination's color through a field gets, where `Draw.Blit(target.color, target, frag)` is refused as it's written. So is a draw that samples the `color` of a target of depth alone, which has none.
  - A depth is stored as reversed 32-bit float with 8 bits of stencil beside it, in every target and in the window, and as forward 24-bit depth with 8 bits of stencil only on a device that lacks that format; what Tide reads of it is forward either way (Depth precision, Decided).
  - A depth a frag reads is one of the draw's 16 textures, however it's read: one it both samples and compares counts once, and is read through two of its samplers (Provisional, 2026-11-05: it counted twice before).
  - **Not there:** a `DepthTexture` as a draw's own source or a frag's own parameter; a comparison other than "isn't nearer"; and skipping a frag that can't discard in a target of depth alone, which a backend may do some day and changes no picture.
  - **Where a point of the world is in a target's image is the game's to work out,** for a frag that looks one up (a shadow map does): through the target's camera as a matrix, `target.WorldToClip()` (see The cameras as matrices, above: the projection, after z turned around, after the camera's transform undone, which a game spelled out itself until that was built); then `uv` is `(x * 0.5 + 0.5, 0.5 - y * 0.5)` of that point and its depth `z * 0.5 + 0.5`, each over `w` under a perspective.
- **Several colors and float images** (built 2026-10-07; a format for each color image after a target's size, four at the most, `target.colors[i]`, a frag's outputs to them by their order with the rest of either dropped or left, and floats where a GPU draws into them with bytes and a line where one doesn't, are decided, above; everything here is a pick, to confirm):
  - **`Format.Rgba16f`** is the enum's third member, and the original float format: four floats of 16 bits a pixel, each any number to three digits or so (up to about 65,000, in steps of a thousandth near 1). It's the one every backend that has float images draws into, blends and reads blended between pixels, so a `Format.Rgba16f` image behaves as a `Format.Rgba8` one does but for what it keeps. It takes twice the memory. The numeric formats and their matching rules follow below.
  - **Where the formats are written:** after the size and, where it's said, the pixels per unit, `RenderTarget(width, height, pixelsPerUnit, Format.Rgba8, Format.Rgba16f)`, and after a screen's factor. A fifth is an error, and so is `Format.Depth` written among several: every target has depth, so it's said alone. A format is a value like any enum's, so one that's only known as it runs, and isn't a color's among several, is a `Format.Rgba8` image, with a line that says so.
  - **`target.colors` is only read one at a time,** `target.colors[1]`, with an int that's any expression. It's no list: `target.colors` by itself and a loop over it are errors that say to read one. (`target.colors.count`, how many it holds, is read since 2026-11-14.) A literal index past 3 is an error; any other image a target hasn't got is found out when a draw samples it, which is passed by with a line that says so, as a draw that samples the color of a target of depth alone is. `Draw.window` has none, like its `color`.
  - **`target.color`, `target.colors[i]` and `target.depth` can't be assigned:** they're the target's own images. (The first and the last compiled before, to C that didn't.)
  - **What the engine draws itself has one color,** which goes into a target's first color image and leaves the others: shapes, text, 2D and 3D meshes drawn with no frag, and so the GUI's widgets, were they drawn there.
  - **A clear fills each image** with its corresponding typed value and sets depth back; numeric float values can exceed one. The existing one-Color clear still broadcasts to ordinary color targets (Numeric images and outputs, below).
  - **A frag's outputs are matched by their order alone,** wherever they are among its parameters and whatever they're called, so `out Color albedo, Sun sun, out Color normal` writes the first image and the second.
  - **Each Color output is finished as the pixel's color is:** times the draw's tint (`Draw.Tint`), then blended over what's in its own image by its own alpha, as the draw's blend says. There's one blend for a draw, not one for each output, a Color output keeps its color times alpha under `Blend.Replace` too. Numeric outputs replace their image without tint, blending or premultiplication.
  - **A frag of several outputs draws anywhere:** into the window or a target of one color image, where its first is the pixel's and the others go nowhere, and into a target of depth alone, where none does. Nothing warns: one frag serves a pass that fills three images and a pass that casts a shadow.
  - **`Draw.Blit`** replaces as many of its destination's color images as its frag has outputs, and leaves the others. Its source is its frag's first `Texture`: a frag that reads several images of a target takes the others as `Texture` parameters, which the blit gives in order after its source and before its destination (Provisional: Several textures a draw gives), or through `Texture` fields of a singleton.
  - **A draw into a target samples none of that target's color images,** the second no more than the first, whichever of them it writes: it's passed by, with the line a draw that samples its own color gets.
  - **Every GPU Tide draws with draws into floats** since the GL backends went (2026-11-05); the decided fallback for one that couldn't (bytes, and a line on the game's output) went with them.
  - **Not there:** a blend for each output; a target's color image as another target's (each target owns its images). (How many images a target has is read since: `target.colors.count`, under Which image a read is of, above.)
- **Numeric images and outputs** (built 2026-11-14; the output types, formats, typed reads and per-image clears are
  decided 2026-11-13 above; the following are implementation picks, Provisional):
  - **Type matching:** R8, R16f and R32f take `float`; Rg8 and Rg16f take `float2`; R32i takes `int`;
    Rgba32f takes `float4`; Rgba8 takes `Color`; Rgba16f takes either `Color` or `float4`. R8/Rg8 clamp
    and quantize channels to unsigned bytes. Half floats have 16-bit precision; 32-bit floats and signed
    integers retain their representable values. Requiring an exact shape, rather than silently dropping or
    filling channels, catches drawing into the wrong image. A mismatch is diagnosed at the draw with its fix.
  - **Numeric reads use a field role:** `[Raw(float)] Texture`, `[Raw(float2)] Texture`,
    `[Raw(float4)] Texture` and `[Raw(int)] Texture`; the same roles apply to Texture3D fields.
    `target.color` and `target.colors[i]` remain image references assigned to those fields in local code.
    Sample and exact-cell reads return the role's type. The role is checked against the source image's format.
    This reuses the existing Texture/Raw precedent instead of a new public type for each format. Bare `[Raw]`
    retains its earlier behavior. A synchronous GPU helper takes `[Raw(float)] Texture image` or the
    corresponding role/Texture3D parameter, read-only, and requires a caller with the same role. This preserves
    the type through helper chains without introducing a separate runtime texture type.
  - **Portable filtering** (Provisional, 2026-11-14; it replaces that day's first rule, nearest reads only, after
    the owner asked that everything a GPU can do be allowed: "make sure everything we can add or validate we do"):
    a typed read that names no filter reads the nearest pixel, as before, whatever the image's own `[Filter]`
    says. A typed float image in `R8`, `Rg8`, `R16f`, `Rg16f` or `Rgba16f` also takes `Filter.Bilinear`,
    `Filter.Trilinear` and `Filter.Anisotropic`, `SampleLevel` and `SampleGrad`, through the GPU's own sampler,
    and gives its role's `float`, `float2` or `float4` with no alpha work. A `SampleLevel` or `SampleGrad` that
    names no filter reads between levels (`Filter.Trilinear`). Those five formats blend and are drawn into on
    every backend (Vulkan 1.3's required formats, WebGPU core, Unity's), so their mipmaps are made of what was
    drawn, when a read that uses them first needs them, as a Color target's are. Wrap remains
    Clamp/Repeat/Mirror, the Sample's own (a `Texture` field takes no `[Wrap]`).
    - **`R32f` and `Rgba32f` blend through exact loads, the same bits on every device** (Provisional, Claude,
      2026-11-14, after the owner's "make sure everything we can add or validate we do"; it replaces that day's
      nearest-only rule). A GPU blends 32-bit floats only with an optional feature (WebGPU's `float32-filterable`,
      a format feature on Vulkan), so a `Filter.Bilinear` read of one is the four texels around the uv (a
      `Texture3D`'s eight) loaded exactly and blended in tidec's shader code by where the uv is between them, as
      the GPU's Bilinear is, with the Sample's wrap on the texels it reaches past an edge. A `Texture`, a
      `TextureArray`'s layer and a `Texture3D` blend so; `Filter.Point` loads the nearest texel. Their one level is
      the image itself, so a `SampleLevel` or `SampleGrad` naming `Filter.Point` loads the nearest texel and one
      naming `Filter.Bilinear` blends the four, whatever level it asks (a GPU's sampler reads an image with no
      smaller images so; corrected 2026-11-15, Claude: this said both load the nearest, and the code blended), and
      so does a `SampleLevel` that names no filter at a level written `0` (Explicit mip level, below). Which images are of these
      formats tidec knows from a typed field's constructor assignments, which it needs fixed already, and from
      each texture a draw gives a frag's or vert's own typed `Texture` (a shader of its own for those): the R8 to
      Rgba16f formats keep the GPU's one sampled read. Weighed: asking for the feature and blending where it's there, nearest elsewhere,
      another picture by device, refused for that; nearest only, the first day's rule; and loads for every format,
      the same bits for those too at four reads where the GPU's sampler takes one, refused for what it costs the
      formats that blend everywhere.
    - **They have no mipmaps:** `Filter.Trilinear`, `Filter.Anisotropic`, a `SampleLevel` or `SampleGrad` that
      names neither Point nor Bilinear (or no filter, which is Trilinear, but for a `SampleLevel` at a level written
      `0`), of an `R32f` or `Rgba32f` image, is a compile error at the draw naming `R16f` or `Rgba16f`. Weighed: a chain made of exact means by a kernel, and an
      eight-load blend between two levels, which would read levels everywhere at about twice a Bilinear's cost and
      a chain's memory; chosen none, as the formats' purpose is numbers as they are.
    - **`R32i` stays nearest:** no GPU blends integers. Any filter but Point, `SampleLevel` and `SampleGrad`
      are errors where they're written.
    - **A read through a blending sampler is never handed an image it can't blend,** whatever path the image
      took to its field (a format chosen as the game runs, a `?:` of two targets, C): at run time such a read
      gets no image, a Color read the white pixel and a typed one zeros. So is a kernel whose written field
      holds an image of another format than its pipeline declares, or one with no storage use: its stores go
      to a private image, with a line that says so once. Neither reaches a GPU binding of another format.
      Nor are smaller images made of such an image for a read between them (Claude, 2026-11-14): making them
      blends, which WebGPU's validation refused on every frame the target was drawn.
    - **The colors of an image of depth alone are no image** (Claude, 2026-11-14): a `TextureArray` or a target
      made with `Format.Depth`, read as colors by a frag, a vert or a kernel, is an error where the compiler sees
      the constructor, naming the `DepthTextureArray` or `DepthTexture` field to read instead. Where it can't (a
      `?:` of two arrays, a `mut` parameter, C), a draw is passed by with a line as before, and a kernel's read
      is what no image reads (white, or zeros for a typed read), never the depth bound as colors, which WebGPU
      refuses and Vulkan filters undefined.
    - **A typed read of no image is zeros,** blended or not, in a Texture, an array or a cube.
    - Ordinary Color and bare Raw textures keep their filters.
  - **Number images as array layers and cube faces** (Provisional, 2026-11-14): `TextureArray(width, height,
    layers[, pixelsPerUnit], format)` and `Cubemap(size, format)` take every number format beside their color
    formats: `R8`, `Rg8`, `R16f`, `Rg16f`, and (Claude, later the same day) `R32f`, `Rgba32f` and `R32i`. A frag's
    numeric output draws into `array.layers[i]` or `cube.faces[i]` and `Clear(value)` fills one with a typed value,
    both matched to the format as a target's are. They're read through `[Raw(float)]`, `[Raw(float2)]`,
    `[Raw(float4)]` or `[Raw(int)]` on a `TextureArray` or `Cubemap` field or a GPU helper's read-only parameter:
    `Sample` gives the role's type, nearest where no filter is named; a filter named blends, and `SampleLevel` and
    (an array's) `SampleGrad` read between mipmaps, Trilinear where they name no filter, for the formats every
    device blends. A typed array's nearest pixel is an exact load where its format is a 32-bit one or isn't known (a
    kernel's field the renderer binds), through a binding every float format fits (an unfilterable
    `texture_2d_array<f32>`, `<i32>` for ints), the texel a nearest sampler gives; one of a known R8 to Rgba16f format
    keeps its nearest sampler, so its nearest and blended reads stay one of a draw's 16 textures. Its `R32f` and
    `Rgba32f` layers blend with `Filter.Bilinear` as four exact loads (Portable filtering).
    - **A cube of 32-bit numbers is six layers** on the GPU, an array's, its faces their targets: no GPU samples an
      integer cube, nor blends 32-bit floats everywhere. tidec reads it by working out the face the direction points
      at and the place on it (the longest axis; x before y before z where two are as long, at a face's very edge),
      and loading the nearest texel there, the same on every backend. It's read at its nearest pixel alone: a
      filter or a level is a compile error at the draw naming `R16f` or `Rgba16f`, as blending across a face's edge
      from loads would take the faces beside it and no backend's own. Weighed: an unfilterable cube binding and a
      non-filtering sampler for the float formats, which leaves integers out and binds differently on Unity; a 2D
      array view of a cube, which Unity's replay can't take of a cube's image; six layers chosen.
    - **`[Raw(int)]`** on an array or a cube reads `R32i` layers and faces, nearest alone: a filter is an error
      that says no GPU blends integers. A typed read of no image is zeros, as ever.
  - **Multisampling:** R8, Rg8, R16f and Rg16f support their usual sample counts and resolve each numeric
    channel by the mean. Numeric float4 outputs into Rgba16f use its ordinary mean resolve too. R32f,
    Rgba32f and R32i require one sample, including when mixed with other images of a target. Optional float32
    multisampling and an integer sample-zero resolve were weighed against the portable common attachment path;
    one sample was chosen instead, with a diagnostic for a request above one.
  - **Clears:** `target.Clear(v0[, v1, v2, v3])` supplies one value per image in format order, of the same
    accepted types as its frag outputs. Floats may be negative or greater than one; R32i takes an int.
    Numeric values undergo no tint, alpha multiplication or blending. Depth and stencil reset within the
    destination's clip as before. A single Color retains the existing broadcast behavior on ordinary color
    targets. Separate methods for each image were weighed against one clear preserving the destination's
    depth/stencil reset and the formats' existing in-order rule.
  - **Portable storage:** kernels and Texture3D support R32f, Rgba32f and R32i alongside the existing
    Rgba8/Rgba16f storage formats. R8/Rg8/R16f/Rg16f have no portable storage bindings and are refused with
    guidance to use R32f or another writable format. Numeric stores preserve every channel without alpha work.
  - **Coverage:** Cutout and Coverage require a Color as the first output. The device takes coverage from
    that output's alpha; a float4's fourth lane is independent data and an integer output has no alpha.
    A hidden extra color attachment or repurposing a numeric lane would change the target or its values, so
    a numeric-only frag uses Discard for cut-outs instead. Other numeric outputs remain unmodified.
- **A target's samples** (built 2026-10-07; that render targets have multisampling, said with a `samples` argument, is decided, above; everything here is a pick, to confirm):
  - **It's a named argument, the last, where a target is made:** `RenderTarget(width, height, samples: 4)`, `RenderTarget(width, height, pixelsPerUnit, Format.Rgba8, Format.Rgba16f, samples: 4)`, `RenderTarget.Window(samples: 4)`, `RenderTarget.Window(0.5, Format.Rgba16f, samples: 4)`. By name because a target's other arguments are told apart by their types and their order (numbers, then formats), and a bare `4` after them would read as nothing: after `RenderTarget(64, 64` it would be the pixels per unit. It's the one argument of a target's that's named, and it's only written with its name: any other name is an error, and so is `samples:` before another argument.
  - **1, 2, 4 or 8.** 1 is a target that says nothing. A number that's known as the game is compiled and is none of those is an error; one that's only known as it runs is the one of those under it (5 is 4, 100 is 8, 0 is 1), with a line that says so.
  - **A device with fewer draws it with what it has,** and the engine says so once, on the game's output: the most of 8, 4 and 2 that's no more than asked and that the device has for what the target holds. WebGPU has 1 and 4 and nothing else, so there 2 is 4 (more than asked, where the other choice was no smoothing at all) and 8 is 4. Nothing lets a game ask what it got.
  - **What it's for:** each of the target's pixels keeps that many colors, depths and stencils while it's drawn into, and a triangle's edge covers some of them, so the edges of 3D meshes, and of 2D ones, are smooth. A frag still runs once for a pixel a triangle covers, not once a sample. The smooth shapes and text are smooth by themselves, and are as they were.
  - **Its images are what its samples come to,** one value a pixel, each time drawing into it ends (a pass): `target.color` and `target.colors[i]` are textures like any target's. Color reads keep their filters; typed numeric reads follow Portable filtering, above. What's drawn into it is kept from frame to frame, sample for sample, until it's cleared, as any target's is.
  - **Its smaller images are any target's** (Provisional, Claude, 2026-11-14): `Filter.Trilinear`, `Filter.Anisotropic` and `SampleLevel` read a chain made of what its samples came to, when a read first needs it after more was drawn. Vulkan had it; WebGPU resolves each pass into the first level of a texture with room for the rest, and makes the rest as a one-sample target's. Unity's replay is handed what it needs to do the same (the target's samples in the packet that makes it, and a Mipmaps of its resolved color); its making of them is Unity's replay's work, still to come, and until then it reads the resolved image alone there. Weighed: refusing those reads of a multisampled target on every backend.
  - **Its depth is read as any target's** (2026-10-13; the owner asked for the engine to be fixed where a game had worked around the refusal there was, and each rule is a pick, to confirm). `target.depth` of a multisampled target is one depth a pixel: one of the pixel's samples, as they are when the draw that reads it is drawn. It's made of the samples only for a target whose depth a draw reads, and again only once more was drawn into the target, so a target nothing reads the depth of has no texture for it and pays no pass. A sample picked, not their mean or their nearest: an edge is a step, as a target's with no samples is, and the depth is one a surface there really has.
  - **A target of depth alone has none:** `Format.Depth` with `samples` above 1 is an error where both are written, and where either is only known as it runs the target has one sample, with a line that says so.
  - **The window has none.** A game that wants an antialiased frame draws it into `RenderTarget.Window(samples: 4)` and brings it to the window with `Draw.Blit`. The window's own framebuffer would take a setting that's the game's and three ways to ask for it that can each be refused (GLFW's hint before the window is made, the WebGL context's `antialias`, which a browser may ignore, and an EGL config on Android), a canvas on WebGPU has no samples of its own at all, and the GUI, the stats and the smooth shapes drawn there gain nothing from it.
  - **It takes that many times the memory:** `samples` colors and depths a pixel, and one more color a pixel for each image they come to. A 4-sample target of the window's size at 1920 by 1080 is about 75 MB where one with none is 17.
  - **Everything else is as for any target:** every draw goes into it, the engine's own, a frag's, a clear, a blit and stencil among them; `Resize` keeps its samples; a hot reload makes it again with them.
  - **Cut-outs: `this.Cutout(alpha)` and `this.Coverage(share)` in a frag** (alpha to coverage, built 2026-10-31 for a game whose foliage, cut with `this.Discard()`, aliased in a 4-sample target). The owner asked for it as code rather than an attribute (an attribute, `[Cutout]`, was built first the same day, and is an error that names the replacement), and for the dithered share as well as the cut; the rest is a pick, to confirm. A frag that calls either is drawn with alpha to coverage, as a frag that calls `this.Discard()` is known to discard: what the pipeline is comes from the frag's code. A draw setting (`Draw.AlphaToCoverage(true) { ... }`), which the asking game suggested, was weighed and left: a frag written to discard would be drawn under it with the wrong meaning, and what a target of one sample does would be open.
    - **Statements, anywhere in the frag itself:** in a branch too, and more than once, the last one reached counting; a path that says nothing covers the pixel whole. One way a frag: both in one frag is an error.
    - **`Cutout` is an alpha, which the engine sharpens, after the tint's alpha:** `(a - 0.5) / max(fwidth(a), 0.0001) + 0.5`, clamped, so a texture's soft alpha and its smaller images far away still give an edge a pixel wide, with nothing of the game's to write. It's worked out as the frag ends, on what the frag's code said. **`Coverage` is the share as it's given**, times the tint's alpha, with nothing sharpened: dithered fades and soft edges, or a cutoff of the game's own with `this.Fwidth`.
    - **Into a target with samples, the GPU makes that the share of a pixel's samples covered** (WebGPU's `alphaToCoverageEnabled` at its 4 samples, Vulkan's `alphaToCoverageEnable`, Unity's `AlphaToMask`), with depth and stencil written only at those samples. **Into a target of one sample** (the window, a target without `samples`, one of depth alone, a device that gave one), its shader cuts at 0.5 itself, so a shadow map's caster can be the scene's frag, and the alpha is 1.
    - **What it covers it covers wholly:** its color's alpha isn't read; its color isn't times an alpha, and doesn't go to white for `Blend.Multiply`; under `Blend.Alpha` a covered sample is replaced; `Add`, `Multiply` and `Replace` are as they say, with the color whole. At an edge with samples, a covered sample's alpha is the coverage (the GPU takes coverage from that output, and making it 1 after, alpha to one, is on neither WebGPU nor WebGL), so over an opaque clear an edge pixel's alpha is a little under 1.
    - **The first output's alpha** is what the GPU covers by, for all of them; a frag's other outputs are finished as any frag's. `this.Discard()` still discards.
    - **Not there:** a frag's own sample mask; a frag that runs for each sample.
  - **How fast a value changes: `this.Ddx(v)`, `this.Ddy(v)` and `this.Fwidth(v)` in a frag** (2026-10-31; the owner asked for derivatives, for smooth signed-distance edges among others; how they work is a pick, to confirm). `v` is a float, a float vector or a `Color`, and what comes back is of its type: how much it changes to the next pixel across, down, and the two's sizes added (Unity's HLSL `ddx`, `ddy` and `fwidth`, with Tide's PascalCase, on `this`, as they're the pixel's).
    - **Asked as the frag starts, wherever they're called.** A GPU only answers outside branches and loops (WebGPU refuses the shader, HLSL leaves it undefined), and a conditional `this.Discard()` ends that in WGSL. So, as for a `Sample` between a texture's smaller images, the frag works `v` out a first time as it starts and asks there, and the call is that answer. A `v` it can't work out there (made of a variable that changes, or one a loop counts) is an error on every platform, as the game is compiled. What can be: the frag's parameters, `this`, constants, functions of them that take everything by value, textures read (a `Sample` between smaller images too, which the GPU picks itself there), and variables declared with `var` and never assigned again. It costs working `v` out twice.
    - **`Ddy` goes down the destination's rows**, as `this.position` counts them, in the window and in a target, on every backend. (The OpenGL backend, removed 2026-11-05, drew a target's pass upside down and handed tidec's GLSL a uniform saying which.)
    - **Not there:** the fine and coarse kinds (`ddx_fine`, `ddx_coarse`), which a GPU may make one; derivatives in a vert, which has no neighboring pixels, or in a function a frag calls, which has no `this` (it takes the answer as a value).
  - **Not there:** asking how many samples a target has, or a device's most; a frag that runs for each sample, or reads one; a resolve other than the GPU's own (the mean of a pixel's samples, which is wrong for light past white in a `Format.Rgba16f` image: a bright edge stays jagged until tone mapping is done before the resolve); samples for the window.
- **`verified` in views**, beyond what's decided:
  - Any `verified` component or filter asks for the entity in the confirmed world: `without verified Dead` is "confirmed, and not `Dead` there", so an entity whose spawn isn't confirmed yet is skipped by it too.
  - The same entity is identified by its complete logical identity, including in a world received from the server.
  - `mut` goes with it: `mut verified Health health` reads the confirmed `Health` and writes the entity's 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`; through the other it's an error that says so.
  - A view of the confirmed world's entities draws them as they are there: nothing it reads of them is blended, corrections aren't smoothed, and `this` is the confirmed entity. Its `World` is still the world it draws.
  - A `verified` value is whole: its text, lists, maps, sets and grids are the confirmed world's, read like any other's, through members, methods, loops, copies of the value and the functions it's passed to. Nothing of them is copied to read them, but the elements of a list or map whose elements hold text, which a view gets a copy of each time it runs. They're to read: like everything a view takes of the match, a change goes to a copy, in a local or in local state.
  - `verified World world` isn't built: an error that points to `verified` component parameters.
  - A frag or vert can't say `verified`: it reads what its view is given. The mesh's components are the view's own as it draws them (the ones that aren't `verified`, where it takes one both ways), and the confirmed ones in a view of the confirmed world's entities.
  - A function's parameter can't say it either: the view takes it `verified` and passes it on.
  - With one world and no server, as on a C host that ticks a world itself, that world is the confirmed one too.
  - Outside a match, a view with a `verified` parameter doesn't run, like any view that reads the match.
  - `verified` is a word of its own before a parameter's type where a type and a name follow, after `with` or `without` where a name follows, and before an event in a handler's `event(...)`. Anywhere else it's a name like any other.
- **Queries in views and local handlers**, beyond what's decided (see Read-only entity queries):
  - Match fields remain read-only. The decided 2026-10-19 rule above permits current attached local fields, with `mut` required for writes, including through verified and recorded rows.
  - `entry.entity` is an `Entity` for the match's entities, the confirmed world's handle in a query whose bindings and filters are all `verified`, and a `LocalEntity` for a local query's.
  - **Outside a match, a view with a query over the match doesn't run**, like any view that reads the match: a view only runs when everything it reads exists. A query that names no component is the match's in a view. A game that wants the rest of the view to go on outside a match keeps the query in a view of its own.
  - A view's rows are made once a frame for the view, when it first runs for an entity, so a view no entity matches makes none, and a view that runs for each of its entities doesn't blend a query's again for each. A view that runs once a frame makes them where its code first names one of its queries, so one that returns before that makes none either. Correction smoothing (`[Position]`, `[Rotation]`) applies to them as to the view's own parameters. Text and lists of the world the view draws are read through a row as through a parameter.
  - As for a view's own parameters: any `verified` binding or filter asks for the entity in the confirmed world; a `verified` binding interpolates between confirmed endpoints, and its text, lists, maps, sets and grids are the confirmed world's, read from its heap; the same component can be bound both ways in one query, `query (Health health, verified Health sure) both`; with one world and no server, that world is the confirmed one too.
  - **A local query** reads the local world as it is, with what views earlier in the frame wrote. A view that changes a local component it also queries sees the rows it changed earlier in that run, as a system does, and its own entity's as it was before the view ran for it.
  - `ownership` isn't a query filter, in a view either: an error, as in a system.
  - **A local handler's rows are its event's tick's once that tick is done**: after all its events and changes, not as each event's turn left things, where the handler's own components are. So an entity the tick destroyed is in no row, the one the event was sent to included, and one it spawned is in them. They aren't blended. The tick records them once, whichever of its events have a handler that reads them, and only when it sent one.
  - Under rollback, a handler that hears a tick as it's predicted gets the rows of the run that first sent its event, and one of a `verified` event the confirmed run's.
  - Nothing in a local handler's query says `verified`: its event does, for all of it. Container fields the handler may read are captured with the other recorded match data, under the decided recorded-container rule.
  - A query of this machine's entities in a local handler is the local world as it is when the handler runs. A handler of a local event, `Forgotten` among them, takes only those. A query over the match counts as something of the match's for `Spawned` and `Destroyed`: a local handler of one that takes it hears the match's.
- `frag` and `vert` declare code the GPU runs for a mesh's pixels and vertices (above, and GPU code below).
- `view` declares a view. It looks like a system and takes the same parameters, but it runs once per rendered frame instead of once per tick. Its `mut` parameters, `Spawn`, `Add`, `Remove`, `Destroy` and `Send` are local (see Local state): a `mut` parameter is a local component or singleton, or one of the match's that has local fields, which are all the view writes of it. Input parameters are errors in a view.
- Views run in declaration order, after all the systems of the frame's ticks. Within a view, entities run in the same order as in systems.
- `Draw` functions can only be called from views and the functions they call (see Functions). Calling them from systems needs to tell predicted ticks from verified or replayed ones, which comes with multiplayer.
- `view` is only a keyword at the start of a declaration, like `input`.
- Positions and sizes are in world units with `y` up. The camera maps them to the screen.
- The Draw functions:
  - `Draw.Clear(color)`: fills the screen.
  - `Draw.SetCamera(center, size)`, or `Draw.Camera(center, size) { ... }` around a block (see Draw settings): the camera for the Draw calls. `center` is the world position at the middle of the screen, and `size` is half the visible height, like Unity's orthographic size. Each frame starts black, with the camera at the origin and one world unit per pixel.
  - `Draw.Circle(center, radius, color)` and `Draw.WireCircle(center, radius, color)`.
  - `Draw.Rect(center, size, color)` and `Draw.WireRect(center, size, color)`.
  - `Draw.Line(from, to, color)`.
  - The shapes with smooth edges (below): `Draw.Line(from, to, width, color)`, `Draw.WireRect(center, size, width, color)`, `Draw.WireCircle(center, radius, width, color)`, `Draw.Rect(center, size, rotation, color)`, `Draw.RoundRect(center, size, radius[, rotation], color)`, `Draw.WireRoundRect(center, size, radius, width, color)`, `Draw.Ellipse(center, radii[, rotation], color)`, `Draw.WireEllipse(center, radii, width, color)`, `Draw.Arc(center, radius, start, sweep, width, color)` and `Draw.Shape(shape)`.
  - `Draw.Text(text, position, size, color)`: `position` is the top left corner and `size` the font size, the height of a line of it. A newline in `text` starts another line under it.
  - `Draw.Text(text, position, size, color, anchor)`: `position` is the place of the text's box that the `Anchor` names, rather than always its top left corner. `Anchor` is the built-in enum `GUILayout.Area` takes, the nine places of Unity's `TextAnchor`, `UpperLeft` to `LowerRight`. The box is the one `Draw.MeasureText` gives: 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. Each line of a text of several is against the anchor's side: lines start at a left anchor, end at a right one, and are centered on one between. Without the argument nothing changes: `Anchor.UpperLeft` is what text has without one.
  - `Draw.Text(text, position, size, color, font)` and `Draw.Text(text, position, size, color, anchor, font)`: the `Font` the text is drawn in. `Font.Regular` is the engine's font, which text has without one; `Font.Bold` is its bold weight, a font file of its own, which a game only carries when its code says `Font.Bold`; and a game has any fonts of its own besides (agreed 2026-11-03: "yeah I want custom fonts; we should also allow multiple fonts to be used for different text on the same game of course"), as assets and decoded from bytes (see Fonts, below). The font is an argument, as a mesh's `Filter` is, since it's about one thing drawn. `target.Text` takes the same arguments for a render target. The GUI's widgets are in their theme's font (`GUITheme.font`); the stats overlay and the debug views are in the regular weight.
  - **Fonts** (agreed 2026-11-03; the owner: "yes we should allow runtime decode, we should be careful with security here"). `asset Font title = "fonts/Title.ttf";` is a font file of the game's, and `List<Font>` and `Map<string, Font>` a glob's, as any asset type's are. `Font.Decode(List<byte> bytes)` gives a `Font fails IOError` of a font file's bytes as the game runs: a player's file, or one fetched. Every font is read by the engine's own reader, which checks each place a file names before it reads it, so no file, however it's made, has the game read or write outside it. The rest are the implementation's picks, Provisional:
    - A `Font` is this machine's, as a `Texture` or a `Clip` is: local code holds one and decodes one (views, local handlers, local tasks and the functions they call), and the match can't. A font every player should see is bytes in the match, which each machine decodes.
    - What's read: TrueType outlines, in a `.ttf`, an `.otf` of TrueType outlines, or a collection's (`.ttc`) first font. An `.otf` of CFF (PostScript) outlines is refused, saying to convert it to `.ttf`. Hints and kerning aren't read: every font is fitted to pixels as the engine's is (see the renderer's notes), by its own letters' measures.
    - An asset that isn't such a font is an error at its declaration, saying why; `Font.Decode` of one fails with `IOError.InvalidData`, as does a file past the reader's limits: 64 MiB, 16,384 points in a glyph, 65,535 vertices a glyph, 4,194,304 in all, 262,144 runs of characters, parts of composite glyphs 8 deep, and 67,108,864 vertices and characters read in all.
    - A character a font has no glyph for is drawn in `Font.Regular`, and measured so.
    - The same font's bytes decoded twice are one font. A machine keeps each font it has decoded until the program ends, 1,024 of them or 512 MiB at most, past which `Font.Decode` fails.
    - `.Regular` and `.Bold` name `Font`'s two where a `Font` goes, as an enum's members do.
    - After a hot reload a decoded font is drawn in `Font.Regular` until it's decoded again; an asset's is found again.
  - What the agreed design of anchors and weights left open, picked by the implementation and not yet confirmed:
    - The regular weight has a name, `Font.Regular`, so a `Font` can be a value: a field, a local, a parameter, the result of a function. `Font` is a name of the engine's, as `Anchor` and `Filter` are, so a game can't declare its own.
    - A game carries the bold weight's file when its code names `Font.Bold` anywhere, whether or not that code ever runs.
    - A code point the bold weight has no glyph for is drawn in the regular weight, and measured as it's drawn. The bold file covers Latin, Greek and Cyrillic, with fewer letters of each than the regular one.
    - Bold is fitted to pixels by its own measures, as the regular weight is by its: its stems are a whole number of pixels thick. Under 13 of the display's pixels that's one pixel in both weights, where bold only differs in its letters' shapes and widths.
    - An `Anchor` made of a number that's none of the nine (`Anchor(40)`) is `Anchor.UpperLeft`.
    - Measuring takes no anchor: a text is as big at every one.
  - `Draw.MeasureText(text, size)` and `Draw.MeasureText(text, size, font)` draw nothing, and return a `float2`: how big `Draw.Text` would draw `text` at `size` where the call is, in `font` (`Font.Regular` without one), with the width of its widest line in `x` and the height of its lines in `y`. Both are positive and in the units the Draw calls are in: the screen's pixels on the screen, and world units under the 2D camera. It's the text's box, which an anchor names a place of: without one, the text reaches `x` to the right of its `position` and `y` below it on the screen. One line is `size` high, and each newline adds the distance from one line to the next; an empty text is still one line high. A `size` that isn't above 0 gives zero, as nothing is drawn. Text is fitted to the display's pixels, so the answer is the one for this display, this camera and this frame, to the pixel: it's measured where it's drawn rather than kept. `target.MeasureText(text, size)` and `target.MeasureText(text, size, font)` measure for a render target, through its own camera: in the units its calls are in, as the text is fitted to its image's own pixels. The name, and that it returns one `float2` rather than a width alone, are the implementation's picks, not yet confirmed.
  - `Draw.Mesh(vertices, indices)`, `Draw.Mesh(vertices, indices, texture)` and `Draw.Mesh(vertices, indices, texture, filter)`: a `List<Vertex>`, a `List<int>`, a `Grid2<Color>` and a `Filter`.
  - The other settings (see Draw settings): `Draw.Blend(mode)`, `Draw.Tint(color)`, `Draw.Transform(...)`, `Draw.Transform(transform)`, `Draw.Depth(mode)`, `Draw.Clip(rect)` and `Draw.Screen()`, each around a block, and each with its `Set` form.
  - In 3D: `Draw.SetCamera(position, rotation, fieldOfView)` and `Draw.SetCamera(transform, projection)`, or `Draw.Camera` with either around a block, and `Draw.Mesh(vertices, indices, transform)`, `Draw.Mesh(vertices, indices, transform, texture)` and `Draw.Mesh(vertices, indices, transform, texture, filter)`: a `List<Vertex3>`, a `List<int>`, a `float4x4`, a `Grid2<Color>` and a `Filter`.
  - Both forms of `Draw.Mesh` take a list of a vertex struct of the game's instead, and after their other arguments, a vert and a frag by name (GPU code, below). The struct's `position` says which: a `float2` is a 2D mesh's, drawn where its vertices are, and a `float3` a 3D mesh's, which takes a transform after its indices.
  - `Draw.Clear(color)` clears the window and its depth; clipping is controlled by `Draw.Clip` and `Draw.SetClip`.
  - `Draw.Cube(center, size[, rotation], color)`, `Draw.Sphere(center, radius, color)`, `Draw.Cylinder(center, radius, height[, rotation], color)` and `Draw.Plane(center, size[, rotation], color)` draw solid unlit meshes. Sizes and heights are full extents. A cylinder's axis is local `y`; a plane spans local `xz`. Nonpositive dimensions draw nothing. Geometry is cached by shape and color, and consecutive matching instances draw together.
  - `Draw.WorldToScreen(float2)` and `Draw.ScreenToWorld(float2)` convert with the currently selected 2D camera; on the screen (`Draw.Screen`, `Draw.SetScreen`) they are identity mappings. `Draw.WorldToScreen(float3)` and `Draw.ScreenToWorld(float3)` use the currently selected 3D camera, including custom projections. Screen `x` and `y` are top-left logical pixels, with `y` down; 3D `z` is normalized depth, 0 at the near plane and 1 at the far limit. Depth 1 for the standard infinite perspective camera has no finite world position.
  - `Draw.ScreenRayOrigin(float2)` and `Draw.ScreenRayDirection(float2)` give a picking ray from the near plane, with normalized world direction, for perspective and orthographic cameras. Device positions count from the bottom left, so they go through `Screen.Flip` first (see GUI, Provisional): `Draw.ScreenToWorld(Screen.Flip(devices.pointer.position))`. Conversion helpers use the current frame's viewport and return zero for a viewport with no size, a singular camera matrix or an undefined projection.
  - One `Draw` has every drawing function, 2D and 3D, with `Blit`, `window` and `list`, which hands the frame's draw list to an extern function; a render target has the same functions as its methods, but for `Blit`, which names its destination, and the two members. `Draw2D` and `Draw3D`, the owners there were until 2026-10-07, are errors that name `Draw`, with the rename as the editors' quick fix (decided).
  - `Draw.Instanced(vertices, indices, instances[, texture[, filter[, wrap]]...][, vert][, frag])` draws one mesh for each item in an instance list, without entities for its items, 2D or 3D by its vertices. Meshes, textures and shaders follow `Mesh`'s forms. See GPU code below for how a list item is supplied to a shader.
- **Render-target content invalidation (Decided, 2026-11-02):** a per-target content revision lets local code detect discarded pixels and rebake immediately after resize, reload or device loss. Aliases observe the same revision; normal drawing/clearing does not invalidate it.
  - **Provisional representation:** `target.contentRevision` is a read-only `long`, positive for a live managed target, zero for invalid/disposed/borrowed targets and `Draw.window`. Compare equality only. Reads in a view observe the current device and effective pixel extent before drawing, including automatic window/display resizing. The host carries revision high-water across web reload; neither reused WASM addresses nor module-local counter resets can reproduce a saved token. Exhausting positive revisions stops rather than reusing a token. GPU and parallel-worker reads are refused as live local resource metadata.
- A render target's size (above), in what the agreed design leaves open. These are the implementation's picks, not yet confirmed:
  - Sizes are numbers, not only ints, as `Screen.width` and `Screen.height` are floats: `RenderTarget(Screen.width / 4, 90.5)`. `Resize` takes them the same way.
  - A target's image has the whole number of pixels nearest its size times its scale, one at least, each way. It's then stretched over the target's size by under half a pixel, as a window's pixels are on a display with a scale that isn't whole: the size stays what was asked for, so conversions and what's drawn at the target's edges land where the size says. A `RenderTarget.Window(factor)` target has the window's own pixels times the factor, rounded the same way, so `RenderTarget.Window()` has the window's pixels exactly.
  - A width, a height, pixels per unit or a factor that isn't above 0, or isn't a number, makes an invalid target, as a default one is, with a diagnostic: drawing with it is skipped.
  - `Resize` on a target made with `RenderTarget.Window` does nothing but a diagnostic: its size is the window's to say. It can't be known when the code is checked, as a target is a value. `Resize` takes no pixels per unit: a target keeps the ones it was made with, and one that wants others is disposed of and made again.
  - No image is bigger than the GPU's largest texture a side. A target that would be, after its scale, keeps its shape with fewer pixels, the most that fit, with a diagnostic when its image is made: what's drawn into it lands where it would, less sharp.
  - A target at the display's scale takes the scale of what its frame is drawn into: the window's or, in a run with no window, the run's `--scale`. A host's C that reads pixels back from a frame of its own (`tide_platform_read_pixels`) draws it at a scale of 1, whatever the display's.
  - A target that follows the window has no pixels per unit of its own: `RenderTarget.Window(factor)` is at the display's scale. A pass that wants the same number of pixels on every display, whatever the window's size, has no form yet.
- Later Draw calls draw over earlier ones, but for 3D meshes among themselves (below), unless `Draw.Depth` says otherwise.
- `Rect`, `WireRect` and the `Line` with no width fill whole pixels, so rects side by side leave no seam and a line is a pixel wide wherever it is. `Circle` and `WireCircle` have a smooth edge, the outline a pixel wide. The other shapes are the smooth ones: a pixel is in one by how far it is from the shape's edge, which is smooth over one pixel of the screen at any size, turned any way.
  - Their lengths (sizes, radii, widths) are in the units the calls are in, as positions are: the world's under a camera, pixels on the screen. A size, radius or width that isn't above 0 draws nothing.
  - Angles are in radians, from `+x` towards `+y`: counterclockwise under a camera, where `y` goes up, and clockwise on the screen, where it goes down. A `rotation` turns a shape about its center.
  - A `radius` rounds a rect's corners, no more than half its smaller side. An ellipse's `radii` are half its width and half its height. An outline (`width`) is inside the shape's edge, no wider than half the shape's smaller side. A thick line's ends are round, and reach half its width past where it ends.
  - `Arc` is part of a ring: of the circle outline `width` thick inside `radius`, what's from the angle `start` on for `sweep`, the other way round for a sweep under 0, cut straight across at both ends. A width of the radius is a slice of a disc. A sweep of a whole turn or more is the whole ring.
  - `Shape` is a built-in struct, and `Draw.Shape(shape)` the call the others but `Arc` are short for: `float2 center`, `float2 size`, `float rotation`, `float radius`, `bool ellipse` (the ellipse that fits `size`, whatever `radius` says), `Color color = Color.white`, `Color color2 = Color.none`, `float outline`, `Color outlineColor = Color.white` and `float soft`. A game can't declare the name outside a namespace.
  - A shape's fill goes from `color` at its top to `color2` at its bottom: its own top and bottom, as it is before `rotation` turns it, the top being the upper one on the screen in the world's units and in pixels alike. `Color.none` for `color2` is one color. The colors in between are blended with their alpha in them, so a fill to a clear color fades and doesn't darken.
  - `outline` is an outline that wide in `outlineColor`, inside the edge, over the fill.
  - `soft` is how far the edge fades. Above 0, outwards: the shape is whole up to its edge, and its color goes on past it, gone `soft` further out (a glow, a shadow). Under 0, inwards: its color is at its edge and gone that far in, with the middle clear. The fade is squared, so it ends smoothly.
  - `Color.none` is a color constant with an alpha under 0, `Color(0, 0, 0, -1)`: exactly that value is none, and drawn with, it shows nothing.
  - `Draw.Shadow(Rect rect, float radius, float size[, Color color])` (Provisional, 2026-10-29): a smooth box at `rect`'s size with corners `radius`, `soft = size`, a quarter of `size` further down `y` (down the screen in pixels), black at 0.4 without a color. A size that isn't above 0 draws nothing.
  - `Math.EaseIn`, `EaseOut`, `EaseInOut` (cubic), `EaseInBack` and `EaseOutBack` (c1 1.70158) of a `float`, saturated first (NaN as 0), the same arithmetic on the CPU and the GPU (Provisional, 2026-10-29).
  - A render target's `size` (`float2`, logical pixels, the window's share for one that follows it, from its shared state so a `Resize` is seen) and `valid` (`bool`: made and not disposed, or `Draw.window`), and its `Rect(rect, radius|radii, fill)` and `Shape(shape, fill)`, drawn by the target's size (Provisional, 2026-10-29).
  - `color.WithAlpha(float alpha)` and `rect.MoveInside(Rect bounds)` (Provisional, 2026-10-29) are methods of the values, as text's are. `WithAlpha` keeps red, green and blue and works on the GPU. `MoveInside` moves, never resizes, the rect as little as it takes to be inside `bounds`; wider or taller, its left or top edge is at theirs; a number that isn't one counts as 0. `Screen.rect` is `Rect(0, 0, Screen.width, Screen.height)`.
  - `color.rgb` (a `float3`), and `rect.position`, `rect.size` and `rect.center` (each a `float2`), are read from the value's own numbers and never assigned; `rect.Contains(float2 point)` has the left and top edges in and the right and bottom ones out, as Unity's, and a point that isn't a number in nothing; `rect.Inset(float amount)` moves every edge in (out, under 0) about the same middle and never gives a negative size (Provisional, 2026-11-14). `rgb` works on the GPU; a Rect isn't a GPU value.
  - **Fills** (the owner's, 2026-10-29: "allowing a function ... and just give the 2-4 colours built-in"; the rest Provisional): `Draw.Rect(Rect rect, float radius, Func<float2, Color> fill)`, `Draw.Rect(Rect rect, float4 radii, Func<float2, Color> fill)` and `Draw.Shape(Shape shape, Func<float2, Color> fill)` color the shape with a function of the pixel's place in it, run on the GPU: `(0, 0)` at its top left and `(1, 1)` at its bottom right, as the shape is before `rotation` turns it, the top being the upper one on the screen as `color2`'s is, clamped to that range past the edge where `soft` reaches. The fill replaces `color` and `color2`; the shape's geometry, outline and soft edge are as `Shape` says, its corners and outline no more than half its smaller side. A size that isn't above 0 draws nothing. The fill's alpha is blended in premultiplied, as `color2`'s is.
    - `Gradient.Vertical`, `Gradient.Horizontal`, `Gradient.Linear(float angle, ...)` and `Gradient.Radial` return fills of two, three or four colors spread evenly: top to bottom, left to right, across at `angle` (radians from `+x` towards `+y`) corner to corner, and from the middle to the middle of the sides. An alpha out of 0 to 1 (`Color.none`'s) is the nearest in it.
    - A fill is any `Func<float2, Color>`: a named function, a lambda with captures, a field. It's GPU code, with its rules. Every fill of a game is one shader, the function's tag and captures part of each shape's instance, so fills drawn in a row are one draw. Called on the CPU it gives what the GPU would, up to rounding.
    - A `Func<float2, float2, Color>` fill (Provisional, 2026-10-29, from the showcases' gaps) is given the place and the shape's size, in the units it's drawn in: `Draw.Rect(rect, radius|radii, fill)` and `Draw.Shape(shape, fill)` take either kind, picked by the function's arguments. Both kinds are one shader.
    - Its anti-aliasing and soft edge go by the display's pixels where the shape lands, through the draw's transform and camera; in a render target the window's size is taken for it. A render target's own `Rect` and `Shape` take no fill yet.
    - The fills' types and shader are Tide code that comes with the compiler (`<tide>/draw.tide`), compiled into a game whose files, together, show a fill: `Gradient.` or `Func<float2, Color>` anywhere, or a `Draw.Rect(` or `Draw.Shape(` whose last argument is a lambda, or the name of a function declared `Color Name(float2 ...)`. A fill that's none of those (a function value of an inferred type) is an error that says to write it one of those ways. A game without one has none of it.
  - The engine's own shaders draw every shape. They take no vert and no frag.
  - Shapes of any kinds drawn one after another are one draw call.
- `Vertex` is a built-in struct: `float2 position`, `float2 uv` and `Color color = Color.white`, so a corner that leaves its color out takes the texture's as it is. `Filter` is a built-in enum, `Point`, `Bilinear`, `Trilinear` and `Anisotropic`, the first three with the values of Unity's `FilterMode` (`Trilinear` and `Anisotropic`: see Mipmaps and Anisotropic filtering). A game can't declare either name outside a namespace.
- Triangles draw whichever way round their corners go. A triangle with an index past the vertices is left out, and so are the one or two indices after the last whole triangle. Colors blend over what's behind them by their alpha. A color is written as it is, never times its alpha (see Alpha and color space).
- `uv` (0, 0) is the outer corner of the grid's cell (0, 0), and (1, 1) the outer corner of its last cell. Past them, it reads the cells at the edge.
- The GPU's copy of a texture is a byte a channel: a cell's floats are clamped to 0 to 1, and NaN is 0. Where the grid has no chunk, it's clear. A grid with an open axis has no size, so it's no texture, and the mesh draws with its colors alone. How big a texture can be is the GPU's limit, at least 2048 by 2048.
- The engine tells whether a grid's cells changed from the hashes it keeps of the grid's chunks, without reading the cells: a frame that changed nothing costs a hash per chunk. A texture no call of a frame draws with is let go, and comes back when one does.
- Views read the match's grids as they are at the latest tick: cells aren't blended.
- `[a, b, c]` where a built-in function takes a list is that list, as it is for a function's argument: `Draw.Mesh(corners, [0, 1, 2])`.
- A clip's `Rect` goes from (x, y) to (x + width, y + height) in the units the calls are in: the world's under a camera, with `y` up, and pixels on the screen. It's where it lands on the screen then, to whole pixels, and stays there when the camera changes. `Draw.Clear` fills the clip. Each frame starts with none, and a view's clip never clips the GUI.
- `Draw.SetCamera` after `Draw.SetScreen()` goes back to the world.
- 3D meshes go through a camera of their own, which the 2D one and the screen leave as it is, and the other calls go through theirs whatever the 3D camera is.
- GPU code (`frag`, `vert` and the functions they call):
  - **`color` is an `out Color`** (A frag's outputs are `out` parameters, above): it starts with no value, and a frag writes it on every path, or the frag is an error. It isn't the pixel already on the screen, which a GPU doesn't let a frag read, so `mut Color` is refused. (It started as `Color.white` until outputs became `out` parameters, 2026-10-07.)
  - `frag` and `vert` are keywords only at the start of a declaration, like `view`. They share their names with functions: a frag and a function can't have the same name. Nothing calls one, and its name is no value: `Draw.Mesh`, `Draw.Instanced`, a target's `Mesh` and `Instanced`, and `Draw.Blit` name it. `local` before one is an error, as it's local already.
  - `Draw.Mesh(vertices, indices[, texture[, filter[, wrap]]...][, vert][, frag])` draws a 2D mesh, and `Draw.Mesh(vertices, indices, transform[, texture[, filter[, wrap]]...][, vert][, frag])` a 3D one. The vertices are a list of a struct with a `position`: a `float2` makes the mesh 2D and a `float3` 3D. Its other fields are floats, ints, their vectors and colors, 12 fields at most, and the GPU reads them from the list as they are. A 3D mesh takes its transform, and a 2D one takes none. Without a frag, the first texture and its filter sample the vertex's `float2 uv`. A frag's or vert's read-only `Texture` parameters receive the draw's explicit Texture arguments, in order (Provisional: Several textures a draw gives); a frag without one samples only its component/singleton fields and assets, and rejects an explicit source. With no frag, a field named `color` has to be a `Color`. A `List<Vertex>` or a `List<Vertex3>` with neither a vert nor a frag is drawn as it was before.
  - `Draw.Instanced(vertices, indices, instances[, texture[, filter[, wrap]]...][, vert][, frag])` replaces `Draw.Mesh`'s single 3D transform with a list. A `List<T>` of an ordinary struct supplies each item to the vert or frag's read-only `T` parameter after its vertex (and a frag's color); either stage can take it, or both. A `List<float4x4>` supplies transforms for a 3D mesh. The instance parameter's type is the list's element type; a struct parameter of another type is the draw's values (above), or an error at the draw. `Mesh` supplies no instance parameter. Other component and singleton parameters bind as before.
  - A 3D instance struct's field named `transform`, when present, is a `float4x4`, applied by the engine and available as `Instance.transform`; without one, the transform is identity. A 2D instance list holds ordinary structs, whose fields a vert can use to place the vertices. Their `transform` field is ordinary data, not applied by the engine, and `Instance.transform` is identity. Only fields the shaders read go to the GPU, plus a 3D transform; unread fields can have types the GPU cannot use. Reading a field or passing the instance whole follows the same rules as component reads. An empty instance list records nothing. Items draw in list order, in one instanced run, which adjacent compatible mesh draws can join.
  - A synchronous drawing function can name a vert or frag in mesh, instanced, skinned and blit draws, using the view's frame and ordinary drawing capabilities. Each component or singleton the shader takes must match exactly one explicit non-`out` parameter of the function by type; no entity or singleton is looked up implicitly. Read-only parameters supply their passed value, and `mut` parameters their current value. Shader reads of attached local fields require the caller's actual bound parameter and forward its local sidecar through helper chains, as ordinary local-field helpers do. Missing or ambiguous inputs are errors; a draw's explicit texture, values and instance list retain their existing rules. Methods and tasks retain their existing drawing restrictions.
  - The view needn't take what its frags and verts read: `with Box` is enough for a frag that reads `Box`, and a singleton needs no mention. The engine hands them over as it does the view's own parameters, blended between ticks the same way, and a view whose frag reads the match doesn't run outside a match. What the view does take is sent as the view has it when it draws.
  - Only the fields the code reads are sent: a component's with each instance, and a singleton's once for the draw. Reading a parameter whole, as a value passed on, sends all of its fields.
  - A `local` field of the match's component or singleton (see Local state) is read like any other field of it: what this machine keeps for the entity being drawn, or the field's default where nothing was written.
  - A frag or vert takes no `World`: the GPU is sent the components of the entity being drawn, and the view copies what it needs of others into a component of it or a singleton.
  - **`this` is the pixel a frag runs for** (agreed 2026-10-07), without a parameter: `this.position`, a `float2` in the screen's logical pixels from the top left, as `Draw.Screen`'s; `this.depth`, a `float` from 0 at the camera's near side to 1; and `this.world`, a `float3`, where on the mesh it is in the world: the vertex's position after the vert, through the draw's transform, blended. A 2D mesh's is its position in the units it's drawn in, with `z` 0. These fields are read-only, and the whole pixel context can't be copied, stored or passed: `this` is accessed through its fields and `Discard()`. A vert has no pixel yet: its `this` is its vertex as the engine would place it, with `this.clip` alone (Where a vert puts its vertex, above). Ordinary functions a frag or a vert calls have no implicit `this`: pass the coordinates they need as ordinary values.
  - **`Instance instance`** (to confirm) is a parameter a frag or a vert can take: `instance.transform` is the `float4x4` the draw was given, and the identity for a 2D mesh.
  - **`instance.Normal(normal)`** (agreed 2026-10-08, of three ways offered: a member of `Instance`, over a `Math` function of any matrix and a normal matrix the engine would supply beside the transform) gives a normal of the mesh, a `float3` of any length, as it is in the world, in the vert or in the frag: `float3 normal = instance.Normal(vertex.normal);`. It's right whatever the draw's transform scales the mesh by. `Math.Rotate(instance.transform, normal)` turns a direction, which is the same thing only for a mesh scaled as much every way: on a ball drawn as an egg, or a cylinder as a flat disc, it leans normals the wrong way. Provisional, Claude's picks:
    - The result is of length 1, and zero for a normal of no length, as `Math.Normalize`'s is.
    - A mesh that a scale under 0 turns inside out has its normals pointing out of it.
    - A mesh flattened to nothing along an axis, whose transform has no inverse, has that axis for its normals, each to the side it leaned.
    - A 2D mesh has no transform: its normal comes back as it is, of length 1.
    - It goes by the draw's transform (through `Draw.Transform`, as `instance.transform` is), and nothing else: a vert that moves its vertices itself works out its own normals.
    - Nothing is sent for it. The GPU works it out from the transform that's sent already (the cross products of its columns, once a vertex, and no inverse), so it costs an instance no bytes, and a pixel less than `Math.Rotate` does. A frag that calls it counts three more of the values a draw's pixels read from the mesh's corners.
    - `Instance` has no other method, and a call of another name is an error that names this one.
  - `Instance` is built in only as a frag's or vert's parameter type. A game that declares a type of its own named `Instance` or `Pixel` gets its own there. An old built-in `Pixel pixel` parameter is an error that says to remove the parameter and use `this`.
  - The camera isn't given: a game keeps where its camera is in its own state, which a frag takes like any singleton.
  - **`this.Discard()`** leaves the pixel undrawn, with no color, depth or stencil written, and ends the frag there. It's a statement of its own, in the frag itself. A discarded path owes its `out` parameters nothing.
  - `source.Sample(uv[, filter[, wrap]])` reads a `Texture`, `Grid2<Color>` or `Grid2<float>` field of a component/singleton parameter, an asset by its name, or a direct read-only `Texture` parameter. `Filter.Bilinear` blends between pixels, `Filter.Point` reads the nearest and `Filter.Trilinear` blends between the texture's smaller images too (see Mipmaps, above, for what its `uv` can be); one that's left out is the texture's own (see Textures, above). A filter and a wrap that are said are written there: the GPU is told how the texture is read before any pixel runs. UVs go from (0, 0) at the top-left outer corner to (1, 1) past the bottom-right pixel, and what's past them is the wrap's to say: the pixels at the edge without one (see `Wrap`, above). A grid with no size samples white. Verts sample too.
  - What the GPU runs: bools, ints, floats, vectors, matrices, colors, enums, and structs of those; locals; `if`; `?:` (between structs, matrices and arrays too, since 2026-10-08, where it's a function of the engine's own for the type in the shader: both sides are worked out, as WGSL's `select` works out a number's); `for` loops that count (a variable of the loop's own, compared with a bound, that only its step changes), with `break` and `continue`; `return;`; the game's functions, methods and operators; `Math`, and the math types with what builds them (next); constructors, constants and `default`. `Random`'s rolls on the type and `Random.seed` (see Random numbers: a generator of the pixel's or the vertex's own, with 32 bits of state). No `Random` value: its state is 64 bits, and a frag or vert that makes one, takes one or rolls with one is an error that says to roll on the type.
  - **Everything in `Math` is on the GPU unless it makes no sense there**, and so are the types it works on and what builds them: vectors, quaternions and matrices, every `Math` function on them (`Math.Hash`, the noise, `Math.Perlin`, `Simplex` and `Cellular`, whose cells are the CPU's, the quaternions' `Mul`, `Rotate`, `Inverse`, `Conjugate`, `Normalize`, `Dot`, `Slerp`, `Nlerp`, `Forward`, `Up`, `Right` and `Angle`, the matrices' `Inverse` and `Determinant`), `quaternion.AxisAngle`, `Euler`, `LookRotation` and `FromToRotation`, `float4x4.TRS`, `Translate`, `Scale`, `PerspectiveFov` and `Ortho`, and the constructors between quaternions and matrices. What's left out is left out for a reason, which its error says with what to write instead. There's one: `Math.Hash` of a `long`, as these GPUs have no 64-bit integers, so no `long` gets there. `Math.Hash(int2(int(x), int(x >> 32)))` is the same number as `Math.Hash(x)`, from halves the CPU split.
    - `Math.Hash` gives exactly the CPU's number there: it's integer math, which wraps the same in every shader language.
    - What works on floats follows the CPU's formulas (`tide/math.h`'s, in its order, so the same handedness and argument order) with the GPU's rounding, which differs between GPUs and from the CPU, most for big arguments: the sine of a number in the thousands is no number to build on.
    - It's forgiving as on the CPU. `Math.Normalize` gives zero for a vector too short to normalize, and the identity for a quaternion. `Math.Min` and `Math.Max` with one NaN give the other. `Math.Clamp` and `Math.Saturate` always give a value in range: its lower bound for NaN, and for bounds the wrong way around. A shader's compiler may reckon without NaN, so these tell one by its bits.
    - It gives a number wherever the CPU does, which the shader languages' own functions leave open: `Math.Pow` of a number under 0 to a whole power, and of anything to the power of 0, which is 1; `Math.Atan2(0, 0)`, which is 0; `Math.SmoothStep` with its edges the wrong way around, or at the same place; `Math.Inverse` of a matrix, which one of the languages has no function for. Where the CPU gives no number (NaN or an infinity: `Sqrt` and `Log` of a number under 0, `Asin` and `Acos` outside -1 to 1, `Pow` of a number under 0 to a power that isn't whole, the inverse of a matrix that has none), the GPU gives whatever it gives.
  - `switch` on an int, a char or an enum, as each shader language has its own.
  - **Lists and arrays on the GPU** (the owner, 2026-10-08: "sending collections to GPU side; and in general trying to make anything that is possible on there too to close the gap", and of how a list travels, that a fixed size "is the annoying part"). That lists get there, with no fixed size, and on every backend there is, is the owner's; each rule here is Claude's pick, Provisional.
    - A list that's a field of a component, a singleton or a draw's values, or a `List<byte>` asset by its name, is read in a frag or a vert: `items[i]`, `items.count` and `foreach (var item in items)`. An element past its ends is zeros. Its elements are what the GPU has values of, bytes and arrays among them; not `long`, text, entities or containers.
    - A grid that's such a field, or an asset by its name, is read a cell at a time: `cells[x, y]`, `cells[at]` and `cells.size` for a `Grid2`, `cells[x, y, z]`, `cells[at]` for an `int3` and a `size` of three for a `Grid3`; the cell as the grid has it, of any type the GPU has values of; zeros outside it and where nothing was set. It's another of the draw's textures than the same grid sampled.
    - A grid with no size on an axis is read the same way (2026-10-08, to close what was a silent difference: the GPU read zeros where the CPU read the cells): cells at any place an int says, before 0 too, and `size` 0 on that axis, as on the CPU.
    - What's sent of a grid is the box its chunks take up, within its size, as one image of numbers; a `Grid3`'s layers are side by side in it. A box whose image would be more than 16,384 pixels a side or 16,777,216 in all isn't sent: the code reads zeros, and a line on stderr says so once. Within 2,048 pixels a side, which every backend has, are 256 by 256 by 256 cells of one number each and 128 by 128 by 128 colors.
    - `byte` is there (the owner, 2026-10-08: "`List<byte>` why?"): an int from 0 to 255, which `byte(x)` and a compound assignment keep to its low 8 bits, as on the CPU.
    - `while`, and a `for` of any shape, are there (the owner, 2026-10-08: "`while` can run forever but so can a stupid for loop"). Nothing bounds a loop.
    - The owner's rule for all of it (2026-10-08): "i want GPU code to be as close to non GPU code". What's refused there is refused because a GPU can't, and its error says why.
    - It's read-only.
    - **A list or a grid has other names there: a local, and a function's or a method's parameter** (built 2026-10-08, from the rule above; every rule is Claude's pick, Provisional). Which list or grid a name stands for is known as the shader is written, never as it runs: neither GLSL ES 3 nor WGSL hands a texture to a function on every backend, so a function that takes one is written once for each list or grid it's called with, and takes nothing for it.
      - `var items = lights.items;` names a field of what the frag or vert takes, an asset, another such local or a parameter. It isn't `mut`, and it isn't a list that's picked or made as the code runs (`flag ? a : b`, a function's result, a literal): an error that says a list there is one the code was given, by a name.
      - `float Sum(List<float> numbers)` is the function the CPU's code calls too. On the GPU its argument is such a name, and the parameter isn't `mut` or `out`. A function passes its own on.
      - `int Cell(Grid2<int> cells, int2 at)`: a function or a method takes a grid, to read `cells[x, y]` and `cells.size`. Such helpers are callable from shader code and local workers; worker-reachable helpers also have CPU bodies over captured grid inputs. A direct call from an ordinary system, view or handler remains an error that says to read cells through their component or singleton. Its grid parameter takes no `mut`, `out` or default, and an operator, an extern, an async function and one that takes an Action take none. A grid alias local is supported only along the shader path; a worker and its helpers read or forward parameters directly, without grid locals.
      - An asset's list or grid is read by its name in a function a frag or vert calls, too.
      - A function still returns no list and no grid, and a struct that holds one isn't a value there.
    - **A struct, a singleton or a component that holds a list is passed on whole** (2026-10-31; the owner, of a game passing every list of a crowd's poses by name through every helper: "ideally we lift that limit instead of working around it"; every rule is Claude's pick, Provisional). A function or method takes one, and its methods are called on it, when it's the one the frag or vert was given, by its name: its own parameter (the draw's values, a singleton, a component) or a function's parameter that stands for one. Nothing is handed to the function for it: its plain fields read where the frag or vert reads them, its lists, grids, maps and sets are the frag's or vert's textures of numbers, and only what some code reads is sent. It's read-only (`mut` methods and parameters are errors), and it isn't kept in a local, made, returned or picked between there. A singleton or a component that holds a texture goes the same way since 2026-11-14 (A function samples the textures of a singleton or a component it's handed, below), and since then a function that reads a component's plain fields this way from a vert and a frag of one draw is written for each stage, which have them in different places (before, the frag's read the vert's, and got zeros). Not built: one that's a field of another (`keep.poses.rows` in a frag).
    - **A function samples the textures it takes** (built 2026-10-08. The owner asked that a function only GPU code calls take a `DepthTexture` and call `Sample` and `Compare` on it, and the same for a `Texture`, with a call from the CPU an error that says so, after Tag's and Sumo's frags each carried a copy of one shadow lookup; a `Cubemap` and a grid by the same rule, and every other rule here, are Claude's picks, Provisional).
      - `float Lit(DepthTexture shadow, float3 at)`, `Color Tile(Texture image, float2 uv)`, `Color Above(Cubemap sky, float3 way)`: a function or a method reads a texture parameter as a frag reads a field, `Sample` with a filter and a wrap or without, a depth's `Compare`, a cube's `Sample(direction)`. A `Grid2<Color>` or `Grid2<float>` parameter is sampled too, and goes where a `Texture` parameter is.
      - The call names the texture: a field of a component or a singleton the frag or vert takes, its own `Texture`, an asset, or in a function, a parameter of its own, which it passes on. One that's picked or made as the code runs (`flag ? a : b`, a function's result) is an error that says a texture there is one the frag or vert was given, by a name. Which texture it is is known as the shader is written, so the function is written once for each texture it's called with and takes nothing for it, as for a list.
      - What a `Sample` there leaves out is the texture's own, as in a frag: its declaration's for a grid's field or an asset, and for a `Texture` field or the frag's own `Texture`, whatever the texture it holds says. Each texture is one of the draw's 16 textures, however it's read, and each way it's read takes one of its 16 samplers.
      - A function samples its own parameter, an asset by its name, or a texture field of a singleton or a component it takes (below). A texture in a plain struct the function takes is an error that says to take the component or singleton, or the texture itself: a struct with a texture in it is no value on the GPU.
      - **A function samples the textures of a singleton or a component it's handed** (approved 2026-11-14, the owner: "go with your recommendations", after Mount & Rifle passed `stage.shadow, stage.closeShadow, stage.farShadow, stage.canopy, stage.sky` at about 115 call sites; every rule is Claude's pick, Provisional). `float3 Sunlit(Stage stage, float3 world)` samples `stage.shadow` and `stage.sky` as the frag would; a method of the singleton samples its own fields by their names (`sky.Sample(way)`) and calls its other methods on the same one. It's the rule of a struct that holds a list, below, for textures: the singleton or component is the frag's or vert's own, by its name (its own parameter, or a function's that stands for one), nothing is passed for it, each of its textures is one of the shader's by its type and its field, and the function is written once however many calls it has (for each stage that reads it differently: a component's plain fields are the vertex's attributes in a vert and what the vertex stage passes on in a frag, so a function reading them from both is written for each). All a function does with a texture parameter it does with such a field: every read (`Sample`, `SampleLevel`, `SampleGrad`, `Compare`, a cube's, a depth cube's, an array's, a volume's), `.size`, a kernel helper's image store, and passing it on to a function that takes the texture, or the whole singleton on to another. A component's textures and fields are each entity's, and local fields are read so too: a frag or vert hands such a function the local fields it reads (a function given them from a frag was an error before). One that holds no texture and no list still goes as a value of its match fields, so a function reading its local fields from a frag or vert is still an error, which now says to read the field in the frag and pass what it holds (making that the same for every type is Open, at the end of Views and drawing). A copy in a local, a struct literal or a result is an error that says it holds a texture, in a frag as in a function, but for a match component or singleton whose textures are all `local` fields: that's a value of its other fields, as it was (with none of its textures, and passed nowhere it goes by its name). A texture of a struct the singleton holds (`stage.lamps.shadow`) isn't built: an error that says to make it a field of the singleton itself.
      - **Such a function, and one that calls it, is the GPU's alone**: no C is written for it, and a call from a system, a view or a handler is an error that says so ("'Lit' reads a render target's depth, which only code the GPU runs does"), with where it reads it. A function that takes a texture and samples none is still everyone's: the CPU's hands it on (to C, say), and the GPU's is written with nothing for it. An operator, an extern, an async function, an `audio` declaration and a function that takes an Action sample nothing, as they take no grid.
      - A texture parameter that's sampled takes no `mut` or `out`; none is returned, kept in a local or in a struct.
      - **A function's `Sample` reads the texture's own pixels, never between its smaller images.** A frag asks how fast a `uv` changes as it starts, of a `uv` it can work out there, and a function's `uv` is its call's. So in what a frag reaches, a `Sample` in a function that says `Filter.Trilinear`, or leaves its filter to a texture whose declaration says it, is an error, and one that leaves it to a `Texture` that may say it, in a game that names `Filter.Trilinear`, is a warning, said once: what a frag's own `Sample` gets for a `uv` it can't work out as it starts. `Texture.SampleGrad` instead accepts explicit numeric derivatives and can read mipmaps through these helpers (Mipmaps, above). A vert has no pixels to compare, there or in a function. Argued against reading blended without a word: a texture that shimmers is found late.
      - A `[Raw]` texture may be read by name or passed through a read-only GPU `Texture` helper parameter. Specialization retains the original asset/grid/field role, so its sample does not divide by alpha. This grants no ordinary CPU Texture argument or mutable/out permission; a `[Raw] Texture` parameter (CPU or GPU) takes one explicitly, and a frag's `[Raw] Texture` source reads the image its draw gives as numbers.
      - A grid parameter is one of the draw's textures of numbers whether the function reads its cells or not, as it was, and another where it's sampled: a function that only samples takes a `Texture`.
      - Not there: a texture's local (`var shadow = lamp.shadow;`), and `Filter.Trilinear` through a function, which would take working the `uv` out at the frag's start from the call's arguments.
    - No size is declared, and none is fixed: a list is sent as it is that frame, up to 2,097,152 pixels of four numbers each (an element of one or two numbers shares a pixel with the next; a bigger one takes whole pixels), and elements past that aren't sent.
    - Each list a draw reads counts as one of its 16 textures, and its count is among the draw's values. A list that didn't change isn't sent again.
    - **What's sent is what's read, and what changed** (built 2026-10-08; the owner: "only sending data that we actually use vs the entire thing, or upload only what changes"; each rule is Claude's pick, Provisional).
      - Of an element (a list's, a grid's cell, a map's value), the parts that some frag or vert of the game reads are sent, and no others. A part is a struct's field, a struct's own fields each apart, and anything else whole (a vector, a matrix, an array). It's one layout for the game, the parts any of its code reads, so every draw that reads the list shares one texture.
      - A part is read by a chain of fields (`lights[i].notch.deep`), through a `foreach`'s variable, and through a local that isn't `mut` and holds an element or a part of one (`var light = lights[i];`, `var notch = light.notch;`), by what the code then reads of the local. Anything else that takes an element reads all of it: an argument, a result, an operator, a `mut` local, `TryGet`'s `out` value. A function that takes a list reads of each list it's called with what it reads of its parameter.
      - A map's key is always sent. A list that's only counted, and a grid only asked its size, send nothing.
      - What isn't sent is zeros in the shader, which nothing reads, so no code can tell.
      - Of a list or a grid that changed, the elements and cells that changed are sent, to the element and the cell, and the rest stay as the GPU has them. A list's count that shrinks sends zeros over what's gone. A grid that's a texture (sampled) is sent the same way, the pixels of the cells that changed.
      - A list made along the way (a draw's values' `[a, b]`) is by what's in it, as before: another content is another texture, sent whole.
    - A component's list is its entity's, so each such entity is a draw of its own. An instance struct's list that the code reads is an error at the draw.
    - A fixed-length array is a value on the GPU as a struct is: a field that's sent with what else the code reads (its elements' numbers, among a draw's 3,984 bytes in 2D or 3,968 in 3D, or an instance's 16 values), a local, a parameter, a result, an array literal. `a[i]` past its ends is zeros, `a[i] = v` there does nothing, `a.count`, `foreach`. An array of arrays is a value the same way (2026-10-08, by the owner's rule that GPU code refuses only what a GPU can't do; how is Claude's pick): `float[4][8]`, each index checked by itself, so a read past either end is zeros and a write there does nothing, and `rows[i]` is a row like any array. A `for`'s step that writes an element runs after each round, a `continue`'s too. None in what a vert hands its frag or in a vertex. Not there, as on the CPU, where the checker refuses them: `==` between arrays, and an array's element as a `mut` argument.
    - **Maps and sets** (built 2026-10-08, asked for as read-only maps and sets on the GPU for a field of a component, a singleton or a draw's values; each rule is Claude's pick, Provisional). A `Map<K, V>` or a `Set<K>` that's such a field is read in a frag or a vert as it's read anywhere: `map[key]` (zeros for a key that isn't there), `Has(key)`, `map.TryGet(key, out value)` (the value type's default for a key that isn't there), `count`, and `foreach`, a map's entries with `key` and `value` and a set's keys, in the order the keys were added, without the removed ones.
      - Keys there are `int`, `byte`, `char` and enums: the keys the CPU has that the GPU has values of. Text, `long`, `Entity` and `PlayerID` keys are an error where the map is read, which says which and why.
      - Values are what a list's elements can be.
      - A local names one and a function takes one as a list's does, by the same rules: no `mut`, none made, returned or picked as the code runs.
      - Read-only. `Add`, `Remove`, `Clear` and assigning `map[key]` are errors, and so is `Get`, whose `V?` the GPU has none of.
      - `TryGet`'s `out` argument is a whole local there (`out var value`, or a variable), not a field of one: a pick, as WGSL hands a function a pointer to a whole variable.
      - It's one of the draw's 16 textures, and two of its values (how many entries, and how many slots its index has). What's sent is the live entries, in order, and an index made for the GPU: a lookup hashes the key with `Math.Hash`, which is the same number on the CPU and the GPU, and probes. Not the CPU's own index, whose hash is of 64 bits, which these GPUs can't compute; the answers are the same, as keys are compared by their bits on both.
      - A map that didn't change isn't sent again. One that changed is made again whole, as a key that's added or removed moves what's after it, and the rows of its texture that came out otherwise are sent.
    - Not built: a list, a map or a grid as a function's result, a `mut` local, or one picked as the code runs; `Sample` of a grid or a texture through a local; a glob's list of assets, and an asset's text; a grid's local in a function that takes no grid; a map's `Get`, and `TryGet` into a field; `foreach` over a grid's cells (on the CPU a grid with an open axis goes through the chunks it has, which the GPU isn't told); storage buffers where a backend has them (Vulkan and WebGPU do).
  - Never there: making or changing a list, a map or a set, maps and sets keyed by text, longs, entities or players, text, entities and players, `long`, `Rect`, spawning, sending and the other changes to the world, `Draw`, the GUI, `Screen`, `Devices`, `Cursor`, `Frame`, `Debug`, C, tasks, errors and `T?`, recursion, and grids used any other way than sampled. A frag's `this` is its pixel; verts and ordinary functions have no `this`. Each unavailable feature is an error where it's written, which says what to do instead, and for code in a function, which frag or vert reaches it. Bytes and longs should be converted to an `int` or `float` in local code before being supplied to a shader.
  - A function a frag or vert calls takes `mut` and `out` parameters as anywhere, and a call that changes a variable that isn't a whole one (a field, a swizzle) is a statement of its own there.
  - A frag reads an int field of its vertex as the triangle's first corner has it, unblended (Integral handed fields, above); a vert reads its own vertex's.
  - What a GPU takes, on every backend, is checked at the draw, which says what the draw reads and what to do about it: 16 values for each vertex (each field of the vertex struct, 4 for a 3D mesh's transform, and one for every 4 floats or 4 ints the code reads of components and an explicit instance struct); 15 values from the mesh's corners to its pixels (each field of the vertex the frag reads, the pixel's place in the world, and one for every 4 floats or 4 ints the frag reads of components and an explicit instance struct); 3984 bytes of singletons' fields for a 2D draw or 3968 for a 3D draw; and 16 textures and 16 samplers, a texture counting once however it's read and each way of reading it taking a sampler.
  - Instances of one mesh drawn in a row through the same vert and frag, with the same singletons' values and the same grids, are one draw.
  - A function both the CPU and the GPU run compiles for both.
  - `tide shaders` (`tidec --shaders`) prints each shader, as WGSL (tidec wrote GLSL too until the GL backends went, 2026-11-05). No game sees a shader compiler's error: what tidec writes always compiles.
- Colors: `+`, `-` and `*` between two colors work channel by channel, alpha too, and a color times a number, or divided by one, scales every channel. `==` and `!=` compare two colors whole, every channel and alpha (Vector math).
- `Draw.SetCamera(position, rotation, fieldOfView)` (and `Draw.Camera` with the same, around a block) is a perspective camera: at `position`, looking along `rotation`'s `+z` with its `+x` to the right of the screen and `+y` up, as Unity's, and seeing `fieldOfView` degrees up and down (clamped to 0.00001 to 179, as Unity does), as much across as the screen's shape gives. It sees from 0.3 units in front of it on, as Unity's cameras, and has no far side, which costs depth precision next to nothing. Each frame starts with one at the origin, looking along `+z`, with 60 degrees.
- `Draw.SetCamera(transform, projection)` is any camera: `transform` places it in the world, looking along its `+z`, and `projection` takes what it sees, looking down `-z` (OpenGL's and Unity's view space), to clip space, the screen's shape included. `Screen.width / Screen.height` is the shape.
- `Vertex3` is a built-in struct: `float3 position`, `float2 uv` and `Color color = Color.white`. A game can't declare the name outside a namespace.
- 3D meshes are the only calls that have depth. Unless `Draw.Depth` says otherwise (see Draw settings), they read and write it: they hide each other by how far they are, whatever their order, and a see-through one blends with what's behind it and writes depth like any other. Every other call draws over what's there, in order. `Draw.Clear` clears depth too, within the clip. Textures and filters are as a mesh's, and there's no lighting. Unlike a 2D mesh's, a triangle is drawn from its front alone, unless `Draw.Cull` says otherwise (see Draw settings).
- A 3D mesh is its two lists. The engine keeps a copy of each it draws, on the GPU too, and only copies it again when it changed: a world's list tells from the hashes its heap keeps of its pages (a list in chunks, of each chunk's), so drawing one that didn't change costs a hash for each of its pages; a list made along the way is read. A mesh no call of a frame draws is let go. A mesh that changed is another copy, so what a frame drew before it changed stays as it was.
- Instances of one 3D mesh drawn in a row, with the same texture and filter and nothing between them, are one draw: a view that runs for each entity and draws one mesh draws them all at once. Lists made along the way are the same mesh when they hold the same.
- `Color` is a built-in value type with `r`, `g`, `b` and `a`, floats from 0 to 1, as in Unity. Its constructor takes any mix of numeric scalars and vectors totaling 3 or 4 components, in order: `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)` supply it. Ints and int vectors widen to floats, and each argument is evaluated once, left to right. The constants are `Color.white`, `black`, `red`, `green`, `blue`, `yellow`, `cyan`, `magenta`, `gray` and `clear`, with Unity's values and names, and `Color.none`, Tide's own: no color, where one can be left out (see the smooth shapes, above). Components and singletons can hold colors, and colors add, subtract, multiply and scale (below).
- Text is written in double quotes, with the escapes `\"`, `\\` and `\n`. Its type is `string` (see Text).
- Blending: a view's match components and singletons are copies, their fields that blend set between last tick's value and this tick's, as far as this moment is between the two ticks. Their local fields aren't part of the copy: a view reads and writes those where they are (see Local state). Vectors, matrices, colors and rects blend component by component, quaternions the short way round (normalized), and structs field by field. An entity that wasn't there last tick is drawn as it is. Local state isn't blended: it's this machine's, as it is.
- `[Snap]` goes on floats, vectors, quaternions, colors and rects of components, singletons and structs; on anything else it's an error that says why.
- `entity.Snap()` is recorded and applied at the end of the tick, like `Destroy`, so it never makes systems wait. Each entity counts its snaps, and views only blend it between two ticks with the same count. `singleton.Snap()` needs the singleton as a `mut` parameter. Local state is never blended, so snapping it is an error, and so is `component.Snap()`, which says to snap the entity. `component.field.Snap()` snaps that field alone (see Views and drawing).
- `Interpolate` isn't for code to call. Custom `Interpolate` belongs to structs and components. A singleton uses it through a struct field, while its ordinary methods follow the same read-only/`mut` receiver rules as other types. A `[Snap]` field of such a type is still drawn as it is.
- Hosts pass the two ticks and how far between them this moment is to `tide_frame`, with the last world the server confirmed; sessions work those out (`tide_session_view`).
- The cursor's lock:
  - **`Cursor.locked` is read in the input's `Sample` too** (proposed, not yet agreed), so a game looks only while the lock holds without a frame's delay: `if (Cursor.locked) look = devices.mouse.delta * 0.003;`. `Sample` reads it of the devices it samples, so it can't call `Cursor.Lock()`, and neither `Sanitize` nor `Predict` can read it, as it can't read `Devices`. A function `Sample` calls can't either: it's passed what it needs.
  - Where neither goes, the error says where it does: the match is told that a view calls `Cursor.Lock()` and that `Sample` reads `Cursor.locked`; a task, a method and a local handler, that views ask every frame. `Cursor.Unlock()` is told that the cursor comes back once no view asks.
  - A function that uses `Cursor` needs the frame, like one that draws: views and the functions they call can call it.
  - While a modal is up (`GUILayout.Modal`), the lock isn't asked for, whatever views ask: its widgets need the pointer. It's asked for again once the modal closes.
  - A finger isn't the mouse: it presses the widgets it touches while the mouse's cursor is locked.
  - A mouse button still held as the cursor comes back (the browser took the lock at Escape while the player fired) was pressed for the game: it presses no widget, and letting it go on one is no click.
  - `Cursor` is built into the language, as `Screen` and `GUI` are: a game can't declare the name, in a namespace or outside one.
  - On the web, Escape never asks for the lock again, nor does a held key repeating. The page asks for the mouse's own movement (`unadjustedMovement`) and, where the system has none, for the usual kind. A lock the browser gives after the game stopped wanting it is let go at once. On desktop, the mouse's own movement is GLFW's raw motion, where the system supports it.
  - While it's locked, the position that stays is where the cursor was when it was locked, and the cursor comes back there.
  - Hosts pass the frame's ask on with `tide_platform_cursor_lock(tide_gui_cursor_lock(gui))`, after `tide_gui_end`, and `tide_platform_poll` says whether the window holds the cursor: `tide_devices.mouse.locked`, which `Cursor.locked` reads, in views of the frame's devices and in `Sample` of the ones it samples.

```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);
}
```

<a id="open-19"></a>

### Open

- Drawing from systems, with the prediction stage (verified, predicted, replayed) visible to the code.
- `verified World`: the confirmed world's other entities, by their handles.
- Queries in local code: `with ownership` in a query; a local handler's match rows as each event's turn left things, where they're the tick's once it's done. Attached local-field reads and mutable bindings are decided above.
- Views reading input, for example to draw where the local player aims before the tick runs.
- GPU code: the camera without explicit parameters. Numeric outputs, triangle side and compute are built; their rules are above and in Compute on the GPU.
- A blend for each of a frag's outputs (WebGPU has one per color target; the GL backends that had one a draw are gone).
- A `DepthTexture` as a draw's own source, for a pass over the screen that reads a scene's depth with no singleton between.
- A function a frag or vert calls reading the local plain fields of a component or singleton that holds no texture and no list (Provisional: A function samples the textures of a singleton or a component it's handed). Today it's an error, and works once the type holds a local texture or a list, because then the type goes to the function by its name, and otherwise as a value of its match fields, which has no local ones. Ways to make it the same for every type: such a type goes by its name once some function GPU code calls reads its local fields; or every component and singleton with local fields goes by its name (then a copy, a literal or a result of one in GPU code is an error, which games have today); or the value carries the local fields a function reads.
- The cameras' matrices (see Provisional, The cameras as matrices): a camera's matrix in code the GPU runs with nothing handed over (`pixel` or a built-in for the draw's own camera); the inverses, from clip space back to the world; whether a 2D camera should also give a `float4x4` to clip space, for a 2D shader's own arithmetic.
- 3D: meshes in the grid's chunks, for voxels.
- The cursor: hiding it without locking it, keeping it in the window without hiding it, and images for it; its lock on Android.
- Layers.
- Textures: a pixel of a byte a channel, a quarter of a `Color`'s memory; sending only the part that changed. Pixels from image files are assets (see Assets).

<a id="compute-on-the-gpu"></a>

## Compute on the GPU

<a id="decided-image-writes-and-volumes-2026-11-13"></a>

### Decided: image writes and volumes (2026-11-13)

The owner approved these rules: "these make sense, lets do all of these".

- A kernel writes an image with `image[at] = value`, as it writes a GPU list. `image` is a render target's image
  with an `int2` place, or a `Texture3D` with an `int3` place. Writing needs no `mut`. A write outside the image goes nowhere.
- `Texture3D` is made in local code with a size and a format. It is machine-local, never match state, as
  `RenderTarget` and `GPUList` are. `Sample` takes a `float3` and blends on all three axes. Kernels write it.
- A `Grid3<Color>` or `Grid3<float>` converts to a `Texture3D` wherever its two-dimensional counterpart converts to a `Texture`.
- **Not there:** a frag drawing into a slice of a volume.

<a id="provisional-image-writes-and-volumes"></a>

### Provisional: image writes and volumes

These are implementation picks, rather than additional owner decisions.

- **Making and owning:** `Texture3D(int3 size[, Format format])`, default `Format.Rgba8`; `Resize(int3 size)`,
  `Dispose()`, `size` (`int3`) and `contentRevision` (`long`). Size is in texels, independent of display scale.
  Copies share the resource and follow resize and disposal. An `int3` was chosen over three scalar dimensions
  to match dispatch and grid sizes; explicit texels over a render target's logical pixels because a volume has no display scale.
- **Sampling:** `Sample(float3 uv[, Filter filter[, Wrap wrap]])`, Bilinear and Clamp by default. Bilinear blends
  the eight neighboring cells, with Point for an exact nearest cell. Clamp, Repeat and Mirror apply on all axes.
  There are no volume mipmaps, and no `SampleLevel`, Trilinear or Anisotropic volume filtering: a full chain and
  its three-dimensional downsampling were weighed against a predictable base-level image for simulation and lookup data.
  A typed `[Raw(float)]`, `[Raw(float2)]` or `[Raw(float4)]` volume reads its nearest cell where no filter is named,
  as a typed `Texture` does, and blends with `Filter.Bilinear` (Provisional, Claude, 2026-11-14, under Portable
  filtering): an `Rgba16f` volume and a `Grid3<float>`'s through the GPU's sampler, an `R32f` or `Rgba32f` one as its
  eight cells loaded exactly and blended in the shader. A `[Raw(int)]` volume reads its nearest cell alone.
- **Exact cells:** `volume[int3 at]` reads a `Color`, or a typed Raw field's float/float2/float4/int, in GPU code, zeros outside. It accompanies continuous
  `Sample` rather than forcing callers to reconstruct cell-center normalized coordinates. A float grid's ordinary volume
  reads its value as red, zero green and blue and alpha one.
- **Portable access:** a kernel that writes an image cannot sample or load it in that run, whichever way it reads
  it (a typed `[Raw(T)]` exact-cell read or Sample too, itself or through a helper). Use a second image
  and alternate them between runs. Read-write storage, even on a format that offers it, was rejected because
  the core formats supporting it differ across targets. Runtime aliases through different fields are checked too.
- **Formats:** writes accept Rgba8, Rgba16f, R32f, Rgba32f and R32i. R8/Rg8/R16f/Rg16f are attachment formats without portable storage writes; use R32f for a scalar written by a kernel. The format of a written field must be inferred
  unambiguously from its constructor assignments; an unknown or ambiguous origin is an error with fixed-constructor
  guidance. The same origins decide a frag's numeric outputs, a typed Clear, `Read<T>` and typed reads, and for a
  field handed to a function as `out` or `mut` they include what that function assigns its parameter (Provisional,
  Claude, 2026-11-14: followed rather than refused, since a helper that makes a target is ordinary code; what C or
  a built-in makes stays unknown and refused; a Color draw into an unknown target is still checked as it runs). Runtime shader variants were weighed and rejected in favor of compile-time format diagnostics.
  A local is followed as a field is (Provisional, Claude, 2026-11-15): its initializer, every assignment after it
  and what a function makes it as an `out` or `mut` argument (`Make(out var t)`, `Remake(t)`) are its origins, so a
  local made two ways, like a field, has no one format, and a Color draw into one that may hold numbers is refused.
  Weighed: following the value at each use (flow-sensitive, so `mut t = Rgba8; Remake(t);` would be the helper's
  format alone), which reads better but makes a local's format depend on where it's read, unlike a field's, and
  takes a pass over the function's control flow the checker doesn't have; and treating any changed local as
  unknown, which is what it did, so a draw into it compiled and was skipped as it ran. Each place (a field, a
  parameter, a local) is followed once a query: a recursive helper handing its parameter back to itself, or fields
  assigned from each other, is a cycle that adds no format (it was a depth limit, which made such a target unknown,
  and followed every path, which for a helper calling itself three times never ended). An unknown format that a C,
  virtual or override function makes says which in a note.
  A Grid3<float>'s sampled R16f image cannot be a storage destination, because core WebGPU has no R16f storage texture.
  Grid conversions are sampled views of CPU data; use an owned Texture3D for writes. Writing their cached GPU
  copies was rejected because CPU grid hashes and residency could then silently replace the kernel's contents.
  At most four storage images are written in a run; larger work is split into separate runs. Written target
  images must be single-sample: use a target without MSAA. Updating only a multisampled target's resolved image
  was rejected because the next resolve would overwrite it with the old samples; replicating every store into
  samples would require another pass.
  Four was chosen over requiring raised device limits, retaining the portable baseline.
- **Alpha:** a Color store premultiplies internally, and sampling or an exact color read reverses it as for a
  render target. A game never multiplies. A color at alpha zero is lost, and byte formats quantize nearly clear
  colors, as existing textures do. Raw numeric sources retain their channels instead.
  Straight-alpha storage was rejected because it would break ordinary sampling and target composition.
- **Order:** image writes, draws and runs behave as if serial in recording order. An image-writing run stays
  at its recorded position; moving it across independent draws was weighed against the extra alias analysis.
  Target mipmaps become stale after a kernel writes their base image. Volumes have no smaller images.
- **Lifetime:** new and resized volumes start zeroed. Device loss and hot reload may discard their pixels;
  `contentRevision` changes so local code can refill them. A normal write does not change the revision.
  An asynchronous allocation becoming ready also changes the revision, allowing code that fills only when it
  changes to retry after the image becomes usable.
  A run deferred by allocation or pipeline readiness advances its written resources' revisions to request a retry;
  retaining old command payloads across frames was rejected to keep draw-list lifetimes bounded.
- **Limits:** each axis is at most 2048 and the image at most 128 MiB, further limited by the device. Sizes are
  checked before multiplying or allocating; a volume that cannot be held is empty and says so once. Invalid
  resize requests leave the existing volume. This fixed ceiling was chosen over allowing unchecked device-sized
  allocations to keep resource requests bounded on every backend.
  Like a GPU list's capacity, the CPU's size remains the requested size when a device cannot hold its image.
- **Not there:** a Texture3D file asset declaration (a stack of PNGs was weighed, but does not specify a numeric
  volume's channel format), volume mipmaps, compressed volumes, and a renderable slice.

<a id="provisional-what-a-kernel-reads-claude-2026-11-14"></a>

### Provisional: what a kernel reads (Claude, 2026-11-14)

The owner asked that every gap a GPU can close be closed ("make sure everything we can add or validate we do"). A
kernel reads images as frags and verts do; these are the picks that made it so.

- **What it reads where it's given none** is a frag's, whether or not any frag of the game reads that kind: a
  `DepthTexture` or `DepthTextureArray` the far limit (a comparison with it is 1), a `Cubemap` the dark cube (black,
  alpha one), a `TextureArray` white, a `Texture` the white pixel, and every typed (`[Raw(T)]`) read zeros. So does
  an image that was disposed, a color image a target hasn't got, the colors of a target or an array of depth alone,
  and an image a blending read can't blend (R32f, Rgba32f, R32i). Weighed: passing the run by with a line, as a
  draw that samples such an image is; a run also writes lists and other images, which runs after it read, so it
  runs with what a missing image reads instead.
- **A run with an image that couldn't be made at all** (a fallback on a lost device) is passed by on every backend:
  a binding left without an image reads anything on Vulkan.
- **Smaller images:** `SampleLevel`, and `Filter.Trilinear` or `Filter.Anisotropic`, in a kernel read the chain made
  of what was last drawn into the image, made before the run as before a draw that reads it so: a target's color
  (multisampled too), an array's layers, a cube's faces, in every format a sampler blends. A pass that draws into
  the target after a run, and a run that writes its image, have the chain made again before the next read.
  Weighed: kernels reading level zero alone, as was built, which contradicted these calls running in kernels.
- **A Color texture's own filter still decides** whether a level is read, as in a frag (Point and Bilinear keep to
  the base image): a kernel names `Filter.Trilinear` to read a level of a `Texture` that carries Bilinear.

<a id="decided-and-provisional-2026-11-05-built-the-same-day"></a>

### Decided and provisional (2026-11-05), built the same day

Claude proposed this after the Mount & Rifle performance pass, and the owner answered it the same day.

- **Decided:**
  - Compute is guaranteed on every render backend, and a backend that can't run it is removed (Backends, below).
  - The `compute` declaration, with `this.index`, `this.at`, `this.local`, `this.group` and `[Group(...)]`.
  - `GPU.Run` in drawing code, ordered with draws as if serial.
  - Readback by `await list.Read()` or `await target.Read()` in local async code.
  - Any draw over a GPU list is indirect, with nothing more written.
  - The engine's own culling is written as a Tide kernel.
  - The order of work (the owner's): compute shaders, then indirect drawing, then GPU culling.
- **Provisional** (Claude's picks): the name `GPUList<T>` (Questions settled, below), ordered `Add` and atomics (the owner: "i trust you here"), and every other rule here.

**Why.** Measured on Mount & Rifle (Vulkan, RTX 4080 SUPER, 1080p), the target is 144 Hz (6.9 ms a frame). Recording meshes takes about 21% of the main thread on foot. DrawFlora makes 665 draws and 159k instances a frame, 47k of them frustum-tested one by one, though their instance data already lives on the GPU in listed pages. The vegetation pass takes about 2 ms of GPU time at any resolution: 17.9M indices a frame, mostly sub-pixel grass. Culling, picking levels of detail and compacting on the GPU replace that CPU work, and only a GPU-side count can then feed a draw.

<a id="built-2026-11-05-and-the-picks-made-building-it-provisional"></a>

#### Built (2026-11-05), and the picks made building it (Provisional)

Kernels, GPU lists, `GPU.Run`, ordered `Add`, atomics, `shared`, `GPU.Barrier`, reads back and indirect instanced draws are built, on Vulkan and WebGPU (`notes/compute.md`). Every pick below is Claude's, Provisional:

- **`this` is the invocation record `Invocation`:** `index` (an `int`), and `at`, `local`, `group` and `count` (each an `int3`, the run's size for `count`). `this.at` is an `int3` whatever the run's size; a run over an `int2` reads `this.at.xy`.
- **A kernel's parameters** are components and singletons, as a frag's, and at most one struct, its run's values, which `GPU.Run` must then be given (and must not be where there's none). No `mut`, `out`, `with`, `World`, plain values, `Instance` or vertex.
- **Group sizes** are constants from 1 to 256 along each axis, at most 256 in all and 64 along z; a run is at most 65,535 groups along an axis (a run past that is passed by, said once).
- **Ordered `Add` needs a group of one axis** (`[Group(64)]`): this.index's order is then the groups' order whatever the run's size, which a group of two or three axes doesn't run in. `Add` is a statement; once at the most on any path; never in a loop. A kernel's Adds to several lists share one scan in the kernel, a lane a list (built 2026-11-05), four lists a scan and any number of lists (since GPU lists in pools, below); the engine's offsets and scatter dispatches after it are still one each a list.
- **GPU lists in pools** (built 2026-11-05; the owner approved lifting the limit of 7 storage buffers a shader bound, and the design of lists suballocated from pooled buffers; the rest is Claude's): a frag, vert or kernel names any number of GPU lists, 64 at the most (an error with the fix past that: one list of a struct, or two draws or runs), where a kernel named at most 7 storage buffers' worth (its lists, a buffer each Add, its run's record). Each list is a range of one of the renderer's two pools, the lists of ints (`GPUList<int>`, which atomics take) and the rest, and a shader finds it by its place there and its capacity, which go with its uniforms (8 bytes a list of the draw's or run's 4096). Reads past a list's count give zeros and writes past its capacity go nowhere as before, never into another list. A device binds a pool as one buffer as big as it binds one (at least 128 MiB, a list's most as before; 2 to 4 GiB on desktop GPUs): a list past what its pool can hold, with every other list of its kind, is an empty one of no capacity on the GPU, said once, where before only the device's memory bounded the lists together. A list's `capacity` on the CPU is what it was made with either way.
- **Writes to a GPU list** are of a list a field of what the kernel takes names, or one a function it calls is given, and of a whole element (`list[i].height = 2` is an error that says to read, change and write back). Functions read GPU lists (through a struct, singleton or component they're given, or one given alone), which makes them code the GPU runs alone.
- **GPU lists passed on alone** (built 2026-11-05): a function's `GPUList<T>` parameter is the list its call names, by a field or by the caller's own such parameter; the function is written once for each storage buffer it's called with, as one taking a `List<T>` is for each list. It isn't a value: no local keeps one, no function returns one, and `?:` doesn't pick one. What a function does to it, writing elements, `Add` and atomics, the kernel that calls it does to the list it passed, so a frag or vert calling one that writes is an error that says a kernel runs it. A call of a function that adds to a list counts as an `Add` of that list: once on a path, not in a loop, and a statement of its own, checked once every function's body is.
- **The count:** only `Add`, `Set`, `Clear` and `SetCount(n)` change it; a write by index past the count leaves it, so a list a kernel fills by index takes `SetCount` from the CPU. `SetCount` is a pick of its own, in local code beside `Set` and `Clear`.
- **`capacity`** is readable on both sides; `contentRevision` on the CPU.
- **Reads back** are of the list as the frame drawn after the read was asked for leaves it (the renderer begins them once that frame's work is recorded). On the web they arrive when the browser has them; without a window (`--capture`, `--frames`, `--script`) at the next frame's start. A task dropped while it waits (cancelled, its owner gone, its local world freed) lets go of its read at once, a target's too, so its slot and what it holds go free; one the renderer has begun goes once the renderer is done with it (Provisional, Claude, 2026-11-14: a dropped read held its slot and its bytes for 600 frames, which made a target's later reads fail). A read nobody polls or lets go of for 600 frames (C that asks and never looks) is let go. 64 are pending at most; past that the await waits.
- **Atomics on `shared` memory** are on a `shared int[N]`'s elements; such an array's reads and writes are atomic too, and it can't be read whole.
- **Shared locals** take no initializer, are changeable without `mut`, and are a kernel's own body's top level.
- **`Draw.Instanced` over a GPU list** takes no `lod:` and no skinned mesh. Inside `Draw.Transform` (built 2026-11-05, after the first cut, which left such a draw unmoved), the draw's matrix goes with its uniforms and the GPU puts each instance's transform through it, as the CPU does a list's; one that mirrors turns the draw's front round, as it does a list's.
- **Instances whose own transforms mirror their mesh** (built 2026-11-05) are drawn with their front the other way round, as a list's are, with nothing read back: a culled draw over a GPU list whose element has a transform is two indirect draws of the whole list, wound each way, and the vertex stage of each puts the corners of the other side's instances (by the sign of their transform's determinant, as the CPU's `mirrors` works it out) at one point, so their triangles cover nothing. Inside `Draw.Cull(Cull.None)` it's one draw. Why two draws rather than drawing both sides and discarding back faces in the frag: no fragment work for back faces and early depth tests kept, for the second draw's vertex work, which is an instance's load and a determinant where nothing mirrors. Instances that mirror are drawn after those that don't, as the CPU's split of a list puts them in runs of their own.
- **Meshes over GPU lists** (built 2026-11-05): `Draw.Mesh`, `Draw.Instanced` and a target's `Mesh` take a `GPUList` of the vertex struct for the vertices, and a `GPUList<int>` or a `List<int>` for the indices.
  - The vertex stage reads each vertex from its list's storage by its index (`vertex_index`), as `list[i]` reads, zeros past the count; such a shader has no vertex attributes. GPU lists' layout (each element's floats, then its ints) isn't a vertex buffer's, and reading them as storage needs nothing of a backend that a frag's reads don't.
  - Indices a GPU list's are read there too, each corner's by its place among them, and the draw is a non-indexed indirect one of as many corners as the list's count on the GPU: no backend binds a storage buffer as indices the same way (Unity's replay doesn't). So a mesh with indices on the GPU has its vertices there too: the CPU's vertices with a GPU list's indices is an error that says to `Set` them into a `GPUList`.
  - The CPU's indices with a GPU list's vertices are an ordinary index buffer, drawn with the CPU's count: as many triangles as there are indices, a vertex past the GPU's count zeros, so a fixed pattern of quads draws however many a kernel made.
  - A vert's rolls tell its runs apart by the vertex's index, the one read from the list of indices where that's a GPU list's.
  - Instances of such a mesh from a CPU list are a list's (`Draw.Transform`, mirroring, frustum culling), but its bounds aren't the CPU's to know: they're frustum culled by the bounds `Draw.Bounds` gives (pinned 2026-11-05), and without it none are culled. `lod:` is an error: levels are made of the CPU's vertices.
- **Runs moved out of passes** (built 2026-11-05): the renderer does a run, or a list's `Set`, `Clear` or `SetCount`, before the draws recorded ahead of it that read none of the lists it writes (and, for a run that samples a render target, draw into no target), in their order: so it splits no render pass it doesn't have to. Observable order is as if serial.
- **A race on shared memory that Unity can't compile** (built 2026-11-05): every invocation of a group writing one place of shared memory, each with its own value, is a race WGSL and SPIR-V allow and Unity's Direct3D 11 compiler (fxc) refuses (X3695). Every write to shared memory but an atomic's is under a condition always true, a word of the group's shared memory that nothing writes (zeroed as the group starts), which fxc can't see through: the write happens for every invocation, as written, on every backend, and fxc compiles it. So nothing is warned (the first cut warned where it could tell, and guarding with `if (local == 0)` wasn't exact). One value written by all is fine everywhere (fxc's X3584, which Unity's shaders turn off).
- **OpenGL and WebGL** passed runs and draws that read GPU lists by, saying so once, and failed reads back: the staging the decided Backends rule describes. History: the GL backends were removed 2026-11-05, so every backend runs them.

<a id="kernels"></a>

#### Kernels

- **A `compute` declaration is code the GPU runs that isn't tied to a draw,** a declaration kind beside `frag` and `vert`. Its signature says what it reads, and the engine supplies it, as for a frag: the components of the entity the calling view runs for, singletons, and one struct of values given at the dispatch. It returns nothing. What a frag's code can do, a kernel's can: math, noise, lists, grids, maps, functions, and `Sample` at a texture's own level.
- **Its `this` is the invocation,** as a frag's is its pixel: `this.index` (an `int`, for a run over a count or a list), or `this.at` (an `int2` or `int3`, for a run over a size), with `this.local` and `this.group` for its place in its group. Ordinary helpers get no `this`, as now.
- **Group size is an attribute:** `[Group(64)]`, `[Group(8, 8)]`, `[Group(4, 4, 4)]`, 64 when left out. The compiler holds it to what every target has (WebGPU's defaults: 256 invocations a group, 64 along z) and says so at the attribute.
- Invocations past the count never run the body. The engine rounds up to whole groups and guards the rest, so a kernel needs no `if (this.index >= n) return;` of its own.

```csharp
struct Blade
{
    float3 root;
    float height;
}

component Meadow
{
    local GPUList<Blade> blades;   // Every blade, made once by Scatter
    local GPUList<Blade> shown;    // This frame's survivors, in order
    local Grid2<float> heights;
}

[Group(8, 8)]
compute Scatter(Meadow meadow)
{
    float2 at = float2(this.at) * 0.25;    // Run once over the heights' size: GPU.Run(Scatter, meadow.heights.size)
    meadow.blades.Add(Blade { root = float3(at.x, meadow.heights[this.at], at.y), height = 0.4 });
}

[Group(64)]
compute CullBlades(Meadow meadow, Eye eye)     // Eye: a local singleton of the game's
{
    Blade blade = meadow.blades[this.index];
    if (Math.Distance(blade.root, eye.position) < eye.reach)
        meadow.shown.Add(blade);
}

view DrawMeadow(Meadow meadow, Models models)
{
    meadow.shown.Clear();                // In frame order, before Cull adds
    GPU.Run(CullBlades, meadow.blades);  // Once for each blade the GPU has
    Draw.Instanced(models.blade, meadow.shown, Sway, Grass);   // Indirect: draws as many as CullBlades kept
}
```

<a id="gpu-lists"></a>

#### GPU lists

- **`GPUList<T>` is a list that lives on the GPU,** as `RenderTarget` is an image that does: machine-local, never match state (a match component or singleton can't hold one), made in local code as `GPUList<T>(capacity)`, `Resize(capacity)` (which empties it), `Dispose()`. Copies share the list. Its elements are what a GPU list's are today: GPU values, not `long`, text, entities or containers.
- **Its contents and count stay from frame to frame** until something writes them. A lost device or a hot reload that changes `T`'s layout leaves it empty, as a target's image is left. A `contentRevision`, as `RenderTarget` has, says when that happened, so a game knows to fill it again.
- **Its count is on the GPU,** between 0 and its capacity. GPU code reads `count`, `[i]` and `foreach`, as for a `List<T>`. Reads past the count are zeros.
- **Kernels write it:** `list[i] = v` (a write past the capacity goes nowhere), and `list.Add(v)` (below). Local code writes it in frame order: `list.Set(items)` sends a `List<T>` and sets the count, and `list.Clear()` sets the count to 0.
- **Writing needs no `mut`.** It's a handle, as drawing into a target needs no `mut` on what holds the target. The compiler records which GPU lists each kernel, frag and vert reads and writes, by the field that names them, and frame ordering (below) is built on that.
- **Frags and verts read it** as they read a `List<T>`.
- **Ordinary `List<T>` fields** are read by kernels the same way frags read them now, uploaded when they change.

<a id="adding-in-order-and-atomics"></a>

#### Adding in order, and atomics

- **`list.Add(v)` in a kernel keeps invocation order:** what invocation 3 adds comes before what invocation 7 adds, and the count is how many were added. The result is the same whatever order the GPU ran them in, so captures stay bit-stable. A culling kernel needs nothing else.
  - An invocation adds at most once to a given list on any path. The check works like definite assignment: "'CullBlades' can add to 'shown' twice". `Add` in a loop is an error that names atomics.
  - Lowering (Claude's pick): the kernel writes a flag and the value for each invocation, then the engine's own reduce, scan and scatter dispatches compact them. That needs no subgroup operations or forward-progress guarantees, so it is portable. A kernel's `Add`s to several lists share the scan.
- **Atomics** are methods on an `int` element of a GPU list or of a `shared` array: `counts.AtomicAdd(i, 1)` gives the old value, with `AtomicMin`, `AtomicMax`, `AtomicAnd`, `AtomicOr`, `AtomicXor`, `AtomicExchange` and `AtomicCompareExchange`. Only `int`: no backend has portable float atomics.
  - What atomics return depends on timing, so results that depend on it differ between runs. GPU results are visual only, so atomics are allowed, and the docs say that a capture can then differ between runs.

<a id="within-a-group"></a>

#### Within a group

- **`shared int[64] sums;`** is a local in a kernel that the whole group shares: one copy a group, zeroed as the group starts (WebGPU does this, and Vulkan 1.3 has it core). It is a fixed-size array of GPU values, within 16 KiB a kernel.
- **`GPU.Barrier()`** waits until every invocation of the group reaches it, with their writes to shared and GPU lists seen.
  - Every invocation must reach it. A barrier inside a branch or loop whose condition can differ between invocations is tidec's error, by WGSL's uniformity rules. A shader compiler's error would be a tidec bug, as now.

<a id="running-a-kernel-and-order-in-a-frame"></a>

#### Running a kernel, and order in a frame

- **`GPU.Run(kernel, over[, values])`** records a dispatch into the frame's draw list. It goes where a draw does: in views, local handlers that draw, and drawing functions. `over` is one of these:
  - an `int`, `int2` or `int3`: that many invocations, read as `this.index` or `this.at`;
  - a `GPUList`: once for each element of its GPU-side count, an indirect dispatch, so kernels chain without reading back;
  - a `List<T>`: its count.
- **`values`** is a struct sent once for the dispatch, as a draw's values are.
- **A frame's GPU work happens as if in recording order.** A draw recorded after a run sees what the run wrote; one recorded before it doesn't. The same holds between runs. This is the scheduler's rule applied within a frame.
  - The renderer knows each command's GPU-list reads and writes from the compiler, and places exactly the barriers they need.
  - It may move a run earlier, out of the render pass it fell in, when nothing between them writes what the run reads or reads what it writes. A render pass is never split for a run that doesn't need it. (Built 2026-11-05: Built, above.)
  - Parallel views keep recording order, as for draws.
- **Kernels write GPU lists and images.** Image writes and volumes follow the dated decisions and provisional rules above.

<a id="results-in-local-code"></a>

#### Results in local code

- **Never the match:** the CPU can't read a GPU list synchronously. `meadow.blades.count` in CPU code is an error that says to read the list back.
- **`await list.Read()`** in local async code gives a `List<T>`, an owned copy, a frame or more later, as a local worker's result arrives. `await list.ReadCount()` gives the count alone. A lost device fails it (`fails`). The game publishes the result into local state.
- **Headless runs (Claude's pick):** a read completes at the start of the next frame, so scripted runs and captures repeat exactly. Real runs complete when the GPU is done.
- In-flight reads are bounded, and a read past the bound waits for an earlier one.

<a id="indirect-drawing-follows"></a>

#### Indirect drawing follows

- **A draw over a GPU list is indirect, with nothing more said:**
  - `Draw.Instanced(mesh, list, ...)` draws as many instances as the list's GPU count;
  - `Draw.Mesh` takes `GPUList` vertices and indices too, for geometry a kernel makes (grass, particles, terrain), with their counts on the GPU. (Built 2026-11-05: Built, above.)
  - The CPU records one command and reads nothing back. No game writes indirect arguments.
- **No CPU culling or level picking** applies to such a draw (the CPU has no instances to test): the kernel does that. A game draws one list a level, filled by one kernel.
- **Backends:**
  - Vulkan uses `vkCmdDrawIndexedIndirect`, with `DrawIndirectCount` (core since 1.2) for many runs in one call (not built: a draw each).
  - WebGPU uses `drawIndexedIndirect`, one a draw. A nonzero first instance there needs the optional `indirect-first-instance` feature, so the instance base goes with the draw's uniforms instead.
  - Unity uses `Graphics.RenderPrimitivesIndexedIndirect` and `CommandBuffer.DispatchCompute`.

<a id="gpu-culling-of-listed-runs-the-engine-s-own"></a>

#### GPU culling of listed runs: the engine's own

This is the first use, step 1 of the agreed plan. It is internal: no language surface, and the same pixels. It is listed here because the owner asked for it to be written as a Tide kernel, which tests whether the language above is complete enough.

- A listed run (`tide_draw_run.listed`) already has its candidates' instances in a GPU page. The CPU then records one entry a run: its page region, mesh bounds, level thresholds, whether it mirrors, and its camera. No per-instance work is left on the CPU.
- One kernel per frame, `engine` code in a `.tide` file in `platform/`, does the rest for every entry's candidates:
  - compiled when the engine builds, by the tool that makes the renderer's SPIR-V now;
  - the frustum test, the level pick and the mirror split, each by the CPU's rule;
  - an ordered `Add` into one list for each run, level and side;
  - the indirect arguments for each.
- **Order is the CPU path's,** so where the GPU and CPU tests agree the runs are the same. They can differ at a boundary: GPU float rounding isn't the quick test's error bound. That changes only which instances near the frustum's edge draw, visually, and is said where captures are compared.
- **Built since, otherwise:** occlusion against the depth drawn so far this frame, from a pyramid, `Draw.Occlusion` (Views and drawing, Occlusion), rather than last frame's depth. The grass's 2 ms of rasterizing is a separate problem. It comes down when distant levels thin out and occluded blades stop drawing, both of which this makes cheap.
- Separate gap, still needed for cached and alternating shadow maps: a listed page and a mesh drawn only every other frame are freed at the reset between (`transient_data_textures`). GPU lists that a game owns persist by construction, but the engine's pages need their own fix.

<a id="what-tidec-writes"></a>

#### What tidec writes

- **WGSL first, as now:**
  - `@compute @workgroup_size(...)` entry points, `var<storage, read>` and `read_write` runtime-sized arrays, `var<workgroup>`, `workgroupBarrier`, `atomicAdd` and the rest.
  - Elements keep the word layout values have everywhere in shaders (each leaf's floats, then its ints), whole, as `array<u32>` with bitcasts (built so: every part, since kernels write them), after a header of four words (the count, the capacity). The CPU writer, the GPU readers and Unity then share one layout, not WGSL's storage alignment rules.
  - tidec bounds-checks reads and writes itself, rather than relying on robust buffer access for writes.
- **SPIR-V** (`spirv.c`) gains:
  - the GLCompute execution model with LocalSize, and the invocation built-ins;
  - the StorageBuffer class with Block, ArrayStride and runtime arrays;
  - Workgroup variables, `OpControlBarrier` and `OpAtomic*`.
- **HLSL** (`hlsl.c`) gains:
  - `[numthreads]`, `RWByteAddressBuffer`, `groupshared`, `GroupMemoryBarrierWithGroupSync` and `Interlocked*`;
  - a `.compute` file per kernel for `tide unity`.
- **GLSL** is not written: the GL backends are removed (Backends, below; done 2026-11-05).
- **`gpu.h`** gains storage buffers, compute pipelines, `dispatch`, `dispatch_indirect`, `draw_indexed_indirect`, and asynchronous buffer reads. The recorder (`gpu_record.c`) records them for Unity.
- **Tests:**
  - goldens, `spirv-val` and fxc `cs_5_0 /WX`;
  - a platform fixture that runs the same Tide functions on the CPU and in a kernel and compares them, as `tide_platform_shaders` does for frags;
  - ordered `Add`'s order and count pinned across group sizes;
  - device loss mid-frame.

<a id="backends-decided-2026-11-05"></a>

#### Backends (decided 2026-11-05)

The owner: "compute shaders will be a guarantee now, if a render backend can't support it then we should remove it".

- **Compute is the baseline: Vulkan 1.3 (desktop, Android, MoltenVK), WebGPU (web) and Unity's compute (DX11/12, Vulkan, Metal). OpenGL 3.3, OpenGL ES 3 and WebGL 2 are removed.**
  - Gains:
    - one code path;
    - `gpu_gl.c`, `gl.h`, the GL half of `tide.js`, KHR_parallel_shader_compile and the ANGLE D3D11 runs deleted;
    - lists, grids, maps and listed pages as storage buffers rather than int textures, without the 1024-pixel rows or the 2,097,152-pixel cap.
  - Losses:
    - Android devices without Vulkan 1.3 (lowering to 1.1 plus extensions is possible later);
    - browsers without WebGPU: Firefox on Linux, Android and Intel Macs for now;
    - Unity's WebGL export, and Unity on GLES 3.0 devices;
    - very old GPUs, VMs and remote desktop.
  - Costs that are easy to miss:
    - tidec's helper texts are written once in GLSL and spelled into WGSL (`put_helper`), so dropping GLSL means making WGSL their source: a refactor of `shader.c` with every golden checked. (As built, Claude's pick, Provisional: the emitter is WGSL only and the helper texts stay in their C-like notation, which `put_helper` spells into WGSL; every WGSL and SPIR-V output came out byte-identical: `notes/shaders.md`.)
    - WebGPU's compatibility mode (Chrome's path on GLES 3.1 Android) allows no storage buffers in the vertex stage by default, so this targets core WebGPU only.
    - Android's emulator fell back to GLES with SwiftShader (its Vulkan there is 1.2), so emulator GPU runs needed a Vulkan 1.3 software device. Checked 2026-11-05: the emulator's own lavapipe (`-gpu lavapipe`) gives the device Vulkan 1.3, and CI's Android job runs the renderer's apps on it (`notes/android-and-mingw.md`). Since 2026-11-14 every GPU fixture a desktop runs as a window program runs there as an app too, the kernels', images', culling's and depth fixtures' among them, on the device's descriptor sets (`notes/android-and-mingw.md`, Every window fixture an app). Their 24-bit depth, anisotropy and culling variants take Tide's settings as a debuggable app does (Settings, Provisional: Tide's settings in an Android app).
    - CI can use lavapipe or SwiftShader for Vulkan and Dawn's software adapter, as it uses SwiftShader WebGPU now.
  - Staging: build compute and indirect drawing on Vulkan and WebGPU, then delete GL in the same series. Between those steps, a game that ran a kernel on OpenGL had its runs passed by, saying why. Done 2026-11-05: GL is gone.
  - **Built 2026-11-05 (Claude's picks, Provisional):**
    - `gpu_gl.c`, `gl.h`, the desktop GL loader and context, Android's EGL/GLES path, the GL half of `tide.js` and KHR_parallel_shader_compile are deleted, and tidec writes no GLSL. There's no fallback and nothing picks a backend: `TIDE_BACKEND`, the page's `backend=`/`Tide.backend` and Android's `tide.backend` extra are gone. A page takes any WebGPU adapter the browser gives, its software one too.
    - A machine that can't draw is told what it needs, never left blank: desktop prints it and, outside a quiet run (`TIDE_HIDDEN`), shows a dialog of the system's (Windows' message box, macOS's alert, on Linux the first of zenity, kdialog and xmessage) saying the game needs Vulkan 1.3; Android draws the message with the CPU into the activity's window until the player leaves; a page shows a note in the canvas's place saying it needs WebGPU. An Android app's manifest requires Vulkan 1.3 (`android.hardware.vulkan.version`, 0x403000), so Google Play offers it only to devices that have it; the screen is for one installed otherwise.
    - Every backend computes and draws into floats: `gpu.h`'s no-compute path and its float-target fallback are gone.
    - Unity: Tide's drawing replays on the graphics APIs that compute: Direct3D 11 and 12, Vulkan, Metal and OpenGL Core 4.5; Unity's OpenGL ES 3 and WebGL get none (their HLSL subshader is gone), only the views' 2D through Unity's GL.
    - The ANGLE D3D11 runs went with WebGL; every web test runs on the browser's software WebGPU, Linux's included, whose browser draws its own with SwiftShader's Vulkan so pages read WebGPU's pixels back; tests that read pixels are labelled `pixels`, to leave out where a browser can't.
- **Not taken:**
  - keeping GL with kernels on CPU threads there, the earlier plan in `notes/rendering.md`. It meant everything twice, and GL slow where compute matters;
  - keeping GL for drawing only. A game using compute wouldn't then run on every machine.

<a id="questions-settled"></a>

#### Questions settled

The owner answered every question on 2026-11-05. The one left to Claude was the type's name. The owner was torn between `ComputeBuffer<T>`, `ComputeList<T>` and `GPUList<T>`: "they are usually called buffers in the GPU land no?".

- **Pick, Provisional: `GPUList<T>`.** It is used as a list is (`count`, `[i]`, `foreach`, `Add`, `Set`), and Tide names a container by how it's used (`List`, `Grid`, `Map`). It goes where a `List<T>` goes in GPU code. Its count travels with it, which a buffer of the GPU's own doesn't have.
- `ComputeBuffer` is Unity's name for a raw buffer without a count. `ComputeList` would suggest only kernels use it, though frags, verts and draws read it too.
- `GPU` capitalized follows `GUI`. A rename stays cheap until it's built.

<a id="gui"></a>

## GUI

<a id="decided-24"></a>

### Decided

- The GUI is immediate mode, called from views, and drawn over the world. It follows Unity's IMGUI.
- `GUILayout` lays widgets out automatically: they stack top to bottom, and `GUILayout.Horizontal()` puts them side by side. `GUI` has the same widgets, each at an explicit `Rect`, which comes first, as in Unity: `GUI.Button(rect, "Quit")`.
- Containers take a block, and they're ordinary functions with an `Action` parameter (see Functions): `GUILayout.Horizontal() { ... }`, `GUILayout.Vertical() { ... }` and `GUILayout.Area(...) { ... }`. Calls always have parentheses.
- Widgets edit values through `mut` parameters, and return whether the value changed: `GUILayout.Toggle("Fullscreen", settings.fullscreen)`. A button returns whether it was pressed.
- **Entered fields** (agreed 2026-10-06): a view can tell that the player pressed Enter in a field they typed into. `TextField`, `IntField` and `FloatField` each have a second version, in `GUILayout` and in `GUI`, with an `out bool entered` parameter (see Out parameters): `GUILayout.TextField("Code", lobby.code, out var entered)`. It's true in the frame Enter ends the typing in that field. What the field returns stays whether the value changed, and without the argument the field is the one there always was. The details are picks, under Provisional.
- Widgets have automatic identity from where they're called and the entity the view runs for. Reorderable data can supply a stable key for a block of controls.
- The engine builds nothing a game couldn't build itself: containers are functions with an `Action`, and widgets are made of pieces games can use too.
- Gamepad and keyboard navigation are built in: focus moves between widgets, the south button presses, the east button goes back.
- Whatever the GUI is using, such as a click on a button or typing in a field, is hidden from the input's `Sample`.
- Typing into a field uses the characters the player types, which follow their keyboard layout, not keys by position.
- `Screen.width` and `Screen.height` are the window's size.
- The widgets: `Label`, `Button`, `Toggle`, `Slider`, `IntSlider`, `TextField`, `IntField`, `FloatField`, `Float2Field`, `Float3Field`, `Float4Field`, `ColorField` and `Space`, and the containers `Horizontal`, `Vertical`, `Area` and `Modal`.
- `GUILayout.Modal(anchor, mut bool open) { ... }` is a panel over the whole screen while `open` is true, like a pause menu. While it's up, it has the focus, the widgets outside it don't work, the game and views get nothing from the devices, and back (Escape or the east button) closes it.
- **Controls:** a view's own widgets are controls. `GUI.Control(rect)` is a widget the view draws itself, however it likes: the GUI handles its input, and draws nothing for it, so showing that it's hovered or has the focus is the view's. It returns a small built-in value that says whether the rect is hovered, held, focused and clicked.
  - It takes the pointer for its rect by itself, as the GUI's own widgets do: a press on it never reaches the input's `Sample` or the other views, from the frame it lands in.
  - It joins Tab and Shift+Tab, arrow, d-pad and left stick navigation alongside the built-in widgets, in the order they're called. Enter, Space and the gamepad's south button click it.
  - `GUI.Disabled(...) { }` and modals stop it like any widget.
  - Custom controls can reserve layout space and draw alongside built-in widgets, in the GUI's declaration order. Ordinary world drawing stays under the GUI.
- **Themes:** the GUI stays bare: one look, and a simple theme for it. `GUITheme` is a built-in struct of the colors the GUI's widgets use, their corners' radius, and (agreed 2026-10-29, the owner taking Claude's recommendation: "i will follow your recommendation") their border, shading, the panels' shadow, the fade between widget states, text size, padding and spacing, and (agreed 2026-11-03: "yeah themes now need a font") the font their text is in, `GUITheme.font`, `Font.Regular` by default. Still no styles for single widgets. Its defaults are the look the widgets have without one, so a theme names only what it changes.
- **Animation** (agreed 2026-10-29: the GUI holds animation state, "Animation state: yes"): `GUI.Animate` eases a value from frame to frame, kept by the GUI and told apart as widgets are, and a control's state comes as eased amounts too. The API is Provisional, below.
  - `GUI.Theme(theme) { ... }` wraps a block: its widgets have the theme, and the look it found is back when the block ends. `GUI.SetTheme(theme)` stays for the widgets that follow, in this view and the ones after it, until it's set again or the frame ends. Every frame starts from the defaults. It's the rule for every setting of a frame with two forms, `Draw`'s too: the plain name around a block, and `Set` for what follows.
  - Round corners are `Draw`'s round rects.
  - The stats overlay and the debug views always keep their own look.
- **Claims:** a view with widgets that read the devices themselves, like a C library's, says what they're using: `GUI.ClaimPointer()` and `GUI.ClaimKeyboard()`. What's claimed is hidden from the input's `Sample` and from the other views, as what the GUI uses is, and the view that claimed it goes on reading it.
- A claim lasts one frame. The view makes it again every frame its widget uses the device, as immediate-mode code draws every frame, so a view that stops running leaves nothing claimed.
- `GUI.ShowKeyboard()` shows a phone's keyboard, as typing into a field does, each frame it's called. It's apart from the keyboard's claim, so a claim for a widget's shortcuts doesn't bring the keyboard up.

```csharp
local singleton Settings
{
    bool open;
    bool fullscreen;
    float volume = 1;
}

view Options(Devices devices, mut Settings settings)
{
    if (GUI.Button(Rect(Screen.width - 210, 10, 200, 40), "Options")) settings.open = true;
    if (devices.keyboard.escape.down || devices.gamepad.start.down) settings.open = true;

    GUILayout.Modal(Anchor.MiddleCenter, settings.open)
    {
        GUILayout.Toggle("Fullscreen", settings.fullscreen);
        GUILayout.Slider("Volume", settings.volume, 0, 1);
    }
}

local singleton Toolbox
{
    bool dragging;
    bool renaming;
    string name;
}

local singleton Hand
{
    int picked = -1;
}

local singleton Lobby
{
    string code;
}

// A card the view draws itself: the GUI says what the player does with it
view Cards(mut Hand hand)
{
    Draw.SetScreen();
    for (var slot = 0; slot < 3; slot++)
    {
        var rect = Rect(40 + slot * 220, 200, 200, 280);
        var card = GUI.Control(rect);
        var center = float2(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5);
        Draw.RoundRect(center, float2(rect.width, rect.height), 18, card.focused || card.hovered ? Color.white : Color.gray);
        if (card.clicked) hand.picked = slot;
    }
}

// The GUI's own widgets, with a look that names what it changes. Enter in the
// field joins, as the button beside it does
view Join(mut Lobby lobby)
{
    mut var entered = false;
    GUI.Theme(GUITheme { field = Color(0.1, 0.12, 0.2), accent = Color.cyan, radius = 10 })
    {
        GUI.TextField(Rect(40, 500, 240, 36), "", lobby.code, out entered);
    }
    if ((GUI.Button(Rect(290, 500, 90, 36), "Join") || entered) && lobby.code != "") Session.Join(lobby.code);
}

// A library's widget, which reads the devices itself, in the window's lower left corner
view Tools(Devices devices, mut Toolbox box)
{
    var pointer = devices.pointer;
    var over = pointer.position.x < 200 && pointer.position.y < 200;
    if (over && pointer.press.down) box.dragging = true;
    if (!pointer.press.pressed) box.dragging = false;
    if (over || box.dragging) GUI.ClaimPointer();

    if (box.renaming)
    {
        GUI.ClaimKeyboard();
        GUI.ShowKeyboard();
        box.name += devices.keyboard.text;
        if (devices.keyboard.enter.down) box.renaming = false;
    }
}
```

<a id="provisional-25"></a>

### Provisional

- **Rectangle and GUI follow-up** (2026-10-25; owner requested the proposed priorities and a performance pass):
  - `Draw.Rect(Rect rect, Color color)`, `(rect, float radius, color)` and `(rect, float4 radii, color)` draw filled SDF boxes with target-pixel AA. Four radii run clockwise from top left; invalid/negative radii become zero, and each is capped at half the smaller side. Equal radii use the existing uniform-radius path. Center/size `Draw.Rect` keeps whole-pixel coverage for adjacent tiles. Themes are not required.
  - `GUILayout.Scroll(float2 size, mut float2 offset) { ... }` reserves a fixed viewport; `GUI.Scroll(Rect rect, mut float2 offset)` places one explicitly. Their layout content is clipped for drawing and pointer hits. Offset is in pixels from the content origin, sanitized and clamped to its measured bounds. Wheel residuals bubble from the innermost hovered viewport to parents. A touch drag beyond six pixels cancels a child's pending press, then belongs to that viewport until release. Focus navigation reveals the selected child. Content executes once, without virtualization or inertia.
  - A scroll offset is read on entry and checked-written back on close, including early exits. Indexed paths evaluate indices once and reacquire current storage at writeback; list removal makes the write a no-op; maps and grids use ordinary assignment semantics. No raw pointer into game heap storage survives the block. At the nesting ceiling the block is skipped.
  - `GUI.FocusNext()` selects the next enabled control, including inside a keyed item; `GUI.ClearFocus()` clears focus. Directional navigation uses screen positions while Tab retains declaration order.
  - Single-line fields support pointer caret/drag selection, Unicode-code-point Left/Right, Shift selection, Home/End, Ctrl word movement/select-all/copy/cut, Backspace/Delete, and 15 undo steps with Ctrl+Z/Y or Shift+Ctrl+Z. Editing keys repeat after 450 ms, at 50 ms intervals with at most one repeat per frame. Text remains bounded to 255 UTF-8 bytes. Number fields initially select their value; numeric commit/Escape behavior remains unchanged. Browser composition commits once and candidate Enter does not submit; inline preedit and grapheme/bidirectional editing remain open.

- **Custom control composition** (2026-10-24; the owner delegated implementation and API choices, prioritizing performance and API):
  - `GUILayout.Reserve(float2 size)` returns the next layout `Rect`, with the requested width and height, without drawing, claiming input or joining focus navigation. `Reserve(size, minWidth, expandWidth)` allows horizontal shrinking to `minWidth` and optional expansion to the column's remembered natural width. Heights stay explicit. Negative and nonfinite dimensions become zero; `minWidth` is clamped to the requested width. Layout executes game code once per frame.
  - `GUI.Draw() { ... }` sends its ordinary `Draw` calls, and those in helpers it calls, to the GUI's list. It starts in screen pixels, at its position in GUI declaration order, above the enclosing panel and below later GUI content. The window's drawing settings are restored on every exit, including `Set` changes inside the block. Render-target settings remain their destination's. Screen-space 2D shapes, text, sprites, indexed meshes, shader runs and clips follow an anchored area's placement; explicit custom cameras and 3D draws retain their own coordinates. This is not a layout or hit-testing transform. The block is skipped if no container nesting space remains, so unscoped drawing cannot leak settings.
  - `GUI.Key(int key) { ... }`, with `long` and `string` forms, adds a scoped data key to child widget and container identities, through helper calls as well. Keys must be unique among siblings from the same call site; zero and the empty string are valid. Reordering or omitting different keys does not transfer focus or pointer capture. Unkeyed repeated sites retain occurrence identity. Identity remains a bounded 32-bit runtime hash, not a persistent application identifier.
  - `GUIControl.down` is the pointer press edge owned by the control, `up` its release edge even outside the rect, and `cancelled` an active gesture aborted because the control became disabled or covered by a modal. Cancellation is reported once while the control is still declared; removal has no callback. `position` is the pointer position in GUI pixels, including while held outside. Existing `pressed` still means held; keyboard/gamepad submission sets `clicked`, without inventing pointer edges. Native capture-loss cancellation is not yet represented separately.

Implemented, awaiting approval:

- Positions and sizes are in pixels, as on a web page, so widgets keep their size when the window changes size. On a display scaled to 150%, a pixel is the display's logical one, 1.5 real pixels wide, as CSS pixels are.
- `Rect(x, y, width, height)` is a built-in value type measured from the top left corner, with `y` down, as in Unity's GUI, with `x`, `y`, `width` and `height`. World drawing and the mouse have `y` up. `GUI`'s rects are on the screen, inside an area or not.
- `Screen.Flip(position)` gives a `float2` position counted from the screen's other edge: `float2(position.x, Screen.height - position.y)`. The devices count pixels from the bottom left with `y` up (see Input), and the screen, the GUI, `Draw.Screen()` and the conversion helpers from the top left with `y` down: `Screen.Flip(devices.pointer.position)` is the pointer on the screen. It's its own inverse, so it converts either way. It's the window's whatever target is drawn into, as the devices are, and readable where `Screen.width` is: views and the functions they call, not the match, the input's code or the GPU. The name is a pick, awaiting the owner.
- `GUILayout.Area(anchor)` places a panel sized to its content at one of nine anchors, the built-in enum `Anchor`, named as Unity's `TextAnchor` (`UpperLeft` to `LowerRight`), 12 pixels from the screen's edges. `GUILayout.Area(rect)` places it at a rect. An anchored area is placed with its size from the frame before, and moves at the end of the frame if the size changed. One too big for the screen starts at its top left margin.
- `GUILayout` widgets outside any area stack from the screen's top left, across every view. In a vertical container, buttons, toggles, sliders and fields stretch to the widest widget's width. Labelled widgets put their label in a column at least 130 wide, so a column of them lines up.
- Widgets shrink when there isn't room: an anchored area is at most as wide as the screen less its margins, and a vertical container's widgets are at most as wide as it is. A row that's too wide shrinks each of its widgets by as much as it can give, with the frame before's widths. Fields and sliders shrink down to a small minimum, a labelled widget's label column first, down to the label; buttons give up half their padding; labels and toggles don't shrink.
- The widgets, with `GUI`'s taking a `Rect rect` first (`TextField` too, see Text):
  - `Label(string text)` and `Button(string text) -> bool`, which returns whether it was pressed.
  - `Toggle(string text, mut bool value)`, `Slider(string label, mut float value, float min, float max)`, `IntSlider(string label, mut int value, int min, int max)`, `IntField(string label, mut int value)`, `FloatField`, `Float2Field`, `Float3Field`, `Float4Field` and `ColorField` (a swatch, and fields for r, g, b and a, from 0 to 1). Each returns whether it changed its value.
  - `GUILayout.Space(float size)`, and the containers `GUILayout.Vertical()`, `GUILayout.Horizontal()` and `GUILayout.Area(...)`.
- A widget's `mut` argument is the variable itself, so its type matches exactly: `Slider` takes a `float` variable, not an `int`.
- Widget IDs come from where each call is in the program, mixed with the entity a view runs for, and for a function that draws, with where it's called from. Calls from one place with the same entity count up, in the order they run.
- Widgets draw as they're called, so, like `Spawn`, they can't be on the right of `&&` or `||` or in a side of `?:`. A statement with several runs them left to right.
- Navigation: Tab and Shift+Tab move the focus between widgets, in the order they were drawn. The arrows, d-pad and left stick move it once a widget has it, and only start moving it while the game isn't reading the devices, so a HUD's button never takes the d-pad from the player. Enter, Space and the south button press; Escape and the east button let go. With the focus, left and right step a slider or number field.
- Arrows, d-pad and stick choose a nearby control in the requested screen direction, using last frame's placed rectangles. At an edge focus stays put. Tab/Shift+Tab wrap through declaration order. Sliders and number fields keep horizontal input for stepping; an editing field uses it for caret movement. The directional edge that first focuses a stepper does not also step it.
- `GUI.Navigate()` says a menu is up: the arrows, the d-pad and the left stick can start moving the focus though the match reads the devices, as in a menu over a match that goes on behind it. A view, or a function it calls, calls it every frame the menu is up, as with `GUI.ShowKeyboard()`. Without it, only Tab starts the focus there. Once a widget has the focus, the keyboard and the gamepad are hidden from the input's `Sample`, as ever.
- Typing: clicking a number field, or pressing Enter on it, starts typing into it with its value selected, so the first character replaces it; typing a number into a focused field starts too. Enter or leaving the field keeps a valid number; Escape keeps the old value.
- **Entered fields**, beyond what's agreed (see Decided). Picks, awaiting the owner:
  - The versions: `TextField(string label, mut string value, out bool entered)`, `IntField(string label, mut int value, out bool entered)` and `FloatField(string label, mut float value, out bool entered)`, with `GUI`'s taking the `Rect` first. The parameter is named `entered` and comes last. `Float2Field`, `Float3Field`, `Float4Field`, `ColorField`, the sliders and `Toggle` have no such version.
  - `entered` is false in every frame but the one Enter ends the typing in: while the player types; when Enter starts the typing in a field that has the focus; when Escape stops it; when the focus leaves by Tab or by a click elsewhere, which keeps a number field's valid number without entering it; and when the field is in a `GUI.Disabled` block, or under a modal that isn't its own. Every call assigns it, so it's never what the variable held.
  - A number field is entered whether or not its number changed, or was a number at all: `entered` says the key, and what the field returns says the value.
  - The numpad's Enter is Enter. A gamepad's south button enters a number field, since it ends its typing as Enter does (it always did); it doesn't end a text field's typing, so it enters none.
  - What's typed in the frame Enter comes in is part of what's entered. Characters and Enter can arrive in one frame (a slow frame, a paste and a quick Enter, a script), and the characters used to be dropped there. It's so for every field that's typed into, with `out entered` or without.
  - The argument is an `out` argument like any other (see Out parameters): the word is written; `out var entered` and `out bool entered` declare a local, the block's, read where the call ran; `out` before a `mut` local or a field of local state assigns it; `out _` leaves it out; it's a write, so a view can't make the match's; and the call keeps its turn among what its statement reads. A call that leaves the word out, or writes it before another argument, is told so as a function's call is, with the editors' quick fix, where the engine's other functions say that no version takes the arguments.
  - Which version a call means goes by how many arguments it has. By name, `entered: out var done`.
  - A phone's keyboard: its Enter, whatever the key is labelled, is the GUI's Enter on the web (a key that names itself and says no position, or a line break typed into the page's field) and on Android (the system's key event), so it enters a field there too. That's by the code and a web test with made-up events: no phone was tried.
  - A widget still can't be on the right of `||`, so the button comes first: `if (GUILayout.Button("Join") || entered)`.
- `mut` before an argument is an error that says to remove it, where it was "expected an expression": the word is the parameter's, and only `out` is written at a call.
- Widgets follow the pointer: the mouse, or a finger. A finger that lifted is nowhere, so nothing stays hovered where it was.
- Hidden from the input's `Sample` and from views' `Devices`: the keyboard and gamepad while a widget has the focus, and the mouse's buttons and scroll, the pointer's press and the primary touch while the pointer is over a widget or an area, or pressing a widget. While a modal is up, everything is, the movement of the mouse and the pointer too. A key or a gamepad's button that went down while the keyboard and the gamepad were the GUI's stays hidden until it's let go, its release too, whatever became of the widget: the key that clicked a button isn't the game's while it's still down, and one the player held before the GUI took the keyboard is the game's again as soon as the GUI lets go.
- The pointer is over a widget or an area where it is now, against where the last frame drew them: the game samples, and views read, before the frame's GUI sees the devices. So a press is the GUI's from the frame it lands in, with nothing before it: a finger that touches a button, or a click the mouse made as it came. And a click made as the mouse left a widget is the game's. A widget takes the pointer a frame after it first appears, so a press on it in that frame reaches the game. A frame remembers the places of up to 1024 widgets and areas; past those, the pointer is the GUI's a frame after the GUI saw it there.
- What a claim hides: `GUI.ClaimPointer()` the mouse's buttons and scroll, the pointer's press and the primary touch, which is what the pointer over a widget hides; `GUI.ClaimKeyboard()` the keys and what's typed, and not the gamepad (the GUI's focus hides both, as both move it). Where the pointer is stays everyone's.
- Claims are statements of views and the functions they call, like widgets; a function's claim is the view's that called it. A view that runs once per entity is one view.
- A claim stands from the end of its frame to the end of the next: it hides from the samples taken after it, and from the next frame's views. So a widget claims the pointer while the pointer is over it, before any press, and a click on it never reaches the game. With no rect, the engine doesn't know where a view's own widgets are, as it does the GUI's, so a press with nothing before it (a finger that touches, a widget that appears under the pointer) reaches the game and the other views for the frame it lands in.
- `GUI.ClaimPointer(Rect rect)` says where a widget of the view's own is, in the GUI's pixels, every frame it's there. While the pointer is on it, the pointer is the view's, as it's the GUI's on the GUI's own widgets: by where the pointer is now against where the last frame's claims were, so from the frame a press lands in, a finger's too. Off the rect it claims nothing: a widget that's dragged claims the pointer with no rect meanwhile. Up to 256 rects in one frame; past those, a rect claims the pointer while the pointer is on it, which hides a frame late.
- The GUI's own use comes first: a view never reads what the GUI is using, whatever it claimed, and the GUI's widgets work under a claim, as they're drawn on top. While a view has the keyboard, Tab and the arrows don't start moving the GUI's focus.
- Views that claim the same device all go on reading it: which of their widgets is on top is theirs to know. Up to 16 views claim in one frame and go on reading; past that, a claim still hides.
- A modal is an anchored area over the screen, dimmed. The one drawn last is on top, and only its widgets work. Its first widget takes the focus the frame after it comes up, and back doesn't close it on the frame it came up, so the press that opened it doesn't. `GUI` has no modal at a rect yet.
- The drawing: a dark panel behind each area and the engine's default font, in the theme's colors.
- `GUI.Control(Rect rect) -> GUIControl`. Its interaction flags follow the device naming convention:
  - `hovered`: the pointer is on it, with nothing of the GUI's over it.
  - `pressed`: the pointer holds it, from a press on it until it lets go, wherever it goes meanwhile, as `devices.mouse.left.pressed` is true while the button is held. A button looks down while it's `pressed` and `hovered`, and a handle follows the pointer while it's `pressed`. It's false in the frame the pointer lets go, and Enter held on it doesn't count.
  - `focused`: the keyboard and the gamepad are on it.
  - `clicked`: a press on it let go on it, or Enter, Space or the south button went down while it had the focus. For one frame.
  - `down`, `up`, `cancelled` and `position`: the pointer edges, cancellation and position described under Custom control composition above.
  - `hover`, `press` and `focus` (Provisional, 2026-10-29): `hovered`, `pressed` and `focused` as floats from 0 to 1 that ease toward them over the theme's `transition`, as `GUI.Animate` does. The first frame a control is called they're at their states.
- A click with the pointer doesn't give a control the focus, as it doesn't a button. In a Disabled block or outside the modal that's up, it cannot hover, hold, focus or click; an active gesture reports cancellation once. The focus skips it, and the pointer on it is still the GUI's.
- While a control has the focus, the view that called it goes on reading the keyboard and the gamepad, but for what moves the focus and clicks: the arrows, Tab, Enter, Space and Escape, and the d-pad, the left stick and the south and east buttons. The input's `Sample` and the other views read none of it, as with any focused widget. So a menu's own shortcuts (a card's number) work while one of its cards has the focus, and a control can be a text field: its view reads `devices.keyboard.text`. A view that runs once per entity is one view. Under a modal, no view reads anything.
- Unkeyed repeated calls use occurrence identity. `GUI.Key` makes repeated controls follow application keys instead.
- `GUILayout.Reserve` supplies layout space for `GUI.Control`, and `GUI.Draw` places its custom visuals among the GUI's widgets.
- `GUITheme`'s fields: `Color`s `text` (text, and a slider's thumb), `panel` (an area's background), `control` (a button, a toggle's box, a slider's rail, a color field's frame), `hot` (those with the pointer on them), `pressed` (a button held down), `field` (a field to type into), `fieldHot` (one with the pointer on it), `accent` (the focus's outline, a toggle's check, a slider's filled part); `float radius` (the corners', in pixels; 0, its default, is square); `Font font` (their text's, `Font.Regular` by default; Provisional: one font for all the widgets, as the theme's text size is one). A modal's dim isn't in it, nor how much a disabled widget fades.
- Provisional (2026-10-29), after those: `Color border = Color(1, 1, 1, 0.12)` and `float borderWidth` (0: none), an outline inside each widget's and panel's edge; `float shading` (0 to 1), how much darker each part's bottom is than its top; `Color shadow = Color(0, 0, 0, 0.35)` and `float shadowSize = 16`, a soft shadow under each area's panel, a quarter of its size lower; `float transition = 0.1`, seconds a widget's body takes to fade between its states' colors; `float textSize = 16`, the widgets' text, a widget being 12 pixels taller; `float padding = 12`, inside an area; `float spacing = 5`, between widgets. A value that isn't a number is the default (0 for the lengths that are 0 by default), and one out of range the nearest in it: lengths at least 0, `shading` at most 1, `textSize` 1 to 512, `transition` at most 60. A row's spacing is the one its last widget was laid out with. The mouse wheel's step stays 28 pixels whatever the text size. The default look gained the panels' shadow and the fades; a game that sets no theme otherwise draws as it did.
- An anchored area (`GUILayout.Area(anchor)`, `GUILayout.Modal`) is shown at a size that eases toward its content's, as `GUI.Animate` does over twice the theme's `transition` (Provisional, 2026-10-29: the owner asked for the settings window that grows and shrinks between tabs to be smoothed), and is placed at its anchor by that size. The first frame it's drawn it's its content's size. While the shown size differs from the content's, from the frame after the change, its content is clipped to the panel; an area at rest has no clip. Its widgets' places go by where they're drawn, as ever.
- `GUI.Tween(float target, float seconds[, float from])` (Provisional, 2026-10-29, from the desktop demo's gaps; the owner: "let's close those gaps"): moves at a constant speed, kept as `GUI.Animate`'s values are; a change from rest takes `seconds`; a change while moving keeps the speed it has, so turning back takes as long as it went; it arrives on time within a relative 1e-5 of rounding. Its first frame, and the first after a frame it wasn't called, it's at its target, or at `from`. No frame time or no seconds is at the target at once.
- `GUI.Target(RenderTarget target, Rect shown) { ... }` and `GUI.Target(target) { ... }` (Provisional, 2026-10-29): the block's widgets draw into the target's destination of the GUI's list, laid out in its logical pixels with its size as the screen's; the pointer is mapped through `shown` (outside it, nowhere), and remembered places, hover, focus navigation and claims are kept in screen pixels, so input hiding works as for any widget. No rect: no pointer. Nested, the window, or an invalid target: the block is skipped. `GUI.Draw` inside draws into the target. The GUI's list is added over the world, so what shows the target is drawn after the block in `GUI.Draw` to show the frame's widgets.
- `Label(text, float size)` in `GUI` and `GUILayout` (Provisional, 2026-10-29: after the showcases, the owner: "lets deal with the gaps you found"): a label at a text size of its own, a heading, its line as tall as a widget of that text size; the same size range as the theme's, a size that isn't a number being the theme's. A toggle's box is no rounder than a quarter of its size whatever the theme's radius, its check and focus outline going around that.
- `GUI.Animate(target, seconds)` and `GUI.Animate(target, seconds, from)` (Provisional, 2026-10-29), of a `float`, a `float2` or a `Color`: the target, eased toward from last frame's value, `1 - e^(-dt * ln(100) / seconds)` of the way left each frame of `dt` seconds (`Frame.dt`), so 99% in `seconds`, settling exactly once within 0.01% of the target. Kept by the GUI, by an ID as a widget's (its call site, the entity, a loop's turn, `GUI.Key`). The first frame it's called, and the first after a frame it wasn't, it's at its target, or at `from`. Up to 1,024 kept at once (shared with the widgets' fades, the anchored areas' sizes and `GUI.Tween`), the oldest free first; past that a new one isn't kept: it's at its target, or at `from`. GPU code keeps no animation state: an animated value reaches a fill or a frag as any value of the view does (captured, or in the draw's values or an instance's). A `seconds` of 0 or less, or a host that gives no frame length, is at the target at once. Nonfinite values aren't kept. Local only, like every widget; nothing of it is in the match.
- A part is no rounder than half its smaller side, so a slider's rail and a toggle's box end as a pill and a circle under a big radius. A part drawn around another (the focus's outline) or inside one (a toggle's check) is rounder or less round by how far it is from it. With a radius of 0 the widgets are the plain rects they always were.
- An area's panel has the theme it opened with, whatever its block sets. `GUI.SetTheme` inside a `GUI.Theme` block ends with the block, which puts back what it found. `GUI.Theme` lays nothing out, like `GUI.Disabled`. Blocks nest up to 32 deep with containers; past that, a `GUI.Theme` changes nothing.
- `GUI.Theme(theme);` with no block is an error that names `GUI.SetTheme`, and `GUI.SetTheme(theme) { ... }` one that names `GUI.Theme`. Several settings in one block, with commas, are `Draw`'s to bring.
- `GUI.Disabled(bool disabled) { ... }` grays out the widgets in its block while `disabled` is true, as Unity's `GUI.enabled = false` and `EditorGUI.DisabledScope` do: they're drawn at half opacity, and can't be hovered, pressed, focused or typed into, so Tab skips them. A widget disabled while it's pressed lets go, and a field disabled while it's typed into keeps its old value. The block lays nothing out: its widgets go on in the container around it, `GUI`'s and `GUILayout`'s alike. The mouse on a disabled widget is still the GUI's, hidden from the input's `Sample`. Inside a disabled block, another stays disabled whatever its own `disabled` is. An area's panel doesn't fade, only its widgets.
- **Quitting** (the owner's ask, 2026-11-04, from a game that called C's `exit` and so skipped the engine's shutdown; Provisional): `Application.Quit()` ends the program after the frame, as its window closing does: the host leaves the match (its server's players told, or with host migration handed it), lets go of its local state, and the platform writes its caches, closes the devices and ends with exit code 0. It's a statement of local code, as `Session`'s calls are, and the host takes it after every other request of the frame. A headless run ends at that frame, as at its script's `quit`, with its pictures; on the web the page stops the frame loop and hears the program's exit (`Tide.onExit(0)`), its last frame still shown, as a page can't close itself; Android finishes the activity. Inside another program (`tide/embed.h`) nothing ends: `tide_embed_status.quit` says it was asked, and Unity's `TideRunner` ends play mode or quits the player, unless its `QuitAsked` event has a handler. A dedicated server runs no local code. A run of several players with no window ends at a player's quit as at a process that stopped (see the standard host's notes).
- **Clipboard:** `Clipboard.Copy(string text)` puts text on this machine's clipboard, like a "Copy" button next to a room's code. It's a statement of local code, as `Session`'s calls are (views, local handlers and the functions they call, not `Sample` or match code), and the host does it after the frame; the frame's last one wins. Up to 255 bytes of UTF-8 for now, cut where a character starts. A browser takes it only shortly after a click or a key, as when a button is pressed. Pasting needs no call: Ctrl+V (Cmd+V on macOS) types what's on the clipboard into the text field that has the focus, but for newlines and tabs, on desktop and the web. Reading the clipboard from code isn't offered, since a browser only gives it to a paste.

<a id="open-20"></a>

### Open

- A field for any enum. A game couldn't write one itself until there are generics.
- Styles and themes.
- More than one block per function, like Swift's labelled trailing closures.
- Public control handles for explicit navigation links; custom composition, scoped keys and GUI-layer drawing are implemented above.
- Scrollbar visuals, list virtualization, kinetic touch scrolling and navigation overrides. Editing keys repeat; general widget navigation repeat remains open.

<a id="prefabs-and-authored-scenes"></a>

## Prefabs and authored scenes

<a id="decided-25"></a>

### Decided

- Authored scenes/prefabs are human-readable text with Tide-like syntax. Files
  describe entities, component values and references; game behavior remains in
  ordinary Tide scripts. Refactoring an invalid component/type/reference must
  produce a compiler/editor diagnostic rather than silently omit an object.
- One rooted entity tree can serve as a reusable entity prefab or a loaded scene.
  Nested entities follow their parent's transform and lifetime. Reusable nested
  prefabs use the same authoring format.
- Values left out use component defaults. Authored overrides remain explicit in
  text, so ordinary source control diffs and merges are understandable.
- A prefab has an explicit name. Entity references are checked against the
  resolved authored composition, including nested prefab instances.
- Required authoring fields may be marked in component code. This validation
  applies to authored composition, while ordinary code can build an entity in
  stages. It does not make regular component constructors require every field.
- Component availability comes from the game's compiled code and packages;
  opening an authored file alone does not give it unrestricted access to code.
- Settings are ordinary components on the root entity, configurable when
  spawning/loading. Prefabs do not declare their own typed parameters for the
  first build (owner decision, 2026-10-12).
- A prefab instance's complete tree, components, references and parenting exist
  before any of its `Spawned` handlers run. Handlers then run root-first (owner
  decision, 2026-10-12).
- Inherited descendants support per-instance field-value overrides using matching
  nested `entity` blocks. Only values of existing component fields may change;
  inherited components and children cannot be added, removed or replaced. Nested
  instance roots retain their existing component and child additions (approved
  2026-10-24). Reference scopes, defaults, construction order and entity counts
  are unchanged.
- Tide has no scene editor of its own (owner, 2026-11-16, removing the native
  one built 2026-10-12). Each game draws in its own way, so an engine editor
  can't show a game's scenes as the game does. Games provide their own tools,
  and the engine's job is to make those easy to build. Authored files are
  edited as text, or made in a Unity project through `tide unity`.

<a id="provisional-26"></a>

### Provisional

**Current text/compiler implementation (2026-10-24).** The spellings and initial
limits below remain provisional except for the decisions above. Transform and
parenting are described separately in the following section.

Use `.tprefab`, normally one named declaration per file, such as
`Enemy.tprefab`. Its body is its root entity. Ordinary component values use the
existing Tide spelling; a semicolon ends each component entry. An `entity` block
adds a named child. Names are stable authored identifiers, not runtime entity IDs.

```csharp
// Enemy.tprefab
namespace Game;

prefab Enemy
{
    Transform;
    Health { value = 100 };
    Aim { muzzle = Weapon.Muzzle };

    entity Weapon : Pistol
    {
        Transform { localPosition = float3(0, 1, 0) };
    }
}

// Pistol.tprefab
namespace Game;

prefab Pistol
{
    Transform;

    entity Muzzle
    {
        Transform { localPosition = float3(0, 0, 0.5) };
    }
}

// Components remain code in .tide files.
component Aim
{
    [SceneRequired] Entity muzzle;
}
```

- `entity Weapon : Pistol` instantiates Pistol as that child and applies the
  component values in Weapon's block as overrides on its root. Its named
  descendants participate in paths such as `Weapon.Muzzle`. Its root can add
  named children and components. A matching `entity Muzzle { Transform {
  localPosition = float3(0, 0, 0.8) }; }` inside Weapon overrides an existing
  descendant's fields; nested matching blocks reach deeper descendants. These
  descendant blocks require nonempty component field assignments: no bare or new
  component, new child, base prefab, removal or replacement. Duplicate matching
  blocks or fields are errors. Top-level prefab variants are not implemented.
- Authoring expressions are literals, the existing constant/default expressions,
  assets and named entity references. They do not call game functions, run
  statements, read live worlds or start tasks. Entity names/paths are resolved
  against the complete composition, allowing forward references. A path is
  relative to the root of the prefab whose source wrote it; inherited paths
  retain that scope in a nested instance. `this` refers to the entity block
  containing the value. Parenting is
  determined by nesting; reference fields may form cycles without changing that
  parent tree. Recursive prefab inclusion and ambiguous/missing names are errors.
- A nested override changes only fields it names. Other fields come from the
  nested prefab and then the component defaults. Duplicate components or fields
  in one authored block are errors. Component/type/default changes in code are
  reflected during validation; stored text need not repeat unchanged defaults.
- Entry points are `Spawn(Enemy)` and `local Spawn(Enemy)`, returning
  Entity and LocalEntity respectively. Root component additions/overrides can
  use the existing argument-list shape, for example
  `Spawn(Enemy, Health { value = 50 })`. The compiler knows every effective
  archetype and checks each instantiated placement's component/reference types.
  Explicit Entity and LocalEntity fields retain their meanings.
  A component literal overrides only its named fields; omitted fields retain
  authored values. A bare component argument resets it to its component defaults.
  Components absent from the authored root can be added through these arguments.
- `Scene.Load(Level)` loads the same authored tree as a scene, with its authored
  root as the scene entity. Loading adds private scene-instance metadata;
  ordinary Spawn does not. Loading/unloading and scene visibility must preserve
  existing scene ownership rules. A loaded root stays independent, as today's
  scenes do. This requires generated construction support, not a global runtime
  prefab registry.
  Root overrides follow the prefab name: `Scene.Load(Level, LevelSettings {
  difficulty = 2 }, Visibility { group = group })`. Visibility is an ordinary
  optional root component, using the same shared groups as entities. Only match
  scenes take Visibility. Loading from local code creates local entities; match
  code creates match entities.
- Settings use ordinary root components, such as
  `LevelSettings { difficulty = 2 }`. Code reads them through its usual typed
  component access. Prefab-specific parameter declarations are not part of the
  proposed first slice. Root overrides must be applied before initialization
  handlers observe the instance.
- Reserve the complete instance's handles, initialize components/references and
  establish parenting before sending any of that instance's Spawned events.
  Then send Spawned in root-first authored order. This makes a root handler's
  required child references usable immediately. Changes recorded by those
  handlers remain ordered/deferred, as elsewhere. Code-driven ordinary Spawn
  keeps its current behavior.
- `[SceneRequired]` initially covers Entity/LocalEntity reference fields and
  nullable forms of those. An effective authored value must resolve to an
  existing entity of the correct placement; a missing/null reference is an
  authoring error. Nested prefab overrides participate in the check. Ordinary
  code-driven Spawn/Add, later assignments and deliberate runtime overrides are
  not constrained by this authoring annotation.
- `.tprefab` files join the same compiler input set as `.tide` files. Folder
  builds include them under existing game/package boundaries, and CMake builds
  use their registered game's source set. IDE analysis shares that build
  context, so completion and rename use actual visible declarations.
  A `.tprefab` file contains prefab declarations and namespace/using directives;
  components, functions and game settings belong in `.tide` files. Prefab
  declarations are also accepted in `.tide` files. Every declaration is validated,
  including unused prefabs and required fields. Composition is initially bounded
  to 1024 entities per instance and 128 levels of nesting.

<a id="open-21"></a>

### Open

Further authoring/editor work:

- Root identity filters. A prefab has no implicit component/type; use explicit
  root components for filters.
- Language-server rename/completion for authored entity paths.
- Authoring machine-local fields on match entities, including model/material
  selection, without putting rendering resources in match snapshots or trusting
  serialized executable code. A basic data tree alone does not solve this.
- Defaults-versus-overrides during live editing/hot reload of existing instances.
  The first slice can instantiate new trees; automatic modification of existing
  gameplay instances needs a separate policy.

<a id="transform-and-entity-parenting"></a>

## Transform and entity parenting

<a id="decided-26"></a>

### Decided

- One built-in `Transform` component works in match or local placement, with `localPosition`, `localRotation` and `localScale`. These values are relative to the parent, and root values place it in the world.
- Match `Transform` bindings use correction smoothing by default: `localPosition` has the `[Position]` role and `localRotation` the `[Rotation]` role. `localScale` retains ordinary tick interpolation. Local placement remains current-value access, and `World` hierarchy queries retain stored-state reads. The default roles are decided; the correction algorithm and half-life retain their provisional status under Views.
- Its computed `position` reads world position and writes `localPosition` in parent space. Component storage remains the three local TRS fields.
- Parenting is an entity relationship, independent of component value types. Descendants move with their parent and are destroyed when their parent is destroyed.
- Reparenting follows Unity's default of preserving world placement, with an option to retain local values. Detaching preserves world placement by default. Cycles are rejected without changing the hierarchy.
- Static access and typed entity handles preserve the match/local boundary. Match hierarchy state participates in deterministic snapshots, hashes and transfer; local hierarchy state stays outside it.

<a id="provisional-27"></a>

### Provisional

Implemented first-build interface and details:

- `entity.SetParent(parent, worldPositionStays = true)` records a deferred structural change. `null` or `default` detaches. Local entity handles require local parents. Commands validate cycles and live generations in deterministic application order.
- `world.LocalToWorld(entity)` returns a `float4x4` composed root to leaf; `world.Parent(entity)` returns the same kind of handle as its argument. Both read stored state, with normal caller capabilities and Transform read dependencies. Dead entities give identity/null, and absent Transform components contribute identity.
- `world.ParentToWorld(entity)` returns the root-to-parent matrix, including a retained visibility anchor where a projected parent is hidden. Ordinary roots and dead entities give identity. `Transform.position` applies this to the binding's current local position. Its setter ignores singular parent matrices, nonfinite inputs and nonfinite converted results.
- Implemented computed properties have explicit accessor bodies, with getter-only and setter-only forms. Compound assignment evaluates the receiver once, then getter, right-hand expression and setter. Numeric prefix increments return the calculated value supplied to the setter, postfix increments the getter's original value. A property cannot be passed by `mut`/`out` or written through a returned subfield. Literals initialize stored fields. Accessors follow ordinary method capabilities, scheduling and GPU restrictions.
- The component context is written `this` and contextual `world`. A local component helper qualifies its parameter with `local`. Verified bindings retain their selected world. Recorded match-event bindings retain identity but grant no historical World query. Component methods use either contextual world access or an explicit World parameter. These spelling and edge choices are implementation details, not additional owner-approved language designs.
- Transform defaults are zero position, identity rotation and unit scale. World rotation composes normalized quaternions. Keeping world placement adjusts local TRS; shear from nonuniform scale and rotation cannot be preserved exactly. Singular/nonfinite results are rejected, without changing local values or links. Keeping world placement requires a Transform on the child.
- Destruction walks descendants before the root and invokes existing Destroyed handlers while each entity still exists. Loaded scene entities remain independent roots. An ordinary subtree parented into another scene transfers membership there; detaching retains its scene.
- The compiler emits private per-world links using existing world-owned containers and checked command queues. No engine runtime registry or new public runtime entry point is required.

<a id="open-22"></a>

### Open

- The prefab text format and editor are future work; this foundation does not implement them.
- More complete hierarchy presentation and authoring APIs.
- Presentation interpolation of a composed hierarchy and optimized deep-hierarchy caching.

<a id="local-state"></a>

## Local state

<a id="decided-27"></a>

### Decided

- The world holds a match: the state every machine simulates the same way. It only exists while a match is on. Single-player is a match too, on a server the machine runs itself and reaches through a loopback transport, the same path as any other connection.
- Local state belongs to one machine and lives outside every world: menus, settings, connection status, animation timers, particles. It's never sent, rolled back or hashed.
- `local` on a singleton, scene or event declaration makes it local. A component defines data and defaults shared by both worlds; local belongs on its placement and access. Match code cannot read local storage, and local code cannot change the match. Structs and ordinary functions work with values from either side.
- A local singleton exists once per machine, for the whole program. Local entities hold components in local storage.
- Views run every frame, in a match or not. They read the match, and read and write local state: `mut` local parameters, and `Spawn`, `Add`, `Remove` and `Destroy` of local entities. A view only runs when everything it reads exists, so a view of match components or singletons doesn't run outside a match.
- Local structural changes and local events are handled at the end of the frame, as the match's are at the end of the tick.
- The GUI is immediate mode, drawn from views (see GUI).
- **Local fields.** `local` before a field of a match component or singleton makes that field this machine's: it lives outside the match, starts at its default on every machine, and is never sent, hashed, snapshotted or rolled back. It's for what a machine keeps for the match's entities to show them: a baked mesh, an animation timer, a smoothed position, a C library's handle. The match's layout, world hash, deltas and what a joining player downloads are exactly what they'd be without the field.
  - Match code can't see local fields: reading or writing one in a system, a match handler or a task is an error, and so is naming one in a `Spawn` or in a component value. The errors say why, and where the code belongs: a view.
  - In a view, `mut Box box` allows writing the component's local fields only. Writing a match field through it stays an error ("a view can't change the match..."), `mut` on a match component with no local fields stays one too, and `mut` that writes no local field gets the usual warning.
  - Nothing attaches or removes them: every entity with `Box` has its local fields, on every machine, however that machine learned of the entity (it ran the spawn, joined later, was sent the world again, took over as host, hot reloaded). They take memory only once written, and reading ones never written gives the defaults.
  - An entity's local fields go when the entity is in neither the world views draw (the predicted one) nor the verified world. So a destroy the client predicted wrong, which the server undoes, keeps them, and a spawn it predicted that never happened leaves none. Nothing about it is timed.
  - Singletons have them too, like a texture painted from the match's state.
  - A view's match fields are blended copies, as ever; local fields aren't blended, and are read and written in place.
- **The compiler enforces the boundary,** so no mistake can reach a running game:
  - Match code (systems, match event handlers, match scenes) can't read or write anything local, and can't read this machine's `Devices`: it takes a `Devices` parameter, the owner's, which the input sends. The input's `Sample` reads this machine's, and writes only the input.
  - Local code (views, local event handlers, local scenes) can read the match but never change it: no `mut` on match components or singletons, and no spawning, changing or sending match things. Views read it as it's drawn, or `verified`; a local handler hears its events (see Events).
  - The only way from local code into the match is input. Starting, joining and leaving a match are session calls, which never touch a running match.
  - Errors say where to go instead: "a view can't change the match: put it in the input and handle it in a system."

```csharp
component Spark
{
    float2 position;
    int framesLeft = 30;
}

// Reads the match and leaves a trail of local sparks behind every ball.
view Trail(Body body, with Ball)
{
    local Spawn(Spark { position = body.position });
}

view DrawSparks(mut local Spark spark)
{
    Draw.Circle(spark.position, 0.1, Color.yellow);
    spark.framesLeft -= 1;
    if (spark.framesLeft <= 0) this.Destroy();
}

// Error: match code can't read local state.
system Count(local Spark spark) { }
```

```csharp
component Box
{
    float3 pos = float3(0, 0, 5);
    local List<Vertex3> verts;
    local List<int> faces;
}

// Bakes each box's mesh once, on this machine, and draws from it
view DrawBox(mut Box box)
{
    if (box.verts.count == 0) Bake(box);
    Draw.Mesh(box.verts, box.faces, float4x4.Translate(box.pos));
}

void Bake(mut Box box)
{
    box.verts = [Vertex3 { position = float3(0, 0, 0) }, Vertex3 { position = float3(0, 1, 0) }, Vertex3 { position = float3(1, 1, 0) }];
    box.faces = [0, 1, 2];
}

// Error: 'verts' is a local field of 'Box': it's this machine's, and the match can't see it.
system Shrink(mut Box box) { box.verts.Clear(); }
```

<a id="provisional-28"></a>

### Provisional

Implemented placement spellings: `Spawn(...)` creates match entities; `local Spawn(...)` creates local entities. A `local` component access qualifier selects local storage in views, local handlers, queries, shader bindings and async parameters, for example `mut local Transform transform` or `query (local Transform transform) transforms`. Ordinary helper parameters retain value/`mut` rules; `local Transform transform` selects local ownership when the helper uses component context. Component methods are specialized for each placement they are called on: implicit `this` is `Entity` or `LocalEntity` accordingly. Explicit entity parameter and return types retain their meaning. An unused user method is checked once in match placement; engine accessors are instantiated only when called. `Get`, `Has`, `TryGet`, `Set`, `Add` and `Remove` select placement from the typed entity handle. Component declarations cannot be `local`. Rendering resources and LocalEntity fields restrict a component to local placement. Components with attached `local` fields currently require match placement; supporting those same definitions on local entities remains open.



- `local` selects entity placement in `local Spawn`, component storage in access parameters, and machine-local singletons, scenes, events, handlers and attached fields. It goes before singletons, events and event handlers; before any other declaration it's an error that says why (structs and functions belong to neither side, views are always local, systems run the match). Anywhere else it's a name like any other, a field's too.
- **`LocalEntity`** is an entity of the local world. `local Spawn` returns one, and `this` is one in a view of local components, where in a view of match components it's an `Entity`. Local code can hold and read an `Entity` (the unit a player selected, say) but never change one. The match's declarations can't hold a `LocalEntity`, and neither can structs, which both sides share.
- A view runs for the entities of one world: its components are all local or all the match's.
- Local handlers handle local events, and `Spawned` and `Destroyed` of local entities, with local state only; the match's events, with what they take of the match as the event left it (see Events); and `Forgotten`, with the match component or singleton whose local fields are going (below).
- The host keeps the local state and calls `tide_local_init(local)` once, then `tide_frame(w, previous, alpha, verified, verified_previous, verified_alpha, local, draw, gui)` every frame. `tide_frame` runs the local handlers of what the match sent since the last frame (which the host handed it with `tide_local_events`), lets go of the local fields of entities that are gone, runs the views, then applies their local changes and events. Outside a match, `w` is NULL, and views that read the match don't run.
- The local world has its own entity table and queue, which grow as they need, as the match's do.
- **`Frame.dt`** (the name is a pick, to confirm: `Time` is the match's, so Unity's `Time.deltaTime` can't be it) is the seconds since this machine's previous frame started, a `float`, read-only: what moves things that aren't the match's (particles, menus, a camera's shake) at the same speed whatever the display's rate.
  - It's this machine's, and has nothing to do with the match: it's there in a local scene and while connecting, where no view that takes `Time` runs, and in a match it's the same value, whatever the tick rate and however many ticks the frame ran.
  - Local code reads it: views, local handlers, local tasks (async functions that read it are local, as ones that use local state are), and the functions they call, in a sort's comparison and a parallel loop's steps too. A local task's `Wait.Seconds` counts the same seconds down, and one that waits a frame at a time, `await Wait.Frames(1)`, moves on by it each frame.
  - The match can't read it, as it's another on every machine: a system or a match handler that does is an error that says to take `Time time` and read `time.dt`, a tick's length, and a function that reads it is local code, which the match can't call. The input's `Sample`, `Sanitize` and `Predict` can't either, as they run once per tick: a view keeps what `Sample` needs in local state. Nor can methods, which are handed nothing, or a frag or vert.
  - It's the length the host measured, as it is: a frame after the window was dragged or the page was hidden is that long, and a game clamps it where a big step would show (`Math.Min(Frame.dt, 0.05)`). It's never negative or NaN, and it's 0 until the host has given a frame's length: in a handler that runs as the local state is made, like `Spawned` of a local `Main`.
  - There's no clock of seconds beside it. A float of seconds loses precision as it grows (after four and a half hours its steps are 2 milliseconds, about an eighth of a frame at 60 a second), which shows in whatever is animated by it. A game adds `Frame.dt` up into a field of its own, and wraps it where what it drives repeats. Asking `Frame` for one, as a member or a function by a clock's name in any case (`Frame.time`, `Frame.t`, `Frame.elapsed`, `Frame.seconds`, `Frame.Now()`), is an error that says so and what to write: that field, or `time.t` of `Time time` for the match's seconds, which is all it says in a system or a match handler.
  - `Frame` is built into the language, as `Screen` and `Cursor` are: a game can't declare the name, in a namespace or outside one.
  - Hosts give it before each `tide_frame`: `tide_local_frame_time(local, seconds)`, which `tide/run.h` does.

```csharp
struct Spark
{
    float2 position;
    float2 velocity;
    float age;
    float life = 0.4;
}

local singleton Sparks
{
    List<Spark> list;
}

view DrawSparks(mut local 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.position += spark.velocity * Frame.dt;
        sparks.list[i] = spark;
        Draw.Circle(spark.position, 0.1, Color.yellow);
        i++;
    }
}
```

Local fields, beyond what's decided:

- **What they hold** is what a local component's fields can: numbers, vectors, enums, structs, fixed arrays, text, lists, maps, sets, grids, `Entity` and `LocalEntity`, each with a default like any field's. `local float3[4] pieces;` keeps an ordinary value array outside the match. `[Snap]` on one is an error, as local state is never blended. A local field shares its name with no other field or method of its component.
- **Where `local` can't go.** On a field of a struct (structs belong to neither side: make the field that holds the struct local), of the input (all of it is sent), of an event (it's sent whole), or of a local singleton (all of it is local already): each is an error that says so, and the last has a quick fix that removes the word.
- **They're reached through a parameter**, `box.verts`, where local code has the component or singleton itself:
  - a view's, read through `Box box` and written through `mut Box box`;
  - an ordinary function's, which gets them with the component or singleton: `void Bake(mut Box box)` writes them, `int Corners(Box box)` reads them, and the caller passes its own bound parameter, `Bake(box)`. The parameter can go through helper chains with its local fields. Such a function is local code: only views, local handlers and functions like it call it, and calling it from match code is an error that says where it uses a local field;
  - a local handler's of one of the match's events, for the entity the event was sent to (see Events);
  - a handler of `Forgotten`'s (below).
- **A component's or singleton's value is the match's part.** A copy (`var b = box;`), a value written out (`Box { ... }`), and what `world.Get<Box>(entity)` or `default` gives have no local fields, and `b.verts` is an error that says to read them through the parameter. So is naming one in a value, `Box { verts = ... }`, and passing a copy to a function that uses them. Methods work on values, so they have none either, including through explicit parameters; an ordinary function that takes a bound component or singleton parameter does.
- **One side at a time.** A function that changes a component's or singleton's match fields through a parameter and uses its local fields through the same one is an error: no code could call it. This follows helper chains too. A view can't pass a match component or singleton to a function that changes its match fields.
- **Local tasks and local fields** (Claude's picks, 2026-11-14). A local task reads and writes the local fields of the match components and singletons it takes, through its parameter, as a view does: `async void Remesh(mut Chunk chunk) { var built = await Faces(chunk.blocks); chunk.mesh = Mesh(built.vertices, built.indices); }`. The rule above that a task can't see them is a match task's, as match code's: a match task that uses them, itself or through a function, is an error that says to split it.
  - **Which world.** Using a component's or singleton's local fields makes an async function local code (see Tasks), as a function it passes the parameter to that uses them does, or a task it starts or awaits with it. `mut` lets it write the local fields alone: writing a match field through the same parameter is the error a function gets for doing both, "but a task runs in one world". A system can't start such a task (it's local), and a view or a local handler starts it with its own parameter, as any task's component.
  - **What the call changes** (Claude's pick, 2026-11-15): a view or a local handler that starts such a task with its own parameter, or hands it to a function that writes its local fields alone, changes those local fields and none of the match fields, which is what it's checked for: a loop in that view over other entities that finds them by its own match fields is indexed as if nothing changed them (Indexed loops, A component handed on to change its local fields alone), and the task can be handed another entity's grid, `Remesh(chunk, row.other.blocks)`, a copy of its own (Grids, Grids an async function takes). A task that writes a match field of it is a match task, which local code can't start, and one that writes both is an error, as before. C is trusted here as anywhere (C interop): local code can hand its own component to an `extern` function's `mut` parameter, and what C writes to its match fields stays in the view's copy of it, which isn't stored back, so the match doesn't change; for the view's loops the call changes all of the component (Indexed loops). Whether local code should be refused that instead is the owner's.
  - **Got again each time it goes on.** A task's components and singletons aren't kept while it waits, and their local fields come with them: each time the task goes on, it finds its entity's where the local world keeps them, so it sees what a view wrote while it waited, and what it writes is the entity's at once, for the next view to draw. Nothing of them is in the task's frame. A task that uses a component's local fields makes the entity's own as it first goes on with them, written or not, and a view that starts one makes them the entity's own as it runs for it, so the view and the task write the same ones: what the view wrote before the start, the task's code reads until its first wait, and the other way round.
  - **The entity gone.** The task ends once its entity is gone from the world views draw, at that frame's task pass (Tasks, above), and the entity's local fields go once it's in neither that nor the confirmed world (When they go, below). So a task never writes the local fields of an entity this machine no longer has, and none are kept for a task. A destroy this machine predicted, which the server undoes, brings back the entity's local fields as the task left them, but not the task: a view that started it starts it again when it reads that it isn't running, for which a local field can keep its handle, `local LocalTask job;` and `if (!chunk.job.isRunning && ...) chunk.job = Remesh(chunk);`.
  - **Hidden, or without the component.** An entity this machine's player may no longer see is gone from both its worlds: its local fields go, with `Forgotten`, and the task ends; if it's shown again it starts at its defaults, with no task. A component the entity loses, or that the server hides from this machine's player while the entity stays, takes that component's local fields, and a task that takes the component ends with them, as a task without one of its components does.
  - **Forgotten while it waited** can't be: local fields go at the start of a frame only for an entity in neither world, or with the component in neither, and that frame's task pass, after its views, ends the task, whose entity or component isn't in the world views draw either. A handler of `Forgotten` can't be async. The local fields of the match's singletons go when there's no match, and a local task that takes one of its singletons ends when it goes on with no match, or with its match (below).
  - **The match over**: its entities' and singletons' local fields all go at the next frame's start, and at that frame's task pass so do the local tasks of its entities, and those that take its components or singletons, even where the next match has entities with the same handles (Tasks).
  - **Rollback.** Local fields aren't rolled back, and nor are local tasks. A task that goes on after a correction reads its component as the corrected world has it, and its local fields as this machine left them. A replay of the same causal spawn is the same entity, whose task goes on; another birth is another entity, which the task, of the first, never sees.
  - **Predicted and verified.** A task reads its match components as the world views draw has them, as of the frame's latest tick and not blended; local fields are the entity's whichever world a view reads, so a view that takes the component `verified` reads the same ones. A task takes nothing `verified`.
  - **Hot reload.** Local fields and waiting local tasks carry over as before, the fields in the local state's bytes and the tasks where their code and frames are the same. A task that carries over finds its entity's local fields where the new build keeps them, as it does after any wait, and a worker it waited for starts again.
  - **Local handlers.** A local handler of a local event takes local state only, so an async one has no match local fields to use. A local handler of one of the match's events can't be async yet; it can start a local task with its component, which ends at once today: it has no match world to hand the task (not built).
- **Memory.** An entity's local fields take memory from the first frame a view leaves them other than their defaults; a view that takes them as `mut` and changes nothing takes none. A local task that uses them, and a view that starts one, make them the entity's own as they run for it (Local tasks and local fields, above; Claude's pick, 2026-11-14). Where a default needs the heap (text, a list with elements, a grid with a size), a view that takes them as `mut` makes the entity's own as it first runs for it. Their text, lists and grids are in the local state's heap; a game whose only such fields are local has no heap in the match.
- **When they go.** At the start of a frame, before the views: an entity's, once it's in neither world, or has the component in neither; a singleton's, once there's no match, back to their defaults; and all of them once the match this machine was in is over (it left, was dropped, or the match ended), whatever match the next frame sees, as another match's entities have the same handles. Entities only come and go with ticks, so a frame looks when either world's tick changed since the last one did.
- **An entity after a rollback** (decided 2026-11-06). Local fields belong to the opaque logical entity, independently of the physical slot or table row storing it. Replaying the same causal spawn keeps its logical identity and local fields, including when authority corrects its initializer values. A different causal birth has a different identity and starts with its local defaults. Removed predicted entities are forgotten once they are absent from both presentation worlds.
  - The generated 32-bit presentation marker derives only from the full logical identity. It contains no digest of component values, private policy or allocator state. It is optional metadata outside the match's hash/packed state; a received entity still has its complete logical identity when that marker is absent. Games needing it retain four bytes per entity in that sidecar.
- **`Forgotten`** is how a local handler hears of it, to let go of what the fields hold, like a C library's handle: a built-in local event, sent to an entity as its local fields of a component go, before they do.

```csharp
component Model
{
    int kind;
    local int handle; // A C library's
}

local event(Forgotten) FreeModel(Model model, mut Loaded loaded)
{
    ReleaseModel(model.handle);
    loaded.count -= 1;
}
```

  - The handler takes the one match component or singleton whose local fields are going, and local singletons. `this` is the entity's handle, an `Entity` that's no longer alive.
  - The entity is gone from the match, so only its local fields are there to read: a match field, or the component as a whole, is an error. What the handler needs of the match goes in a local field while the entity is there.
  - It runs for entities that had something written, as the others have nothing to let go of, and for a singleton once, as the match goes. It isn't async, and the program ending sends none.
  - Games can't send it, and a handler of it is a local handler: `local event(Forgotten) ...`.
- **In C**, the generated `Box` struct, `tide_get_Box` and the rest stay the match's part. The local fields are a struct of their own, `Box_local`, which the local state keeps: `tide_has_Box_local(local, entity)` says whether anything was written for an entity, `tide_get_Box_local(local, entity)` gives a copy (the defaults when nothing was, with text, lists and grids empty), and `tide_set_Box_local(local, entity, value)` sets them, as their bytes. A singleton's are `local->Arena_local`.
- **Hosts** give the frame both confirmed endpoints and their independent fraction: `tide_frame(w, previous, alpha, verified, verified_previous, verified_alpha, local, draw, gui)`, where `tide_session_view` supplies `verified`, `verified_previous` and `verified_alpha`. NULL is for a host with one world: `w` is all there is, and it's what `verified` parameters read too.
- **Hosts hand local handlers what the match sent**, before each frame: `tide_local_events(local, tide_session_events(session))`, which `tide/run.h` does. The session records what its client's ticks send, each event once however often its tick ran, and again for `verified` handlers once the server confirmed the tick. A host that ticks a world itself gives the tick a log, `tide_world_tick_events(w, jobs, &events)`, and hands that over the same way: with no server, what it ticks is all there is, so a tick's events are heard by both kinds of handler at the next frame. `tide_world_tick(w)` records nothing, and its world comes out the same. See `tide/events.h`.
- **Hot reloading** carries local fields over by name with the rest of the local state: an entity's as its component's, field by field, and a singleton's as a local singleton's. A component that's gone, or has no local fields left, takes them with it. What a session recorded of the match's events for local handlers isn't carried over: a swap comes between two frames, when the last frame's were heard, and the ticks a client had run and not had confirmed tell `verified` handlers nothing once the new build confirms them as they were. They still don't tell the others twice.

<a id="open-23"></a>

### Open

- Saving local state, such as settings, between runs.
- **An `Entity` local code holds, after a rollback.** A rollback can give a handle to another entity (see local fields, above), and an `Entity` in local state, like a selected unit, then names the other one: nothing tells local code yet. Local fields are told apart, but only follow what this machine spawned: after the server sends a world again, its entities are known by their handles. And a predicted entity that the server's order gave another handle is another entity to local fields, which start over there rather than move with it.
- Local state for a component the game didn't declare, like a package's: a declaration of its own that says which component it's for, on the storage local fields have.
- Local fields in tasks, and in a component's methods; another entity's, through the `World`.

<a id="scenes"></a>

## Scenes

<a id="decided-28"></a>

### Decided

- 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.
- `scene Arena { ... }` declares one. A loaded scene is an entity like any other: the declaration is its component, and its fields are the scene's state. A system that takes `Arena` runs once per loaded arena.
- An empty scene can end with a semicolon: `scene Main;` means the same as `scene Main { }`. This also applies to `local scene Main;`; braces remain valid.
- `local scene` declares a local one (see Local state). A scene only holds entities of its own side.
- `Scene.Load(Arena { size = 30 })` loads a scene into the current world and returns its entity. `Scene.Unload(scene)` unloads it, destroying every entity it owns. `Spawn` of a scene is an error that says to use `Scene.Load`.
- Scenes should be easy to move between: a menu, then a lobby, then the game, each gone once the next is up (the owner, 2026-11-14: "I imagine scenes almost as what I'm mainly doing ... menu is gone sort of thing", and of the proposals, "just allowing scenes to be more easily dealt with would be a big win"). How that's spelled is under Provisional. Declarations that only exist while a scene is loaded were offered and turned down for now ("i dont think we need" them; "i might change my mind").
- Loading and unloading happen at the end of the tick, like `Spawn` and `Destroy`. Preparation, when declared, precedes `Spawned`; otherwise `Spawned` handlers set a scene up immediately. Its entities get `Destroyed` when it unloads (see Events).
- **Scene preparation** (agreed 2026-11-05). A match scene may declare one `prepare(parameters) { ... }` block. Parentheses are required, including `prepare()`. Its own fields and methods are in scope, and `this` is its root entity. Explicit component and singleton parameters declare ordinary match access; root components must be supplied when the scene loads. Preparation is deterministic synchronous match code, before `Spawned`, for initial and subsequent loads. It may query, change match data and spawn; it cannot await, start async tasks, read local state or load another scene, including indirectly through helpers or sent events.
- The whole match's ticks wait during local preparation, while the host continues networking and local presentation. Progress is game-authored component/singleton data; views read consistent observations of it. There is no inferred percentage. Entities created by preparation exist before the root's `Spawned` handlers.
- Each peer with the full state executes preparation independently from the committed state. The server resumes after its own preparation, without waiting for clients; slower clients catch up through inputs or ordinary state recovery. A game controls waiting, deadlines and removal of unready players.
- `Scene.IsPrepared(scene)` reports this machine's completion; `Scene.IsPrepared(scene, player)` reads server-acknowledged player readiness. Both return false for absent, unloaded or non-scene handles. A scene without preparation completes immediately, and players still acknowledge it. Local scenes allow only the one-argument query and retain ordinary `Spawned` initialization.
- Only committed loads start heavy preparation. A completed result becomes the baseline reused by ordinary prediction and rollback. Leaving cancels and discards unfinished preparation.
- **Ownership:** a spawn joins the scene of the entity the code runs for. In a handler, that's the entity the event was sent to. 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 is never owned: it lives until it's unloaded, whoever loaded it.
- Project startup selects a prefab or scene independently of its name. A prefab starts as an ordinary loaded match scene with its authored root and complete construction before root-first `Spawned`, followed by normal game systems, views, camera and input. No wrapper entity or handwritten `Main` is required. A selected ordinary scene retains its match/local placement. Without a selection, existing `scene Main` startup is unchanged.
- `settings { startScene = Qualified.Name; }` persists that selection. `tide run/build <project> --scene Name` overrides it for that build without changing source or existing `Main` declarations (approved 2026-10-24).
- The selected startup is also the fallback, or `Main` without a selection: when the last scene of its world unloads, it loads again, initialized as at the start. A match startup comes back in the match, a local one in local state while this machine is offline (see Provisional).
- When startup is local, a match can't load it, so a match whose last scene unloads ends. Every machine in it goes offline with `Disconnected` and the reason `Ended` (see Sessions); local state carries on.
- Loaded scenes share their world: the same systems, singletons and `Time`. Scenes that share nothing are separate worlds, which never communicate. Only the server creates worlds, so match code can't (see Open).
- **Visibility:** scenes, entities and whole components use one audience mechanism at different scopes. A loaded scene root's `Visibility` group limits all entities owned by that scene, including later spawns. Scenes are public by default. `Visibility.Set(group, audience)` changes the shared live audience; a player newly included receives the scene's permitted state. Entity and component restrictions intersect the enclosing scene audience and cannot broaden it. Scene ownership and lifetime remain independent of audience groups.
- A scene whose group audience is empty exists only on the server, which is where secrets like RNG seeds go. Code that reads a private scene only predicts correctly on machines that see it, and the server corrects the others.
- A client never loads match scenes on its own: it has the ones the server has it in.
- A system named `Main` is an ordinary system. Without a selected startup or a `scene Main`, compilation reports a missing entry point.

```csharp
scene Arena
{
    int size = 20;
}

scene Hand
{
    PlayerID player;
}

// Sets up each arena. The floor joins that arena.
event(Spawned) SetupArena(Arena arena)
{
    Spawn(Floor { size = arena.size });
}

// Deals each player a hand only they can see.
event(PlayerJoined joined) DealIn()
{
    var group = Visibility.CreateGroup(Audience.Only(joined.player));
    Scene.Load(Hand { player = joined.player }, Visibility { group = group });
}

system Collapse(Arena arena)
{
    if (arena.size <= 0) Scene.Unload(this);
}
```

<a id="provisional-29"></a>

### Provisional

- **Visibility implementation:** sessions project permitted state per recipient, verify it each tick and correct from known verified baselines. See State visibility below for the agreed model, provisional APIs and current limits; validation status belongs in `notes/`.
- **Preparation implementation:** the host runs a private world copy on its background provider, then adopts the completed world at the same tick. It publishes progress snapshots between completed top-level preparation statements; helpers and loops need not publish intermediate progress. Hosts without a provider run synchronously. Sharded matches currently reject preparation blocks. Visibility clients receive the server's permitted result rather than regenerating from missing private inputs. Scene readiness uses the existing authenticated, ordered command channel; it is a player's completion report, not proof against a malicious client.
- `scene` and `local scene` are only keywords at the start of a declaration. A scene's component can have methods, and `Add` can give its entity other components, like any entity.
- `Spawn`, `Add` and `Remove` of a scene's component are errors that point to `Scene.Load` and `Scene.Unload`. `Destroy` on a scene's entity unloads it, and `Scene.Unload` of an entity that isn't a scene does nothing.
- `Scene.Load` makes its entity right away, like `Spawn`, so it follows the same evaluation order and can't be inside `?:` or on the right of `&&` and `||`.
- An entity spawned into a scene that's been unloaded by the spawn's turn is never made, like the loot an enemy drops while its arena unloads.
- Entities unload in archetype order, each archetype's from its last row, and the scene's own entity last. Each gets its `Destroyed` handlers.
- `Scene.Load(Scene { ... }, Component { ... }, ...)` accepts ordinary root components, including `Visibility { group = group }`, before initialization handlers run. Root components are positional, unique and use the same placement/value rules as Spawn; `Scene.Load(scene: Arena)` remains valid when no root components follow. Authored prefab loads use their ordinary root overrides. Local scenes can take ordinary local root components, but no Visibility.
- Scene components expose their declared state; audience policy lives in the root Visibility and shared group directory, and preparation metadata is engine-owned. There is no separate scene visibility enum or player-membership API.
- **Scene filters** (the spelling is the owner's; the rest is provisional): `with scene Arena` and `without scene Arena` in a system's, a view's or an event handler's parameters take only the entities of a loaded `Arena`, or only those of none. An entity's scene is the one it was spawned into (see Ownership above); a scene's own entity is one of its entities, its scene being itself. `with Arena` still filters by the component, so it takes a scene's own entity alone: `event(Spawned) Setup(with Main)` runs once. Several scene filters can be given, each a scene of the entities' own side. A scene filter alone runs for every entity of the scenes, as an `Entity` parameter alone does. `scene` is a word of its own there only right before a name; a filter naming a prefab, or a component that isn't a scene, is an error that says so.
- Startup name resolution: the selection names a declaration, not a string, constructed value or runtime expression. Settings resolve through their source file's namespace/using context; a CLI name has no such context and an unqualified name resolves only in global scope. Invalid or duplicate persistent settings remain errors even with a CLI override. A prefab loads in match placement with normal placement/reference checks; a prefab merely named Main is not the default entry point.
- The engine loads the effective startup itself: `tide_world_init` loads a match startup, and `tide_local_init` a local one, with `TIDE_MAIN_IS_LOCAL` defined. `tide/run.h` starts without a match when startup is local. The startup root is the world's first entity.
- The fallback waits for the end of the tick (the frame, in local state), once every change and handler has applied, so unloading one scene and loading another in the same tick never brings it back. 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 that ends runs no more ticks after the one that left it without a scene. The server tells every player then, and anyone who tries to join. Only the match ends: local state carries on as it was, so whatever local scenes were loaded stay loaded.
- **`Scene.Switch(Arena { size = 30 })`** (built 2026-11-14; the name and the rules are the agent's picks): unloads every scene loaded in its world and loads this one, returning its entity. It takes what `Scene.Load` takes (a scene or a prefab, then root components) and goes where `Scene.Load` goes, a function included.
  - **Which scenes go:** all of the world the scene is of, the match's for a match scene and this machine's for a local one, whichever code loaded them and whatever code switches: no handle is needed, so a button in a view that runs for no entity switches as well as a system of the scene does. Entities in no scene stay, as they do through any unload.
  - **When:** at the end of the tick or frame, in its turn among the tick's changes. Scenes loaded earlier in the same tick go with the rest, each with its `Spawned` and then its `Destroyed`; scenes loaded after it stay. The world is never without a scene in between, so the fallback doesn't load and a match doesn't end.
  - It's `Scene.Unload` of each and one `Scene.Load`, with nothing of its own: the same `Destroyed` handlers, preparation, visibility and prediction.
  - A sharded match refuses it, with an error that says to unload each scene and load the next: its scenes are on several servers.
- **A local startup only comes back offline** (built 2026-11-14, the agent's pick): the fallback loads a local startup scene when no local scene is loaded, this machine is in no match (`Session.state` is `Offline`), and no `Session.Start`, `Join`, `Connect` or `Leave` of this frame waits its turn. So a menu that unloads itself as it starts or joins a match stays gone for the match, and is back the frame after this machine is offline again, whether the match ended, the player left, or joining failed. Before, it loaded again at once, under the match. A match startup's fallback is unchanged.

<a id="open-24"></a>

### Open

- The server's own code: creating worlds from scenes, and moving players between them.
- Entity references that say what they point to, so the compiler can check `Scene.Unload` on an entity read from a field. It can already check `this` in a system taking the scene's component, as in `Collapse`.

<a id="state-visibility"></a>

## State visibility

<a id="decided-29"></a>

### Decided

- Visibility is server-controlled match state. It applies to entities and whole components; fields do not have independent visibility. A hidden entity or component is absent from the recipient's state and queries, rather than replaced with a fake value.
- A `Visibility` component assigns an entity to a shared audience group; on a scene root it also limits every entity owned by that scene. Groups allow world chunks, sets of entities and distant players to share a live audience without repeating a policy on each object. Component audiences can restrict an otherwise visible entity, so a card's back and secret face can be separate components.
- Entity policy respects its enclosing scene; component policy respects its entity. A narrower rule cannot broaden the enclosing rule. The server retains and simulates the full match. Clients predict using permitted state and receive authoritative corrections for consequences they cannot reproduce from it.
- Inputs remain the primary simulation stream. State correction uses a known verified baseline. Hashes verify each tick's permitted state; partition size and the mechanism for locating differences are implementation choices.
- `Shown` and `Hidden` distinguish local availability changes from genuine `Spawned` and `Destroyed` lifetime events (see Events). Hiding an entity does not announce its later destruction.
- The game decides interest rules and public consequences. The engine provides visibility tools rather than inferring what an arbitrary hidden entity might affect.
- The server's own machine sees the whole match (the owner, 2026-11-04: the host may see everything the server does, so that its machine doesn't tick the match twice). Its player is a player like any other in the match, but it has no projection: its views and local code read the server's world, hidden entities and components included, and its local handlers hear everything the match sends. Visibility hides state from the other machines.

<a id="provisional-30"></a>

### Provisional

- `Audience` is a copied value: `Audience.All`, `Audience.None`, `Audience.Only(PlayerID)` and `Audience.From(List<PlayerID>)`. Mutable values have `Add(PlayerID)` and `Remove(PlayerID)`; `Contains(PlayerID)` is read-only. Two audiences are equal (`==`, `!=`) when they have the same players.
- `Visibility.CreateGroup(Audience)` returns an opaque `VisibilityGroup`. `Visibility.Set(group, audience)` replaces its live audience; `Visibility.DestroyGroup(group)` makes stale references empty. Handles are not reused in that match. A default handle means all players.
- `Visibility { group = group }` supplies entity policy. An entity with no `Visibility` is public subject to its enclosing scene. An entity's mutable `Visibility` has `Set<T>(Audience)`, `Set<T>(VisibilityGroup)` and `Reset<T>()`, where `T` is one ordinary whole component. Reset removes the component override. These writes belong to match code and their helper effects participate in scheduling. Ordinary transform parenting does not inherit visibility; the scene root is the enclosing policy.
- Group tables and policy memberships remain authoritative. Recipient projections contain permitted values rather than the private audience table. Match singletons remain public; per-entity secrets belong in components or private scenes.
- Transform parenting does not propagate policy. A projected hierarchy cuts links to hidden parents or hidden parent Transform components. A cut subtree containing permitted Transform state receives an internal parent matrix/rotation anchor computed in the original root-to-parent operation order; unchanged local transform values then preserve exact composed placement, including nonuniform scale and shear. Hidden entity/component payloads are not copied. A cut subtree with no permitted Transform receives no anchor; arbitrary `world.LocalToWorld` on such a partial entity can omit hidden influence, and `world.Parent` sees only projected links. Derived placement is exposed only to support permitted spatial state.
- Match task continuations and opaque `Resident` allocations remain server-only in visibility-enabled games. Clients receive neither raw allocator metadata nor hidden continuation payloads. Cross-boundary gameplay effects must be represented in permitted ordinary state.
- `[Native]` fields are not in a recipient's projection either: they're 0 in a client's world as it receives it, as wherever an entity arrives, and the library makes its state again from the ordinary fields (Box3D and Box2D their worlds, from the bodies). A recipient's hash leaves them out too, so a client's own handles don't count.
- A client's own ticks can't number groups. `Visibility.CreateGroup` there gives a group the client sees (the default handle) when the audience has the client's player, and one hidden from it otherwise; what it puts in a hidden group stays in its world but not in its projection or hash, as it isn't in the server's projection. A group a client made has another number than the server's, so a spawn into one the client sees is corrected once. `Visibility.Set` and `DestroyGroup` change nothing on a client: a reveal or conceal comes with the server's correction.
- Genuine lifecycle journals select recipients at event time, after match handlers and before destruction, and copy only data authorized local listeners consume. Their query rows use the recipient's permitted component set, including excluded-component filters. A private destruction cause record distinguishes a permitted genuine death from concealment even when no local death listener exists. It is not a local event.
- **What each machine hears as an entity goes** (Claude's picks, 2026-11-15, from the hosting machine hearing `Hidden` for every chunk the match destroyed). The server's own machine sees the whole match (Decided), so its local handlers hear every genuine `Spawned` and `Destroyed` and every `Changed<...>` the server's ticks make, hidden entities included, each once and verified at once, while its player keeps up with the server. An entity leaves that machine only as the match destroys it, which is never a concealment there: it hears `Destroyed` and not `Hidden` (which comes for a component removed, or a handler's filter no longer met). The exception is ticks that machine's player didn't follow: where it takes the server's world whole (after another build takes over, or once it fell behind), an entity it had that went in the ticks it skipped goes as `Hidden`, and what came in them as `Shown` with no `Spawned`, with no `Changed<...>` for them, as for a player joining; and what a scene's preparation sent before its host took what local handlers hear isn't kept for it. Another player's machine hears `Destroyed` for an entity it may see at the destruction's turn and `Hidden` for one it may not, whether that was ticks before or in the same tick (its group's audience changed, or the group destroyed, before the `Destroy` was applied): it couldn't see it at its destruction. So a host and a guest differ only by what each may see. Where a machine's own run of a tick destroys an entity the server hid from its player earlier in that tick (a system that sets its own group and destroys its entity; `Visibility.Set` changes nothing on a client), its predicted handlers hear `Destroyed`, as it ran the tick, and its `verified` ones `Hidden`, as the server confirmed it. `Forgotten` comes once on every machine as the entity leaves it, whichever way, so it's the hook for letting go of what a machine keeps for an entity.
- Commands execute server-only in the visibility path. Raw command targets, payloads and large transfers are not replayed to projected clients; permitted state consequences are corrected into their worlds. Owner input is filtered conservatively when its entities or restricted components are hidden, while the recipient's own input remains. Projected remote `previous_inputs` normalize to current permitted input, rather than retaining history from outside the current audience; previous/current wire baselines use the same permitted form before delta encoding.
- Generic custom local/verified events are produced by the client's permitted simulation, not forwarded as arbitrary authoritative outward events. Games remain responsible for public state and input payloads and for what command handlers expose. An authoritative custom-event audience API remains open.
- Projected clients cannot currently promote their partial worlds into authoritative hosts. Existing host migration remains available for full-world games; visibility takeover is refused until a trusted complete-state handover is implemented.
- Current integration uses a canonical per-recipient value stream and bounded delta repair. A hierarchical hash search or game-visible page API is not part of the language API.
- **What a repair costs goes by what changed** (2026-11-14). A machine whose world differs from the server's is sent the entities that differ for it since the tick it last confirmed, each as what differs from what it had, the entities that came into its sight whole and the names of those that left: not its whole view again. Where that comes to more than 32 KiB and is mostly new values of entities it already had, the server offers block hashes of its view instead, as before, which can cost less. A projection lists its entities by their identities, so a machine's rows may be wherever its own ticks and its repairs put them. Each tick's check hashes a container (a chunk's grid, a list, a map) again only when a page it's kept in changed, and a table's rows again only where their pages, their values' pages or their audiences changed. Nothing a game can observe changes but the cost: a world of thousands of chunks sends a player the chunks they walk into.
- In a game that parents transforms (`SetParent` and the other hierarchy operations), what a machine may know of the links (a parent and siblings it may see) and the anchor of a child whose parent it may not see depend on other entities, so they go apart from the entities: as one list of the entities that have any, sent whole with each repair and hashed whole each tick. Its cost is the hierarchy's, a few entities in a world of chunks. (Claude's picks, 2026-11-15.)
- What a machine's own ticks made that the server hides from it (a spawn into a group it isn't in) goes at each repair, as it went when a whole projection loaded.
- **Its systems go across threads as any game's do** (Claude's picks, 2026-11-14; nothing a game's code can observe). A game that hides state keeps each component's and singleton's text, lists, maps, sets and grids apart and in runs, as other games have since 2026-11-13, so a per-entity system that changes its own entities' grids (a new chunk of terrain made from its seed) or lists splits across threads, on the server and on every player's machine, and the world is one thread's bytes on every machine. What players are sent and checked against is their values, wherever each is kept. A shard's game keeps one heap (The world split across servers).
- **A group's audience set by a system's rows is set after them, in their order** (Claude's pick, 2026-11-14). Where a per-entity system's own code calls `Visibility.Set(group, audience)` (outside its parallel loops' steps and the blocks it hands to functions) and that's all it changes of the match's own memory, its rows don't keep it on one thread: on threads they note what they set, and once they're all done each audience is set in its entities' order, which is what setting each where it is would come to, as nothing of a system reads a group's audience back. Two entities that set one group in one tick leave it with the later one's. `CreateGroup` and `DestroyGroup` in a system, a `Set` through a function or in a handler, and a `Visibility` value's own `Set<T>` keep the system's entities in order, as before.

<a id="open-25"></a>

### Open

- A general authoritative outward-event API and its explicit audience/payload rules.
- Whether the server's own machine's views and local queries should see only what its player's audience permits (a fog of war drawn the same on the host), while its world stays the server's.
- Server-side task prediction alternatives and opt-in safe projections for opaque resident libraries.

<a id="shards"></a>

## Shards

One match world split across servers by where things are, for worlds larger than one server holds: a shared canvas with thousands of players, a planet. The agreed design (2026-10-22), built in part since: what's built and what isn't is in `notes/sharding.md`.

<a id="decided-30"></a>

### Decided

- **A shard is an ordinary match.** Each region of the world runs as its own match world on its own server. What another shard tells it (state near the border, an entity arriving, a borrowed entity, an event) comes in as input stamped with the receiving shard's tick, like a command. So each shard keeps every guarantee a match has: determinism given its own input log, rollback for its clients, a hash every tick, cheap snapshots, replays.
- **A split world need not match the same game on one server.** Results depend on when messages crossed between shards; each shard is exactly reproducible from its own log (the owner: "acceptable of course").
- **Seamless, in one build.** Game code doesn't name shards or borders: the world is split and joined automatically, and the whole design is built together rather than zones first.
- **Turned on by settings; where an entity is comes from its position.** A game turns sharding on with a setting. Where an entity lives is decided by the position it already has: a `[Position]` field, which also marks it for correction smoothing, or its `Transform`'s world position.
- **A range the game sets.** How far the game's code looks around (sight, reach) is the game's own setting, in world units; region sizes don't change its meaning.
- **Convenience over explicitness, without duplicating anything.** Code that touches entities across a border works without change, and nothing can be duplicated or lost by it:
  - Every entity has exactly one owner at every tick. Moving it between shards is a move: the old shard never writes it again once it has sent it.
  - Messages between shards take effect exactly once, including across crashes and restores.
  - Code that would change something this shard doesn't own isn't applied from stale copies: it waits until this shard owns everything it changes and then runs again from the start, rechecking its guards with fresh state.
- **Global entity handles.** An entity's handle is the same on every shard and stays the same when it moves; references never need remapping.
- **A game can tell.** Code can find out that it ran late because it waited for a border, and whether this shard owns an entity. Code that ignores both still works.
- **Singletons and the clock live with the orchestrator,** not on any one region's shard. Every shard reads them; changing one is a border write like any other.
- **Saved worlds.** The record that makes cross-shard messages exactly-once is also the world's durable save, which a hosted world keeps.
- **Engine and service.** The engine (open source) has the shard protocol and an orchestrator for one machine: all shards in one process or on one box, for development, tests and small self-hosted worlds. Tide's hosting service runs the orchestrator across machines: regions split and merged by load, durable saves, recovery of failed shards and monitoring.
- **Intent, not mechanism** (the owner, 2026-10-23): shards shouldn't be a game's concern. What the engine can work out it does; what it needs from a game, it asks as a fact about the game (how far things reach, where they are, what holds what together), not as an instruction about shards. C libraries take more care, but that doesn't show where they're used. Agreed on these grounds: `reach`, `[Position]` deciding where an entity is, `[Native]` and `[Together]`, replacing `shardRange`, `[Partition]`, `[PerShard]`, `[Shared]`, `[Ghosts]`, `[GoesWith]` and `Shards.moves`.
- **Sharding on demand** (the owner, 2026-10-23): a world isn't a preset number of shards. A region whose shard struggles is split, and quiet ones merge back.
- **Physics and C state** (2026-10-23, the owner agreeing to the agent's recommendation): a library's state for an entity goes with the entity, and bodies near a border see their neighbours' copies as kinematic. A consensus model across shards for bodies that touch was raised as food for thought, not adopted.
- **Visibility** applies per shard, to that shard's own clients (2026-10-23, as recommended).
- **Hot reload** changes every shard's build at one tick boundary (2026-10-23, as recommended).
- **Billing**: one running shard is one machine of the project's preset (the owner, 2026-10-23).

<a id="provisional-31"></a>

### Provisional

Picks for the first build; names and details to confirm.

- **Settings.** `settings { shards = true; reach = 64; }`. `reach` is how far anything in the game looks or acts, in world units: sight, an attack's range, a query for what's nearby. It's required with `shards`, as no default suits every scale; the error says what the number is. Both are part of the build and the simulation identity.
- **Where an entity is**: its first `[Position]` field of two or three axes on a match component, the game's components before packages' (Box3D's and Box2D's `Body.position`), in declaration order; without one, the world position of its `Transform` root. Every such `[Position]` in a sharded game has as many axes, and an entity in a `Transform` hierarchy always lives with its root.
- **Entities with no position** live with their `Transform` root; others go with the first entity their fields name (a part with its body, a bag with its `owner`), or else with the entity whose code spawned them, wherever it goes, a tick or two behind it. One spawned by code for no entity and naming none stays on the root, and a scene goes nowhere: its entities are on every shard.
- **Regions** are never narrower than twice `reach`, so a shard isn't split a few units from its neighbour unless the game's range is that small. They are chosen by the orchestrator and change while the world runs: a region is split when its shard owns more entities than a limit, or is steadily busier than a share of its time (the host measures how long its updates take), and two neighbouring regions merge when together they're a quarter of both. The hosting service splits by load; the one-process orchestrator only by entities unless told, as its shards share one machine.
- **One shard until it's needed.** A world split into one region (the hosting service's, and `--shards 1`) is the root alone, owning all of it. When its load comes back down after splitting, its last two regions merge, and the last region left merges into the root: the world is one shard again, as it started.
- **`[Native]`** marks a field holding a C library's state, like a handle (for library authors; nothing a game writes). On a component it's a number or a bool, 0 wherever its entity arrives or is copied, with no default. On a singleton it's anything, and each shard keeps its own: such a singleton's other fields are the world's, the root's on every shard (plain values only, so a list or map there is an error unless it's `[Native]` too), and the library's own code for no entity that takes it runs on every shard, for that shard. A game's code using it is ordinary: code for no entity runs once, on the root, so a setting a game writes is every shard's; code for an entity on a region that writes a setting has it there at once, and the root takes it as the world's a tick or two later.
- **`[Together]` on a component's `Entity` field**: what it names is kept on one shard with the entity that has it, as a joint keeps its bodies. Everything `[Together]` ties, directly or through others (a chain or a ring of joints), is one group, which goes where its lead is: the member with a position and the lowest handle. The shard that has the lead asks for any member another shard has. Inferring it from references would tie two players together for good because something names both, so it's written.
- **`Shards.Together(a, b)` and `Shards.Apart(a, b)`** (for library authors, like `[Together]`; match code only): two entities act on each other for now, like two bodies that touch, and are one group like `[Together]`'s until as many `Apart` calls say they don't. Each shard counts its own pairs, in match state, summed from its tick's last run in a fixed order whatever threads said them; a pair goes when its count is 0 or neither entity is on the shard. Nothing in a game that isn't sharded.
- **`Shards.Spans(entity, center, size)`** (for library authors; match code only; agreed with the owner, 2026-10-24, the name Provisional): the entity covers that box this tick, past its position, like a floor or a terrain, so every shard whose region is within `reach` of any of it has a copy, not only those near its position. Said each tick it holds; a span within `reach` of the entity's position changes nothing. **`Shards.on`** is whether the game is sharded, a constant, so a library's work for this compiles away in a game that isn't. The physics packages say it for their static bodies.
- **Entities with no position** another shard has a copy of: one goes where the entity it goes with is (a part with its body), and so does its copy.
- **Physics packages.** Box3D's and Box2D's `Physics` holds their worlds as `[Native]` state and their settings as the world's; their handles are `[Native]` fields; a body that arrives is made anew from its `Body` (where it was and as fast), and a copy system keeps a copy of each neighbour's body near the border, of its type (a dynamic one as heavy as the body, put back where its owner last had it each tick), with every shape it has: its own, its parts' (which go with their body, by what they name), meshes, hulls and height fields. Each side reports touches and hits to the entities it owns. A joint's `a` and `b` are `[Together]`, so a joint holds across borders, and two dynamic bodies that touch are `Shards.Together` while they do, so they're on one shard, each with its weight against the other. A static body that reaches past its position (a long floor, a terrain, a plane) is copied to every shard it reaches.
- **Visibility.** The groups' directory lives with the root like a singleton: every shard reads its copy, and code elsewhere that creates, changes or destroys a group waits on the border. Other shards see a change a tick or two later, as no shard can act on what hasn't reached it: a group narrowed on the root hides its members from the root's players at once and from other shards' players that much later. Making every shard switch at one tick would only delay it on the root too, so it isn't done (the owner, 2026-10-24, as recommended); a game that must hide something from a moment on narrows it that much before. Each shard projects its own world for its own clients.
- **Hot reload** under `tide run --shards`: a new build waits for a quiet moment (no delivery or destroy waiting on a border, no message holding the old build's values on its way, no checkpoint being gathered), at most three seconds, then every shard changes build together, carrying its world over to another layout as a match's is; ghosts on their way are dropped and sent again whole. Never quiet in time, the game starts over and says why. On the web the old program hands the whole match over as a checkpoint.
- **What a shard runs.** Systems, handlers and tasks run for the entities a shard owns. A task goes with the entity it belongs to when that moves or is lent, and goes on there. A shard also holds read-only copies (ghosts) of its neighbours' entities within `reach` of its region, and of the singletons; queries, `world.Get` and `world.Has` read them, a tick or two behind. Code running for no entity runs once for the world, beside the singletons.
- **Events** sent to an entity another shard owns go to that shard and run there, a tick or two later, all of their handlers. An event sent to no entity runs on the shard that sends it; `PlayerJoined` and `PlayerLeft` run on the root.
- **Waiting on a border.** Changing an entity or singleton this shard doesn't own (`world.Set`, `Add`, `Remove`, `Destroy`, parenting, a `mut` singleton) makes the code that did it wait. The tick runs again without it, so nothing it did is kept; this shard asks for what it touched, and holds what it borrowed while it waits. A waiting handler or command runs once, in full, at the first tick this shard owns everything it changes. A waiting system's row is retried each tick until then. So is a waiting task's resume. Reading by handle an entity this shard holds no copy of finds nothing, as for one that's destroyed: code that reads what's farther than `reach` keeps it in range or sends it an event. A shard keeps what it borrowed (for a while) or what its own waiting code needs from a shard with a higher number that asks for it, until that code has run; a shard with a lower number always gets what it asks for, so no two shards wait on each other forever. Borrowed entities return by position once nothing holds them. A destroy whose `Destroyed` handlers change what this shard doesn't own waits with them: until they can run, the entity (and the entities parented to it) stays, read by queries and `world.Get` as before, but no system or handler runs for it.
- **`Shards.delay`** (int, ticks) is how long the running code waited for a border: 0 except in code that waited. **`Shards.Owns(entity)`** is whether this shard owns it now. Both are read-only, in match code.
- **Writing a singleton every tick** from systems on every shard serialises the world on it; in a sharded game the compiler warns about a system that takes a singleton `mut` and runs for each entity, and suggests state on an entity or scene, or an event, instead.
- **Players** join the world at the root, which gives them their PlayerID and sends `PlayerJoined`; every other shard takes them as the same player. `PlayerLeft` comes once no shard has them.
- **Clients** play in their home shard, the one that owns most of their player's entities: it's the world local code and local handlers see. A client also follows every shard that owns any of the player's entities and every region within `reach` of them, sending each its input, so moving home switches at once with nothing to download. While an entity is on its way from one shard to another, a player's machine keeps following both.
- **Views draw every shard a client follows**, each entity once: from the shard that owns it, or, while it's on its way between two (or owned by a shard the client doesn't follow), from the first world that has a copy, the home's first. A view for each entity runs for each shard's own entities, reading that shard's world (its singletons and `Shards.Owns`); a view for no entity reads the home's; a view's query has every followed shard's rows, and a view's `World`, and a function's it calls, finds an entity in the world that owns it. Near a border, that's the neighbour's own entities rather than the home's copies of them.
- **`Shards.Of(entity)`** (an int; the name Provisional, Claude's pick of 2026-10-24 for the Earth demo, which paints what each shard owns) is, in a view or local code, the number of the shard that owns an entity as this machine sees it: the drawn world that owns it, else the shard a copy came from, from 0; -1 for an entity no followed world has. It's for showing the split, not for game rules: in a match system or handler it's an error that says the match is one world. Always 0 in a game that isn't sharded.
- **Local handlers** hear every followed shard's events, each where it was sent, once. `Shown` and `Hidden` are of the followed worlds together: an entity is shown when the first of them has it and hidden when none has it any more, whichever shards it moves between. Correction smoothing applies to each entity from the shard that owns it.
- **Watching an area** (agreed with the owner, 2026-10-23; the names are Provisional): `Session.Watch(center, size)` in local code makes this machine follow the shards whose regions are within `reach` of that box too, wherever its player is, so views draw what they own: a camera zoomed out over the world, a spectator, a map. It holds until `Session.Unwatch()`; calling it again as the camera moves changes the area. `center` and `size` are a `float2` or `float3` (or `double2`, `double3`), both alike; a 2D game's z is ignored. In a world that isn't sharded it does nothing, as that machine has the whole world already.
- **The clock.** Shards tick at the same rate with the same tick numbers, set by the orchestrator.
- **Running one.** A sharded game's match started on a machine runs every shard there; the standard host's `--shards` and `--shard-width` split it into regions along x to try borders out. A dedicated server (`--shards`, `--shard-width`, `--shard-most`) runs each shard as one of its matches and a player asking for match 0 joins the world.
- **Exactly once by replay.** A shard's input log (players' inputs and shards' messages) is recorded durably before the messages its ticks produce leave it, and its world is checkpointed now and then. A shard that fails is restored from its checkpoint and log, which, being deterministic, reproduces the same messages; receivers drop repeats by sequence number. A message's sender keeps it until every shard has applied what it was handed and its ticks are kept. The world's own changes of shape (splits, merges, more entity indices) happen only when nothing is on its way, each followed by a checkpoint. A dedicated server keeps it all in a folder (`--shard-journal`), and started again with it, goes on where the world was; players there have 20 seconds to come back as themselves.

<a id="sessions"></a>

## Sessions

<a id="decided-31"></a>

### Decided

- Single-player and multiplayer are the same: every match runs on a server, and this machine's player connects to it, over a loopback transport when the server is on this machine. The engine assumes nothing about what a game does with it, like pausing; games build that from inputs and state.
- On the server's machine its player has no world of its own (the owner, 2026-11-04): it shares the server's after each tick, so the match is ticked once there, however many players are in it, and it never predicts or rolls back. It's still a player like any other: it joins (`PlayerJoined`), has a `PlayerID`, owns entities, and sends input and commands, which go straight in. Each tick is confirmed as it runs, so its local handlers hear each event once, as it happens and as verified at once. It sees the whole match (State visibility).
- Local code decides which match this machine is in: `Session.Start(scene)` starts one on this machine, `Session.Join(code)` joins the match in a room by its code, `Session.Connect(address, port)` joins another machine's by its address, and `Session.Leave()` leaves. `Start` names the scene the match starts in, with its values like `Scene.Load`'s: `Session.Start(Arena { size = 30 })`. `Session.Start()` uses the selected startup, or `Main` without a selection, with its initial values. This lets code such as a package's menu start a match without naming the game's scenes; it is an error when startup is local. `Join` and `Connect` get whatever the server runs.
- There's one kind of match. Whether others can join it is a switch on it, not another way to start one: a match starts closed, `Session.Open()` lets others join the match this machine runs, and `Session.Close()` stops letting them, at any time. Single-player is a match nobody else was let into.
- The machine that runs a match sends players out of it with `Session.Kick(player, message)`, or every other machine's with `Session.KickAll(message)`. The message is text, so a game can say anything, and kicked players get it with their `Disconnected`. A kick isn't a ban.
- A ban keeps a player out of the match for the rest of it, kicking them and refusing them as they come back (the owner's ask, 2026-11-04, from a game that re-kicked banned players itself; its shape is Provisional, below).
- The machine that runs a match says what it means by leaving it: `Session.Leave()` leaves, and with host migration the match goes on without this machine; `Session.End()` ends the match for everyone, who go offline with `Ended`. A crash, or closing the window, is a `Leave`.
- **Host migration** is a game's choice, off by default: `settings { hostMigration = true; }`. When the machine running a room's match leaves or stops answering, another player's machine takes the match over from the last tick it verified, and the other players join it again as the same players. The old host's player leaves the match (`PlayerLeft`), and from then on, entities without an owner read the new host's input.
  - Only room matches change hands. A match joined by address (`Session.Connect`) has no relay to meet at again, so it ends, as it does without host migration.
  - A new host only has what its machine could see: private scenes it wasn't in are lost, whole. A game that uses host migration shouldn't keep secrets.
  - No player ever gets another's cookie. With host migration on, every player gets a hash of each player's cookie, so a new host can tell who's coming back and nobody can pass for someone else.
  - A host that leaves says so, and the match changes hands at once. One that stops answering is only noticed after the time-out, so players wait a few seconds first.
- Players find each other's matches in rooms, by a code. The hosting machine picks its room's code itself, so local code has it at once, with nothing to wait for: `Session.room`.
- **A game can bring its own match transport and its own lobby and matchmaking service without the engine changing** (the owner, 2026-10-11, of the Steam integration: "as long as any user could technically also do it themselves in your game without having to change the tide engine"). What comes with tide for a store is built on that same public surface, and nothing in the engine is for one store. Engine changes for it are for where the public surface can't do the job ("we should if we hit a wall only"). Host migration is part of it where the store's model makes sense of it ("we should support host migration if steam makes sense").
- Local code sees where this machine stands through a built-in local singleton, `Session` (taken as a parameter like any singleton), and the built-in local events `Connected` and `Disconnected`.
- Clients have no input delay: their own input applies at once, and they run ahead of the server so it arrives in time. Only other players' inputs are ever guessed. A client that can't afford to run its predicted ticks again delays its input instead, a tick at a time, until it can (see Settings, `prediction`); a game can ask for delay in place of prediction altogether.
- Local code tells what's predicted from what the server has confirmed with one word, `verified`: before a view's parameter or filter it reads the confirmed world (see Views and drawing), and before a local handler's event it hears the event once its tick is confirmed (see Events). Without it, a view draws the world as this machine predicts it, and a local handler hears each tick as this machine first ran it.
- The desktop transport is our own thin layer on UDP. The web's is WebRTC data channels that neither order nor resend, so browsers host matches as well as join them. A relay we host introduces players to each other; their packets go straight between them whenever their networks allow it (see AGENTS.md, Networking).

```csharp
local scene Main { }

scene Arena
{
    int size = 20;
}

view Menu(Session session)
{
    if (session.state != SessionState.Offline) return;
    GUILayout.Area(Anchor.MiddleCenter)
    {
        if (GUILayout.Button("Play")) Session.Start(Arena);
        if (GUILayout.Button("Host"))
        {
            Session.Start(Arena { size = 40 });
            Session.Open();
        }
        if (GUILayout.Button("Join")) Session.Join("K7QF2M");
        if (GUILayout.Button("Connect")) Session.Connect("192.168.1.5");
    }
}

local event(Disconnected gone) BackToMenu()
{
    // gone.reason says why: Left, TimedOut, Refused, ServerLeft, Failed, Ended, Kicked or Banned,
    // and gone.message what a kick or a ban said.
}
```

<a id="provisional-32"></a>

### Provisional

Implemented, awaiting approval:

- `Session` has `state` (`SessionState.Offline`, `Connecting` or `Connected`), `player` (this machine's `PlayerID`, once connected), `ping` (the network's round trip to the server, in milliseconds: from when this machine sent to when the answer arrived, less what the server held it, so no wait for a frame is in it), `server` (whether this machine runs it), `open` (whether others can join it, which only the server's machine knows) `room` (the code of the room the match is in, or `""`, as it is while the match is closed) and `invite` (below). It's read-only. A single-player match is `Connected` too, with `server` true and `open` false.
- **`Session.invite`** (the owner asked for host a room, copy a link, send it, 2026-10-21; the name and what it is off the web are the agent's picks, which the owner accepted): what others open to join the match, for `Clipboard.Copy(session.invite)`, read wherever `session.room` is and refused wherever it is. `""` whenever `room` is.
  - On the web, a link: the page's address without its query or fragment (`origin` and `pathname`), then `?join=` and the room's code, like `https://example.com/my-game/?join=K7QF2M`, so it works wherever the page is served (a site, `localhost`, a LAN address). Opening it joins the room, as `?join=` always did. A web host's invite stays `""` until the relay confirms its room is registered, even if `room` already has a code. A page that's no place to link to (not `http:`, `https:` or `file:`), a link longer than 255 bytes, and a `room` that `?join=` wouldn't pass on whole (a game's own network's text with anything but letters, digits and `/`, which `ROOMID/0` has) have the room's text itself.
  - Natively (desktop, Android), where there's no page to link to, the room's code itself: what a friend types to join.
  - Up to 255 bytes of printable ASCII, so `Clipboard.Copy` takes it whole.
- `Connected` is sent once the match's world has arrived and this machine plays in it; `Disconnected { DisconnectReason reason; string message; }` when it leaves: `Left` (it called `Leave`, or started another match), `TimedOut` (the server stopped answering, or never did), `Refused` (another build of the game, no room left, or a closed match), `ServerLeft` (the server's machine left, which ended the match), `Failed` (it couldn't start: no network, a port in use, an address that isn't one, a room nobody has) `Ended` (the match's last scene unloaded, and startup is local; see Scenes), `Kicked` (the server's machine sent it away) or `Banned` (it banned this machine's player, or turned them away as banned). `message` is the kick's or the ban's, and `""` for the other reasons.
- `Session.Kick(player)` and `Session.KickAll()` send no message. A kicked player leaves the match at once, as if they had left: `PlayerLeft` follows, and they can join again, as the same player, while the match is open. A goodbye can be lost: a kicked player who didn't hear it is told again whenever they're in touch, while they still send to the server and when they join it again, before they're let in (taking a match over with host migration included). Once they've heard, they can join again. Kicks only change a match this machine runs: on a client, or offline, they do nothing, and this machine's own player can't be kicked (it calls `Leave`). A message is up to 255 bytes of UTF-8, cut where a character starts. A frame takes up to 16 kicks; a `Start`, `Join`, `Connect` or `Leave` after them drops them, as it does Opens. A machine kicked from a match it joined with `--join` or `--connect` doesn't join it again by itself.
- **Bans** (built 2026-11-04; the names and what a ban holds are the agent's picks). `Session.Ban(player, message)` (named `player:` and `message:`, the message optional) kicks the player with `Banned` and the message, and refuses them with the same each time they try to join again, open or closed, before anything else (a kick's resending included). `Session.Unban(player)` lifts it: they join again, as the same player, while the match is open. Both go in a frame's kicks, in order, up to 16 in all; on a client, offline, in a sharded match, for this machine's own player and for a slot nobody has played in (or a first-time player still joining, whom no `PlayerID` names yet) they do nothing.
  - **What a ban holds**: the player's slot, as admission knows it. A returning player is their slot by their cookie's digest (the secret their machine was given on first joining) and, under a host with trusted identities (`tide_server_desc.identity`), by their account too, so a new cookie doesn't get past a ban there. A machine that comes with neither (another device, cleared storage, or a session that joins a migrated match at its new host's address, which starts it with no cookie) is someone new. The banned slot is kept for them: their `PlayerID` is given to nobody else while the ban holds.
  - **It lasts as the match does**: it's server state outside the world, never hashed or snapshotted with it, and goes with the match when it changes hands (the handover carries each banned slot's digest and message) and through managed recovery (`tide_server_recovery`'s `banned` and `ban_messages`). A hot reload that keeps the server keeps it. A new match has none.
  - A dedicated server's C bans with `tide_server_ban(tide_hosting_server(host, match), player, message)`, and `tide_server_unban` and `tide_server_banned` go with it.
- `Session.Open(port)` takes players in a room, and on `port` too, 7777 without one, except on the web, which has no ports. A closed match turns away anyone who isn't in it, coming back or not; the players in it stay. Opened again, it takes players in the same room and on the same port. `Open` and `Close` only change a match this machine runs: on a client, or offline, they do nothing. When it can take players neither in a room nor on the port, the match stays closed. Opens and Closes before a `Start`, `Join`, `Connect` or `Leave` in the same frame were for the match it ends, so they're dropped. `Session.Play` and `Session.Host` are errors that point to `Start` and `Open`.
- `Session.Connect(address, port)` takes `"192.168.1.5"`, `"192.168.1.5:7777"` or a name like `"localhost"`, and the port is 7777 without one.
- A room's code is 6 letters and digits, without look-alikes (no `0`, `O`, `1` or `I`), like `K7QF2M`: about a billion codes. Case and spaces don't matter when joining. Text that isn't a code is no longer an error at `Session.Join`, as a game's own network reads its own text (below): `Session.Join("")` is the one error, and a literal that reads as a machine's address (`"192.168.1.5"`, `"localhost:7777"`) is a warning that points to `Connect`, which a constant or a variable doesn't get. With Tide's rooms, text that isn't a code fails as it's joined (`Failed`).
- **A game's own network** (built 2026-10-11; the shapes are Claude's picks). A game's C registers a `tide_network` (`tide/network.h`, `tide_network_set`): `host`, `join`, `address`, and optionally `failed`, `update` and the three functions of host migration (`place`, `migrate`, `migrated`). From then on `Session.Open()` opens the match on it, `Session.Join(text)` hands it the text, and `Session.room` is what it says the match is joined by. The Tide side has no new syntax: an `extern` function the game calls from local code registers it.
  - It's registered before the `Open` or `Join` it's for; the same frame will do. A match stays on the network it started on until this machine leaves it, whatever is registered meanwhile. `tide_network_set(NULL)` is Tide's rooms again.
  - With one registered, `Session.Open()` takes players on it alone: no room and no UDP port, and the port argument means nothing. `Session.Connect` is unchanged. A run of several players with no window (`--players`) goes through it too.
  - `Session.room` holds up to 63 bytes of printable ASCII, cut by the engine; `Session.Join` passes up to 255 bytes on. Where a match's players meet again is up to 32 letters and digits, checked by the engine before a network is handed it.
  - A transport's addresses are of a kind of their own (`TIDE_ADDRESS_NETWORK`), whose 48 bits are the network's to give a meaning. A host joined on one gets 15 seconds to first answer, as a room's does.
  - Host migration is the network's to decide by one authority of its own; without the three functions a match ends with its host. A match its host ended is told to the network (the transport's `end`), which answers `ended` to players who come to take it over.
  - Under `tide run`, a reload while a match is on the game's own network starts the game over: the transports are the old build's code. On the web the functions are there, and a network that doesn't exist in a page registers nothing.
  - A game's library keeps the registration in its own copy of the engine, so hosts ask the game for it (`tide_host_game.network`); a custom host serves it with the `tide_network_match_*` functions.
- A code another room already has is refused by the relay, and the host picks another at once, before anyone could have read it: `Session.room` changes. It's `""` while the relay can't be reached; the host keeps trying, and the room opens again under the same code if it's still free. Players already in keep playing: only joining needs the relay.
- Joining a room that doesn't exist, or whose host can't be reached, ends with `Failed` at once. A room's host gets 15 seconds to answer for the first time, rather than 5, since WebRTC can take a while to find a way through routers.
- Desktop and web players meet in the same rooms: desktop games speak WebRTC too, with an implementation of our own (no third-party code, so games carry no license terms for it). Everyone reaches the relay over `wss://`: desktop games with their system's TLS (on Linux, OpenSSL's libssl, which they load if it's there).
- Under `tide run --web`, a reload goes on with the match closed: the room closes, and the other players drop out.
- Session calls are statements, in views and local handlers, and in the functions and methods they call (see Functions and blocks). Match code can't make them, as it runs the same on every machine, nor can `Sample`: a function that makes one is an error where either calls it.
- A match can't start in a scene that holds text or lists yet.
- Starting a match leaves the one this machine is in first, which sends `Disconnected` with `Left` before the new one's `Connected`.
- The server's player joins before the match's first tick, as `PlayerJoined` handled at the end of it; the server only starts ticking then.
- When startup is the match's, `tide/run.h` starts it at once, and opens it with `--host [port]`, or joins another with `--join code` and `--connect address` on the command line (and `tide run --host`, `--join` and `--connect`).
- A match takes up to the game's `maxPlayers` players, 16 without the setting and 65536 at most (see Settings). One more is refused, as from a full match.
- A client predicts at most a second ahead of the last tick the server confirmed, however many ticks that is at the match's tick rate; beyond it, it waits for the server. The server keeps four seconds of ticks to send again; a player further behind gets its complete permitted world again. A player that was sent the world has every tick since kept for it until it catches up, however long the world took to arrive, up to 32 seconds: one that can't catch up in that long gets the world again.
- Joining takes a round trip and a half: a hello gets a welcome, and the world comes once the player writes back, so that a hello from an address that isn't the player's costs the server a datagram and never puts a player in the match. One that never writes back is forgotten in two seconds. Players who join in the same tick are sent one packing of the world.
- **Coming back:** joining a server gives this machine a cookie, and joining the same server again (the same room, or the same address) presents it, so the player gets their `PlayerID` back, and with it whatever the game kept for them. If the server still has them connected (their old connection went quiet), the new one takes over with no events at all; if they'd left, `PlayerJoined` comes again with the same `PlayerID`. A server keeps a slot for a player who left until it has no slot that was never used; then it gives away the one away longest, and that player's cookie stops working.
- The cookie lives as long as the program: it doesn't survive a restart yet, and it's not safe against someone on the network guessing it.
- **Host migration:** the first player's machine to reach the room takes the match over: the relay pings the room's host for 3 seconds, and if it doesn't answer, or it left, gives the room to the first player there and introduces the others to it. A host that answered keeps the room, and the players who came join it again.
- While a match changes hands, local code sees no `Connected` or `Disconnected`: `Session.state` is `Connecting`, `Session.player` stays the same, and views see the last world this machine had. On the new host, `Session.server` becomes true.
- The new host runs the match at its tick rate, and goes on from the last tick it verified. The last host's player gets `PlayerLeft` at the first tick. A player who doesn't come back within 20 seconds gets `PlayerLeft` too; one who comes back later is the same player, with `PlayerJoined` again.
- A closed match changes hands closed: its players come back, but no one new joins. The room keeps its code, and its key (128 random bits) only goes to the match's players, so no one else can take the room over.
- A host that's still running but doesn't answer the relay in time, like one stopped at a breakpoint, loses the room to its players. When it carries on, its match fails on its own machine (`Failed`).
- `Session.End()` on a client does nothing. A match that ends, by `Session.End()` or by its last scene unloading, ends at the relay too: for five minutes, players who come back to its room to take it over are told it ended, and go offline with `Ended`, whatever goodbye they missed. The room's code stays taken that long.
- **The match while a frame waits for the GPU** (built 2026-11-03 for desktop; Android's, Provisional, Claude, 2026-11-14). While Vulkan waits, after a frame is shown, for the fence of the frame whose resources the next one reuses, the standard host goes on with the match (the network and the session's ticks, no views, input, drawing or reloads: `tide_platform_update_while_waiting`), so a GPU-bound frame doesn't hold up the match's traffic. Desktop's window does this, and since 2026-11-14 Android's activity too: until then it presented without the host's updater, so a GPU-bound phone's match waited out each fence (`tide_platform_gpu_wait_app` found it). Weighed: keeping it desktop's alone, as built on 2026-11-03, which had no reason given but a first platform. The web's WebGPU and runs with no window never call it.

<a id="open-26"></a>

### Open

- Keeping the cookie across restarts, and making it unguessable.
- Tide syntax for process-level dedicated-server orchestration; native C entry points are implemented (see Dedicated servers below).
- Keeping a room open across reloads under `tide run --web`.
- Lobbies in the language or the engine: they're packages (`lobby`, and `steam` for Steam), over a game's own network where they bring one.
- A game's own network: whether `Session.Open` should also take a UDP port beside it, a ping that leaves out the frame's wait without the transport's own clock, and keeping a match on it across a reload.
- Showing other players from confirmed state, blended between confirmed ticks (see Views and drawing, Open).

<a id="dedicated-servers"></a>

### Dedicated servers

**Decided:** a dedicated server has no window, rendering, audio, views or local
player. One process hosts independent matches of the same game, sharing immutable
assets and execution resources. Creation and joining have separate admission
policies, supporting client-requested matches and creation restricted to trusted
sources. Match IDs route requests and do not confer access. Pluggable
authentication runs outside simulation; ordinary deterministic join events admit
accepted players. Credentials remain outside replicated state. Server packs can
omit assets reached only from client code without changing shared match identity.

**Provisional, implemented:** `tide run/build --server`, the C
`tide_server_entry(tide_hosting_desc *)` process hook, per-match typed `tide_start`
selection, and `tide/hosting.h` admission/multiplexing APIs. Standard clients use
`Session.Connect("host:port/0")` or `Session.Join("ROOMID/0")` to request a match;
a nonzero suffix joins its ID. Anonymous policies are explicit. Custom clients
provide bounded credentials over protected transports to the game's verifier;
acceptance binds an opaque identity to the match's `PlayerID`, including
reconnects. Current ownership, limits and callbacks are documented in
`docs/c/network.md` and `notes/dedicated-servers.md`. There is no new Tide syntax.
Native process restart persistence and native crash isolation remain outside
that native host. Sandboxed managed execution is a separate service below.

<a id="managed-hosting-and-compatibility"></a>

### Managed hosting and compatibility

**Decided:** build client/server artifacts locally by default; upload exact
immutable releases, with a server-only option. Match admission uses an automatic
simulation identity rather than manually maintained versions. Match code,
transitive helpers, schemas/defaults/settings, simulation-read assets and the
toolchain participate; presentation-only code/assets can be excluded. Custom C
and libraries are conservative inputs initially. Release identity and simulation
compatibility are distinct. No production hot reload or native client code
delivery is implied.

**Provisional, implemented:** `tide login/logout/deploy`, GitHub developer OAuth,
Stripe prepaid fulfillment and the single-host Fly service (a separate repository).
Each match runs inside a worker-owned WASM instance with bounded imports,
memory and execution. Project-scoped runtime credentials can control matches
without publishing authority. Default occupied lifetime has an empty grace;
explicit worlds save/recover on their original release and stable ID, subject
to credit, capacity and finite save retention. Game C may supply save/load
callbacks; the default checkpoint has exact-release scope. Concrete interfaces,
operator limits, tests and unbuilt production/operational work are recorded in
the service's own repository. This adds no Tide syntax and
does not declare a publicly launched hosting service.

Generated `tide_game.simulation`/`TIDE_SIMULATION_ID` use a canonical checked
simulation graph plus normalized compiler/runtime source identity. Session
protocol 15 checks it; `tide_game.hash` retains its layout/hot-reload role.
Dedicated admission protocol 2 checks simulation identity before creation.
Mismatches use the existing Refused reason with update guidance in the message.

<a id="settings"></a>

## Settings

<a id="decided-32"></a>

### Decided

- `settings { ... }` sets the engine's settings for the game. Each is set without a type: `tickRate = 30;`. The game's own values are constants (see Constants).
- `settings` is a keyword only at the top level of a file, so it still works as a name everywhere else.
- Every setting has a default, so a block only lists what it changes.
- A game can have several blocks, in any of its files, and together they're one list of what it sets: each sets what the others don't. A setting that two of them set is an error, as one set twice in a block is. A second block is no error by itself: what clashes is two that set the same thing.
- Values are constant expressions, and can name constants. The startup selection names a prefab or scene declaration instead (see Scenes).
- Settings are part of the build, so every machine in a match has the same ones.
- The editor completes the settings' names and shows each one's default and what it does. A name that isn't a setting is an error that says which one was meant.
- The first settings are `title` (the window's), `tickRate` (ticks per second, 60 by default), `maxPlayers` (how many players a match takes, 16 by default), `hostMigration` (see Sessions), `prediction` (how clients keep up with the match, see below), `appId` (the app's ID on phones), `version` (the version people see), `stats` (the stats overlay, see below) and `debugViews` (the engine's debug views, like the profiler, see below). The window's size and the default port can come later.
- `prediction` is one of the built-in enum `Prediction`: `Rollback` (the default) or `Delay`. With `Rollback`, a client runs ahead of the server with no input delay, guessing other players' inputs, and runs ticks again when a guess was wrong; when what its rollbacks cost is more than a frame can afford (one rollback about a frame, and all of them a budget an update on the whole), it delays its input a tick at a time, predicting less, until it fits, and takes the delay back once there's been room to spare for a moment. With `Delay`, clients never predict: their inputs are delayed so every player's reach the server before its tick, and ticks run once each, as the server confirms them, as many ticks behind as that takes. A game that would rather every machine ran each tick once, like one whose ticks are expensive, or whose views can't show a rollback well, picks `Delay`.

```csharp
settings
{
    title = "Asteroids";
    tickRate = 30;
    hostMigration = true;
}
```

- **Shared player ceiling (Decided).** `maxPlayers` accepts 1 through 65,536 players, defaulting to 16. Dedicated-server total connections use the same supported ceiling, with a separate capacity setting.

<a id="provisional-33"></a>

### Provisional

Implemented, awaiting approval:

- `hostMigration` is true or false, or a constant that is.
- `shards` and `reach`: see Shards.
- `debugViews` is true or false, or a constant that is, false by default: the engine's debug views are on in the game. The standard host then shows the profiler at F7, and hides it at F7 again: where a frame's time goes (input, the match's ticks and its netcode, each view, drawing) and a tick's (each system, then its changes and events), as averages over half a second. `--debug-views` on the game's command line (`debug-views` in a web page's address), `tide run --debug-views` and `tide_run_desc.debug_views` turn them on whatever the setting says. Nothing is measured while the profiler is hidden. In generated C it's `tide_game_api.debug_views`, read each frame, so under `tide run` a reload changes it. The names (`debugViews`, `--debug-views`), the key and what the profiler shows are to confirm.
- **Ticks alongside the views (Provisional, implemented on desktop).** `ticksAlongsideViews` is true or false, or a constant that is, false by default. On the machine that runs the match (a host, single-player included), the last tick an update finds due is begun there (joins and leaves, inputs and commands go in) and its systems, changes, handlers and hash run on the job threads while the frame goes on to its local handlers, its views and its drawing; an update after ends it, which is when this machine's player gets its world, the other players its frame, and local handlers what it sent. A frame with a tick then takes the frame's thread the longer of the two rather than their sum. For that, views show the match as of the moment of the frame before: every tick due by then has ended by the time the next frame's views are made, so nothing waits where a tick fits in a frame, and a tick that doesn't is waited for. What's drawn is one frame older (7 ms at 144 frames a second, a tick at frame rates up to the tick rate), near and far entities alike; input is sampled and reaches the match as soon as without it, and is seen that frame later. Results are the same match, tick for tick, as with ticks in the update. Local handlers hear a tick's events the frame its world is first shown; at fewer frames a second than ticks, a frame's earlier ticks still run in its update and are heard then, up to a frame's worth of ticks before they're drawn. Other players get a tick's frame at the host's next update rather than at once. C reached through `extern` from both match code and views is called from two threads at once, the tick's and the frame's, which is the game's to make safe. It does nothing on a machine that joined a match another runs, in a sharded match, or where the pool has no thread to lead a tick (the web, for now): ticks run in the update there, and views aren't behind. `--ticks-alongside` on the game's command line, `tide run --ticks-alongside` and `tide_session_desc.alongside` turn it on whatever the setting says. In generated C it's `tide_game_api.ticks_alongside`, read each frame, so under `tide run` a reload changes it. The name, the default, and whether it should be on by itself where a tick is costly are to confirm.
- **Confirmed presentation and collider rewind (Decided, implemented).** Verified view values interpolate by default on a separate confirmed clock and hold at the latest confirmation. `settings { maxRewind = 0.25; }` enables a finite nonnegative window in seconds (default 0). With it, the input gains read-only `ViewTime viewTime` (`int tick`, `float alpha`, `bool valid`), stamped after sampling from the last presented confirmed interval. Its time is `tick - 1 + alpha`. The server validates it as an untrusted client claim against fraction/range, its connection snapshot, advertised server time and the configured window. Invalid claims become invalid timestamps; ordinary input remains usable. Physics packages explicitly opt whole bodies into history with `rewind = true`, and `physics.Rewind(time, out query)` returns a detached read-only query scene or false. Historical opted-in geometry collides with current non-opted geometry. All existing query forms are available on `query`; neither preparing nor using it changes simulation geometry or contacts. Missing history never clamps or falls back. Games still validate shooter, origin, aim, weapons and damage from authoritative state; a timestamp cannot prove what a modified client displayed.
- `maxPlayers` is an int known while compiling: how many players a match takes. The world keeps an input for each, and the server's after them, so it's part of the game's data layout: builds with different `maxPlayers` are different games, which can't share a match, and under `tide run` a reload that changes it starts the match over. In a full-world match every player's input goes to every other each tick, so traffic can grow with the square of the player count. Visibility can restrict recipient input and state delivery; practical capacity depends on the game and workload. In generated C it's `TIDE_GAME_PLAYERS` and `tide_game_api.max_players`.
- `prediction` is `Prediction.Rollback`, `Prediction.Delay` or `Prediction.Owned`, or a constant that is. It's the client's: the server runs the match the same either way, and players of all kinds share a match. In generated C it's `tide_game_api.prediction`, a `tide_prediction`.
- **Owned prediction (decided 2026-11-07):** `Prediction.Owned` predicts the player's owned entities and their children. Other entities stay confirmed; confirmed ticks simulate the whole permitted world. Singleton systems run only in the conservative transitive dependency set of owned simulation (owner decision 2026-11-07), including helper/query/event effects. Ordering alone does not select a system. Possible owned spawners and shared task continuations are retained conservatively; dynamically targeted structural writers may retain additional work. Unrelated singleton values remain at the prediction baseline and do not participate in near-state reuse comparison. Heap/input/structural comparisons remain conservative. The spelling and nearest-explicit-Owner inheritance rule are provisional: walk this entity and its ancestors until the first Owner, whose player decides inclusion. Positions are irrelevant. Ownership/parentage is checked before each predicted tick; no owned entities means no per-entity prediction. `Far` filters excluded entities, including unpositioned ones. `predictionRange` cannot be combined with this mode. The same confirmed rendering and bounded retained-prediction rules as spatial prediction apply.
- **`predictionRange`** (asked for by the owner 2026-11-04: "far stuff acts as Prediction.Delay essentially and only ticks once instead of rollbacking"; near meets far "as if they were constant/solid"; reconciles that look odd at the border are acceptable; positions as shards find them). A finite number of world units over 0, or a constant that is, with `Prediction.Rollback` only (with `Delay` it's an error). Without it a client predicts everything, as before. Decided by the owner: entities far from the player aren't run in predicted ticks and stay as last confirmed, ticking once as each tick is confirmed; what's near reads them as they stand; positions go by `[Position]` and `Transform` as shards' do. Claude's picks, Provisional:
  - The name, and that near is a box: within the range, axis by axis, of the box around the positions of every entity whose `Owner` is this machine's player. A player owning nothing with a position predicts everything. An entity in a hierarchy goes by its root's position; one with no position is always near, as is anything spawned in a predicted tick.
  - What a far entity is left out of: the systems and match event handlers that run for each entity. A system written in C is handed the runs of rows between far ones (owner, 2026-11-04). A singleton system and a query still run for everything. Queries, `World` reads and changes made to a far entity by near code work as they do anywhere; so do a system's `mut` query rows, which write far entities like any other (decided by the owner, 2026-11-04).
  - **`Far`** (the name decided by the owner, 2026-11-04) is the filter for what a predicted tick leaves out, for code that goes through everything at once to leave it out too: `with Far` and `without Far` in a system's, a C system's or a query's parameters, and nowhere else (`Far far` is an error: it has no fields). It's a tag only a client's predicted worlds give, so on the server and in confirmed ticks `with Far` matches nothing and `without Far` everything. A system for each entity, in Tide or in C, that says `with Far` runs for far entities in predicted ticks, where it'd otherwise leave them out. Without `predictionRange` nothing is ever Far: a package names it either way, and a game's own system `with Far` warns that it never runs. A game's own component named `Far` takes the name.
  - **The physics packages hold what's far** (the owner agreed 2026-11-04, picks below Claude's): Box2D's and Box3D's steps leave far bodies where they were last confirmed. Their `HoldFar` system (`with Far`) gives the step the far bodies, which puts each island of far bodies alone to sleep and keeps each sleeping set of them asleep, held: a near body touching one meets it as a static body, without waking it, and hears `Touched` and `Hit` from it; the far body's entity hears nothing until its tick is confirmed. Their `Leave` is `without Far` (as every C system now is in predicted ticks), so a far body's component stays byte for byte its confirmed one. An island where far bodies touch or are joined to near ones isn't held, and steps whole in the physics world, though the far bodies' components still aren't written: near bodies meet them where the physics world has them. A near island touching a held body doesn't fall asleep in predicted ticks. Holding is once for each run of predicted ticks, which starts from a confirmed world that holds nothing.
  - Near and far are decided again on the world each run of predicted ticks starts from, the last verified one, and on each predicted tick while nothing is far. A tick run with anything far is never reused as the server's: the confirmed tick runs once for the whole world. When it leaves everything but the far rows as predicted (decided by the owner, 2026-11-04: "skip, bounded"), the predicted ticks after it stand, their far entities as of an older confirmed tick; otherwise, or once those far entities are more than a quarter of a second older than the confirmed tick, the predicted ticks run again, near alone, from the far entities just confirmed. So with anything far, a confirmed tick costs one whole-world tick, and a rollback of what's near when what's near went otherwise or a quarter of a second has gone by. Claude's picks: the quarter of a second (`FAR_STALE_SECONDS`); what's compared (every singleton and every row not far in the predicted world, packages' `[Native]` fields left out as C's own, and entities, commands, tasks, inputs and lists whole, so a list that changed anywhere reruns).
  - Far entities are drawn as confirmed (the owner, 2026-11-04: "we should blend them"): a view's or its query's blended component of a far entity is the presented confirmed world's, blended with the one before on the confirmed clock, as a `verified` parameter is. A component holding text, lists or grids, whose values belong to the drawn world's heap, is drawn as the drawn world has it, a tick at a step. Far entities take no prediction correction smoothing; crossing the range jumps between predicted and confirmed.
- The input delay (`tide_client_status.delay_ticks`, which `tide run --stats` shows) is how many ticks before a tick runs its input is sampled. A client samples inputs as its clock says, as far ahead as it ever predicted, and runs ticks that many short of them. Predicting, it starts at none, and adds a tick when the ticks it would run again cost more than its budget (`tide_client_desc.resim_budget`, 4 ms a frame unless the host says, measured with the host's clock; without one, as in tests and benchmarks, there's no delay), one change per round trip. Not predicting, it starts at the lead and round trip its inputs go ahead by, plus half a round trip for the frame to come back and two ticks for it to be late by; it adds a tick when its clock reached a tick whose frame hadn't come, and takes one back once frames have come three ticks early for five seconds. Either way, a frame whose tick the clock hasn't reached waits for the clock, so ticks run at the match's pace however early their frames come, and views blend up to the clock less the delay.
- `tickRate` is an int from 1 to 1000, known while compiling. The machine that runs a match decides its rate (its desc's, or its game's), and the players who join tick at it. A new `tickRate` under `tide run` takes effect when a match starts.
- `title` is text written out, or a constant that is. `--title` and CMake's `TITLE` go over it, and without any of them, the window has the game's name: its folder's under `tide`, its target's under CMake. Under `tide run`, a new title shows the next time the game runs. On Android it's the app's name under its icon.
- `appId` is text written out, or a constant that is: what Android and iOS, and their app stores, know the app by, like `com.studio.game`, the same for every version. It's two parts or more between dots, of letters and digits, each starting with a letter: what Android and iOS both take. Without it, apps are `dev.tide.<the game's name>`, which is fine to test with; an app made to ship (`tide build --android --distribution`) needs one.
- `stats` is true or false, or a constant that is. With it, the window shows the stats in its bottom right corner with no option asking for them, as `tide run --stats` and CMake's `STATS` do. It's part of the build like every setting, so what `tide build` makes shows them too: a game takes it out before players get it, unless the frame rate is theirs to see. Under `tide run`, setting it or taking it out shows at the next reload. In generated C it's `tide_game_api.stats`, which the standard host reads beside its own `tide_run_desc.stats`.
- The stats are a drawer (`tide/stats.h`), which the standard host draws over the game:
  - Closed, it's one line: the frame rate, and in a match another machine runs, the ping (`60 fps   ping 34 ms`). A click or a tap on it, or F8, opens it: the rest is listed above that line, which stays where it is, so a click in the same place closes it again. The list is two columns, a label on the left and its value on the right, in groups: what a frame's work takes on its thread (`cpu`: everything but the wait for the display, with `render`, the part of it that's rendering, listed under it, and `gpu` beside them, with the frame's draw calls in its label, or on a line of their own where there's no GPU timer; a `vertices` row counts submitted indices/vertices times instances at their selected LOD in every render-target pass, including shapes, text, meshes, blits and clear triangles, without the host overlays); the match's (the ping of a match this machine runs, with the input delay in its label when there is one; the bandwidth, up and down on one line; the entity count); the machine's (the threads ticks run on, the memory the program has (as the system counts it; on the web, its WebAssembly memory), what draws); and the three systems that took longest on average per measured run over the last half second, each keeping its row while it stays among them. Open, the panel keeps the widest it has been, so its edge doesn't jump. Outside a match it has the lines that aren't a match's, and on a screen too low for all of it, the lines there's room for, from its top.
  - It starts closed when the game's setting, `tide build --stats` or CMake's `STATS` asks for the stats, and open under `tide run --stats` (`tide_run_desc.stats_open`). Open or closed is the host's own, whatever build of the game runs, so a reload keeps it.
  - A press that lands on it is the drawer's until it's let go, wherever it goes meanwhile: the mouse's buttons, and any finger. The game's input never samples it and its views and GUI never read it, from the frame it lands in. A press that began elsewhere stays the game's when it crosses the drawer, and a mouse whose cursor is locked is on nothing. The game reads F8 like any key.
  - Closed, the host measures nothing for it: the frame rate is frames counted, and the ping is the session's. A frame's work, the systems' times and the memory are measured while the list is open. Timing averages update every half second; rendering's CPU cost is part of the CPU total and has its own `render` line, indented under `cpu`. Desktop OpenGL and WebGPU devices with timestamp queries show asynchronous `gpu` drawing time, including render targets and excluding the drawer and display wait (WebGPU sums pass durations). Unsupported backends show no GPU line. CPU and GPU overlap, so their times aren't added. Closing or reloading discards old timings.
  - What's picked, to confirm: that it's a drawer at all, and closed by default; the key, F8, beside the profiler's F7; what the one line says, and that the ping is in it only when another machine runs the match; that `tide run --stats` alone starts it open; that it shows outside a match too, where the stats showed nothing before; that a game can't ask where it is, and leaves the corner free by its own numbers (about 80 by 40 pixels, 190 wide with a ping); the two columns, the groups, `render` under `cpu`, a system keeping its row, and the panel's width that only grows while it's open (2026-10-07, for the owner's ask that it read better and shift less; the draw calls in the GPU line's label, the bandwidth on one line and no tick line were their own asks); and the names in C (`tide/stats.h`, `tide_run_desc.stats_open`, `tide_platform_draw_over`).
- `version` is text written out, or a constant that is: the version people see, like `1.2.0`, one to three numbers between dots, which Android and iOS both take (iOS's version has to be). Without it, it's `1.0`. The number app stores order updates by is each build's own: on Android, the minutes since 2020.
- A setting that's set twice, a name that isn't a setting, and a type written before one are errors. The first is at the second place the setting is set, in the same block or in another, and says where the other one is, with its file when that's another. Set twice to the same value, it's still an error. The last two say that a game's own values are constants.
- In generated C, the settings are in `tide_game_api` (`tick_rate` and `title`), in the `.c` rather than the header, so they don't change the game's hash.
- **Tide's settings in an Android app** (Provisional, Claude, 2026-11-14). The engine's own settings for a run, the `TIDE_` names a desktop run takes from its environment (`TIDE_GPU_CULLING`, `TIDE_VULKAN_ANISOTROPY` and the like), aren't the game's `settings`, and a phone has no environment to give an app. A debuggable Android app (any but `tide build --android --distribution`'s) takes them from its intent's `tide.env`, `NAME=value` words apart, and sets them before `main`; it says each it set in its output (`setting: TIDE_NAME=value`), and each it left out (a name not `TIDE_` and capitals, digits and underscores), so whoever started it can tell: `cmake/run_android.mjs` fails a test whose app didn't say each of its own, which would otherwise pass as the test without them. An app built to ship takes none, and says so: any app on the phone can start another's activity with extras, and a setting such as `TIDE_RELAY` would point its game elsewhere. Weighed: a test passing its whole environment, as a program run through adb does (the caller's `TIDE_HIDDEN` would make local and CI runs differ); one extra a setting (the intent's keys through JNI for nothing more); settings in every app (the point above); and a silent activity, with each test checking its own setting (the fixtures work out what to expect from the same setting they're given, so one that never arrived passes as the default does).

<a id="open-27"></a>

### Open

- Changing settings when the game starts, from the command line or a file: the server would send its settings to the players who join.
- The web page's title: it doesn't show the `title` setting yet.

<a id="c-functions"></a>

## C functions

<a id="decided-33"></a>

### Decided

- Games can call C libraries. `extern` declares a function written in C, with no body: `extern float Noise(float x);`. Calls cost what a call between C functions does.
- Any code that can call a function can call an extern one, match code and local code alike. The language doesn't mark or check what C does: its determinism, the state it keeps and its thread safety are the game's responsibility. The compiler treats a C call as touching no tracked data, so the call alone does not make systems wait or prevent otherwise independent rows from running in parallel. Modelled structural/event effects still require canonical source order. A spawned `Entity` passed to C already has its final logical identity; component installation remains deferred, so lookups before application may find no component data.
- The C function's name is the extern's own name as written, or the one `[NativeName("...")]` gives, so the Tide name can follow Tide's style: `[NativeName("stb_perlin_noise3")] extern float Noise(...);`. A namespace doesn't change the C name.
- A game's C is in its folder, with nothing to set up: every `.c` file there compiles with the game, with the engine's determinism flags, and every prebuilt library there (`.a`, `.lib`, `.so`, `.dll`, `.dylib`) links with it when it was built for the platform being built for. tide tells which platform a library is for from its contents, not its name or folder, so one folder holds every platform's libraries. C for one platform only uses `#ifdef`, as any C does.
- A game's C++ files (`.cpp`) compile with it too, as C++ with no runtime: tide brings no C++ standard library, exceptions or RTTI. What Tide calls is `extern "C"`. C++ that needs the runtime comes as a prebuilt library behind a C API: a shared one, which has its runtime inside, or a static one built to need none, which is the only kind the web has.
- On Android, a game's prebuilt libraries are shared ones (`.so`). An ELF static library has nothing that says whether it's Linux's or Android's (clang makes the same objects for both), and tide tells libraries by their contents, so an ELF one is Linux's: no folder or name says otherwise.
- Writing `external` gets an error that points to `extern`.
- C takes pointers without Tide having pointer arithmetic: the parameter says how a value is passed, and the call takes its address. `mut T` and `out T` are `T *`, `in T` is `const T *`, a `List<T>` is a pointer to its elements (`T *` with `mut`), with the count passed separately, and a `string` is a zero-terminated UTF-8 copy. Each is only valid during the call. A `const char *` that C returns is copied into text.
- C calls keep the order of evaluation: calls to C, and to functions that call it, run left to right like the rest of Tide, whatever order C would pick. One with a `mut` or an `out` parameter is a call that writes (see Evaluation order).
- A game's C draws by taking the frame's draw list: `extern void DrawUI(DrawList list);`, called as `DrawUI(Draw.list)` from a view or a function it calls. C draws into it with `tide/draw.h`, as much as it likes, in order with the view's own Draw calls. So libraries that hand over triangles each frame (Dear ImGui, Nuklear, Spine) need no way to return lists to Tide.

```csharp
[NativeName("stb_perlin_noise3")]
extern float Noise(float x, float y, float z, int xWrap, int yWrap, int zWrap);

component Ground
{
    float2 position;
    float height;
}

system Shape(mut Ground ground)
{
    ground.height = Noise(ground.position.x, ground.position.y, 0, 0, 0, 0);
}
```

<a id="provisional-34"></a>

### Provisional

Implemented, awaiting approval:

- Extern functions take and return numbers, `bool`, `char` (an `int32_t` in C, its code point), vectors, matrices, quaternions, `Color`, `Rect`, `Entity`, `PlayerID`, enums (`int32_t` in C, or `uint8_t` and `uint16_t` for `: byte` and `: ushort`), and structs and components of those, by value. A struct is a C struct with the same fields in the same order: Tide's types have no padding the compiler adds, so the layouts match. The vector types are `tide/math.h`'s (`tide_float3` and the like), which C files can include.
- A `mut` parameter is a pointer to the caller's variable (`float *`, `Stats *`), which C can change, as `mut` works for Tide functions.
- An `out` parameter that isn't a list is the same pointer (see Out parameters): `extern bool TryHalf(int value, out int half);` is `bool TryHalf(int value, int *half)`. The difference is Tide's: the call says `out`, can declare the variable there, and passes in nothing C should read. C is trusted to write it: a variable C leaves alone keeps what it held, which for one declared at the call is its type's default. `out string` is an error, as C can't make Tide's text: C returns text.
- An `in` parameter points at the caller's variable or field when it's one of the parameter's type, and otherwise at a copy made for the call, like a computed value or one that converts (`int3` to `in float3`). `in` is only for extern functions: Tide functions' parameters are read-only already. It doesn't go on text or lists, which go by address anyway.
- A list's elements are plain data (no text or lists in them). C gets NULL for an empty list. With `mut`, C can change the elements, but not how many there are. C can't return a list.
- Provisional, awaiting the owner: `out List<T>` is a list C makes, as C#'s `out`: `extern int WriteImage(out List<byte> image);`, called as `physics.size = WriteImage(out physics.image);`. C decides its elements and how many there are, and what the list held isn't passed, so nothing of it is copied for C.
  - C gets a `tide_list_out *` (`tide/list.h`). `tide_list_out_room(out, count)` gives memory for `count` elements side by side, for C to fill, with whatever was there in it. Asking again gives memory for the new count and the earlier one is no longer good. `tide_list_out_count(out, count)` says how many of them, from the first, the list has once C returns: at most the room last asked for. Never called, the list is empty.
  - Once C returns, the list is exactly those elements: more than it had, fewer, or none. A world's list is written chunk by chunk and only where its bytes differ from what it had, so chunks that come out the same stay shared with the world's snapshots and aren't hashed again; the chunks past the new count go back to the heap.
  - C that knows which elements changed says only those, and the list keeps the rest. `tide_list_out_keep(out, count)` says the list keeps what it holds and is `count` long once C returns: the elements past that go, and the ones it gains are zeros. `tide_list_out_part(out, first, elements, count)` then says the `count` elements from `first` on are the ones at `elements`. Nothing of what the list keeps is written, compared or hashed: only the parts are, each with the elements it goes over. A part's elements are read once C has returned, so they're in memory that's still good then (C's own, not the function's variables). Parts are written in the order they're given, and what's past the list's count is left out. Of keeping and asking for room, what C said last stands.
  - Only an `extern` function's `out List<T>` is made this way, of the elements a `mut List<T>` goes to C with; a Tide function's `out List<T>` is a list it assigns, like any `out` parameter. The call says `out`, as every call with an `out` parameter does: `WriteImage(physics.image)`, as it was written before `out` was every function's, is an error that says so.
  - To everything but C it's an `out` parameter like any other: the argument is a list the code can change (a `mut` component's or singleton's field, a `mut` local, a function's own `mut` list), the call is one that writes (see Evaluation order), and a system that makes one of the match's lists this way waits as one that changes it does.
  - Picked beyond that: the room is NULL for no elements, and for more than a list holds (see Limits); a count said before the room is asked for again is forgotten with that room; `mut out` is an error that says to drop `mut`; the memory is the engine's, kept between calls, which C neither frees nor keeps.
- C gets text as it is when a zero follows it, and a copy in the scratch area otherwise. Text C returns is copied into the scratch area, as C may reuse its memory; NULL is empty text. A `mut string` can't go to C.
- An `Action` and the devices can't be passed to C, nor structs that hold text or lists.
- `DrawList` is only an extern function's parameter, a `tide_draw_list *` in C, neither `mut` nor `in`. `Draw.list` is only an argument for one: a local, a field or a Tide function's parameter can't hold it. It needs the frame, as drawing does, so it's an error in systems, tasks and a parallel loop's steps.
- C draws meshes with `tide_draw_mesh`, or `tide_draw_vertices` and `tide_draw_triangles` for vertices that several batches share, and clips with `tide_draw_set_clip` and `tide_draw_unset_clip`, or `tide_draw_push_clip` and `tide_draw_pop` around some of them. `tide_vertex` is `Vertex`.
- Shaders are tidec's to write: generated code draws through them with `tide_draw_mesh_shaded` (`tide/mesh.h`) and a `tide_shader` (`tide/draw.h`), and C has no frag or vert of its own yet.
- C draws 3D meshes with `tide_draw_mesh_3d`, through `tide_draw_set_camera_3d` and `tide_draw_set_camera_matrices`. `tide_vertex3` is `Vertex3`. A `tide_mesh` is its vertices and indices where C keeps them, and a `version`, as a texture's: the draw list copies them when it hasn't got that version, and C says they changed by changing it (`tide_mesh_version` hashes them).
- C's textures are pixels it keeps: `tide_texture` is their address, `width`, `height` and a `version`, 4 bytes a pixel (red, green, blue, alpha), rows from the first. The draw list copies them when their version or size isn't what it last copied, so C can free or change them once the call returns, and says they changed by changing the version. C holds no handle, and nothing is created or freed.
- At a hot reload the draw list forgets the textures it copied, as the new build's C may name other pixels at the same address and version.
- Calls are put in order the way spawns and GUI calls are: what has to go first runs before its statement, and before a loop's condition each round. An `&&` or `||` whose right side calls C, or a `?:` whose sides do, runs as `if` statements then, so each part still only runs when it would, with its own calls in order. So do struct operators that call C.
- `extern` declarations go at the top level of a file, not in structs. `local` doesn't apply to them.
- The C name must be a C identifier, not a C keyword. `[NativeName]` can't name the engine's functions (`tide_...`), and two externs can't name the same C function.
- tidec declares each extern function itself in the generated C, from its Tide signature, rather than including the library's header, whose names could clash with the game's. If the signature doesn't match C's, the game is wrong the way C would be.
- Libraries: static libraries and Windows import libraries link in; `.so` and `.dylib` files link and are copied next to the game, which finds them there; a `.dll` is copied next to the game, and links through its import library (`.lib`). Windows games build for MinGW, so a static library built with Microsoft's compiler may need its C runtime and fail to link; rebuild it with clang or MinGW. A library tide can't read (LLVM bitcode, text) is left out, saying so.
- On Android, the game's shared libraries (`.so`) for each of the app's CPUs link and go in the app with the game, each under the name it was linked with (its soname, or else its file's name), which has to be `lib<name>.so`. Android's libraries and Linux's are both ELF: a shared library is Android's when it has the note Android's NDK puts in what it links (`.note.android.ident`). tide warns about a library whose segments are aligned for pages smaller than 16 KiB, which may not load on phones that have those.
- On the web, only C files and WebAssembly libraries define functions. A web build fails when a function has no definition there (an extern function, or one the game's C calls), rather than when the page calls it: a web program may only leave undefined what the platform layer does, which the page defines.
- `tide run` builds again when a C or C++ file, header or library changes. C code is part of the game's library, which each build replaces, so the state C keeps starts over at each reload.
- tide's own CMake (`tide_add_game`) compiles the `.c` and `.cpp` files in the game's folder but the host's, or those listed after `SOURCES`. It doesn't pick up libraries.
- C++ files are `.cpp`, `.cc` and `.cxx`. They build as C++20 with `-nostdinc++ -fno-exceptions -fno-rtti -fno-threadsafe-statics` on every platform: the standard library's headers aren't found even where the system has them, so the same code builds everywhere. C's headers are there. `.hpp`, `.hh`, `.hxx` and `.inl` files count as headers, like `.h`: a change to one builds the folder's files again.
- tide defines nothing of the runtime's: code that uses `new`, `delete` or a pure virtual function defines `operator new`, `operator delete` and `__cxa_pure_virtual` itself. A global's constructor runs before the game does (at each reload under `tide run`). A function's static with a constructor is made the first time through, with no lock.
- A build that fails for want of the runtime says so after the compiler's or the linker's errors, with what to write instead: a standard header that isn't there (`<cstdint>` gets C's `<stdint.h>`), `throw`, `try`, `typeid`, `dynamic_cast`, `new`, `delete`, `__cxa_pure_virtual`, and a prebuilt library built to need the runtime.

<a id="systems-written-in-c"></a>

### Systems written in C

Provisional. The owner approved the direction (2026-10-05: a system whose body is C, "in a way that lets others use this too for their own situations"); the syntax, the semantics and the C API below are picks that await them.

An extern function is called for one entity at a time, with a copy of what it reads. C that wants every entity's data (a physics library, pathfinding, animation, a loop written with SIMD) is handed the components as the arrays the match keeps them in.

```csharp
[NativeName("game_move")]
extern system Move(mut Position position, Velocity velocity, Time time, without Frozen);
```

```c
void game_move(tide_rows *rows, const Time *time);
```

- **The declaration.** `extern system Name(parameters);`: a system's declaration with `extern` before it and no body. It takes the attributes a system takes (`[Stage]`, `[Before]`, `[After]`) and `[NativeName]`, as an extern function does: its C function has its own name as written, or the one `[NativeName]` gives, whatever its namespace. Extern systems that share a name each say theirs, and a C function is one extern function or one extern system, declared once. A body is an error that says to end it with `;`. `extern view` and `extern event(...) Name(...)` are errors that say only a system can be written in C.
- **To the rest of the language it's the system its declaration says.** It runs for the entities its parameters pick, it's ordered and scheduled as a system, and what it reads and writes is what it declares: a component or singleton it takes `mut` is written, and the rest is read. One it takes `mut` that holds text, lists, maps, sets or grids is one whose memory C can change, kept in the match's own memory, so the system waits for every system that changes what's kept there and they for it, whatever data they share (Claude's pick, 2026-11-15: two that change it at once would corrupt it). Nothing warns about access it doesn't use, as its code can't be read. `tide schedule` shows it as `Move  (per entity, in C)`, and the editors' line above it says `in C`.
- **Parameters.** Components, to read or `mut`; `with` and `without` filters; singletons, to read or `mut` (the engine's stay read-only). Each of these is an error that says it isn't there yet for a system written in C, and what to write instead:
  - a sparse component, or a filter by one: which rows have it is told row by row, and C is handed whole runs;
  - the `World`, a `query`, `Devices`, the input: a system written in Tide takes them, and can call C;
  - an `Entity` parameter: C reads each row's entity from its rows;
  - a component with no fields as a parameter: it's a filter, `with`.

  What no system takes is the error it always was: `with ownership`, `verified`, `out`, a default, `local`, `async`.
- **What C is called with.** One call for each run of rows: a chunk of an archetype the filters admit, or a piece of one when the tick shares a chunk out over threads, in the order a system written in Tide would go through them on one thread. A run has at least one row. The function takes the run, a `tide_rows *`, then the singletons the declaration takes, in its order, each by address (`const` for one it only reads), and returns nothing. Components are reached through the run, numbered from 0 in the order of the system's parameters; filters and singletons don't count.
- A system with no component and no filter runs once a tick, as in Tide: C is called once, with a run of no rows and its singletons.
- **The C API**, `tide/rows.h`:
  - `tide_rows_count(rows)`, and `tide_rows_entities(rows)`, each row's entity.
  - `tide_rows_floats(rows, component, offset)` and `tide_rows_ints(rows, component, offset)`: the array of a 4-byte field (a float, an int, an int enum, half a long or an entity), a value a row, by where the field starts in the C struct that has the component's fields in order (`offsetof`). `tide_rows_floats_mut` and `tide_rows_ints_mut` are the same to write, for a `mut` component, with what's there in them.
  - `tide_rows_get(rows, component, row, &value)` and `tide_rows_set(rows, component, row, &value)`: one row's whole component, for the fields that aren't 4 bytes, for a component whose size isn't a multiple of 4 (kept 2 bytes or 1 at a time), and for C that works a struct at a time.
- **Nothing is copied to read**: an array is the match's own memory. **Writing is on demand, a field at a time**: asking for an array to write is what makes that field's page the match's own, a copy when a snapshot shares it, and a page that comes out as it was is the snapshot's again once C returns, with its hash. `tide_rows_set` writes the 4 bytes that differ and asks for no other. So C that writes nothing costs nothing, and C that writes 5 fields of 40 touches 5 pages.
- An array to write is the field from then on: C reads it through that pointer too. One of the same field asked for to read before it may be the memory the snapshot kept.
- A call that can't be answered stops the program, saying which function it was, in which system, and what to write instead: a component number the system doesn't have, an offset that isn't a 4-byte field's, a component not in fields of 4 bytes, an array to write or a `tide_rows_set` of a component that isn't `mut`, a row past the run.
- **Text, lists, maps, sets and grids.** A component or a singleton that holds some can be taken; those fields are handles into the match's heap, which C leaves as they are. C has no way to read or change them from here yet.
- **C can't spawn, destroy, add, remove or send** from a system: there's no call for it. A system written in Tide does, from what C left in a component or singleton.
- **Threads.** It splits its entities across threads by the rule a system written in Tide does: its runs go to several threads at once unless it takes a singleton as `mut`. C is trusted, so what it does on several threads is the game's to get right: each run reaches its own rows, and a system that keeps something from one run to the next, or needs them in order, takes a `mut` singleton.
- **How much work it is.** Its code can't be read, so where the engine reckons whether a tick is worth threads, a row counts as 256 operations: what a few calls would, as C is written for what's more work than a line of Tide. No attribute says otherwise yet.
- tidec declares the C function in the generated `.c`, from the declaration, as it does an extern function's. A web build fails at its link when nothing defines it.

Picked beyond what was asked for:

- A system that runs once a tick is allowed, and gets a run of no rows rather than no run, so every system written in C has one signature.
- Components and singletons that hold text or lists are allowed (an extern function refuses such a struct), as C can't be handed a singleton any other way and a physics library's is likely to hold lists. Their handles are C's to leave alone.
- A component with no fields as a parameter is an error rather than a component C can't ask anything of.
- `tide_rows_get` and `tide_rows_set` number rows from 0 within the run, and a row past it stops the program.
- The C function's prototype in generated C has no parameter names, as a game's could be anything.
- `extern` is a word before `system`, a name anywhere else, as it is before a function.

<a id="provisional-resident-state"></a>

### Provisional: resident state

A C library whose state is big and lives between calls (a physics world) has, until now, been a guest in the match: all of its state written into a list of the match's after every tick, and the library's own world made again from that list on every rollback (see the Box3D package). Resident state is the other way round, for libraries that come with tide (the owner, 2026-10-07: "for ours only is fine to start with"): the library's memory is the world's, snapshots of it are copies of the pages that changed, a rollback is copying them back, and nothing is serialized except to send or to reload. The owner asked for the direction ("how do we make it a resident? how do we allow externals to take part?"); the rest is Claude's picks.

- `Resident` is a built-in type for one field of a match singleton: `singleton Physics { Resident state; ... }`. Tide code can't read or write it, copy it out, or pass it except to an extern function's `in Resident` or `mut Resident` parameter, or put it in a struct, a component, a list, an event, an input, local state or the GPU. It's for the package's C alone, which gets it with the singleton. Only one such field per singleton, and eight at most in a game. A singleton that holds one can't be copied into a local or assigned whole. A Tide function or method can borrow it to read or change it, but can't take the same singleton both by value and `mut`: changing it could release pages the read copy still names. An extern function's borrowed `in Resident` and `mut Resident` parameters can be used together.
- **What it holds.** The pages of the library's arena as they were when the tick ended (a snapshot of that machine's own, never sent and never hashed), and three numbers the C side writes: a `kind` (which library's), a `stamp` (which state), and a `digest`. The world's hash covers the stamp and the digest, and nothing else of it. So what the match agrees on is the digest, and the engine's hash check finds a divergence through it within a tick, as it would through the pages of the library's state as a list.
- **The arena.** `tide/resident.h`: the engine keeps one arena for each kind in the process, at a fixed address for as long as the process runs (reserved whole, committed as it's used; 64 MiB unless the library says otherwise, past which the program stops as it does when a world runs out of memory). The library allocates everything it owns from it (`tide_arena_alloc`, `tide_arena_free`, which can be called from the tick's threads at once) and says what it may have written (`tide_arena_touch`): the arena keeps a byte a page for that. The arena's bytes are position-dependent (they hold pointers) and never the same twice (threads allocate in whatever order they get there): they're this process's own, and nothing of them crosses a machine. A compatible reloaded build takes the arena over at the same address and relinks what named the old build.
- **Commit and restore.** When the library's tick is done, `tide_arena_commit(arena, resident, stamp, digest)` copies every touched page into the resident (pages the world owns, shared with its snapshots and copied on write like every other page; a page that wasn't touched stays the one the world had) and clears the touches. Before a tick of a world whose resident pages aren't the arena's, `tide_arena_restore(arena, resident)` copies into the arena every page that differs from what the arena holds, by identity (the arena remembers which page it last loaded or committed at each place): the pages of the ticks between, and nothing else. A world's copy shares the pages; its free releases them.
- **Canonical bytes** are written by the library, through the kind's functions (`tide_resident_register(&kind)`, which the library calls as it loads; a world names its kind by the name's hash, so a library loaded again finds it): `pack` writes what a machine that has none of this state needs to make it (the library's own serialization, as the image is today), and `unpack` makes the arena's state from them and commits it. The engine calls them where a world is packed, unpacked, sent as a delta or carried across a reload, and only there: a joining player, a resync, a host migration, a hot reload. Nothing else ever serializes. A delta carries them whole (not against a base) for now.
- **Hot reloading.** A native reload with the same layout keeps the arena at its address: the registry rides in the local state the host keeps (`tide_local.tide_residents`), and the engine detaches that registry before the local state is cleared or freed. A build that takes over relinks callbacks, scratch and pointers into the previous build's constants (`relink`). A reload that changes the layout carries the resident through canonical bytes by the field's name, into the new build's arena. The web always migrates through canonical bytes, into its new linear memory.
- **One arena a kind**, so one live state: a world at another stamp is restored before it's stepped, and a question asked of a world at another stamp (a view's query of the confirmed world) restores that state, answers, and the next tick restores its own. Several arenas a kind, for a server and a client at different ticks in one process, are an open question: a page's bytes belong to the arena they were taken from.
- **What it costs, against the state as a list:** a tick pays for copying the pages it touched, not for writing its state out and comparing it; a rollback pays for copying the pages that differ, not for making a world again and writing it out whole. The library's own step is what it was.
- **Not built, and open:** a resident in a component or in local state; several arenas a kind; deltas against a base; a game's own libraries (which would need position-independent pages, or a schema to relocate them); what the digest covers beyond what the library says.

<a id="open-28"></a>

### Open

- Systems written in C: spawning, sending and structural changes from C; sparse components, with which rows have them as an array; the `World` and queries; text and lists; views and event handlers; and the game saying how much work a row is.
- Objects C owns (`ma_engine *`): a handle type only local state can hold, since pointers differ between machines.
- Keeping the state of C libraries across hot reloads, by building them apart from the game's library.
- Reading declarations from C headers, with tide's built-in clang.

<a id="packages"></a>

## Packages

<a id="decided-34"></a>

### Decided

- Games share code as packages: Tide code (and C) from a git repository, at a commit, or from a folder on this machine.
- A game lists its packages in a file of its own, `tide.packages`. A package from git is always pinned to a commit there, so every build of a game builds the same code; there's no lock file, and nothing is generated.
- A game can pin its Tide release with `tide = <exact-version>` in `tide.packages`; `tide pin [version]` writes this line. Decided (2026-10-29): CLI project build and package commands select that version from the shared side-by-side cache and ask before downloading a missing release, leaving the main installation unchanged. Unity retains its package-selected toolchain; engine source builds ending in `-dev` retain their development compiler. Only a game pins its Tide; packages declare a minimum version. Decided (2026-11-03): standalone games may instead follow `tide = nightly` or `tide = stable` (`tide pin nightly|stable`). Each channel shares one installation, checked at command startup and updated in place only while idle. A complete installed channel is reused offline or after a failed download; the exact selected version is reported. Selecting a channel authorizes later updates after its first consented installation. Exact cached releases expire after 30 days without use; active sessions, the main installation and channel installations are retained. Existing caches get a fresh grace period on first observation. Unity keeps its package-selected exact compiler.
- A game builds what its packages need, and what those need, without listing them, and its own line for one of them wins (the owner, 2026-10-30: "we should include dependencies automatically").
- A package declares nothing global: everything it declares is in its namespace.
- `tide update` moves packages to the newest commit of what they follow: a branch, or the newest tag of a version.
- Packages come from git hosts. Code adapts to the version of tide it builds with (see Conditional compilation).

```
# tide.packages
github.com/someone/tide-physics@v1 b01aac4d779e32c9c415283b65e40c86d691e7ab
../shared
```

<a id="provisional-35"></a>

### Provisional

Implemented, awaiting approval:

- `tide.packages` has a line each, and `#` at the start of a line or after a space starts a comment. A package line is a source, then its commit: `github.com/owner/repo 0123...` (40 hex digits, or 64), with `@ref` after the source for what `tide update` follows (the default branch without one) and `//folder` for a package in a folder of the repository. A line that starts with `.`, `/` or a drive (`../shared`, `D:/shared`) is a folder, relative to the file's, and has no commit. A line without its commit is an error that says `tide update` pins it.
- A package is a folder whose `tide.packages` says `package Name`: its name and namespace, dotted or not. Its files are in that namespace or one inside it, and it can't declare `Main`, the input or settings, which are the game's. `tide 0.3` says the oldest tide it builds with; a game can say it too. Its other lines are the packages it needs; a package from git can't need a folder.
- What a package needs, the game builds too, and what that needs, each from the line of the package that needs it: a package from git at the commit that line names, a folder relative to that package's folder. The game's `tide.packages` lists only what it chooses; `tide add`, `update`, `eject` and `fetch` write no lines for what packages need. Where the game lists the same source (any commit) or the same folder, the game's line is what's built. Two packages needing one from git at different commits, which the game doesn't list, is an error at the second one's line naming both, with a note that the game's line chooses and the line to write; the same commit, or the same folder, is one package. A package's line from git without a commit is an error unless the game lists that package. Two packages of the same name are an error.
- Files compile with each package's first, in an order where each package comes after those it needs (by name where that leaves a choice), each package's by path, then the game's. That's the default order of systems.
- A subfolder with a `tide.packages` of its own is a game or a package of its own, and isn't part of the folder's game or package: a package's example game lives inside it, listing `..`.
- A version-looking ref (`v1`, `v1.2`, `1.2.3`) follows the newest tag whose numbers start with it, leaving out pre-releases; any other ref is a branch, or else a tag, of that name.
- Packages from git download as their host's archive of the commit (GitHub, GitLab, Codeberg and Bitbucket), with curl and tar, into a cache shared by every game: `$TIDE_PACKAGES`, or `%LOCALAPPDATA%/Tide/packages` on Windows and `~/.tide/packages` elsewhere, at `<host>/<owner>/<repo>/<commit>`. A commit's files go there one by one, and a file named `.tide-fetched` last, which says they're all there: a folder without it is downloaded again. `tide run` and `tide build` download what's missing. Branches and tags come from git's own list of them (`info/refs`), which every host serves.
- `tide add <source>` takes URLs as people copy them (`https://...git`, `git@host:owner/repo`) and writes the source as `tide.packages` does. `tide update [names]` matches a package by its name, its repository's or folder's name, or its source, and only changes commits, leaving the rest of the file as it is.
- A package's systems that match no entity, and its handlers of events nothing sends, aren't warned about: a game may use only part of a package.
- The language server analyzes a game with its packages, and a package's file with an open game that uses it, or else the package on its own, which needs no `Main`.

Packages that come with tide: a package in tide's installation, which a game opts into with one line, and which costs a game that doesn't list it nothing. How the line is written and where the package is looked up are picks, awaiting the owner:

- Provisional: the line is a name alone, lower-case letters and digits after a letter: `box2d`. Nothing else in the file is written that way: a git source has a `/`, a folder starts with `.`, `/` or a drive (so a folder of that name beside the game is `./box2d`), and `package` and `tide` lines take a second word.
- Provisional: it takes no commit and no `@ref`, each an error that says why: the package is the version this tide came with. So what a game builds of it depends on the tide that builds it, where a git line's commit doesn't; `tide 0.3` in the game's file says the oldest.
- Provisional: the package is the folder `src/packages/<name>` of tide's installation (the folder tide's `bin` is in), beside `src/engine`: both are sources that compile with the game. This repo's are in `packages/`, which a build installs there. The installation's own `packages` folder is where packages from git are kept, and holds none of these, so `tide upgrade` replaces them with the rest of the installation and leaves that folder alone.
- Provisional: it's otherwise a package like any other. Its `tide.packages` says `package Name` and lists what it needs, which the game builds without listing it: another that comes with tide by its name, or one from git. It can't need a folder, as a package from git can't. `tide run` reloads the game when its files change, as it does for a folder's.
- Provisional: a name no package has is an error that lists the names there are, with the closest when one is close. `tide add <name>` writes the line, in lower case however the name was typed; `tide update` leaves the line alone and says nothing about it, and `tide update <name>` says `tide upgrade` is what updates it.
- `#if` lines in `tide.packages` say which builds a package is in (the owner, 2026-10-11, of a Steam package for shipping and another for testing: "similar to `#if def` sort of thing ... just add a steam define when building for steam", and packages for debug or release builds only). Provisional, the rest: `#if`, `#elif`, `#else` and `#endif` at a line's start, with conditions as a `.tide` file's (symbols, `!`, `&&`, `||`, `==`, `!=`, parentheses, `true`, `false`, `TIDE_0_4_OR_NEWER`), read with the build's symbols: `DEBUG` in the default debug mode (undefined with `--release` or `--distribution`), and each `--define`. Any other `#` line stays a comment; `#ifdef` and `#ifndef` are errors that say what to write. A line a condition leaves out is no part of the build: nothing of its package compiles or links, its `PACKAGE_` symbol isn't defined, and it's never "listed twice" with a line of another branch. `package` and `tide` lines can't be inside one. A condition can't read a `PACKAGE_` symbol, which this file makes. A package's own `#if` lines are read with the same build's symbols. `tide add`, `update`, `fetch` and `eject` take every line, whichever build it's for, and check the file as a `tide run` would build it (`DEBUG` alone); editors read it so too. A symbol only this file reads isn't in the game's hash by itself: the packages it brings are.
- `tide eject <package>` makes one of the game's packages the game's own (decided 2026-10-11: a command that puts a package's files in the project to edit). Provisional, the rest: it copies the package, from git at its line's commit or one that comes with tide, into `packages/<its folder's name>` in the game's folder, without what tide made there (`.tide`, `build`, `.tide-fetched`, `.git`), and writes that folder (`./packages/rooms`) in place of the line's source and commit, keeping a comment after them. It stays a package, with its `package` line and what it needs. One that's a folder already is left alone and said so; a folder already there is an error and nothing is copied or written.

<a id="open-29"></a>

### Open

- A registry of names, so a line doesn't need its host.
- Packages from private repositories, and hosts other than those four.
- Symbols for the packages a game has, so code can add to another package only when it's there (`#if PHYSICS`).

<a id="dev-tools"></a>

## Dev tools

Agreed 2026-11-16, from the owner's question of how a team's members get tools of their own (isolating a piece, jumping to a situation, inspecting entities), checked on paper against two of the owner's games before anything was built. The game provides its tools; the engine makes them easy to make, and never assumes how a game draws.

Decided:
- **`dev` before a declaration** (the owner's pick over a `[Dev]` attribute or a build value a game checks): `dev command GiveAmmo { ... }`, `dev view GunTools(...)`, `dev scene GunRange { }`. A build without dev doesn't have them at all, so a release server can't be sent a dev command.
- **Code without `dev` can't use what's `dev`**, checked by the compiler in every build, so a build without dev fails nowhere a dev build passed.
- **A dev build is a switch of its own**, apart from optimization and target: an optimized or a web build can be a dev one, for playtesters.
- **A scenario is a dev scene**, which `--scene` starts in place of the start scene; one that wants the game's usual start loads it itself.
- **The inspector's edits change the match for everyone**, applied by the server. What depends on a field follows it through match handlers of `Changed<...>` (Events), not an event of the inspector's own.
- Order of the pieces: `dev` and the dev menu (built), dev scenes (built), the tweak file (being built), the inspector, checkpoints, picking on screen, pausing and rewinding a run.

Provisional (Claude's picks, built 2026-11-16):
- `dev` goes before any declaration but settings and namespaces, and before a type's method. A dev type's methods, a dev scene's preparation, a dev generic's instances and a lambda written in dev code are dev too. A field can't be dev: it's in every build, and a dev component or singleton holds what dev code needs.
- **Which builds** (the owner agreed): `tide run` builds with dev unless `--no-dev` or `--distribution`; `tide build` with `--dev`; tidec's `--dev`; `tide_add_game(... DEV)`. Schedule and shader listings see the dev declarations.
- **The dev menu**: the key under Escape (backquote, the owner's pick, where Valve's games open their console) in a dev build with `dev` views shows it over the views, listing them by name with a switch each; a dev view runs only while its switch is on (the owner agreed), kept by name across hot reloads. The game sees the key too. The menu is the standard host's (tide/host.h); another host shows dev views through `tide_show_dev_views`.
- **Scenarios** (built 2026-11-16): `--scene` takes a scene with its fields as Tide writes them, `--scene "Battle { side = 50 }"` (tidec, `tide run`/`build`, `tide_add_game(... SCENE ...)`); a prefab is named alone. A build started that way doesn't warn that code on what only the usual start makes never runs.
- **Tweaks** (agreed 2026-11-16, the owner's: the `tweak` keyword, tweaks on fields, a separate file holding only what differs from the code, the editor showing the override and going between the two, a dev build's changes going through the server to every machine; then, replacing the first file's JSON the same day: `.tweaks` files of Tide's own syntax, several to a game, whose values are worked out with math and constants). Claude's picks: `tweak T Name = value;` at the top of a file or a namespace, T a number, bool, vector, Color or enum. A `.tweaks` file is `Name = value;` lines (qualified names, `//` comments); every one in the game's folder and its folders is read (the folders of the files tidec is given, without their folders, where it's given no game folder); a value is a constant expression of numbers, other tweaks and constants, operators, constructors and Math's functions, checked as the tweak's own, an error when it uses anything else; a tweak set in two files is an error, a name no tweak has a warning. A tweak isn't known while compiling: a case, a bound, a setting or a constant's value can't read one in any build; a field's default can (the build's value). Without dev each read is the build's value, as a constant; with dev, code that runs reads the match's hidden `TideTweaks` singleton, local code this machine's copy, and GPU and audio code the build's value. Tweak fields: `tweak float kick = 0.1;` in a component's, singleton's or struct's body is a tweak of that type's, the same for every value of it and held by none, read as `gun.kick`, `Gun.kick` or `kick` in its methods, named `Gun.kick` in a `.tweaks` file; a value of the type can't give one, and code can't set any tweak. Live changes: tidec writes the values it worked out beside the C (`<name>_tweaks.bin`), which `tide run` makes again as a `.tweaks` file changes, with no C built; the standard host takes them (half a second at most) into this machine's copy and sends them to the match (`TideSetTweaks`). The dev menu edits a tweak written plainly and writes its value into the file that sets it, or the one beside its declaring code, keeping the rest; one worked out is shown read-only. In editors: a lens on each overridden tweak with the file's value, opening the file at its name; the tweak's hover says it; in a `.tweaks` file, which editors hand tidels as Tide, a name's hover and go to definition.
- The compiler's check covers names and methods code writes in declarations, signatures, fields and bodies, generic instances' and lambdas' too. A build without dev says of a name it doesn't find, when it's a dev one, that it's dev and left out.

<a id="mods"></a>

## Mods

**Decided** is what the owner agreed (2026-10-05); the design proposed for the rest is under **Open**. Of it all, two parts are built (**Provisional**, below): `virtual` and `override`, as the language has them for any package, and the service's first slice, for web games, with `tide publish`. What a mod may be, games that load builds, and the sandbox aren't.

**Open again** (the owner, 2026-10-06: "its no longer decided"): who builds a game with its mods. That a service we run does was agreed, and built as a first slice, which is on hold. It isn't decided any more, and neither is what rested on it, each marked below: where a player's build comes from, who signs it and how it's revoked, what the `mods` setting lets a game run, and a closed game's source being the service's alone. What's being weighed instead, with nothing of it agreed: a game loads a build of itself for its platform, as `tide run`'s host loads one, and that build is compiled on the player's own machine from the mods' source where the platform allows a compiler (the developer opting in to ship it), or made elsewhere and fetched where it doesn't. What stands: a mod is a package and its code is game code, every machine of a match runs the same build, `virtual` and `override`, a mod being Tide alone, the prompt being the game's, memory safety, and the sandbox on desktop. And one thing agreed since: mods are the same on every platform (below).

**Agreed since** (the owner, 2026-11-14), which settles who builds on desktop. None of it is built:

- On desktop, a mod is compiled on the player's machine, from its Tide source, by a compiler the game ships with. A mod never arrives compiled: nothing could check that such a library came from Tide and keeps its rules. Platforms where no compiler can run are still open.
- There are two ways for a game to take mods, both wanted, and which is the developer's choice:
  - **Compiled with the game.** The game ships its `.tide` files as they are, and the game and its mods build as one program. What Decided says below of one program, with the same storage, schedule and speed, is this way's.
  - **Loaded into the game.** The game ships finished, with its declarations and none of their code. A mod is compiled by itself against those declarations and loaded into the running game as a library. This is for a game that doesn't give its source away, and its mods' code costs more than the game's (see Open, Mods loaded into a finished game).
- A game's declarations are visible to its mods unless the developer hides them, with a marker whose name is to pick (agreed "for a first run").
- C is unsafe for mods unless the developer says otherwise: a mod calls a function of the game's that reaches `extern` only where the developer marked it for mods. Such a function can hand a mod what the language keeps from it (a file read that takes any path). The marker's name is to pick.
- For mods loaded into the game: their systems run one after another, in a fixed order, at the named phases' boundaries, for a first version (joining the threaded schedule later changes no mod's source), and desktop comes first, the web after.
- A loaded mod that puts one of the game's components on one of the game's entities, in a combination the game never makes, should work rather than be an error (the owner: an error is "too limiting", said with "i could be wrong"). How is under Open.

<a id="decided-35"></a>

### Decided

- A mod is a package that someone other than a game's developer adds to it. It builds as packages do: its files compile with the game's, as one program, so a mod's code is game code, with the same language, storage, schedule and speed. There's no scripting layer, nothing is interpreted, and games carry no runtime for mods.
- (Open again, see above.) Mods are built by a service we run, beside the relay and hosting, not on players' machines: it has the game's source and the mods', builds the game with them for each platform, and signs what it built. A game runs only builds signed for it.
- Every machine of a match runs the same build, as ever, its local code included: mods never differ between the players of a match, not even ones that only change views, since a view can show a player what gives them an advantage.
- (Open again, see above.) A player who joins a match with other mods gets its build from the service, never from the match's host. The game is told first, with the mods' names and where they're from, so that it can ask its player ("this match runs these mods"), who then knows that code from outside the game is about to be downloaded. It joins once local code says yes, and nothing is fetched before that.
- That prompt is the game's own, in its look and its language. The engine draws none and enforces none: it can't tell whether a game asked, one of its own wouldn't fit the game, and it isn't what keeps a player safe. A game whose code never says yes joins no such match, so none skips the prompt by accident. For mods a developer listed, whether to ask is the game's choice, as the developer approved them. For mods from anyone, telling the player is a condition of the service, which turns such mods off for a game that doesn't.
- A build's mods are a set: the order they're listed in changes nothing, since what would depend on it is an error.
- A mod is Tide alone: no `extern`, no C or C++ files, no libraries.
- `virtual` before a declaration says it can be replaced, as in C#, and `override` before another replaces it. Both are always written: nothing is replaced by having the same name, and nothing can be replaced that its developer didn't mark. It happens while compiling: what was replaced isn't in the build, and an override costs what the code it replaced would.
- An override matches by name and by parameters, both: the parameters' types, a system's filters among them, as overloads are told apart. Two systems can have the same parameters and filters under different names, and several declarations can share a name, so neither alone says which is meant.
- An override takes the place of what it replaces: its stage, its `[Before]` and `[After]`, and every reference to its name. Nothing calls the code that was replaced, for now (see Open).
- Two mods that replace the same declaration are an error that names both.

```csharp
// The game
virtual system Move(mut Position position, Velocity velocity, Time time)
{
    position.value += velocity.value * time.dt;
}

// A mod
override system Move(mut Position position, Velocity velocity, Time time)
{
    position.value += velocity.value * time.dt * 2;
}
```

- A mod's code sees files as a web page's does: files of its own, and nothing else of the machine.
- A mod's code calls nothing that reaches outside the game: `Session.Connect` and `Clipboard.Copy` are the first two. Which calls those are is part of the sandbox's work.
- (Open again, see above.) `mods` is a setting, false by default. With it, what `tide build` makes can also run the builds the service signed for the game. A game without it has none of this.
- (Open again, see above.) A closed game's source is seen by the service alone. Its modders have its declarations, each without its body.
- (Open again, see above.) Builds are signed with a key per game, and a build can be revoked: a game stops running one the service says no longer stands.
- On desktop, a build with mods runs inside the system's sandbox, as a second layer under the language's own rules. On the web, the browser's is that layer. A system that can't sandbox a build runs no mods, and the game says why: making the sandbox work wherever games ship is our job, so that's the exception.
- That no Tide code can corrupt memory is the language's promise to every game, and mods rest on it: it isn't a rule for mods.
- Mods are the same on every platform Tide targets, phones and consoles included (the owner, 2026-10-06, replacing what was agreed before, that a platform whose store forbids code downloaded after installing has the mods its developer built in and no others). The engine holds no platform back for what a store allows: whether a store or a system lets a game load code that came after it was installed is the game's developer's to know, and so is mods being less useful somewhere for it.

<a id="provisional-36"></a>

### Provisional

`virtual` and `override`, implemented for every package, a mod's or not, awaiting approval:

- **Where the words go.** Where `local` and `async` do, in any order with them, before a declaration with code: a system, a view, a handler (an event's, a command's, a local one), a function, a method, a frag or a vert. They're words of their own only there, and names like any other everywhere else, a function's type too (`virtual Make()` is a function that returns a `virtual`).
  - On data (a component, singleton, struct, event, command, enum, scene or the input), a constant, the settings or an `extern` function, each is an error that says what the words are for, and why this isn't it. Editors offer to remove the word.
  - Operators, `Interpolate` and the input's `Sample`, `Sanitize` and `Predict` aren't replaced either: an error on each.
  - `virtual override` together is an error: a declaration is replaced once, so nothing could replace an override.
- **The name an override writes.** It's the name of what it replaces, looked up as any reference is from the override's file: with its namespace (`override system Combat.Move(...)`), or alone in that namespace, in one inside it, or after `using Combat;`. Two `using` namespaces that both have it are ambiguous, as for any name.
  - A method's override is written outside its type, since it's in another package, with the type before the method's name: `override bool Stats.IsDead()`, or `override bool Combat.Stats.IsDead()`. The type's fields and methods are in scope, as in the type's body. Where a type and a namespace have the same name, it's the type.
  - An override's code reads names as its own file does: its namespace and its `using` lines.
  - It declares no name of its own: nothing in its own namespace is named after it, and it clashes with nothing there.
- **What it has to match.** An override that names nothing is an error that says what there is: the name in another namespace, with how to write it, a declaration of another kind under that name, or the closest name. One whose parameters are no declaration's lists the declarations the name has, as a wrong reference to a shared name does. One that matches a declaration that isn't `virtual` says so, and that marking it is its developer's choice; editors offer to mark it where it's the game's own.
  - Beyond its parameters' types, an override is what it replaces: a view's is a view, a handler's handles the same event (a command's the same command), `local` and `verified` on its event as the other has them, and `async` as the other is. A function's or a method's returns the same type, `fails` with the same error, and has `out` where the other has it. Each is an error that says what the replaced declaration has, with the override's start as it should be written.
  - It can differ in its parameters' names, in `mut` (a parameter's, and a method's own), and in a function's default values. Calls are checked against the override, since it's what's built: its defaults, its names for arguments passed by name, and its `mut`.
- **Where it runs.** It writes no attribute of its own: `[Stage]`, `[Before]` or `[After]` on an override is an error that says it keeps the replaced declaration's. Those are read as the replaced declaration's file wrote them. Its place in the default order is the replaced declaration's, among that one's file's declarations.
- **Another package.** An override is in another package than what it replaces, the game counting as one: a package replaces the game's code or another package's, and a game a package's. One in the same package is an error that says to change the declaration itself. A package can mark its own declarations `virtual`.
  - `tide` and the language server say which package each file is in. `tidec` by itself is told with `--package <Name>` before a package's files, on its command line or as a line of a list of files, which is how this repo's tests build games with packages (`tide_add_game(... PACKAGES <Name> <files>...)`).
- **What was replaced.** It's still checked for errors, as the code it is: its names, types, what it may write, what it returns and assigns. It isn't checked for what depends on the code that calls it or that it calls (a match system that calls a function that draws, say), as those rules are worked out over the program that's built, which it isn't in.
  - Nothing of it is built or counted: its spawns, Adds and Removes make no archetype, what it sends counts as sent by nobody, its calls make nothing wait, and it's in no schedule. It warns about nothing.
- **Parameters nothing uses.** A virtual declaration's parameters are what its overrides get, and an override's are those of what it replaces, so neither is warned about a parameter it never uses: a virtual system with an empty body is a hook. `mut` is each one's own, and one that's never written is still warned about.
- **The same declaration again, without `override`.** It's the error it always was (`is already declared with these parameters`). Where the first one is `virtual` and in another package, a note says `override` is what replaces it, and editors offer the word.
- **Names in tools and generated C.** An override in place goes by the replaced declaration's name, with its namespace: `Combat.Move` in `tide schedule`, the profiler and messages, `tide_system_Combat_Move` in generated C. A game that uses neither word generates the C it did, byte for byte.
- **Editors.** Hover says what an override replaces and what replaced a declaration, and so does a line above each. Go to definition on an override's name, or on `override`, goes to what it replaces; on a use of the name, to what's built under it. Go to implementation on a virtual declaration goes to its override. Find usages and rename treat an override and what it replaces as one name. After `override`, completion lists the virtual declarations of other packages that nothing replaces yet, each written out as the file would write it.

The service's first slice. Implemented, and on hold (the owner, 2026-10-06: it may be too complicated, from the service's side): the code is in the services' own repository, and nothing of it is deployed. It ran for a day at `builds.tide-engine.dev`. A developer publishes a version of a game's source; whoever has the game's key asks for a build of that version with a set of mods; the service builds it as a web page in a machine made for that build, signs it, and serves it at a link anyone can open. It was agreed for this slice that a game is an id and a key, with no accounts; that a build is named by a SHA-256 of the game's id, the version, its mods sorted, and tide's version; that builds are signed with a key per game, ECDSA on P-256, as 64 bytes; and that a build can be revoked. The picks:

- Provisional: `tide publish [folder]`, the name proposed below. It sends what a build reads from the game's folder: its `.tide` files, its C and C++ with their headers, its libraries and its `tide.packages`, with the packages in folders inside the game's. Packages from git aren't sent, as their commits name them, and a package in a folder outside the game's is an error. It doesn't compile the game first: a version that doesn't build is found when a build is asked for.
- Provisional: the game's key is in the environment, as `TIDE_GAME_KEY`, and nowhere else: no file. A key is the game's id, a dot and a secret, so one variable says which game too. An id is lower-case letters, digits, dots and dashes, as it's part of addresses. `TIDE_BUILDS_URL` names another service than ours.
- Provisional: a version is named by the SHA-256 of what was sent, and `tide` writes that archive itself (a tar, with no times, owners or modes, its files in one order) rather than with the system's `tar`, so the same files are the same version from any machine. `tide publish` says one line, with the version.
- Provisional: asking for a build is an HTTP call, not a command: `POST /games/<id>/builds` with `{"version": ..., "mods": [...]}` and the key as `Authorization: Bearer`. `GET /games/<id>/builds/<build>` says how it went, with what `tide` said, and `DELETE` there revokes it. The page is at `/b/<build>/`.
- Provisional: a mod's line is a package from git with its commit, as `tide.packages` writes it, from the hosts `tide` downloads from. What `tide update` follows (`@v1`) is no part of a build's name, a repository listed twice is an error, and a build takes 32 at most. Folders and the packages that come with tide aren't mods. Nothing checks yet that a mod is Tide alone.
- Provisional: the mods' lines go at the end of the game's `tide.packages`; what they need comes from their own lines, as for any package. A mod the game already lists, or two packages of one name, is the error a build of that file gives.
- Provisional: `tide fetch [folder]`, a new command: it downloads the packages from git that the game lists and the machine doesn't have, each at its commit, what they need included, and builds nothing. The service fetches with it, then builds with no network.
- Provisional: what's signed is a manifest, a line of JSON: `{"build", "target", "sha256", "size"}`, the SHA-256 being the page's. It's at `/b/<build>/manifest.json`, its signature (r then s) at `/b/<build>/manifest.sig`, and the game's public key, 65 bytes uncompressed, at `/games/<id>/key`. Nothing checks them yet: a game that loads builds will.
- Provisional: a build that failed is built again when it's asked for again. A revoked one never is: what it built is deleted, and its link answers 410.
- Provisional: a page is fetched again each time it's opened (`Cache-Control: no-cache`, with an `ETag`), so a revoked build is gone from caches too.
- Provisional: the limits. A version is 64 MB at most, and unpacks to 4096 files of 256 MB; a build has 10 minutes, 1 GB of memory and a page of 64 MB; its packages unpack to 512 MB; a game keeps 512 MB of versions and builds; 4 builds run at once.
- Provisional: whoever asks for a build gets all that `tide` said of it. That's the game's own developer for now, as asking takes the game's key; a modder of a closed game will get what it says of the mod's own files.

<a id="open-30"></a>

### Open

Proposed, awaiting the owner. None of it is built, but for the service's first slice (Provisional, above).

The language:

- A mod sees every declaration of the game's, as a package does (see Open, Access control). It declares what a package can, less `extern`. The packages it needs are mods too, or come with tide, or are ones the game lists itself: only those last two can have C.

What a mod's code reaches:

- Files. In a mod's code, `File`, `Directory` and the `Application` paths are that mod's: a persistent folder and a temporary one of its own, inside the game's, and the files its package came with, to read. A path that leaves them fails with `IOError.AccessDenied`. It goes by where the call is written, which the compiler knows. In a build with mods, the game's own code is kept to the game's folders too, by the sandbox, so a function of the game's that a mod calls reaches no further.
- Sessions. A mod's matches are in rooms: besides `Session.Connect`, a port for `Session.Open` isn't a mod's to give.
- `Clipboard.Copy` is on the list because text a player pastes elsewhere is a way out of the game.
- The rest is as it is for any code: devices (the game's window's alone), drawing, the GUI, `Debug`.
- What no rule stops: a mod can hang the game or end it, use its memory, draw anything in its window (a box that asks for a password included), and send what a player does in the game to the match's other players. Revoking builds, and the developer's say over who publishes, answer those.

The game:

- With the `mods` setting, a game runs another build of itself as a library on desktop and a program on the web, loaded as `tide run`'s host loads one, with nothing watched or carried over. It has the game's public key in it.
- A build is named by what it's made from: the game's published version, its mods, each at its commit, and tide's version. The mods are sorted first, so the same set listed in another order is the same build. The platform isn't part of the name: a build's generated C is the same everywhere, so its players share matches across platforms as they do now.
- Local code asks for a build by its mods, written as `tide.packages` writes packages. The game gets it, checks it, and starts it in the running one's place: the match and the local state start over. The command line takes the same. The names are to pick.
- A room says which build its match runs, and a server on an address says it as it refuses a hello. That's what a game about to join is told from. Once local code says yes, it gets the build, starts it, and joins. A join nothing said yes to ends with a reason of its own.
- Host migration and hosted servers need nothing new: every machine has the build, and the service builds a hosted server's with the rest.

The service:

- A developer publishes each version's source to it (`tide publish`, a name to pick): the Tide, the C, the libraries and the packages' commits. It stays private unless the developer says otherwise.
- Modders of an open game have its source. A closed one's declarations are what `tide` and the language server check a mod against. Only the service can build such a mod: `tide run` sends the mod's files as they are and runs what comes back. What a build says of the game is then its declarations, never its code.
- Who publishes mods for a game is the developer's choice, at the service, changed without shipping the game again: anyone, or the mods the developer lists.
- Builds run in machines made for one build, with no network while they compile (packages are fetched before, by commit) and limits on time, memory and what they write.
- A build is made once for each platform, the first time one is asked for, and kept by its name.
- Signatures are ECDSA on P-256 over a SHA-256 of the build's name, its platform and its file. A game checks one with the code it has for WebRTC (`rtc_p256_verify`), a page with the browser's own, every time a build is loaded, not only when it's fetched. The service keeps each game's key.
- Revoking is how a build that turned out harmful stops running on machines that already have it. So before a game loads a build it has, it asks the service whether the build is still allowed. It keeps the answer for a while, a day as proposed, and asks again after that: within that time the build runs with no network, and a build revoked meanwhile may still run. A shorter time stops a bad build sooner, and keeps modded play from starting sooner when a player is offline or the service is down. A revoked build is deleted. The developer revokes, and so do we.
- It's billed to the game: builds, what's kept and what's downloaded.

The sandbox:

- A build with mods runs in a process of its own, which the game starts sandboxed: an AppContainer and a job object on Windows, Landlock and seccomp on Linux, a sandbox profile on macOS. It has its window, the GPU, gamepads, the network, the game's folders, and its builds to read. It has no other file, no other process, and starts no program.
- The network stays open, as rooms need it. So code that got past the language's rules could still reach the network, with nothing of the machine's to send but the game's own files.
- WebAssembly is the sandbox where the platform runs it itself: browsers. On desktop it would mean a runtime in every game, ours to write or someone else's, and mod code slower than the game's, which the first decision rules out.
- Phones: the engine loads a build there as anywhere (see Decided: mods are the same on every platform). Apple's and Google's stores forbid native code downloaded after installing, as far as we know, and iOS itself loads only code that's signed, which is the developer's to deal with. Their own web views may run WebAssembly, so a modded game could also be its web build there.

Mods loaded into a finished game (proposed 2026-11-14 after the owner agreed to the two ways above; nothing below is agreed or built, and none of it was checked against the code generator):

- Where mods come from isn't the engine's: a game hands it a set of mod folders. Steam's Workshop is one source of them, through a wrapper in `packages/steam`, and a game's own folder is another. A lobby or room says which mods its match runs, by a name made of the game's version, the mods' contents sorted, and tide's version.
- A game built to take such mods has, generated for it: a description of its storage (its archetypes and where each component's column is), so a mod's systems can query the game's components; a pointer for each `virtual` declaration, which an override replaces, a replaced system being handed whole runs of rows so its loop still vectorizes; a list of handlers for each event; and its functions that a mod may call, which are never inlined into the mod.
- The runtime keeps a mod's own components, singletons and events inside the match world, described by their size and layout when the mod loads, so snapshots, rollback, hashes and packing cover them. A mod's component on one of the game's entities is in a table beside the game's, by entity. This is a registry of types at run time, for mods' types alone.
- What it costs: a mod's code is slower than the game's (the tables beside, and no inlining across the boundary), and a game built to take mods pays an indirect call for each `virtual` and a check of the list on each send. A game not built for them pays nothing.
- Questions:
  - A combination of the game's components that the game never makes has no archetype to go in, and it's to work (above). Proposed: the runtime makes a table for it when it first appears, described as a mod's own types are, and the game's systems go through such tables after their own. Two things the engine has suggest it fits, read from the notes and not checked in the code: a system's loop is already a function of its rows' columns, shared by archetypes with the same columns (`notes/ecs.md`), so it can be called on a table made later; and sparse components already keep some combinations out of the archetypes. What it would cost a game built to take mods: each system looks at a list of such tables, empty unless a mod made one; a lookup by entity (`Has`, `Get`) has one more case; and those tables' rows are saved, hashed and packed by description, slower than generated code does it. To settle: that the tables a match has are the same on every machine and across rollback.
  - The system's sandbox against Steam: a sandboxed game can't talk to Steam's client, so a process outside the sandbox would have to hold Steamworks for it. Not designed.
  - Compiling a mod reads a stranger's files (the source, images, models, fonts), so it runs inside the sandbox too.
  - Platforms where no compiler can run. An interpreter for a mod's code, against the same boundary, is the candidate: consoles and phones forbid native code downloaded later, and generally allow interpreted code. It would be much slower, and it's the opposite of "nothing is interpreted" (Decided).
  - Weighed and not chosen: shipping the game's code as LLVM bitcode with its declarations, and linking it again with each set of mods on the player's machine. Full speed and one way through the ECS, for a link step each time the mods change.

The order to do the work in, proposed:

1. `virtual` and `override`, across packages. They're useful with no service: expansions, variants, and mods a developer builds in. Built (see Provisional).
2. Memory safety as a tested promise (see Open, at the end).
3. tidec's rules for mods: Tide alone, and files of their own.
4. Games that load signed builds, and the service, with listed mods only.
5. The sandbox, then mods from anyone.

Questions:

- Whether a game can also open every declaration at once, without a `virtual` on each.
- `base()` in an override, to call what it replaced: maybe later.
- Whether scenes and singletons' defaults can be replaced, which is how a mod would change `Main`.
- What else a mod's code can't call, beyond `Session.Connect` and `Clipboard.Copy`.
- How long a build runs offline before the service is asked again.
- Whether a modded game on a phone is its web build in the system's web view.

<a id="audio"></a>

## Audio

Built: clips, one-shots, `Sound`, buses, `audio` effects and sources, device backends and the microphone. The original design below is followed by the per-card implementation picks, which describe the current API. [Audio](https://tide-engine.dev/game/audio.md) has runnable examples.

<a id="decided-36"></a>

### Decided

- **Audio is presentation, never the match.** Like drawing, it reads the world and writes nothing to it: no sound is in a snapshot, a hash, a delta or a world sent to a joiner. Everything here is local code's and the platform layer's, and the simulation never includes an audio header.
- **One-shot sounds come from local handlers of match events.** `local event(Hit hit) HitSound(...)` is heard once under rollback: a sound plays late when a correction brings its event in, and never twice. A `verified` handler plays a sound only once the server confirmed the event.
- **Continuous sounds come from views**, which run every frame and see blended positions: a view says what should be sounding this frame, as it says what should be drawn.
- **Two ways to play**, both wanted: a quick sound that's fired and forgotten (`Audio.Play`), and a sound source a game keeps track of to change its pitch, volume and position as it plays (a `Sound` value in a local field).
- **Procedural audio**: a game modifies sound with code of its own, as Unity's `OnAudioFilterRead` lets it, and can make sound from nothing (a synth) or from a stream (a microphone). It's a declaration of its own, `audio`, compiled to C that runs on the audio thread, with the same shape as code the GPU runs: its parameters say what it reads.
- **Formats:** WAV, Ogg Vorbis, MP3 and native FLAC as build-time Clip sources. Runtime playback uses the engine's WAV and Vorbis decoders; MP3/FLAC are converted into float32 PCM WAV during the build, without adding their decoders to games.
- **Small and fast**: the pack stays as small as the author's files, and what plays is fast to reach at runtime. The pack keeps the file's bytes as they are; short clips are decoded to PCM at load, long ones streamed.
- **Headless runs have audio**: a run with no window mixes as a device would, and what played can be captured beside the frame's picture.
- **The block a filter sees is wrapped**, not a bare `float[512]` a game has to remember the size of: a built-in `Samples` that holds the array and says its size.

Original design sketch. The implemented API below differs; see [Audio](https://tide-engine.dev/game/audio.md) for current code.

```csharp
struct Knobs { float cutoff; }
struct LowpassState { float last; }

audio Lowpass(mut Samples samples, mut LowpassState state, Knobs knobs)
{
    for (var i = 0; i < samples.count; i++)
    {
        state.last += (samples[i] - state.last) * knobs.cutoff;
        samples[i] = state.last;
    }
}

local singleton Engine
{
    Sound hum;
}

[Stage(Layers.World)]
view Engines(Body body, Throttle throttle, mut Engine engine)
{
    engine.hum.clip = engineLoop;
    engine.hum.position = body.position;
    engine.hum.pitch = 0.8 + throttle.amount * 0.6;
    engine.hum.effect = Lowpass;
    engine.hum.knobs = Knobs { cutoff = 0.2 + throttle.amount * 0.5 };
    engine.hum.playing = true;
}

local event(Hit hit) HitSound(Body body)
{
    Audio.Play(hitClip, body.position, 0.8);
}
```

<a id="provisional-37"></a>

### Provisional

The following is the initial proposal, awaiting the owner. Later per-card picks below describe what is built and supersede it where they differ.

- **`Audio.Play(clip[, volume[, pitch]])` and `Audio.Play(clip, position[, volume[, pitch]])`** start a one-shot the mixer then owns: nothing comes back, and nothing can stop it. A `float2` position places it under the 2D listener, a `float3` under the 3D one. It's a call that does something, so it keeps its turn in evaluation order and is refused in match code, as drawing is.
- **`Sound` is a built-in struct**, a value kept in a local field: `clip` (a `Clip`), `position` (a `float3`; a 2D sound is one with `z` 0, under the 2D listener where no 3D camera is set), `volume`, `pitch`, `loop`, `bus`, `playing`, `effect` (an `audio` declaration, or none) and `knobs` (the struct that declaration reads). A view writes it each frame. The mixer keeps a voice for each `Sound` a frame names, told apart as GUI widgets are (by the field and the entity), and fades a voice out over a few milliseconds when a frame stops naming it, so a destroyed entity's sound doesn't hang. `playing = false` stops it the same way; writing `clip` to another clip starts over. A `Sound` has no methods: the fields are the API.
- **The listener** is a frame's setting, with both forms like the draw settings: `Audio.Listener(position, rotation) { ... }` and `Audio.SetListener(...)`, defaulting to the 3D camera, or to the 2D camera's center where none is set. Volume falls off with distance by one curve with a game-set reference distance (`Audio.SetFalloff(near, far)`), and pans by the listener's right.
- **Buses are a game's enum**, `[Bus] enum Bus { Master, Music, Sfx, Voice }`: `Audio.SetVolume(Bus.Music, 0.5)` holds for the frames after until it's set again, and a bus can have an `effect` too (`Audio.SetEffect(Bus.Master, Compress, knobs)`). Every voice goes through its bus and then `Master`. No graph, no sends, no reverb zones in v1.
- **`audio` declarations** run on the audio thread, once a block, for the voice or bus they're set on. Their parameters: the block, `mut Samples`; at most one `mut` struct, the voice's own state, which persists between blocks and nothing else reads or writes (plain fields only, as a frag's); and read-only structs, the knobs, which the frame writes into the `Sound` (or the bus) and the mixer hands the thread with its next block, so the thread reads a copy, never the local world. What's refused is what the GPU refuses, and for the same reason: the `World`, text, lists, maps, grids, allocation, `Debug.Log`, events, tasks, anything that reaches outside; `Math` all works; the functions it calls are checked the same way (`refuse` in the shader writer's checking pass is most of the rule). A declaration given as a `Sound`'s `effect` filters that voice; one set on a bus filters the mix; one given to a `Sound` whose clip is `Clip.none` is a **source**: its block starts as silence and what it leaves is what plays (a synth). One `audio` per voice or bus in v1; chains are functions it calls.
- **`Samples`** is a built-in struct holding one `float[512]`: `samples[i]` (a float, interleaved left then right, with an array's bounds rule: past the end reads zero and writes nothing), `count` (512), `frames` (256), `channels` (2), `rate` (48000), each a constant, and `Frame(i)` as a `float2` with `SetFrame(i, value)`. In generated C it's the array, so a filter's loop vectorizes. If the block ever changes size, every filter still compiles.
- **The mixer is stereo at 48 kHz in blocks of 256 frames**, in floats, on the system's audio thread. A clip is resampled to 48 kHz at load and a mono clip plays as a stereo voice; a device that wants another rate or block size is adapted to behind the mixer, which is a backend's job. Pitch is linear resampling. The frame hands the thread its commands (voices named, knobs, bus volumes, one-shots) through a lock-free queue, double-buffered by frame: the frame never blocks on audio and the thread never waits for a frame.
- **The microphone is a source**: `Clip.Microphone` as a `Sound`'s clip gives the voice the capture device's frames, which its `effect` can filter and its bus plays or mutes (`volume` 0 to only process). Capture starts when a frame first names such a `Sound` and stops when none does. On phones and the web the system asks the player; until they say yes the source is silence. Nothing of it reaches the network in v1: voice chat is a package later, over the data channel.
- **Assets:** `asset Clip shot = "sfx/shot.wav";`, alone or as a glob's `List<Clip>` or `Map<string, Clip>`. Source files accept mono/stereo PCM 8/16/24/32-bit or float32/64 WAV, Ogg Vorbis, MPEG Layer III MP3 and native FLAC with a declared sample count. WAV/Vorbis bytes are retained; MP3/FLAC are validated and converted to float32 PCM WAV at build time, with source rate and channel count preserved. The latter imports are limited to 128 MiB source, 256 MiB decoded PCM and 30 minutes. At load, WAV and Vorbis up to ten seconds are decoded once on the pool's threads at their source rate; longer Vorbis streams during playback. Converted MP3/FLAC is always fully decoded, so Ogg Vorbis is the compact streaming choice for long music. Unsupported formats, codecs, channels and damaged data give a diagnostic at the path. A `Clip` names its declaration's sound; saved files refresh retained values under `tide run`. `Clip.none` plays nothing. No `Clip.length` property is built; clips are local code's.
- **Headless:** a run with no window mixes exactly the blocks a device would ask for at the frame loop's made-up 60th of a second (at 48 kHz a frame is 800 frames of audio, 3.125 blocks of 256: the mixer runs as many whole blocks as the time reached), and `--capture-audio <file.wav>` writes the run's whole mix as 16-bit stereo PCM beside `--capture`'s PNG. Nothing in it is a device's or a clock's, and the mixer is the engine's own float code, so a headless run's audio is the same bytes on every machine, which its pictures can't be. A script line, `300 capture-audio hit.wav`, writes what played since the last such line. Tests compare the mixer's output exactly, on every platform, with no device.
- **Backends**, one mixer against a small `platform/src/audio.h` (a device that asks for stereo frames at a rate, and a capture device that gives them): WASAPI on Windows, CoreAudio on macOS, ALSA loaded at run time on Linux (as OpenGL and X11 are, so games link nothing), AAudio on Android, and on the web an `AudioWorklet` fed from a ring buffer the program fills in shared memory, in `tide.js` as the GPU's objects are. A machine with no device (CI, a server) runs the null backend: the mixer still runs, so `Clip.length` and captures work. Phones and browsers start audio only after a player's gesture, and a phone in the background loses its device: the activity and the page handle both, and nothing in the API says "failed". **Hot reload:** voices live in the platform layer, which outlives the game's library on desktop, so sounds keep playing across a reload; on the web they go with the page's state, as the stats drawer does. An `audio` declaration whose code changed is swapped at the next block.
- **Stats:** the drawer's open list gains one line, voices playing and the mixer's time a block, measured only while it's open.
- **The order to build it in:** the mixer, the null backend and `--capture-audio` with tests; WAV assets and `Audio.Play` from a local handler; `Sound` fields and the listener; buses; `audio` declarations with state and knobs; backends, desktop first, the web second, Android last; Vorbis; the microphone.

Picks made as the mixer was built (2026-10-07, the first card: `tide/audio.h`, `platform/src/mixer.c`, `--capture-audio`; nothing of it is in Tide yet), awaiting the owner too:

- **A frame's audio is a list, as its drawing is** (`tide_audio_frame`): one-shots, the voices named this frame by an id, the listener, a falloff and each bus's volume and effect, with every effect's knobs copied in. The host hands it to the platform once a frame, after the frame drew, and the mixer takes it at its next block: the newest frame wins for what's state (voices, listener, buses), and one-shots go through a queue of their own so none is lost when two frames come between two blocks. The mixer allocates nothing and waits for nothing on its thread.
- **Every frame starts from the defaults**, as draw settings do: a frame that says no listener has it at the origin, its right +x, and one that says no falloff has a spatial sound at its volume within 1 unit and silent past 50. A listener is a position and a rotation; a spatial sound pans by where it is against the listener's right (equal power: a sound in front is heard at 0.707 each side), and falls off as `near / distance`, scaled to reach 0 at `far`. A sound that isn't spatial plays at its volume on both channels.
- **A voice named again goes on; one not named fades out over a block** (256 frames, 5 ms) and is gone, as does one whose `playing` goes false, and `playing` back to true starts its clip over; another clip starts over too. A voice whose clip ended, and doesn't loop, stays silent while it's named. A one-shot can't be stopped and ends with its clip. Volume and pan changes ramp over a block, so a value written each frame doesn't click; a voice's first block starts at its gains, with no ramp in.
- **Limits** (a game's own sounds past them are dropped, counted for the stats): 256 voices and one-shots at once, a new one past that taking the quietest's place; 1,024 one-shots queued between two blocks; 16 buses; an effect's state of a megabyte, 4 KiB of it in the voice itself and anything bigger in memory the mixer makes for the voice while it plays (it was 4 KiB in all until 2026-10-08), and its knobs of 256 bytes (1 KiB until `Effect` values held them: an `audio` declaration's structs are checked against both as the game compiles, below).
- **Effects run on the audio thread in order**: a voice's on its block after its clip is read (so a source with no clip starts from silence), before its volume and pan; a bus's on the bus's mix before the bus's volume; then every bus into the master, and the master out. A voice's effect state starts over when its effect's id changes. A frame's `forget` (a reload) stops every voice at once, with no fade, and drops every effect.
- **A clip is read at its own rate**, mono or stereo, through linear interpolation, at `pitch` times its speed: resampling at load is an optimization for later, not a rule. The cursor is a double, so a long clip doesn't drift.
- **Headless runs** render 800 frames of audio after each frame (48,000 a second over 60), in whole blocks with the remainder carried, so `--capture-audio` is the run's whole mix and a script's `capture-audio` line what played since the last. A sound a frame plays starts at the first whole block not yet rendered when the frame ran, up to a block (5 ms) later than the frame's own start. The WAV is 16-bit stereo PCM, each sample clamped and rounded to the nearest, ties away from zero. `tide_platform_audio` on a window with a device does nothing yet: the backends are a later card.

Picks made as `Clip` assets and `Audio.Play` were built (2026-10-07, the second card), awaiting the owner too:

- **`Clip` is a type beside `Texture`, this machine's.** An asset's (`asset Clip shot = "sfx/shot.wav";`, and a glob's `List<Clip>` or `Map<string, Clip>`, including borrowed collection parameters above), a value in local fields, locals and parameters, and never the match's: the error is the one rendering resources give ("rendering resources belong to this machine, so the match can't use them"), as the rule is the same, though the words name rendering. `Clip.none` is the default. A `Clip` names its declaration's sound, as a `Texture` names its image, so a copy follows `tide run`'s packs, and a name the loaded pack hasn't got plays nothing. No way to make a `Clip` of bytes at runtime yet, and nothing to read of one (no `length`).
- **The pack keeps a WAV as the file is**, decoded by the engine the first time it's played (a memcpy's worth of work for PCM) and kept by what's in the file, so two declarations of one file are one decode, a file edited under `tide run` another beside it, and a voice that plays the old samples keeps them until the game's library is unloaded (`tide_clips_free`, after the host had the mixer forget). Decoding on the pool's threads at load came with Vorbis (the seventh card, below).
- **What a WAV may be:** PCM of 8, 16, 24 or 32 bits or floats of 32 or 64, plain or `WAVE_FORMAT_EXTENSIBLE`, one or two channels, any rate; a sample becomes a float by one division, so a file is the same bits everywhere. The build refuses anything else at the path ("isn't a WAV that decodes").
- **`Audio.Play(clip[, volume[, pitch]])`, `Audio.Play(clip, position[, volume[, pitch]])`** with a `float2` (z 0) or a `float3`, each default 1: three overloads, as `Draw`'s are. Who may call: views, local handlers and the functions they call, which are handed the local state as functions that read `Frame.dt` are (the frame's audio list is in it: `tide_local_audio`, which the host gives before each frame); the match, the input's `Sample`, tasks, methods and GPU code can't, each with its own message, and a function that plays called from the match is the error `Frame.dt`'s is. So `Audio` is an owner like `Draw`, with `Draw`'s rule widened to local handlers, where `Draw` stays a view's.
- **A host that gives no audio list** (a C host of its own) records nothing, and nothing breaks.
- **A hot reload stops every sound**: the old build's clips are its own, so the host has the mixer forget before it unloads the library (`tide_platform_audio_forget`). A pack loaded again (a saved file under `tide run`) stops nothing.

Picks made as `Sound` fields and the listener were built (2026-10-07, the third card), awaiting the owner too:

- **`Sound` is a built-in struct**, `{ Clip clip; float3 position; bool spatial; float volume = 1; float pitch = 1; bool loop; bool playing; }`, in generated C only for a game that names it, as `Depth` is. It's a resource of this machine's, as it holds a `Clip`: local singletons, local components, a match component's `local` fields and structs in those, and never the match's or a list's. `bus`, `effect` and `knobs` join it with their cards.
- **The frame names every `Sound` that plays, itself** (`tide_local_sounds`, at the end of `tide_frame`, after the views and the local commands they queued, so an entity spawned or destroyed in a frame is counted that frame): a view only writes the fields. A voice is named by its field's path (hashed) and, for a row's, the entity's bits, so the same field on the same entity is the same voice frame after frame, and another entity's another voice. A `Sound` that isn't `playing` isn't named, so the mixer fades it out as it fades one whose field is gone; `playing` false then true, or another clip, starts over (the mixer's rule). Nothing of a `Sound`'s state is in the field but what the game wrote: where the clip is up to is the mixer's.
- **The listener and the falloff are `Set` forms alone for now**: `Audio.SetListener(position, rotation)`, `Audio.SetListener(center)` (2D: z 0, facing +z) and `Audio.SetFalloff(near, far)`, each a frame's setting that holds from where it's set to the frame's end, and every frame starts from the defaults. The block forms (`Audio.Listener(...) { }`), and the listener defaulting to the frame's camera, aren't built: the default is the origin.

Picks made as buses and `audio` declarations were built (2026-10-07, the fourth and fifth cards), awaiting the owner too:

- **`[Bus]` on an enum of the game's** names its buses, the first the master, 16 at most, one such enum a game; `Sound.bus` is of that enum (an `int` in a game with none, 0 to 15), and `Audio.SetVolume(bus, volume)` and `Audio.SetEffect(bus, effect)` take it. No block forms yet.
- **An `audio` declaration is a function the audio thread runs** (`audio Name(...)`, a declaration word like `frag`): its first parameter `mut Samples samples`, then at most one `mut` struct of plain fields (its state) and at most one read-only struct of plain fields (its knobs), in either order. `Samples` is a built-in struct of one field, `float[512] values`, so `samples.values[i]` and `samples.values.count` are the block (the wrapper the owner asked for, over a bare `float[512]`): no `Frame(i)`, `frames`, `channels` or `rate` yet. Its body is checked as a function's, and then refused if it, or a function it calls, draws, plays, reaches files, reads `Frame.dt`, reaches the world, calls C, is a task, or makes text, lists, maps, sets or reads grids: the audio thread has no scratch memory and no world. A `Random` is allowed, as plain arithmetic.
- **An effect is a value**, `Effect`, made by calling the declaration with its knobs: `Lowpass(Knobs { cutoff = 0.2 })`, or `Square()` with none. It's a built-in struct of the declaration's id (its name hashed), the knobs' size and 256 bytes of them, which `Sound.effect` keeps and `Audio.SetEffect(bus, effect)` takes; so a game's knobs are 256 bytes at most, and an `Effect` in local state survives a reload as a name (the new build's table of effects resolves it). No way to say "no effect" but `default`. In generated C each declaration has a wrapper of the mixer's signature and an entry in a table by id, which the frame's walk resolves as it names a `Sound`; the Effect's knobs bytes go into the frame's list by copy.
- **A state and its knobs have a size, and a struct past it is an error** (2026-10-08). An `audio` declaration's state struct is 1,048,576 bytes at the most (a megabyte: 2.7 seconds of stereo), and its knobs struct 256, what an `Effect` holds. A struct's bytes are what the generated C has for it, which tidec knows: its fields in order with their padding, a `float` or an `int` 4, a `long` 8, a `bool` or a `byte` 1, an array its elements'. A bigger one is an error at the parameter ("an audio declaration's state is 1048576 bytes at the most, and 'Tail' is 1048580"), with a note that says to make it smaller. A declaration that rolls with `Random`, itself or through a function it calls, keeps its generator after its own state, on the next 8 bytes (Random numbers, above), so its state is 8 bytes less at the most, and the error says so, with where it rolls.
- **A state can be big, for an echo or a reverb** (the owner, 2026-10-08: "i do want echo or reverb to be a future feature so maybe we prepare now", and of the two questions that left: that a long delay line is written as a longer array in the state, and that it's built now. The megabyte, the 4,096 bytes a voice keeps itself and the rules below are Claude's picks). Until then a state was 4,096 bytes, kept in every one of the mixer's 256 voices and 16 buses, which is 1,024 floats, about 10 ms of stereo: no delay line to speak of. What's built:
  - **The mixer makes a big state's memory** (one of more than 4,096 bytes) for a voice or a bus while frames play it, on the frame's thread, and frees it there once the audio thread is done with it: the audio thread allocates nothing, as before. So only the sounds that play through such an effect pay for it. A state of up to 4,096 bytes is in its voice, as it always was.
  - **A frame that doesn't play the voice lets its big state go**, and the next that does starts the effect over, from zeros: a `Sound` whose `playing` goes false, or whose field is gone, or that's given another effect. That's what the game sees of any effect's state. Underneath, a small state's lifetime is its voice's in the mixer, which fades out over a block, and a big one's is by the frames as they were submitted, so where two frames come between two blocks of audio and the first doesn't play the voice, a big state starts over though the mixer never saw the voice stop. A bus's effect is said every frame (`Audio.SetEffect`), and a frame that doesn't say it lets its state go the same way.
  - **A one-shot has no big state**: C that gives one an effect with one plays it without the effect. `Audio.Play` takes no effect in Tide.
  - **An effect that says more state than the most there is plays nothing of its own** (`tide_audio_voice` records no effect for it): for C, as tidec refuses such a declaration.
- **A long array: more than 4,096 elements, in an audio declaration's state alone** (2026-10-08, the owner's pick over a buffer type of its own; the rules are Claude's). `float[96000] line;` is a field of a struct, and such a struct, or one that holds it through structs and arrays, is only ever an `audio` declaration's state. Up to 1,048,576 elements, all of an array's lengths together, as many as a state has bytes. Everywhere else an array holds 4,096 at the most, as it did, with the error it had.
  - **Nothing copies it**, as a copy would be hundreds of kilobytes on the audio thread's stack. A value with a long array in it is read and written where it is: `tail.line[i]`, `tail.line.count`, a field of it, an element of an array of such structs and that element's fields, or the state passed on to a function or a method as a `mut` parameter. Anything else is an error where it's written, which says what to write: a local of it (`var copy = tail;`), an assignment of one (`pair.a = pair.b;`, `tail = default;`, a struct's literal), a `foreach` over a long array (which goes through a copy of its array: go through it by index), `==`, text made of one, an argument a parameter takes by value.
  - **Where such a type can't be written:** a field of anything but a struct (a component's, a singleton's, an event's, the input's), what a list, a map, a set, a grid or a `T?` holds, a local, a constant, a parameter that isn't `mut` (an `out` one, an operator's, a frag's or a vert's, an `extern` function's, an async function's, an audio declaration's knobs), and what a function returns. Such a struct has no methods, as `this` is a copy: a function takes it `mut`.
  - **An element of an array of such structs isn't passed on as `mut`** (`Sum(hall.sides[0])`), by the rule arrays' elements already had: the function takes what holds the array, and which element.
  - **A struct's field defaults count for nothing in a state**, long or not: a state starts as zeros.
  - Not built: a way to say how long a state's array is as the game runs; a `Sound`'s share sent to another bus (what lets one reverb on a bus serve many sounds, each at its own amount); a state a game reads back from a view.
- **The named gating** that keeps other games' C as it was covers `Sound`, `Samples` and `Effect` (the structs, their blend helpers, the layout) and the arrays only their fields made (`float[512]`, `byte[256]`: their types and helpers), which are numbered after the game's own arrays so those keep their names.

Picks made as the backends were built (2026-10-07, the sixth card), awaiting the owner too:

- **One pull for every device** (`platform/src/audio_out.c`): the mixer's stereo at 48 kHz, read out at the device's rate by linear interpolation between two of the mixer's frames (so a device at 48 kHz hears each frame a frame late, and other rates a little blurred: a proper resampler is for later), a mono device given the average and more channels the two and silence. Each backend fills its device from it on the device's thread: WASAPI (shared mode, event driven, at the device's mix format, floats or 16-bit integers), CoreAudio (the default output unit, given stereo floats at 48 kHz to convert itself), ALSA (`libasound.so.2` at run time, `default`, stereo floats at 48 kHz with ALSA's own resampling, 50 ms, a thread of ours writing a block at a time), AAudio (floats, a data callback). The device opens with the window and closes with it; a run with no window opens none.
- **The web's device is the page's** (`platform/web/audio.c`, `tide.js`): an AudioContext and an AudioWorklet of our own, which plays stereo chunks the main thread posts it; the page asks the program to render (`tide_web_audio_render`, up to 4096 frames) from its frame and from a 20 ms timer, enough to keep about 90 ms queued by the context's clock, as the program's mixer has no thread of its own in a page. So the web is about 90 ms behind the frame, where a desktop is a device buffer (10 ms) behind. The context resumes at the page's first pointer, key or touch, which browsers want; a page starved of chunks (one that was away) starts again from where the clock is, with nothing to catch up. Nothing is shared with the worklet, isolated page or not, as a copy a chunk is small.
- **A forget waits for the device's thread** (`tide_mixer_forget`, `tide_mixer_rendered_elsewhere`): a reload stops every voice once that thread has taken the forget at its next block, or after half a second, for a device that stalled.
- **Not run here**: CoreAudio (no Mac, and CI has none for now), AAudio (built under the NDK, no device), ALSA on a machine with a device (WSL has none). WASAPI is run by `tide_platform_audio_device` on this machine, and the web's by the page tests, which open the context in headless Chrome without a gesture, suspended.

Picks made as Ogg Vorbis was built (2026-10-07, the seventh card), awaiting the owner too:

- **The decoder is `tide/vorbis.h`** (`engine/src/vorbis.c`), from the Vorbis I specification and RFC 3533, in floats, with a sine of its own for its windows and twiddles (the engine's math is floats, and tidec compiles the decoder for the build's check without the math library): the same samples on every machine. It's held against ffmpeg's decodes of three files its encoder wrote (`tests/audio`), to within 3e-5 of a sample. The whole file is read as pages first (every checksum checked) and its packets copied out, so the bytes it was opened from can go; headers are parsed at open and nothing of the audio is decoded then, which is what the build's check does to a file.
- **Floor type 0 is refused** ("a floor of type 0, which this decoder doesn't read"): no encoder has written one in twenty years, and untested code is worse than a clear refusal. Files of more than two channels are refused as WAVs are: the mixer plays mono and stereo.
- **What a file holds is its last page's granule position**, and the reader never gives more: a file whose encoder padded nothing after its last block ends a part of a block short of it (ffmpeg's own encoder does: its decoder then gives 128 frames fewer than the granule, and for another file 160 more; the reader gives the granule). A packet cut short or corrupt decodes as the specification has it (silence for one that ends in its floors, what was decoded for one that ends in its residues), and the file goes on.
- **Ten seconds is the line between decoding whole and streaming** (`tide_clips_whole_seconds`, a variable so tests move it), by the granule and the rate: under it a clip is decoded whole as a WAV is, over it the `tide_clip` carries the opened file (`stream`) and no samples, and a voice that plays it holds a `tide_vorbis_reader` (made at its first block, on the audio thread, about `tide_vorbis_reader_size` bytes: 300 KB for stereo at the biggest block size), reading two frames at a time through the same interpolation a decoded clip's samples go through, so pitch and the clip's own rate work alike; a loop rewinds the reader at the end. A WAV is never streamed: its decode is a copy.
- **Clips are decoded as the pack loads** (`tide_clips_prepare`, which the standard host calls after `tide_assets_load` and after each pack `tide run` writes, with the platform's pool), each file once, on the pool's threads where there's more than one clip to do; `tide_clip_of` still decodes a clip nothing prepared, at its first play. `tide_pack_clips_each` is how the engine lists a pack's clips.
- **What a reader costs** is Vorbis's: the three reference files (1.3 seconds of audio) decode in 2 ms in a release build (6 in a debug one), about six hundred times real time a core, so a game's library of effects is ready in milliseconds, behind the web's wait for its GPU device. A streamed voice's block (256 frames) is a fraction of a Vorbis block, so the audio thread decodes a Vorbis block every few of its own.
- **Seeking a streamed clip isn't built**: a `Sound` whose `time` would move it can't yet, and a stream starts over when the frame starts its Sound over. Nor are a Vorbis clip's bytes at runtime, chained Ogg streams (the first logical stream is read, and the rest ignored), or an Ogg that starts at another granule than 0.

Picks made as the microphone was built (2026-10-07, the eighth card), awaiting the owner too:

- **`Clip.Microphone` and `Clip.none` are members of `Clip`** (the built-in members' table, so editors list and explain them). `Clip.none` had been documented and never built; it's `default`. The microphone's clip names nothing of the pack's: a `tide_clip` that says `microphone`, mono at the mixer's rate, with no samples.
- **The frame says it** (`tide_audio_frame.microphone`, set by a voice whose clip is the microphone and is playing), **and the platform opens the device while frames do** (`tide_platform_audio`), closing it when none does, and trying again every second while it couldn't be opened: a player still being asked, a device that isn't there yet. Nothing asks until a game names such a `Sound` playing, so a game that never does never prompts anyone.
- **What's captured goes through one path** (`platform/src/audio_in.c`): the device's frames, whatever their channels (averaged to one) and rate (linear interpolation to the mixer's, each device frame emitted as it came and one frame late), into the mixer's ring (`tide_mixer_capture`, 16384 frames). The renderer takes a block from the ring as each block begins, once it holds four blocks (21 ms: a device delivers in bursts), plays silence and waits for a prime again when it runs dry, and skips to the newest frames, a prime back, when it's more than eight blocks behind (a device that ran on while nothing rendered). Every microphone voice plays that block, in both channels, whatever its pitch: the device sets the pace. A forget empties the ring.
- **A one-shot of the microphone records nothing**: `Audio.Play(Clip.Microphone)` is silent, as a one-shot has no end a device would give it.
- **The backends:** WASAPI's default capture endpoint on a thread of ours (floats or 16-bit integers, a silent packet as zeros); an `AudioQueue` input of mono floats at 48 kHz on macOS; ALSA's capture stream, mono floats at 48 kHz, read on a thread of ours; AAudio's input stream on Android, after `RECORD_AUDIO`, which the app's manifest names only for a game that says `Clip.Microphone` (`game_info.microphone`, from tidec's `uses_microphone`) and the app asks for (`requestPermissions`, through JNI) the first time it wants the device, then polls as the platform tries again; `getUserMedia` on the web, into the context the output plays in, through a worklet that posts what it hears to the page and the page to the program (`tide_web_audio_captured`), silence until the player allows it and the context runs.
- **A run with no window plays a file into it**: `--microphone <file>` (`tide_headless_desc.microphone`, a WAV or Ogg Vorbis, read before anything runs and refused with exit code 2 when it can't be), looped, a 60th of a second of it a frame through the same path a device's frames take, so a test hears it where a player would be heard; without it the microphone is silent.
- **Capture validation:** `tide_platform_audio_device` opens and closes this machine's WASAPI capture (nothing checks what it hears: a muted one hears silence). A headless Chrome check with its fake microphone ran `getUserMedia`, the input worklet and the WebAssembly capture bridge through the resampler and mixer: nonzero samples reached a muted voice's effect, output stayed silent, and closing capture ended the stream's tracks. Six Node checks cover delayed permission and worklet answers after close/reopen, queued messages, sample delivery and the input processor. **Not run here:** CoreAudio, ALSA with a device, AAudio, and the browser's physical microphone or permission prompts. **Not built:** choosing a device, stereo capture, echo cancellation or gain control as choices (the web's `getUserMedia` has the browser's defaults), Android's permission result as a callback (the platform polls), a macOS bundle with its usage text, voice chat.

<a id="optional-voice-package-2026-10-22"></a>

### Optional voice package (2026-10-22)

**Decided:** working voice chat through sessions is an optional package using Opus and the existing microphone. Games without the package do not compile/link its codec or allocate its buffers. Voice is local presentation, outside ticks, commands, rollback, snapshots and deterministic hashes.

**Decided (2026-10-22):** the optional voice package also supports RNNoise microphone noise suppression, controlled by the local `VoiceClient.noiseSuppression` setting, defaulting to true.

**Implemented provisional choices:** `voice` / namespace `Voice`, local `VoiceClient.enabled`, `transmitting` and `volume`, `ConfigureVoice` ordering, and `SetVolume(PlayerID, float)`. Both flags default false; microphone capture requires transmission in a connected session. The host relays unreliable packets to other subscribed players. Global chat, 48 kHz mono, 20 ms frames, 24 kbit/s, 40 ms initial receive buffering, Opus DTX/FEC/concealment, 32 receive slots and 32 player gains are first-build choices. C hosts use the optional `tide_voice_provider` and local-data session API; no language builtin or generated runtime call is added. [Voice chat](https://tide-engine.dev/packages/voice.md) documents use and limits. Teams, proximity routing and positional voice remain unbuilt; in Unity, voice plays through Unity's audio (2026-10-22).

The older microphone implementation notes above describe the pre-package state; voice chat is no longer deferred.

**Implemented provisional suppression choices:** suppression filters only outgoing capture. RNNoise 0.2's smaller built-in model runs on the frame thread in 480-sample blocks before Opus; its history resets on transmission start and setting changes. State is lazy and retained until client teardown; off means no filter work. The model ships with the optional voice package; games without it compile/link neither RNNoise nor Opus. No engine, simulation or wire-format change is needed.

**Decided (2026-10-22):** game code can process received voice with custom audio effects and dynamic parameters, including radio effects.

**Implemented provisional processing choices:** `VoiceClient.bus` is a local integer receive bus, default 0 (master). `Voice.SetBus(PlayerID, int)` overrides one speaker; negative removes the override, and other out-of-range buses fall back to master. Routes apply to existing playback without restarting codecs. At most 32 player routing overrides persist independently of volume overrides until changed or the local connection/match changes, with initial setup preserving them. The default bus persists across reconnects. Voice uses the existing 16 mixer buses: speakers on one bus are mixed before its ordinary `Audio.SetEffect`, sharing its effect state and live knobs. Processing affects only this receiver's playback, with no compiler, mixer, simulation or packet change.

<a id="open-31"></a>

### Open

- Effects a game can't write itself: a reverb, which needs more state than a struct of plain fields (a `float[N]` delay line fits once arrays are in `audio` state structs, which is the first thing to try), and sends to a shared reverb bus.
- A chain of `audio` declarations on one voice (`List<Effect>`), where v1 has one.
- 3D audio beyond panning and distance: HRTF, occlusion, doppler (`pitch` by hand does the last).
- Streaming a clip from a URL or a file at runtime (`Web.Fetch` gives the bytes; a `Clip` made of bytes is the missing piece), and recording to a file.
- Sample-accurate scheduling (a sound that starts at a tick's exact time, music synced to the match's beat): `Audio.Play` starts at the next block.
- Whether the simulation should ever hear audio (a rhythm game's match reading the music's position): today it reads `Time.t` and the view keeps the music to it.

<a id="conditional-compilation"></a>

## Conditional compilation

<a id="decided-37"></a>

### Decided

- Code can adapt to the version of tide it builds with, as C# code adapts to Unity's with `#if UNITY_2022_3_OR_NEWER`: tide gives the tools, and packages adapt to the versions they support.

```csharp
#if TIDE_0_4_OR_NEWER
const int SLOTS = 8;
#else
const int SLOTS = 4;
#endif
```

<a id="provisional-38"></a>

### Provisional

Implemented, awaiting approval:

- C#'s directives: `#if`, `#elif`, `#else` and `#endif`, each on a line of its own (spaces before it are fine, and a `//` comment after it), nesting. Conditions take symbols, `true`, `false`, `!`, `&&`, `||`, `==`, `!=` and parentheses.
- Tide's versions are symbols: `TIDE_0_4_OR_NEWER` is true in tide 0.4 and after, `TIDE_0_4_2_OR_NEWER` in 0.4.2 and after. Only a version's numbers count: a pre-release (0.4.0-nightly.3) is the version it comes before. Any other symbol that starts with `TIDE_` is an error, so a misspelled version doesn't quietly leave code out.
- Lines a directive leaves out aren't read, only looked through for the directives that end them, as in C#: they can hold anything, like code with syntax a newer tide reads. A directive inside a `/* */` comment in code that's read is part of the comment.
- Editors show the lines left out as comments, fold each branch, and the formatter leaves directives and those lines as they are.

Symbols beyond tide's versions (the owner, 2026-10-07: `#if` with no `#define` isn't much, symbols from the command line, `#if DEBUG`, and knowing whether a package is installed; everything below is Claude's pick of how):

- To `#if`, a symbol is defined or not, as in C#: a value a build gives it (below) changes nothing there. One that nothing defines is false, and no error: `#if STEAM` has to compile in the build that doesn't define it.
- `#define NAME` and `#undef NAME` are C#'s: for the file they're in, and before its first token, as they're for all of it; after code they're an error. `#undef` takes away a build's symbol too, in that file. A line in a branch that's left out isn't read.
- `--define NAME` on `tide run`, `build`, `schedule` and `shaders` (and tidec, and a line of its `@list`; `DEFINES` in `tide_add_game`, whose `<target>_schedule` reads them too) defines a symbol for every file of the game and its packages, and `--define NAME=value` defines it with a value (below). No `-D` spelling. Whether a setting or a `tide.packages` line should list them is Open (below).
- `DEBUG` is defined in `tide`'s default debug mode, and undefined with `--release` or `--distribution` (in this repo's CMake builds: in the Debug configuration). A command line's own `--define DEBUG=value` (or `DEFINES DEBUG=value`) is kept, value and all, in place of the debug mode's. Nothing else is predefined: no `RELEASE`, no symbols for `--web` or `--android`, and none for platforms, as a game is one code for all of them.
- `PACKAGE_<NAME>` is defined for each package the game builds with: its name (the `package Name` of its `tide.packages`, its namespace) in capitals, anything that's no letter or digit as `_`. No versions of packages.
- `TIDE_` and `PACKAGE_` names, `true` and `false` can't be defined, by a file or a command line.
- **The build's symbols that conditions read are part of the game's identity.** Each one a condition reads (not a file's own, not tide's versions) is listed in the generated header with whether it's defined, so it's in the game's hash: a debug and a release build of a game that says `#if DEBUG`, or builds with other `--define`s that the game reads, are different games and join none of each other's matches, where they'd otherwise connect and correct each other every tick. A game that reads none has the header it had. The alternative that was weighed: refusing those symbols in match code, which a lexer can't tell.
- Editors read `DEBUG` as defined and know the game's packages; what a command line defines they don't, and read as not defined.

Symbols read by code, with values (built 2026-11-14; the owner approved "a define with a value, readable as an expression", "go with your recommendations", and each rule below is Claude's pick):

```csharp
const bool PREPASS = !defined(NO_PREPASS);
const int ARMY_SIDE = define(ARMY_SIDE, 500); // tide run --define ARMY_SIDE=1000
```

- **`defined(NAME)`** is a constant `bool`: whether `#if NAME` would be true in that file (its own `#define` and `#undef` first, then the build's symbols, tide's versions too). A `TIDE_` name that's no version is the error it is in `#if`.
- **`define(NAME, default)`** is a constant: the value the build's `--define NAME=value` gave, or `default`, a constant, when the build gives NAME none. The spelling pairs with `defined`: `define` reads the value a define gave. Its type is the type of where it goes, when the default converts to that as an ordinary value would (`type_assignable`): `define(SCALE, 1)` in a `float` reads a float, `define(MANY, 5)` in a `long` a long. Where it goes is a `const`, a field, a local, a parameter, an assignment, a `return` (what `check_expr_want_any` is given), or a part of a vector, a color or a quaternion (`float3(define(X, 0), 0, 0)`, `check_construct`). Anywhere else (arithmetic, `?:`, `Math`) the type is the default's, and a decimal value where that's an int is an error whose note says to write the default as a float, `define(S, 1.0)` (or as a long, `5L`, for a bigger whole number). A default that doesn't convert to where it goes keeps its own type, so where it goes refuses it as it refuses the default without the `define`, in every build (`const int N = define(N, 1.5)` is "constant 'N' is int, not float" whatever the build gives; an int default that fits no byte, where a byte goes, stays the default). The type is `bool` (`true` or `false`), `byte`, `int` or `long` (decimal digits, with `-` before a negative one, fitting the type; no hex, no `_`), `float` or `double` (decimal, `2.5`, `-1e3`, finite in the type and not rounding to zero there unless it's zero, so C takes the literal), `string` (the text as it is: UTF-8, with no control characters but tabs and line breaks), or an enum (a member's name, as written, an alias's too). Anything else, a vector say, is an error that says to read its parts, each a define. A value that isn't one is an error at the `define`, naming the symbol, the value and the type, with a note that shows a value that would be (`--define ARMY_SIDE=500`).
- **A symbol defined with no value** (`--define FAST`, `DEBUG`, or a file's `#define FAST`, which never has one) reads as `true` where the type is `bool`, and is an error anywhere else, whose note fits where the symbol came from: the build's says to give it a value or read it with `defined`; a file's own `#define` (which is over the build's in that file) says to take it away or write a `const`. Tide's versions and the packages' `PACKAGE_` symbols never have a value, so `define` of one is an error in every build, whose note says to read it with `defined`. A symbol defined with an empty value (`--define TITLE=`) has the empty value.
- **The call becomes the literal it reads as** while checking (`check_symbol_call`), so it goes anywhere a constant does: a `const`, a field's default, an array's size, a `switch` case, a GPU function (`compiler/tests/shaders/defines.tide`), a function's body. No type, function or constant is called `defined` or `define` (`is_builtin_name`), and editors don't rename to them; a method, a parameter, a callable field or a local `Func` of the name is called instead where it's in scope, as one called `Spawn` or `GPUList` is.
- **`#if` never reads a value.** `#if SIDE == 3` (a number, text or a `-` after `==` or `!=`), `#if SIDE > 3` (`<`, `>`, `<=`, `>=` and a single `=` after a condition), and `==` or `!=` beside a symbol the build gave a value (`#if START == Hard` with `--define START=Hard`, which would otherwise compare two symbols' being defined) are errors that say to compare the constant in code or define a symbol for each choice; `#if defined(SIDE)`, C's spelling and code's, is an error that says to write `#if SIDE`. `==` and `!=` between symbols with no value compare whether each is defined, as before. `tide.packages` conditions say the same.
- **Command lines.** `--define NAME=value` splits at the first `=`, so a value can hold `=`; the name is what `--define NAME` takes, and `NAME=` is an empty value. A name given twice takes the later value: the lexer's last word stands, and `tide` passes the C compiler that one `-D`. Handwritten game and package C gets `-D NAME=value` as clang reads it (the value as C tokens, not a string, so text with an unmatched quote or an apostrophe, `Don't`, is a clang warning in every C file); a symbol with no value is 1 there, as before. `tide.packages` `#if` lines read a symbol with a value as defined.
- **Identity.** Every build symbol a condition or code reads is in the generated header's comment with what it was, `NAME=0`, `NAME=1` or, with a value, `NAME="value"` (quotes and backslashes escaped, bytes outside printable ASCII and `?` as `\xNN`), so it's in the game's hash: builds that read different values are different games, as builds that read a symbol differently are. A game that reads no valued symbol has the header it had. The generation cache's key and custom C's identity already held each `--define` as written, value and all.
- Editors know no command line, so `define(NAME, default)` reads as its default there, and `defined(NAME)` as `#if` reads NAME. They offer both in completion, with signature help.

<a id="open-32"></a>

### Open

- A file's `#define NAME value`: a file's symbols have no value, and a value in a file is a `const`.
- `#if` reading values (`#if SIDE == 3`), which is refused.
- Whether `==` and `!=` in `#if` should take only `true` and `false` beside a symbol, refusing two symbols compared (`#if START == Hard` with no value given is "both undefined", so true): C#'s rule compares their being defined, as Tide does, and only a symbol given a value is refused.
- `char` and vector values: a vector is read as its parts, each a define.
- A setting or a `tide.packages` line that lists a game's defines, so editors and plain `tide run` know them.
- A text value outside ASCII on Windows: `tide` and tidec read a narrow command line, in the console's code page, so such a value is refused as not UTF-8 (the note says so on Windows). Reading the wide command line would fix it.

<a id="open-33"></a>

## Open

- Archetype derivation for additional authored forms beyond the current checked prefab composition.
- Archetype growth past what reachability trims: an `Add` or `Remove` on an entity read from a field or a parameter still reaches every archetype of its world, so a game that toggles many components on arbitrary entities multiplies combinations. Sparse components (a presence bit in the row instead of an archetype of their own) are the way out; see Entities.
- How modules, such as the engine's built-in systems, initialize when there's a single `Main`.
- Access control: whether a namespace can keep declarations to itself.
- Memory safety as a promise: that no Tide code, however wrong, can corrupt memory or reach outside its world. Mods rest on it (see Mods), and so does a player who takes a world from a host they don't know. Where it stands (2026-10-05):
  - **Tested, for what Tide alone can say.** `compiler/tests/safety/` is games that try each way in: an index anywhere in a list, a grid, a map or text, sizes nothing can have, handles to entities that are gone or never were, ints and floats at their limits, loops whose places are at the ints' edge, a sort whose comparison lies, events and tasks in their thousands, and drawing and widgets given NaN, infinities and indices past what they index. Each ends in a defined way, with what it gave pinned, under AddressSanitizer and UndefinedBehaviorSanitizer on every push (the `sanitize` preset). What they found is fixed, and what's left is below.
  - **What a stack that runs out does is open, and the owner's.** Tide has no limit on how deep calls go, and generated code doesn't check. Today a function that calls itself with no end stops the program as the system stops one whose stack ran out: a crash, with no message of the engine's, or, where the C compiler turned the recursion into a loop, a program that never ends. It's a crash and not something worse on Windows (which checks big frames), on Linux and Android (games are compiled so that a function with locals bigger than a page touches each page), and on the web's own thread (which stops at memory's edge). macOS wasn't checked. It's not known to be one on the web's other threads, whose stacks are memory like any other with nothing beside them to stop at: a deep enough call there writes over what's next to its stack. The choices:
    1. Leave it: a crash where the platform gives one. Nothing to build, and the web's threads stay as they are.
    2. A stop with a message, as an endless chain of events has: generated code checks how much stack is left where a function can call itself (a comparison a call, in those functions alone), and stops naming the function. The same on every platform, the web's threads included, and the only one of the three that closes them.
    3. A limit on depth instead (a count, say 10,000 calls deep): simpler to say, but a count isn't a size, so big locals still run out before it, and it would need 2's check as well.
  - **Bytes from another machine** aren't tested as hostile: a world, a delta or an input a server or a player made up. Sessions check what they read (sizes, counts, a world's hash), and a fuzzer covers the WebRTC stack, but nothing yet feeds a session's own messages broken at random.
  - **A game's C is trusted**, as ever: the promise is about Tide code.
  - **Still to do: programs made at random.** The tests are the ways in someone thought of. A generator of valid Tide programs, run the same way, is what finds the rest.
