Categories

# How do I compose a rotation matrix with human readable angles from scratch?

The one thing that has always hindered me from doing 3D programming is failing to understand how math works. I can go along with math fine in programming flow using methods and functions, then its all clear and logical to me, but in mathematical notation, I just can’t make heads or tails from it.

I have been reading websites, a watching videos of institutes trying to explain this, but they all use mathematical notation and I simply get lost in it, my mind won’t translate it to something understandable. I might have a defect there.

Also, Just using someone’s code isn’t my interest, I want to understand the mechanics behind it, the logic. I’d be happy to use someone else’s code, but I really want to understand how it works.

The question

Can you explain to me in simple terms without mathematical notation, just programming notation/functions/psuedocode, how to implement a matrix transform along all 3 axes?

Ideally what I want is the material/understanding to write a method/object where I can define the angles of 3 axes similar to glRotate to rotate the collection of quads/triangles I have. (I am trying to program a 3D rotation of a cube shapes without having access to OpenGL functions to do it for me because this is done in one draw call every time something changes in the display list.)

What have I done?

I have attempted at making a 90 degrees transform function to get the hang of the math but failed utterly in making a proper matrix which in theory should have been the simplest to do. You can see my failed attempt in all its glory on http://jsfiddle.net/bLfg0tj8/5/

``````Vec3 = function(x,y,z) {
this.x = x;
this.y = y;
this.z = z;
}
Matrix = function Matrix() {
this.matrixPoints = new Array();
this.rotationPoint = new Vec3(0,0,0);
this.rotationAngle = 90;
}
Matrix.prototype.addVector = function(vector) {
this.matrixPoints.push(vector);
}
Matrix.prototype.setRotationPoint = function(vector) {
this.rotationPoint = vector;
}
Matrix.prototype.setRotationAngle = function(angle) {
this.rotationAngle = angle;
}
Matrix.prototype.populate = function() {
translateToOrigin =     [[1,0,0-this.rotationPoint.x],
[0,1,0-this.rotationPoint.y],
[0,0,0-this.rotationPoint.z]];
rotationMatrix =         [[0,-1,0],
[0,1,0],
[0,0,1]];
translateEnd =         [[1,0,this.rotationPoint.x],
[0,1,this.rotationPoint.y],
[0,0,this.rotationPoint.z]];
currentColumn = 0;
currentRow = 0;
this.combomatrix = this.mergeMatrices(this.mergeMatrices(translateEnd,rotationMatrix),
translateToOrigin);
}
Matrix.prototype.transform = function() {
newmatrix = new Array();
for(c = 0;c<this.matrixPoints.length;c++) {
newmatrix.push(this.applyToVertex(this.matrixPoints[c]));
}
return newmatrix;
}
Matrix.prototype.applyToVertex = function(vertex) {
ret = new Vec3(vertex.x,vertex.y,vertex.z);
ret.x = ret.x + this.combomatrix * vertex.x +
this.combomatrix * vertex.y +
this.combomatrix * vertex.z;

ret.y = ret.y + this.combomatrix * vertex.x +
this.combomatrix * vertex.y +
this.combomatrix * vertex.z;

ret.z = ret.z + this.combomatrix * vertex.x +
this.combomatrix * vertex.y +
this.combomatrix * vertex.z;
return ret;
}
Matrix.prototype.mergeMatrices = function(lastStep, oneInFront) {
step1 = [[0,0,0],[0,0,0],[0,0,0]];
step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;

step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;

step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;
//============================================================
step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;

step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;

step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;
//============================================================
step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;

step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;

step1 =   lastStep * oneInFront +
lastStep * oneInFront +
lastStep * oneInFront;
return step1;
}
Matrix.prototype.getCurrentMatrix = function() {
return this.matrixPoints;
}
myvectors = [new Vec3(50,50,0), new Vec3(20,80,0), new Vec3(80, 80, 0)];

function drawVectors(vectors,color) {
for(c=0;c<vectors.length;c++) {
document.getElementById("whoa").innerHTML += '<div style="color:'+color+';position:absolute;left:'+vectors[c].x+'px; top:'+vectors[c].y+'px;z-index:'+vectors[c].z+';">('+c+').</div>';
}
}
matrix = new Matrix();
for(c=0;c<myvectors.length;c++) {
}
matrix.setRotationPoint(new Vec3(50,70,0));
matrix.populate();
somematrix = matrix.transform();
drawVectors(matrix.getCurrentMatrix(),"lime"); // draw current matrix that was hand coded
drawVectors([matrix.rotationPoint],'white'); // draw rotation point
drawVectors(somematrix,"red"); // transformed matrix... somehow two points merge``````
``````<div id="whoa" style="position:relative;top:50px;left:150px;background-color:green;color:red;width:400px;height:300px;">
&nbsp;
</div>``````

