Creating a matrix for a billboarded quad? - math

I'm trying to come up with a proper algorithm to create a matrix which gets the quad to face the camer straight up but I'm having difficulty.
The quad I'm drawing is facing downwards, here's the code I have so far:
D3DXVECTOR3 pos;
pos = D3DXVECTOR3(-2.0f, 6.0f, 0.1f);
D3DXMATRIX transform;
D3DXMatrixTranslation(&transform, pos.x, pos.y, pos.z);
D3DXVECTOR3 axis = D3DXVECTOR3(0, -1, 0);
D3DXVECTOR3 quadtocam = pos - EmCameraManager::Get().GetPosition();
D3DXVec3Normalize(&quadtocam,&quadtocam);
D3DXVECTOR3 ortho;
D3DXVec3Cross(&ortho, &axis, &quadtocam);
float rotAngle = acos(D3DXVec3Dot(&axis,&quadtocam));
D3DXMATRIX rot;
D3DXMatrixRotationAxis(&rot,&ortho,rotAngle);
transform = rot*transform;
This works when it comes to making the quad face the camera however it doesn't stay up right when facing it from all angles.
In this screen shot: http://imgur.com/hFmzc.png On the left the quad is being viewed straight on (vector is 0,0,1), in the other its being viewed from an arbitrary angle.
Both times it's facing the camera, however when from an arbitrary angle its tilting along its local z axis. I'm not sure how to fix it and was wondering what the next step here would be?

Rotating around an arbitrary axis will always make that. You should rotate your model around y axis first to make it point(up vector) to your camera and after rotate it around your ortho axis which would be aligned with the model's right vector.
Assuming that z axis is coming out of the screen here's some code:
D3DXVECTOR3 Zaxis = D3DXVECTOR3(0, 1, 0);
D3DXVECTOR3 flattenedQuadtocam = quadtocam;
flattenedQuadtocam.y = 0;
float firstRotAngle = acos(D3DXVec3Dot(&Zaxis,&flattenedQuadtocam));
D3DXMATRIX firstRot;
D3DXMatrixRotationAxis(&firstRot,&Zaxis,firstRotAngle);
transform = firstRot*transform;
This should be put right after this line:
D3DXVec3Normalize(&quadtocam,&quadtocam);
Then the rest of your code should work.

Related

Calculate if cannon with limited rotation angles can do fire in 3D space

I want to create a game where it can be a lot of different cannons what will have different limit of fire angle (vertical and horizontal).
I found this formula to calculate angle between cannon and enemy position depend on cannon forward look vector in 2D:
float cannon_limit_angle = Math.PI * 0.5;
//the vectors 2d
vec2 cannon_pos = vec2(1,3);
vec2 cannon_facing = vec2(1,1);
vec2 enemy_pos = vec2(3,2);
//normalized vectors
vec2 cannon_facing_n = normalize(guard_facing);
vec2 enemy_to_cannon = normalize(hero_pos - guard_pos);
// calculating the angle
float angle = acos(dot(cannon_facing_n, enemy_to_cannon));
if (angle < cannon_limit_angle * 0.5) {
// Enemy inside limit angle
}
Now I am wondering how can I achieve this in 3D space?
I need the limits in horizontal and vertical axes. Thanks
If your code works in 2D it will work in 3D space as well,
since is valid in the 3D space. It works in 2D space as a particular case.
You could also simplify, by giving the cosine of the angle instead of the angle itself, then you don't have to calculate the acos of the value, and you reduce your test to a correlation threshold.

How to get the absolute rotation of a Node in JavaFX

In JavaFX the rotateProperty of a Node provides me with its rotation in degree relative to its parent. Is there a way to get the absolute rotation in degree, either relative to the Scene or the Screen?
For example, is there a way to calculate the angle from the Transform object of a Node i can get from getLocalToSceneTransform()?
So, i did the math myself, and for my case i either get the rotation in Radians via:
double xx = myNode.getLocalToSceneTransform().getMxx();
double xy = myNode.getLocalToSceneTransform().getMxy();
double angle = Math.atan2(-xy, xx);
or
double yx = myNode.getLocalToSceneTransform().getMyx();
double yy = myNode.getLocalToSceneTransform().getMyy();
double angle = Math.atan2(yx, yy);
In both cases this can be converted to 360-degrees:
angle = Math.toDegrees(angle);
angle = angle < 0 ? angle + 360 : angle;
The question isn't really well defined, since different Nodes in the Scene graph are potentially rotated about different axes.
The getLocalToSceneTransform() method will return a Transform representing the transformation from the local coordinate system for the node to the coordinate system for the Scene. This is an affine transformation; you can extract a 3x4 matrix representation of it relative to the x- y- and z-axes if you like.

Drawing a rotating sphere by using a pixel shader in Direct3D

