Rotate 2D vector with glm proper - c++

In a game I'm making, guns have a spread (float) and I want to give each bullet's angle a random value from range [-spread, spread]. For this I thought I could use glm::rotate, but the problem is that the bullets spread in almost every direction.
The code I use is:
void Gun::fire(const glm::vec2& direction, const glm::vec2& position, std::vector<Bullet>& bullets) {
static std::mt19937 randomEngine(time(nullptr));
// For offsetting the accuracy
std::uniform_real_distribution<float> randRotate(-_spread, _spread);
for (int i = 0; i < _bulletsPerShot; i++) {
// Add a new bullet
bullets.emplace_back(position,
glm::rotate(direction, randRotate(randomEngine)),
_bulletDamage,
_bulletSpeed);
}
}
(At the top I included vector and glm/gtx/rotate_vector.hpp)

I don't recall if GLM uses Radians or Degrees for calculating rotation, but 2 Radians is nearly a third of a full circle, which means that bullets will vary in direction by as much as 2 thirds of a whole circle. You may wish to test with smaller numbers, or else verify that GLM does indeed use Degrees to calculate rotation.
EDIT: In the most recent version of GLM, I looked through the source code. There's a commented out version of Rotate that explicitly converts Degrees to Radians, but the accessible source code has no such explicit conversion. So I'm left to presume that it is expecting Radians, not Degrees, as your inputs for Rotation.

Related

Find the distance between a 3D point and an Orientated Ellipse in 3D space (C++)

