design issue, base class knows its derivative - c++

Basically I have a base class called Geometry, and some derivative such as Point, Polygon, etc...
Geometry implements a method intersection like this :
Geometry* intersection(Geometry* other)
{
Geometry* inter = compute_intersection(this, other);
if (inter is a polygon)
return new Polygon(inter);
if (inter is a point)
return new Point(inter);
}
When I compute the intersection of two geometries in my program, I obtain a Geometry* and I can dynamic_cast it to whatever it really is.
Is it a good design ? What, I think, might be wrong is that I have to check real type each time I compute an intersection and dynamic_cast the result (which can be slow). But what I think is the main problem is that with this design, Geometry must know its derivative (Point, Polyline? etc...).
What could be a good solution to avoid these problems ?

Why do you need to construct a new object of the returned object, can't you jsut return it straight away? If you can not, just implement one additional method in each derivative class that wraps the result from compute_intersection in a new object and call this new method instead of compute_intersection in Geometry.
In my answer I assume the only possible situation: compute_intersection is abstract and each deriving class implements it.

If you find yourself needing to new according to inherited type to copy objects, then you can use virtual copy constructors, by implementing a clone() function that returns a copy of the object:
virtual Obj* Obj::clone() const { return new Obj(*this); }
This can be called from your intersection() function.

There are two issues here as far as I'm concerned.
Firstly, I don't care much for functions which get/set things. I'm more interested in telling objects to do something for me.
Secondly, you are trying to implement multiple dispatch (in this case double dispatch). This is where the behaviour you want depends upon the types of multiple objects.
My normal mantra of encapsulate, encapsulate, encapsulate guides me towards the following ideas:
Encapsulate what you want to do with the intersection e.g.
Put its area into a spreadsheet cell
Add geometry points to a display list
Encapsulate the dispatch of one type given another type
Look into the visitor pattern
Encapsulate applying the behaviour to an intersection

Perhaps you can use boost::variant:
typedef boost::variant<Point, Polygon/*, and other...*/> Geometry_Variants;
Geometry_Variants intersection(Geometry_Variants const& other)
{
// compute the intersection and return Point or Polygon
}

Your problem is known under the name: multiple dispatch or multi methods. There is no real good answer to this problem in C++ as far as I know. A good discussion of this problem by Andrei Alexandrescu is here:
http://books.google.fr/books?id=aJ1av7UFBPwC&pg=PA263&lpg=PA295&dq=modern+c%2B%2B+design+multiple+dispatch&source=bl&ots=YRdIZrWiaV&sig=2Vj0Blst_jmhMCAZIJ8gUiG_pl4&hl=fr&sa=X&ei=082XT86RHNS18QPW7f3mBQ&ved=0CCYQ6AEwAA#v=onepage&q&f=false
I recommend you to buy the book it's worth its price.

Related

How to check collision in geometric base classes without casting to derived ones

