Eigen C++: Best Way To Convert 2D Polar To Cartesian - c++

I am currently doing:
Eigen::Vector2d polar(2.5, 3 * M_PI / 4);
Eigen::Vector2d cartesian = polar.x() * Vector2d(cos(polar.y()), sin(polar.y()));
but I'm not sure if this is the correct way to use Eigen or if there is some better built in way.
Thanks!

That looks right to me if you're wanting to stick with using Eigen.
Generally though since the polar representation has angles, it might be good to avoid using the Eigen::Vector2d just for the sake of reducing mistakes that may be made in the future (like adding multiple angles together and not dealing with the fact that 0 == 2*PI). Maybe you could do it with structs instead:
struct Polar { double range; double angle; };
struct Cartesian { double x; double y; };
Cartesian to_cartesian(const Polar& p) {
double c = cos(p.angle);
double s = sin(p.angle);
return {p.range * c, p.range * s};
}
Polar to_polar(const Cartesian& c) {
return {std::sqrt(c.x * c.x + c.y * c.y), std::atan2(c.y, c.x)};
}

Related

C++ bicubic interpolation with a thermal image

At the moment I'm using a MLX90641 sensor on a STM32 to get a temperature grid.
The grid itself is 18x12 pixels.
I'd like to bicubic interpolate this grid to a 31x23 one, I think that's the most logical one?
My math / calculus knowledge is just sufficient enough to grasp the idea of bicubic interpolation. Yet I can't figure out to make it work in code.
Used language is C++ and https://www.paulinternet.nl/?page=bicubic as a source.
double cubicInterpolate (double p[4], double x) {
return p[1] + 0.5 * x*(p[2] - p[0] + x*(2.0*p[0] - 5.0*p[1] + 4.0*p[2] - p[3] + x*(3.0*(p[1] - p[2]) + p[3] - p[0])));
}
double bicubicInterpolate (double p[4][4], double x, double y) {
double arr[4];
arr[0] = cubicInterpolate(p[0], y);
arr[1] = cubicInterpolate(p[1], y);
arr[2] = cubicInterpolate(p[2], y);
arr[3] = cubicInterpolate(p[3], y);
return cubicInterpolate(arr, x);
}
Do I loop through my array of doubles and call the function bicubicInterpolate on each value?
Why do they use parameters double x, double y?
Anyone able to help me apply this function to my double grid[192]?
Thanks!

C++ Convert 3D Velocity Vector To Speed Value

In a game I am working on I get the velocity of a game world object like so
void getObjectVelocity(int objectID, vec3_t *velocityOut);
So if I were to call this function like this
vec3_t storeObjectVelocity;
getObjectVelocity(21/* just an example ID */, &storeObjectVelocity);
The velocity of the object with the ID of 21 would be stored in storeObjectVelocity.
For testing purposes I am trying to print the speed of this object based off it's velocity in the middle of the game screen.
Here's an example just to give you a better idea of what I'm trying to accomplish
int convertVelocityToSpeed(vec3_t velocity)
{
//This is where I am having issues.
//Converting the objects 3D velocity vector to a speed value
}
int testHUDS()
{
char velocityToSpeedBuffer[32] = { 0 };
vec3_t storeObjectVelocity;
getObjectVelocity(21, &storeObjectVelocity);
strcpy(velocityToSpeedBuffer, "Speed: ");
strcat(velocityToSpeedBuffer, system::itoa(convertVelocityToSpeed(storeObjectVelocity), 10));
render::text(SCREEN_CENTER_X, SCREEN_CENTER_Y, velocityToSpeedBuffer, FONT_SMALL);
}
Here is my vec3_t struct in case you were wondering
struct vec3_t
{
float x, y, z;
};
Length of a vector is calculated as
√( x² + y² + z²)
So in your program, something like this will works:
std::sqrt( velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z )
As #Nelfeal commented, last approach can overflow. Using std::hypot this problem is avoided. Since is more secure and it's clearer, this should be the first option if C++17 is available. Even knowing that it's less efficient. Remember to avoid premature micro optimizations.
std::hypot(velocity.x, velocity.y, velocity.z)
Also, you should think about passing velocity as a const reference to the function.
Speed is a scalar quantity given by the magnitude of a velocity vector |velocity|. Magnitude of a 3D vector is computed as:
So in your code you want to implement your method as:
int convertVelocityToSpeed(vec3_t velocity)
{
return std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z);
}
you may need to include the math header #include <cmath> and I have assumed your vec3_t holds int values although this is unusual for a velocity in physics simulations, they are usually floating point types. If not you need to check your return type.
#include <cmath>
using namespace std;
sqrt(pow(velocity.x,2), pow(velocity.y,2), pow(velocity.x,2));
Use sqrt from cmath and pow from cmath.
EDIT
edited the mistype import as corrected by in the comments