To give some background to this question, I'm creating a game that needs to know whether the 'Orbit' of an object is within tolerance to another Orbit. To show this, I plot a Torus-shape with a given radius (the tolerance) using the Target Orbit, and now I need to check if the ellipse is within that torus.
I'm getting lost in the equations on Math/Stack exchange so asking for a more specific solution. For clarification, here's an image of the game with the Torus and an Orbit (the red line). Quite simply, I want to check if that red orbit is within that Torus shape.
What I believe I need to do, is plot four points in World-Space on one of those orbits (easy enough to do). I then need to calculate the shortest distance between that point, and the other orbits' ellipse. This is the difficult part. There are several examples out there of finding the shortest distance of a point to an ellipse, but all are 2D and quite difficult to follow.
If that distance is then less than the tolerance for all four points, then in think that equates to the orbit being inside the target torus.
For simplicity, the origin of all of these orbits is always at the world Origin (0, 0, 0) - and my coordinate system is Z-Up. Each orbit has a series of parameters that defines it (Orbital Elements).
Here simple approach:
Sample each orbit to set of N points.
Let points from first orbit be A and from second orbit B.
const int N=36;
float A[N][3],B[N][3];
find 2 closest points
so d=|A[i]-B[i]| is minimal. If d is less or equal to your margin/treshold then orbits are too close to each other.
speed vs. accuracy
Unless you are using some advanced method for #2 then its computation will be O(N^2) which is a bit scary. The bigger the N the better accuracy of result but a lot more time to compute. There are ways how to remedy both. For example:
first sample with small N
when found the closest points sample both orbits again
but only near those points in question (with higher N).
you can recursively increase accuracy by looping #2 until you have desired precision
test d if ellipses are too close to each other
I think I may have a new solution.
Plot the four points on the current orbit (the ellipse).
Project those points onto the plane of the target orbit (the torus).
Using the Target Orbit inclination as the normal of a plane, calculate the angle between each (normalized) point and the argument of periapse
on the target orbit.
Use this angle as the mean anomaly, and compute the equivalent eccentric anomaly.
Use those eccentric anomalies to plot the four points on the target orbit - which should be the nearest points to the other orbit.
Check the distance between those points.
The difficulty here comes from computing the angle and converting it to the anomaly on the other orbit. This should be more accurate and faster than a recursive function though. Will update when I've tried this.
EDIT:
Yep, this works!
// The Four Locations we will use for the checks
TArray<FVector> CurrentOrbit_CheckPositions;
TArray<FVector> TargetOrbit_ProjectedPositions;
CurrentOrbit_CheckPositions.SetNum(4);
TargetOrbit_ProjectedPositions.SetNum(4);
// We first work out the plane of the target orbit.
const FVector Target_LANVector = FVector::ForwardVector.RotateAngleAxis(TargetOrbit.LongitudeAscendingNode, FVector::UpVector); // Vector pointing to Longitude of Ascending Node
const FVector Target_INCVector = FVector::UpVector.RotateAngleAxis(TargetOrbit.Inclination, Target_LANVector); // Vector pointing up the inclination axis (orbit normal)
const FVector Target_AOPVector = Target_LANVector.RotateAngleAxis(TargetOrbit.ArgumentOfPeriapsis, Target_INCVector); // Vector pointing towards the periapse (closest approach)
// Geometric plane of the orbit, using the inclination vector as the normal.
const FPlane ProjectionPlane = FPlane(Target_INCVector, 0.f); // Plane of the orbit. We only need the 'normal', and the plane origin is the Earths core (periapse focal point)
// Plot four points on the current orbit, using an equally-divided eccentric anomaly.
const float ECCAngle = PI / 2.f;
for (int32 i = 0; i < 4; i++)
{
// Plot the point, then project it onto the plane
CurrentOrbit_CheckPositions[i] = PosFromEccAnomaly(i * ECCAngle, CurrentOrbit);
CurrentOrbit_CheckPositions[i] = FVector::PointPlaneProject(CurrentOrbit_CheckPositions[i], ProjectionPlane);
// TODO: Distance from the plane is the 'Depth'. If the Depth is > Acceptance Radius, we are outside the torus and can early-out here
// Normalize the point to find it's direction in world-space (origin in our case is always 0,0,0)
const FVector PositionDirectionWS = CurrentOrbit_CheckPositions[i].GetSafeNormal();
// Using the Inclination as the comparison plane - find the angle between the direction of this vector, and the Argument of Periapse vector of the Target orbit
// TODO: we can probably compute this angle once, using the Periapse vectors from each orbit, and just multiply it by the Index 'I'
float Angle = FMath::Acos(FVector::DotProduct(PositionDirectionWS, Target_AOPVector));
// Compute the 'Sign' of the Angle (-180.f - 180.f), using the Cross Product
const FVector Cross = FVector::CrossProduct(PositionDirectionWS, Target_AOPVector);
if (FVector::DotProduct(Cross, Target_INCVector) > 0)
{
Angle = -Angle;
}
// Using the angle directly will give us the position at th eccentric anomaly. We want to take advantage of the Mean Anomaly, and use it as the ecc anomaly
// We can use this to plot a point on the target orbit, as if it was the eccentric anomaly.
Angle = Angle - TargetOrbit.Eccentricity * FMathD::Sin(Angle);
TargetOrbit_ProjectedPositions[i] = PosFromEccAnomaly(Angle, TargetOrbit);}
I hope the comments describe how this works. Finally solved after several months of head-scratching. Thanks all!

Rotating a 2D polygon shape algorithm