I've this situation:
class Shape{};
class Triangle : public Shape{};
class Rectangle : public Shape{};
class Square : public Rectangle{};
I want to implement a virtual collideWith method in the base class that works this way:
Shape *square = new Square();
Shape *triangle = new Triangle();
bool test = square.collideWith(triangle);
Is there a way to implement this method in order to work with base class without explitit casting do derived classes?
I've thinked to create a namespace that do it:
namespace Collision {
bool isCollisionBetween(const Triangle &triangle, const Square &square) {/* calculus */}
bool isCollisionBetween(const Rectangle &rect, const Square &square) {/* calculus */}
// and so on for all combination
}
But then I don't know how I can apply this when I have something like
std::set<Shape*> shapesSet;
and I want to calculate all collision for this set.
Is it possible or it's always necessary to explicity cast Shape class to the right inherited one?
In general you would solve a problem like this as follows:
Give Shape an abstract function describing the shape, that each subclass must implement.
Each subclass implements this function based on the specific type it is.
A collideWith() function in Shape uses the abstract function of two types to determine the property.
This way when a shape is added, none of the other shapes need to be changed and you don't have to add a function to compare it with each other shape. Only the new shape has to provide functions for all required properties.
Now the difficult part is to decide what property each shape can provide. And in your case it might be difficult to provide it with an efficient implementation.
Examples of properties you can use to provide a collision detection are:
polygonRepresentation()
asVectorGrahpic()
convertToBitMap()
As you can imagine, in your problem, it might be difficult to find a proper representation suitable for each item. Then you probably have to revert to comparisons that know all the elements. But this is really an anti Object Oriented pattern, and will lead to trouble when the amount of shapes or properties increases.
ok, my comment was a little bit missleading you. What I meant was:
To create the collisionInformation make something like a "BroadPhase" (This is optional but very helpful). Consider it as a precheck if potential shapes are colliding. Google therefore "Binary Space Partition". Forget about Quad- or Octtrees at this time. This phase will create a potential contact and their information. Ask your self: which shapes are colliding? which collision resolve function am i calling? Should I use polymorphism or function pointers? (i.e calling a function pointer to a static bool CollisionResolver::handle( Box b, Circle c ); which can be retrieved/called through collisoinInformation ). What callback am I calling if there is a collision? Save all this info to this collisoinInformation object
Create your different collision handle functions to treat collisions between different shapes. Iterate your i.e std::vector saving your collisionInformation and call ( a now imaginary function) colIter->resolve() which is calling the right implementation of your collision handle functions. If you found a collision ask yourself: Which functions will I call? What information could I provide? i.e stuff additional information into your collisoinInformation or maybe create a new object collisionPair etc... You could save collision point, normal, the shapes....
Collision detection was successfully an is calling "saved" callbacks to your final gameObjects. i.e you could call GameObject::OnCollision( const ContactPair& p );
Hope this helps you a little bit more than my previously added comment
ps: A good tip for starters: Look behind the scenes of current open source implementation. i.e ODE or PhysX

Alternate ways to identify polymorphic objects?

I've been searching all through the web and I seem to not find any alternate way of doing comparing if two polymorphic objects are the same type, or if a polymorphic object IS a type. The reason for this is because I am going to implement a Entity System inside of my game that I am currently creating.
I have not found another way of doing this other than with the use macros or a cast (the cast not being a portable method of doing so). Currently this is how I am identifying objects, is there a more efficient or effective way of doing this? (without the use of C++ RTTI)
I pasted it on pastebin, since pasting it here is just too much of a hassle.
http://pastebin.com/2uwrb4y2
And just incase you still do not understand exactly what I'm trying to achieve, I'll try to explain it. An entity in a game is like an object inside of the game (e.g. a player or enemy), it have have components attached to it, these components are data for an entity. A system in the entity system is what brings the data and logic of the game together.
For example, if I wanted to display a model up on the screen it would be similar to this:
World world; // Where all entities are contained
// create an entity from the world, and add
// some geometry that is loaded from a file
Entity* e = world.createEntity();
e->add(new GeometryComponent());
e->get<GeometryComponent>()->loadModel("my_model.obj"); // this is what I want to be able to do
world.addSystem(new RenderingSystem());
// game loop
bool isRunning = true;
while(isRunning)
{
pollInput();
// etc...
// update the world
world.update();
}
EDIT:
Here's a framework, programmed in Java, that does mainly what I want to be able to do.
http://gamadu.com/artemis/tutorial.html
See std::is_polymorphic. I believe boost has it too.
If T is a polymorphic class (that is, a class that declares or inherits at least one virtual function), provides the member constant value equal true. For any other type, value is false.
http://en.cppreference.com/w/cpp/types/is_polymorphic
Edit:
Why can't you just do this in your example?
Entity* e = world.createEntity();
GemoetryComponent* gc = new GeometryComponent();
gc->loadModel("my_model.obj");
e->add(gc);
Create the structure before stripping the type information.
If you're determined not to use C++'s built-in RTTI, you can reimplement it yourself by deriving all classes from a base class that contains a virtual method:
class Base {
public:
virtual string getType() = 0;
};
Then every derived class needs to overload this method with a version that returns a distinct string:
class Foo : public Base {
public:
string getType() { return "Foo"; }
};
You can then simply compare the results of calling getType() on each object to determined if they are the same type. You could use an enumeration instead of a string if you know up front all the derived classes that will ever be created.
Entity* e = world.createEntity();
e->add(new GeometryComponent());
e->get<GeometryComponent>()->loadModel("my_model.obj");
// this is what I want to be able to do
First the simple: there is a base type to all of the components that can be added, or else you would not be able to do e->add(new GeometryComponent()). I assume that this particular base has at least one virtual function, in which case the trivial solution is to implement get as:
template <typename T>
T* get() {
return dynamic_cast<T*>(m_component); // or whatever your member is
}
The question says that you don't want to use RTTI, but you fail to provide a reason. The common misundertandings are that RTTI is slow, if that is the case, consider profiling to see if that is your case. In most cases the slowness of dynamic_cast<> is not important, as dynamic_casts should happen rarely on your program. If dynamic_cast<> is a bottleneck, you should refactor so that you don't use it which would be the best solution.
A faster approach, (again, if you have a performance bottleneck here you should redesign, this will make it faster, but the design will still be broken) if you only want to allow to obtain the complete type of the object would be to use a combination of typeid to tests the type for equality and static_cast to perform the downcast:
template <typename T>
T* get() {
if (typeid(*m_component)==typeid(T))
return static_cast<T*>(m_component);
else
return 0;
}
Which is a poor man's version of dynamic_cast. It will be faster but it will only let you cast to the complete type (i.e. the actual type of the object pointed, not any of it's intermediate bases).
If you are willing to sacrifice all correctness (or there is no RTTI: i.e. no virtual functions) you can do the static_cast directly, but if the object is not of that type you will cause undefined behavior.

