# Ownership

> Let players write the values they control, such as a cursor or a dragged card, while the room decides what everyone sees.

Every entity has an **owner**: the room, or a player. The room owns
everything unless it gives an entity to a player, and the owner of an
entity may write the fields its kind declares **writable** straight from
the client, with no round trip. The room still checks each write and
always has the last word.

Use ownership for values a player sets directly: a cursor, aim, a camera,
a piece being dragged, per-player settings. Movement the room simulates
stays room-owned and goes through [prediction](/docs/client/prediction).
Scores, hit results and anything else that decides the game stay
room-owned too.

## Declaring writable fields

```ts
// schema.ts
import { defineSchema, entity } from "@irtio/room";

export const Cursor = entity("cursor", {
  x: "f32",
  y: "f32",
  color: "u8",
}, { writable: ["x", "y"], onOwnerLeave: "delete" });

export const Settings = entity("settings", { volume: "u8", coins: "u32" }, { writable: ["volume"] });

export const schema = defineSchema({ private: Settings, entities: [Cursor] });
```

- Only the listed fields can be written by the owner. The rest are the
  room's, even on an entity a player owns, so `color` above is set by the
  room alone.
- Any kind that isn't [hidden](/docs/room/state-sync#hidden-entities)
  can be given to a player, with or without writable fields. The owner
  of a kind with none can't write it, but the entity is always in its
  view, it's listed by `ownedBy` and `mine`, and its owner-only fields
  reach it.
- `ownerOnly` lists fields only the owner's connections are sent; every
  other connection holds their defaults and gets no changes to them. A
  predicted car's velocity, which only its driver's replay reads, is one:
  `entity("car", { x: "f32", y: "f32", vx: "f32", vy: "f32" }, { ownerOnly: ["vx", "vy"] })`.
  A new owner gets them right after the ownership change; the previous
  owner keeps the values it had. They save bandwidth, and hide only
  values a player never owned. Room state saves them as any field, and
  they're part of the schema hash.
- The shared state, `room.state`, is always the room's and can't have
  writable fields.
- A player owns its own private state, so it can write the private kind's
  writable fields.
- Writable fields are part of the schema hash: a client built with
  different writable fields fails to connect with 4004.

## In the room

```ts
// room.ts
import { defineRoom } from "@irtio/room";
import { Cursor, schema } from "./schema.js";

export default defineRoom({
  schema,
  onJoin(room, conn) {
    if ([...room.entities.ownedBy(conn.player, Cursor)].length > 0) return;
    room.entities.create(Cursor, { color: conn.player.length % 8 }, { owner: conn.player });
  },
  writes: {
    cursor(room, conn, cursor, write) {
      if (write.x === undefined) return write;
      return { ...write, x: Math.min(Math.max(write.x, 0), 800) };
    },
  },
});
```

- `create(kind, values, { owner })` gives a new entity to a player.
  `room.entities.setOwner(entity, player)` moves one, and
  `setOwner(entity, undefined)` gives it back to the room.
  `ownerOf(entity)` returns the player, or `undefined` for the room, and
  `ownedBy(player, kind)` iterates what a player owns.
- Owners are player IDs, not connections. Ownership survives reconnects
  and is saved in room state, so it survives hibernation. When the
  owner's presence ends, the kind's `onOwnerLeave` decides what happens
  to the entity; see below.
- The room may write any field of any entity, including fields a player
  owns.

### When the owner leaves

`onOwnerLeave` on the kind says what happens to an entity when its
owner's [presence](/docs/room/presence) ends:

| `onOwnerLeave` | The entity |
|---|---|
| `"room"` (the default) | goes back to the room |
| `"delete"` | is deleted |
| `"leader"` | goes to the leader, or the room without one; [native rooms](/docs/guides/concepts) only |

A player's presence ends at once after its client's `room.close()`, or 10
seconds (`PRESENCE_GRACE`) after a dropped connection that doesn't come
back. `onPlayerLeave` runs first, while the player still owns
everything, so it can give an entity to someone else or delete it; the
rule then applies to whatever the player still owns. An async
`onPlayerLeave` gets as far as its first `await` before the rule
applies.