I have searched stackoverflow and find this question useful and learned about the 2D shape rotation.
I have the coordinates in such format
int x1=-30, x2=-15, x3=20, x4=30;
int my1=-30,y2=-15,y3=0,y4=15,y5=20,y6=30;
and have some center and pivot points like this
int xc=320, yc=240;//Center of the figure
int xp=0, yp=0;//Pivot point for this figure
I used this function to draw the shape
void draw_chair()
{
int loc_xc = xc+xp;
int loc_yc = yc+yp;
line(x2+loc_xc,my1+loc_yc,x2+loc_xc,y5+loc_yc);
line(x3+loc_xc,my1+loc_yc,x3+loc_xc,y5+loc_yc);
line(x2+loc_xc,my1+loc_yc,x3+loc_xc,my1+loc_yc);
line(x2+loc_xc,y2+loc_yc,x3+loc_xc,y2+loc_yc);
line(x2+loc_xc,y3+loc_yc,x3+loc_xc,y3+loc_yc);
line(x1+loc_xc,y4+loc_yc,x4+loc_xc,y4+loc_yc);
line(x2+loc_xc,y3+loc_yc,x1+loc_xc,y4+loc_yc);
line(x3+loc_xc,y3+loc_yc,x4+loc_xc,y4+loc_yc);
line(x1+loc_xc,y4+loc_yc,x1+loc_xc,y6+loc_yc);
line(x4+loc_xc,y4+loc_yc,x4+loc_xc,y6+loc_yc);
}
The problem is that, Now I am confused at how to compute the rotated x and y values
I tried google and found this piece of code to rotate
int tempx=x1;
x1=tempx*cos(angle)-my1*sin(angle);
my1=tempx*sin(angle)+my1*cos(angle);
tempx=x2;
x2=tempx*cos(angle)-y2*sin(angle);
y2=tempx*sin(angle)+y2*cos(angle);
tempx=x3;
x3=tempx*cos(angle)-y3*sin(angle);
y3=tempx*sin(angle)+y3*cos(angle);
tempx=x4;
x4=tempx*cos(angle)-y4*sin(angle);
y4=tempx*sin(angle)+y4*cos(angle);
I tried this but it did not rotated shape properly but instead this code converts shape into some other strange shape. Also I have 4 x points and 6 y points, then how to compute new value for each point?
Any Idea? or hint?
Thanks
You cannot technically rotate a coordinate, as it is just a point with no notion of direction.
The code you found is used to rotate vectors, which is indeed what you'll need, but first you would need to convert your coordinates into vectors. You can think of vectors as being the invisible line that connects the center of the figure to your points, so it consists of two points, which in your case you can assume one to be (0,0) since you later increment them with the center of the figure, and the other corresponds to your pairs such as (x2,my1), (x2,y5)... as used in your line drawing function.
Your code should actually become something like this:
PS: unless you pass in only the perfect angles, you cannot expect the figure to always work with integer coordinates. You would need them to be doubles)
int point1x, point1y;
point1x = (int) round(x2*cos(angle)-m1y*sin(angle));
point1y = (int) round(x2*sin(angle)+m1y*cos(angle));
int point2x, point2y;
point2x = (int) round(x2*cos(angle)-y5*sin(angle));
point2y = (int) round(x2*sin(angle)+y5*cos(angle));
...
line(point1x+loc_xc, point1y+loc_yc, point2x+loc_xc, point2y+loc_yc);
and so on.
Also, make sure your angle value is in radians, as both sin() and cos() functions assume that. If you are passing down degrees, convert them to radians first with the following formula:
double pi = acos(-1);
double rotation_angle = (double) angle / 180.0 * pi;
and use rotation_angle instead of angle in the code above.

Turn a mesh based on its local coordinates

