CGAL - Proper way of adding data to Triangle class - c++

I have begun using CGAL and encountered an issue I am not able to solve. I load a model as a list of triangles and want to store additional information for each triangle - a color. I also want to use the AABB tree from CGAL but I have noticed that I have basically two options:
class DataTriangle {
public:
Point_3 x;
Point_3 y;
Point_3 z;
int color;
}
Follow the "AABB_custom_example.cpp" example and create a functor that converts my DataTriangle to a CGAL::Simple_cartesian::Triangle_3 every time. This wastes computation time because it constructs new Triangle_3 object every time.
I can make my own triangle and include Triangle_3 as a member:
class MyTriangle {
Triangle mTriangleCgal;
int color;
const Triangle& getTri() const { return mTriangleCgal; }
}
Then again declare a My_triangle_primitive functor, define
typedef K::Point_3 Point;
typedef K::Triangle_3 Datum;
typedef const K::Triangle_3& Datum_reference;
and reference the underlying triangle as such.
Datum_reference datum() { return tri->getTri(); }
Is this solution okay? I feel it should not waste time by constructing any new objects. Am I right?
The third idea I came up with is simply creating a custom iterator that will go through the vector of MyTriangles and instead of the class itself, return the Triangle_3 class. I should be able to pass this iterator into the AABB tree constructor and get the tree constructed from plain Triangle_3 objects, which should work just fine.
Is there another way of approach that I missed that is prefered to these three? Is number 2 okay to use if there is not another way?
Thank you

Related

C++ function with different return types

Let's say I want to write a function that takes a plane and a line in R^3 and returns their intersection. Obviously, I have to distinguish between three possible cases: i) the line intersects the plane in a single point, ii) the line is a subset of the plane, iii) the line is parallel to the plane (and not a subset of it). This results in three possible return types for the function.
I've been working a lot with OCaml recently, which would allow me to distinguish between these different types very explicitly by returning a variant type from my function. How do people deal with this kind of issue in C++?
One idea that comes to mind is to use a tuple of {bool, bool, vector} as my return type, where the first boolean says whether the line and the plane have a non-empty intersection, the second boolean says whether they intersect in a single point if the first boolean is true (and is meaningless otherwise), and the vector returns the unique intersection if both booleans are true (and is meaningless otherwise). However, this feels very inelegant and hacky, I have to inform users of the function of the meaning of the tuple entries using comments, I return variables which can be meaningless, etc.
What is the best way to deal with this problem?
Here are several generic (i.e. not limited to geometrical lines and points) ways to cope with the problem.
std::variant (or its older sibling boost::variant for those who cannot run C++17).
Plain old union (tagged):
struct LinePlaneIntersection {
enum { IsLine, IsPlane } intersection_type;
union {
Point p;
Line l;
};
};
If Point and Line have not-trivial constructors and/or destructors, you'd need to add ctors and dtors to the above scheme.
Plain old inheritance.
class LinePlaneIntersection { ... };
class NoIntersection : public LinePlaneIntersection { ... };
class OnePointIntersection : public LinePlaneIntersection { ... };
class OneLineIntersection : public LinePlaneIntersection { ... };
Return a LinePlaneIntersection* (or better and much preferable std::unique_ptr<LinePlaneIntersection>) from your function. Then there's of course the problem of what to do with the returned value. You may want to use the Visitor pattern here.
Continuation passing. Don't return anything, accept a continuation instead. In this case, three continuations:
void intersect (Line line, Plane plane,
std::function<void(Line)> onLine,
std::function<void(Point)> onPoint,
std::function<void()> onNothing);
I would do something like:
struct Point3D
{
double x;
double y;
double z;
};
struct Line
{
Point3D p1;
Point3D p2;
};
struct Plan {
Point3D p;
Point3D orthogonalDir;
};
std::optional<std::variant<Point3D, Line>>
ComputeIntersection(const Line& line, const Plan& plan);
Although there are nice new shiny ways of dealing with this (std::tuple, std::variant, &c.), the tried-and-tested way is to design a class (or even a set of related classes) that can represent the various states and return an instance of that.
It's this approach that always seems to scale up best as your project evolves. So much so, that the committee behind Java has never emitted a tuple or a variant type into their language and libraries.
Why not return a struct with an enum type? Someone using the function could then first check the type of intersection before attempting to use the data.
enum IntersectType {
INTERSECTION_NONE,
INTERSECTION_POINT,
INTERSECTION_LINE,
};
struct Point3D {
double x;
double y;
double z;
}
struct LinePlaneIntersect {
IntersectType type;
std::vector<Point3D> intersect; //since you mentioned vector
};
//Check within another function
struct LinePlaneIntersect intersection = fun(line, plane);
if (intersection.type == INTERSECTION_POINT) {
// do something
}

