Automatically add an object to a vector of that objects parent - c++

I am designing a game engine in c++. I am currently working on categorizing the different entities in the game. My base class is SpriteObject that two classes MovableObject and FixedObject inherit from. Now if i for example create an instance of a MovableObject and want to add it to a Vector of Sprite and a Vector of MovableObject i just do:
Vector<Sprite*> sprites;
Vector<MovableObject*> movableObjects;
MovableObject* movingObject = new MovableObject();
sprites.push_back(movingObject);
movableObjects.push_back(movingObject);
But as the different categories and entities grow the code will get large (and it would get tiresome to add every entity to every vector that it belongs to). How do i automatically add an object to the vector that it belongs to when it is created?
EDIT 1: I think i just came up with a solution, what if i just make a global static class Entities that holds all the vector of entities in the scene. Every entity could have access to this class and when a entity is created it just adds a pointer version of itself to the corresponding vector(s) in that global class.
EDIT 2: But i forgot that my solution requires me to still manually add every entity to its matching vector. I just split the work among the different entities.

This is a nice problem.
I think that I would implement it like this: There will be an addToVector() method in Sprite class, and each derived class will override it to add itself to the corresponding vector.

I would suggest a different approach. But before I start I would like to note one thing with your current design.
I would hide the creation of those objects behind a facade. Call it a scene or whatever. Using new manually is bad from a couple of perspectives. First of all if you decide you want to change the scheme on how you allocate/construct your objects you have to change it everywhere in the code. If you have a lets say a factory like Scene you just change the implementation and the calls to scene->CreateObject<Sprite>() will remain the same everywhere else. This might get important once you start adding stuff like custom memory allocation schemes, object pools etc and at some point you will if you will start to grow your engine. Even if this is just an excercise and a for fun project we all want to do this like its actually done, right ;) ?
Now going back to the core - dont abuse inheritance.
MovableObject is not a Sprite. Static Object is not a sprite either. They are that, movable and static elements.
A sprite can be movable or static, so it has a behavior of a dynamic or static element.
Use composition instead. Make a Sprite accepting behavior, or better a list of behaviors. In fact the Sprite itself is just a behavior on a Game object too, it just controls the way it is presented to the user.
What if you had an object that can be attached multiple behaviors like the fact it is a dynamic one, it has a sprite presence on the scene and even more is a sound emitter!
If you add those behaviors to the object you have to create them first. They can, when constructed, decide to which list they should subscribe to.
This is all metaphors for actually a well known system, that is proven to work well and is actually used in most game engines nowadays. Its a Entity Component System.
You object with behaviors are Entities, Components are those Behaviors and each of them is controlled by one system that knows the component and knows how to update/handle them.
Objects in the scene are merely a set of components attached to them that act upon them.

Related

Object propagation

