Circular dependencies and better ways to do it? - c++

I really enjoy coding but currently every project I started has ended early due to the circular dependencies really messing with me and my head. I have been having problems, I am trying to make games, however due to my class structure I rely on some circular dependencies which cause problems in the end that almost always grow and go out of my control.
How I usually structure it:
class Game
class GameContext
class Window
class GameContext
class EventManager
class GameContext
class StateManager
class GameContext
I use this since I sometimes need to access for example the Window from the EventManager. In the end I always seem to lose it. Is there a better way for something like this that avoids circular dependencies? And if not how do you really go about thinking when you have to deal with them? I thought I understood them but clearly not.
What I am trying to archive is a centeral storage "Context" class which other classes could access but I do not know how to avoid circular dependencies in such a case.
To really show what I mean you can look at THIS, my latest failed atempt.
The problem I have with this current structure seems to be something to do with a dependency between the EventManager and the GameStateManager since in EventManager I get a error on GameStateID being undefined.

I managed to figure out my problem and it was more in the way of how I thought about it, I thought I wanted a structure like this:
class Game
class GameContext
class Window
class GameContext
class EventManager
class GameContext
But what I actually wanted was:
class Game
class Window
class EventManager
class GameContext
Where every every class except GameContext contains a pointer to a GameContext.
Also one of my problems was my understanding of forward declaration, I did not understand them and mixed and spread them everywhere because I thought it was magic.

Related

Level Editor Import Objects (Classes)

i was working on making my own game tools in c++ to expand my knowledge on problem solving. But i was stuck thinking on the design of my level editor. I want to be able to import any header that by default will be assumed to contain one class and instantiate an object from it. Now i don't know how to allocate those custom classes on the scene as each class is considered different from the others so i can't use a vector to put them all there.
Now i wanted to know whether making a base class like EmptyGameObject and then making each class inherit from it will solve the problem.
But then i encountered another problem.
How do we construct a class depending on its name ?
like:
class name : CustomClass, imported from custom_class.h
thanks you for your help in advance.

C++ classes hierarchy design choice

In my simulation I have different objects that can be sensed in three ways: object can be seen and/or heard and/or smelled. For example, Animal can be seen, heard and smelled. And piece of Meat on the ground can be seen and smelled but not heard and Wall can only be seen. Then I have different sensors that gather this information - EyeSensor, EarSensor, NoseSensor.
Before state: brief version gist.github.com link
Before I started implementing NoseSensor I had all three functionality in one class that every object inherited - CanBeSensed because although classes were different they all needed the same getDistanceMethod() and if object implemented any CanBeSensed functionality it needed a senseMask - flags if object can be heard/seen/smelled and I didn't want to use virtual inheritance. I sacrificed having data members inside this class for smell, sounds, EyeInfo because objects that can only be seen do not need smell/sound info.
Objects then were registered in corresponding Sensor.
Now I've noticed that Smell and Sound sensors are the same and only differ in a single line inside a loop - one calls float getSound() and another float getSmell() on a CanBeSensed* object. When I create one of this two sensors I know what it needs to call, but I don't know how to choose that line without a condition and it's inside a tight loop and a virtual function.
So I've decided to make a single base class for these 3 functionality using virtual inheritance for base class with getDistanceMethod().
But now I had to make my SensorBase class a template class because of this method
virtual void sense(std::unordered_map<IdInt, CanBeSensed*>& objectsToSense) = 0;
, and it meant that I need to make SensorySubSystem class(manages sensors and objects in range) a template as well. And it meant that all my SubSystems like VisionSubSystem, HearingSubSystem and SmellSubSystem inherit from a template class, and it broke my SensorySystem class which was managing all SensorySubSystems through a vector of pointers to SensorySubSystem class std::vector<SensorySubSystem*> subSystems;
Please, could you suggest some solution for how to restructure this or how to make compiler decide at compile time(or at least decide once per call//once per object creation) what method to call inside Hearing/Smell Sensors.
Looking at your original design I have a few comments:
The class design in hierarchy.cpp looks quite ok to me.
Unless distance is something specific to sensory information getDistance() doesn't look like a method that belongs into this class. It could be moved either into a Vec2d-class or to a helper function (calculatePositon(vec2d, vec2d)). I do not see, why getDistance() is virtual, if it does something different than calculating the distance between the given position and the objects position, then it should be renamed.
The class CanBeSensed sounds more like a property and should probably be renamed to e.g. SensableObject.
Regarding your new approach:
Inheritance should primarily be used to express concepts (is-a-relations), not to share code. If you want to reuse an algorithm, consider writing an algorithm class or function (favour composition over inheritance).
In summary I propose to keep your original class design cleaning it up a little as described above. You could add virtual functions canBeSmelled/canBeHeard/canBeSeen to CanBeSensed.
Alternatively you could create a class hierachy:
class Object{ getPosition(); }
class ObjectWithSmell : virtual Object
class ObjectWithSound : virtual Object
...
But then you'd have to deal with virtual inheritance without any noticeable benefit.
The shared calculation code could go into an algorithmic class or function.

Mutual inclusion with singleton

I currently have a problem with mutual inclusion in a project of mine (C++).
Normally, if I had a mutual inclusion problem, I'd easily solve it by either forward declaration or redesigning the classes a bit. But this time, I'm stuck:
I have a class called Game, which creates and launches core game systems, where one of these is called GraphicsSystem.
In the Game constructor, a GraphicsSystem object is dynamically created and stored in a GraphicsSystem* pointer. Looks like this:
Game::Game ()
{
gfxSys = new GraphicsSystem(80, new Camera());
}
Now my GraphicsSystem class needs to access a Game class's method at one point to get the player object, which is stored within the Game object. The respective part looks like this (Game is btw a singleton!):
void GraphicsSystem::handleFrame ()
{
ElementList elements = Game::instance()->getPlayer()->getEnvironment()->getElements();
}
Now I tried forward declaration in both directions already, but that wouldn't satisfy the compiler. I could of course also just put the player pointer into the graphics system, but I really don't want to do that, since he doesn't belong there.
Is there any way to resolve this without me having to change the design too much? I'm really stumped right now, so I hope you guys can help me.
I'm using Visual Studio 2010 (Visual C++).
Thank you in advance!
Chris
Forward declare GraphicsSystem in Game.h. Include Game.h in GraphicsSystem.h if it needs it. Include Game.h and GraphicsSystem.h in Game.cpp. Include Game.h and GraphicsSystem.h in GraphicsSystem.cpp.
That should work based off the code you posted.
There are two main ways to break circular dependencies in C++.
1) Create a 'interface' class which lists the methods implemented by your real class and which your real class inherits from. Then you can include that instead of the declaration of the real class.
2) Pimpl - a class holds an opaque pointer to its real data, solving the problem of having to include declarations for the types of member variables.
I know this is going to sound dodgy, but have you considered holding a global reference to the initialized Game class?
I know globals are evil and so on and so forth, and I'm sure lots of people are going to rage, but in my personal experience I have succumb to Singletonitis with the Game class (among others) and found that sometimes it just simply isn't necessary.
The biggest question you need to ask yourself is "Who are you trying to protect your Game object from? and is there any reason why you need to request an instance each time you need the game class? I'm pretty sure that if your Game object wasn't initialized, you wouldn't be doing much else in your engine anyway.
Hope this might help you think about things in a different way, even though it's not answering your question directly.

