Last active
December 16, 2015 22:29
-
-
Save fowlmouth/5506957 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import fowltek/vector_math | |
type | |
TVector2f = TVector2[float] | |
TPos = TVector2f | |
TVel = TVector2f | |
PSprite = ref object | |
TComponent = enum | |
CPos, CVel, CSprite | |
const | |
componentSizes: array[TComponent, int] = [sizeof(TPos), sizeof(TVel), sizeof(PSprite)] | |
discard """ | |
given a new entity with position, sprite: | |
typeinfo = [ | |
2 (size), | |
cpos, 0, | |
csprite, sizeof(tpos), | |
#nextcomponent, sizeof(tpos)+sizeof(psprite) | |
] | |
entity data = [vector2(0.0, 0.0), spriteinstance] | |
""" | |
type | |
PTypeInfo* = ptr TTypeInfo | |
TTypeInfo* = object | |
components: int | |
data: array[0 .. <1024, TTypeInfoEntry] | |
TTypeInfoEntry = tuple[comp: TComponent, offset: int] | |
TEntity = tuple[id: int, typeinfo: PTypeInfo] | |
TEntityManager = object | |
entityData*: seq[cstring] | |
proc newTypeInfo(components: varargs[TComponent]): PTypeInfo = | |
let compCount = components.len | |
result = cast[PTypeInfo](alloc0((compCount * sizeof(TTypeInfoEntry)) + sizeof(int))) | |
result.components = compCount | |
var acc = 0 | |
for i in 0 .. high(components): | |
result.data[i] = (components[i], acc) | |
inc acc, componentSizes[components[i]] | |
proc newEntity (em: var TEntityManager; components: varargs[TComponent]): TEntity = | |
result.typeinfo = newTypeinfo(components) | |
# reserve an id and data space for entity | |
proc getComponent[A](entityManager: var TEntityManager; ent: TEntity, component: TComponent): ptr A = | |
for i in 0 .. <ent.typeInfo.components: | |
template thisData: expr = ent.typeInfo.data[i] | |
if thisData.comp == component: | |
return cast[ptr A](entityManager.entityData[ent.id][thisData.offset].addr) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's very easy to associate a numeric ID to each component type:
In C++, I used to do it like this
In nimrod, one way to do it is like this:
This is still a run-time way to assign the IDs. For a Nimrod
implementation, I planned to switch to compile-time methods.
With this association in place, getComponent becomes:
Now let's get back to defining the types that can support this
Finally, let's look at some procs for creating objects