Game Development Community

dev|Pro Game Development Curriculum

Rigid Shape Class

by Thomas \"Man of Ice\" Lund · 04/07/2004 (9:57 am) · 256 comments

Download Code File

History
2005-09-08 Updated with performance fix from XoCluTch

What is this?
For my game I needed a boulder that rolls down a hill, and that one needs to evade. Initial attempts to use the existing classes (items, shapes and especially projectiles) fail because of too simple physics and/or lack of collision box support. I was faced with either implementing collision boxes in the projectile class, look into ODE or try to code my own rigid body class.

Thanks to Ben Garney I didnt have to do any of these (thanks ;-) ), as there already exists rigid physics in the engine. The rigid.cc/h files have everything needed, but they are only available as con/net objects using the vehicle classes.

So I simply took the base vehicle class and the hover vehicle class, merged them together and removed most of the unneeded code. The result is actually fantastic, and I cant believe this isnt standard part of Torque.

As the code basically is a hover vehicle there might be parts of the code that should be removed further. If you spot any of those, then post here and I'll update the codebase.

What does it look like?
No resource without a movie :-)
Here is the final result from a tech demo level in my upcomming action adventure game.

www.codejar.com/rigidshape4.wmv

I also did a few early tests and I've included the movies here. The lack of realism is totally due to way too much impulse applied with a large vertical factor + low mass for the chests.

www.codejar.com/rigidshape.wmv
www.codejar.com/rigidshape2.wmv
www.codejar.com/rigidshape3.wmv

All movies are approx 3 MB

How to add
First thing is to add the 2 attached files in the zip to your engine\game dir and to your project. Then open the shapebase.h and find this

class ShapeBaseConvex : public Convex
{
   typedef Convex Parent;
   friend class ShapeBase;
   friend class Vehicle;

and add

friend class RigidShape;

Also in the same file down the bottom find this

#define StaticShape_GenericShadowLevel 2.0f
#define StaticShape_NoShadowLevel 2.0f

and add

#define RigidShape_GenericShadowLevel 0.7f
#define RigidShape_NoShadowLevel 0.2f

Recompile your engine and thats it.

If you want to do this "for real", then one also needs to define a new objectType. I have reused the ShapeBaseObjectType - change that if you want or go through tons of code and add a RigidShapeObjectType.

How to use
From script you now got access to a RigidShapeData datablock and a RigidShape object type. Your DTS object is required to have a mass node, but nothing else. The code still includes dusttrail and splash emitters from the vehicle code, as well as impact + water sound. This example does not use any of those.

An example datablock for a rigid shape is included below

datablock RigidShapeData( BouncingBoulder )
{	

   category = "RigidShape";
	
   shapeFile = "~/data/shapes/boulder/boulder.dts";
   emap = true;

   // Rigid Body
   mass = 500;
   massCenter = "0 0 0";    // Center of mass for rigid body
   massBox = "0 0 0";         // Size of box used for moment of inertia,
                              // if zero it defaults to object bounding box
   drag = 0.2;                // Drag coefficient
   bodyFriction = 0.2;
   bodyRestitution = 0.1;
   minImpactSpeed = 5;        // Impacts over this invoke the script callback
   softImpactSpeed = 5;       // Play SoftImpact Sound
   hardImpactSpeed = 15;      // Play HardImpact Sound
   integration = 4;           // Physics integration: TickSec/Rate
   collisionTol = 0.1;        // Collision distance tolerance
   contactTol = 0.1;          // Contact velocity tolerance
   
   minRollSpeed = 10;
   
   maxDrag = 0.5;
   minDrag = 0.01;

   triggerDustHeight = 1;
   dustHeight = 10;

   dragForce = 0.05;
   vertFactor = 0.05;

   normalForce = 0.05;
   restorativeForce = 0.05;
   rollForce = 0.05;
   pitchForce = 0.05;
};

By including the category="" it now shows up in the world editor under the Shapes, and its fully working. Spawn the object on a hilltop and see it roll down :-)

For the mission editor to work you will need to add a create() function that hooks into the mission editor. You can either put this into a rigidShape.cs file (dont forget to load it from game.cs) or put it into any .cs file in the server\script

// Hook into the mission editor.

function RigidShapeData::create(%data)
{
   // The mission editor invokes this method when it wants to create
   // an object of the given datablock type.
   %obj = new RigidShape() {
      dataBlock = %data;
   };
   return %obj;
}

If you want to have a little fun pushing things around then add this to your player onCollision:

function Armor::onCollision(%this,%obj,%col)
{

...

if (%col.getDataBlock().getName() $= "BouncingBoulder") {
	 // Apply an impulse to the object we collided with
	 %eye = %obj.getEyeVector();
         %vec = vectorScale(%eye, 10);
	 
        // Add a vertical component to give the item a better arc
	%dot = vectorDot("0 0 1",%eye);
	if (%dot < 0)
		%dot = -%dot;
	%vec = vectorAdd(%vec,vectorScale("0 0 2",1 - %dot));

	// Set the object's position and initial velocity
	%trans = %col.getTransform();
   
   // Heres the position and rotation.
   %pos = getWords(%trans, 0, 2);
	%col.applyImpulse(%pos,%vec);	 
}

...

}

I've done a few tests with forces, masses and such - and as you saw from my movies with varying results.

The objects are fully network aware, and I bet this code can replace ODE for most purposes if you dont need total realism.

As I wrote earlier, the code can be stripped down further. There are various pieces of the physics that I do not understand fully and left in. I would be very happy if someone could run through those parts and see if any of it can be taken out.

Regarding performance, I've tried to add approx 20 shapes to a scene and then letting all collide with each other (its in one of the movies actually). I noticed no performance degradation at all with those simple shapes (they had a 6 sided box as collision mesh.

The boulders in the last movie have an approx 25 faced hedra inside it as a collision mesh. I think I had 15 of those in an scene without performance degradation.

These shapes do have 1 problem though, and that is the collision detection that sometimes fails - exactly as vehicles. If they gain too much speed they will dip into the terrain or go through it. I think a lot of people are looking into that problem at the moment here www.garagegames.com/mg/forums/result.thread.php?qt=17384

Enjoy ;-)
Page «Previous 1 2 3 4 5 6 7 Last »
#1
04/07/2004 (10:20 am)
This looks terrific, Thomas. I can't wait for the link to become active so I can give it a bash. Thanx!
#2
04/07/2004 (10:42 am)
Looks great, need to get that link working.
#3
04/07/2004 (11:43 am)
AAaaaaannnnnnndddddd code has been uploadet once again - take your shot at it guys (and girls?)!
#4
04/07/2004 (12:07 pm)
Looking awesome! :)
Some functions you are going to need though I think (at least the first one):
function RigidShapeData::create(%block)
{
   %obj = new RigidShape() {
      dataBlock = %block;
   };
   return(%obj);
}

//-----------------------------------------------------------------------------

function RigidShapeData::onAdd(%this,%obj)
{
}
Now I just have to model a boulder to test it! ;)
#5
04/07/2004 (12:11 pm)
This looks awesome. Your project looks cool too Thomas.
#6
04/07/2004 (12:17 pm)
Ahh yes - thank you Stefan. I forgot about the create() for the mission editor *slaps himself*

Updated the information above with the needed info.
#7
04/07/2004 (12:20 pm)
Oh - and here is a link to my little test boulder. Its purely coders art, so no harm in giving it away. It will be replaced soon by a more irregular gfx artist modelled version, hehehe.

Dump it into your data\shapes dir somewhere

www.codejar.com/boulder.zip
#8
04/07/2004 (12:46 pm)
Very cool, Thomas. Glad to see you got it up here. :)
#9
04/07/2004 (1:03 pm)
hm, any idea why my player wouldn't trigger Armor::onCollision() at all and I can run right through the boulder?
#10
04/07/2004 (1:28 pm)
I was wondering the same thing.... no collision mesh perhaps?

Otherwise, seems pretty good so far.
Edit:
How about an underwater setting?
Halve the force/velocity or something?
#11
04/07/2004 (1:35 pm)
hm, no, I did a quick sphere model with a "collision" mesh in it... didnt change anything... weird... and its a ShapeBaseObjectType, so it *should* collide I think...
#12
04/07/2004 (2:30 pm)
Hmmm... Thats a wierd one, I'l look into it myself, but I probably wont be able to do much.
Edit:
Looks like they only collide at high speed..... ???
#13
04/07/2004 (3:10 pm)
Guess what, its not ShapeBaseObjectType. In fact it doesnt seem to be a child of anything. its just defined as
class Rigid

And that would explain why you dont get player->rigidShape collision.

* I seem to get that collision but only when the rigid shape is moving. i.e falling on top of me.

now shouldnt it read
class Rigid: public ShapeBase
#14
04/07/2004 (3:14 pm)
Ignore me, i was reading rigid source and not rigidShape hehe.
#15
04/07/2004 (3:31 pm)
Still only collides when the object isnt at rest...

You sure everything is included in the resource Thomas?

It must work, otherwise you wouldnt be able to do as whats seen in the vids.
#16
04/07/2004 (9:40 pm)
This variable is what is making it not collide while at rest.

contactTol = 0.1; // Contact velocity tolerance

However, when I set this to 0.0, my game froze when I spawned the object.

Edit: To fix the collision while at rest, in rigidShape.cc, around line 1173 add.

if (vn < -mDataBlock->contactTol) {

               // Apply impulses to the rigid body to keep it from
               .......
               .......
            }
            else// <<=====  add this else statement
            {
               if (!isGhost() && c.object->getTypeMask() & ShapeBaseObjectType) {
                  ShapeBase* col = static_cast<ShapeBase*>(c.object);
                  queueCollision(col,v - col->getVelocity());
               }
            }

Edit 2: That fix doesn't seem to work very good. I think we all should work on this to make the best rigid object possible.
#17
04/07/2004 (11:43 pm)
Look in
void RigidShape::updatePos(F32 dt)

....

if (!mRigid.atRest) {
collided = updateCollision(dt);

If we are atRest, not collision checking. :)
#18
04/07/2004 (11:48 pm)
edited
#19
04/08/2004 (8:38 am)
No, because i removed that check, and it still doesnt collide while not moving.
#20
04/08/2004 (8:50 am)
Hmmmz... Cool game in the vids :D
Page «Previous 1 2 3 4 5 6 7 Last »