I had a problem developing a part of my application that deals with geometry. In particular, I would like to have a class hierarchy and separate methods for intersections.
Problem
The hierarchy will be something like this:
And the intersection methods are something like:
namespace intersections { bool intersection( const Box &, const Box &); bool intersection( const Box &, const Sphere &); }
It is pretty simple. The problem now arises when I want to store all the geometries together in one structure, say, for example, std::vector (or a KD tree or something else).
For this I need to use std::vector<Geometry*> . However, reading from this vector would make it possible to obtain Geometry* objects, and therefore I have no way to call the corresponding intersection function.
Example problem:
std::vector<Geometry*> arrGeometry;
If I implemented the algorithms inside the geometry objects, the problem could be solved by the visitor and some rather strange call of the call function.
However, I would like to keep intersection algorithms outside of the Geometry classes. causes:
to avoid deciding which one should have ownership (for example, where do you intersect between a field and a sphere, in Box or in Sphere ?)
to avoid cluttering geometry objects, all this can be done for geometry, which is quite a lot (just to name a few: voxelize it, calculate intersections, apply constructive geometry operators ...). Thus, it is highly desirable to separate the logic from the data.
On the other hand, I need to have a hierarchy instead of templates, because for some things specific geometry can be abstracted ... (for example, to store it in std::vector or KD-Tree or ...).
How would you solve this? Is there any design template suitable for this? I tried to look at some libraries, but in the end I was more embarrassed that I was already ...
The easiest way (which is sometimes used) is to use RTTI (or fake it) and downcastings, but this is not completely repaired ... (adding new geometry implies changing a large number of switch statements, although all the code).
Any thoughts?
Thank you very much in advance.