Game Development Community

dev|Pro Game Development Curriculum

PhysX in TGE Version 0.3 (Work-In-Progress)

by Shannon "ScarWars" Scarvaci · 07/03/2006 (11:35 am) · 269 comments

Outline
1. License
2. Get SDK from Ageia
3. Implementation
4. Scripts
5. Know Issues
6. Need your supports!

License:
The license of PhysX is following:
Free:
  * Commercial & non-commercial use on PC
       Must keep registration information currect
       Must agree to the EULA at the time of download (pops up, but is copied below)
       Available for Windows & Linux (soon)
       No PhysX HW support requirement
  * PS3 platform (through Sony pre-purchase)
  * All platforms through some of our middleware partnerships, such as UE3, Gamebryo 2.2,
     and others
k per platform:
  * Xbox 360
  * Fee may be waived at our discretion for multi-platform developers providing PC HW support
  * Fee may be waived at our discretion for some Tools & Middleware providers

Get SDK from Ageiq
You can obtain the SDK from www.ageia.com website, my currently version for this physics is 2.7.0.

If you are using Visual Studio then you need to add "include" and "library" in the project configuration.
(If you using linux or mac, then i don't know where to setup because I dont have linux or mac with me)
Directory for include files:
C:\Program Files\AGEIA PhysX SDK\v2.6.4\SDKs\Physics\include
C:\Program Files\AGEIA PhysX SDK\v2.6.4\SDKs\Foundation\include
C:\Program Files\AGEIA PhysX SDK\v2.6.4\SDKs\PhysXLoader\include
C:\Program Files\AGEIA PhysX SDK\v2.6.4\SDKs\Cooking\include
Directory for library files:
C:\Program Files\AGEIA PhysX SDK\v2.6.4\SDKs\lib\win32
Note: These files' path's are relative to my hard drive, your files may be in different directory depending on how you installed the PhysX SDK.

Please install AGEIA PhysX Runtime in your PC (prefered lastest version)
Also put two dll file (PhysXLoader.dll and NxCooking.dll from AGEIA PhysX SDK\v2.7.0\SDKs\Bin\win32) in the example folder.


Implementation
Copy the 17 files from "PhysX" folder into engine/PhysX and modify some TGE's source code files.

Player
in game/player.h in bold
//----------------------------------------------------------------------------

[b]struct sNxActor;[/b]
class Player: public ShapeBase
{
  typedef ShapeBase Parent;
  [b]sNxActor *mActor;[/b]
protected:
  /// Bit masks for different types of events
  enum MaskBits {

game/player.cc at the top in bold
//-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
[b]#include "physX/PhysX.h"
#include "physX/PhysXWorld.h"[/b]
#include "game/player.h"

game/player.cc in Player::Player() function
mMountPending = 0;

   [b]mActor = NULL;[/b]
}

game/player.cc in Player::onAdd() function
gCamFXMgr.clear();
        }

	 [b]PhysXWorld *PxWorld = PhysXWorld::getWorld(isServerObject());
	 if (PxWorld) {
		 mActor = PxWorld->AddShapeBase(this);
	 }[/b]

   return true;

game/player.cc in Player::setPosition(...)
else {
      mat.set(EulerF(0, 0, rot.z));
      mat.setColumn(3,pos);
   }
   [b]if (mActor) {
      QuatF q(mat);
      Point3F pos;
      mat.getColumn(3,&pos);
      NxQuat quat;
      quat.setXYZW(q.x,q.y,q.z,q.w);
      mActor->actor->setGlobalOrientationQuat(quat);
      mActor->actor->setGlobalPosition(NxVec3(pos.x,pos.y,pos.z));
   }[/b]
   Parent::setTransform(mat);
   mRot = rot;
}

Terrain
in terrain/terrData.cc
at the top of the file
#include "terrain/terrRender.h"
#include "terrain/blender.h"

[b]#include "physX/PhysXWorld.h"[/b]

extern bool gDGLRender;

terrain/terrData.cc in TerrainBlock::onAdd function near the end
if(!unpackEmptySquares())
                 return(false);

	[b]PhysXWorld *PxWorld = PhysXWorld::getWorld(isServerObject());
	if (PxWorld) {
		PxWorld->SetupTerrainCollision(); // old style
	}[/b]

   return true;
}

