Skip to content

Commit

Permalink
feat: added hooks to engine step loop
Browse files Browse the repository at this point in the history
  • Loading branch information
ColinEspinas committed Oct 16, 2024
1 parent 9da26cb commit 7596a63
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/core/Engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export class Engine {
fullscreen: true,
container: 'body',
framerate: null,
hooks: {
beforeStep: () => { },
afterStep: () => { },
},
...options,
}
this._container = document.querySelector(this._options.container as string) as HTMLElement
Expand Down Expand Up @@ -98,6 +102,18 @@ export class Engine {
* to fix the timestep for fixed update loops (useful for physics and user interactions).
*/
protected step(now: number): void {
// Call beforeStep hook
try {
if (!this.options.hooks || !this.options.hooks.beforeStep) {
throw new EngineError(this, 'ENGINE:FAILURE', 'No beforeStep hook given to engine.')
}
this.options.hooks.beforeStep()
}
// eslint-disable-next-line unused-imports/no-unused-vars
catch (_) {
throw new EngineError(this, 'ENGINE:FAILURE', 'Error in beforeStep hook')
}

if (!this.rootNode) {
throw new EngineError(this, 'ENGINE:FAILURE', 'No root node given to engine, cannot run.')
}
Expand All @@ -118,6 +134,18 @@ export class Engine {
system.step(this.time.delta)
})
this.rootNode.step(this.time.delta)
// Call afterStep hook
try {
if (!this.options.hooks || !this.options.hooks.afterStep) {
throw new EngineError(this, 'ENGINE:FAILURE', 'No afterStep hook given to engine.')
}
this.options.hooks.afterStep()
}
// eslint-disable-next-line unused-imports/no-unused-vars
catch (_) {
throw new EngineError(this, 'ENGINE:FAILURE', 'Error in afterStep hook')
}

// Request next step
requestAnimationFrame(this.step.bind(this))
}
Expand Down
16 changes: 16 additions & 0 deletions src/types/options.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,20 @@ export interface EngineOptions {
* @default null
*/
framerate?: number | null

/**
* Hooks are functions that are called at specific points in the engine's runtime.
*/
hooks?: {
/**
* Called before the engine's step loop.
* @default () => { }
*/
beforeStep: () => void
/**
* Called after the engine's step loop.
* @default () => { }
*/
afterStep: () => void
}
}

0 comments on commit 7596a63

Please sign in to comment.