I have a plane in a 3D-World and its orientation is saved in any way (e.g. pitch, yaw and roll). Now when I want the plane to turn left, but glRotatef doesn't do the job as it sticks to global coordinates and does not care about the rotation of the plane, and simply changing the yaw doesn't help either as this is also not relative to the planes actual rotation and would only mean "left" when the plane flies straight to the horizon. What I would need would be like this:
float pitch = 10 , yaw = 20, roll = 30; //some initial values
Turn(&pitch, &yaw, &roll , 5, 0 , 0 ) //calculate new pitch, yaw and roll as if
//the plane had turned 5 degrees to the right (relative to its current orientation and roll!)
//pitch, yaw and roll are updated to reflect the new orientation.
Many people suggest usage of Quaternions but I have no idea on how to implement them to a Turn function (one working example is Blitz3D, which has a "RotateEntity" function for global rotation like glRotatef and "TurnEntity" for rotation based on the orientation) I think the function internally works like this:
transform pitch, yaw, roll to a Quaternion like EulerToQuat in
OpenGL + SDL rotation around local axis
perform the local rotation using Quaternion mathematics (no source found)
transform Quaternion back to yaw, roll, pitch (no source found)
I finally solved the problem by switching to carrying a matrix for every ship around all the time. Pitch, yaw and roll are only calculated when needed, which is rarely the case. Finally, glRotatef does the job - you only have to apply it to the already rotated matrix - and save the result, so that the change is not dropped.
Following code is my implementation on a ship structure which carries x,y,z, Matrix[16], dx, dy, dz. (Note that all ship arrays have to be initialized with the IdentityMatrix):
//*************************** Turn Ship **********************************
void TurnShip(long nr,float yaw, float pitch=0,float roll=0) {
//Turns ship by pitch, yaw and roll degrees.
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(&ship[nr].Matrix[0]);
glRotatef(yaw,0,1,0);
glGetFloatv(GL_MODELVIEW_MATRIX,&ship[nr].Matrix[0]);
glLoadMatrixf(&ship[nr].Matrix[0]);
glRotatef(pitch,1,0,0);
glGetFloatv(GL_MODELVIEW_MATRIX,&ship[nr].Matrix[0]);
glLoadMatrixf(&ship[nr].Matrix[0]);
glRotatef(roll,0,0,1);
glGetFloatv(GL_MODELVIEW_MATRIX,&ship[nr].Matrix[0]);
}
What the function does is loading the ships matrix stored in a simple float array, manipulate it and then save it back to the array. In the graphics section of the game, this array will be loaded with glLoadMatrixf and thus will be applied to the ship without any hassle or mathematics.
//*************************** Accelerate Ship relative to own orientation **
void AccelerateShip(long nr,float speedx,float speedy, float speedz)
{ //use speedz to move object "forward".
ship[nr].dx+= speedx*ship[nr].Matrix[0]; //accelerate sidewards (x-vector)
ship[nr].dy+= speedx*ship[nr].Matrix[1]; //accelerate sidewards (x-vector)
ship[nr].dz+= speedx*ship[nr].Matrix[2]; //accelerate sidewards (x-vector)
ship[nr].dx+= speedy*ship[nr].Matrix[4]; //accelerate upwards (y-vector)
ship[nr].dy+= speedy*ship[nr].Matrix[5]; //accelerate upwards (y-vector)
ship[nr].dz+= speedy*ship[nr].Matrix[6]; //accelerate upwards (y-vector)
ship[nr].dx+= speedz*ship[nr].Matrix[8]; //accelerate forward (z-vector)
ship[nr].dy+= speedz*ship[nr].Matrix[9]; //accelerate forward (z-vector)
ship[nr].dz+= speedz*ship[nr].Matrix[10]; //accelerate forward (z-vector)
}
This is the best part of what I learned today - the part the tutorials often don't tell you as they are all about maths - I can pull the vectors that point up, left and in front of my ship right out of the matrix and apply acceleration upon them so that my ship can strave left,right,up down, accelerate and brake - and glRotatef cares for them so they are always updated and no maths involved at our side at all :-)

Transformations in computer graphics

