Skip to content

Instantly share code, notes, and snippets.

@ooflorent

ooflorent/em.js Secret

Last active January 7, 2016 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ooflorent/84260ef9aa8498fb63b1 to your computer and use it in GitHub Desktop.
Save ooflorent/84260ef9aa8498fb63b1 to your computer and use it in GitHub Desktop.
function CompileFunction(body) {
return (new Function(`return (${body})`))()
}
function CompileEntityConstructor(props) {
return CompileFunction(`
function Entity() {
this._mask = 0
${props.map(prop => `this._${prop} = undefined`).join(";")}
}
`)
}
function CompileGetComponent(prop) {
return CompileFunction(`
function ${prop}$get() {
return this._${prop}
}
`)
}
function CompileSetComponent(prop, index) {
return CompileFunction(`
function ${prop}$set(component) {
if (component === null || component === undefined) {
this._${prop} = undefined
this._mask = this._mask & ${~(1 << index)}
} else {
this._${prop} = component
this._mask = this._mask | ${1 << index}
}
}
`)
}
function createManager(comps) {
class EntityManager {
constructor() {
this._pool = []
}
create() {
return this._pool.length > 0
? this._pool.pop()
: new Entity()
}
destroy(entity) {
this._pool.push(entity)
}
}
const keys = Object.keys(comps)
const Entity = CompileEntityConstructor(keys)
Entity.prototype.destroy = function () {
this._manager.destroy(this)
this._mask = 0
}
for (let i = 0; i < keys.length; i++) {
Object.defineProperty(Entity.prototype, keys[i], {
enumerable: true,
get: CompileGetComponent(keys[i]),
set: CompileSetComponent(keys[i], i),
})
}
const em = new EntityManager()
Object.defineProperty(Entity.prototype, "_manager", {
value: em,
})
return em
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment