Just Code it!
Header

The base of all the Maths that I will use is the Vector for sure (well, the number itself… but I have no intention to start from there :P).
I assume that you are somehow familiar with the concept of vector and its basic operations (sum, vector/dot product, etc).

The vector that I need for this project is a 3D vector. Sometime it is more convenient to represent 3D vectors using 4 components (with the last one “w” set to 1) to simplify some transformation. I will start using a 3-components vector for now.

We could use directly the Vector3 class (or Vector4) in XNA for this, but I will write my own just to have more control over it and to play directly with the operations/methods that I will expose. It is just a chance to see what’s behind and we can decide to remove it in the future if we don’t need it anymore.
The nice thing about writing your own basic classes is that they will be very portable and what you will have to provide will be just the wiring with the current library (OpenGL/DirectX/XNA) Vector/Matrix classes. The rest of your code will (almost) work without any change (well… you will have to change the rendering as well).

Declaration
The basic starting point for the Vector3 class is just a set of 3 properties that stores the coordinates we are interested in.
Without wasting too much time, I will just declare the three properties as public fields in my Vector3 class.
Those are the basic declaration in C++, C# and Java:
class Vector3 {
public:
float x;
float y;
float z;
}

public class Vector3
{
public float x;
public float y;
public float z;
}

public class Vector3
{
public float x;
public float y;
public float z;
}

Easy :).

Dot Product
Aside from the 3 fields (and properties) used to represent the 3 coordinates (x, y, z), there are some more useful methods to implement.
A set of basic operations (amongst the obvious one such as assignment or equality operator) are:

  • Dot/Vector product
  • Scale
  • Magnitude (Normal/Squared)
  • Normalisation

The implementation of the dot product is straightforward.
In C#, assuming to implement it as an overloading of the multiplication operator (“operator *”), the code will be something like this:

public static float operator *(Vector3 _vectorA, Vector3 _vectorB)
{
return _vectorA.x * _vectorB.x +
_vectorA.y * _vectorB.y +
_vectorA.z * _vectorB.z;
}

Just as an example, in C++ this could be implemented in a slightly different way when declaring it as a member function:

float operator *(const Vector3 &_vector) const
{
return x*_vector.x + y*_vector.y + z*_vector.z;
}

And in Java it is more fun… I am sarcastic here. I have to implement it in another completely different way (no operator overloading):

public float GetDotProduct(Vector3 _vector)
{
return x*_vector.x + y*_vector.y + z*_vector.z;
}

It is quite interesting to notice how the overloading differs in C# and C++ and especially (missing :P) in Java.
If for some reason you like the Java version, then you can easily apply this in the other two languages as well… if you want to achieve the opposite instead (overloading in Java) then… good luck :).

I have to admit that the Dot Product is not really exciting. So let’s look at the Cross Product for a more (even if not much more) interesting example.

Cross Product
The Cross Product, differently from the previous one, is an operation between two vectors that returns another Vector. You can find the formal definition and all several properties explanation from the long series of resources on the book-shelves and websites (wiki).
A common way to write it is: v = a x b, where the “x” represent the cross product operation.
What is important to know at the moment is that when implementing the cross product you need to pay immediately attention at least to a couple of really important details:

  • You need to take into account the handedness of the coordinate system.
  • It is not a commutative operation.

(Coordinate Systems)
To see the difference due to the handedness of the coordinate system you can simply use the left-hand rule or right-hand rule that matches the handedness of your coordinate system to easily visualize how the resulting vectors differ.
The left/right-hand rules are quite easy to apply. Just use your left/right hand (or one of your friends :P), shape it like a fist and stick out the first three fingers (thumb pointing up, index pointing forward and yes, the third and preferred one, perpendicular to the other two). Now, keeping the three fingers (initially) at 90 degrees each one with the other, just rotate your left/right hand so that your thumb matches the direction of you first vector (“a”). Then rotate your hand around that axis (represented by the thumb) so that your index finger ends up on the same plane identified by the second vector (“b”) and the thumb (still fixed on “a”). If you see that you should spread the thumb and the index more than 180 degrees in order to match your index with the vector “b”, than simply flip your hand around the thumb (rotate it of 180 degrees around it) and you will see that (assuming that you can stretch your fingers as much as 180 degrees) the second vector can always be matched by your index finger now.
After all this stretching exercise you will find that the third loved middle-finger will point along the direction of the vector that results from the cross product.
Now you can relax you muscles, the left/right-hand rule will not tell you more than this… you cannot shrink or elongate your fingers to find out the length of such a vector :P… I hope.

Back to the Cross Product
The fact that it is not a commutative operation should now be clear. Just try to apply the same hand rule assuming that “a” and “b” are switched. Not only you will find that the direction is not the same, but you will find out that is exactly the opposite of the previous one! It is in fact true that the cross product is an anti-commutative operation!

Enough said about this… well, one thing is missing. The length of the resultant vector.
For this you can just stick to the definition I will give, or, if you are interested or curious, refer to a math book (or Wikipedia if you prefer). I will not explain where this came from because it is not relevant in this context and it would include some concepts related to matrices that I didn’t explain yet.
The direct and fast result is this:
The result of “v = a x b” is a vector with the components defined as:

  • x = ay * bz – az * by
  • y = az * bx – ax * bz
  • z = ax * by – ay * bx