The green text is the original triangle, the white point the center point, the red points the failed transformation(I think, because it isn’t aligned around the center point). The tutorial I was in thought me how to combine matrices into a combined matrix, but I guess I screwed up somewhere.

As I said, it’s really really hard for me to understand mathematical notation and speak. And not helping is that most teachers skip parts of the explanation. Took me 2 hours alone to understand when multiplying matrices you need to add each step together instead of just keep on multiplying. Yay for explanations.

A practical example what I work with/want to work with

For example I have a cube, loaded from a wavefront obj file located in the world at

``````x = 50
y = 100
z = 200
``````

The cube is drawn using quads and some uv mapping. No problems here. It renders beautifully with all the textures showing correctly.

These are the location coordinates for each “face” of the cube which is drawn using a quad.

``````// Front face
-1.0, -1.0,  1.0,
1.0, -1.0,  1.0,
1.0,  1.0,  1.0,
-1.0,  1.0,  1.0,

// Back face
-1.0, -1.0, -1.0,
-1.0,  1.0, -1.0,
1.0,  1.0, -1.0,
1.0, -1.0, -1.0,

// Top face
-1.0,  1.0, -1.0,
-1.0,  1.0,  1.0,
1.0,  1.0,  1.0,
1.0,  1.0, -1.0,

// Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0,  1.0,
-1.0, -1.0,  1.0,

// Right face
1.0, -1.0, -1.0,
1.0,  1.0, -1.0,
1.0,  1.0,  1.0,
1.0, -1.0,  1.0,

// Left face
-1.0, -1.0, -1.0,
-1.0, -1.0,  1.0,
-1.0,  1.0,  1.0,
-1.0,  1.0, -1.0
``````

So this works all great. But what if I want this cube rotated 90 degrees along the x axis and 45 degrees around the z axis? I cannot use glRotate because at the moment I pass the data to the tesselator object I cannot do any matrix transforms to it via the opengl functions because it’s just taking in the data, not actually rendering it per se.

The way the data is stored is as following:

``````WaveFrontObject()
|
|-> Groups(String groupname)
|
|-> Faces()
|
|-> Vertex(float x, float y, float z)[]
|-> Float UVmap[] corresponding to each vertex
|-> drawFace() // Draws the face as a quad or triangle
``````

So each of the above coordinates I gave is stored as a face of the wavefront object in the group “cube”.

When the cube is added to the tesselator it is translated to the right coordinates in the world and it renders normal.

It always renders the same however. If I would want it to render at an angle I would have to make a seperate wavefront object at this moment to be able to do that. In my opnion that is madness to do when it can be solved with some math.

Needed in the answer

1. Explanation step by step how to build a translation matrix and an attempt to explain the math to me.
2. Explanation how to apply the translation matrix to the quads/triangles in the faces whist they keep oriented around the center of their location

x = 50.5
y = 100.5
z = 200.5

3. Some example/pseudo code to go along with the explanation.

The used programming language used to explain isn’t really relevant as long as its in the C family

Please try to stay away from mathematical notation/speak. I don’t know what alpha beta, thetha is, I do know what x axis, y axis and z axis is. I do know what angles are, but I do not know the names mathematicians find for it.

If you wish to use math names, please explain to me what they are in the 3D world/code and how they are formed/calculated.

I simply want to make a method/object along the lines of

``````Matrix.transformVertices(vertices[], 90deg x, 45 deg y, 0 deg z);
``````

• The whole purpose of mathematical notation is to make things easier to understand. A programmed algorithm will always be just a specialized case of a general mathematical concept. When it comes to linear algebra, I think you might find this very helpful (especially how a matrix acts as a “function” on pieces of incoming data): betterexplained.com/articles/linear-algebra-guide

Jan 21, 2015 at 20:20

• What you ask is impossible. Of course you can copy and paste a matrix class or a rotation method, i am sure you can find plenty out there. Therein you will see arrays summed and multiplied with each other following some for-loop schemes. If you know arrays and for loops that is as close as you can get with a purely programming and no-mathematics way to understand it. If that is not enough for you, you have to continue to try to learn the math. Sometimes this is hard if all tutorials don’t match your way of thinking, but maybe you can visit a course or sth where you live.