Interior
in interior/interior.h
class Interior
{
   ...
   friend class EditInteriorResource;
   [b]friend class PhysXInterior;[/b]

in interior/interiorInstance.h
class InteriorInstance : public SceneObject
{
   ...
   friend class FloorPlan;
   [b]friend class PhysXInterior;
   friend class PhysXWorld;[/b]

in interior/interiorInstance.cc
#include "platform/profiler.h"
[b]#include "physX/PhysXWorld.h"[/b]

...

bool InteriorInstance::onAdd()
{
   ...
   
   addToScene();

   [b]PhysXWorld *PxWorld = PhysXWorld::getWorld(isServerObject());
   if (PxWorld) {
      PxWorld->SetupInterior(*this);
   }[/b]
   return true;
}

TSStatic
in ts/tsShapeInstance.h
class TSShapeInstance
{
   ...
   friend class TSPartInstance;
   [b]friend class PhysXTSStatic;
   friend class PhysXActor;[/b]

in game/tsStatic.h
class TSStatic : public SceneObject
{
   ...
   friend class TSStaticConvex; 
   [b]friend class PhysXTSStatic;[/b]

in game/tsStatic.cc
#include "sim/netConnection.h"
[b]#include "physX/PhysXWorld.h"[/b]

...

bool TSStatic::onAdd()
{
   ...
   
   addToScene();

   [b]PhysXWorld *PxWorld = PhysXWorld::getWorld(isServerObject());
   if (PxWorld) {
      PxWorld->SetupTSStatic(*this);
   }[/b]
   return true;
}

ShapeBase
in game\shapeBase.h
class ShapeBase : public GameBase
{
   typedef GameBase Parent;
   friend class ShapeBaseConvex;
   friend class ShapeBaseImageData;
   [b]friend class PhysXWorld;[/b]

Material in GameBase
in game\gameBase.h
[b]struct PhysXMaterialData;[/b]
struct GameBaseData : public SimDataBlock {
   ...
   void unpackData(BitStream* stream);
   [b]// PhysX
   PhysXMaterialData* mMaterialBlock;[/b]
};
...
class GameBase : public SceneObject
{
   ...
   enum GameBaseMasks {
      InitialUpdateMask =     Parent::NextFreeMask,
      DataBlockMask =         InitialUpdateMask << 1,
      ExtendedInfoMask =      DataBlockMask << 1,
      ControlMask =           ExtendedInfoMask << 1,
      [b]//NextFreeMask =        ControlMask << 1
      // PhysX
      MaterialDataBlockMask = ControlMask << 1,
      NextFreeMask =          MaterialDataBlockMask << 1[/b]
   };
   ...

