Assets

View source

Provides a typed pool for one family of assets.

Each stored asset is identified by an asset ID and held through reference-counted Handle values. Use the pool to add, replace, reserve, look up, and release assets. Releasing the last handle removes the asset from the pool; additions, replacements, and removals produce AssetAdded, AssetModified, and AssetDropped events.

Create one pool for each asset constructor. Keep a handle while an asset is in use and release it when that reference is no longer needed. A pool can be exposed as a world resource when application code needs shared access.

Examples

import { Assets } from '@wimaengine/asset'

class Texture {}
const textures = new Assets(Texture)
const handle = textures.add(new Texture())
const assetId = handle.id()
const retained = textures.upgrade(assetId)
const texture = textures.getByAssetId(assetId)

handle.drop()
retained?.drop()
textures.update()
const events = textures.flushEvents()

Constructor


constructor<T>(type: Constructor<T>)

View source

Creates a typed asset pool for values identified by type.

The supplied constructor is retained as the asset family’s type identity for handles and resource access.

Type Parameters

T

Parameters

NameDescriptionDefault
type

Constructor for the asset values in this container.

—

Properties


Methods


add(asset: T): Handle<T>

View source

Inserts an asset into this typed pool and returns its owning handle.

The value is accepted as supplied; the pool does not perform a runtime constructor check. The returned Handle owns the first reference, and an AssetAdded event is pending for Assets#flushEvents. Release the handle with Handle#drop when it is no longer needed; Assets#update applies that queued release.

Examples

import { AssetAdded, Assets } from '@wimaengine/asset'

class Texture {
  constructor(source) {
    this.source = source
  }
}

const textures = new Assets(Texture)
const handle = textures.add(new Texture('/textures/player.png'))
const [event] = textures.flushEvents()

console.log(textures.get(handle) instanceof Texture) // true
console.log(event instanceof AssetAdded) // true
console.log(event.type === Texture) // true
console.log(event.id === handle.id()) // true

handle.drop()
textures.update()

Parameters

NameDescriptionDefault
asset

Asset value to store in this pool.

—

Returns

A handle owning the first reference to the new slot.

set(handle: Handle<T>, asset: T): void

View source

Fills or replaces the asset held by a live handle.

A handle from Assets#reserve initially addresses an empty slot, so its first fill queues AssetAdded. If the previous value is truthy, replacement queues AssetModified; otherwise the pool queues AssetAdded. Each event contains the handle’s asset ID, not either asset value.

A stale handle is ignored when its index or generation no longer matches this pool, so no asset or event changes. For a live handle, this method preserves the slot’s reference count and generation. It always returns undefined.

Examples

import { AssetAdded, AssetModified, Assets } from '@wimaengine/asset'

class Texture {
  constructor(source) {
    this.source = source
  }
}

const textures = new Assets(Texture)
const handle = textures.reserve()
console.log(textures.flushEvents().length) // 0: reserve queues nothing

textures.set(handle, new Texture('first'))
const [added] = textures.flushEvents()
textures.set(handle, new Texture('second'))
const [modified] = textures.flushEvents()

console.log(added instanceof AssetAdded) // true
console.log(modified instanceof AssetModified) // true
console.log(modified.id === handle.id()) // true
console.log(textures.get(handle).source) // 'second'

handle.drop()
textures.update()
textures.flushEvents() // Clear the AssetDropped event.
textures.set(handle, new Texture('stale'))
console.log(textures.get(handle)) // undefined
console.log(textures.flushEvents().length) // 0: stale set is ignored

Parameters

NameDescriptionDefault
handle

Handle whose live slot should be filled or replaced.

—
asset

Asset value to store in the slot.

—

Returns

Always returns undefined, including for a stale handle.

setUsingAssetId(assetId: AssetId, asset: T): void

View source

Replaces the asset identified by an asset ID.

If the slot currently contains a truthy value, the pool queues AssetModified; otherwise it queues AssetAdded. A stale ID is ignored, leaves the pool unchanged, and does not allocate a replacement slot. The method returns undefined.

Parameters

NameDescriptionDefault
assetId

Packed ID identifying the asset slot.

—
asset

Asset value to store in the slot.

—

Returns

Always returns undefined.

setWithUUID(uuid: string, asset: T): Handle<T>

View source

Adds or replaces an asset associated with a UUID.

If the UUID is already mapped, its stored handle is used for the replacement and a cloned handle is returned. A live mapping queues the same lifecycle event as Assets#set; a stale mapping leaves the pool unchanged but still returns a clone of the stale handle. Otherwise the asset is added and the UUID keeps its own cloned handle. Release the returned handle when it is no longer needed. UUID associations are not removed automatically when an asset is dropped.

Parameters

NameDescriptionDefault
uuid——
asset——

getEntry(handle: Handle<T>): AssetEntry<T>

View source

Returns entry metadata for a handle whose slot identity is still valid.

A reserved slot returns an entry even when its asset is undefined. Returns undefined when the handle is stale because its slot identity no longer matches the pool.

Parameters

NameDescriptionDefault
handle——

getEntryByAssetId(assetId: AssetId): AssetEntry<T>

View source

Returns entry metadata for a packed asset ID while its slot identity is still valid.

Returns undefined when the ID is stale, even if its former index now stores another asset. A reserved slot still returns its entry while its asset is undefined.

Parameters

NameDescriptionDefault
assetId——

get(handle: Handle<T>): T

View source

Returns the asset addressed by a handle in this pool.

Returns undefined when the handle is stale or its slot is reserved or empty.

Examples

import { Assets } from '@wimaengine/asset'

class Texture {}
const textures = new Assets(Texture)
const handle = textures.add(new Texture())

console.log(textures.get(handle) instanceof Texture) // true

handle.drop()
textures.update()
console.log(textures.get(handle)) // undefined: the handle is stale

Parameters

NameDescriptionDefault
handle

Handle identifying the asset slot.

—

Returns

The asset, or undefined for a stale or empty slot.

getByUUID(uuid: string): T

View source

Returns the asset associated with a UUID.

Returns undefined when the UUID has not been registered or its entry is no longer live.

Parameters

NameDescriptionDefault
uuid——

getByAssetId(id: AssetId): T

View source

Returns the asset identified by a packed asset ID.

Returns undefined when the ID is stale or its slot is reserved or empty.

Examples

import { Assets } from '@wimaengine/asset'

class Texture {}
const textures = new Assets(Texture)
const handle = textures.add(new Texture())
const assetId = handle.id()

console.log(textures.getByAssetId(assetId) instanceof Texture) // true

handle.drop()
textures.update()
console.log(textures.getByAssetId(assetId)) // undefined: the ID is stale

Parameters

NameDescriptionDefault
id

Packed ID identifying the asset slot.

—

Returns

The asset, or undefined for a stale or empty slot.

getHandleByUUID(uuid: string): Handle<T>

View source

Returns a cloned handle for a UUID association.

The returned Handle is a separate reference whose acquisition is applied by Assets#update; release it with Handle#drop when it is no longer needed. Returns undefined when the UUID is not mapped. If a mapping exists but its slot is empty or stale, this method still returns a clone with that identity; use Assets#get to check the asset value.

Examples

import { Assets } from '@wimaengine/asset'

class Texture {}
const textures = new Assets(Texture)
const original = textures.setWithUUID('player', new Texture())
const lookup = textures.getHandleByUUID('player')

console.log(lookup !== undefined) // true
console.log(lookup !== original) // true: the lookup is a clone
lookup?.drop()
original.drop()
textures.update()

Parameters

NameDescriptionDefault
uuid

UUID associated with an asset.

—

Returns

A cloned handle, or undefined when the UUID is not mapped.

flushEvents(): readonly AssetEvent<T>[]

View source

Returns the lifecycle events queued since the previous flush.

A non-empty batch is detached before it is returned, so later mutations are placed in a new batch. An empty flush keeps the current empty array. Events may be AssetAdded, AssetModified, or AssetDropped.

Examples

import { AssetAdded, AssetModified, Assets } from '@wimaengine/asset'

class Texture {}
const textures = new Assets(Texture)
const empty = textures.flushEvents()
const handle = textures.add(new Texture())
console.log(empty.length) // 1: an empty flush does not rotate the buffer

const added = textures.flushEvents()
textures.set(handle, new Texture())
const modified = textures.flushEvents()
console.log(added[0] instanceof AssetAdded) // true
console.log(modified[0] instanceof AssetModified) // true
console.log(added !== modified) // true

Returns

The pending event batch.

drop(handle: Handle<T>): void

View source

Releases one reference held by a handle immediately.

For a valid handle, this method releases one reference synchronously. If other references remain, the asset stays in the pool and no event is queued. When the count reaches zero, the asset is cleared, its index is recycled, and an AssetDropped event is queued immediately. A stale handle is ignored.

Unlike Handle#drop, this method does not mark the handle as dropped or defer the release. Release each reference exactly once; calling this method again on the same handle releases another reference while its slot identity still matches.

Examples

import { AssetDropped, Assets } from '@wimaengine/asset'

class Texture {
  constructor(name) {
    this.name = name
  }
}

const textures = new Assets(Texture)
const owner = textures.add(new Texture('player'))
const assetId = owner.id()
textures.flushEvents() // Clear the AssetAdded event.
const retained = textures.upgrade(assetId)

textures.drop(owner)
console.log(textures.getByAssetId(assetId).name) // 'player'
console.log(textures.flushEvents().length) // 0: one reference remains

textures.drop(retained)
const [event] = textures.flushEvents()
console.log(event instanceof AssetDropped) // true
console.log(event.id === assetId) // true
console.log(textures.getByAssetId(assetId)) // undefined

Parameters

NameDescriptionDefault
handle

Handle whose reference should be released.

—

Returns

Always returns undefined.

upgrade(assetId: AssetId): Handle<T>

View source

Retains the entry identified by an asset ID and returns a new handle for that reference.

The reference count is incremented immediately; no queued operation is needed. The returned Handle has the same type, index, and generation as the ID and owns one additional reference. Returns undefined when the entry is missing or its generation does not match the ID. A reserved entry is valid even while its asset is undefined, so an ID for that slot can also be upgraded.