Jan 21, 2015 at 20:47

• While I would feel bad to downvote such a carefully written question, I agree with the previous commenters that it’s a tough request. And I don’t think it’s a good fit for SO. Explaining mathematical concepts without mathematical notation is almost a contradiction in itself. And even though this is fairly basic math, it would still take a substantial amount of explanation if everything has to be explained from scratch. If I gave it a shot despite all that, I’m still not sure that I would do better than all the people who get paid for writing math books. Then the whole thing might get deleted.

Jan 22, 2015 at 6:15

• Michael Faraday struggled with math notation, too, and he seemed to do ok en.wikipedia.org/wiki/Michael_Faraday

Jul 3, 2017 at 17:46

• I know this question is about a year old and already has an accepted answer I’d still like to point out a few quick simple things that can still help in the understanding of some of the math behind 3D Transformations. First is the simple use of an open source and header only C++ Library called `glm` you can find it here: glm.g-truc.net/0.9.9/index.html and a very good video series that pertains to many different fields of math that may be useful found here: youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw/…. Look for the linear algebra series!

Nov 7, 2018 at 11:10

So the question really is Understanding 4×4 homogenous transform matrices

well without the math behind the only thing that left is geometric representation/meaning which is far better for human abstraction/understanding.

1. So what the 4×4 matrix is?

It is representation of some Cartesian coordinate system and it is composed of:

1. `3` basis vectors (one for each axis) red,green,blue

So if the red,green,blue vectors are perpendicular to each other then the coordinate system is orthogonal. If they are also unit vectors then it is orthonormal (like for example unit matrix).

2. origin point gray

3. projection and homogenous side (unmarked bottom rest of the matrix)

This part is there only for enabling rotation and translation at once, therefore point used must be homogenous that means in form `(x,y,z,w=1)` for points and `(x,y,z,w=0)` for direction vectors. If it was just `(x,y,z)` then the matrix would be `3x3` and that is not enough for translation. I will not use any projections they are uneasy to explain geometrically.

This layout is from OpenGL notation there are also transposed representation out there (vectors are rows not columns)

now how to transform any point to/from this coordinate system:

``````g=M*l;
l=Inverse(M)*g;
``````

where:

• `M` is transform matrix
• `l` is `M` local coordinate system point (LCS)
• `g` is global coordinate system point (GCS)

for the transposed version (DirectX) it is:

``````l=M*g;
g=Inverse(M)*l;
``````

That is because transposed orthogonal rotation matrix is also inverse of itself 2. how to visualize it

Yes you can draw the matrix numbers but they do not make sense at first look especially if the numbers are changing so draw the axises vectors as on image above. Where each axis is a line from `origin` to `origin + line_size*axis_vector`

3. how to construct it

Just compute axis vectors and origin and put them inside matrix. To ensure orthogonality exploit cross product (but be careful with order of multiplicants to use the right direction) Here example of getting 3 basis vectors from direction

4. effects

• rotation is done by rotating the axises so you can compute each axis by parametric circle equation …
• scaling is done by multiplying axises by scale factor
• skewing is just using non perpendicular axises
5. rotation

For most cases the incremental rotation is used. There are two types

• local rotation `M'=M*rotation_matrix` it rotates around local coordinate axises like you will control plane or car or player … Most engines/games do not use these and fake it with euler angles instead which is a cheap solution (have many quirks and problems) because most people who using OpenGL do not even know this is possible and rather stack list of `glRotate/glTranslate` calls…

• global rotation `M'=Inverse(Inverse(M)*rotation_matrix)` it rotates around global coordinate system axises.

where `rotation_matrix` is any standard rotation transform matrix.

If you have different matrix layout (transposed) then the rotations local and global are computed the other way around …

You can also compute your `rotation_matrix` from `3` angles like:

``````rotation_matrix=rotation_around_x(ax)*rotation_around_y(ay)*rotation_around_z(az);
``````

see Wiki rotation matrices the 3D `Rx,Ry,Rz` from `Basic rotations` are what you need. As you can see they are just unit circle parametric equation really. The order of multiplication change how the angles converge to target position. This is called Euler angles and I do not use it (I integrate step changes instead which has no restrictions if done properly not to mention it is simpler).

