Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write efficient entity system like in C++

I'm trying to make an efficient "entity system" in C++, I've read a lot of blog/articles/documentation on the Internet to get lot of information but I've got some questions again.

I've find two interesting subjects:

  • Data-driven system
  • Entity component system

For me, the two systems look very similar.

So, I've found this example by Adam Smith: https://stackoverflow.com/a/2021868

I need to have a flexible system like this:

// Abstract class
class Component
{
     // data here
}

// exemple
class Car : public Component
{
    // Data here
}

// Entity with components
class Entity
{
   std::vector<Component*> components;
}

So, if my entity have the followings components: Car, Transform, Sprite, did my components array will had linear data like data-driven system?

Now, I have Systems:

class System 
{
     virtual void init();
     virtual void clear();
     virtual void update();

     std::unordered_map< const char*, Entity*> entities;
}

class RendererSystem : public System
{
    // Methods's definition (init, clear, …).

    void update()
    {
       for( entity, … )
       {
           Sprite* s = entity->getComponent('sprite');
           ...
       }
    }
}
  • I've read that virtual functions are bad, it's bad in that case?
  • Get component need a static_cast, that's bad?
  • In data-driven system, I saw pointer everywhere, si where is the "original" variables, I need to put new everywhere or I will have a class with an array of same data?
  • Did I make this right?

All this points look "blur" in my mind.

like image 445
Sooner Avatar asked Nov 13 '22 16:11

Sooner


1 Answers

  1. Virtual functions do have some overhead but nothing that you should care about unless you are doing millions of calls per second so just ignore that fact.
  2. A static cast is not bad by itself but it breaks static type checking where it is used so if you can move the behavior inside the object on which you cast so that you just call the appropriate method without having to know the specific runtime instance of an object then it's better
  3. It's not clear what you are asking, even if you have vectors of element in a data-driven approach, each element in the collections needs to be allocated with a new (if it's a pointer). Then once you allocated it you won't need to do it again as soon as you will pass the reference to the item around
like image 171
Jack Avatar answered Dec 18 '22 07:12

Jack