Implementing a component System for my 2d C++ game

I've been trying to figure out a way to implement a component system for my simple 2d fighting game where I can easily swap in new components returned from my system functions. The idea is I have a bunch of system functions which will work on a set of components:
example:
PosisiontComponent MovementSystem(PositionComponent pos, VelocityComponent vel)
{
//..Make entity move
return pos;
}
The key here is I want to return a new copy of the component, and not modify the state directly in within my system function (for easier comprehension and testing of systems). Ideally, this new updated position component can then be inserted in my Fighter (which acts basically like an entity class) through an myFighter.Insert() member function of some sort. So far, I'm thinking of using a std::map<int key, Component* comp> to store my components with the key being a unique id that is connected with only one component type which I can use to look up certain components within the map. The fighter class might look something like:
class Fighter
{
public:
void Insert(Component* comp);
Component* Get();
std::map<int, Component*> componentMap;
}
Fighter::Fighter(std::string const imageFilePath, float startPositionX, float startPositionY) :
sprite(imageFilePath, 200, 200)
{
componentMap[0] = new PositionComponent(glm::vec2{ 0.0f, 0.0f });
componentMap[1] = new VelocityComponent();
}
void Fighter::Insert(Component* component)
{
componentMap.erase(compID);
componentMap[compID)] = component;
}
Component* GetComponent()
{
return componentMap[id];
}
The problem I'm running into is I don't quite know how I would return individual components through a GetComponent() function (currently just getting compiler errors due to conversion of type problems) with the current implementation.
My question(s) are:
1.) Is my current implementation a viable solution? Is there a way to extract specific components from GetComponent() function without getting compiler issues? If not, whats a better way to easily swap out individual components inside my Fighter class?
Assuming each entity can only have one component per type, you could use templates.
template<typename T>
T* getComponent() {
for (auto &component : components)
{
T* derivedComponent = dynamic_cast<T*>(component);
if (derivedComponent)
{
return derivedComponent;
}
}
return NULL;
}
Then using it will be simple and it does not require an id to be shared around. Also the order of the map can be changed without breaking the game. This is would happen as you add and remove components at runtime.
Fighter* f;
PosisiontComponent* positionComponent = f->getComponent<PosisiontComponent>();
This is the approach I have used in the past and it has worked very nicely. However, I would recommend using smart pointers as opposed to raw pointers for these containers.

Why did QuantLib introduce the Handle class?