Anyway if you need you can convert transform matrix into euler angles relatively easily see:

6. glRotate

If you want `glRotate` which is rotation around arbitrary axis not by 3 angles then There is workaround:

1. create transform matrix `N` for that axis
2. then transform your matrix `M` to it
3. rotate `N` by angle
4. then transform `M` back from `N` to global coordinates

Or you can use Rodrigues_rotation_formula instead

To transform Matrix to/from Matrix in this case just transform axises as points and leave the origin as is but the origin of `N` must be (0,0,0)!!! or the vectors transformed must have `w=0` instead.

7. usage

Transformations are cumulative that means:

• `p'=M1*M2*M3*M4*p;` is the same as `M=M1*M2*M3*M4; p'=M*p`

So if you have many points to transform then you precompute all transformations to single matrix and use just it. Do not need to multiply points by all subsequent matrices. OK now the concept:

you should have `3` coordinate systems:

• camera `C`
• world (usually unit matrix)
• object `O` (each object have its own matrix)

so if you have cube with `8` vertexes `p0,...,p7` then you have to perform transformation on each point from object local coordinates to camera local coordinates. Some gfx api do some of it so you apply only what you have to so you really need:

• `p(i)'=inverse(C)*unit*M*p(i);`

the transforms are cumulative and unit matrix does not change anything so:

• `Q=inverse(C)*M; p(i)'=Q*p(i);`

so before drawing compute `Q` for drawed object then take each point `p(i)` of the object and compute the transformed `p(i)'` and draw/use the transformed one … The `p(i)'` is in local camera coordinate system (x,y of the screen) but there is no perspective there so before drawing you can also add any of the projection matrices and divide by `z` cordinate at the end … The projection is also cumulative so it can be also inside `Q`

[edit1] C++ example

