/* ============= CMod_PhysicsInit ============= */ void CMod_PhysicsInit() { Com_Printf("----- Initializing Newton Physics Engine -----\n"); Com_Printf("Initialized with Newton Version %i.%i \n", NEWTON_MAJOR_VERSION, NEWTON_MINOR_VERSION); Com_Printf("----------------------------------------------\n"); // create the Newton World bspModels.clear(); g_world = NewtonCreate (AllocMemory, FreeMemory); // use the standard x86 floating point model // Dushan - the engine will try to use the best possible hardware setting found in the current platform this is the default configuration NewtonSetPlatformArchitecture (g_world, 2); // Set up default material properties for newton defaultMaterialGroup = NewtonMaterialGetDefaultGroupID(g_world); NewtonMaterialSetDefaultFriction (g_world, defaultMaterialGroup, defaultMaterialGroup, 0.9f, 0.5f); NewtonMaterialSetDefaultElasticity (g_world, defaultMaterialGroup, defaultMaterialGroup, 0.4f); NewtonMaterialSetDefaultSoftness (g_world, defaultMaterialGroup, defaultMaterialGroup, 0.1f); NewtonMaterialSetCollisionCallback (g_world, defaultMaterialGroup, defaultMaterialGroup, NULL, NULL, NULL); NewtonMaterialSetDefaultCollidable (g_world, defaultMaterialGroup, defaultMaterialGroup, 1 ); // configure the Newton world to use iterative solve mode 0 // this is the most efficient but the less accurate mode NewtonSetSolverModel (g_world, 8); NewtonSetFrictionModel (g_world, 0); g_collision = NULL; }
world::world(): _world(NULL), _accum(0), _freq(1.0 / 60.0) { // default to global gravity gravity.enabled = true; _world = NewtonCreate(); const float WORLD_SIZE = 1000; const vec3 A(-WORLD_SIZE, -WORLD_SIZE, -WORLD_SIZE), B(-A); NewtonSetWorldSize(_world, &A.x, &B.x); platform(PLAT_OPTMIZED); solver(3); friction(FRIC_ADAPTIVE); threads(2); clearCache(); int mid = NewtonMaterialGetDefaultGroupID(_world); // allow bodies to be swept-tested NewtonMaterialSetContinuousCollisionMode(_world, mid, mid, 1); NewtonMaterialSetCollisionCallback(_world, mid, mid, NULL, &beginContactCB, &processContactCB); }
dNewton::dNewton() :m_maxUpdatePerIterations(2) { // create a newton world m_world = NewtonCreate(); // for two way communication between low and high lever, link the world with this class for NewtonWorldSetUserData(m_world, this); // set the simplified solver mode (faster but less accurate) NewtonSetSolverModel (m_world, 1); // by default runs on four micro threads NewtonSetThreadsCount(m_world, 4); // set the collision copy constructor callback NewtonWorldSetCollisionConstructorDestructorCallback (m_world, OnCollisionCopyConstruct, OnCollisionDestructorCallback); // use default material to implement traditional "Game style" one side material system int defaultMaterial = NewtonMaterialGetDefaultGroupID (m_world); NewtonMaterialSetCallbackUserData (m_world, defaultMaterial, defaultMaterial, m_world); NewtonMaterialSetCompoundCollisionCallback(m_world, defaultMaterial, defaultMaterial, OnCompoundSubCollisionAABBOverlap); NewtonMaterialSetCollisionCallback (m_world, defaultMaterial, defaultMaterial, OnBodiesAABBOverlap, OnContactProcess); // add a hierarchical transform manage to update local transforms new dNewtonTransformManager (this); // set the timer ResetTimer(); }
NzPhysWorld::NzPhysWorld() : m_gravity(NzVector3f::Zero()), m_stepSize(0.005f), m_timestepAccumulator(0.f) { m_world = NewtonCreate(); NewtonWorldSetUserData(m_world, this); }
PhysWorld3D::PhysWorld3D() : m_gravity(Vector3f::Zero()), m_maxStepCount(50), m_stepSize(0.005f), m_timestepAccumulator(0.f) { m_world = NewtonCreate(); NewtonWorldSetUserData(m_world, this); m_materialIds.emplace("default", NewtonMaterialGetDefaultGroupID(m_world)); }
Import::Import(const char* pathName, Interface* ip, ImpInterface* impip) { // set the path for textures char* ptr = NULL; sprintf (m_path, "%s", pathName); for (int i = 0; m_path[i]; i ++) { if ((m_path[i] == '\\') || (m_path[i] == '/') ) { ptr = &m_path[i]; } } *ptr = 0; m_ip = ip; m_impip = impip; m_succes = TRUE; MaterialCache materialCache (NewDefaultMultiMtl()); SetSceneParameters(); dFloat scale; scale = float (GetMasterScale(UNITS_METERS)); dMatrix scaleMatrix (GetIdentityMatrix()); scaleMatrix[0][0] = 1.0f / scale; scaleMatrix[1][1] = 1.0f / scale; scaleMatrix[2][2] = 1.0f / scale; dMatrix globalRotation (scaleMatrix * dPitchMatrix(3.14159265f * 0.5f) * dRollMatrix(3.14159265f * 0.5f)); NewtonWorld* newton = NewtonCreate(); dScene scene (newton); scene.Deserialize (pathName); // dScene::Iterator iter (scene); // for (iter.Begin(); iter; iter ++) { // dScene::dTreeNode* node = iter.GetNode(); // dNodeInfo* info = scene.GetInfoFromNode(node); // if (info->GetTypeId() == dMeshNodeInfo::GetRttiType()) { // dMeshNodeInfo* mesh = (dMeshNodeInfo*) scene.GetInfoFromNode(node); // mesh->ConvertToTriangles(); // } // } scene.BakeTransform (globalRotation); GeometryCache geometryCache; MaxNodeChache maxNodeCache; LoadMaterials (scene, materialCache); LoadGeometries (scene, geometryCache, materialCache); LoadNodes (scene, geometryCache, materialCache.m_multiMat, maxNodeCache); ApplyModifiers (scene, maxNodeCache); scene.CleanUp(); NewtonDestroy(newton); }
CollisionDetection::CollisionDetection( bool gernerateMeshes ): gernerateMeshes(gernerateMeshes), objCollision(NULL) { newtonWorld = NewtonCreate(); for(int i=0; i < 16; i++) idmatrix[i] = 0.0f; idmatrix[0] = 1.0f; idmatrix[5] = 1.0f; idmatrix[10] = 1.0f; idmatrix[15] = 1.0f; enemyEnt = NULL; shapeID = 5; }
Zone::Zone(Game *game) { m_game = game; m_player = NULL; m_mainArchive = 0; m_mainWld = 0; m_terrain = NULL; m_objects = NULL; m_actorTree = NULL; m_collisionChecksStat = NULL; m_collisionChecks = 0; m_collisionWorld = NewtonCreate(); m_movementAheadTime = 0.0f; }
int main (int argc, char* argv[]) { _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF|_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF)); // initialize graphics system if (!InitGraphicsSystem (800, 600)) { exit (0); } // set a callback for destroying the world ate termination atexit (ShutDown); // Create a Simple Scene Manager g_sceneManager = new SceneManager(); // set the memory allocators NewtonSetMemorySystem (AllocMemory, FreeMemory); // create the Newton World g_world = NewtonCreate (); // use the standard x87 floating point model NewtonSetPlatformArchitecture (g_world, 0); // set a fix world size // dVector minSize (-500.0f, -500.0f, -500.0f); // dVector maxSize ( 500.0f, 500.0f, 500.0f); // NewtonSetWorldSize (g_world, &minSize[0], &maxSize[0]); // initialize Newton Visual Debugger #ifdef USE_VISUAL_DEBUGGER g_newtonDebugger = NewtonDebuggerCreateServer (); #endif // configure the Newton world to use iterative solve mode 0 // this is the most efficient but the less accurate mode NewtonSetSolverModel (g_world, 1); // now populate the world with Graphic and physical entities CreateScene(g_world, g_sceneManager); // run the main application loop until the user terminate the app for (;;) { // Draw the screen. AdvanceSimulation (GetTimeInMicrosenconds ()); } // Never reached. return 0; }
bool Physics::initialize() { // init physics engine _p_world = NewtonCreate( physicsAlloc, physicsFree ); assert( _p_world ); // set minimum frame rate NewtonSetMinimumFrameRate( _p_world, 1.0f / FIX_PHYSICS_UPDATE_PERIOD ); NewtonSetSolverModel( _p_world, 0 ); // 0: exact, 1 adaptive, n linear. for games linear is ok NewtonSetFrictionModel( _p_world, 0 ); // 0: exact, 1 adaptive // setup all predefined materials setupMaterials(); return true; }
// Constructor World::World(Ogre::Real desiredFps, int maxUpdatesPerFrames, Ogre::String name) : m_bodyInAABBIterator(this) { #ifndef WIN32 pthread_mutex_init(&m_ogreMutex, 0); #endif setUpdateFPS(desiredFps, maxUpdatesPerFrames); m_limits = Ogre::AxisAlignedBox(Ogre::Vector3(-100,-100,-100), Ogre::Vector3(100,100,100)); m_world = NewtonCreate(); if (!m_world) { // world not created! } NewtonWorldSetUserData( m_world, this ); // create the default ID. m_defaultMatID = new OgreNewt::MaterialID( this, NewtonMaterialGetDefaultGroupID( m_world ) ); m_leaveCallback = NULL; m_defaultAngularDamping = Ogre::Vector3(0.1f, 0.1f, 0.1f); m_defaultLinearDamping = 0.1f; m_debugger = new Debugger(this); // set the default solve mode to be iterative the fastest setSolverModel (SM_FASTEST); // use the more advanced hardware in the system Ogre::String description; setPlatformArchitecture (3); getPlatformArchitecture (description); // set one tread by default setThreadCount(1); // store the world by name in a static map worlds[name] = this; }
Error PhysicsWorld::create(AllocAlignedCallback allocCb, void* allocCbData) { Error err = ErrorCode::NONE; m_alloc = HeapAllocator<U8>(allocCb, allocCbData); // Set allocators gAlloc = &m_alloc; NewtonSetMemorySystem(newtonAlloc, newtonFree); // Initialize world m_world = NewtonCreate(); if(!m_world) { ANKI_LOGE("NewtonCreate() failed"); return ErrorCode::FUNCTION_FAILED; } // Set the simplified solver mode (faster but less accurate) NewtonSetSolverModel(m_world, 1); // Create scene collision m_sceneCollision = NewtonCreateSceneCollision(m_world, 0); Mat4 trf = Mat4::getIdentity(); m_sceneBody = NewtonCreateDynamicBody(m_world, m_sceneCollision, &trf[0]); NewtonBodySetMaterialGroupID(m_sceneBody, NewtonMaterialGetDefaultGroupID(m_world)); NewtonDestroyCollision(m_sceneCollision); // destroy old scene m_sceneCollision = NewtonBodyGetCollision(m_sceneBody); // Set the post update listener NewtonWorldAddPostListener(m_world, "world", this, postUpdateCallback, destroyCallback); // Set callbacks NewtonMaterialSetCollisionCallback(m_world, NewtonMaterialGetDefaultGroupID(m_world), NewtonMaterialGetDefaultGroupID(m_world), nullptr, onAabbOverlapCallback, onContactCallback); return err; }
PhysicMap::PhysicMap() { float min[] = {-2000, -2000, -2000}; float max[] = {2000, 2000, 2000}; m_world = NewtonCreate(0, 0); NewtonSetWorldSize(m_world, min, max); NewtonSetSolverModel(m_world, 0); NewtonSetFrictionModel(m_world, 0); m_mapID = NewtonMaterialCreateGroupID(m_world); m_playerID = NewtonMaterialCreateGroupID(m_world); NewtonMaterialSetDefaultSoftness(m_world, m_mapID, m_playerID, 0.0f); NewtonMaterialSetDefaultElasticity(m_world, m_mapID, m_playerID, 0.2f); NewtonMaterialSetDefaultFriction(m_world, m_mapID, m_playerID, 0.5f, 0.0f); NewtonMaterialSetDefaultSoftness(m_world, m_playerID, m_playerID, 0.0f); NewtonMaterialSetDefaultElasticity(m_world, m_playerID, m_playerID, 0.2f); NewtonMaterialSetDefaultFriction(m_world, m_playerID, m_playerID, 0.5f, 0.0f); }
iPhysicsWorld* iPhysics::createWorld() { iPhysicsWorld* result = nullptr; #ifdef __IGOR_DEBUG__ _worldListMutex.lock(); // this is a workaround to prevent an assertion within the creation of a newton world #endif NewtonWorld* world = NewtonCreate(); NewtonSetSolverModel(static_cast<const NewtonWorld*>(world), 1); NewtonSetThreadsCount(static_cast<const NewtonWorld*>(world), 4); result = new iPhysicsWorld(world); #ifndef __IGOR_DEBUG__ _worldListMutex.lock(); // this is a workaround to prevent an assertion within the creation of a newton world #endif _worlds[result->getID()] = result; _worldListMutex.unlock(); return result; }
void ConvexApproximationObject::BuildMesh() { // since max does no provide the iNode that will own this mesh I have no choice bu to apply the root matrix to all vertex ConvexApproximationClassDesc* const desc = (ConvexApproximationClassDesc*) ConvexApproximationClassDesc::GetDescriptor(); INode* const sourceNode = desc->m_sourceNode; //dMatrix rootMatrix1 (GetMatrixFromMaxMatrix (sourceNode->GetNodeTM (0))); dMatrix rootMatrix (GetMatrixFromMaxMatrix (sourceNode->GetObjectTM(0))); dVector scale; dMatrix stretchAxis; dMatrix orthogonalRootTransform; rootMatrix.PolarDecomposition (orthogonalRootTransform, scale, stretchAxis); orthogonalRootTransform = orthogonalRootTransform.Inverse(); // create a Newton world, as a manager of everything Newton related stuff NewtonWorld* const world = NewtonCreate (); // create an empty mesh and load the max mesh to it NewtonMesh* const sourceMesh = NewtonMeshCreate (world); // load all faces NewtonMeshBeginFace(sourceMesh); LoadGeometries (sourceMesh, orthogonalRootTransform); NewtonMeshEndFace(sourceMesh); // make a convex approximation form this newton mesh effect desc->m_progress = -1; Interface* const inteface = desc->m_currentInterface; inteface->ProgressStart("Creation Convex approx ...", TRUE, ConvexApproximationClassDesc::ReportMaxProgress, NULL); NewtonMesh* approximationMesh = NewtonMeshApproximateConvexDecomposition (sourceMesh, m_currentConcavity, 0.2f, m_currentMaxCount, 1000, ConvexApproximationClassDesc::ReportProgress); inteface->ProgressEnd(); NewtonMeshDestroy (sourceMesh); // now convert the new mesh to a max poly Object MNMesh& maxMesh = GetMesh(); maxMesh.ClearAndFree(); int faceCount = 0; int vertexCount = NewtonMeshGetVertexCount(approximationMesh); for (void* face = NewtonMeshGetFirstFace(approximationMesh); face; face = NewtonMeshGetNextFace(approximationMesh, face)) { if (!NewtonMeshIsFaceOpen(approximationMesh, face)) { faceCount ++; } } //maxMesh.Clear(); maxMesh.setNumVerts(vertexCount); maxMesh.setNumFaces(faceCount); // add all vertex int vertexStride = NewtonMeshGetVertexStrideInByte(approximationMesh) / sizeof (dFloat64); dFloat64* const vertex = NewtonMeshGetVertexArray (approximationMesh); for (int j = 0; j < vertexCount; j ++) { dVector p (orthogonalRootTransform.TransformVector(dVector (float (vertex[vertexStride * j + 0]), float (vertex[vertexStride * j + 1]), float (vertex[vertexStride * j + 2]), float(1.0f)))); maxMesh.P(j) = Point3 (p.m_x, p.m_y, p.m_z); } // count the number of face and make a face map int faceIndex = 0; for (void* face = NewtonMeshGetFirstFace(approximationMesh); face; face = NewtonMeshGetNextFace(approximationMesh, face)) { if (!NewtonMeshIsFaceOpen(approximationMesh, face)) { int faceIndices[256]; int indexCount = NewtonMeshGetFaceIndexCount (approximationMesh, face); NewtonMeshGetFaceIndices (approximationMesh, face, faceIndices); MNFace* const face = maxMesh.F(faceIndex); face->MakePoly(indexCount, faceIndices, NULL, NULL); face->material = 0; faceIndex ++; } } maxMesh.InvalidateGeomCache(); maxMesh.InvalidateTopoCache(); maxMesh.FillInMesh(); maxMesh.AutoSmooth(45.0f * 3.1416f / 160.0f, false, false); NewtonMeshDestroy (approximationMesh); NewtonDestroy (world); }
pyScene::pyScene(void) { m_scene = new dScene (NewtonCreate ()); }
void DemoEntityManager::Cleanup () { // is we are run asynchronous we need make sure no update in on flight. if (m_world) { NewtonWaitForUpdateToFinish (m_world); } // destroy all remaining visual objects while (dList<DemoEntity*>::GetFirst()) { RemoveEntity (dList<DemoEntity*>::GetFirst()); } m_sky = NULL; // destroy the Newton world if (m_world) { // get serialization call back before destroying the world NewtonDestroy (m_world); m_world = NULL; } // memset (&demo, 0, sizeof (demo)); // check that there are no memory leak on exit dAssert (NewtonGetMemoryUsed () == 0); // create the newton world m_world = NewtonCreate(); // link the work with this user data NewtonWorldSetUserData(m_world, this); // set joint serialization call back CustomJoint::Initalize(m_world); // add all physics pre and post listeners // m_preListenerManager.Append(new DemoVisualDebugerListener("visualDebuger", m_world)); new DemoEntityListener (this); m_cameraManager = new DemoCameraListener(this); // m_postListenerManager.Append (new DemoAIListener("aiManager")); // set the default parameters for the newton world // set the simplified solver mode (faster but less accurate) NewtonSetSolverModel (m_world, 4); // newton 300 does not have world size, this is better controlled by the client application //dVector minSize (-500.0f, -500.0f, -500.0f); //dVector maxSize ( 500.0f, 500.0f, 500.0f); //NewtonSetWorldSize (m_world, &minSize[0], &maxSize[0]); // set the performance track function //NewtonSetPerformanceClock (m_world, dRuntimeProfiler::GetTimeInMicrosenconds); // clean up all caches the engine have saved NewtonInvalidateCache (m_world); // Set the Newton world user data NewtonWorldSetUserData(m_world, this); // we start without 2d render m_renderHood = NULL; m_renderHoodContext = NULL; }
// create physics scene void InitScene() { BoxPrimitive* box; BoxPrimitive* floor; NewtonBody* boxBody; NewtonBody* floorBody; NewtonCollision* collision; // create the newton world nWorld = NewtonCreate (PhysicsAlloc, PhysicsFree); // set the linear solver model for faster speed NewtonSetSolverModel (nWorld, 8); // set the adpative friction model for faster speed NewtonSetFrictionModel (nWorld, 1); // Set the termination function atexit(CleanUp); // create the the floor graphic objects dVector size (100.0f, 2.0f, 100.0f); dMatrix location (GetIdentityMatrix()); location.m_posit.m_y = -5.0f; // create a box for floor floor = new BoxPrimitive (location, size, g_floorTexture); // create the the floor collision, and body with default values collision = NewtonCreateBox (nWorld, size.m_x, size.m_y, size.m_z, NULL); floorBody = NewtonCreateBody (nWorld, collision); NewtonReleaseCollision (nWorld, collision); // set the transformation for this rigid body NewtonBodySetMatrix (floorBody, &location[0][0]); // save the pointer to the graphic object with the body. NewtonBodySetUserData (floorBody, floor); // set a destrutor for this rigid body NewtonBodySetDestructorCallback (floorBody, PhysicsBodyDestructor); // set the initial size size = dVector(0.5f, 0.5f, 0.5f); // create the collision collision = NewtonCreateBox (nWorld, size.m_x, size.m_y, size.m_z, NULL); // create 100 stacks of 10 boxes each location.m_posit.m_x = -10.0f; for (int k = 0; k < 10; k ++) { location.m_posit.m_z = 0.0f; for (int j = 0; j < 10; j ++) { location.m_posit.m_y = 2.0f; for (int i = 0; i < 10; i ++) { // create a graphic box box = new BoxPrimitive (location, size); //create the rigid body boxBody = NewtonCreateBody (nWorld, collision); // save the pointer to the graphic object with the body. NewtonBodySetUserData (boxBody, box); // set a destrutor for this rigid body NewtonBodySetDestructorCallback (boxBody, PhysicsBodyDestructor); // set the tranform call back function NewtonBodySetTransformCallback (boxBody, PhysicsSetTransform); // set the force and torque call back funtion NewtonBodySetForceAndTorqueCallback (boxBody, PhysicsApplyForceAndTorque); // set the mass matrix //NewtonBodySetMassMatrix (boxBody, 1.0f, 1.0f / 6.0f, 1.0f / 6.0f, 1.0f / 6.0f); NewtonBodySetMassMatrix (boxBody, 1.0f, 1.0f, 1.0f, 1.0f); // set the matrix for tboth the rigid nody and the graphic body NewtonBodySetMatrix (boxBody, &location[0][0]); PhysicsSetTransform (boxBody, &location[0][0]); location.m_posit.m_y += size.m_y * 2.0f; } location.m_posit.m_z -= size.m_z * 4.0f; } location.m_posit.m_x += size.m_x * 4.0f; } // release the collsion geometry when not need it NewtonReleaseCollision (nWorld, collision); }