I am trying to follow this course about computer graphics, but I'm stuck in the homework 1. I don't understand what's the role of the vector eye and up. The descripcion of the homework can be found in this link, there's also the skeleton of the first assignment.
So far I have the following code:
// Transform.cpp: implementation of the Transform class.
#include "Transform.h"
//Please implement the following functions:
// Helper rotation function.
mat3 Transform::rotate(const float degrees, const vec3& axis) {
// Please implement this.
float radians = degrees * M_PI / 180.0f;
mat3 r1(cos(radians));
mat3 r2(0, -axis.z, axis.y, axis.z, 0, -axis.x, -axis.y, axis.x, 0);
mat3 r3(axis.x*axis.x, axis.x*axis.y, axis.x*axis.z,
axis.x*axis.y, axis.y*axis.y, axis.y*axis.z,
axis.x*axis.z, axis.z*axis.y, axis.z*axis.z);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
r2[i][j] = r2[i][j]*sin(radians);
r3[i][j] = r3[i][j]*(1-cos(radians));
}
}
return r1 + r2 + r3;
}
// Transforms the camera left around the "crystal ball" interface
void Transform::left(float degrees, vec3& eye, vec3& up) {
eye = eye * rotate(degrees, up);
}
// Transforms the camera up around the "crystal ball" interface
void Transform::up(float degrees, vec3& eye, vec3& up) {
vec3 newAxis = glm::cross(eye, up);
}
// Your implementation of the glm::lookAt matrix
mat4 Transform::lookAt(vec3 eye, vec3 up) {
return lookAtMatrix;
}
Transform::Transform()
{
}
Transform::~Transform()
{
}
for the left method it appears to be doing the right thing, which is, rotating the object around the y-axis (actually I'm not sure if the object is moving or what I'm moving is the camera, can someone clarify?).
for the up method I cannot make it work which will be rotating the object (or camera?) around the x-axis (at least that's what I think).
finally, I don't understand what should the lookAt method should do.
Can someone help me understand the actions to be performed?
Can someone explain what are the roles of vectors eye and up?
View transforms are often implemented using a "look-at" function. The idea being that you specify where the camera is, what direction it is looking in, and what direction represents "up" in your particular space, and you get a matrix back which represents that transform.
It looks like you're trying to implement some kind "rotating ball" navigation control. That's fairly simple - horizontal movement should rotate around some "Y" axis, and vertical movement should rotate around the "right" (or X) axis. Generally those rotations work around the current view axes, rather than globally, so that the movement is intuitive. I'm not sure exactly what you're looking for there.
A look-at function works as follows.
A 3x3 matrix representing a rotation can be viewed as being composed the 3 perpendicular unit axes of the space you are transforming into. So if you can supply those vectors, you can build the matrix.
The first axis is easy. A camera is typically oriented to look along "Z", so if you take the vector representing the direction of the thing being looked at from the camera's position, then normalise it, this is the Z axis.
Then you need to define a distinct 'up' vector - (0,1,0) is typical, but you will need to choose a different one in cases where the Z-axis is pointing in the same direction.
The cross product of this 'up' vector and the 'Z' axis gives the 'X' axis - this is because the cross product gives a perpendicular vector, and what constitutes horizontal will be perpendicular to both the 'forward' direction, and 'up'.
Then the cross product of the 'X' and 'Z' axes gives the 'Y' axis (which is not necessarily the same as the 'Y' axis - consider looking towards the ceiling or towards the floor).
These three axes, normalised, (x,y,z) directly form a rotation matrix.
The translation portion of the matrix is generally the position of the camera, transformed by the rotation's inverse (such that when transforming the camera position by the lookat matrix itself, it should end up back at the origin).
1) Your course is using the OpenGL library, and your homework assignment is to fill in the skeleton module "Transform.cpp".
2) The method you're asking about is "mat4 Transform::lookAt(vec3 eye, vec3 up)":
lookAt: Finally, you need to code in the transformation matrix, given
the eye and up vectors. You will likely need to refer to the class
notes to do this. It is likely to help to dene a uvw coordinate frame
(as 3 vectors), and to build up an auxiliary 4 4 matrix M which is
returned as the result of this function. Consult class notes and
lectures for this part.
3) A hint for what these two arguments "eye" and "up" mean should be in your class notes and lectures.
4) Another hint is to "define a uvw coordinate frame (as three vectors), and build up an auxiliary 4x4 matrix ... which is returned as a result...".
5) A final hint:
Q: What's the difference between an OpenGL mat3 and mat4?
A:
What extractly mat3(a mat4 matrix) statement in glsl do?
mat3(MVI) * normal
Returns the upper 3x3 matrix from the 4x4 matrix and multiplies the
normal by that. This matrix is called the 'normal matrix'. You use
this to bring your normals from world space to eye space.
The reason why the original matrix is 4x4 and not 3x3 is because 4x4
matrices let you do affine transformations and contain useful
information for perspective rendering. But to take a normal from world
space to eye space, you just need the 3x3 model view matrix.

"Looking At" an object with a Quaternion

