Rotate scene about Up vector in jsc3d - matrix

I'm using jsc3d to load and display some 3d objects on a canvas. The viewer has already a built-in feature that allows to rotate the "view coordinates" (correct me if i'm wrong) about the Y axis by dragging the mouse.
The rotation is performed through a classic rotation matrix, and finally the trasformation matrix is multiplied by this rotation matrix.
The totation about the Y axis is calculated in a way that resembles a circular movement around the whole scene of loaded objects:
JSC3D.Matrix3x4.prototype.rotateAboutYAxis = function(angle) {
if(angle != 0) {
angle *= Math.PI / 180;
var c = Math.cos(angle);
var s = Math.sin(angle);
var m00 = c * this.m00 + s * this.m20;
var m01 = c * this.m01 + s * this.m21;
var m02 = c * this.m02 + s * this.m22;
var m03 = c * this.m03 + s * this.m23;
var m20 = c * this.m20 - s * this.m00;
var m21 = c * this.m21 - s * this.m01;
var m22 = c * this.m22 - s * this.m02;
var m23 = c * this.m23 - s * this.m03;
this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03;
this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23;
}
};
Now, dragging the mouse will apply this rotation about the Y axis on the whole world, like on the left side in the picture below. Is there a way, to apply a rotation about the Up vector to keep it in the initial position, like it appear on the right side?
I tried something like that:
var rotY = (x - viewer.mouseX) * 360 / viewer.canvas.height;
var rotMat = new JSC3D.Matrix3x4; // identity
rotMat.rotateAboutYAxis(rotY);
viewer.rotMatrix.multiply(rotMat);
but it has no effect.
What operations shall be applied to my rotation matrix to achieve a rotation about the Up vector?
Sample: https://jsfiddle.net/4xzjnnar/1/

This 3D library has already some built-in functions to allow scene rotation about X,Y,and Z axis, so there is no need to implement new matrix operations for that, we can use the existing functions rotateAboutXAyis, rotateAboutYAxis and rotateAboutZAxis, which apply an in-place matrix multiplication of the desired rotation angle in degrees.
The scene in JSC3D is transformed by a 3x4 matrix where the rotation is stored in the first 3 values of each row.
After applying a scene rotation and/or translation, applying a subsequent rotation about the Up vector, is a problem of calculate a rotation about an arbitrary axis.
A very clean and didactic explanation how to solve this problem is described here: http://ami.ektf.hu/uploads/papers/finalpdf/AMI_40_from175to186.pdf
Translate the P 0 (x 0 ,y 0 ,z 0 ) axis point to the origin of the coordinate system.
Perform appropriate rotations to make the axis of rotation coincident with
z-coordinate axis.
Rotate about the z-axis by the angle θ.
Perform the inverse of the combined rotation transformation.
Perform the inverse of the translation.
Now, its easy to write a function for that, because we use the functions already available in JSC3D (translation part is omitted here).
JSC3D.Viewer.prototype.rotateAboutUpVector = function(angle) {
angle %= 360;
/* pitch, counter-clockwise rotation about the Y axis */
var degX = this.rpy[0], degZ = this.rpy[2];
this.rotMatrix.rotateAboutXAxis(-degX);
this.rotMatrix.rotateAboutZAxis(-degZ);
this.rotMatrix.rotateAboutYAxis(angle);
this.rotMatrix.rotateAboutZAxis(degZ);
this.rotMatrix.rotateAboutXAxis(degX);
}
Because all above mentioned functions are using degrees, we need to get back the actual Euler angles from the rotation matrix (simplified):
JSC3D.Viewer.prototype.calcRollPitchYaw = function() {
var m = this.rotMatrix;
var radians = 180 / Math.PI;
var angleX = Math.atan2(-m.m12, m.m22) * radians;
var angleY = Math.asin(m.m01) * radians;
var angleZ = Math.atan2(-m.m01, m.m00) * radians;
this.rpy[0] = angleX;
this.rpy[1] = angleY;
this.rpy[2] = angleZ;
}
The tricky part here, is that we need always to get back the current rotation angles, as they results from the applied rotations, so a separate function must be used to store the current Euler angles every time that a rotation is applied to the scene.
For that, we can use a very simple structure:
JSC3D.Viewer.prototype.rpy = [0, 0, 0];
This will be the final result:

Related

Monogame - Rotate Sprite around centre of screen and itself

I have a problem and although I serached everywhere I couldn't find a solution.
I have a stacked sprite and I'm rotating this sprite around the center of the screen. So I iterate over a list of sprites (stacked) and increase the y-coordinate by 2 every loop (rotation is increased step by step by 0.01f outside of the loop):
foreach(var s in stacked)
{
Vector2 origin = new Vector2(Basic.width / 2, Basic.height / 2);
Rectangle newPosition = new Rectangle(position.X, position.Y - y, position.Width, position.Height);
float angle = 0f;
Matrix transform = Matrix.CreateTranslation(-origin.X, -origin.Y, 0f) *
Matrix.CreateRotationZ(rotation) *
Matrix.CreateTranslation(origin.X, origin.Y, 0f);
Vector2 pos = new Vector2(newPosition.X, newPosition.Y);
pos = Vector2.Transform(pos, transform);
newPosition.X = (int)pos.X;
newPosition.Y = (int)pos.Y;
angle += rotation;
s.Draw(newPosition, origin, angle, Color.White);
y += 2;
}
This works fine. But now my problem. I want not only to rotate the sprite around the center of the screen but also around itself. How to achieve this? I can only set one origin and one rotation per Draw. I would like to rotate the sprite around the origin 'Basic.width / 2, Basic.height / 2' and while it rotates, around 'position.Width / 2, position.Height / 2'. With different rotation speed each. How is this possible?
Thank you in advance!
Just to be clear:
When using SpriteBatch.Draw() with origin and angle, there is only one rotation: the final angle of the sprite.
The other rotations are positional offsets.
The origin in the Draw() call is a translation, rotation, translate back. Your transform matrix shows this quite well:
Matrix transform = Matrix.CreateTranslation(-origin.X, -origin.Y, 0f) *
Matrix.CreateRotationZ(rotation) *
Matrix.CreateTranslation(origin.X, origin.Y, 0f);
//Class level variables:
float ScreenRotation, ScreenRotationSpeed;
float ObjectRotation, ObjectRotationSpeed;
Vector2 ScreenOrigin, SpriteOrigin;
// ...
// In constructor and resize events:
ScreenOrigin = new Vector2(Basic.width <<1, Basic.height <<1);
// shifts are faster for `int` type. If "Basic.width" is `float`:
//ScreenOrigin = new Vector2(Basic.width, Basic.height) * 0.5f;
// In Update():
ScreenRotation += ScreenRotationSpeed; // * gameTime.ElapsedGameTime.Seconds; // for FPS invariant speed where speed = 60 * single frame speed
ObjectRotation+= ObjectRotationSpeed;
//Calculate the screen center rotation once per step
Matrix baseTransform = Matrix.CreateTranslation(-ScreenOrigin.X, -ScreenOrigin.Y, 0f) *
Matrix.CreateRotationZ(ScreenRotation) *
Matrix.CreateTranslation(ScreenOrigin.X, ScreenOrigin.Y, 0f);
// In Draw() at the start of your code snippet posted:
// moved outside of the loop for a translationally invariant vertical y interpretation
// or move it inside the loop and apply -y to position.Y for an elliptical effect
Vector2 ObjectOrigin = new Vector2(position.X, position.Y);
Matrix transform = baseTransform *
Matrix.CreateTranslation(-ObjectOrigin.X, -ObjectOrigin.Y, 0f) *
Matrix.CreateRotationZ(ObjectRotation) *
Matrix.CreateTranslation(ObjectOrigin.X, ObjectOrigin.Y, 0f);
foreach(var s in stacked)
{
Vector2 pos = new Vector2(ObjectOrigin.X, ObjectOrigin.Y - y);
pos = Vector2.Transform(pos, transform);
float DrawAngle = ObjectRotation;
// or float DrawAngle = ScreenRotation;
// or float DrawAngle = ScreenRotation + ObjectRotation;
// or float DrawAngle = 0;
s.Draw(pos, SpriteOrigin, DrawAngle, Color.White);
}
I suggest moving the Draw() parameter away from destinationRectangle and use the Vector2 position directly with scaling. Rotations within square rectangles can differ up to SQRT(2) in aspect ratio, i.e. stretching/squashing. Using Vector2 incurs a cost of higher collision complexity.
I am sorry for the ors, but without complete knowledge of the problem...YMMV
In my 2D projects, I use the vector form of polar coordinates.
The Matrix class requires more calculations than the polar equivalents in 2D. Matrix operates in 3D, wasting cycles calculating Z components.
With normalized direction vectors (cos t,sin t) and a radius(vector length),in many cases I use Vector2.LengthSquared() to avoid the square root when possible.
The only time I have used Matrices in 2D is display projection matrix(entire SpriteBatch) and Mouse and TouchScreen input deprojection(times the inverse of the projection matrix)