Adding numerical integration to objects that update their physical state

I considered this scenario: objects that roughly look like this:
class PhyisicalObject
{
private:
virtual void Update() = 0;
friend class PhysicsController;
void DoUpdate() { this->Update(); }
};
There's a controller class called a PhysicsController that manages the dynamics of a pool of physical objects by calling their DoUpdate() method. This method, in terms, calls an overloaded version of the Update()function where a numerical integrator is used to compute the objects position, velocity and acceleration step-wise. I thought that having an interface implying this functionality would be a good starting point:
class IIntegrator
{
virtual void opertor() (const vec3& pos, const vec3& vel, vec3& outPos, vec3& outVel);
};
Now inheriting this IIntegrator abstract class and providing the implementation for various methods is the next step (explicit Euler, RK4, Verlet, Midpoint, Symplectic Euler and perhaps some semi-implicit/IMEX or implicit ones would be excellent). The problem is that I don't see clearly how to do the following two things:
Each physical object computes its own acceleration at any of its vertices in different ways (considering the objects consist of masspoints connected through springs or some kind of constraining objects). This function must be passed to the integrator, but it is object specific. It is possible to get pointers to non-static methods, but how would this fit the IIntegratorinterface?
When an object calls its Update() method, what happens behind the scenes is that an integrator is used to provide the functionality. I'd like to switch the integration method on the fly, perhaps. Or at least instantiate the same kind of object with different integrators. To me, it sounds like a factory doing that and, for on-the-fly integrator switching.. perhaps a strategy pattern? What solution would be quite elegant and efficient in this context?
Without going into implementation details, here are a few design patterns that might be applied to your problem
Factory or Prototype To create objects at startup from a file, or clone them during run-time, respectively.
Composite This might be used to model PhysicalObjects, either as stand-alone objects or collections connected by strings, springs or gravitational forces.
Iterator or Visitor This might be used by PhysicsController to iterate over all physical objects (composite or stand-alone) and apply a function over them.
Strategy To select different IIntegrator objects and their integration functions at runtime.
Apart from the GoF book (Amazon), a good online resource is here

Inheritance/interface decisions for physics engine

This is for a small game project with SDL on MinGW/Windows.
I am working on a physics engine, and my idea was to have a Physics::Object, which all physical objects should derive from and it registers itself with a global Physics::System class (it's a monostate pattern) so that the user doesn't need to track which objects are included in physics calculations and just needs to call a function like Physics::System::PerformTimestepCalculation(double dt).
This works fine, and I even implemented it using a single derived class Physics::Circle, which is a 2d circle. I was pretty happy with the predictive collision detection, even though I still need to optimise it.
Anyway, I ran into trouble when I started adding other primitives to include in the calculation, e.g. line. The Physics::System::PerformTimestepCalculation(double dt) became littered with calls to Object::GetID() or similar functions (may way to avoid dynamic_cast<>), but I feel dirty.
I did a bit of reading and realised that my the elements of my hierarchy are not substitutable (i.e. the collision between two circles is very different between the collision of two lines).
I like the way my Physics::Objects "self register" with the System class so they automatically get included in the calculations, and I don't really want to lose this.
There must be some other sensible design paths. How can I better redesign things so non-substitutable objects do not get in the way?
Edit FYI:
In the end I have broken away entity and shape properties, similar to how it was described in the accepted answer, and similar to an entity-component-system model. It means I still have the yuk logic of "is this a circle or a line, and is that a line or a circle?", but I'm no longer pretending that polymorphism helps me here. It also means I use some sort of factory and can have multiple calculation worlds happening at once!
The most successful publically available physics engines are not very heavy on the 'patterns' or 'object oriented design'.
Here's a rundown to back up my, admittedly bold, assertion:
Chipmunk - written in C, enough said.
Box2d - Written in C++, and there is some polymorphism here. there's a hierarchy of shapes (base class b2Shape) with a few virtual function. That abstraction leaks like a sieve, though, and you'll find lots of casts to leaf classes throughout the source code. There's also a hierarchy of 'contacts', which proves more successful, although with a single virtual function it would be trivial to rewrite this without polymorphism (chipmunk uses a function pointer, I believe). b2Body is the class used to represent rigid bodies, and it is non-virtual.
Bullet - Written in C++, used in a ton of games. Tons of features, tons of code (relative to the other two). There's actually a base class that the rigid body and soft body representations extend, but only a small part of the code can make any use of it. Most of the base class's virtual function relate to serialization (save/load of the engine state), of the two remaining virtual functions soft body fails to implement one with a TODO informing us that some hack needs to be cleaned up. Not exactly a ringing endorsement of polymorphism in physics engines.
That's a lot of words, and I haven't even really started answering your question. All I want to hammer home is that polymorphism is not something that is applied effectively in existing physics engines. And that's probably not because the authors didn't "get" OO.
So anyway, my advice: ditch polymorphism for your entity class. You're not going to end up with 100 different types that you can't possibly refactor at a later date, your physics engine's shape data will be fairly homogeneous (convex polys, boxes, spheres, etc) and your entity data will likely be even more homogeneous (probably just rigid bodies to start with).
Another mistake that I feel you're making is only supporting one Physics::System. There is utility in being able to simulate bodies independently of eachother (for instance, for a two player game), and the easiest way to do this is to support multiple Physics::Systems.
With that in mind, the cleanest 'pattern' to follow would be a factory pattern. When users want to create a rigid body, they need to tell the Physics::System (acting as a factory) to do it for them, so in your Physics::System:
// returning a smart pointer would not be unreasonable, but I'm returning a raw pointer for simplicity:
rigid_body_t* AddBody( body_params_t const& body_params );
And in the client code:
circle_params_t circle(1.f /*radius*/);
body_params_t b( 1.f /*mass*/, &circle /*shape params*/, xform /*system transform*/ );
rigid_body_t* body = physics_system.AddBody( b );
Anyhoo, kind of a rant. Hope this is helpful. At the very least I want to point you towards box2d. It's written in a pretty simple dialect of C++ and the patterns applied therein will be relevant to your engine, whether it's 3D or 2D.
The problem of hierarchies is that they don't always make sense, and trying to cram everything into a hierarchy just results in awkward decisions and frustrating work down the line.
The other solution that can be used is the tagged union one, best embodied by boost::variant.
The idea is to create an object that can hold one instance of a given type (among a preselected list) at any given time:
typedef boost::variant<Ellipsis, Polygon, Blob> Shape;
And then you can provide the functionality by switching over the type list:
struct AreaComputer: boost::static_visitor<double> {
template <typename T>
double operator()(T const& e) { return area(a); }
};
void area(Shape const& s) {
AreaComputer ac;
return boost::apply_visitor(s, ac);
}
The performance is the same as a virtual dispatch (so not too much, normally), but you get greater flexibility:
void func(boost::variant<Ellipsis, Blob> const& eb);
void bar(boost::variant<Ellipsis, Polygon> const& ep);
// ...
You can provide functions only when relevant.
And on the subject of binary visitation:
struct CollisionComputer: boost::static_visitor<CollisionResult> {
CollisionResult operator()(Circle const& left, Circle const& right);
CollisionResult operator()(Line const& left, Line const& right);
CollisionResult operator()(Circle const& left, Line const& right);
CollisionResult operator()(Line const& left, Circle const& right);
};
CollisionResult collide(Shape const& left, Shape const& right) {
return boost::apply_visitor(CollisionComputer(), left, right);
}

What are some 'good use' examples of dynamic casting?

We often hear/read that one should avoid dynamic casting. I was wondering what would be 'good use' examples of it, according to you?
Edit:
Yes, I'm aware of that other thread: it is indeed when reading one of the first answers there that I asked my question!
This recent thread gives an example of where it comes in handy. There is a base Shape class and classes Circle and Rectangle derived from it. In testing for equality, it is obvious that a Circle cannot be equal to a Rectangle and it would be a disaster to try to compare them. While iterating through a collection of pointers to Shapes, dynamic_cast does double duty, telling you if the shapes are comparable and giving you the proper objects to do the comparison on.
Vector iterator not dereferencable
Here's something I do often, it's not pretty, but it's simple and useful.
I often work with template containers that implement an interface,
imagine something like
template<class T>
class MyVector : public ContainerInterface
...
Where ContainerInterface has basic useful stuff, but that's all. If I want a specific algorithm on vectors of integers without exposing my template implementation, it is useful to accept the interface objects and dynamic_cast it down to MyVector in the implementation. Example:
// function prototype (public API, in the header file)
void ProcessVector( ContainerInterface& vecIfce );
// function implementation (private, in the .cpp file)
void ProcessVector( ContainerInterface& vecIfce)
{
MyVector<int>& vecInt = dynamic_cast<MyVector<int> >(vecIfce);
// the cast throws bad_cast in case of error but you could use a
// more complex method to choose which low-level implementation
// to use, basically rolling by hand your own polymorphism.
// Process a vector of integers
...
}
I could add a Process() method to the ContainerInterface that would be polymorphically resolved, it would be a nicer OOP method, but I sometimes prefer to do it this way. When you have simple containers, a lot of algorithms and you want to keep your implementation hidden, dynamic_cast offers an easy and ugly solution.
You could also look at double-dispatch techniques.
HTH
My current toy project uses dynamic_cast twice; once to work around the lack of multiple dispatch in C++ (it's a visitor-style system that could use multiple dispatch instead of the dynamic_casts), and once to special-case a specific subtype.
Both of these are acceptable, in my view, though the former at least stems from a language deficit. I think this may be a common situation, in fact; most dynamic_casts (and a great many "design patterns" in general) are workarounds for specific language flaws rather than something that aim for.
It can be used for a bit of run-time type-safety when exposing handles to objects though a C interface. Have all the exposed classes inherit from a common base class. When accepting a handle to a function, first cast to the base class, then dynamic cast to the class you're expecting. If they passed in a non-sensical handle, you'll get an exception when the run-time can't find the rtti. If they passed in a valid handle of the wrong type, you get a NULL pointer and can throw your own exception. If they passed in the correct pointer, you're good to go.
This isn't fool-proof, but it is certainly better at catching mistaken calls to the libraries than a straight reinterpret cast from a handle, and waiting until some data gets mysteriously corrupted when you pass the wrong handle in.
Well it would really be nice with extension methods in C#.
For example let's say I have a list of objects and I want to get a list of all ids from them. I can step through them all and pull them out but I would like to segment out that code for reuse.
so something like
List<myObject> myObjectList = getMyObjects();
List<string> ids = myObjectList.PropertyList("id");
would be cool except on the extension method you won't know the type that is coming in.
So
public static List<string> PropertyList(this object objList, string propName) {
var genList = (objList.GetType())objList;
}
would be awesome.
It is very useful, however, most of the times it is too useful: if for getting the job done the easiest way is to do a dynamic_cast, it's more often than not a symptom of bad OO design, what in turn might lead to trouble in the future in unforeseen ways.