aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorZack Mulgrew <zmulgrew@linkedin.com>2016-02-29 01:22:57 -0800
committerZack Mulgrew <zmulgrew@linkedin.com>2016-04-07 23:44:54 -0700
commite231a289306fadcda13093d47587613600ec2d89 (patch)
treee03a1c0c844f05d2df575c6b9ae76e8a0c30717a
parentceeddb88ba08e8a94f160246bb8562715a3203a5 (diff)
Allow Entity cloning via EntityManager::create_from_copy
-rw-r--r--entityx/Entity.h22
-rw-r--r--entityx/Entity_test.cc19
2 files changed, 41 insertions, 0 deletions
diff --git a/entityx/Entity.h b/entityx/Entity.h
index b55a45f..0f037b4 100644
--- a/entityx/Entity.h
+++ b/entityx/Entity.h
@@ -332,6 +332,7 @@ class BaseComponentHelper {
public:
virtual ~BaseComponentHelper() {}
virtual void remove_component(Entity e) = 0;
+ virtual void copy_component_to(Entity source, Entity target) = 0;
};
template <typename C>
@@ -340,6 +341,9 @@ public:
void remove_component(Entity e) override {
e.remove<C>();
}
+ void copy_component_to(Entity source, Entity target) override {
+ target.assign_from_copy<C>(*(source.component<C>().get()));
+ }
};
/**
@@ -566,6 +570,24 @@ class EntityManager : entityx::help::NonCopyable {
}
/**
+ * Create a new Entity by copying another. Copy-constructs each component.
+ *
+ * Emits EntityCreatedEvent.
+ */
+ Entity create_from_copy(Entity original) {
+ assert(original.valid());
+ auto clone = create();
+ auto mask = original.component_mask();
+ for (size_t i = 0; i < component_helpers_.size(); i++) {
+ BaseComponentHelper *helper = component_helpers_[i];
+ if (helper && mask.test(i))
+ helper->copy_component_to(original, clone);
+ }
+ return clone;
+ }
+
+
+ /**
* Destroy an existing Entity::Id and its associated Components.
*
* Emits EntityDestroyedEvent.
diff --git a/entityx/Entity_test.cc b/entityx/Entity_test.cc
index e07a567..9e75ee3 100644
--- a/entityx/Entity_test.cc
+++ b/entityx/Entity_test.cc
@@ -501,6 +501,25 @@ TEST_CASE_METHOD(EntityManagerFixture, "TestComponentAssignmentFromCopy") {
REQUIRE(!copy);
}
+TEST_CASE_METHOD(EntityManagerFixture, "TestEntityCreateFromCopy") {
+ Entity a = em.create();
+ a.assign<CopyVerifier>();
+ ComponentHandle<CopyVerifier> original = a.component<CopyVerifier>();
+ ComponentHandle<Position> aPosition = a.assign<Position>(1, 2);
+ Entity b = em.create_from_copy(a);
+ ComponentHandle<CopyVerifier> copy = b.component<CopyVerifier>();
+ ComponentHandle<Position> bPosition = b.component<Position>();
+ REQUIRE(original);
+ REQUIRE(original->copied == false);
+ REQUIRE(copy);
+ REQUIRE(copy->copied == 1);
+ REQUIRE(aPosition->x == bPosition->x);
+ REQUIRE(aPosition->y == bPosition->y);
+ REQUIRE(aPosition.get() != bPosition.get());
+ REQUIRE(a.component_mask() == b.component_mask());
+ REQUIRE(a != b);
+}
+
TEST_CASE_METHOD(EntityManagerFixture, "TestComponentHandleInvalidatedWhenComponentDestroyed") {
Entity a = em.create();
ComponentHandle<Position> position = a.assign<Position>(1, 2);