So I am currently trying to create a function that will take two 3D points A and B, and provide me with the quaternion representing the rotation required of point A to be "looking at" point B (such that point A's local Z axis passes through point B, if you will).
I originally found this post, the top answer of which seemed to provide me with a good starting point. I went on to implement the following code; instead of assuming a default (0, 0, -1) orientation, as the original answer suggests, I try to extract a unit vector representing the actual orientation of the camera.
void Camera::LookAt(sf::Vector3<float> Target)
{
///Derived from pseudocode found here:
///https://stackoverflow.com/questions/13014973/quaternion-rotate-to
//Get the normalized vector from the camera position to Target
sf::Vector3<float> VectorTo(Target.x - m_Position.x,
Target.y - m_Position.y,
Target.z - m_Position.z);
//Get the length of VectorTo
float VectorLength = sqrt(VectorTo.x*VectorTo.x +
VectorTo.y*VectorTo.y +
VectorTo.z*VectorTo.z);
//Normalize VectorTo
VectorTo.x /= VectorLength;
VectorTo.y /= VectorLength;
VectorTo.z /= VectorLength;
//Straight-ahead vector
sf::Vector3<float> LocalVector = m_Orientation.MultVect(sf::Vector3<float>(0, 0, -1));
//Get the cross product as the axis of rotation
sf::Vector3<float> Axis(VectorTo.y*LocalVector.z - VectorTo.z*LocalVector.y,
VectorTo.z*LocalVector.x - VectorTo.x*LocalVector.z,
VectorTo.x*LocalVector.y - VectorTo.y*LocalVector.x);
//Get the dot product to find the angle
float Angle = acos(VectorTo.x*LocalVector.x +
VectorTo.y*LocalVector.y +
VectorTo.z*LocalVector.z);
//Determine whether or not the angle is positive
//Get the cross product of the axis and the local vector
sf::Vector3<float> ThirdVect(Axis.y*LocalVector.z - Axis.z*LocalVector.y,
Axis.z*LocalVector.x - Axis.x*LocalVector.z,
Axis.x*LocalVector.y - Axis.y*LocalVector.x);
//If the dot product of that and the local vector is negative, so is the angle
if (ThirdVect.x*VectorTo.x + ThirdVect.y*VectorTo.y + ThirdVect.z*VectorTo.z < 0)
{
Angle = -Angle;
}
//Finally, create a quaternion
Quaternion AxisAngle;
AxisAngle.FromAxisAngle(Angle, Axis.x, Axis.y, Axis.z);
//And multiply it into the current orientation
m_Orientation = AxisAngle * m_Orientation;
}
This almost works. What happens is that the camera seems to rotate half the distance towards the Target point. If I attempt the rotation again, it performs half the remaining rotation, ad infinitum, such that if I hold down the "Look-At-Button", the camera's orientation gets closer and closer to looking directly at the target, but is also constantly slowing down in its rotation, such that it never quite gets there.
Note that I don't want to resort to gluLookAt(), as I will also eventually need this code to point objects other than the camera at one another, and my objects already use quaternions for their orientations. For example, I might want to create an eyeball that tracks the position of something moving around in front of it, or a projectile that updates its orientation to seek out its target.
Normalize Axis vector before passing it to FromAxisAngle.
Why are you using a quaternion? You're just making things more complex and requiring more computation in this instance. To set up a matrix:-
calculate vector from observer to observed (which you're doing already)
normalise it (again, doing it already) = at
cross product this with the observer's up direction = right
normalise right
cross product at and right to get up
and you're done. The right, up and at vectors are the first, second and third row (or column, depending on how you set things up) of your matrix. The final row/column is the objects position.
But it looks like you want to transform an existing matrix to this new matrix over several frames. SLERPs do this to matricies as well as quaternions (which isn't surprising when you look into the maths). For the transformation, store the initial and target matricies and then SLERP between them, changing the amount to SLERP by each frame (e.g. 0, 0.25, 0.5, 0.75, 1.0 - although a non-linear progression would look nicer).
Don't forget that you're converting a quaternion back into a matrix in order to pass it to the rendering pipeline (unless there's some new features in the shaders to handle quaternions natively). So any efficencies due to quaternion use has to take into account the conversion process as well.