C++ object interaction - c++

I'm having a 2d world in c++ filled with animal-like entities for a program I'm writing. I have a world class, and and entity class (and a cascade of different kinds of entities inheriting from entity).
I want the entity to "know" which world its in and be able to interact well with the 2d array of entities, but I don't want it to inherit from world (after all, entities aren't worlds). So I'm just trying to get some ideas for a good way to implement this. I could of course have each entity contain a pointer to the world it's in, but it seems rather messy. Is there an easier way for an entity in a 2d array to "know" which world object contains it.
Is there any way in c++ for an object that's a member variable for another object to know the object that contains it?
Thanks!

Aggregation (supplying each entity with a world pointer) is the simplest solution. Another solution is to have a third mediator object which maintains pointers to worlds and entities, stores their relationship, and mediates (hence the name) the communication between them. This object could be a global singleton (most programmers will shudder but I don't think a few of these are a bad thing), or else every world and entity will need a pointer to it to communicate, which obviously isn't a big improvement on the first solution.

Assuming I've understood you correctly, an alternative to a world pointer in each entity is to give each world a unique id, then store that id in the entity as it is added to its world.

I have a world class
Oh dear.
That aside, what is your entity's meaningful interaction with its environment? Should it be able to query arbitrary information, see over the horizon, interrogate the state of other entities?
Or is it supposed to have some limited view, based on its location and attributes?
In the first case it is apparently a godlike entity, and mundane concerns such as encapsulation and separation of concerns don't apply.
In the second case, expose an interface (you can make it abstract to reduce coupling) which allows it to see only what it ought.
OK, so the second case could look something like
class World; // is a dumb container of entities
class Environment; // is an entity's window on the world
class Entity {
public:
void take_a_turn(Environment&) = 0;
};
class Environment {
public: // control what an entity can do to (see of) the World
container<const Entity*> visible_entities() const;
result attempt_to_eat(const Entity*);
result attempt_to_mate(const Entity*);
result run_away_from(const Entity*);
};
of course, if your Entity objects are active (ie, they run autonomously and continuously in their own threads), they need to keep a reference or pointer to the world or environment.
However, if you're just invoking them, one at a time, when they have a chance to do something, passing the reference in each time is fine.

For the world maybe you can create some kind of global engine. The engine will have systems and the world could be considered a system inside the engine. You would request from the engine the world system in the constructor of your entity and do what you need to inside there.
class World : public System
{
// info in here
}
class Engine
{
public:
World * getWorldSystem(); // Not as good
System * getSystem( std::string name ); // uses lookup, convert to right type
}
The problem with an engine class is "How do I reference it?" In most cases you would include the .h file for the engine which also has an:
extern Engine * ENGINE;
Inside of it, which is horrible I understand but with the engine/system architecture you have to have it somewhere. Or you use a singleton explicitly.
As for your inheritance tree maybe change your design scheme completely. Component based architecture might be a way for you to solve this problem.
While inheritance makes sense in a lot of situations building a component based entity will help you with the huge chain of weird types that each animal must have.
Take:
class Component
{
public:
Component();
virtual ~Component();
}
class WalkComponent : public Component
{
public:
Walk(); // Something here allows the entity to walk on the ground
}
class FlightComponent : public Component
{
public:
Fly(); // Something in here moves the entity around using flight
}
Right away you can see that you could attach a walk component and a flight component to the entity and it would have both, rather than trying to create an inheritance tree that allows both of those.

Related

Should I use static classes in an ECS?

Hey I am currently working on a small entity component system where there are classes like EntityManager, ComponentManager and SystemManager that are only instantiated once and heavily communicate with each other.
I created a class world which owns all the managers and acts as the center for all communication between the managers. Making all the Managers static would make a lot of things much easier, more understandable and I wouldn't even need the world class.
I know though that static classes (I know "static classes" don't exist but I mean classes with only static members) act as if they were global and global variables are Bad®.
So I wonder what is recommended to do in this case
Thanks for your answers
Che
Edit:
The World class looks like this:
class World
{
public:
EntityManager* entityManager;
ComponentManager<PositionComponent>* componentManager;
MovementSystem* movementSystem;
Entity e;
public:
World(sf::RenderWindow& window);
void update();
};
To communicate each Manager needs a pointer to the world to access the other managers. Like this world->entityManager->getEntitys()
(I suggest that the project is a game or something close to it)
I don't suggest you to make all members static. The main problem with it that you're loosing control on object's lifetime. You can't destroy and create new object at runtime easily because there is no object. For example, if you want to change a manager at runtime you'll have to implement cleanup code manually. In case of C++ objects C++ helps you with errors/warnings, default values and class members by value.
There are few popular ways to implement and use managers in gamedev:
Use Singleton pattern. In this case class have one static method that returns link to non-static object.
Pass dependencies that method requires during the method call manually.
Singleton pattern, I think, is the best way in terms of price-quality ratio for you. Despite on all criticism of this pattern it does its job well (most of game projects I saw used Singleton approach to implement manager classes).
There is an important thing I want to suggest you about this pattern. Don't use default implementation of Singleton pattern. Create methods for creating and destroying object instead of hiding it inside of getter. Here's simple example of glue code for a manager:
class Manager {
private:
static Manager* ms_manager;
public:
static void CreateManager() { ms_manager = new Manager(); }
static void DestroyManager() { delete ms_manager; }
static Manager* GetInstance() { return ms_manager; }
};
Usage is:
Manager::GetInstance()->SomeMethod();
Passing dependencies approach has its own advantages. It may sounds too difficult to pass everything in every Update method but it's not. You can create context class, set all dependencies there and pass it to every method that needs it. It's almost like your World class but it must be structure with minimum of code and no dependencies. Don't store there any game objects by value (only primitives, geometry vectors and stuff like this). It may be something like this:
struct Context {
EntityManager* entityManager;
ComponentManager<PositionComponent>* componentManager;
MovementSystem* movementSystem;
Entity* rootEntity;
};
Usage is:
GameObject::Update(Context& context) { context.entityManager->SomeMethod(); }
The point of this approach that you can tune context for some objects at runtime. For example, if you have LODs you can save in context current LOD level and change it at runtime for some objects depends on distance to the camera.

Preventing unauthorised use of components

I'm building a component system where an abstract type Component is inherited from to make components. So far, I have drawable, physical, movable and other components. All seems to go well, and in the Game class I perform the following:
void Game::init()
{
pPlayer->addComponent(pMovable);
}
void Game::processEvents()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
pMovable->moveUp(2.f);
// etc..
pPlayer->setVelocity(pMovable->getVelocity());
}
void Game::update()
{
pPlayer->update(0);
}
void Game::play()
{
while (pWindow->isOpen())
{
// ...
processEvents();
}
}
So far, the component system is really basic and simple. The player is of type Object and whenever I call the player's update function, I also have the Object's update function also called. This should really be automated, but that will change in the future. What the real problem is this:
pPlayer can still access pMovable's velocity even if it has not added pMovable as a component. This is problematic because it means anyone can simply get the velocity from pMovable and then plug it into their object without having to add pMovable as part of their component. Now, what does tend to happen is that the movement becomes unmanaged since there is no movable component to regulate it. I term this unauthorised use of the component, and I want to develop a way by which a component can 'deny' usage of its functionality to an object it is not owned by. There are many solutions to this problem, and I need one which is efficient and practical for use. Here are mine:
Throw an exception if the client attempts to allocate a component function into its own without adding it;
Create a system by which objects and components are identified and the component keeps track of the objects it is owned by, and the objects keep track of the components it owns. Because this is a many-to-many relationship, an intermediate class that manages all this would have to be created; it also avoids a circular header inclusion.
Have a function NOT part of an object simply 'deactivated'. This would require the use of a boolean like 'componentAdded' and all functions would have to check whether the component was added or not, else the function won't do what it ought to be doing.
If you have other solutions to prevent the unauthorised use of components, please share them as I'm keen to learn from others as to how they implemented/or would implement a component system as I have done here.
You can't prevent specific classes from inheritance. It's an all or nothing proposition: any class inherits from the base or none.
The best you can hope for is to narrow the interface. For example, instead of allowing decendents of Object in a function, you may want to have a class Stationary_Object or Enemy_Object to refine the interface. This allows you to write functions that take any Enemy_Object and won't take a Stationary_Object (like a tree or wall).
Edit 1: Cheating with friends
You can allow member access by declaring the members as private and granting access to specific classes using the friend class. The problem is that the class with data will need to be modified whenever a new type of friend is created. I believe this use of friendship defeats the purpose of reusability.
Edit 2: detecting ownership
Let's say we have three classes:
class Engine;
class Car
{
Engine car_engine;
};
class Boat
{
Engine boat_engine;
};
And a function:
void Fix_Car_Engine(Engine& e)
{
}
There is no method in C++ for the Fix_Car_Engine to know that it is fixing a car engine or a boat engine. The function only knows that it has been given a generic engine to fix (or it only knows about the common Engine stuff of the variable).
This issue can be mitigated by refining or narrowing the interface:
class Car_Engine : public Engine;
class Boat_Engine : public Engine;
class Car
{
Car_Engine diesel_engine;
};
class Boat
{
Boat_Engine propellor_engine;
};
In the above example, the Engine class has two specializations: Car_Engine and Boat_Engine. The Car now has a Car_Engine member and the Boat has a Boat_Engine.
The functions can now be created to operate on special engines:
void fix_boat_engine(Boat_Engine& be);
void fix_car_engine(Car_Engine& ce);
The fix_car_engine will now only work with Car Engines. You could say that it works on any class that has-a Car Engine (as long as you pass the Car Engine member). Likewise, the fix_boat_engine function only operates on Boat Engines.
Given:
class Rocket_Engine : public Engine;
Also, this specialization prevents a Rocket_Engine from being passed to either function. The functions require specific engine types.

Entity Systems in C++

In game development there is a notion of Entity System which is aiming to simplify the game loop by gaining a flexible architecture. For details see the links below:
http://www.richardlord.net/blog/what-is-an-entity-framework
http://shaun.boyblack.co.za/blog/2012/08/04/games-and-entity-systems/
Now I wonder how it is possible to realize automatic Node creation when a Component is added to an Entity in C++? Please tell me the principle of identifying what Nodes can be spawned from a specific Entity, i.e. you should have list of Component and classes that aggregate components. And you should understand what classes can be created with the list of data.
For example I have Components:
class PositionComponent
{
int m_x;
int m_y;
int m_rotation;
};
class VelocityComponent
{
int m_vX;
int m_vY;
int m_vAngular;
};
class RenderableComponent
{
Sprite m_view;
};
And nodes:
class MoveNode
{
PositionComponent m_position;
VelocityComponent m_velocity;
};
class RenderNode
{
RenderableComponent m_rend;
PositionComponent m_position;
};
Now if I create an Entity like this:
Entity * e = new Entity;
e.add(new PositionComponent);
e.add(new VelocityComponent);
Then I want to have a code that creates a MoveNode automatically, and if I add also this:
e.add(new RenderableComponent);
Then I want to know that also RenderNode is created. Consequently, when I delete it:
e.remove(new RenderableComponent);
the RenderNode should be deleted. And this process, of course, should not be bind to the specific Nodes and Components I have defined.
How is it possible to realize this in C++?
I am slightly confused, since it appears to mix concepts. I will try to shed some light on the two concepts.
Entity & Component
The entity component system is quite common in game engines, for example Unity implements it quite visibly. It tries to address the issue that simple inheritance does not work well in many cases, such as mixing rendering and collision information; is a Collidable also a Renderable? And since multiple inheritance is a scary thing for many and not supported in many languages, the only way out of this is the Entity/Component design. (Actually not the only solution, but that is a different issue.)
The design for entity component is quite simple, you have a class Entity that takes multiple objects of type Component. There will be multiple components that "do" something, like a MeshRenderer, TriMeshCollision or RigidBodyMotion. As stated in the articles, the actual logic does not need to be implemented in the components themselves. The component just "flags" the entity for specific logic. It makes sense to delegate the actual work to be done in a tight loop in a system, maybe even in a different thread, but more to that later.
Then the actual entity is composed. There are two basic ways to do this, in code or in data.
For example you compose objects in code that represent one "real world" object; the object of type Goblin exists and it is derived from the class Entity. The constructor from Goblin will then create all components and register them on itself. Inheritance is now only done for high level logic, for example the FastGoblin is derived from Goblin and only has a different material and speed setting.
The second way to create objects is through data, that is you have some form of object description language. (Take something in XML or JSON) This will then create in a factory method something based on a given template in that is defined in this object description language.
Node Based Work Scheduling
It may make sense to have objects that are fully defined, but the logic not being executed. Think about objects on the server or in the editor. On the server you do not want the rendering code to be in the way. So the basic approach is to create components that contain no data. The problem to solve is, how do you efficiently get things done without iterating through the entire scene each frame and typecasting the objects around?
What your second link describes is basically a botched version of Designing the Framework of a Parallel Game Engine
There needs to be a way to schedule the work in an efficient way. The proposed solution is to have "nodes" that each do a specific task. The nodes are then scheduled, by submitting them to either a work scheduler or a specific system.
Take for example rendering. You have an entity and it has a MeshRenderer component. This component will create a RenderNode and submit it to the RenderSystem. Then when it is time to render the frame the RenderSystem will simply iterate over each RenderNode and call its display method. In the display method the actual rendering is done.
Alternatively the system, engine or entity can create nodes based on specific component configurations. Take for example physics. The Entity has the TriMeshCollision and RigidBodyMovement components. The PhysicsSystem seeing this configuration creates a RigidBodyNode that takes the two components as inputs and thus implements rigid body motion. Should the entity only have a TriMeshCollision component the PhysicsSystem would then create a StaticColliderNode to implement the behavior.
But like the construction mechanic for components from data, the nodes can also be created and attached to the entity through a factory function. This can be part of either the object definition or a rule based system.
Mapping this design into C++ should be straight forward. The rather difficult bit is to figure out a way how the different bits get connected; for example, how the MeshRenderer gets access to the RenderSystem so it can submit its RenderNode. But this can be solved with a singleton (shudder) or by passing a Game/Engine object around at the construction of the Entity or Component.
Is this good design?
But the issue I want to address here is: Is this good design?
I have troubles with your second link (Games And Entity Systems), since I think the design will fall flat on its nose quite quickly. This is true for other aspects like physics, but this will become quite inefficient when considering modern 3D rendering.
When you need to organize the scene spatially to efficiently cull hidden objects, organize the objects into batches for lighting and reduce resource switching then the entire "list of nodes" concepts is moot since you need a separate organisational structure anyway.
At this point you can let the components "talk" directly to the systems and each system has its own unique specific API that is fit for its specific purpose. The requirements of rendering, sound and input are each significantly different and tying to cram them into on API is futile.
See Also
Entity/Component based engine rendering separation from logic

How to avoid having my GameManager class be friend with most stuff?

I'm writing a game for a video game course (which unfortunately taught nothing), and I'm having trouble designing the interactions between the game entities and the class that actually runs the game.
My problem reduces pretty much to this: assuming an entity has a position, it shouldn't be able to modify it directly (instead having to wait for the game manager to run a game step), but it should be able to access it, to run AI checks and so on.
My solution would be to create a Position class that is friend with GameManager, and to create an entity class like this
class Entity {
public:
Position & getPosition() { return pos_; }
private:
Position pos_;
};
So the manager would be able to modify the entities' positions but other classes would only be able to observe. However this reasoning would hold for lots and lots of other properties, and since the entity class is actually derived into a series of subclasses, which have more and more properties, I would have to put the friend attribute almost everywhere.
What would be a better approach to solve this problem?
The idea of identifying certain classes as friend and certain others as non-friend is not a good idea, for many reasons. What this means is that,
How this class is being used is also a concern of this class.
But this is not its concern at all. This class, whatever class is under consideration, should be designed to do its own responsibility.
Now, with your case, first of all you should decide on where the action/behaviour of changing position belongs to; does it belong to Entity, Entity Manager, or something else. For example, which of these two cases make more sense:
Entity changes its position from x1 to x2.
Entity Manager changes to position of Entity from x1 to x2.
Suppose you decided that this behaviour really belongs to Entity, rather than Entity manager (case 1). In that case, as is pointed out in the comments by #bengoesboom, it should provide a setter that users of the class can use to change its position.
Now, if you think that this class might be used in ways that is not desired, then you should enforce constraints and business rules within this class. For example (just a simple example), if you want to allow only certain range of values in an operation. You check the input, if it is not in the range, then you throw an exception.
Once, you have properly taken care of rules and constraints, then you don't care about who will use this class.

How to restructure this code hierarchy (relating to the Law of Demeter)

I've got a game engine where I'm splitting off the physics simulation from the game object functionality. So I've got a pure virtual class for a physical body
class Body
from which I'll be deriving various implementations of a physics simulation. My game object class then looks like
class GameObject {
public:
// ...
private:
Body *m_pBody;
};
and I can plug in whatever implementation I need for that particular game. But I may need access to all of the Body functions when I've only got a GameObject. So I've found myself writing tons of things like
Vector GameObject::GetPosition() const { return m_pBody->GetPosition(); }
I'm tempted to scratch all of them and just do stuff like
pObject->GetBody()->GetPosition();
but this seems wrong (i.e. violates the Law of Demeter). Plus, it simply pushes the verbosity from the implementation to the usage. So I'm looking for a different way of doing this.
The idea of the law of Demeter is that your GameObject isn't supposed to have functions like GetPosition(). Instead it's supposed to have MoveForward(int) or TurnLeft() functions that may call GetPosition() (along with other functions) internally. Essentially they translate one interface into another.
If your logic requires a GetPosition() function, then it makes sense turn that into an interface a la Ates Goral. Otherwise you'll need to rethink why you're grabbing so deeply into an object to call methods on its subobjects.
One approach you could take is to split the Body interface into multiple interfaces, each with a different purpose and give GameObject ownership of only the interfaces that it would have to expose.
class Positionable;
class Movable;
class Collidable;
//etc.
The concrete Body implementations would probably implement all interfaces but a GameObject that only needs to expose its position would only reference (through dependency injection) a Positionable interface:
class BodyA : public Positionable, Movable, Collidable {
// ...
};
class GameObjectA {
private:
Positionable *m_p;
public:
GameObjectA(Positionable *p) { m_p = p; }
Positionable *getPosition() { return m_p; }
};
BodyA bodyA;
GameObjectA objA(&bodyA);
objA->getPosition()->getX();
Game hierarchies should not involve a lot of inheritance. I can't point you to any web pages, but that is the feeling I've gather from the several sources, most notably the game gem series.
You can have hierarchies like ship->tie_fighter, ship->x_wing. But not PlaysSound->tie_fighter. Your tie_fighter class should be composed of the objects it needs to represent itself. A physics part, a graphics part, etc. You should provide a minimal interface for interacting with your game objects. Implement as much physics logic in the engine or in the physic piece.
With this approach your game objects become collections of more basic game components.
All that said, you will want to be able to set a game objects physical state during game events. So you'll end up with problem you described for setting the various pieces of state. It's just icky but that is best solution I've found so far.
I've recently tried to make higher level state functions, using ideas from Box2D. Have a function SetXForm for setting positions etc. Another for SetDXForm for velocities and angular velocity. These functions take proxy objects as parameters that represent the various parts of the physical state. Using methods like these you could reduce the number of methods you'd need to set state but in the end you'd probably still end up implementing the finer grained ones, and the proxy objects would be more work than you would save by skipping out on a few methods.
So, I didn't help that much. This was more a rebuttal of the previous answer.
In summary, I would recommend you stick with the many method approach. There may not always be a simple one to 1 relationship between game objects and physic objects. We ran into that where it was much simpler to have one game object represent all of the particles from an explosion. If we had given in and just exposed a body pointer, we would not have been able to simplify the problem.
Do I understand correctly that you're separating the physics of something from it's game representation?
i.e, would you see something like this:
class CompanionCube
{
private:
Body* m_pPhysicsBody;
};
?
If so, that smells wrong to me. Technically your 'GameObject' is a physics object, so it should derive from Body.
It sounds like you're planning on swapping physics models around and that's why you're attempting to do it via aggregation, and if that's the case, I'd ask: "Do you plan on swapping physics types at runtime, or compile time?".
If compile time is your answer, I'd derive your game objects from Body, and make Body a typedef to whichever physics body you want to have be the default.
If it's runtime, you'd have to write a 'Body' class that does that switching internally, which might not be a bad idea if your goal is to play around with different physics.
Alternatively, you'll probably find you'll have different 'parent' classes for Body depending on the type of game object (water, rigid body, etc), so you could just make that explicit in your derivation.
Anyhow, I'll stop rambling since this answer is based on a lot of guesswork. ;) Let me know if I'm off base, and I'll delete my answer.