A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file resource.ts
* @brief Resource system for global singleton data
*/
import { deepClone } from '../util/deepClone';
import { RESOURCE_SHAPES } from './resourceShapes';
// =============================================================================
// Resource Definition
// =============================================================================
/**
* A resource type, as {@link defineResource} returns it: the world holds one
* value per definition. Opaque — pass it to `Res`/`ResMut`, `insertResource` or
* `getResource` rather than reading it.
*
* @public
*/
export interface ResourceDef<T> {
/** @internal */
readonly _id: symbol;
/** @internal */
readonly _name: string;
/** @internal */
readonly _default: T;
}
let resourceCounter = 0;
// Interned by NAME, module-globally, like component identity (component.ts). A
// hot reload re-evaluates this declaration, and a fresh symbol would address a
// slot nothing filled — which `get` answers with the DEFAULT, not a failure.
const resourceIdRegistry = new Map<string, symbol>();
function resourceId(name: string): symbol {
let id = resourceIdRegistry.get(name);
if (id === undefined) {
id = Symbol(`Resource_${name}`);
resourceIdRegistry.set(name, id);
}
return id;
}
/**
* Declare a resource: one value the whole world shares. A NAMED one is addressed
* by its name, so two declarations of one name are one resource; an unnamed one
* is addressed by the definition, and two calls answer two.
*
* An empty slot materialises the LATEST declaration's `defaultValue`.
*
* @public
*/
export function defineResource<T>(defaultValue: T, name?: string): ResourceDef<T> {
const anonymous = `Resource_${++resourceCounter}`;
const def: ResourceDef<T> = {
_id: name === undefined ? Symbol(anonymous) : resourceId(name),
_name: name ?? anonymous,
_default: defaultValue
};
// The engine's own resources answer to their NAME too, because a compiled
// module's manifest carries names.
if (name && RESOURCE_SHAPES[name]) builtinByName.set(name, def as ResourceDef<unknown>);
else if (name !== undefined) declaredByName.set(name, def as ResourceDef<unknown>);
return def;
}
/** Registered by `defineResource` for the names `resourceShapes.ts` declares. */
const builtinByName = new Map<string, ResourceDef<unknown>>();
/** And for the names a PROJECT declares, which a manifest also carries. */
const declaredByName = new Map<string, ResourceDef<unknown>>();
/**
* The engine resource a manifest's NAME refers to, or undefined when the module
* that declared it was never loaded — a trimmed build without the input plugin
* would be one, and a twin reading a resource with no address is not something
* to discover at the first row.
*
* @internal
*/
export function builtinResource(name: string): ResourceDef<unknown> | undefined {
return builtinByName.get(name);
}
/**
* A named resource a project DECLARED, whether or not anything has inserted one.
*
* The storage learns a name on INSERT, so a resource nothing had touched was
* invisible to the AOT handshake.
*
* @internal
*/
export function declaredResource(name: string): ResourceDef<unknown> | undefined {
return declaredByName.get(name);
}
// =============================================================================
// Resource Descriptors (for system parameters)
// =============================================================================
/**
* A request for read access to a resource, as {@link Res} returns it. Opaque —
* the system body receives the resource value itself.
*
* @public
*/
export interface ResDescriptor<T> {
/** @internal */
readonly _type: 'res';
/** @internal */
readonly _resource: ResourceDef<T>;
}
/**
* A request for write access to a resource, as {@link ResMut} returns it.
* Opaque — the body receives a `ResMutInstance`, whose `set`/`modify` are what
* store the value back.
*
* @public
*/
export interface ResMutDescriptor<T> {
/** @internal */
readonly _type: 'res_mut';
/** @internal */
readonly _resource: ResourceDef<T>;
}
/**
* Ask a system for read access to a resource: the world's single instance of
* `resource`, passed to the system body as the stored value itself.
*
* Not a copy — an object resource's fields are reachable through it. Replacing
* the value, and the change tick recording it, is what {@link ResMut} is for.
*
* @public
*/
export function Res<T>(resource: ResourceDef<T>): ResDescriptor<T> {
return { _type: 'res', _resource: resource };
}
/**
* Ask a system for write access to a resource. The body receives a
* {@link ResMutInstance}, not the value: `set` or `modify` is what stores it back
* and stamps the change tick a `Changed` filter reads.
*
* @public
*/
export function ResMut<T>(resource: ResourceDef<T>): ResMutDescriptor<T> {
return { _type: 'res_mut', _resource: resource };
}
// =============================================================================
// Resource Instances (Runtime)
// =============================================================================
/**
* Write access to a resource, as {@link ResMut} asked for. `get` reads,
* `set` replaces, `modify` edits in place — and both writers store the value
* back and bump the change tick, which is the part `Res` cannot do.
*
* @public
*/
export class ResMutInstance<T> {
private value_: T;
private readonly setter_: (v: T) => void;
constructor(value: T, setter: (v: T) => void) {
this.value_ = value;
this.setter_ = setter;
}
get(): T {
return this.value_;
}
set(value: T): void {
this.value_ = value;
this.setter_(value);
}
modify(fn: (value: T) => void): void {
fn(this.value_);
this.setter_(this.value_);
}
/** @internal */
updateValue(value: T): void {
this.value_ = value;
}
}
// =============================================================================
// Resource Storage
// =============================================================================
export class ResourceStorage {
private resources_ = new Map<symbol, unknown>();
private resMutPool_ = new Map<symbol, ResMutInstance<unknown>>();
private ticks_ = new Map<symbol, number>();
private globalTick_ = 0;
private nameRegistry_ = new Map<string, ResourceDef<unknown>>();
/**
* Slots holding a materialised default rather than a value somebody put
* there. `has` is what every self-gating subsystem asks before installing
* itself, so a read must not answer it: a resource defaulting to `null`
* would report present the moment any system took it as a parameter.
*/
private defaulted_ = new Set<symbol>();
/** What each slot is called, so nobody has to reconstruct it from a symbol. */
private names_ = new Map<symbol, string>();
/** Record what a slot is called, whichever door reached it. */
private note_(resource: ResourceDef<unknown>): void {
this.names_.set(resource._id, resource._name);
if (resource._name && !resource._name.startsWith('Resource_')) {
this.nameRegistry_.set(resource._name, resource);
}
}
insert<T>(resource: ResourceDef<T>, value: T): void {
this.resources_.set(resource._id, value);
this.defaulted_.delete(resource._id);
this.ticks_.set(resource._id, ++this.globalTick_);
this.note_(resource as ResourceDef<unknown>);
}
get<T>(resource: ResourceDef<T>): T {
if (!this.resources_.has(resource._id)) {
// Clone so each storage owns its default; mutating it never leaks
// into the shared ResourceDef or a sibling world.
this.resources_.set(resource._id, deepClone(resource._default));
this.defaulted_.add(resource._id);
this.names_.set(resource._id, resource._name);
}
return this.resources_.get(resource._id) as T;
}
set<T>(resource: ResourceDef<T>, value: T): void {
this.resources_.set(resource._id, value);
this.defaulted_.delete(resource._id);
this.ticks_.set(resource._id, ++this.globalTick_);
this.note_(resource as ResourceDef<unknown>);
}
has<T>(resource: ResourceDef<T>): boolean {
return this.resources_.has(resource._id) && !this.defaulted_.has(resource._id);
}
remove<T>(resource: ResourceDef<T>): void {
this.resources_.delete(resource._id);
this.defaulted_.delete(resource._id);
this.resMutPool_.delete(resource._id);
this.ticks_.delete(resource._id);
this.names_.delete(resource._id);
this.nameRegistry_.delete(resource._name);
}
/**
* Every slot this storage holds, as `[name, value]` — including one only a
* read has materialised, which is most of them in a running game.
*
* The name is the declaration's. Reconstructing it from the id's
* description is a second author of what a resource is called.
*/
entries(): Array<[string, unknown]> {
return [...this.resources_].map(([id, value]) => [this.names_.get(id) ?? '', value]);
}
getChangeTick(resource: ResourceDef<unknown>): number {
return this.ticks_.get(resource._id) ?? 0;
}
getByName(name: string): ResourceDef<unknown> | undefined {
return this.nameRegistry_.get(name);
}
getRegisteredNames(): string[] {
return Array.from(this.nameRegistry_.keys());
}
getResMut<T>(resource: ResourceDef<T>): ResMutInstance<T> {
let instance = this.resMutPool_.get(resource._id) as ResMutInstance<T> | undefined;
if (instance) {
instance.updateValue(this.get(resource));
return instance;
}
instance = new ResMutInstance(
this.get(resource),
(v) => this.set(resource, v)
);
this.resMutPool_.set(resource._id, instance as ResMutInstance<unknown>);
return instance;
}
}
// =============================================================================
// Builtin Resources
// =============================================================================
/**
* The frame's clock, as {@link Time} carries it. `delta` is what almost
* everything integrates by — it is already multiplied by `scale`, so honouring a
* pause costs a system nothing.
*
* @public
*/
export interface TimeData {
/** Seconds since the previous frame, scaled by `scale`. */
delta: number;
/** Accumulated scaled game seconds; frozen while paused except for explicit frame steps. */
elapsed: number;
/** Render frames completed — machine-dependent; see `fixedTick`. */
frameCount: number;
/** Fixed-update timestep in seconds — the FixedUpdate / physics cadence. */
fixedDelta: number;
/**
* Interpolation factor in [0, 1) into the current fixed step
* (fixedAccumulator / fixedDelta), set after the fixed-update loop each
* frame. Render-time systems lerp prev→current state by this to smooth
* fixed-step simulation (e.g. physics) onto the variable render rate.
*/
fixedAlpha: number;
/**
* Monotonic count of completed FixedUpdate steps — the simulation's own
* time axis (frameCount counts render frames, which vary per machine).
* Netcode stamps snapshots and input commands with this.
*/
fixedTick: number;
/**
* Multiplier on `delta` and on the fixed-step accumulation; negatives clamp
* to 0. At 0 the frame still runs — systems tick and a menu draws — while
* everything advancing by `delta` (movement, navigation, behaviour trees,
* the physics step) advances by nothing.
*
* Read once at the top of the frame, before any system runs, so a write
* takes effect from the next frame: a game that pauses in `Update`
* integrates that frame in full and freezes from the one after.
*/
scale: number;
/** Real frame time, unaffected by `scale`, for whatever must keep moving. */
unscaledDelta: number;
}
/**
* The frame clock, as `Res(Time)`. The engine writes it once per frame before
* any system runs; `scale` is the one field a project sets.
*
* @public
*/
export const Time = defineResource<TimeData>(
{ ...RESOURCE_SHAPES['Time']!.fields } as unknown as TimeData, 'Time');