Adding a list of forces to a particle in c++

I'm kinda new to c++, so sorry if it's a dumb question.
I have a struct that represents a particle in a particle system. Along with the standard stuff like position, velocity, and mass, I want to give it a list of forces, such that each force is a function, where I pass it the particle, and based on the current state of the particle (or not), this function returns a force vector. Ideally I would sum up the results of every such force vector to get a net force, which I could then use to calculate the velocity of the particle for the next tick.
This is what I want my particle to look like
struct particle {
double mass;
// position
double x, y, z;
// velocity
double dx, dy, dz;
std::list<function> forces;
};
Now my question is: Can I do this without implementing a generic force base class that implements a function to calculate a force? Is there a way I can just specify a list of functions with the same call signature?
If you can guarantee that all functions will have the same method signature, then you can use the templated function[cppreference.com] class. I've modified your sample to illustrate how to use it.
#include <functional>
#include <list>
#include <cmath>
using namespace std;
struct particle
{
double mass;
// position
double x, y, z;
// velocity
double dx, dy, dz;
// A list of forces that take a particle and return a double
// The space between the two > symbols is needed in pre-c++11 compilers.
list<function<double(const particle&)> > forces;
};
// An example function to calculate the force due to gravity.
double gravity(const particle& p)
{
return p.mass * -9.8;
}
// Making something up for air resistance
double resistance(const particle& p)
{
return 0.1 * sqrt(p.dx * p.dx + p.dy * p.dy + p.dz * p.dz);
}
int main()
{
particle p;
p.mass = 10;
p.x = 0;
p.y = 100;
p.z = 0;
p.dx = 0;
p.dy = 0;
p.dz = 0;
p.forces.push_back(gravity);
p.forces.push_back(resistance);
}
If you're going to be dealing with three dimensional forces, you'll probably want more information in the return type than just a double, but this should be a good starting point. Also, if you have a c++11 compatible compiler, you may also want to lookup lambda functions so that the functions can be created in the same line.
You can use std::function. Something like this:
// define a type for the function
typedef std::function< void(particle const&, float *fxfyfz) > forcer_function;
std::vector< forcer_function > forces;
Now, some words with regards to performance. Since this is particles you're talking about, I'm assuming that you have a reasonably large number of particles (eg some hundreds at least). So I'm assuming that you have an interest in getting this code to run moderately fast.
So, first, using std::list for your container is not advised due to bad cache properties. It will make your code much slower. Therefore, the use of std::vector.
Second, adding the list of forces as a member of your particle structure is uncommon. Do you really want to use different forces per particle? Typically, there are <5 forces and >100-1000 particles. If you can use the same collection of forces for all of your particles, then moving the forces out of your particle class will give you a gain. For example,
struct particle
{
double mass;
// position
double x, y, z;
// velocity
double dx, dy, dz;
};
struct particle_container
{
std::vector< particle > particles;
std::vector< forcer_function > forces;
void update();
};
void particle_container::update()
{
for(particle &p : particles) {
double rx, ry, rz;
rx = ry = rz = 0.0;
for(forcer_function fn : forces) {
double f[3];
fn(p, &f[0]);
rx += f[0];
ry += f[1];
rz += f[2];
}
// integrate resulting force, etc
// ...
}
}
If OTOH you really want to use per-particle forces, you can still use the approach I outlined above by grouping particles with the same force collection in different container objects. Then you can reuse all of the above, and adding one more class will fix it:
struct particle_groups
{
std::vector< particle_container > groups;
void update();
};
void particle_groups::update()
{
for(auto &g : groups) {
g.update();
}
};
If you really, really, want no grouping, then at least consider whether there's a way you can use particle members zeroing out inactive forces. Then you could still use the approach above. For example, like this:
struct particle
{
double mass;
// position
double x, y, z;
// velocity
double dx, dy, dz;
// is gravity active? either 1.0 or 0.0
double grav;
// is player interaction active? either 1.0 or 0.0
double player;
// etc... for all possible forces
};
Then just multiply eg, your resulting gravity by the particle's grav member, and you effectively switch gravity off or on for that particle, according to whether particle.grav's value is 1.0 or 0.0.
Finally, std::function is slow. You can use a mix of the two approaches above and use a single function. Like this:
struct particle
{
double mass;
// position
double x, y, z;
// velocity
double dx, dy, dz;
};
struct force_settings
{
double grav;
double attractor;
double player;
//etc...
};
struct particle_container
{
// no need to keep pointers to functions
force_settings forces;
std::vector< particle > particles;
void update();
void compute_forces(particle const& p, double *rf) const
{
// zero resulting force
rf[0] = rf[1] = rf[2] = 0.0;
// compute gravity, (assume y axis)
rf[1] += forces.grav * 9.8; // will be either 9.8 or 0.0
// compute attractor
double ax = p.x - attractor.x;
double ay = p.y - attractor.y;
double az = p.z - attractor.z;
rf[0] += forces.attraction * ax*ax;
rf[1] += forces.attraction * ay*ay;
rf[2] += forces.attraction * az*az;
// etc... more forces here
}
};
void particle_container::update()
{
for(particle &p : particles) {
double rf[3];
compute_forces(p, &rf);
// integrate, etc...
}
}