   [b]// PhysX
   bool setMaterialDataBlock(PhysXMaterialData* dptr);
   bool onNewMaterialDataBlock(PhysXMaterialData* dptr);[/b]

};
...
in game\gameBase.cc
[b]#include "physX/PhysX.h"
#include "physX/PhysXActor.h"[/b]
#include "platform/platform.h"
...
GameBaseData::GameBaseData()
{
   ...
   [b]mMaterialBlock = 0;[/b]
}
...
[b]IMPLEMENT_CONSOLETYPE(PhysXMaterialData)
IMPLEMENT_GETDATATYPE(PhysXMaterialData)
IMPLEMENT_SETDATATYPE(PhysXMaterialData)[/b]

void GameBaseData::initPersistFields()
{
   Parent::initPersistFields();
   ...
   [b]addField("materialBlock", TypePhysXMaterialDataPtr, Offset(mMaterialBlock, GameBaseData));[/b]
}
...
bool GameBase::onNewDataBlock(GameBaseData* dptr)
{
   ...
   [b]onNewMaterialDataBlock(mDataBlock->mMaterialBlock);[/b]

   setMaskBits(DataBlockMask);
   return true;
}
...
bool GameBase::setDataBlock(GameBaseData* dptr)
{
   ...
}

[b]bool GameBase::setMaterialDataBlock(PhysXMaterialData* dptr)
{
   if (isGhost() || isProperlyAdded()) {
      if (mDataBlock->mMaterialBlock != dptr)
         return onNewMaterialDataBlock(dptr);
   }
   else
      mDataBlock->mMaterialBlock = dptr;
   return true;
}

bool GameBase::onNewMaterialDataBlock(PhysXMaterialData* dptr)
{
   mDataBlock->mMaterialBlock = dptr;

   if (!mDataBlock->mMaterialBlock)
      return false;

   setMaskBits(MaterialDataBlockMask);
   return true;
}[/b]
...
U32 GameBase::packUpdate(NetConnection *, U32 mask, BitStream *stream)
{
   ...
   [b]if (stream->writeFlag((mask & MaterialDataBlockMask) && mDataBlock->mMaterialBlock != NULL)) {
      stream->writeRangedU32(mDataBlock->mMaterialBlock->getId(),
                             DataBlockObjectIdFirst,
                             DataBlockObjectIdLast);
   }[/b]

   // cafTODO: ControlMask
   return 0;
}

void GameBase::unpackUpdate(NetConnection *con, BitStream *stream)
{
   ...
   [b]if (stream->readFlag()) {
      PhysXMaterialData* dptrMD = 0;
      SimObjectId id = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);

      if (!Sim::findObject(id,dptrMD) || !setMaterialDataBlock(dptrMD))
         con->setLastError("Invalid packet GameBase::unpackUpdate()");
   }[/b]
}

Scripts
Copy three script files (PhysX.cs, physXActorBox.cs and physXActorSphere.cs) in starter.fps/server/scripts and add three lines of code in starter.fps/server/scripts/games.cs

// PhysX
	 exec("./physX.cs");
	 exec("./physXActorBox.cs");
	 exec("./physXActorSphere.cs");
	 exec("./physXJoints.cs");

add one line of code in common/client/mission.cs
function clientCmdMissionStart(%seq)
{
   // The client recieves a mission start right before
   // being dropped into the game.
	[b]startPhysX();[/b]
}

and in every mission file need to add PhysXWorld as show in bold:
new SimGroup(MissionGroup) {

	 [b]new PhysXWorld() {
		errorReport = false; // set to true if you want error report from PhysX
	 };[/b]
	
	 new ScriptObject(MissionInfo) {
	 ...

If you want to testing around by droping the object in the free-look camera, then use default.bind.cs script
function addCrate(%val)
{
	if (%val)
		commandToServer('pxcrate');
}
function addBox(%val)
{
	if (%val)
		commandToServer('pxbox');
}
function addRock(%val)
{
	if (%val)
		commandToServer('pxsphere');
}

moveMap.bind( keyboard, "alt r", addCrate);
moveMap.bind( keyboard, "alt t", addBox);
moveMap.bind( keyboard, "alt y", addRock);

Know Issues
Terrain is the problem here because PhysX can accept 256x256 collision mesh in their engine which is mean squareSize equal to one! So the TGE's default squareSize is 8 and you see object will miss the collision in some area of the terrain. Possible solution is to create chunks, for example if you use squareSize of 8 then use 64 chunks of 256x256 collision mesh.

Loading the mesh of 256x256 collision will very slow but there possible solution is to write the mesh to file create by PhysX engine and read the file from PhysX will be lots faster, similar to lighting system which is used in TGE.

I've tried number of way to use Terrain collision in PhysX such as split in four section, NxHeightfield which make it very slow but I haven't tried this in PPU yet. So I have to stick with 256x256 collision mesh for a while.

Player/ShapeBase collision with PhysX's object is not complete.

Networking:
Loading objects from the begin in the remote client sometime not showing but if object appear during the gameplay will work ok. That something i need to be working on. (There may be some problem because of improved speed, but didn't test it yet)

Improved PhysX Speed
Big thank to decryptoid for helping us in PhysX, esp. for speed improvement.

Need your supports!
Now you can play with PhysX in your TGE game! If you find any improvement for this Physics in coding or script or anything please post here and I'll happy to update in here.
Also please use TDNfor any info to advise for our community

In the future:
- Run in PPU.
- Player collision.
- ShapeBase, (TSStatic and Interior - Completed) collision.
- Use advance physics such as joints, clothes and fluid. Done two type of joints

Enjoy your Physics!

Check out the video.
First Video
Second Video
Joints Video (4MB, prefer download before watch)

This is my first resource, please be kind to me :)

Due to file limit please download from here Updated 13th Apirl 2006

Here TGEA PhysX Resource here
#61
06/01/2006 (10:10 am)
They are talking over a different licence like they have with dark basic software and I dont think the intergration is hardly easy if you support all the features.
#62
06/01/2006 (5:31 pm)
The integration is should be fairly easy but creating this resource aren't easy. Should I continues to do this or stop and let the employees do it?
#63
06/01/2006 (5:35 pm)
Maybe you will be an employee after this ! ;p
#64
06/01/2006 (5:36 pm)
by all means carry on, its obviously not going to happen in the near future garage games have got alot on their plate at the moment. 2.4 is being released publically this month :-)

ps Does anyone have the PPU yet?
#65
06/01/2006 (6:14 pm)
What are you working on at the moment, are you going to intergrate it into shapebase
#66
06/04/2006 (12:31 pm)
@ John - I have the ppu - and read the above posts - Shannon has said
Quote:
In the future:
- Run in PPU.
- Player collision.
- ShapeBase, TSStatic and Interior collision.
- Use advance physics such as joints, clothes and fluid.
#67
06/24/2006 (5:04 am)
Hi i've got the following compiler error:

c:\copy\torque\TGE\engine\physx\PhysX.h(30): fatal error C1083: Include-Datei kann nicht ge
#68
06/24/2006 (5:06 am)
rest of message:
werden: 'NxPhysics.h': No such file or directory

Physx.h:
#include

i've set the correct path to the include directory in the project properties and the file is there:
../lib/physx/Physics/include

Can anybody help ?
#69
06/25/2006 (4:14 am)
I'm alone here :-(

I've implemented it into the TSE and now i don't get these error anymore.

Now i have only one Problem. The boxes are falling through the ground terrain..

I've created a new terrain with 256x256 chunks but i got the same problem.
#70
06/25/2006 (9:56 am)
Your terrain is Atlas I presume? You have to add that support in. The code you added for terrain collision was for terrain, not atlas.
#71
06/25/2006 (10:36 am)
Hi,
yes you're right. Already seen it. I trying to implement it into the atlas terrain. Don't know if it will work.

I've implemented this:
// Physx integration
		PhysXWorld *PxWorld = PhysXWorld::getWorld(isServerObject());	
		if (PxWorld) 
		{		
			PxWorld->SetupTerrainCollision(); 
		}
 		//********************
to the AtlasInstance::onAdd() method

Then i've changed the PhysXTerrain::SetupWholeTerrain() method to
if (gTerrain) return;

	PhysXWorld *PxWorld = PhysXWorld::getWorld(server);
	if (PxWorld) {

		AtlasInstance *terrain;
		if (server) {
			terrain = dynamic_cast<AtlasInstance*>(Sim::findObject("Terrain"));
		} else {
			SimGroup *serverConnection = dynamic_cast<SimGroup*>(Sim::findObject("ServerConnection"));
			if (serverConnection) {
				for(SimGroup::iterator itr = serverConnection->begin(); itr != serverConnection->end(); itr++)
				{
					terrain = dynamic_cast<AtlasInstance*>(*itr);
					if(terrain)
					{
						break;
					}
				}
			}
		}
		if(!terrain) {
				Con::printf("Physx:Terrain not found!");
				return;
		} else
		{
			Con::printf("Physx: Terrain collision updated in PhysX");
		}
	}
The biq question is how to get the therrain Information from the AtlasInstance ?

And why do i have to recalculate the mesh data ? may be i can use such things like from AtlasResourceInfo::render:
GFX->drawIndexedPrimitive(GFXTriangleList, 0, mVert->mNumVerts, 0, mPrim->mIndexCount / 3);
to use the "mVerts" and the "mPrim" direct for the
terrainDesc.points	= mVert;
		terrainDesc.triangles = mPrim;
if i find a way to access it.
May be you have some ideas ?
#72
06/26/2006 (1:47 pm)
I alway get these error:

physXActorBox.cs (34): Register object failed for object (null) of class PhysXActor.

i'm searching since yesterday to fix it. But i cannot find the reason. I've added some boxes into the mission file:
new PhysXActor() {
      position = "242.478 111.948 48.8378";
      rotation = "0.0174583 -0.0228017 -0.999588 1.0609";
      scale = "1 1 1";
      dataBlock = "pxCrate1";
      materialBlock = "pxMaterialBox";
   };
       new PhysXActor() {
      position = "242.478 111.948 46.8378";
      rotation = "0.0174583 -0.0228017 -0.999588 1.0609";
      scale = "1 1 1";
      dataBlock = "pxCrate1";
      materialBlock = "pxMaterialBox";
   };

Its working fine. But if i want to implement a box by keypress i get these error.
here is my (not really my :-) code
datablock PhysXMaterialData(pxMaterialBox) {
	pxRestitution = 0.0;
	pxStaticFriction = 0.5;
	pxDynamicFriction = 0.5;
};

datablock PhysXActorData(pxCrate1) {
  // Mission editor category
    category = "Physics";
	pxShape = "box";
	friction = 0.1;
	mass = 20.0;
    elasticity = 0.1;
    shapeFile = "~/data/shapes/boxes/crate/crate.dts";
};

function PhysXActorData::create(%data)
{
	%obj = new PhysXActor() {
		dataBlock = %data;
		materialBlock = pxMaterialBox;
	};
	return %obj;
}

function serverCmdpxCrate(%client) {
	createpxCrate(%client);
}

function createpxCrate(%client) {
	new PhysXActor() 
	{
		position = "242.478 111.948 54.8378";
		rotation = "0.0174583 -0.0228017 -0.999588 1.0609";
		scale = "1 1 1";
		dataBlock = "pxCrate1";
		materialBlock = "pxMaterialBox";
	};
 
}
#73
06/29/2006 (11:01 pm)
Hi !
I'm alone here ? :-D
i've implemented it into TSE but only with a plane as Ground. I found a solution for the second issue.

I understand it so:
The main lop of physics is running in asynchronus mode. So it could be happened that you want to add a box but the gScene is write locked because the PhysXWorld is calculatin the results of the simulation.

with the term: gScene->isWritable() you can ask if the scene is write locked.

I've changed the code so that every actor asked for this and wait with adding the actor until the Scene isn't write locked anymore. I've used the following code

if (!gScene)
{
return false;
}
while(gScene->isWritable()==false)
{}

I know these code is not really good because if the Scene is not writeable for a long time than the loop is infinite.
May be someone have a better idea ?
#74
07/02/2006 (1:15 am)
It seems that no one is interrested to implement PhysX :-(
#75
07/02/2006 (2:04 pm)
Hey, im planning to use physx in tse, just its a massive task implemnting it
#76
07/02/2006 (3:25 pm)
Yeah, I'm planning to use PhysX... once it's built into Torque. Or once a comprehensive guide is written. As it is, there's no indication of difficulty, except for some obscure discussions between people who know quite a bit more than me.

I got in touch with Shannon (see discussion above), but once he found out that I don't even have a compiler yet he stopped writing back. I dropped it, too. Really, a guide picking up on a step-by-step is what's necessary, even if it's just a rough outline referencing other resources here Garage Games or anywhere else. Some students here at BCC have a website, too ( http://riki.thegameaddicts.net/index.php?title=Main_Page) but everybody's too busy at school, working, or sleeping that they don't have time to update a website, too. After all, hardly anybody's paid to do it, and who knows where it is on the GG radar?

So whatever. All this hard work goes against the who Gamer ethos; most of the fun is sitting around and amusing yourself, a lot of game programming is not that. Then again, getting your own game to work leaves you a lot more fulfilled than beating-all-the-maps-on-the-hardest-setting.
#77
07/03/2006 (1:08 am)
Hi,
may be it's a way to implement NXOgre into TSE ?
NXOgre is a PhysX implementation into Ogre 3d

www.nxogre.org/Main_Page
#78
07/03/2006 (4:28 pm)
And what about those who don't have PPU? Or it requires PPU if you want to implement it for free in commercial game?
#79
07/04/2006 (1:01 am)
WOW... This is very cool... Well done Shannon.
#80
07/04/2006 (3:19 am)
The license of PhysX is following:

Free:
-Non-commercial use
-PS3 platform (through Sony pre-purchase)
-Through some of our middleware partnerships, such as UE3, Gamebryo 2.2, and others--often limited to non-commercial use
-PC platform (if the game makes significant use of PhysX HW)

$50k per platform:
-All other uses
-Fee may be waived at our disgression for multi-platform developers providing PC HW support
-Fee may be waived at our disgression for some Tools & Middleware providers



What is "significant use"?
This will be specified in the contract, and may depend on the title, but general rules of thumb:

Grandmother test: If you show the game running on PhysX HW side-by-side with the non-HW version, your grandmother would be able to easily point out the differences.

Gamer test: The gamer is going to want to run your game with PhysX HW. In other words, we're helping you make your game (inexpensively, but with a world-class SDK), so you are helping us sell HW (by having a great game supporting PhysX HW).