A hibernation doesn't apply the rule: owners keep what they own, and
`onJoin` finds it again, by `ownedBy` or by
[key](/docs/room/state-sync#entity-ids-and-lookups). After the room wakes, the
rule applies to every owner who hasn't rejoined within the presence
grace.

`onOwnerLeave` isn't part of the schema hash, so changing it needs no
client update. A room with room code refuses `"leader"`, since only
native rooms have a leader.

### writes

`writes` maps a kind's name to its handler,
`(room, connection, entity, write)`, which runs for each owner write to
an entity of that kind at the start of the tick, before the stepper.
When the writer's connection sends a message or call, or closes, before
that tick, its writes are applied first, so `onMessage`, the call's
handler and `onLeave` see them; another player's writes still wait for
the tick. A room
[without ticks](/docs/room/sdk#with-or-without-ticks) runs it
for each write as it arrives, and sends the result in the state update
that follows. A room going to
[sleep](/docs/room/sdk#sleeping-rooms) applies the writes it
holds first. `entity` is typed as that kind's entity, and `write` holds
the fields written, typed as the kind's writable fields. Return:

| Return | Applies |
|---|---|
| `write` | the write as sent |
| other values | those values, such as `write` clamped to the board; any field of the kind |
| `undefined` | nothing; the write is rejected |

- Keys are the names of the private kind and of entity kinds with
  writable fields; any other key is a type error, and `defineRoom`
  throws on one.
- A handler must be synchronous. If it throws, the error is logged and
  the write is rejected.
- A kind without a handler applies writes as sent: a writable field is
  then a claim the room accepts from the player.

Before a handler runs, the room drops writes to entities the player
doesn't own, to fields that aren't writable, and values of the wrong
type.

## On the client

```ts
// client.ts
import { connect } from "@irtio/client";
import { Cursor, schema } from "./schema.js";

const room = await connect("board-1", { schema });

addEventListener("pointermove", (e) => {
  for (const cursor of room.entities.mine(Cursor)) {
    cursor.x = e.clientX;
    cursor.y = e.clientY;
  }
});

room.private.volume = 5;

room.entities.onCorrect(Cursor, (cursor, fields) => console.log("the room moved", cursor.id, fields));
room.entities.onOwner(Cursor, (cursor) => console.log(cursor.id, "is now", room.entities.ownerOf(cursor) ?? "the room's"));
```

- `room.entities.mine(kind)` iterates the entities of a kind the local
  player owns. Setting a writable field changes the client's copy at
  once; writing any other field, or an entity the player doesn't own,
  throws a `TypeError`.
- The client sends its writes at most once per room tick; until then
  the last write to a field wins. In a room without ticks it sends them
  at the end of the task that made them, and during a burst, such as a
  drag, at most once per 16 ms. It also sends them before each call
  and `send` and before `close()`, so the room has them first: a handler
  sees what the player wrote just before calling. `room.flush()` sends
  unsent writes at once.
- An unreliable message is the exception. Writes travel reliably, so
  over a real connection an unreliable message can arrive ahead of the
  writes made before it, and `onMessage` then runs without them.
- Clients can't create or delete entities, or change an owner. Send the
  room a message and let it decide.

## Corrections

The room wins. A client keeps its own values for the writable fields it
owns and ignores the room's ordinary changes to them. When the room's
value differs from what the owner wrote, because its write handler
clamped or rejected it or room code wrote the field, the owner gets a
**correction** with the room's value:

- It overwrites the client's copy and drops the client's unsent writes to
  those fields.
- `onChange` runs for the fields, then `onCorrect`, where a game can snap
  or smooth.
- Every other client only ever sees the room's value.

A correction arrives with the rest of its state update. On a
reconnect or a change of generation, unsent writes are dropped and the
full state update brings the room's values.

## Interest

A player always sees the entities it owns, whatever the room's interest
says. They count toward the cap on entities a connection sees.

## Common mistakes

- **Making fields the stepper writes writable.** The room overwrites the
  owner's value every tick and sends a correction each time. Keep
  simulated movement room-owned and use prediction.
- **Trusting writable fields without a write handler.** A modified client can
  write any value of the field's type. Bound what's possible, such as a
  speed or the board's edges.
- **Writing in `onEnter` before the owner op arrives.** An entity given
  to a player mid-game becomes writable when its owner change is applied;
  use `onOwner` or `mine` rather than assuming.