C++ Game - Signalling a parent class, circular dependency issue

I'm having a little circular-dependency problem. It works fine, but it makes for ugly-seeming code. It's in the context of a Snake game.
I have a class, Snake, which contains a vector of SnakeSegments, and manages their interaction (for instance moving and growing as a unit, rather than as separate entities).
When a SnakeSegment collides with a Food object, it flips its hasEaten member to true. The Snake routinely queries the SnakeSegments, essentially for this member. If any of the queries return positive (i.e. one has hit food), then the Snake will grow as a unit (i.e. expand the head and shrink the tail). This is all fine and good, but I'd much prefer a more signal-based approach, where, when a SnakeSegment hits food, it sends an alert (signal, interrupt, etc.) to the Snake class, which tells it to grow. This means I wouldn't have ugly code in my Snake's Update function, checking all the segments; and I would instead have an OnEat() function in my Snake class.
However, this leads to circular dependencies; the Snake contains a vector of SnakeSegments, and the SnakeSegments have a Snake& or Snake* member, which tells them whom to alert when they eat. In the code, I essentially just have to pre-declare the Snake class:
class Snake;
class SnakeSegment
{
...
Snake* alertOnEat;
...
};
and my Snake class just works normally
#include "SnakeSegment.hpp"
class Snake
{
...
std::vector segments;
...
void OnEat();
...
};
Are there any nicer designs to this? Note that it isn't just a problem occuring here; a similar problem occurs in a number of areas (e.g. the GameWorld contains a Snake member, and the Snake alerts the GameWorld when it dies), so a solution specific to Snake and SnakeSegment isn't what I'm looking for.
Your current design is perfectly fine in most situations. Yes, it creates a circular dependency, but it also is the simplest and the clearest way to do it.
However, you should limit those dependencies between interfaces or base classes rather than to the derived classes directly. The world-snake dependency is a good example. You probablly don't necessarily want the World class to know about all the possible game object types. However, what you can do is derive all your game objects from a common GameObject class and make World and GameObject interdependant.
There are also more complicated ways to avoid dependencies all with their pros and cons, they mostly differ on the level of separation and clarity. Among those, function pointers, delegates, observers, listerners, functors, etc.
In the end, it always come down to how much complexity you are ready to introduce to your architecture in exchange of flexibility and clear separation of concerns.
Never forget that design is compromise.
What you may want to look at for this problem is the Observer/Observable design pattern. It allows you to create objects that observe (Snake) observable objects (SnakeSegment) and get notified right away when their state has changed.
Wikipedia has a good example of it written in many languages including C++.
It's a common pattern used in a lot of GUI development so the View layer can change when any of the underlying Model data changes.

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.