Skip to content

Commit 2311596

Browse files
committed
feat: added hooks to engine step loop
1 parent 9da26cb commit 2311596

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/core/Engine.ts

+28
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ export class Engine {
6363
fullscreen: true,
6464
container: 'body',
6565
framerate: null,
66+
hooks: {
67+
beforeStep: () => { },
68+
afterStep: () => { },
69+
},
6670
...options,
6771
}
6872
this._container = document.querySelector(this._options.container as string) as HTMLElement
@@ -98,6 +102,18 @@ export class Engine {
98102
* to fix the timestep for fixed update loops (useful for physics and user interactions).
99103
*/
100104
protected step(now: number): void {
105+
// Call beforeStep hook
106+
try {
107+
if (!this.options.hooks || !this.options.hooks.beforeStep) {
108+
throw new EngineError(this, 'ENGINE:FAILURE', 'No beforeStep hook given to engine.')
109+
}
110+
this.options.hooks.beforeStep()
111+
}
112+
// eslint-disable-next-line unused-imports/no-unused-vars
113+
catch (_) {
114+
throw new EngineError(this, 'ENGINE:FAILURE', 'Error in beforeStep hook')
115+
}
116+
101117
if (!this.rootNode) {
102118
throw new EngineError(this, 'ENGINE:FAILURE', 'No root node given to engine, cannot run.')
103119
}
@@ -118,6 +134,18 @@ export class Engine {
118134
system.step(this.time.delta)
119135
})
120136
this.rootNode.step(this.time.delta)
137+
// Call afterStep hook
138+
try {
139+
if (!this.options.hooks || !this.options.hooks.afterStep) {
140+
throw new EngineError(this, 'ENGINE:FAILURE', 'No afterStep hook given to engine.')
141+
}
142+
this.options.hooks.afterStep()
143+
}
144+
// eslint-disable-next-line unused-imports/no-unused-vars
145+
catch (_) {
146+
throw new EngineError(this, 'ENGINE:FAILURE', 'Error in afterStep hook')
147+
}
148+
121149
// Request next step
122150
requestAnimationFrame(this.step.bind(this))
123151
}

src/types/options.d.ts

+16
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,20 @@ export interface EngineOptions {
3232
* @default null
3333
*/
3434
framerate?: number | null
35+
36+
/**
37+
* Hooks are functions that are called at specific points in the engine's runtime.
38+
*/
39+
hooks?: {
40+
/**
41+
* Called before the engine's step loop.
42+
* @default () => { }
43+
*/
44+
beforeStep: () => void
45+
/**
46+
* Called after the engine's step loop.
47+
* @default () => { }
48+
*/
49+
afterStep: () => void
50+
}
3551
}

0 commit comments

Comments
 (0)