Views and visibility
A view decides what clients are told about your data, and a few options decide which clients are told about which rows. This page explains both, option by option.
What a view is
Your components are the server's private truth. Clients never read them. What clients see is a view: a read-only table with one row per entity, that the registry rebuilds from components at the end of every tick. A client is sent that table, and only the parts of it that it should have.
meadow's walkers are the first example. Each player has a Walker component; the world turns it into a view, so that players near each other can see each other:
void onStart() override { view<Walker>().spatial("x", "y"); // the view of Walker: seen by players nearby }
On the client the same struct opens the same view:
auto walkers = session.view<Walker>(); // the view called "Walker" walkers.each([&](ecs::Entity e, const Walker& now) { draw(e, now.x, now.y); });
Notice that the server wrote nothing about how a row travels. It only said "this struct is a view" and, with .spatial, "show it by distance". Aether does the rest: it works out what changed, who is near whom, and what each client already has.
There are two separate questions, and the options of this page answer one or the other:
- What is in a row, and how does it travel? Which fields, which of them travel as small changes, how much history to keep, how often to send. See Fields that change and Tuning.
- Who sees which rows? Near the player, everyone, only the owner, or only chosen players. See Visibility.
Defining a view
On a server::Game you define a view in onStart() with view<Row>(name). Row is a flat struct (data page); the view has one row per entity that has that component, and the row has the struct's members, in declaration order.
void onStart() override { view<Walker>().spatial("x", "y"); // the view "Walker" view<meadow::Sheep>("flock").spatial("position"); // the view "flock", from the Sheep component view<Purse>().ownerOnly(); // the view "Purse" }
view<Row>() returns a builder (ecs::ViewBuilder&) and every option below is a call on it, so options chain: view<Walker>().spatial("x", "y").every(2).history(2). A view of a struct has these defaults:
- its name is the struct's name (
Walker), or the name you pass, or the name of anAETHER_VIEWmacro; - its source is the component of the struct, registered here if it is not yet;
- every member is a delta field (see below), at tier Normal;
- it is subscribable with
Subscribe::Auto; - history 1, every 1, priority 1, 1024 rows reserved;
- nobody sees it until you choose a visibility (see Visibility).
Names
A view's name is how the client finds it, and it must be the same on both sides.
| Where | How the name is given |
|---|---|
| Server | view<Walker>() is called "Walker": the struct's name without its namespace. view<Walker>("players") is called "players". With AETHER_VIEW(S, "name", ...) the default is the macro's name. |
| Client | session.view<Walker>() looks for "Walker". session.view<Walker>("players") looks for "players". |
If the client asks for a name the server does not have, it is not a crash: the view stays empty and onError gets one message that lists what the server has:
the server has no view called 'points' (it has: Walker, scores), so session.view<Row>("points") stays empty. The view is looked up by the name the server gave it (view<Row>("name") there); use that name here
The client's row struct is matched by member name and type to the fields of the server's row. A client struct may list fewer members than the server's (extra fields are skipped), but a member the server does not send, or sends as another type, is one error and an empty view:
client::view<Score>: the server's view 'scores': ecs::Type 'scores': field 'points' is uint32, not float: use field<uint32_t>("points") (the view is looked up by that name; if the server calls it something else, say so: session.view<Row>("name"))
When views are built
The builders are collected while onStart() runs and built together when it returns. So every view must be defined in onStart(). Defining one later throws std::logic_error:
server::Game::view<Flat>(): the views are built when onStart() returns, so a view cannot be added later (in onJoin, update or a handler). Define every view in onStart(); ...
Mistakes in the options (an unknown field, a bad spatial, history(0)) are not noticed when you write them: they throw std::invalid_argument naming the view and the field when the views are built, that is, when onStart() returns, and the server does not start. The messages are quoted with each option below.
Two things that stop a view being built
- The name is taken. Two views with one name, or a view named like another struct's component, throw ecs::View 'Hero': a component or view of that name exists or ecs::Registry: a component or view named 'Flat' exists. Two different structs with one unqualified name throw the clash error of the data page.
- The struct is not flat.
view<S>()with astd::mapmember is a compile error that says how to show part of a local component: a function view.
What clients receive from a view
You do not write these messages, but knowing them explains every option that follows. After each tick's commit, the server writes one tick message to each client. It carries, for each view the client may see, a few kinds of entry.
The layout
A client is not compiled against your server's structs, so before the first entry of a view the server sends that view's layout: one message per view and client, describing the row. The client decodes every later row by it, and the typed client binds its own struct to it by name and type (that is the matching of the previous section).
| Part | Content |
|---|---|
| view | View::id(): a number, from 0 in build order |
| subscribe | 0 for Auto, 1 for Explicit |
| every | the view's every(k) (the client's alpha(e) needs it) |
| name | the view's name (at most 255 bytes) |
| block length | the size of a row in bytes |
| fields | per field, in row order: name (at most 255 bytes), kind (Prim), width in bytes, and flags: bit 0 says it is a delta field (its position among the delta fields is its bit in a Delta's mask), bits 1-2 its tier |
A server::Game sends layouts by itself. A layout that can never be sent (it does not fit the output ring's largest message, or a name is longer than 255 bytes) is never sent, and the view is never replicated to that client, with no error. ecs::layout(view) (declared in aether/ecs/Layout.h) builds the bytes (it throws std::length_error for a name over 255 bytes, std::logic_error for an empty View).
The four entries
| Entry | Content | When |
|---|---|---|
| Full | the entity and the whole row | the first time a client is sent an entity (it has no row of it) |
| Delta | the entity, a mask with one bit per delta field, and only the delta fields that changed | afterwards, when at least one delta field differs from the row the client was last sent. If that row has aged out of the view's history, the Delta carries every delta field |
| Unsubscribed | the entity | the client should forget the row: the entity was destroyed, or stayed out of sight for unsubscribeDelay sends |
| Snap | like a Full, for an entity the client already has | after snap(e): the change is a jump (a portal, a respawn), and clients should not smooth across it |
Entries come in the order Unsubscribed, Deltas, Fulls. A viewer that has nothing new is, by default, sent no message at all for about a second at a time (then a keep-alive): so a client's tick stamp can skip, and it must not be used as a clock; use session.serverTime() (Client).
For the views that have a radius, entries are sent a grid cell at a time (a cell block) and may also be Leave (an entity moved out of a cell) or a cell reset or drop. That is an optimisation of the same entries and the client's typed view hides it; the network page covers it.
Subscriptions: Auto and Explicit
A client is subscribed to an entity once it has been sent its Full; from then on it is sent Deltas. Who does the subscribing is the view's mode, set with subscribable:
Subscribe::Auto(the default for a struct view): the server subscribes the client when the ring took the Full. Nothing for the client to do.Subscribe::Explicit: the client sends a subscribe message for an entity it wants (session.subscribe, Client), and until it does it is sent a Full on every send. Use it when a client should choose what it follows.
A client can also tell the server to stop sending an entity for a while (ignore), and to say that it got a Delta for an entity it does not have (don't know, which the typed client does for you). Those are described on the client page.
Visibility: who sees which rows
A view does nothing until you say who sees its rows. There are four ways, and you pick one per view.
| Option | Who sees a row | Typical use |
|---|---|---|
.spatial(...) | players whose own entity is within the radius of the row | the world: walkers, sheep, projectiles |
.global() | every client, every row, wherever it is | a scoreboard, a list of matches |
.ownerOnly() | a client sees only the row of its own player entity | a hand of cards, an inventory total, a cooldown, a purse |
| none of the three | only the players you show the entity to, with p.show(e) | private or hand-picked entities; an inventory (recipe) |
They are exclusive: global() with spatial() or ownerOnly() throws ecs::View 'Hero': global() cannot be combined with spatial() or ownerOnly(); ownerOnly() with spatial() throws ecs::View 'Hero': ownerOnly() and spatial() cannot be combined: a private view has no radius; spatial twice throws ecs::View 'Hero': spatial() called twice.
The default: only what you show
With none of the three options, the view reaches a player only for entities you have shown to it, and for the player's own entity (a player always sees itself). This is on purpose: private data should be hidden by default, not shown by accident.
view<Walker>() with no option, two clients: the first sees 10 (its own row)
the second, shown the entity at x = 5, sees 5 10
show and hide
p.show(e); // this player sees entity e, in every view it has a row in, wherever it is, until hide p.hide(e);
Player::show(e) works in onJoin too: it is applied when the client is attached. It covers every view in which e has a row (a row it does not have is nothing to send), except ownerOnly views, which only ever show a player its own entity. hide(e) undoes it, and does nothing for an entity that was not shown. Showing also works on top of spatial: it makes a far entity a neighbour. Private data is therefore a separate view, not private fields in a shared one: a field of a row cannot be hidden from some viewers of the row.
focus and unfocus
p.focus(target); // this player cares about target: it is sent entity by entity, every send, wherever it is p.unfocus(target);
focus is about priority, not permission. It makes the entity (its target, a party member, a boss) go to this player first when a bandwidth budget is tight, and it is sent to this one player entity by entity wherever it is. It changes nothing for the other players, and it is independent of show and hide. A target that dies is let go for you. In onJoin it is applied when the client is attached. The budget itself is on the network page.
global()
view<Standing>().global(); // every client is sent every row
A global view is for things that everyone needs wherever they are. It is not spatial: there is no radius and no grid. Every row goes to every client, so keep these views small.
ownerOnly()
view<Purse>().ownerOnly(); // each client is sent only the row of its own player entity
A private view: a client is sent only the row that belongs to its own player entity (the entity in p.entity), never anyone else's. Not spatial. The row may appear later than the client attached: it is sent once the entity has it. If the player is given a new entity (a respawn), the private rows follow the new entity.
server::Game therefore sends the viewer's own player row every tick even from a view with every(k) (ownerRowEveryTick). Even so, leave the views the client predicts from at every(1), the default, and make sure they reach the owner: through spatial (a player is within its own radius), global or ownerOnly. A byte budget can still leave out an own row of a view that sits out under every(k).A player with no entity
A client whose p.entity is kNoEntity (a spectator, or a player waiting to respawn) has no position. It still sees every global view, and everything you show or focus to it; it has no spatial neighbours.
spatial: showing rows by distance
A world is too big to tell every player about everything. spatial tells the view which fields are a row's position, and from then on a client is sent only the rows near its own player. Everything about it is in this section: what the arguments name, what a row must hold, how far "near" is, and how exact that is.
The forms
view<Walker>().spatial("x", "y"); // two members of the row view<meadow::Sheep>("flock").spatial("position"); // one member that is a struct with x and y // low level, on a registry, for a hand-made view: ecs::View::define("walkers").from(walker).select(walker, "x").select(walker, "y") .subscribable().spatial(walker, "x", "y").build(registry);
| Form | What the strings name |
|---|---|
spatial(x, y) | The flattened names of two fields of the view's row (the data page): the members of the struct passed to view<Row>(), or of Out in a function view. For struct Walker { double x, y, speed; } they are "x" and "y". A nested member is named by its path: spatial("position.x", "position.y"). |
spatial(position) | The name of one member that is a struct with double x and double y. It is exactly spatial("position.x", "position.y"). The member must be a struct with those two names. |
spatial(component, x, y) | For a view you build yourself with ecs::View::define(name): component is the source and x, y are its fields as the component names them, not the names the view gives them with as(). |
The strings are resolved when the views are built, against the real fields. Nothing is looked up when you write the call, so a wrong string is reported at start-up, not at compile time. The errors, all std::invalid_argument, as produced by the code:
| Mistake | Message |
|---|---|
| a field that does not exist | ecs::View 'NoPos': spatial(): there is no field 'x' in 'NoPos' |
a field that is not double (float, an integer) | ecs::View 'Flat': spatial(): field 'n' is not a Float64 |
the member in spatial("x") is not a struct | ecs::View 'Flat': spatial(): there is no field 'x.x' in 'Flat' |
spatial called twice | ecs::View 'Hero': spatial() called twice |
| by names on a hand-made view | ecs::View 'v': spatial(x, y) by names needs View::define<S>() or a function view; use spatial(component, x, y) |
a hand-made view that is not subscribable() | ecs::View 'v': spatial(): the view is not subscribable |
a hand-made view where a field is not selected | ecs::View 'v': spatial(): field 'y' is not selected |
the component is a leftJoin | ecs::View 'v': spatial(): component 'Stats' is a leftJoin |
a groupBy view | ecs::View 'v': spatial(): a groupBy view has no position, only a join does |
| a component that is not a source of the view | ecs::View 'v': spatial(): component 'X' is not a source |
Both fields must be double; a position held in float members is refused, so declare it as double. The position is read from the view row each send, after the commit, and converted to float for the grid. A position that is not finite (NaN or infinity) keeps the entity out of the grid, and it is counted in Interest::unplaced(). Coordinates may be negative and unbounded.
Whose position is the viewer's?
A viewer's position is the position of its own player entity (the one in p.entity) in the spatial view with the lowest id (the one built first) that has a row for that entity. A viewer whose entity is kNoEntity, or has no row in a spatial view, has no position and no spatial neighbours: it is sent only what is shown, focused or global.
The radius
How near is "near"? The radius is not a property of the view: it is one number per player, in world units (the units of your x and y), set in the game's options.
Game({.radius = 400}); // everyone Game({.radius = [](const Player& p) { return p.link().congested() ? 150.f : 400.f; }}); // a rule of the player
- Default 64 world units. If you set nothing, a client is sent the rows of a spatial view only within 64 of its own player. In a debug build the first time some rows are beyond a default radius, one notice of this form is printed to stderr (once; the numbers vary): aether: view 'Walker': 6 of its 7 rows are farther than 64 world units from a client's player, so that client is not sent them. 64 is the DEFAULT radius. To see farther: server::GameOptions{.radius = ...} (or InterestPolicy::radius). Printed once, in debug builds only.
- A rule is asked once per player per send.
GameOptions::radiusis a number or a function of thePlayer. - Never clamped. Whatever it answers is used. There is no minimum and no maximum.
- NaN or negative is a bug in your rule. A debug build prints a line of this form (the client and the number vary) aether: the radius rule of client 3 (name=Ayla) answered -1: a radius is a number >= 0 (a release build would use 0 and count it in stats().badRadius) and aborts. A release build uses 0 (the viewer sees only what is shown to it by hand) and counts the answer in
Game::stats().badRadius. - The low-level form is
InterestPolicy::radius, a number or a function of theserver::Client.
How exact is it? cellSize
Underneath, the world is kept in a grid of square cells, so that "who is near this player" is a lookup, not a search. InterestPolicy::cellSize is the side of a cell in world units (default 32, finite and greater than 0; "about the usual radius"). You set it in the game options: Game({.interest = {.cellSize = 8}, .radius = 64}).
For the common case, the view is spatial, Subscribe::Auto, every(1), and not global or owner-only, the rows are sent a cell at a time. A viewer holds every cell that touches its radius circle: a little more than the circle, never less. So the radius is accurate to one cell: rows up to one cell diagonal beyond the radius can be sent. We measured it: a viewer at the origin, radius 64, sheep standing at x = 50, 64, 66, 70, 90, 100 and 130:
cellSize | Sheep the viewer is sent (x) |
|---|---|
| 32 (the default) | 50, 64, 66, 70, 90 |
| 8 | 50, 64, 66, 70 |
| 64 | 50, 64, 66, 70, 90, 100 |
With 32, the cell that spans x = 64 to 96 touches the circle at 64, so everything in it comes with it (90 but not 100). With 8 the extra is at most 8. A game that needs "nothing beyond the circle" (a far player must not see it) sets cellSize small against the radius. The cost of a small cell is more cells to hold; the SDK's own kart game uses 8 with a radius of 35.
The other views, Subscribe::Explicit ones and ones with every(k) above 1, are sent entity by entity, and they are exact: the same sheep, with Explicit or every(2), gave 50 and 64 only. Entities you show are always on this exact path, whatever the view.
unsubscribeDelay and cap
Two more numbers of the game's .interest options shape what a player keeps:
| Option | Default | Meaning |
|---|---|---|
interest.unsubscribeDelay | 3 | How many sends a subscribed entity may be out of sight (outside the radius, lost its row, hidden) before the client is sent Unsubscribed. Meanwhile it gets nothing, and if it comes back in time its Deltas carry on: a sheep standing on the edge of the radius does not flap. 0 means on the first send. A destroyed entity is Unsubscribed on the next send whatever this says. For cell blocks it applies to held cells, at most 255 sends. |
interest.cap | 2000 | The most subscriptions one viewer holds, over all views. At the cap, a neighbour it has no subscription to gets no Full until one is removed. For cell blocks a cell counts as one: a cell that does not fit is not taken; the cell that holds the viewer's own row is taken whatever the cap says. A cap of 0 is refused when the Game is constructed: ecs::Interest: cap must be at least 1 (std::invalid_argument). |
Game({.interest = {.cellSize = 16, .cap = 500, .unsubscribeDelay = 5}, .radius = 200});
GameOptions must be written with designated initialisers in declaration order: interest comes before radius. Your compiler will say so if you swap them.The same page of the options lists the budget settings (budget, weight, cellWeight, crowdEvery, cut, focus, nearReserve, workers): they decide what is sent when the connection is short of bytes, and are on the network page.
Fields that change: delta and tiers
Sending a whole row every tick would waste bytes on the fields that did not change. So after a client has a row (its Full), it is sent only the fields that changed: a Delta. A field is part of Deltas if it is a delta field.
In a view of a struct, every member is a delta field, so a change to any member is sent. You normally do nothing. The registry finds a change by comparing the row's bytes with the same entity's row at the previous commit; one compare per row per tick.
Tier
When a client's connection cannot carry everything, a Delta can be cut. Each delta field has a Tier that says how soon it may be dropped:
ecs::Tier | Meaning when bandwidth is short |
|---|---|
High | Never left out of a Delta that goes. |
Normal (the default) | Left out only after the Low fields. |
Low | Left out first. The fields left out are sent later, in a later Delta: nothing is lost, only delayed. |
A Delta that does not fit is cut to its High and Normal fields, then to its High fields, before it is left out altogether. How far a block may be cut is the game's cut option (Cut::Low by default: only Low fields may be left out; Cut::LowAndNormal; Cut::Never), covered on the network page.
The three forms of delta()
view<meadow::Sheep>("flock").spatial("position") .delta("mood", ecs::Tier::Low) // by (flattened) name .delta(&meadow::Sheep::shorn, ecs::Tier::High) // by member: the compiler checks the name .delta(&meadow::Sheep::position, ecs::Tier::High); // a struct or array member gives its tier to every field in it
| Form | Argument and meaning |
|---|---|
delta(Tier tier = Tier::Normal) | On a view you build field by field: marks the field you selected or aggregated last as a delta field, at tier. |
delta(std::string_view field, Tier tier) | For a view of a struct: gives the field named field that tier. The name is the flattened name ("position.x", "hotbar[2]", "trail.count"), checked when the views are built: ecs::View 'Hero': delta("nope", tier): the struct has no member of that name (it has: name, position.x, position.y, hotbar[0], ..., hp). |
delta(&S::member, Tier tier) | The same, naming the member itself, so a wrong name does not compile. A member that is a struct, array or list gives the tier to every field in it. The member must belong to the view's struct. The name is read from the struct the pointer is of and checked against the view when the views are built, so a pointer to a member of another struct throws then (delta("x", tier): the struct has no member of that name (it has: ...)). |
A field that is not a delta field
On a view you build yourself (below), a field you select without delta() travels only in a Full. That is useful for a value that never changes after the entity appears, and a trap for one that does:
delta() is not seen by the registry as a change at all, so it produces no Delta. A client that already has the row keeps the old value until it is sent a Full again, which may be never. Mark every field that can change with delta().In the layout, delta fields are the ones with flag bit 0, and a Delta's mask has one bit per delta field, in the order they were selected.
history: how far back to remember
view<Walker>().spatial("x", "y").history(4);
history(commits) sets how many commits older than the last one the view keeps (so commits + 1 in all). The default is 1. It matters for two things:
- The baseline of a Delta. A Delta is the difference from the row the client was last sent, so the server keeps that commit's row. A client sent every tick needs only the previous commit. A view with
every(k), or a client whose bandwidth budget leaves its entries out for k sends, needs at leastkcommits of history, or its Deltas fall back to carrying every delta field (correct, but bigger). - Reading the past on the server with
View::at(entity, stamp)(below).
history(0) throws at build: ecs::View 'Hero': history must be at least 1. Each kept commit is a copy of the whole view, so history costs memory in proportion to the rows.
How often, how important, how big
every(k)
view<meadow::Sheep>("flock").spatial("position").every(2).history(2); // half as often
every(k) makes the view take part in a viewer's send once in k sends, instead of every tick. It is for things that change slowly (scenery, a door), where sending half as often halves the bytes. The viewers are spread over the k sends (the rule is (send number + viewer number) % k == 0, where the viewer number counts the clients attached before it), so the load is level. On the sends a view sits out, nothing of it is looked at for that viewer: no neighbours, no Deltas, no Fulls, no Unsubscribed, and unsubscribeDelay counts only the sends the view takes part in.
- Default 1;
every(0)throws at build: ecs::View 'Hero': every must be at least 1. - Give such a view
history(k)or more. - The client knows each view's
every(it is in the layout), so itsalpha(e)interpolates over the right interval. - The viewer's own row still goes every tick under a
server::Game(see Own-row views and prediction). - It is the whole view that sits out, which is different from the game option
crowdEvery, where grid cells take turns. Cell blocks are used only forevery(1)views; anevery(k)view is sent entity by entity, and is exact (see the radius).
priority(n)
view<Walker>().spatial("x", "y").priority(10);
Under a bandwidth budget, the entries of the view are n times as urgent as those of a view with priority 1, and views are written in priority order, highest first. The urgency of an entry is priority x weight x (sends waited + 1). Default 1; priority(0) throws at build: ecs::View 'Hero': priority must be at least 1. Without a budget, priority has no effect on what is sent. n is a std::uint32_t.
reserve(rows)
view<Walker>().spatial("x", "y").reserve(20000);
Rows to allocate up front, so the view does not grow while the game runs. Default 1024. It is only a hint: a view holds as many rows as there are entities. rows is a std::size_t.
subscribable(mode)
view<Walker>().spatial("x", "y").subscribable(ecs::Subscribe::Explicit);
Says that clients may be sent this view, and who subscribes (Auto and Explicit). A view of a struct is already subscribable with Subscribe::Auto, so you call it only to choose Explicit. A view you build yourself with ecs::View::define(name) is not subscribable by default and reaches nobody until you call it (and spatial needs it, see above).
Reading a view on the server
A view is also a table you can read on the server. Rows are built at the end of every tick, so a view shows the world as of the last commit; during update() that is the end of the previous tick. This is how you answer "where was it two ticks ago?" without keeping your own history.
void update(float) override { const ecs::View walkers = registry().findView("Walker").value(); const auto x = walkers.field<double>("x"); for (const ecs::Entity e : walkers.entities()) { // entities that have a row const ecs::ConstRow now = walkers.row(e); const ecs::ConstRow then = walkers.at(e, registry().lastCommit() - 2); // two commits ago, if still kept if (now && then) { double moved = now.get(x) - then.get(x); (void)moved; } } }
| Call | Returns |
|---|---|
registry().findView(name) | std::optional<View>: the view with that name, or empty. |
view.row(e) | The entity's row at the last commit, as a ConstRow; a false row if it has none. |
view.at(e, stamp) | The entity's row at the newest commit whose stamp is at most stamp (lag compensation); a false row if it had none then or that commit has aged out of the history. Valid until the next commit. |
view.floor(stamp) | The stamp of the commit at(e, stamp) reads, or 0 if none. |
view.size(), view.entities() | How many entities have a row at the last commit, and a std::span<const Entity> of them. |
view.type(), view.field<T>(name), view.fields<Ts...>(names...) | The row's Type and field handles (the data page). |
view.id(), history(), subscribable(), subscribe(), spatial(), priority(), every() | What the view was built with. |
View rows and history do not change until the next commit, so a ConstRow you hold is stable for the rest of the tick. The stamps are what the game passed to commit; a server::Game uses its tick count. Reading a view never costs anything and never changes what is sent.
Views of local components
A local component (std::map, std::vector, a class with a constructor) cannot be selected into a view, because a view row is a fixed block of fields. The bridge is a function view: a function fills a plain row from the object. Everything in this page then applies to it unchanged: spatial (naming members of the row struct), global, ownerOnly, show, every, history, priority.
view<Pin>().from(herd, [](const meadow::Herd& in, Pin& out) -> bool { if (in.pen.empty()) return false; // no row this commit out.x = 1; out.y = 2; out.sheep = static_cast<std::uint32_t>(in.pen.size()); return true; }).spatial("x", "y");
All the rules (one row per source entity, runs at every commit, out starts zeroed, false skips, a throw drops the row and is reported once, no select beside it) are on the data page.
The low-level form: ecs::View::define
Under view<Row>() is ecs::View::define, which works on a registry without a Game and builds views that combine components. You need it for a join (one row from several components of an entity) or an aggregate (one row that folds many entities).
const ecs::View playerView = ecs::View::define("playerView") .from(physics).join(stats).leftJoin(look) // rows: entities with physics AND stats; look is optional .select(physics, "x").as("posX").delta(ecs::Tier::High) .select(physics, "y").as("posY").delta(ecs::Tier::High) .select(physics, "vx").delta() .select(stats, "strength") // not a delta field: only in a Full .select(look, "hair").delta(ecs::Tier::Low) .history(16).subscribable().spatial(physics, "x", "y").priority(10).build(registry);
The same form with a struct is ecs::View::define<S>(name), which is what view<S>(name) calls: ecs::View::define<Walker>("players").spatial("x", "y").build(registry);. build registers the view, so every option must be set before it.
Sources and fields
| Call | Meaning |
|---|---|
from(c) | The main source. Required, and first. Called twice: from() called twice. A tag cannot be a source: 'dead' is a tag: it cannot be a source. A local component is a compile error (use from(local, fn)). |
join(c) | The entity has a row only if it also has c. |
leftJoin(c) | The entity's row has c's fields if it has c, and zeros if it does not. |
select(c, field) | Copies one field of a source into the row, under its own name. field is a flattened name of c. An unknown field: field 'zzz': there is no field 'zzz' in 'Physics'. A component that is not a source: field 'hp': component 'Stats' is not a source. |
selectAll(c) | Every field of c, under its own names. |
as(name) | Renames the field selected or aggregated last. Two fields with one name: field 'x': duplicate output name. |
delta(tier = Normal) | Marks the last field a delta field (above). Before any field: delta() before any field. |
A view with no from() throws no from(); one with no field, no fields.
Aggregates: groupBy
An aggregate view folds the rows of one component into the row of the entity that a field of theirs names. A party is an entity; its members are rows that name their party:
struct Member { ecs::Entity party; std::uint32_t level; }; auto member = registry.component<Member>(); const ecs::View partyView = ecs::View::define("partyView") .from(member).groupBy(member, "party") // one row per entity named by member.party .count().as("members") .sum(member, "level").as("totalLevel") .max(member, "level").as("highestLevel") .history(4).subscribable().build(registry);
| Call | Result field |
|---|---|
groupBy(c, field) | Makes the view an aggregate. c must be the from() component; field must be a uint64 holding an Entity (groupBy: field 'hp' is not a uint64). Rows whose target is dead or kNoEntity are skipped. Only aggregates may follow: select or join with it throws select with groupBy: only aggregates may follow groupBy. |
count() | uint32: how many rows. Named count unless as() follows. |
sum(c, field) | int64 for a signed integer (int8, int16, int32, int64), uint64 for an unsigned one, float64 for float or double. |
avg(c, field) | float64; 0 for an empty group. |
min(c, field), max(c, field) | The source field's own type. |
last(c, field) | The source field's value of the row visited last: storage order, not stable when rows are removed. |
aggregate(c, field, Merge) | The general form of the five above. Merge: Count, Sum, Avg, Min, Max, Last. |
sum, avg, min, max on a string or a bool throw (sum needs a number field, avg needs a number field, min and max need a number field); an aggregate without groupBy throws an aggregate without groupBy; spatial on an aggregate throws (above). An aggregated row has no position of its own, so show it with global() or show.
Build errors
build(registry) throws std::invalid_argument, always starting ecs::View 'name': , for: no from, no fields, an unknown field, a component that is not a source, a component of another registry, a duplicate output name, select with groupBy, an aggregate without groupBy, groupBy on a field that is not uint64, sum/avg/min/max on a string or bool, history, every or priority of 0, global() with spatial or ownerOnly, ownerOnly with spatial, an empty name, a source twice (component 'X' is a source twice), and a component or view of that name exists.
The two views of the examples are readable on the server like any other (partyView.row(party)), and clients receive them as described above. The Game's view<S>() covers the single-component case; use ecs::View::define directly when you work with a Registry and an Interest yourself (see Going below Game).
Reference
Every public item of this page. All of ViewBuilder's methods return ViewBuilder& so they chain, except build. On a server::Game, view<Row>(name) gives you the builder.
server::Game::view
template <class Row> ecs::ViewBuilder& view(std::string_view name = {});
| Parameter | Detail |
|---|---|
Row | A flat struct (data page). The view has its members as fields, in declaration order, all delta fields at tier Normal; it is subscribable (Auto). A non-flat Row is a compile error that points to function views. |
name | The view's name. Default: the struct's name without its namespace, or the name of an AETHER_VIEW macro. The client must use the same: session.view<Row>("name"). |
| Returns | The builder. It is built, with all the others, when onStart() returns. |
| Throws | Called after onStart() has returned: std::logic_error (the views are built when onStart() returns ...). Bad options are std::invalid_argument at build (each is listed with its option). |
See also: Defining a view.
ecs::ViewBuilder
Sources and fields
static ViewBuilder View::define(std::string name); template <class S> static ViewBuilder View::define(std::string_view name = {}); ViewBuilder& from(Component c); template <class T, class Fn> ViewBuilder& from(const Local<T>& source, Fn fn); template <class C, class Fn> ViewBuilder& from(const Typed<C>& source, Fn fn); ViewBuilder& fromFunction(Component source, Type rowType, std::string rowName, std::function<bool(const std::uint8_t*, std::uint8_t*)> fn); ViewBuilder& join(Component c); ViewBuilder& leftJoin(Component c); ViewBuilder& select(Component c, std::string_view field); ViewBuilder& selectAll(Component c); ViewBuilder& as(std::string name); View build(Registry& registry);
| Item | Detail |
|---|---|
View::define(name) | Starts a view you build field by field. name must be unique among components and views (a component or view of that name exists) and non-empty (the name is empty). Not subscribable until you say so. |
View::define<S>(name = {}) | The view of a plain struct: named name, else the macro's name, else the struct's; fields are the members of S, all delta at Normal; subscribable; source is the component of S, registered if need be. Compile errors for a non-plain or non-flat S. |
from(c) | The main source. Required, first, once. Not a tag, not a local. |
from(local, fn), from(typed, fn), fromFunction | Function views: data page reference. |
join(c), leftJoin(c) | More sources. A component may be a source only once. Not a tag, not a local. |
select(c, field) | Copies field (a flattened name) of source c. Not allowed after groupBy. |
selectAll(c) | Every field of c under its own name. |
as(name) | Renames the field selected or aggregated last (names are unique). |
build(registry) | Registers the view and returns the handle. Throws std::invalid_argument; the full list is in Build errors. |
Aggregates
ViewBuilder& groupBy(Component c, std::string_view field); ViewBuilder& count(); ViewBuilder& sum(Component c, std::string_view field); ViewBuilder& avg(Component c, std::string_view field); ViewBuilder& min(Component c, std::string_view field); ViewBuilder& max(Component c, std::string_view field); ViewBuilder& last(Component c, std::string_view field); ViewBuilder& aggregate(Component c, std::string_view field, Merge merge); enum class Merge : std::uint8_t { Count, Sum, Avg, Min, Max, Last };
Result types and rules are in the Aggregates table: count is uint32; sum is int64, uint64 or float64; avg is float64 (0 when empty); min, max and last keep the source type. A local component given to any of these is a compile error (a local component stays on the server; use view.from(component, function) to show part of it (groupBy)).
Fields that change, and history
ViewBuilder& delta(Tier tier = Tier::Normal); ViewBuilder& delta(std::string_view field, Tier tier); template <class S, class T> ViewBuilder& delta(T S::*member, Tier tier); ViewBuilder& history(std::size_t commits); enum class Tier : std::uint8_t { High, Normal, Low };
| Item | Detail |
|---|---|
delta(tier) | Marks the last selected or aggregated field as a delta field. Before any field: delta() before any field. |
delta(field, tier) | For a view of a struct: the tier of the named (flattened) field. A name the struct does not have throws at build. |
delta(&S::member, tier) | The same by member pointer; a struct, array or list member tiers every field in it. A static_assert says S must be a plain struct. |
Tier | High (0, never cut), Normal (1, the default), Low (2, cut first). Stored in bits 1-2 of a field's flags in the layout. |
history(commits) | Commits older than the last that are kept. Default 1. 0 throws history must be at least 1. |
Delivery
ViewBuilder& subscribable(Subscribe mode = Subscribe::Auto); ViewBuilder& spatial(Component c, std::string_view x, std::string_view y); ViewBuilder& spatial(std::string_view x, std::string_view y); ViewBuilder& spatial(std::string_view positionMember); ViewBuilder& global(); ViewBuilder& ownerOnly(); ViewBuilder& every(std::uint32_t k); ViewBuilder& priority(std::uint32_t n); ViewBuilder& reserve(std::size_t rows); enum class Subscribe : std::uint8_t { Auto, Explicit };
| Item | Detail |
|---|---|
subscribable(mode) | Clients may be sent the view. Auto (default): the server subscribes after the Full. Explicit: the client subscribes; a Full on every send until then. A hand-made view is not subscribable until this is called. |
spatial(c, x, y) | For a hand-made view: x, y are fields of c as the component names them. Needs: subscribable, not groupBy, c is from or a join (not leftJoin), both Float64, both selected. |
spatial(x, y) | For View::define<S>, view<Row>() and function views: names of two double fields of the row. |
spatial(positionMember) | Same as spatial(m + ".x", m + ".y"); the member is a struct with double x, y. |
global() | Every client is sent every row. Not with spatial or ownerOnly. |
ownerOnly() | A client is sent only the row of its own player entity. Not with spatial. |
every(k) | The view takes part in a viewer's send once in k. Default 1; 0 throws every must be at least 1. |
priority(n) | Urgency multiplier under a budget. Default 1; 0 throws priority must be at least 1. |
reserve(rows) | Rows allocated up front. Default 1024. |
(ViewBuilder::fromStruct(component, members, ensure) is the call View::define<S> uses to name a struct's component and members; a game does not call it.)
Example, every option on one view:
view<meadow::Sheep>("flock").spatial("position") .delta("mood", ecs::Tier::Low).delta(&meadow::Sheep::shorn, ecs::Tier::High) .history(2).every(2).priority(10).reserve(20000).subscribable(ecs::Subscribe::Auto);
See also: spatial, delta, history, every, priority, reserve, subscribable.
ecs::View
const Type& type() const; std::uint16_t id() const; std::size_t history() const; bool subscribable() const; Subscribe subscribe() const; bool spatial() const; std::uint32_t priority() const; std::uint32_t every() const; template <class T> Field<T> field(std::string_view name) const; template <class... Ts> std::tuple<Field<Ts>...> fields(NameOf<Ts>... names) const; ConstRow row(Entity e) const; ConstRow at(Entity e, Stamp stamp) const; Stamp floor(Stamp stamp) const; std::size_t size() const; std::span<const Entity> entities() const; std::optional<View> Registry::findView(std::string_view name) const; std::vector<std::uint8_t> layout(View view); // aether/ecs/Layout.h
| Member | Detail |
|---|---|
type() | The layout of a row (Type): its fields are the view's output fields, in order. |
id() | Dense from 0, in build order. It is the view number in layouts and tick messages. |
history(), subscribable(), subscribe(), spatial(), priority(), every() | What the view was built with (subscribe() is meaningful when subscribable). For a view with history(4), history() is 4. |
field<T>(name), fields<Ts...>(names...) | Handles into a row, as for a Type; std::invalid_argument for an unknown field or a wrong T. |
row(e) | The entity's row at the last commit; a false ConstRow if none. |
at(e, stamp) | The row at the newest commit whose stamp is at most stamp; false if none then, or aged out. Valid until the next commit. |
floor(stamp) | The stamp that at reads; 0 if none. |
size(), entities() | Entities with a row at the last commit. |
layout(view) | The layout message body. Throws std::logic_error for a default-constructed View, std::length_error for a name over 255 bytes. |
Registry::findView(name) | The view called name, or an empty optional. |
A View is a small handle; copy it freely. The registry owns the view.
Player::show, hide, focus, unfocus
void Player::show(ecs::Entity e); void Player::hide(ecs::Entity e); void Player::focus(ecs::Entity e); void Player::unfocus(ecs::Entity e); // low level, on ecs::Interest void Interest::show(server::Client&, View view, Entity e); void Interest::hide(server::Client&, View view, Entity e); void Interest::show(server::Client&, Entity e); void Interest::hide(server::Client&, Entity e); void Interest::focus(server::Client&, Entity e); void Interest::unfocus(server::Client&, Entity e);
| Call | Detail |
|---|---|
show(e) | This player sees e in every subscribable view where e has a row, except ownerOnly views, wherever it is, until hide. In onJoin, applied at attach. Throws std::logic_error (server::Player::show(): this Players has no Interest) only for a Players built without an Interest. |
hide(e) | Undoes show. A no-op if e was not shown. |
focus(e) | Sent to this player entity by entity, every send, and first under a budget. Independent of show. A dead target is dropped at the next send. |
unfocus(e) | Undoes focus. A no-op if not focused. |
Interest::show(client, view, e) | For one view. The view must be subscribable (std::logic_error); the client must be attached (std::logic_error). Useful for views without spatial, and for entities out of the radius. |
Interest options (GameOptions::interest, InterestPolicy)
Game({.interest = {.cellSize = 32.f, .cap = 2000, .unsubscribeDelay = 3}, .radius = 64});
| Option | Type, default | Meaning |
|---|---|---|
cellSize | float, 32 | Side of a grid cell in world units. Finite and greater than 0. See How exact is it? |
radius (in GameOptions, not in interest) | number or Rule<float, const Player&>, 64 | How far a player sees spatial rows, in world units; never clamped; NaN or negative is a bug (debug: abort with a message; release: 0, counted in stats().badRadius). The low-level InterestPolicy::radius is a rule of const server::Client&. |
cap | std::uint32_t, 2000 | Subscriptions per viewer, over all views. 0 throws ecs::Interest: cap must be at least 1. |
unsubscribeDelay | std::uint32_t, 3 | Sends an entity (or a held cell, at most 255) may be out of sight before Unsubscribed. 0: on the first send. |
maxIgnoreMs, maxIgnored | std::uint32_t, 600000 and 4096 | Limits of the client's ignore message: the longest ignore (a longer one is cut), and ignored entries per viewer. |
The budget options (budget, weight, focus, cellWeight, nearReserve, crowdEvery, cut, workers) and the message-type options are documented on The network page.
Messages and entries, summarised
| Name | Value | Meaning |
|---|---|---|
Entry::Full | 0 | [kind][entity u64][row of blockLength bytes] |
Entry::Delta | 1 | [kind][entity u64][mask, one bit per delta field, in select order, (n+7)/8 bytes][the changed delta fields, each at its width] |
Entry::Unsubscribed | 2 | [kind][entity u64] |
Entry::Snap | 3 | As Full, for an entity the viewer has |
Entry::Leave | 4 | Only inside cell pieces: the entity is no longer in this cell |
The tick message is [stamp i64][last input sequence u32] followed by sections [view u16][entries u16]. A client sends subscribe [view u16][entity u64], ignore [view u16][entity u64][ms u32] and don't know [view u16][entity u64]; a body of the wrong length, an unknown view, or a view that is not subscribable is dropped and counted in dropped(). A game never writes these by hand; the typed client does.