I would like to draw a textured circle in Direct3D which looks like a real 3D sphere. For this purpose, I took a texture of a billard ball and tried to write a pixel shader in HLSL, which maps it onto a simple pre-transformed quad in such a way that it looks like a 3-dimensional sphere (apart from the lighting, of course).
This is what I've got so far:
struct PS_INPUT
{
float2 Texture : TEXCOORD0;
};
struct PS_OUTPUT
{
float4 Color : COLOR0;
};
sampler2D Tex0;
// main function
PS_OUTPUT ps_main( PS_INPUT In )
{
// default color for points outside the sphere (alpha=0, i.e. invisible)
PS_OUTPUT Out;
Out.Color = float4(0, 0, 0, 0);
float pi = acos(-1);
// map texel coordinates to [-1, 1]
float x = 2.0 * (In.Texture.x - 0.5);
float y = 2.0 * (In.Texture.y - 0.5);
float r = sqrt(x * x + y * y);
// if the texel is not inside the sphere
if(r > 1.0f)
return Out;
// 3D position on the front half of the sphere
float p[3] = {x, y, sqrt(1 - x*x + y*y)};
// calculate UV mapping
float u = 0.5 + atan2(p[2], p[0]) / (2.0*pi);
float v = 0.5 - asin(p[1]) / pi;
// do some simple antialiasing
float alpha = saturate((1-r) * 32); // scale by half quad width
Out.Color = tex2D(Tex0, float2(u, v));
Out.Color.a = alpha;
return Out;
}
The texture coordinates of my quad range from 0 to 1, so I first map them to [-1, 1]. After that I followed the formula in this article to calculate the correct texture coordinates for the current point.
At first, the outcome looked ok, but I'd like to be able to rotate this illusion of a sphere arbitrarily. So I gradually increased u in the hope of rotating the sphere around the vertical axis. This is the result:
As you can see, the imprint of the ball looks unnaturally deformed when it reaches the edge. Can anyone see any reason for this? And additionally, how could I implement rotations around an arbitrary axis?
Thanks in advance!
I finally found the mistake by myself: The calculation of the z value which corresponds to the current point (x, y) on the front half of the sphere was wrong. It must of course be:
That's all, it works as exspected now. Furthermore, I figured out how to rotate the sphere. You just have to rotate the point p before calculating u and v by multiplying it with a 3D rotation matrix like this one for example.
The result looks like the following:
If anyone has any advice as to how I could smooth the texture a litte bit, please leave a comment.

Calculation of the position of an object moving in a circular motion in 3D

i have an object that is doing a circular motion in a 3d space, the center or the circle is at x:0,y:0,z:0 the radius is a variable. i know where the object is on the circle (by its angle [lets call that ar] or by the distance it has moved). the circle can be tilted in all 3 directions, so i got three variables for angles, lets call them ax,ay and az. now i need to calculate where exactly the object is in space. i need its x,y and z coordinates.
float radius = someValue;
float ax = someValue;
float ay = someValue;
float az = someValue;
float ar = someValue; //this is representing the angle of the object on circle
//what i need to know
object.x = ?;
object.y = ?;
object.z = ?;
You need to provide more information to get the exact formula. The answer depends on which order you apply your rotations, which direction you are rotating in, and what the starting orientation of your circle is. Also, it will be much easier to calculate the position of the object considering one rotation at a time.
So, where is your object if all rotations are 0?
Let's assume it's at (r,0,0).
The pseudo-code will be something like:
pos0 = (r,0,0)
pos1 = pos0, rotated around Z-axis by ar (may not be Z-axis!)
pos2 = pos1, rotated around Z-axis by az
pos3 = pos2, rotated around Y-axis by ay
pos4 = pos3, rotated around X-axis by ax
pos4 will be the position of your object, if everything is set up right. If you have trouble setting it up, try keeping ax=ay=az=0 and worry about just ar, until your get that right. Then, start setting the other angles one at a time and updating your formula.
Each rotation can be performed with
x' = x * cos(angle) - y * sin(angle)
y' = y * cos(angle) + x * sin(angle)
This is rotation on the Z-axis. To rotate on the Y-axis, use z and x instead of x and y, etc. Also, note that angle is in radians here. You may need to make angle negative for some of the rotations (depending which direction ar, ax, ay, az are).
You can also accomplish this rotation with matrix multiplication, like Marcelo said, but that may be overkill for your project.
Use a rotation matrix. Make sure you use a unit vector.

Given an angle and dimensions, find a coordinate along the perimeter of a rectangle

