From da7277b5e1502d4e6e474c6acb4b73aa1c924c6f Mon Sep 17 00:00:00 2001 From: Christian Treffs Date: Tue, 26 May 2020 15:03:31 +0200 Subject: [PATCH] Add all components sequence to entity --- Sources/FirebladeECS/Entity.swift | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Sources/FirebladeECS/Entity.swift b/Sources/FirebladeECS/Entity.swift index ccd6077..2b31389 100644 --- a/Sources/FirebladeECS/Entity.swift +++ b/Sources/FirebladeECS/Entity.swift @@ -125,6 +125,37 @@ public struct Entity { public var numChildren: Int { nexus.numChildren(for: self) } + + /// Returns an iterator over all components of this entity. + @inlinable + public func makeComponentsIterator() -> ComponentsIterator { + ComponentsIterator(nexus: nexus, entityIdentifier: identifier) + } + + /// Returns a sequence of all componenents of this entity. + @inlinable + public func allComponents() -> AnySequence { + AnySequence { self.makeComponentsIterator() } + } +} + +extension Entity { + public struct ComponentsIterator: IteratorProtocol { + private var iterator: AnyIterator + + @usableFromInline + init(nexus: Nexus, entityIdentifier: EntityIdentifier) { + if let comps = nexus.get(components: entityIdentifier) { + iterator = AnyIterator(comps.compactMap { nexus.get(component: $0, for: entityIdentifier) }.makeIterator()) + } else { + iterator = AnyIterator { nil } + } + } + + public mutating func next() -> Component? { + iterator.next() + } + } } extension Entity: Equatable {