Recycling clears an entry’s asset but does not change its generation until the index is reserved again. Therefore an ID can still resolve after Assets#drop has removed its asset and before that index is reused; the resulting handle then refers to an empty entry. When the index is reused, the incremented generation makes the old ID stale. Release the returned handle with Handle#drop when it is no longer needed.

Examples

import { Assets } from '@wimaengine/asset'

class Texture {
  constructor(name) {
    this.name = name
  }
}

const textures = new Assets(Texture)
const owner = textures.add(new Texture('player'))
const retained = textures.upgrade(owner.id())
if (!retained) throw new Error('The asset ID is stale')

owner.drop()
textures.update() // The retained reference keeps the asset alive.
console.log(textures.get(retained).name) // 'player'

retained.drop()
textures.update()
console.log(textures.get(retained)) // undefined

Parameters

NameDescriptionDefault
assetId

Packed ID of the entry to retain.

—

Returns

A handle for the retained entry, or undefined when the ID is stale.

reserve(): Handle<T>

View source

Reserves a slot for an asset that will be filled later.

The returned Handle owns the first reference even before the slot contains an asset. The slot’s asset is initially undefined, its generation is incremented, and no lifecycle event is queued. Fill the slot with Assets#set or Assets#setUsingAssetId; that operation queues the first asset lifecycle event.

If a slot index is reused, its incremented generation makes older handles and asset IDs for that index stale. The reservation does not return an asset value.

Examples

import { Assets } from '@wimaengine/asset'

class Texture {
  constructor(name) {
    this.name = name
  }
}

const textures = new Assets(Texture)
const handle = textures.reserve()
console.log(textures.get(handle)) // undefined: the slot is empty
console.log(textures.flushEvents().length) // 0: reserve queues no event

textures.set(handle, new Texture('player'))
console.log(textures.get(handle).name) // 'player'

handle.drop()
textures.update()

Returns

Handle owning the first reference to the reserved slot.

values(): readonly AssetEntry<T>[]

View source

Returns the pool’s entries in slot-index order.

Each position corresponds to the slot index used by a Handle. Released slots remain represented by an AssetEntry with an undefined asset, and a later reservation reuses that position with a new generation. Use Assets#get or Assets#getByAssetId for ordinary asset access. Treat the returned array as read-only.

Returns

Entries at their pool indexes, including recycled slots.

statictoSnapshot(assets: Assets<unknown>, world: World): AssetsSnapshot<unknown>

View source

Creates a snapshot of this pool’s index-aligned asset values.

The world must provide a TypeRegistry. When the registry has an entry for this asset constructor, each populated value is passed to that entry’s serialize hook. If the entry is missing, the original asset value is kept as-is; if the entry exists without that hook, the populated slot becomes undefined. Empty or reserved slots remain undefined, preserving their indexes for restoration. The returned AssetsSnapshot stores the asset constructor’s type ID.

Examples

import { Assets } from '@wimaengine/asset'
import { OpaqueInfo, TypeRegistry } from '@wimaengine/reflect'
import { World } from '@wimaengine/ecs'

class Texture {
  constructor(source) {
    this.source = source
  }
}

const registry = new TypeRegistry()
registry.register(Texture, OpaqueInfo.default())
registry.get(Texture).setMethod(function serialize(texture) {
  return { source: texture.source }
})

const world = new World()
world.setResource(registry)
const textures = new Assets(Texture)
textures.add(new Texture('player.png'))
const reserved = textures.reserve()
const snapshot = Assets.toSnapshot(textures, world)

console.log(snapshot.assets[0]) // { source: 'player.png' }
console.log(snapshot.assets[reserved.index]) // undefined

Parameters

NameDescriptionDefault
assets

Live asset pool being snapshotted.

—
world

World containing the TypeRegistry used for optional asset serialization.

—

staticfromSnapshot(snapshot: AssetsSnapshot<unknown>, world: World, sceneAssetId: AssetId): Assets<unknown>

View source

Restores an asset pool from a snapshot value.

Parameters

NameDescriptionDefault
snapshot——
world——
sceneAssetId——

update(): void

View source

Applies queued reference operations from asset handles.

Handle#clone and Handle#drop queue operations on the shared AssetChannel. This method applies the pending batch in queue order. An acquisition increments the matching entry’s reference count; a release decrements it. An operation for a stale asset ID is ignored. A release that removes the last reference clears and recycles the slot and queues an AssetDropped event.

Examples

import { AssetDropped, Assets } from '@wimaengine/asset'

class Texture {}
const textures = new Assets(Texture)
const owner = textures.add(new Texture())
textures.flushEvents() // Clear the AssetAdded event.

const retained = owner.clone()
owner.drop()
textures.update() // Applies acquire, then release; the asset remains live.
console.log(textures.get(retained) instanceof Texture) // true

retained.drop()
textures.update() // Applies the final release.
const [dropped] = textures.flushEvents()
console.log(dropped instanceof AssetDropped) // true