I'm writing a script where icons rotate around a given pivot (or origin). I've been able to make this work for rotating the icons around an ellipse but I also want to have them move around the perimeter of a rectangle of a certain width, height and origin.
I'm doing it this way because my current code stores all the coords in an array with each angle integer as the key, and reusing this code would be much easier to work with.
If someone could give me an example of a 100x150 rectangle, that would be great.
EDIT: to clarify, by rotating around I mean moving around the perimeter (or orbiting) of a shape.
You know the size of the rectangle and you need to split up the whole angle interval into four different, so you know if a ray from the center of the rectangle intersects right, top, left or bottom of the rectangle.
If the angle is: -atan(d/w) < alfa < atan(d/w) the ray intersects the right side of the rectangle. Then since you know that the x-displacement from the center of the rectangle to the right side is d/2, the displacement dy divided by d/2 is tan(alfa), so
dy = d/2 * tan(alfa)
You would handle this similarily with the other three angle intervals.
Ok, here goes. You have a rect with width w and depth d. In the middle you have the center point, cp. I assume you want to calculate P, for different values of the angle alfa.
I divided the rectangle in four different areas, or angle intervals (1 to 4). The interval I mentioned above is the first one to the right. I hope this makes sense to you.
First you need to calculate the angle intervals, these are determined completely by w and d. Depending on what value alfa has, calculate P accordingly, i.e. if the "ray" from CP to P intersects the upper, lower, right or left sides of the rectangle.
Cheers
This was made for and verified to work on the Pebble smartwatch, but modified to be pseudocode:
struct GPoint {
int x;
int y;
}
// Return point on rectangle edge. Rectangle is centered on (0,0) and has a width of w and height of h
GPoint getPointOnRect(int angle, int w, int h) {
var sine = sin(angle), cosine = cos(angle); // Calculate once and store, to make quicker and cleaner
var dy = sin>0 ? h/2 : h/-2; // Distance to top or bottom edge (from center)
var dx = cos>0 ? w/2 : w/-2; // Distance to left or right edge (from center)
if(abs(dx*sine) < abs(dy*cosine)) { // if (distance to vertical line) < (distance to horizontal line)
dy = (dx * sine) / cosine; // calculate distance to vertical line
} else { // else: (distance to top or bottom edge) < (distance to left or right edge)
dx = (dy * cosine) / sine; // move to top or bottom line
}
return GPoint(dx, dy); // Return point on rectangle edge
}
Use:
rectangle_width = 100;
rectangle_height = 150;
rectangle_center_x = 300;
rectangle_center_y = 300;
draw_rect(rectangle_center_x - (rectangle_width/2), rectangle_center_y - (rectangle_center_h/2), rectangle_width, rectangle_height);
GPoint point = getPointOnRect(angle, rectangle_width, rectangle_height);
point.x += rectangle_center_x;
point.y += rectangle_center_y;
draw_line(rectangle_center_x, rectangle_center_y, point.x, point.y);
One simple way to do this using an angle as a parameter is to simply clip the X and Y values using the bounds of the rectangle. In other words, calculate position as though the icon will rotate around a circular or elliptical path, then apply this:
(Assuming axis-aligned rectangle centered at (0,0), with X-axis length of XAxis and Y-axis length of YAxis):
if (X > XAxis/2)
X = XAxis/2;
if (X < 0 - XAxis/2)
X = 0 - XAxis/2;
if (Y > YAxis/2)
Y = YAxis/2;
if (Y < 0 - YAxis/2)
Y = 0 - YAxis/2;
The problem with this approach is that the angle will not be entirely accurate and the speed along the perimeter of the rectangle will not be constant. Modelling an ellipse that osculates the rectangle at its corners can minimize the effect, but if you are looking for a smooth, constant-speed "orbit," this method will not be adequate.
If think you mean rotate like the earth rotates around the sun (not the self-rotation... so your question is about how to slide along the edges of a rectangle?)
If so, you can give this a try:
# pseudo coode
for i = 0 to 499
if i < 100: x++
else if i < 250: y--
else if i < 350: x--
else y++
drawTheIcon(x, y)
Update: (please see comment below)
to use an angle, one line will be
y / x = tan(th) # th is the angle
the other lines are simple since they are just horizontal or vertical. so for example, it is x = 50 and you can put that into the line above to get the y. do that for the intersection of the horizontal line and vertical line (for example, angle is 60 degree and it shoot "NorthEast"... now you have two points. Then the point that is closest to the origin is the one that hits the rectangle first).
Use a 2D transformation matrix. Many languages (e.g. Java) support this natively (look up AffineTransformation); otherwise, write out a routine to do rotation yourself, once, debug it well, and use it forever. I must have five of them written in different languages.
Once you can do the rotation simply, find the location on the rectangle by doing line-line intersection. Find the center of the orbited icon by intersecting two lines:
A ray from your center of rotation at the angle you desire
One of the four sides, bounded by what angle you want (the four quadrants).
Draw yourself a sketch on a piece of paper with a rectangle and a centre of rotation. First translate the rectangle to centre at the origin of your coordinate system (remember the translation parameters, you'll need to reverse the translation later). Rotate the rectangle so that its sides are parallel to the coordinate axes (same reason).
Now you have a triangle with known angle at the origin, the opposite side is of known length (half of the length of one side of the rectangle), and you can now:
-- solve the triangle
-- undo the rotation
-- undo the translation

Resources