Get rotation about y-axis from rotation matrix

i can't figure out how to extract the rotation around the global y-axis from the model matrix of my object.
I have the current model matrix from my object as an glm::mat4 and i need to cancel out the rotation around the y-axis.
Are there any functions in glm i haven't noticed?
You have to convert the rotation part of the matrix to Euler angles. It is not a trivial operation. I don't know if "glm" have a function for that, but there is a code (other methods may exists) to convert rotation part of a 4x4 matrix to X, Y and Z Euler angles:
function Matrix4ToEuler(OutEuler, InMatrix4)
{
let cy = Math.sqrt(InMatrix4[0] * InMatrix4[0] + InMatrix4[1] * InMatrix4[1]);
if(cy > 0.001) {
OutEuler.x = Math.atan2(InMatrix4[6], InMatrix4[10]);
OutEuler.y = Math.atan2(-InMatrix4[2], cy);
OutEuler.z = Math.atan2(InMatrix4[1], InMatrix4[0]);
} else {
OutEuler.x = Math.atan2(-InMatrix4[9], InMatrix4[5]);
OutEuler.y = Math.atan2(-InMatrix4[2], cy);
OutEuler.z = 0;
}
}

Points inside circular sector

I am working on a mobile application. My application gets the user position and orientation and then show some points of interest near his location.
Now, what I need is to know if the user is in front of a point of interest. My idea is to do this based on his position and orientation, using a circular sector of a small radius (about 5 meters) and I want to know if there is any formula or if anyone has a recommendation on how to achieve this.
I assume you have Lat/Lon coordinates and user moving/viewing azimuth.
You can calculate direction to object and it's bearing (azimuth) and compare with your limits.
Note: It is difficult to ensure 5 meters precision with GPS/geolocation
This excellent page contains all the needed formulas. Excerpt:
distance
JavaScript:
var R = 6371000; // metres
var φ1 = lat1.toRadians();
var φ2 = lat2.toRadians();
var Δφ = (lat2-lat1).toRadians();
var Δλ = (lon2-lon1).toRadians();
var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
bearing
JavaScript:
(all angles in radians)
var y = Math.sin(λ2-λ1) * Math.cos(φ2);
var x = Math.cos(φ1)*Math.sin(φ2) -
Math.sin(φ1)*Math.cos(φ2)*Math.cos(λ2-λ1);
var brng = Math.atan2(y, x).toDegrees();

famo.us quaternion rotation around z axis

As far as I know a quaternion is a set of four values (W X Y Z) that are used to specify a rotation in 3D space. For a given axis (x y z) and angle (α), the quaternion representing a rotation around the axis from the origin (0,0,0) to (x,y,z). So a rotation of 90 degrees about the z axis (0 0 1) should be:
var quaternion = new Quaternion(Math.PI/2, 0, 0, 1);
but famo.us turns it for ~60 degrees...
I've also tried var quaternion = new Quaternion(90, 0, 0, 1); but in this case famo.us turns it for ~5 degrees
is it a bug of the framework?
How should I use it to turn it on 90 degreez around z axis?
Documentation is still totally useless..
Try using this method Quaternion.makeFromAngleAndAxis(angle, v)
I have found this to be the most straight forward approach to making it a little more readable and useable.
Example jsBin
Where
var degrees = 90;
var angle = Math.PI/180 * degrees;
var v = new Vector(0, 0, 1);
var quaternion = new Quaternion();
quaternion.makeFromAngleAndAxis(angle, v);
...To get the transform
quaternion.getTransform();
Something to remember from Math Class
A circle has 360 degrees. Each degree is represented by the unit circumference of a circle 2 * PI * r. We will assume we have a radius of 1. So divide your total circumference by 360 and you get one degrees 2PI/360 or PI/180.
In Summary:
one degrees of our circle is = Math.PI/180
your angle of direction is = Math.PI/180 * degrees
Just found answer in one wiki article:
var angle = Math.PI/2;
var axis = [0,0,1];
var w = Math.cos(.5 * angle);
var x = axis[0] * Math.sin(.5 * angle);
var y = axis[1] * Math.sin(.5 * angle);
var z = axis[2] * Math.sin(.5 * angle);
var quaternion = new Quaternion(w, x, y, z);
try this transformation - Transform.rotateZ(angle);
Refer to - http://famo.us/docs/reference/pages/0.3/transforms.html

