iMSTK
Interactive Medical Simulation Toolkit
imstkEntity.cpp
1 /*
2 ** This file is part of the Interactive Medical Simulation Toolkit (iMSTK)
3 ** iMSTK is distributed under the Apache License, Version 2.0.
4 ** See accompanying NOTICE for details.
5 */
6 
7 #include "imstkEntity.h"
8 #include "imstkComponent.h"
9 
10 namespace imstk
11 {
12 std::atomic<EntityID> Entity::m_count{ 0 };
13 
14 Entity::Entity(const std::string& name) : m_name(name)
15 {
16  m_count++;
17  m_ID = m_count;
18 }
19 
20 void
21 Entity::addComponent(std::shared_ptr<Component> component)
22 {
23  CHECK(component != nullptr) << "Tried to add nullptr component";
24  auto iter = std::find(m_components.begin(), m_components.end(), component);
25  if (iter != m_components.end())
26  {
27  LOG(FATAL) << "Tried to add component to entity twice";
28  return;
29  }
30  m_components.push_back(component);
31  component->m_entity = shared_from_this();
32  this->postEvent(Event(modified()));
33 }
34 
35 bool
36 Entity::containsComponent(std::shared_ptr<Component> component) const
37 {
38  auto iter = std::find(m_components.begin(), m_components.end(), component);
39  return iter != m_components.end();
40 }
41 
42 std::shared_ptr<Component>
43 Entity::getComponent(const unsigned int index) const
44 {
45  CHECK(index >= 0 && index < m_components.size()) <<
46  "Component with index does not exist, index out of range";
47  return m_components[index];
48 }
49 
50 void
51 Entity::removeComponent(std::shared_ptr<Component> component)
52 {
53  auto iter = std::find(m_components.begin(), m_components.end(), component);
54  if (iter != m_components.end())
55  {
56  (*iter)->m_entity = std::weak_ptr<Entity>();
57  m_components.erase(iter);
58  }
59  else
60  {
61  LOG(FATAL) << "Failed to remove component on entity, could not find " << m_ID;
62  }
63  this->postEvent(Event(modified()));
64 }
65 } // namespace imstk
Base class for events which contain a type, priority, and data priority defaults to 0 and uses a grea...
void removeComponent(std::shared_ptr< Component > component)
Remove component if it exists.
Definition: imstkEntity.cpp:51
Compound Geometry.
std::shared_ptr< T > getComponent() const
Get the first component of type T.
Definition: imstkEntity.h:84
static std::atomic< EntityID > m_count
current count of entities
Definition: imstkEntity.h:154
std::shared_ptr< T > addComponent()
Create and return a component on this entity.
Definition: imstkEntity.h:55
bool containsComponent() const
Check if contains component of type T.
Definition: imstkEntity.h:121