Skip to content

10 · Resources

What it is

A resource is a single value owned by the world, not attached to any entity: the frame time, the input state, the configuration, the asset storage, the renderer. Systems access resources by type (C++) or by name (Luau).

Why we need it

Some data has exactly one instance. Putting it on an entity ("the entity that holds the time") would be awkward and slow to find.

  • R1 (Bevy-style engine): every engine service becomes a resource: Ethan's Backend (platform + renderer), Input, Settings, TextureAssets, the network state.
  • R2 (Luau): scripts read resources like time and write their own (a game.Score resource).

How others do it

ECS Singletons
Bevy Res<T> / ResMut<T>; NonSend<T> for data that must stay on the main thread
flecs Singletons: a component set on the component's own entity
EnTT registry.ctx() context variables
Unity DOTS Singleton components (SystemAPI.GetSingleton<T>())

Our choice

Bevy's model: Res<T> (read), ResMut<T> (write) and NonSend<T> / NonSendMut<T> for main-thread-only values. Resources are registered by name like components, so the type-erased API and Luau can reach them.

How it works

Declaring and storing

A resource is a C++ type declared with RTYPE_ECS_RESOURCE, or a run-time (Luau) description. It is a second kind of the type core (see "The type core"): ResourceInfo { TypeInfo type; bool nonSend; }, registered in a ResourceRegistry (TypeRegistry<ResourceInfo>), its value kept in a ResourceStorage slot (zero or one value in a ByteColumn, with its added / changed ticks). Unlike a component, a resource may be any movable class: constructors, private members, move-only (the platform and the renderer).

struct Time {
    float delta;
    float fixedDelta;
};
RTYPE_ECS_RESOURCE(Time, "rtype.Time");

struct Score {
    std::int32_t value;
};
RTYPE_ECS_RESOURCE(Score, "game.Score", value);   // reflected: replicable, reachable from Luau

A name is one kind of type only: registering a resource named like a component or an event is refused (WorldState::checkNameFree()), and the other way round.

Resources API

Resources live in a Resources object owned by the world, reached with world.getResources() (like world.getComponents() for components, see World):

rtype::ecs::Resources& resources = world.getResources();
resources.insert(Time{.fixedDelta = 1.F / 60.F});
const Time& time = resources.require<Time>();

A plugin that provides a default resource uses insertIfAbsent(): it inserts only when the resource has no value, so what the game or another plugin inserted first is kept (value and ticks untouched). Without an argument it inserts T{}; it returns whether it inserted:

resources.insertIfAbsent<TextureAssets>();                 // TextureAssets{} unless one is already there
resources.insertIfAbsent(Time{.fixedDelta = 1.F / 60.F});  // or a given value
Typed (C++) Type-erased (Luau, network)
registerType<T>(options): registers (like getComponents().registerType<T>()) registerType(ResourceInfo), find(name)
insert(value), insertNonSend(value), insertIfAbsent(value = T{}) insert(id, bytes)
has<T>(), get<T>() (nullptr if missing) has(id), get(id)
require<T>(): throws MissingResourceException naming it
getMut<T>(), requireMut<T>(): Mut<T>, marks changed on write getMut(id): marks changed on access
remove<T>(), getTicks<T>() remove(id), getTicks(id)

Resource ticks are clamped with the pools' by checkChangeTicks(), so change detection survives the tick wrap.

System parameters

Systems read resources through parameters (system/ResourceParam.hpp), built at each run with getResources().require<T>() / requireMut<T>(). They give ->, * and get(), and isAdded() / isChanged() against the system's last run; a written parameter marks the value changed only when written through -> / * (like Mut). The four are aliases of one ResourceParam<T, Access, Thread> template, so a system's signature tells the scheduler what it reads, writes, and whether it needs the main thread:

app.insertResource(Time{.fixedDelta = 1.F / 60.F});
app.insertResource(std::move(settings));               // Ethan's core::config::Settings
app.insertNonSendResource(std::move(backend));         // Ethan's plugins::graphics::Backend

void tick(rtype::ecs::ResMut<Time> time);
void drawSprites(/* queries... */ rtype::ecs::NonSendMut<rtype::plugins::graphics::Backend> backend);
Parameter Access Thread
Res<T> read any
ResMut<T> write any
NonSend<T> read main thread only
NonSendMut<T> write main thread only

Why main-thread resources

GLFW requires most of its calls (window creation, event polling) on the main thread, and Vulkan presentation is usually tied to the window's thread. Marking the platform and renderer as NonSend tells the scheduler that systems using them must run on the main thread. In the sequential v1 scheduler this changes nothing at runtime; it is there so a parallel scheduler later knows the constraint.

Resources the engine plugins insert

Resource Inserted by Kind
Time TimePlugin (every App has one) Res
Settings core (from the config file) Res
Backend (platform + renderer) GraphicsPlugin NonSend
Input InputPlugin Res
TextureAssets (AssetId → texture, load queue) GraphicsPlugin ResMut to load, Res to look up
Sound assets an audio plugin (later, once an audio library is chosen) Res
ServerState / ClientState ServerPlugin / ClientPlugin Res
State<T> app.state<T>() (see Scheduler) Res

From Luau

app:resource("game.Score", { type = "Score", replication = "everyChange" })   -- declared like a component

function ScoreOnKill:run(ctx)
    ctx.resources["game.Score"].value += 100
end

A script resource is described by a Luau type exactly like a component; a replicated resource is sent like a component of a hidden singleton entity.

Connections

Pitfalls

  • Turning everything into a resource. Per-player data (score per player) belongs on the player's entity, not in a resource map; otherwise queries, replication and despawning do not see it.
  • Hidden ordering. Two systems writing the same resource must be ordered explicitly; the scheduler rejects ambiguous orders (see Scheduler). The exception is ResAppend<T>, for a resource systems only add to: two appending systems need no order, but each is still ordered against whatever reads or writes it. Use it only when the order of the additions cannot change the result.
  • Missing resource. require<T>() throws MissingResourceException naming the resource ("Resource 'rtype.Time' is not in the world: insert it (or add the plugin that does) before using it"); with #120, a system asking for Res<T> reports it the same way. get<T>() returns nullptr for resources that are genuinely optional.

Open questions

  • Should replicated resources exist, or should replicated singletons always be entities? (ECS + network)