2018-11-25 17:44:32 +00:00
|
|
|
/* global performance */
|
|
|
|
import Screen from './screen'
|
|
|
|
import Input from './input'
|
|
|
|
import { ShaderManager } from './shader'
|
|
|
|
|
2019-12-28 16:35:25 +00:00
|
|
|
let gl
|
|
|
|
|
2018-11-25 17:44:32 +00:00
|
|
|
class Engine {
|
|
|
|
constructor () {
|
2019-12-29 02:20:57 +00:00
|
|
|
this.screen = Screen
|
2018-11-25 17:44:32 +00:00
|
|
|
this.input = new Input(this.screen.gl.canvas)
|
|
|
|
this.shaders = new ShaderManager()
|
|
|
|
this.running = false
|
|
|
|
|
|
|
|
// Queues
|
|
|
|
this.rst = []
|
|
|
|
this.ust = []
|
|
|
|
|
|
|
|
this.frameTime = 0
|
|
|
|
this.frameCount = 0
|
|
|
|
this.fps = 0
|
2019-02-26 12:02:12 +00:00
|
|
|
|
2019-12-28 16:35:25 +00:00
|
|
|
gl = this.screen.gl
|
|
|
|
}
|
|
|
|
|
|
|
|
static get GL () {
|
|
|
|
return gl
|
|
|
|
}
|
|
|
|
|
|
|
|
static get gl () {
|
|
|
|
return gl
|
2018-11-25 17:44:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
get gl () {
|
|
|
|
return this.screen.gl
|
|
|
|
}
|
|
|
|
|
2019-12-29 12:58:53 +00:00
|
|
|
prepare () {
|
2018-11-25 17:44:32 +00:00
|
|
|
// Set clear color to black, fully opaque
|
2019-12-28 20:51:31 +00:00
|
|
|
gl.clearColor(0.0, 0.0, 0.0, 1.0)
|
2018-11-25 17:44:32 +00:00
|
|
|
|
|
|
|
// Clear the color buffer with specified clear color
|
|
|
|
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
|
|
|
|
|
|
|
|
// Enable depth testing
|
|
|
|
gl.enable(gl.DEPTH_TEST)
|
|
|
|
|
|
|
|
// Enable back-face culling
|
|
|
|
gl.enable(gl.CULL_FACE)
|
|
|
|
gl.cullFace(gl.BACK)
|
2019-12-29 12:58:53 +00:00
|
|
|
}
|
2018-11-25 17:44:32 +00:00
|
|
|
|
2019-12-29 12:58:53 +00:00
|
|
|
render () {
|
2018-11-25 17:44:32 +00:00
|
|
|
// Render functions
|
|
|
|
for (let i in this.rst) {
|
|
|
|
this.rst[i](gl)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
update (dt) {
|
|
|
|
this.input.update()
|
|
|
|
|
|
|
|
// Updates
|
|
|
|
for (let i in this.ust) {
|
|
|
|
this.ust[i](dt)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
step () {
|
|
|
|
this.running && window.requestAnimationFrame(() => this.step())
|
|
|
|
|
|
|
|
this.render(this.gl)
|
|
|
|
|
|
|
|
let ts = performance.now()
|
|
|
|
let timeDiff = ts - this.frameTime // time difference in milliseconds
|
|
|
|
this.frameCount++
|
|
|
|
|
|
|
|
if (timeDiff > 0) {
|
|
|
|
this.fps = Math.floor(this.frameCount / timeDiff * 1000)
|
|
|
|
this.frameCount = 0
|
|
|
|
this.frameTime = ts
|
|
|
|
}
|
|
|
|
|
|
|
|
this.update(timeDiff / 1000)
|
|
|
|
}
|
|
|
|
|
|
|
|
addRenderFunction (fn) {
|
|
|
|
this.rst.push(fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
addUpdateFunction (fn) {
|
|
|
|
this.ust.push(fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
startGameLoop () {
|
|
|
|
if (this.running) throw new Error('Game Loop is already running!')
|
|
|
|
|
|
|
|
this.running = true
|
|
|
|
this.step()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-29 12:58:53 +00:00
|
|
|
export default new Engine()
|