Because the result is a vector we can use more fantasy when writing our code :). Those are some example of useful methods to apply this operation in the different languages.
Notice that if the two vectors are parallel the result will be 0!

Looking at the C++ example first we could decide to overload the “operator %” (if you like it) and even the “operator %=”, the compound assignment operators (well you will not like this if you didn’t like the previous of course). Here it is how it could look:

Vector3 operator %(const Vector3 &_vector) const
{
return Vector3(y * _vector.z - z * _vector.y,
z * _vector.x - x * _vector.z,
x * _vector.y - y * _vector.x);
}

void operator %=(const Vector3 &_vector)
{
*this = VectorProduct(_vector);
}

of course this is a quite lazy version of the “opertor %=”… a more optimised one should be:

void operator %=(const Vector3 &_vector)
{
float tx = y * _vector.z - z * _vector.y;
float ty = z * _vector.x - x * _vector.z;
float tz = x * _vector.y - y * _vector.x;
x = tx; y = ty; z = tz;
}

If you want, there is still an improvement to make here. If you try to write the following line:

vectorA = vectorB %= vectorC;

You will notice that the compiler is not really happy… This is because our compound “operator %=” doesn’t return anything. If you want to be able to do such a thing, then you should consider modifying the code for this operator in something like this:

Vector3& operator %=(const Vector3 &_vector)
{
float tx = y * _vector.z - z * _vector.y;
float ty = z * _vector.x - x * _vector.z;
float tz = x * _vector.y - y * _vector.x;
x = tx; y = ty; z = tz;
return *this;
}

As a last note worth considering is to define all those as inline functions in C++.

The C# version is:

public static Vector3 operator %(Vector3 _vectorA, Vector3 _vectorB)
{
return new Vector3(_vectorA.y * _vectorB.z - _vectorA.z * _vectorB.y,
_vectorA.z * _vectorB.x - _vectorA.x * _vectorB.z,
_vectorA.x * _vectorB.y - _vectorA.y * _vectorB.x);
}

And in Java:

public Vector3 GetVectorProduct(Vector3 _vector)
{
return new Vector3(y * _vector.z - z * _vector.y,
z * _vector.x - x * _vector.z,
x * _vector.y - y * _vector.x);
}

Other Operations
Enough for Vector3. All the other operation are quite straightforward to implement as well, so it is just a question of describing their functionality:

  • Add/Sum: basic operations to add and subtract to vectors.
  • Copy/Clone: return a copy of the vector object (if we are using mutable objects).
  • Compare: check if two vectors represent the “same” vector in space
  • Scale: multiplies a vector by a number.
  • Magnitude (Normal/Squared): returns the length of the vector. The squared length is useful in some cases and it is nice to have if we can avoid to waste computational time computing a square root that we don’t really need.
  • Normalisation: scales the vector in order to obtain a unit length vector.
  • More as we need them :).

Next thing will be more challenging for sure: The Matrix!

Physics Engine – Introduction

March 12th, 2011 | Posted by riccardotramma in .NET | C++ | CSharp | Java | Physics - (1 Comments)

I decided to document here my personal project: “Building a small Physics Engine” perfectly usable to build small/medium games.

My intention is to bring this series of posts as far as possible. During this journey anyway, although good code and clean architecture is always important and always a basic principle for the code I am going to write, I cannot assure that I will always bring this to the extreme for this project and I will probably take some short-cuts and some lazy choice for several reasons:

  • This is a personal project
  • I want just to have fun with it
  • I don’t want to digress too much from the main argument
  • The aim is to quickly (and happily) build a Physics Engine after all
  • I don’t want to waste too much time refining something that I don’t really need (for now)

I will not explain everything in detail (there are books and books on the matter and it is not my intention to write a new one) and what I will state will not be necessarily complete and mathematically impeccable (some assumptions will be always along the way to simplify matters), but (hopefully) it will work! :)
I will assume a basic knowledge of some concepts, especially basic Maths/Physics concepts and operations. If something should not be clear just google it or ask it if you cannot find the answer you are looking for, I’ll try to answer asap.

We have to consider that there are several (sometime drastically different!) ways to obtain the same result or to simulate/model a concept. Some are better than others, sometime it is only or a question of personal preferences or can be that the results are only better in the specific context where we are using our (mathematical) model.
That said I will mostly use my personal preferences for techniques and methods, while I will use some less-efficient/precise ways when I reckon that I can save some developing time/resources and the result is still pretty acceptable. This is still a demo/personal-fun project and more fine-grained/polished/robust/efficient code can be added later on if anyone is interested. I will probably mention anyway some different techniques that I will maybe discuss more in detail even giving some examples if I will consider them worthwhile at the moment of mentioning them.

What about the source code?
Well, I will present code mainly in C# (I assume), but I do not exclude that I will show some concepts using C++ or even Java… just for fun and to have more examples :)… the important thing are the concepts after all… and the code, yes, the code!
I will give examples using DirectX, XNA or OpenGL and I will use (on my machine) Visual Studio (2005/2008/2010) or Eclipse… and yes, even the operating system will not be unique! I will use Windows or Mac (well… even Linux maybe… no ok, not for now, but it should not be difficult to implement with the existing material)!
This should give a broad view on how achieve things in different systems, using different libraries with different languages… what else? :)

So, let’s start from the basic, Math! Yes, Math is always the base :)… well, Geometry in this case.