Skip to content

Commit

Permalink
feat(core): add basic actor pool
Browse files Browse the repository at this point in the history
  • Loading branch information
tomaisthorpe committed Jul 4, 2024
1 parent a2ff636 commit 98d4346
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/blue-trains-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tedengine/ted': minor
---

Add simple actor pool with preallocation
68 changes: 68 additions & 0 deletions packages/ted/src/core/actor-pool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type TActor from './actor';

export interface TPoolableActor extends TActor {
/**
* Resets the actor to its initial state
*/
reset(): void;

pool: TActorPool<TPoolableActor>;
}

export default class TActorPool<T extends TPoolableActor> {
private actors: T[] = [];

constructor(
// Function that creates a new actor
private readonly actor: () => T,
startingInstances: number,
) {
// Prefill the pool with instances
for (let i = 0; i < startingInstances; i++) {
const actor = this.actor();
actor.pool = this;

this.actors.push(actor);
}
}

/**
* Acquires an actor from the pool, and initializes a new one if necessary
* @returns
*/
public acquire(): T | undefined {
if (this.actors.length === 0) {
const actor = this.actor();
actor.pool = this;
return actor;
}

return this.actors.pop();
}

/**
* Releases actor back to the pool, resets and removes it from the world
* @param actor
*/
public release(actor: T): void {
actor.reset();

if (actor.world) {
actor.world.removeActor(actor);
}

this.actors.push(actor);
}

/**
* Runs destroy all actors remaining in the pool.
* This will not destroy actors that have been acquired.
*/
public destroy(): void {
for (const actor of this.actors) {
actor.destroy();
}

this.actors = [];
}
}
3 changes: 3 additions & 0 deletions packages/ted/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ export { default as TFollowComponentCameraController } from './cameras/follow-co
export { default as TActor } from './core/actor';
export * from './core/actor';

export { default as TActorPool } from './core/actor-pool';
export * from './core/actor-pool';

export { default as TEventQueue } from './core/event-queue';
export * from './core/event-queue';

Expand Down

0 comments on commit 98d4346

Please sign in to comment.