``````//\$\$---- Form CPP ----
//---------------------------------------------------------------------------
// apart from math.h include you can ignore this machine generated VCL related code
#include <vcl.h>
#pragma hdrstop
#include "win_main.h"
#include <math.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TMain *Main; // pointer to main window ...
//---------------------------------------------------------------------------
// Here is the important stuff some math first
//---------------------------------------------------------------------------
const double deg=M_PI/180.0;
double divide(double x,double y);
void  matrix_mul       (double *c,double *a,double *b); // c = a * b
void  matrix_mul_vector(double *c,double *a,double *b); // c[ 4] = a * b[ 4]
void  matrix_subdet    (double *c,double *a);           // c = all subdets of a
double matrix_subdet   (          double *a,int r,int s);//      = subdet(r,s) of a
double matrix_det      (          double *a);           //       = det of a
double matrix_det      (          double *a,double *b); //       = det of a and subdets b
void  matrix_inv       (double *c,double *a);           // c = a ^ -1
//---------------------------------------------------------------------------
double divide(double x,double y)
{
if (!y) return 0.0;
return x/y;
}
void  matrix_mul       (double *c,double *a,double *b)
{
double q;
q[ 0]=(a[ 0]*b[ 0])+(a[ 1]*b[ 4])+(a[ 2]*b[ 8])+(a[ 3]*b);
q[ 1]=(a[ 0]*b[ 1])+(a[ 1]*b[ 5])+(a[ 2]*b[ 9])+(a[ 3]*b);
q[ 2]=(a[ 0]*b[ 2])+(a[ 1]*b[ 6])+(a[ 2]*b)+(a[ 3]*b);
q[ 3]=(a[ 0]*b[ 3])+(a[ 1]*b[ 7])+(a[ 2]*b)+(a[ 3]*b);
q[ 4]=(a[ 4]*b[ 0])+(a[ 5]*b[ 4])+(a[ 6]*b[ 8])+(a[ 7]*b);
q[ 5]=(a[ 4]*b[ 1])+(a[ 5]*b[ 5])+(a[ 6]*b[ 9])+(a[ 7]*b);
q[ 6]=(a[ 4]*b[ 2])+(a[ 5]*b[ 6])+(a[ 6]*b)+(a[ 7]*b);
q[ 7]=(a[ 4]*b[ 3])+(a[ 5]*b[ 7])+(a[ 6]*b)+(a[ 7]*b);
q[ 8]=(a[ 8]*b[ 0])+(a[ 9]*b[ 4])+(a*b[ 8])+(a*b);
q[ 9]=(a[ 8]*b[ 1])+(a[ 9]*b[ 5])+(a*b[ 9])+(a*b);
q=(a[ 8]*b[ 2])+(a[ 9]*b[ 6])+(a*b)+(a*b);
q=(a[ 8]*b[ 3])+(a[ 9]*b[ 7])+(a*b)+(a*b);
q=(a*b[ 0])+(a*b[ 4])+(a*b[ 8])+(a*b);
q=(a*b[ 1])+(a*b[ 5])+(a*b[ 9])+(a*b);
q=(a*b[ 2])+(a*b[ 6])+(a*b)+(a*b);
q=(a*b[ 3])+(a*b[ 7])+(a*b)+(a*b);
for(int i=0;i<16;i++) c[i]=q[i];
}
void  matrix_mul_vector(double *c,double *a,double *b)
{
double q;
q=(a[ 0]*b)+(a[ 1]*b)+(a[ 2]*b)+(a[ 3]);
q=(a[ 4]*b)+(a[ 5]*b)+(a[ 6]*b)+(a[ 7]);
q=(a[ 8]*b)+(a[ 9]*b)+(a*b)+(a);
for(int i=0;i<3;i++) c[i]=q[i];
}
void  matrix_subdet    (double *c,double *a)
{
double   q;
int     i,j;
for (i=0;i<4;i++)
for (j=0;j<4;j++)
q[j+(i<<2)]=matrix_subdet(a,i,j);
for (i=0;i<16;i++) c[i]=q[i];
}
double matrix_subdet    (         double *a,int r,int s)
{
double   c,q;
int     i,j,k;
k=0;                            // q = sub matrix
for (j=0;j<4;j++)
if (j!=s)
for (i=0;i<4;i++)
if (i!=r)
{
q[k]=a[i+(j<<2)];
k++;
}
c=0;
c+=q*q*q;
c+=q*q*q;
c+=q*q*q;
c-=q*q*q;
c-=q*q*q;
c-=q*q*q;
if (int((r+s)&1)) c=-c;       // add signum
return c;
}
double matrix_det       (         double *a)
{
double c=0;
c+=a[ 0]*matrix_subdet(a,0,0);
c+=a[ 4]*matrix_subdet(a,0,1);
c+=a[ 8]*matrix_subdet(a,0,2);
c+=a*matrix_subdet(a,0,3);
return c;
}
double matrix_det       (         double *a,double *b)
{
double c=0;
c+=a[ 0]*b[ 0];
c+=a[ 4]*b[ 1];
c+=a[ 8]*b[ 2];
c+=a*b[ 3];
return c;
}
void  matrix_inv       (double *c,double *a)
{
double   d,D;
matrix_subdet(d,a);
D=matrix_det(a,d);
if (D) D=1.0/D;
for (int i=0;i<16;i++) c[i]=d[i]*D;
}
//---------------------------------------------------------------------------
// now the object representation
//---------------------------------------------------------------------------
const int pnts=8;
double pnt[pnts*3]=     // Vertexes for 100x100x100 cube centered at (0,0,0)
{
-100.0,-100.0,-100.0,
-100.0,+100.0,-100.0,
+100.0,+100.0,-100.0,
+100.0,-100.0,-100.0,
-100.0,-100.0,+100.0,
-100.0,+100.0,+100.0,
+100.0,+100.0,+100.0,
+100.0,-100.0,+100.0,
};
const int facs=6;
int fac[facs*4]=        // faces (index of point used) no winding rule
{
0,1,2,3,
4,5,6,7,
0,1,5,4,
1,2,6,5,
2,3,7,6,
3,0,4,7,
};
double rep=        // 4x4 transform matrix of object (unit from start) at (0,0,+100)
{
1.0,0.0,0.0,  0.0,
0.0,1.0,0.0,  0.0,
0.0,0.0,1.0,100.0,
0.0,0.0,0.0,1.0,
};
double eye=        // 4x4 transform matrix of camera at (0,0,-150)
{
1.0,0.0,0.0,   0.0,
0.0,1.0,0.0,   0.0,
0.0,0.0,1.0,-150.0,
0.0,0.0,0.0,1.0,
};
//---------------------------------------------------------------------------
// this is how to draw it
//---------------------------------------------------------------------------
void obj(double *pnt,int pnts,int *fac,int facs,double *rep,double *ieye)
{
// variables for drawing
int i;
double p0,p1,p2,p3,m,d;
// gfx api variables (change to your stuff) Main is the main form of this application
TCanvas *scr=Main->bmp->Canvas;
double xs2=Main->ClientWidth/2,ys2=Main->ClientHeight/2;
double v=xs2*tan(30.0*deg); // 60 degree viewing angle perspective projection

matrix_mul(m,ieye,rep);             // cumulate all needed transforms

for (i=0;i<facs*4;)                 // go through all faces
{
// convert all points of face
matrix_mul_vector(p0,m,&pnt[fac[i]*3]); i++;
matrix_mul_vector(p1,m,&pnt[fac[i]*3]); i++;
matrix_mul_vector(p2,m,&pnt[fac[i]*3]); i++;
matrix_mul_vector(p3,m,&pnt[fac[i]*3]); i++;
// here goes perspective divide by z coordinate if needed
d=divide(v,p0); p0*=d; p0*=d;
d=divide(v,p1); p1*=d; p1*=d;
d=divide(v,p2); p2*=d; p2*=d;
d=divide(v,p3); p3*=d; p3*=d;
// here is viewport transform (just translate (0,0) to middle of screen in this case
p0+=xs2; p0+=ys2;
p1+=xs2; p1+=ys2;
p2+=xs2; p2+=ys2;
p3+=xs2; p3+=ys2;
// I use VCL GDI TCanvas you use what you have ...
// and wireframe only to keep this simple (no Z buffer,winding culling,...)
scr->Pen->Color=clAqua;     // perimeter wireframe
scr->MoveTo(p0,p0);
scr->LineTo(p1,p1);
scr->LineTo(p2,p2);
scr->LineTo(p3,p3);
scr->LineTo(p0,p0);
//      scr->Pen->Color=clBlue;     // face cross to visualy check if I correctly generate the fac[]
//      scr->MoveTo(p0,p0);
//      scr->LineTo(p2,p2);
//      scr->MoveTo(p1,p1);
//      scr->LineTo(p3,p3);
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void TMain::draw()
{
if (!_redraw) return;
bmp->Canvas->Brush->Color=clBlack;
bmp->Canvas->FillRect(TRect(0,0,xs,ys));

// compute inverse of camera need to compute just once for all objects
double ieye;
matrix_inv(ieye,eye);
// draw all objects
obj(pnt,pnts,fac,facs,rep,ieye);

Main->Canvas->Draw(0,0,bmp);
_redraw=false;
}
//---------------------------------------------------------------------------
__fastcall TMain::TMain(TComponent* Owner) : TForm(Owner)
{
// window constructor you can ignore this ... (just create a backbuffer bitmap here)
bmp=new Graphics::TBitmap;
bmp->HandleType=bmDIB;
bmp->PixelFormat=pf32bit;
pyx=NULL;
}
//---------------------------------------------------------------------------
void __fastcall TMain::FormDestroy(TObject *Sender)
{
// window destructor release memory ... also ignoe this
if (pyx) delete pyx;
delete bmp;
}
//---------------------------------------------------------------------------
void __fastcall TMain::FormResize(TObject *Sender)
{
// on resize event ... just resize/redraw backbuffer also can ignore this
xs=ClientWidth;  xs2=xs>>1;
ys=ClientHeight; ys2=ys>>1;
bmp->Width=xs;
bmp->Height=ys;
if (pyx) delete pyx;
pyx=new int*[ys];
for (int y=0;y<ys;y++) pyx[y]=(int*) bmp->ScanLine[y];
_redraw=true;
}
//---------------------------------------------------------------------------
void __fastcall TMain::FormPaint(TObject *Sender)
{
// repaint event can ignore
_redraw=true;
}
//---------------------------------------------------------------------------
void __fastcall TMain::tim_redrawTimer(TObject *Sender)
{
// timer event to animate the cube ...
_redraw=true;

// rotate the object to see it in motion
double ang,c,s;

ang=5.0*deg; c=cos(ang); s=sin(ang);    // rotate baround z by 5 degrees per timer step
double rz= { c, s, 0, 0,
-s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };

ang=1.0*deg; c=cos(ang); s=sin(ang);    // rotate baround x by 1 degrees per timer step
double rx= { 1, 0, 0, 0,
0, c, s, 0,
0,-s, c, 0,
0, 0, 0, 1 };
matrix_mul(rep,rep,rz);
matrix_mul(rep,rep,rx);

draw();
}
//---------------------------------------------------------------------------
``````

here is how it looks like: And GIF animation with back face culling: [notes]

If you have more questions then comment me …

[Edit2] basic 3D vector operations often needed

If you do not know how to compute vector operations like cross/dot products or absolute value see:

``````// cross product: W = U x V
W.x=(U.y*V.z)-(U.z*V.y)
W.y=(U.z*V.x)-(U.x*V.z)
W.z=(U.x*V.y)-(U.y*V.x)
// dot product: a = (U.V)
a=U.x*V.x+U.y*V.y+U.z*V.z
// abs of vector a = |U|
a=sqrt((U.x*U.x)+(U.y*U.y)+(U.z*U.z))
``````

here my C++ vector math:

``````static double vector_tmp;
double divide(double x,double y) { if ((y>=-1e-30)&&(y<=+1e-30)) return 0.0; return x/y; }
double* vector_ld(double x,double y,double z)          { double *p=vector_tmp; p=x; p=y; p=z; return p;}
double* vector_ld(double *p,double x,double y,double z) {                      p=x; p=y; p=z; return p;}
void  vector_copy(double *c,double *a)         { for(int i=0;i<3;i++) c[i]=a[i];       }
void  vector_abs(double *c,double *a)          { for(int i=0;i<3;i++) c[i]=fabs(a[i]); }
void  vector_one(double *c,double *a)
{
double l=divide(1.0,sqrt((a*a)+(a*a)+(a*a)));
c=a*l;
c=a*l;
c=a*l;
}
void  vector_len(double *c,double *a,double l)
{
l=divide(l,sqrt((a*a)+(a*a)+(a*a)));
c=a*l;
c=a*l;
c=a*l;
}
void  vector_neg(double *c,double *a)          { for(int i=0;i<3;i++) c[i]=-a[i];      }
void  vector_add(double *c,double *a,double *b) { for(int i=0;i<3;i++) c[i]=a[i]+b[i]; }
void  vector_sub(double *c,double *a,double *b) { for(int i=0;i<3;i++) c[i]=a[i]-b[i]; }
void  vector_mul(double *c,double *a,double *b) // cross
{
double   q;
q=(a*b)-(a*b);
q=(a*b)-(a*b);
q=(a*b)-(a*b);
for(int i=0;i<3;i++) c[i]=q[i];
}
void  vector_mul(double *c,double *a,double  b) { for(int i=0;i<3;i++) c[i]=a[i]*b; }
void  vector_mul(double *c,double  a,double *b) { for(int i=0;i<3;i++) c[i]=a*b[i]; }
double vector_mul(         double *a,double *b) { double c=0; for(int i=0;i<3;i++) c+=a[i]*b[i]; return c; } // dot
double vector_len(double *a) { return sqrt((a*a)+(a*a)+(a*a)); }
double vector_len2(double *a) { return (a*a)+(a*a)+(a*a); }
``````

[Edit3] local rotations for camera and object control via keyboard

As this has been asked a lot lately here some example answers of mine with demos:

• @MichaelDibbets no that is not right 1. vertex is still vertex you just convert it to homegenous coordinates so (x,y,z) becomes (x,y,z,1) so you can multiply it and 4×4 matrix together

Jan 22, 2015 at 11:21

• @MichaelDibbets 2. matrix represents coordinate system of your object (cube) if it si untranslated unrotated then it is unit matrix (1,0,0,0, 0,1,0,0, 0,0,0,1, 0,0,0,1) after some movement,rotation it will become different. if you want to construct one then take the axises of you objects vectors of x axis,y axis ,z axis in global world coordinate system and fill the matrix with them, then take the origin point and fill it also there last add the (0,0,0,1) at the bottom. I use as origin the middle point of the object and axises are Z for forward movement, Y for up and X for right …

Jan 22, 2015 at 11:22

• @MichaelDibbets most meshes are already translated to (0,0,0) like your cube example so point1 is not necessary , point 2 is done in single step by using single transform matrix (this translate and rotate the object to desired position) point 3 is not translate back but transform to camera view coordinates instead which can be also done in step 2. I will try to make working example for you in C++ …

Jan 22, 2015 at 12:35

• @MichaelDibbets added C++ example and repaired few thing local/global rotation was reversed and the camera/world/object transform cumulation was in wrong order for current matrix layout

Jan 22, 2015 at 14:04

• @Dudeson (debuleted) btw if youre interested see Bulletpoints EVERYWHERE

Nov 24, 2015 at 9:30