-
-
Save ooflorent/84260ef9aa8498fb63b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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