I have a collection of objects, lets say QVector<ApplicationStates>, which registers the most important operations done in my software. Basically, this object is meant to process redo/undo operations.The application is built using a lot of delegated objects. Operations which have to be registered lie in a lot of these objects. As such, I am always passing my collection of objects, in each delegate under the form:
class AWidget : public QWidget{
AWidget(QVector<ApplicationStates>* states, QWidget* parent = nullptr);
...
It seems ugly to me. I think about two solutions:
Singleton;
Simply declare the QVector as a static global variable (I read that global variables are evil).
Does someone have a suggestion?
Thanks for your answers.
I get into a similar situation from time to time, and I have found simply wrapping your vector in a class called something like "ApplicationContext" then passing a shared pointer or reference to an instance of that around saves the day. It has many benefits:
You avoid the global / singleton, and you are free to in fact have several instances concurrently in the future
If you suddenly have more than just that vector of objects that you need to pass arround, simply extend your context class to add whatever you need
If your vector suddenly becomes a map or changes in other ways, you need not change any interfaces that pass it along such as the signals/slots. (You will need to change the implementation where the vector is used of course).
BONUS: The code becomes easily testable! You can now make test cases for this class.
This might not be the best solution in all cases, but I think it comes pretty close in this case!

Child/Parent structure with different classes in C++

I've decided to make my next game using my own simple engine. I've already written some code for object rendering, physics etc. and now I'm thinking about how to easily connect them together.
I want to make hierarchic structure with one master object, lets call it Scene which will have parent as Sprites or InteractiveObjects and every Sprite or InteractiveObject could have its own child which would have its own child.. I think you already got my point here :)
Let's assume, that every object type will inherit from some base object, let's call it Node for example. I'm not sure yet, if Node will be "real" object which will have its size, position etc. or only abstract wrapper for every object in game (I tend to option two actually).
And finally. My goal is, to have object of actual Scene, call something like Scene->Move(x,y) and it will move every child of Scene (or Sprite, InteractiveObject etc.). Or Scene->Render() and it will render every (renderable) child. If I create Sprite, I want to add child like Sprite->addChild() and child could be another Sprite, InteractiveObject or just simple Node.
And now my question. What's the best way to implement it with C++? Or am I totally wrong and this structure is stupid? :)
I should think that whether or not the structure is sensible depends somewhat on what you really want to achieve -- the system sounds very flexible, but usually there's a trade-off between flexibility and performance. Depending on the genre of the game, performance may be hard enough to come by.
Also, if all things derive from some BaseNode, they all need (although possibly empty) methods for all kinds of things whether or not they actually can be rendered, moved etc. Or you'd end up with lots of dynamic_casts, which isn't very nice either. It might therefore be better to have slightly less flexibility and differentiate between game entities and graphical entities, with the latter being part of the former (you might want to allow a game entity to be made up from multiple graphical entities, or sub-entities, though).
If you do go with your current architecture, I should think that each BaseObject has something like a vector and when you call, say, render() on a master object, it goes through all it's children and calls render on them. They do the same and do any render code that is appropriate to them.
Another question is, though, whether an object could feasibly be attached to several other objects (if there is a difference between rendering and physics, for example). If so, it can get hairy to know when to delete an object, unless you don't use plain BaseObject*, but some form of auto_ptr or shared_ptr.
I hope that this answer does help you a little, though I realise it's not a simple "this is they way!" one.

GUI application and singleton/dependency injection

I am working on an application with a GUI using wxWidgets. I got an object used as a "model": its data has to be used to draw the ui and the ui should modify it. Let's call this class Model.
The structure of the applications looks like this:
A wxApp-derived object, that possesses:
a wxFrame-derived object, that possesses a
wxGLCanvas-derived object.
another wxFrame-derived object.
For the Model class,
I could use a singleton that
would make things very simple: I
could just use model.getThatData()
or model.setThatData() anywhere.
However, I can't disagree when people
say that it's a global variable with
a fancy dress.
I could also use dependency
injection (or is it something
else): I instanciate Model in the
wxApp object, and then I pass a
reference to the instance model in
the constructors of both wxFrame-derived classes,
same thing with wxGLCanvas
constructor, and I store the
reference as an attribute of the
needed classes.
However, this doesn't seem either a
very good solution. Suppose the
first wxFrame object doesn't need
to use model. We will nontheless
have to pass a reference to model
in its constructor to be able to
pass it to the wxGLCanvas-derived
object. So that design could lead to
many (?) unnecessary passings.
?
What do you think ? I have been asking myself this question for a long time...
However, this doesn't seem either a very good solution. Suppose the first wxFrame object doesn't need to use model. We will nontheless have to pass a reference to model in its constructor to be able to pass it to the wxGLCanvas-derived object. So that design could lead to many (?) unnecessary passings.
Passing pointers around is peanuts compared to the nightmares of untangling the dependencies between classes/objects, hidden in the implementation (== singletons).
The #2 is the way I do it. The goal is to be able just by looking at the class declaration to have an idea about the class prerequisites. Ideally, if in the context I have everything what c'tor/init method needs, I should be able to instantiate and use the object. That way the life-cycle also becomes clear: the prerequisites may not be released until the object is released.
Does the frame dependent on a specific canvas class? Or the canvas object interchangeable?
If the latter is the case, then the constructor for the frame should be parameterized by a reference to a canvas object. This way, the application will take care of instantiating the model, creating the canvas using said model, and passing the canvas to the frame. The frame will no more be dependent on the model directly.
If the frame is dependent on a specific canvas class (that is, the frame instantiates its own canvas, and knows what type of canvas it wants). Then if the canvas' constructor is dependent on the Model object, by proxy your frame is also dependent on the model. So #2 is correct.
Put it into a simple MVC model. (Recall that C interacts with M and V, and M and V do not interact with each other.)
Your model is (obviously) the "M" in MVC. Your widgets are the "V" in MVC.
See the problem here? You're trying to give the "M" to the "V"; you're missing the "C" to delegate everything. Your "C" may be your wxApp (it depends on how you want to design things).
In other words, the controller should give the data the view needs from the model to the view; the view shouldn't grab its own data directly from the model.
(Therefore, both of your proposals are, in my opinion, poor options in an MVC application.)

Building an index: Copies or pointers?

I have a data structure that stores ... well, data. Now, I need to access various pieces of data in slightly different manner, so I'm essentially building an in-memory index. But I'm wondering: should the index hold pointers or copies?
To elaborate, say I have
class Widget
{
// Ways to access the list of gears...
private:
std::list<Gears> m_gears;
};
Now, I have two Widgets, and there exists between these two a mapping between their Gears. Currently, this is
boost::unordered_map<Gear, Gear>
but Gear is a fairly hefty class, and I feel like making so many copies is poor design. I could store a pointer, but then the mapping is only valid for the lifetime of the corresponding Widgets, and you start getting ->s... (And if that std::list ever changes to a std::vector, it gets more complex...)
Pertaining to the copies, it's actually slightly worse: There's two boost::unordered_maps, one for each direction. So, for each Gear, I'm making up to 2 copies of it.
Alternatively, I could put the index inside the Widget class, but I feel like this violates the responsibilities of the Widget class.
You might try Boost Pointer Container Library: http://www.boost.org/doc/libs/1_43_0/libs/ptr_container/doc/ptr_container.html
I think it addresses exactly the problem you are facing.
Could you store all gears in one place, like statically in the gears class, and then have each mapping AND widget store only the reference/index to it?
You would have to keep track of references to each gear so you know when you can dispose them, but that should be easy enough.

Maintaining a std::set<boost::shared_ptr>

I'm writing a game and an accompanying engine in C++. The engine relies heavily on automation using a simple embedded scripting language. Scripts can create object classes, define event listeners on them, and produce instances from them. At present, an instance must be bound to a script-global identifier in order to preserve its existence. The obvious result of this is that there can be no anonymous objects, which will be by far the most common.
At present, instances are managed using a std::set<Instance*, spatial_sort>, where spatial_sort is a functor that sorts instances by position, for rendering and collision detection. Instances are removed and re-inserted each frame using their current position as a hint, under the assumption that they're not likely to move a whole lot in a fiftieth of a second. If a dead flag is set in the instance, it is erased from the set. The Instance constructors and destructor invoke insert(this) and erase(this), respectively.
In order to allow anonymous instances, I want to change the set to a std::set<boost::shared_ptr<Instance>, spatial_sort>, which would allow Instance to share ownership of instances and preserve their existence until they destroy themselves. Unfortunately, because the calls to insert() need to be placed in the constructor, shared_from_this() won't work for obtaining a shared_ptr to the Instance. It doesn't matter at all that Instance happens to already inherit from boost::enable_shared_from_this<> via its base class.
Can anyone recommend a suitable workaround?
Edit:
I did what I should have been doing in the first place, and split the behaviour of the Instance class into two classes: Instance and Reference. The expression new SomeClass in a script then returns a Reference to a new Instance. The Instance objects themselves are never managed using a shared_ptr, so they are responsible for committing suicide in response to a suitable event, e.g., end of animation, end of level, etc.
Thanks for the help! Refactoring is as good a solution as any if it Just Works.
You could add a static method to Instance that you then use to create new objects and that also does the administrative stuff like adding it to the set:
static Instance* create(int something) {
boost::shared_ptr<Instance> sptr(new Instance(something));
instanceset.insert(sptr);
return sptr.get();
}
If you want to make this the only way to construct an object of this class you could also make the normal constructor private or protected.
For more on this see also the C++ FAQ Lite entry about "Dynamic binding during initialization", which is not directly related but uses the same technique to work around the restrictions on the use of virtual functions in constructors.