I check this slides but still didn't get :
1) what problem does Handle sovled?
2) what is the benefit to add the Handle class?
From its source code, I cannot get any clue either:
template <class Type>
class Handle {
protected:
class Link : public Observable, public Observer {
public:
explicit Link(const shared_ptr<Type>& h =
shared_ptr<Type>());
void linkTo(const shared_ptr<Type>&);
bool empty() const;
void update() { notifyObservers(); }
private:
shared_ptr<Type> h_;
};
boost::shared_ptr<Link<Type> > link_;
public:
explicit Handle(const shared_ptr<Type>& h =
shared_ptr<Type>());
const shared_ptr<Type>& operator->() const;
const shared_ptr<Type>& operator*() const;
bool empty() const;
operator boost::shared_ptr<Observable>() const;
};
template <class Type>
class RelinkableHandle : public Handle<Type> {
public:
explicit RelinkableHandle(const shared_ptr<Type>& h =
shared_ptr<Type>());
void linkTo(const boost::shared_ptr<Type>&);
};
Could someone give a better example?
Thanks.
The short answer: the Handle class is a smart pointer to pointer.
What is it good for? Take, for example, an instance of an interest-rate index such as Euribor6M. Right now, its constructor takes a handle to a yield term structure from which it forecasts its future fixings. What would change if we used a shared_ptr instead?
Let's look at a use case. Warning: I'm simplifying things to avoid writing too much code, but it's a legitimate use case we have. Let's say we initialized the index with a flat curve to begin with:
shared_ptr<SimpleQuote> r = make_shared<SimpleQuote>(0.01);
shared_ptr<YieldTermStructure> curve =
make_shared<FlatForward>(today, r, Actual360());
shared_ptr<InterestRateIndex> index = make_shared<Euribor6M>(curve);
(in a real use case, curve would be an Euribor curve bootstrapped over a set of quoted rates). The constructor of index takes a copy of the passed shared_ptr<YieldTermStructure> and makes a copy of it to store as a data member. After it's built, we'll pass the index to other instruments (swaps, floating-rate bonds, whatever).
In case the interest rate changed, and given we still have a hold of the r quote, our client code can write
r->setValue(0.015);
Since r and curve are shared pointers, this will also change the rate in the copy of the curve inside the index (because both curve and its copy inside index point to the same object). As a result, the index fixings and the depending instrument values will also change.
However, let's say we want to start using another curve. In this case, we might want to switch to an interpolated curve instead of a flat one:
vector<Date> dates = ... ;
vector<Rate> rates = ... ;
shared_ptr<YieldTermStructure> curve2 =
make_shared<ZeroCurve>(dates, rates, Actual360());
(in a real case, we might want to bootstrap the curve on a different set of quotes or to use another way to model rates).
How can we tell index that it should start using curve2? Using shared_ptr, we can't. Even if we say:
curve = curve2;
this will cause curve to point to the interpolated curve, but the copy of curve inside index will keep pointing to the old one. This is not a problem with shared_ptr, but with pointers in general. How do you solve it? By adding another layer of indirection. If you were using raw pointers, you'd start using pointers to pointers. In our code, Handle does the same thing: it "points" to a shared_ptr, and is implemented so that two copies of the same handle point to the same shared_ptr. This way, if you write:
shared_ptr<SimpleQuote> r = make_shared<SimpleQuote>(0.01);
shared_ptr<YieldTermStructure> curve =
make_shared<FlatForward>(today, r, Actual360());
RelinkableHandle<YieldTermStructure> h(curve);
shared_ptr<InterestRateIndex> index = make_shared<Euribor6M>(h);
you can later write:
h.linkTo(curve2);
and both the handle you hold and its copy inside index will point to the new curve.
As for the difference between RelinkableHandle and Handle: you can only call linkTo on the former. The idea is that you instantiate a RelinkableHandle, pass around copies as just Handle, and so you ensure that nobody but you can change what it points to (using const wouldn't work, since constness can be cast away by a simple copy).

Circular issue: accessing set of objects from within its own member function

I am simulating a set of spheres interacting with each other.
For this reason I made a class sphere that stores its position x-y-z and has a method update() that updates its position.
class cSphere {
double x; double y; double z;
void update()
}
This update function, however, depends on the positions of the other spheres. I am not sure how to best handle this circular problem.
What I tried first was to create a std::vector *vec_spheres in my main() as a global variable and access it within update() by defining extern std::vector *vec_spheres in cSphere.h. This does of course not work though.
I am now thinking about creating a singleton class that returns a pointer to *vec_spheres but that also seems hacky.
Thanks for your advice!
In the light of LawOfDemeter I don't suggest making that knowledge the responsability of cSphere::update.
Instead, make a higher entity (cSphereSimulation, PhysicsEngine, ...?) that knows how to calculate the new positions of all spheres.
In pseudo code:
struct cSimulation
{
std::vector<cSpheres> _spheres;
void update()
{
// calculations using all positions...
for (auto& sphere : _spheres)
sphere.update(newLocation);
}
// ...

Is it better to store class constants in data members or in methods?

I recently wrote a class that renders B-spline curves. These curves are defined by a number of control points. Originally, I had intended to use eight control points, so I added a constant to the class, like so:
class Curve
{
public:
static const int CONTROL_POINT_COUNT = 8;
};
Now I want to extend this class to allow an arbitrary amount of control points. So I want to change this to:
class Curve
{
public:
int getControlPointCount() {return _controlPointCount;}
};
The question is whether it isn't better to store constants in methods to begin with, to facilitate adaptability. In other words, isn't it better to have started thus:
class Curve
{
public:
int getControlPointCount() {return 8;}
};
The advantage of this is that I could have just changed one symbol in the method in question, instead of moving around constants etc.
Is this a good practice or a bad one?
int getControlPointCount() {return _controlPointCount;}
This is an accessor. Swapping a const static for an accessor is not really a gain as litb has pointed out. What you really need to future-proof is probably a pair of accessor and mutator.
int getControlPointCount() {return _controlPointCount;} // accessor
I'd also throw in a design-const for the accessor and make it:
int getControlPointCount() const {return _controlPointCount;} // accessor
and the corresponding:
void setControlPointCount(int cpc) { _controlPointCount = cpc;} //mutator
Now, the big difference with a static object is that the control-point count is no longer a class-level attribute but an instance level one. This is a design change. Do you want it this way?
Nit: Your class level static count is public and hence does not need an accessor.
Typically I favour maintaining as few couplings manually as possible.
The number of control points in the curve is, well, the number of control points in the curve. It's not an independent variable that can be set at will.
So I usually would expose a const standard container reference:
class Curve
{
private:
std::vector<Point>& _controlPoints;
public:
Curve ( const std::vector<Point>& controlPoints) : _controlPoints(controlPoints)
{
}
const std::vector<Point>& getControlPoints ()
{
return _controlPoints;
}
};
And if you want to know how many control points, then use curve.getControlPoints().size(). I'd suspect that in most of the use cases you'd want the points as well as the count anyway, and by exposing a standard container you can use the standard library's iterator idioms and built-in algorithms, rather getting the count and calling a function like getControlPointWithIndex in a loop.
If there really is nothing else in the curve class, I might even go as far as:
typedef std::vector<Point> Curve;
(often a curve won't render itself, as a renderer class can have details about the rendering pipeline, leaving a curve as purely the geometric artifact)
To better answer your question, one should also know how the controlPointCount variable is set. Is it set outside from your class? In this case, you should also define a setter. Or the Curve class is the sole responsible for setting it? Is it set only on compile time or also on runtime.
Anyway, avoid a magic number even in this form:
int getControlPointCount() {return 8;}
This is better:
int getControlPointCount() {return CONTROL_POINT_COUNT;}
A method has the advantage that you can modify the internal implementation (use a constant value, read from a configuration file, alter the value dynamically), without affecting the external of the class.
class Curve
{
private:
int _controlPointCount;
void setControlPointCount(int cpc_arg)
{
_controlPointCount = cpc_arg;
}
public:
curve()
{
_controlPointCount = 8;
}
int getControlPointCount() const
{
return _controlPointCount;
}
};
I will create a code like this, with set function in private, so that no body can play with control point count, until we move to the next phase of development..where we update start to update the control point count at runtime. at that time, we can move this set method from private to public scope.
While understanding the question, I have a number of conceptual problems with the example:
What is the return value for getControlPointCount() when the number of control points is not limited?
Is it MAXINT?
Is it the current number of control points on the curve (thus breaking the logic that says that this is the largest possible number of points?)
What happens when you actually attempt to create a curve with MAXINT points? You will run out of memory eventually.
The interface itself seems problematic to me. Like other standard collection classes, the class should have encapsulated its limitation on number of points, and its AddControlPoint() should have returned an error if a limitation on size, memory, or any other violation has occurred.
As for the specific answer, I agree with kgiannakakis: a member function allows more flexibility.
I tend to use configuration + constant (default value) for all 'stable' values through the execution of the program. With plain constants for values that cannot change (360 degrees -> 2 pi radians, 60 seconds -> 1 minute) or whose change would break the running code (minimum/maximum values for algorithms that make them unstable).
You are dealing with some different design issues. First you must know whether the number of control points is a class or instance level value. Then whether it is a constant at any of the two levels.
If all curves must share the same number of control points in your application then it is a class level (static) value. If different curves can have different number of control points then it is not a class level value, but rather a instance level one.
In this case, if the number of control points will be constant during the whole life of the curve then it is a instance level constant, if it can change then it is not constant at this level either.
// Assuming that different curves can have different
// number of control points, but that the value cannot
// change dynamically for a curve.
class Curve
{
public:
explicit Curve( int control_points )
: control_points_( control_points )
{}
// ...
private:
const int control_points_;
};
namespace constant
{
const int spline_control_points = 8;
}
class Config
{
public:
Config();
void readFile( std::string const & file );
// returns the configured value for SplineControlPoints or
// constant::spline_control_points if the option does not
// appear in config.
int getSplineControlPoints() const;
};
int main()
{
Config config;
config.readFile( "~/.configuration" ); // read config
Curve c( config.getSplineControlPoints() );
}
For integral type I'm usualy using:
class Curve
{
public:
enum
{
CONTROL_POINT_COUNT = 8
};
};
If constant doesn't need for any entities except class implementation I declare constants in *.cpp file.
namespace
{
const int CONTROL_POINT_COUNT = 8;
}
In general, all your data should be private and accessed via getters and setters. Otherwise you violate encapsulation. Namely, if you expose the underlying data you lock yourself and your class into a particular representation of that underlying data.
In this specific case I would have done the something like the following I think:
class Curve
{
protected:
int getControlPointCount() {return _controlPointCount;}
int setControlPointCount(int c) { _controlPointCount = c; }
private:
static int _controlPointCount = 0;
};
Constants in general should not be defined inside methods. The example you're choosing has two unique features. First, it's a getter; second, the type being returned is an int. But the point of defining constants is to use them more than once, and to be able to refer to them in a convenient way. Typing "8" as opposed to "controlPointCount" may save you time, and may not seem to incur a maintenance cost, but this won't typically be true if you always define constants inside methods.