Check if mouse is within triangle C++

I'm making a application for school in which I have to click a particular object.
EDIT: This is being made in 2D
I have a rectangle, I rotate this rectangle by X.
The rotation of the rectangle has made my rectangles (x,y,width,height) become a new rectangle around the rotated rectangle.
http://i.stack.imgur.com/MejMA.png
(excuse me for my terrible paint skills)
The Black lines describe the rotated rectangle, the red lines are my new rectangle.
I need to find out if my mouse is within the black rectangle or not. Whatever rotation I do I already have a function for getting the (X,Y) for each corner of the black rectangle.
Now I'm trying to implement this Check if point is within triangle (The same side technique).
So I can either check if my mouse is within each triangle or if theres a way to check if my mouse is in the rotated rectangle that would be even better.
I practically understand everything written in the triangle document, but I simply don't have the math skills to calculate the cross product and the dot product of the 2 cross products.
This is supposed to be the cross product:
a × b = |a| |b| sin(θ) n
|a| is the magnitude (length) of vector a
|b| is the magnitude (length) of vector b
θ is the angle between a and b
n is the unit vector at right angles to both a and b
But how do I calculate the unit vector to both a and b?
And how do I get the magnitude of a vector?
EDIT:
I forgot to ask for the calculation of the dotproduct between 2 cross products.
function SameSide(p1,p2, a,b)
cp1 = CrossProduct(b-a, p1-a)
cp2 = CrossProduct(b-a, p2-a)
if DotProduct(cp1, cp2) >= 0 then return true
else return false
Thank you everyone for your help I think I got the hang of it now, I wish I could accept multiple answers.
If you are having to carry out loads of check, I would shy away from using square root functions: they are computationally expensive. for comparison purposes, just multiply everything by itself and you can bypass the square rooting:
magnitude of vector = length of vector
If vector is defined as float[3] length can be calculated as follows:
double magnitude = sqrt( a[0]*a[0] + a[1]*a[1] + a[2]*a[2] );
However that is expensive computationally so I would use
double magnitudeSquared = a[0]*a[0] + a[1]*a[1] + a[2]*a[2];
Then modify any comparative calculations to use the squared version of the distance or magnitude and it will be more performant.
For the cross product, please forgive me if this maths is shaky, it has been a couple of years since I wrote functions for this (code re-use is great but terrible for remembering things):
double c[3];
c[0] = ( a[1]*b[2] - a[2]*b[1] );
c[1] = ( a[2]*b[0] - a[0]*b[2] );
c[2] = ( a[0]*b[1] - a[1]*b[0] );
To simplify it all I would put a vec3d in a class of its own, with a very simple representation being:
class vec3d
{
public:
float x, y, z;
vec3d crossProduct(vec3d secondVector)
{
vec3d retval;
retval.x = (this.y * secondVector.z)-(secondVector.y * this.z);
retval.y = -(this.x * secondVector.z)+(secondVector.x * this.z);
retval.z = (this.x * secondVector.y)-(this.y * secondVector.x);
return retval;
}
// to get the unit vector divide by a vectors length...
void normalise() // this will make the vector into a 1 unit long variant of itself, or a unit vector
{
if(fabs(x) > 0.0001){
x= x / this.magnitude();
}
if(fabs(y) > 0.0001){
y= y / this.magnitude();
}
if(fabs(z) > 0.0001){
z = / this.magnitude();
}
}
double magnitude()
{
return sqrt((x*x) + (y*y) + (z*z));
}
double magnitudeSquared()
{
return ((x*x) + (y*y) + (z*z));
}
};
A fuller implementation of a vec3d class can be had from one of my old 2nd year coding excercises: .h file and .cpp file.
And here is a minimalist 2d implementation (doing this off the top of my head so forgive the terse code please, and let me know if there are errors):
vec2d.h
#ifndef VEC2D_H
#define VEC2D_H
#include <iostream>
using namespace std;
class Vec2D {
private:
double x, y;
public:
Vec2D(); // default, takes no args
Vec2D(double, double); // user can specify init values
void setX(double);
void setY(double);
double getX() const;
double getY() const;
double getMagnitude() const;
double getMagnitudeSquared() const;
double getMagnitude2() const;
Vec2D normalize() const;
double crossProduct(Vec2D secondVector);
Vec2D crossProduct(Vec2D secondVector);
friend Vec2D operator+(const Vec2D&, const Vec2D&);
friend ostream &operator<<(ostream&, const Vec2D&);
};
double dotProduct(const Vec2D, const Vec2D);
#endif
vec2d.cpp
#include <iostream>
#include <cmath>
using namespace std;
#include "Vec2D.h"
// Constructors
Vec2D::Vec2D() { x = y = 0.0; }
Vec2D::Vec2D(double a, double b) { x = a; y = b; }
// Mutators
void Vec2D::setX(double a) { x = a; }
void Vec2D::setY(double a) { y = a; }
// Accessors
double Vec2D::getX() const { return x; }
double Vec2D::getY() const { return y; }
double Vec2D::getMagnitude() const { return sqrt((x*x) + (y*y)); }
double Vec2D::getMagnitudeSquared() const { return ((x*x) + (y*y)); }
double Vec2D::getMagnitude2 const { return getMagnitudeSquared(); }
double Vec2d::crossProduct(Vec2D secondVector) { return ((this.x * secondVector.getY())-(this.y * secondVector.getX()));}
Vec2D crossProduct(Vec2D secondVector) {return new Vec2D(this.y,-(this.x));}
Vec2D Vec2D::normalize() const { return Vec2D(x/getMagnitude(), y/getMagnitude());}
Vec2D operator+(const Vec2D& a, const Vec2D& b) { return Vec2D(a.x + b.x, a.y + b.y);}
ostream& operator<<(ostream& output, const Vec2D& a) { output << "(" << a.x << ", " << a.y << ")" << endl; return output;}
double dotProduct(const Vec2D a, const Vec2D b) { return a.getX() * b.getX() + a.getY() * b.getY();}
Check if a point is inside a triangle described by three vectors:
float calculateSign(Vec2D v1, Vec2D v2, Vec2D v3)
{
return (v1.getX() - v3.getX()) * (v2.getY() - v3.getY()) - (v2.getX() - v3.getX()) * (v1.getY() - v3.getY());
}
bool isPointInsideTriangle(Vec2D point2d, Vec2D v1, Vec2D v2, Vec2D v3)
{
bool b1, b2, b3;
// the < 0.0f is arbitrary, could have just as easily been > (would have flipped the results but would compare the same)
b1 = calculateSign(point2d, v1, v2) < 0.0f;
b2 = calculateSign(point2d, v2, v3) < 0.0f;
b3 = calculateSign(point2d, v3, v1) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
In the code above if calculateSign is in the triangle you will get a true returned :)
Hope this helps, let me know if you need more info or a fuller vec3d or 2d class and I can post:)
Addendum
I have added in a small 2d-vector class, to show the differences in the 2d and 3d ones.
The magnitude of a vector is its length. In C++, if you have a vector represented as a double[3], you would calculate the length via
#include <math.h>
double a_length = sqrt( a[0]*a[0] + a[1]*a[1] + a[2]*a[2] );
However, I understand what you actually want is the cross product? In that case, you may want to calculate it directly. The result is a vector, i.e. c = a x b.
You code it like this for example:
double c[3];
c[0] = ( a[2]*b[3] - a[3]*b[2] );
c[1] = ( a[3]*b[1] - a[1]*b[3] );
c[2] = ( a[1]*b[2] - a[2]*b[1] );
You can calculate the magnitude of vector by sqrt(x*x + y*y). Also you can calculate the crossproduct simpler: a x b = a.x * b.y - a.y * b.x. Checking that a point is inside triangle can be done by counting the areas for all 4 triangles. For example a is the area of the source triangle, b,c,d are areas of other ones. If b + c + d = a then the point is inside. Counting the area of triangle is simple: we have vectors a, b that are vertexes of triangle. The area of triangle then is (a x b) / 2
One simple way without getting into vectors is to check for area.
For example ,lets say you have a rectangle with corners A,B,C,D. and point P.
first calculate the area of rectangle, simply find height and width of the rectangle and multiply.
B D
| /
| /
|/____ C
A
For calculating the height,width take one point lets say A, find its distance from all other three points i.e AB,AC,AD 1st and 2nd minimum will be width,and height, max will be diagonal length.
Now store the points from which you get the height, width, lets says those points are B,C.
So now you know how rectangle looks, i.e
B _____ D
| |
|_____|
A C
Then calculate the sum of area of triangles ACP,ABP,BDP,CDP (use heros formula to compute area of rectangle), if it equals to the area of rectangle, point P is inside else outside the rectangle.

Radian or Degrees?

When I create matrix of rotation from Euler angles, Should I convert a degrees(Euler angles) to radians, and then count matrix of rotation for OpenGL?
But what should I do with a quaternions?
Should I do following:
void setQuaternionsFromEuler(float bank, float heading, float attitude)
{
float DegreeToRadian = 3.14f/180.0f;
double c1 = cos(heading/2*DegreeToRadian);
double c2 = cos(attitude/2*DegreeToRadian);
//...
double s3 = sin(bank/2*DegreeToRadian);
this.w = c1*c2*c3 - s1*s2*s3;
//...
}
And,
void setMatrixFromEuler(float x, float y, float z)
{
float DegreeToRadian = 3.14f/180.0f;
x *= DegreeToRadian;
y *= DegreeToRadian;
//...
}
Or not?
It depends on how you define your input.
The trig functions of C++ take radian exclusively, so you need to convert to radian eventually but that may be done before the data even enters your program (such that the angle values in the resources are all in radian)
Rotation matricies don't have angles anymore, so it's not really related with OpenGL, but the trigonometric functions you use from the standard library in C or C++ are defined on radians, so if your user-facing API works with degrees, then yes you should convert to take the cos/sin.