Skip to content

Instantly share code, notes, and snippets.

@planetis-m
Last active July 19, 2020 19:45
Show Gist options
  • Save planetis-m/7040f305d21b3953b41aff5d7e9201cf to your computer and use it in GitHub Desktop.
Save planetis-m/7040f305d21b3953b41aff5d7e9201cf to your computer and use it in GitHub Desktop.
const componentRegistry = CacheSeq"anymap.componentRegistry"
proc makeField(n: NimNode): NimNode =
let s = n.strVal
result = ident(toLowerAscii(s[0]) & substr(s, 1))
macro component*(s: untyped): untyped =
expectKind s, nnkTypeDef
result = copyNimTree(s)
componentRegistry.add result[0].basename
macro world*(s: untyped): untyped =
expectKind s, nnkTypeDef
result = copyNimTree(s)
if result[2][2].kind == nnkEmpty:
result[2][2] = newNimNode(nnkRecList)
template makeStorage(component): untyped =
seq[component]
for c in items(componentRegistry):
result[2][2].add newIdentDefs(c.makeField, getAst(makeStorage(c)))
when isMainModule:
type
Position {.component.} = object
x, y: float
Velocity {.component.} = object
x, y: float
Acceleration {.component.} = object
x, y: float
World {.world.} = object
registry: seq[uint16]
@planetis-m
Copy link
Author

planetis-m commented Jul 19, 2020

worth using this pattern instead:

proc `[]`(a: AnyMap, t: typedesc[Position]): seq[Position] =
   result = a.data0

proc `[]`(a: var AnyMap, t: typedesc[Position]): var seq[Position] =
   result = a.data0

proc main =
   var a: AnyMap
   let ent1 = 0'u16

   a[Position].add Position(x: 0, y: 0)
   a[Velocity].add Velocity(x: 1, y: 0)

   a[Position][ent1].x += a[Velocity][ent1].x
   a[Position][ent1].y += a[Velocity][ent1].y

   echo a[Position][ent1].x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment