Skip to content

Commit 6a3a3ac

Browse files
authored
Merge pull request #21 from ineka-dev/feature/hooks
Engine hooks
2 parents 4112003 + 8e4cafc commit 6a3a3ac

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

.changeset/few-schools-explain.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@ineka/engine": minor
3+
---
4+
5+
Added hooks to execute code at engine's key locations

src/core/Engine.ts

+26
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: async () => { },
68+
afterStep: async () => { },
69+
},
6670
...options,
6771
}
6872
this._container = document.querySelector(this._options.container as string) as HTMLElement
@@ -98,6 +102,17 @@ 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+
catch (err) {
113+
console.error(err)
114+
}
115+
101116
if (!this.rootNode) {
102117
throw new EngineError(this, 'ENGINE:FAILURE', 'No root node given to engine, cannot run.')
103118
}
@@ -118,6 +133,17 @@ export class Engine {
118133
system.step(this.time.delta)
119134
})
120135
this.rootNode.step(this.time.delta)
136+
// Call afterStep hook
137+
try {
138+
if (!this.options.hooks || !this.options.hooks.afterStep) {
139+
throw new EngineError(this, 'ENGINE:FAILURE', 'No afterStep hook given to engine.')
140+
}
141+
this.options.hooks.afterStep()
142+
}
143+
catch (err) {
144+
console.error(err)
145+
}
146+
121147
// Request next step
122148
requestAnimationFrame(this.step.bind(this))
123149
}

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 async () => { }
43+
*/
44+
beforeStep: () => Promise<void>
45+
/**
46+
* Called after the engine's step loop.
47+
* @default async () => { }
48+
*/
49+
afterStep: () => Promise<void>
50+
}
3551
}

0 commit comments

Comments
 (0)