Transform mouse coordinates to 3d coordinates

I have the following problem:
I have my mouse coordinates and I have a Model (Data Points) and I want the 3d Coordinates of my mouse coordinates and my lookAt Vector of this coordinates, so that I can make a raycast with the object, so that I can see the 3d values of the data points. So I want to click with the mouse and then I want to see the coordinates of the datapoint I clicked at.
I have the following from a tutorial, but it doesn't work. The ray origin and ray direction are not correct (I draw I line from ray origin in the ray direction and the ray origin isn't right:
Can anyone help me? Here is the code:
// Move the mouse cursor coordinates into the -1 to +1 range.
pointX = ((2.0f * (float)mouseX) / (float) screen_width) - 1.0f;
pointY = (((2.0f * (float)mouseY) / (float) screen_height) - 1.0f) * -1.0f;
m_D3D->GetProjectionMatrix(projectionMatrix);
pointX = pointX / projectionMatrix._11;
pointY = pointY / projectionMatrix._22;
// Get the inverse of the view matrix.
m_Camera->GetViewMatrix(viewMatrix);
D3DXMatrixInverse(&inverseViewMatrix, NULL, &viewMatrix);
// Calculate the direction of the picking ray in view space.
direction.x = (pointX * inverseViewMatrix._11) + (pointY * inverseViewMatrix._21)+
inverseViewMatrix._31;
direction.y = (pointX * inverseViewMatrix._12) + (pointY * inverseViewMatrix._22)
+ inverseViewMatrix._32;
direction.z = (pointX * inverseViewMatrix._13) + (pointY * inverseViewMatrix._23)
+ inverseViewMatrix._33;
// Get the origin of the picking ray which is the position of the camera.
origin = m_Camera->GetPosition();
// Get the world matrix and translate to the location of the sphere.
m_Impact->GetWorldMatrix(worldMatrix);
//D3DXMatrixTranslation(&translateMatrix, -5.0f, 1.0f, 5.0f);
//D3DXMatrixMultiply(&worldMatrix, &worldMatrix, &translateMatrix);
// Now get the inverse of the translated world matrix.
D3DXMatrixInverse(&inverseWorldMatrix, NULL, &worldMatrix);
D3DXVec3TransformCoord(&rayOrigin, &origin, &inverseWorldMatrix);
D3DXVec3TransformNormal(&rayDirection, &direction, &inverseWorldMatrix);
// Normalize the ray direction.
D3DXVec3Normalize(&rayDirection, &rayDirection);
//collision_object->setTransform(col_matrix);
collision_model->setTransform(col_matrix);
float collision_point[3];
//bool collision_result = collision_object ->rayCollision(rayOrigin,
rayDirection, true);
bool collision_result = collision_model ->rayCollision(rayOrigin,
rayDirection, true);
if(collision_result == true)
{
intersect = true;
//collision_object->getCollisionPoint(collision_point, true);
collision_model->getCollisionPoint(collision_point, false);
*coordX = collision_point[0];
*coordY = collision_point[1];
*coordZ = collision_point[2];
}
One simple way to build a ray from mouse is as follow (pseudo code)
Get mouse coords to -1 -> 1 range (as you already do)
Create view projection matrix (view*projection)
Invert it.
Create 2 mouse vectors:
near = Vector3(mousex,mousey,0);
far = Vector3(mousex,mousey,1);
rayorigin = transformcoord(near, inverseviewprojection);
rayend = transformcoord(far, inverseviewprojection);
raydir = normalize(rayend-rayorigin);

Resources