/** * CreateGroundPlane(): Create Ground Plane * @return */ void CreateGroundPlane(){ /* * Create Ground Plane * Static Actor: has no 'NxBodyDesc' */ //actor Descriptor with Collection of Shapes. NxActorDesc actorDesc; //Plane Shape Descriptor NxPlaneShapeDesc planeDesc; //平面方程式: ax + by + cz + d = 0; planeDesc.normal = NxVec3(0, 1, 0); //面の法線はY軸(↑)方向 planeDesc.d = 0.0f; //Y = 0.0fに面を作る actorDesc.shapes.pushBack( &planeDesc ); //ActorにPlaneを登録 //NxScene Creates Actor and Returns a Pointer. NxActor* pActor = pScene->createActor( actorDesc); pActor->userData = NULL; //PhysX上のActorと(ゲームなどの)データ上のActorを結びつける //Set the parameters for the Default Material //Physicsの"Material"とは目に見える表面材質ではなく,物体の物理学的特徴を表す NxMaterial* defaultMaterial = pScene->getMaterialFromIndex( 0 ); defaultMaterial->setRestitution( 0.3f ); //反発係数 defaultMaterial->setStaticFriction( 0.5f ); //静止摩擦係数 defaultMaterial->setDynamicFriction( 0.5f ); //動摩擦係数 }
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ PhysicsProcessor::PhysicsProcessor() { NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; NxPhysicsSDK* pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL, desc, &errorCode); if( pPhysicsSDK == NULL ) { throw std::exception("Exception: Cannot create PhysX SDK Pointer."); } this->m_pPhysicsSDK = pPhysicsSDK; this->m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.025f); NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(0.0f, -9.81f, 0.0f); NxScene* pScene = this->m_pPhysicsSDK->createScene(sceneDesc); if( pScene == NULL ) { throw std::exception("Exception: Cannot create PhysX Scene Pointer."); } this->m_pScene = pScene; PhysicsActorFactory* pFactory = &PhysicsActorFactory::instance(); pFactory->setScene(this->m_pScene); NxMaterial * defaultMaterial = this->m_pScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); }
//----------------------------------------------------------------------------- // InitScene //----------------------------------------------------------------------------- bool CPhysicScene::InitScene (const TInitInfo& initInfo) { // Create the scene m_pScene = CPhysicEngine::Ref().GetNxPhysicsSDK()->createScene (initInfo.nxInfo); if ( m_pScene == NULL ) return false; // Editar las propiedades del material por defecto NxMaterial* defaultMaterial = m_pScene->getMaterialFromIndex(0); defaultMaterial->setRestitution (0.0f); defaultMaterial->setStaticFriction (0.5f); defaultMaterial->setDynamicFriction (0.4f); // CreateBox (NxVec3(0,0,0), NxVec3(10, 10, 10), 1); // Configuramos callback collisiones //!! m_pScene->setUserContactReport(this); m_pScene->setUserTriggerReport(this); m_pCollisionMng = initInfo.pCollisionMng; // Inicializar gestor de agua CPhysicWaterMgr::TInitInfo initWaterInfo; initWaterInfo.pScene = this; initWaterInfo.fWaterLevel = Globals::g_fWaterLevel; initWaterInfo.fWaterDensity = 4.f; initWaterInfo.fFrictionAngular = 10.f; initWaterInfo.fFrictionLinear = 5.f; m_WaterMgr.Init( initWaterInfo ); // Comprobar si debemos activar el gestor de agua //!! m_bWaterMngEnabled = initInfo.bWaterMngEnabled; return true; }
void PhysStart ( void ) { gAllocator = new UserAllocator; gPhysicsSDK = NxCreatePhysicsSDK ( NX_PHYSICS_SDK_VERSION,gAllocator ); if ( !gPhysicsSDK ) return; gPhysicsSDK->setParameter ( NX_MIN_SEPARATION_FOR_PENALTY, -0.05f ); gPhysicsSDK->setParameter ( NX_VISUALIZATION_SCALE, 1 ); gPhysicsSDK->setParameter ( NX_VISUALIZE_COLLISION_SHAPES, 1 ); gPhysicsSDK->setParameter ( NX_VISUALIZE_ACTOR_AXES, 1 ); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1); NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.broadPhase = NX_BROADPHASE_COHERENT; sceneDesc.collisionDetection = true; sceneDesc.userContactReport = carContactReport; gScene = gPhysicsSDK->createScene ( sceneDesc ); NxMaterial* defaultMaterial = gScene->getMaterialFromIndex ( 0 ); defaultMaterial->setRestitution ( 0.0f ); defaultMaterial->setStaticFriction ( 0.5f ); defaultMaterial->setDynamicFriction ( 0.5f ); gPhysicsSDK->setActorGroupPairFlags(0, 0, NX_NOTIFY_ON_TOUCH); }
void InitNx() { // Create the physics SDK gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION); if (!gPhysicsSDK) return; // Set the physics parameters gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01); // Set the debug visualization parameters gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); // gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.simType = NX_SIMULATION_HW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene){ sceneDesc.simType = NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) return; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Create the objects in the scene CreateGroundPlane(); capsule1 = CreateCapsule(NxVec3(0,5,0), 1, 0.5, 10); capsule1->raiseBodyFlag(NX_BF_KINEMATIC); capsule2 = CreateCapsule(NxVec3(0,3,0), 1, 0.5, 10); // capsule2->setLinearDamping(0.1); capsule2->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); NxVec3 globalAnchor = NxVec3(0,5,0); NxVec3 globalAxis = NxVec3(0,1,0); d6Joint = CreateD6Joint(capsule1, capsule2, globalAnchor, globalAxis); gSelectedActor = capsule2; gForceStrength = 50000; gCameraSpeed = 10; // Initialize HUD InitializeHUD(); InitializeSpecialHUD(); // Get the current time getElapsedTime(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
bool initNx() { NxSDKCreateError error; gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, new ErrorStream(), NxPhysicsSDKDesc(), &error); if (gPhysicsSDK == NULL) { cout << "Physics SDK creation failed: " << PhysXUtils::getErrorString(error) << endl; return false; } gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.2f); // 0.2 is the best I've tried NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(0.0f, -9.81f, 0.0f); g_NxScene = gPhysicsSDK->createScene(sceneDesc); if (g_NxScene == NULL) { cout << "ERROR: unable to create PhysX scene" << endl; return false; } NxMaterial* defaultMaterial = g_NxScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); NxPlaneShapeDesc planeDesc; NxActorDesc actorDesc; actorDesc.shapes.pushBack(&planeDesc); g_NxScene->createActor(actorDesc); return true; }
//------------------------------------------------------------------------------------------------- bool sdPhysicsSystem::LoadScene(sdMap* pkMap) { if (!m_bInitialized || !pkMap) return false; sdTerrain* pkTerrain = pkMap->GetTerrain(); NIASSERT(pkTerrain); // 创建空白NxScene CreateEmptyScene(pkTerrain->GetTerrainSize()); NIASSERT(m_pkScene); float fTimeStep = 1.f / 60.f; m_pkScene->setTiming(fTimeStep, 6, NX_TIMESTEP_FIXED); m_pkScene->setUserTriggerReport(m_pkUserTriggerReport); NxMaterial* pkDefaultMaterial = m_pkScene->getMaterialFromIndex(0); NIASSERT(pkDefaultMaterial); pkDefaultMaterial->setRestitution(0.1f); pkDefaultMaterial->setStaticFriction(0.5f); pkDefaultMaterial->setDynamicFriction(0.5f); // 加载地形数据到NxScene CreateTerrain(pkTerrain); // 加载预生成的物件数据到NxScene // 生成地形的边界 CreateTerrainBound(pkTerrain); return true; }
void InitNx() { // Create a memory allocator gAllocator = new UserAllocator; // Create the physics SDK gPhysicsSDK = CreatePhysics(); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.simType = NX_SIMULATION_HW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene){ sceneDesc.simType = NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) return; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Set Core Dump directory char buff[512]; FindMediaFile(fnameCD, buff); #ifdef WIN32 SetCurrentDirectory(buff); #elif LINUX chdir(buff); #endif // Create the objects in the scene NxActor* groundPlane = CreateGroundPlane(); NxActor* box = CreateBox(NxVec3(5,0,0), NxVec3(0.5,1,0.5), 20); NxActor* sphere = CreateSphere(NxVec3(0,0,0), 1, 10); NxActor* capsule = CreateCapsule(NxVec3(-5,0,0), 2, 0.5, 10); // pyramid = CreatePyramid(NxVec3(0,0,0), NxVec3(1,0.5,1.5), 10); AddUserDataToActors(gScene); gSelectedActor = capsule; // gSelectedActor = pyramid; // Initialize HUD InitializeHUD(); // Get the current time getElapsedTime(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
void InitNx() { // Create a memory allocator gAllocator = new UserAllocator; // Create the physics SDK gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator); if (!gPhysicsSDK) return; // Set the physics parameters gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01); // Set the debug visualization parameters gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 2); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.simType = NX_SIMULATION_HW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene){ sceneDesc.simType = NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) return; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Create the objects in the scene CreateGroundPlane(); mainBox = CreateMainObject(); gSelectedActor = mainBox; gCameraPos = NxVec3(0,15,-50); gCameraSpeed = 20; gForceStrength = 50000000; // Initialize HUD InitializeHUD(); // Get the current time getElapsedTime(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
bool CreateScenario() { DestroyScenario(); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.simType = bHWScene? NX_SIMULATION_HW : NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(0 == gScene) { bHWScene = !bHWScene; sceneDesc.simType = bHWScene? NX_SIMULATION_HW : NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(0 == gScene) return false; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Create the plane in primary scene groundPlane = CreateGroundPlane(); // Create compartment(HSM, managed hardware scene) attached to this scene NxCompartmentDesc desc; desc.type = NX_SCT_RIGIDBODY; desc.deviceCode = NxU32(NX_DC_PPU_0); gCompartmentHW = gScene->createCompartment(desc); desc.deviceCode = NxU32(NX_DC_CPU); gCompartmentSW = gScene->createCompartment(desc); // Create objects boxHW = CreateManagedBox(NxVec3(6, 0, 0), NxVec3(0.5, 1, 0.5), 20, gCompartmentHW); boxSW = CreateManagedBox(NxVec3(3, 0, 0), NxVec3(0.5, 1, 0.5), 20, gCompartmentSW); sphereHW = CreateManagedSphere(NxVec3(-6,0,0), 1, 10, gCompartmentHW); sphereHW = CreateManagedSphere(NxVec3(-3,0,0), 1, 10, gCompartmentSW); capsule = CreateManagedCapsule(NxVec3(0,0,0), 2, 1, 5, 0); gSelectedActor = boxHW; // Initialize HUD InitializeHUD(); // Start the first frame of the simulation StartPhysics(); return true; }
static bool InitNx() { if (!gAllocator) gAllocator = new UserAllocator; // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator, NULL, desc, &errorCode); if(gPhysicsSDK == NULL) { printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode)); return false; } #if SAMPLES_USE_VRD // The settings for the VRD host and port are found in SampleCommonCode/SamplesVRDSettings.h if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger() && !gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(SAMPLES_VRD_HOST, SAMPLES_VRD_PORT, SAMPLES_VRD_EVENTMASK); #endif gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.025f); // Create two scenes for(NxU32 i=0;i<2;i++) { NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; gScenes[i] = gPhysicsSDK->createScene(sceneDesc); if(gScenes[i] == NULL) { printf("\nError: Unable to create one of the two PhysX scenes, exiting the sample.\n\n"); return false; } // Create ground plane NxPlaneShapeDesc PlaneDesc; NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&PlaneDesc); gScenes[i]->createActor(ActorDesc); //materials are no longer shared between scenes so they have to be set up for both: NxMaterial * defaultMaterial = gScenes[i]->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); } return true; }
bool PhysicsManager::createScene() { if(!mSDK) return false; // Create a scene NxSceneDesc sceneDesc; sceneDesc.setToDefault(); //sceneDesc.timeStepMethod = NX_TIMESTEP_VARIABLE; sceneDesc.timeStepMethod = NX_TIMESTEP_FIXED; sceneDesc.gravity = NxVec3(0.0f, -14.1f, 0.0f); sceneDesc.simType = NX_SIMULATION_SW; mScene = mSDK->createScene(sceneDesc); if(mScene == NULL) { printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n"); return false; } mScene->setActorGroupPairFlags(0,0,NX_NOTIFY_ON_START_TOUCH|NX_NOTIFY_ON_TOUCH|NX_NOTIFY_ON_END_TOUCH); // Set default material NxMaterial* defaultMaterial = mScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create ground plane //NxPlaneShapeDesc planeDesc; //NxActorDesc actorDesc; //actorDesc.shapes.pushBack(&planeDesc); //mScene->createActor(actorDesc); mScene->setUserTriggerReport(this); mScene->setUserContactReport(this); mIsSceneCreated = true; mIsRunningSim = true; mCurrentTime = 0; return true; }
//----------------------------------------------------------------------- bool PhysXBridge::initNx(Real gravityY) { if (!mPhysicsSDK) { // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; mPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, new PhysXLogging(), desc, &errorCode); if(!mPhysicsSDK) { EXCEPT(Exception::ERR_INTERNAL_ERROR, "PU: Cannot initialise the PhysX SDK.", "PhysXBridge::initNx"); } mPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05f); } // Create a scene if (!mScene) { NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(0.0f, gravityY, 0.0f); mScene = mPhysicsSDK->createScene(sceneDesc); if(!mScene) { EXCEPT(Exception::ERR_INTERNAL_ERROR, "PU: Cannot create a PhysX Scene.", "PhysXBridge::initNx"); } // Set the contact report mScene->setUserContactReport(&mPhysXContactReport); // Set default material NxMaterial* defaultMaterial = mScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create ground plane createPlane(); } // Create a controller ControllerManager& controllerManager = ControllerManager::getSingleton(); ControllerValueRealPtr physXBridgeUpdateValue(PU_NEW PhysXBridgeUpdateValue(this)); mTimeController = controllerManager.createFrameTimePassthroughController(physXBridgeUpdateValue); return true; }
void InitNx() { // Create a memory allocator gAllocator = new UserAllocator; // Create the physics SDK gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator); if (!gPhysicsSDK) return; // Set the physics parameters gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01); // Set the debug visualization parameters gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); //gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); //gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); //gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1); // Create the scene NxSceneDesc sceneDesc; sceneDesc.simType = NX_SIMULATION_SW; sceneDesc.gravity = gDefaultGravity; gScene = gPhysicsSDK->createScene(sceneDesc); // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); groundPlane = CreateGroundPlane(); //groundPlane->getShapes()[0]->setFlag(NX_SF_FLUID_DRAIN,true); // Create drain actors CreateDrainActors(); fluidEmitter = CreateFluidEmitter(0.35, 0.35); // Initialize HUD InitializeHUD(); // Get the current time getElapsedTime(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
bool InitNx() { // Initialize PhysicsSDK NxPhysicsSDKDesc desc; gMyPhysX.initPhysX(desc); if(isPhysXHardwarePresent()) printf("PhysX Hardware is available in your system!\n"); // Create a scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; gMyPhysX.createDefaultScene(sceneDesc); // Create ground plane NxPlaneShapeDesc PlaneDesc; PlaneDesc.group = 2; NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&PlaneDesc); gMyPhysX.getScene()->createActor(ActorDesc); NxMaterial * defaultMaterial = gMyPhysX.getScene()->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create trigger NxVec3 zeroV(0,0,0); CreateTrigger(NxVec3(0,10,0), 10); CreateTrigger(NxVec3(-40,10,0), 10, &zeroV, false); CreateCube(NxVec3(-40,10,40), 10, NULL, false, true); CreateCube(NxVec3(-40,10,80), 10, NULL, true, false); //This creates a kinematic actor with a trigger, note that kinematic //triggers get interactions with static objects, thus this trigger //(which is placed directly above the ground) will directly get an //enter event for the ground plane (and change it's color). CreateTrigger(NxVec3(40,10,0), 10, NULL, true); //You can try to move it up just a little bit, and you will see //that it will no longer intersect the ground plane. //CreateTrigger(NxVec3(40,11,0), 10, NULL, true); return true; }
// // ESciVis::InitPhysX // void ESciVis::InitPhysX( void ) { LOG_INIT("PhysX"); // Create the physics SDK nx = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION); if (!nx) return; // Set the physics parameters nx->setParameter(NX_SKIN_WIDTH, 0.01f); // Set the debug visualization parameters nx->setParameter(NX_VISUALIZATION_SCALE, 1); nx->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); nx->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(0,0,0); sceneDesc.simType = NX_SIMULATION_SW; nx_scene = nx->createScene(sceneDesc); if(!nx_scene) { sceneDesc.simType = NX_SIMULATION_SW; nx_scene = nx->createScene(sceneDesc); if(!nx_scene) return; } // coocking lib : nx_cook = NxGetCookingLib(NX_PHYSICS_SDK_VERSION); if (!nx_cook) { RUNTIME_ERROR("NxGetCookingLib() failed"); } nx_cook->NxInitCooking(); // Create the default material NxMaterial* defaultMaterial = nx_scene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); }
bool GraphicsClass::InitializePhysX(NxScene* scene) { n_scene = scene; // plane NxPlaneShapeDesc plane_desc; plane_desc.normal = NxVec3(0,1,0); plane_desc.d = 0.0f; NxMaterial* defaultMaterial = n_scene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); NxActorDesc plane_actor; plane_actor.shapes.pushBack(&plane_desc); n_scene->createActor(plane_actor); return true; }
void PhysScene::create(const Desc& desc) { Scene::create(desc); { // Access to PhysX requires CS, despite the object is not activated yet CriticalSectionWrapper csw(universe->getCS()); pNxPhysicsSDK = universe->pNxPhysicsSDK; pNxScene = pNxPhysicsSDK->createScene(desc.physics.nxSceneDesc); if (pNxScene == NULL) throw MsgPhysSceneNxSceneCreate(Message::LEVEL_CRIT, "PhysScene::create(): Unable to create NxScene"); // Set simulation parameters pNxScene->setTiming((NxReal)universe->maxTimeStep); NxMaterial* defaultMaterial = pNxScene->getMaterialFromIndex(0); defaultMaterial->setRestitution((NxReal)desc.physics.restitution); defaultMaterial->setStaticFriction((NxReal)desc.physics.staticFriction); defaultMaterial->setDynamicFriction((NxReal)desc.physics.dynamicFriction); } }
bool PhysX::InitNx() { // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; m_pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL, desc, &errorCode); if(m_pPhysicsSDK == NULL) { printf("Unable to initialize the PhysX SDK, exiting the sample.\n"); return false; } m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.03f); // Create a scene NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(0.0f, -9.81f, 0.0f); m_pScene = m_pPhysicsSDK->createScene(sceneDesc); if(m_pScene == NULL) { printf("Unable to create a PhysX scene, exiting the sample.\n"); return false; } // Set default material NxMaterial* defaultMaterial = m_pScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create ground plane NxPlaneShapeDesc planeDesc; NxActorDesc actorDesc; actorDesc.shapes.pushBack(&planeDesc); m_pScene->createActor(actorDesc); return true; }
bool InitNx() { // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, 0, desc, &errorCode); if(gPhysicsSDK == NULL) { printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode)); return false; } gPhysicsSDK->setParameter(NX_SKIN_WIDTH, gSkinWidth); gPhysicsSDK->setParameter(NX_DEFAULT_SLEEP_ENERGY, 0.01f); // Create a scene NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(0.0f, -9.81f, 0.0f); sceneDesc.userNotify = &g_SleepCallBack; //用户自定义事件 sceneDesc.userContactReport = &gMyContactReport; gScene = gPhysicsSDK->createScene(sceneDesc); if(gScene == NULL) { printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n"); return false; } gScene->setTiming(); // Set default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); CreatePhysicsTerrain(); return true; }
//---------------------------------------------------------------------------- // Init data //---------------------------------------------------------------------------- bool CPhysicsManager::Init () { m_bIsOk = true; m_pMyAllocator = new CPhysicUserAllocator; assert(m_pMyAllocator); m_bIsOk = (m_pMyAllocator != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Inicializando la libreria PhysX"); // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; m_pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, m_pMyAllocator, NULL, desc, &errorCode); /*Precompilation Directives*/ #if defined( _DEBUG ) #define USE_DEBUGGER #ifdef USE_DEBUGGER m_pPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect("127.0.0.1"); #endif #endif m_bIsOk = (m_pPhysicsSDK != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el PhysXSDK"); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: -------PhsX Settings---"); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: El valor del SkinWidth es: %f", m_InitParams.m_fSkinWidth); //TODO por XML m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, m_InitParams.m_fSkinWidth); m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.1f); //CODI PER PRINTAR INFO DELS JOINTS m_pPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); m_pPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); m_pPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1); m_pPhysicsSDK->setParameter(NX_CONTINUOUS_CD, 1); // Create a scene LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: El valor de la gravedad es: %f", m_InitParams.m_fGravity); NxSceneDesc sceneDesc; //TODO por XML sceneDesc.gravity = NxVec3(0.0f, m_InitParams.m_fGravity, 0.0f); sceneDesc.gravity = NxVec3(0.0f, -9.8f, 0.0f); m_pScene = m_pPhysicsSDK->createScene(sceneDesc); m_bIsOk = (m_pScene != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Solo hay un material, con los siguientes params"); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->Restitution %f:", m_InitParams.m_Restitution_DefMat); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->StaticFriction %f:", m_InitParams.m_StaticFriction_DefMat); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->DynamicFriction %f:", m_InitParams.m_DynamicFriction_DefMat); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: ----END PhsX Settings---"); // Set default material NxMaterial* defaultMaterial = m_pScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(m_InitParams.m_Restitution_DefMat); defaultMaterial->setStaticFriction(m_InitParams.m_StaticFriction_DefMat); defaultMaterial->setDynamicFriction(m_InitParams.m_DynamicFriction_DefMat); //Collision Flags //m_pScene->setGroupCollisionFlag(ECG_ARMA,ECG_ESCENARI,true); //Create a controllerManager m_pControllerManager = NxCreateControllerManager(m_pMyAllocator); m_bIsOk = (m_pControllerManager != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el controlador de caracteres"); m_pCookingMesh = new CPhysicCookingMesh(); assert(m_pCookingMesh); m_bIsOk = m_pCookingMesh->Init(m_pPhysicsSDK, m_pMyAllocator); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el CookingMesh"); } } //m_bIsOk m_pControllerManager?*/ }//isOk m_pScene? }//isOk m_pPhysicsSDK ? }//isOk m_pMyAllocator ? if (!m_bIsOk) { std::string msg_error = "PhysicsManager::Init-> Error en la inicializacion de PhysX"; LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str()); Release(); throw CException(__FILE__, __LINE__, msg_error); } return m_bIsOk; }
void Vehicle::loadScene(const std::string &fileName) { //车的父节点 mBaseCarNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(fileName + "BaseCarNode"); //DotSceneLoader* dsl = new DotSceneLoader();//rel //dsl->parseDotScene(fileName + ".scene", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, mSceneMgr, mBaseCarNode); mVehicleRenderable = new VehicleRenderable(mSceneMgr, mBaseCarNode); mVehicleRenderable->load(fileName + ".vrf"); //车身节点 mBodyNode = static_cast<Ogre::SceneNode*>(mBaseCarNode->getChild(fileName + "Body")); //轮子节点 mWheels[TOP_LEFT].mSceneNode = static_cast<Ogre::SceneNode*>(mBaseCarNode->getChild(fileName + "LTWheel")); mWheels[TOP_LEFT].mName = fileName + "LTWheel"; mWheels[TOP_RIGHT].mSceneNode = static_cast<Ogre::SceneNode*>(mBaseCarNode->getChild(fileName + "RTWheel")); mWheels[TOP_RIGHT].mName = fileName + "RTWheel"; mWheels[Bottom_LEFT].mSceneNode = static_cast<Ogre::SceneNode*>(mBaseCarNode->getChild(fileName + "LBWheel")); mWheels[Bottom_LEFT].mName = fileName + "LBWheel"; mWheels[Bottom_RIGHT].mSceneNode = static_cast<Ogre::SceneNode*> (mBaseCarNode->getChild(fileName + "RBWheel")); mWheels[Bottom_RIGHT].mName = fileName + "RBWheel"; //设置整体参数 NxBodyDesc bodyDes; //bodyDes.wakeUpCounter = 1E8; bodyDes.mass = 12000;//mVehicleInfo.gMass; //bodyDes.massLocalPose.t = NxVec3(mVehicleInfo.gMassLocalPose.x, mVehicleInfo.gMassLocalPose.y, mVehicleInfo.gMassLocalPose.z); bodyDes.angularDamping = 0.03f; bodyDes.linearDamping = 0.08f; //写入车身的shapeDesc mBoundingBox = mBodyNode->getAttachedObject(0)->getBoundingBox(); NxBoxShapeDesc boxDes; NxVec3 dimen (mBoundingBox.getHalfSize().x, mBoundingBox.getHalfSize().y, mBoundingBox.getHalfSize().z); NxVec3 localPos (mBodyNode->getPosition().x, mBodyNode->getPosition().y, mBodyNode->getPosition().z); ////车身到轮子的距离 //NxReal d1 = NxMath::abs(mBodyNode->getPosition().y - mWheels[0].mSceneNode->getPosition().y); ////包围盒半径之和 //NxReal d2 = mBoundingBox.getHalfSize().y + mWheels[0].mSceneNode->getAttachedObject(0)->getBoundingBox().getHalfSize().y; ////判断轮子是否与车身的包围盒重叠 //if(d1 < d2) //{ // //设置为最大适合高度 // dimen.y = (mBoundingBox.getSize().y - (d2 - d1)) / 2.0f; //} boxDes.dimensions.set(dimen); boxDes.localPose.t = localPos; NxActorDesc actorDesc; actorDesc.body = &bodyDes; actorDesc.globalPose.t = NxVec3(mOriginalPos.x, mOriginalPos.y, mOriginalPos.z); NxQuat quat; quat.setWXYZ(mOriginalQuat.w, mOriginalQuat.x, mOriginalQuat.y, mOriginalQuat.z); actorDesc.globalPose.M.fromQuat(quat); actorDesc.shapes.pushBack(&boxDes); mActor = mNxScene->createActor(actorDesc); mActor->setCMassOffsetLocalPosition(NxVec3(0, -mBoundingBox.getSize().y, 0)); mBodyShape = static_cast<NxBoxShape*>(mActor->getShapes()[0]); //写入轮子的shapeDesc createWheelShapeDesc(&mWheels[TOP_LEFT], true); createWheelShapeDesc(&mWheels[TOP_RIGHT], true); createWheelShapeDesc(&mWheels[Bottom_LEFT], false); createWheelShapeDesc(&mWheels[Bottom_RIGHT], false); //mWheels[TOP_LEFT].mWheelDesc.localPose.t = NxVec3(mBoundingBox.getHalfSize().x, 2, 0); //mWheels[TOP_RIGHT].mWheelDesc.localPose.t = NxVec3(-mBoundingBox.getHalfSize().x, 2, 0); //mWheels[Bottom_LEFT].mWheelDesc.localPose.t = NxVec3(mBoundingBox.getHalfSize().x, -mBoundingBox.getHalfSize().y, 0); //mWheels[Bottom_RIGHT].mWheelDesc.localPose.t = NxVec3(-mBoundingBox.getHalfSize().x, -mBoundingBox.getHalfSize().y, 0); //创建轮子 mWheels[TOP_LEFT].mWheel = static_cast<NxWheelShape*>(mActor->createShape(mWheels[TOP_LEFT].mWheelDesc)); mWheels[TOP_RIGHT].mWheel = static_cast<NxWheelShape*>(mActor->createShape(mWheels[TOP_RIGHT].mWheelDesc)); mWheels[Bottom_LEFT].mWheel = static_cast<NxWheelShape*>(mActor->createShape(mWheels[Bottom_LEFT].mWheelDesc)); mWheels[Bottom_RIGHT].mWheel = static_cast<NxWheelShape*>(mActor->createShape(mWheels[Bottom_RIGHT].mWheelDesc)); NxMaterial* mat = mNxScene->getMaterialFromIndex(0); mat->setFrictionCombineMode(NX_CM_MULTIPLY); mat->setStaticFriction(300.2f); mat->setDynamicFriction(100.5f); }
NxScene* plSimulationMgr::GetScene(plKey world) { if (!world) world = GetKey(); NxScene* scene = fScenes[world]; if (!scene) { NxSceneDesc sceneDesc; sceneDesc.gravity.set(0, 0, -32.174049f); sceneDesc.userTriggerReport = &gSensorReport; sceneDesc.userContactReport = &gContactReport; scene = fSDK->createScene(sceneDesc); // See "Advancing The Simulation State" in the PhysX SDK Documentation // This will cause PhysX to only update for our step size. If we call simulate // faster than that, PhysX will return immediately. If we call it slower than that, // PhysX will do some extra steps for us (isn't that nice?). // Anyway, this should be a good way to make us independent of the framerate. // If not, I blame the usual suspects (Tye, eap, etc...) scene->setTiming(kDefaultStepSize); // Most physicals use the default friction and restitution values, so we // make them the default. NxMaterial* mat = scene->getMaterialFromIndex(0); float rest = mat->getRestitution(); float sfriction = mat->getStaticFriction(); float dfriction = mat->getDynamicFriction(); mat->setRestitution(0.5); mat->setStaticFriction(0.5); mat->setDynamicFriction(0.5); // By default we just leave all the collision groups enabled, since // PhysX already makes sure that things like statics and statics don't // collide. However, we do make it so the avatar and dynamic blockers // only block avatars and dynamics. for (int i = 0; i < plSimDefs::kGroupMax; i++) { scene->setGroupCollisionFlag(i, plSimDefs::kGroupAvatarBlocker, false); scene->setGroupCollisionFlag(i, plSimDefs::kGroupDynamicBlocker, false); scene->setGroupCollisionFlag(i, plSimDefs::kGroupLOSOnly, false); scene->setGroupCollisionFlag(plSimDefs::kGroupLOSOnly, i, false); } scene->setGroupCollisionFlag(plSimDefs::kGroupAvatar, plSimDefs::kGroupAvatar, false); scene->setGroupCollisionFlag(plSimDefs::kGroupAvatar, plSimDefs::kGroupAvatarBlocker, true); scene->setGroupCollisionFlag(plSimDefs::kGroupDynamic, plSimDefs::kGroupDynamicBlocker, true); scene->setGroupCollisionFlag(plSimDefs::kGroupAvatar, plSimDefs::kGroupStatic, true); scene->setGroupCollisionFlag( plSimDefs::kGroupStatic, plSimDefs::kGroupAvatar, true); scene->setGroupCollisionFlag(plSimDefs::kGroupAvatar, plSimDefs::kGroupDynamic, true); // The dynamics are in actor group 1, everything else is in 0. Request // a callback for whenever a dynamic touches something. scene->setActorGroupPairFlags(0, 1, NX_NOTIFY_ON_TOUCH); scene->setActorGroupPairFlags(1, 1, NX_NOTIFY_ON_TOUCH); fScenes[world] = scene; } return scene; }
void InitNx() { // Initialize Camera Parameters gCameraAspectRatio = 1.0f; gCameraPos = NxVec3(0,5,-15); gCameraForward = NxVec3(0,0,1); gCameraRight = NxVec3(-1,0,0); // Create the physics SDK gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION); if (!gPhysicsSDK) return; // Set the physics parameters gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01); gPhysicsSDK->setParameter(NX_DEFAULT_SLEEP_LIN_VEL_SQUARED, 0.15*0.15); gPhysicsSDK->setParameter(NX_DEFAULT_SLEEP_ANG_VEL_SQUARED, 0.14*0.14); // Set the debug visualization parameters gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_AABBS, 1); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.simType = NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) { sceneDesc.simType = NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) return; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Create the objects in the scene groundPlane = CreateGroundPlane(); // Create dynamic actors CreateSphere(NxVec3(6.0f, 0.0f, 24.0f), 0); CreateBox(NxVec3(6.0f, 0.0f, 16.0f), 0); CreateCapsule(NxVec3(6.0f, 0.0f, 6.0f), 0); gSelectedActor = CreateConvex(NxVec3(6.0f, 0.0f, 0.0f), 0); // Create static actors CreateSphere(NxVec3(0.0f, 0.0f, 24.0f), 0); CreateBox(NxVec3(0.0f, 0.0f, 16.0f), 0); CreateCapsule(NxVec3(0.0f, 0.0f, 6.0f), 0); CreateConvex(NxVec3(0.0f, 0.0f, 0.0f), 0); // Create kinematic actors CreateSphere(NxVec3(-6.0f, 0.0f, 24.0f), 0); CreateBox(NxVec3(-6.0f, 0.0f, 16.0f), 0); CreateCapsule(NxVec3(-6.0f, 0.0f, 6.0f), 0); CreateConvex(NxVec3(-6.0f, 0.0f, 0.0f), 0); bPause = false; gCapsuleSegment.p0 = NxVec3(0, 1.2f, 0.5f); gCapsuleSegment.p1 = NxVec3(0, 3.2f, 0.5f); // Initialize HUD InitializeHUD(); // Get the current time getElapsedTime(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
Data(bool useHardware, bool useHardwareOnly, bool useMultithreading, PhysicsParams *params) : sdk(0), scene(0), crashed(false), statsNumActors(0), statsNumDynamicActors(0), statsNumDynamicActorsInAwakeGroups(0), statsMaxDynamicActorsInAwakeGroups(0), statsSimulationTime(0), statsSimulationWaitTime(0), statsSimulationStartWaitTime(0), startSimulationTime(0), statsContacts(0), ccd(false), ccdMaxThickness(0.5f), runningInHardware(false), physicslib_fluid_containment_actor(0), physicslib_fluid_containment_shape(0), physicslib_fluid_containment_sphere_actor(0), physicslib_fluid_containment_sphere_shape(0) { if (params == NULL) { params = &physics_defaultParams; ::Logger::getInstance()->debug("PhysicsLib - No physics params given, using defaults."); } if (params->scriptRunner == NULL) { ::Logger::getInstance()->warning("PhysicsLib - No script runner given, collision groups, etc. will be initialized to default values."); } NxPhysicsSDKDesc sdkDesc; if(!useHardware) sdkDesc.flags |= NX_SDKF_NO_HARDWARE; sdk = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, getLogger(), sdkDesc); //sdk = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION); // HACK: ... physxSDK = sdk; if(sdk) { if(sdk->getHWVersion() == NX_HW_VERSION_NONE) useHardware = false; if (params->ccd) { sdk->setParameter(NX_CONTINUOUS_CD, true); sdk->setParameter(NX_CCD_EPSILON, 0.001f); } this->ccd = params->ccd; this->ccdMaxThickness = params->ccdMaxThickness; NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(params->gravity.x, params->gravity.y, params->gravity.z); sceneDesc.userContactReport = &contactReport; //sceneDesc.userNotify = &userNotify; if(useHardware) { sceneDesc.simType = NX_SIMULATION_HW; if (useHardwareOnly) { sceneDesc.flags |= NX_SF_RESTRICTED_SCENE; } } else { sceneDesc.simType = NX_SIMULATION_SW; } if (!useMultithreading) { // Disable threading sceneDesc.flags = 0; } runningInHardware = useHardware; sceneDesc.flags |= NX_SF_ENABLE_ACTIVETRANSFORMS; scene = sdk->createScene(sceneDesc); if(scene) { NxMaterial *defaultMaterial = scene->getMaterialFromIndex(0); defaultMaterial->setStaticFriction(params->defaultStaticFriction); defaultMaterial->setDynamicFriction(params->defaultDynamicFriction); defaultMaterial->setRestitution(params->defaultRestitution); #ifdef PROJECT_CLAW_PROTO // Create material for cops (larger friction, no restitution) NxMaterialDesc materialDesc; materialDesc.restitution = 0.0f; materialDesc.restitutionCombineMode = NX_CM_MIN; materialDesc.staticFriction = 10.0f; materialDesc.dynamicFriction = 10.0f; unitMaterial = scene->createMaterial(materialDesc); #endif sdk->setParameter(NX_VISUALIZATION_SCALE, 1.f); #ifndef PROJECT_SHADOWGROUNDS sdk->setParameter(NX_SKIN_WIDTH, 0.01f); #endif // NEW: the new scriptable collision/contact group initialization int contactFlags1 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES; #ifdef PHYSICS_FEEDBACK int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES; #else int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_FORCES; #endif if (params->scriptRunner != NULL) { bool ok = params->scriptRunner->runPhysicsLibScript("physics_init", "set_contacts"); if (!ok) ::Logger::getInstance()->error("PhysicsLib - Failed to run physics_init:set_contacts script (script/sub may not be loaded or did not return expected value)."); } for (int i = 0; i < PHYSICS_MAX_COLLISIONGROUPS; i++) { for (int j = 0; j < PHYSICS_MAX_COLLISIONGROUPS; j++) { if (physicslib_group_cont[i][j] != physicslib_group_cont[j][i]) { ::Logger::getInstance()->error("PhysicsLib - Improperly mirrored physics contacts data (group1 -> group2 does not have same flag as group2 -> group1)."); ::Logger::getInstance()->debug("contacts data group numbers follow:"); ::Logger::getInstance()->debug(int2str(i)); ::Logger::getInstance()->debug(int2str(j)); } if (physicslib_group_cont[i][j] == PHYSICSLIB_GROUP_CONTACT_FLAGS1) scene->setActorGroupPairFlags(i, j, contactFlags1); else if (physicslib_group_cont[i][j] == PHYSICSLIB_GROUP_CONTACT_FLAGS2) scene->setActorGroupPairFlags(i, j, contactFlags2); } } if (params->scriptRunner != NULL) { bool ok = params->scriptRunner->runPhysicsLibScript("physics_init", "set_collisions"); if (!ok) ::Logger::getInstance()->error("PhysicsLib - Failed to run physics_init:set_collision script (script/sub may not be loaded or did not return expected value)."); } for (int i = 0; i < PHYSICS_MAX_COLLISIONGROUPS; i++) { for (int j = 0; j < PHYSICS_MAX_COLLISIONGROUPS; j++) { if (physicslib_group_coll[i][j] != physicslib_group_coll[j][i]) { ::Logger::getInstance()->error("PhysicsLib - Improperly mirrored physics collision data (group1 -> group2 does not have same flag as group2 -> group1)."); ::Logger::getInstance()->debug("collision data group numbers follow:"); ::Logger::getInstance()->debug(int2str(i)); ::Logger::getInstance()->debug(int2str(j)); } scene->setGroupCollisionFlag(i, j, physicslib_group_coll[i][j]); } } // OLD SCHEISSE... /* // Contact groups { int contactFlags1 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES; #ifdef PHYSICS_FEEDBACK int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_ON_TOUCH | NX_NOTIFY_FORCES; #else int contactFlags2 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_FORCES; #endif //int contactFlags3 = NX_NOTIFY_ON_START_TOUCH | NX_NOTIFY_FORCES; scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, contactFlags2); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, contactFlags2); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags1); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags2); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags2); //scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags2); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, contactFlags1); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_UNITS, contactFlags2); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_STATIC, PHYSICS_COLLISIONGROUP_UNITS, contactFlags2); scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_STATIC, contactFlags1); //scene->setActorGroupPairFlags(PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, PHYSICS_COLLISIONGROUP_UNITS, contactFlags3); } // Collision groups { // claw scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_CLAW, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_NOCOLLISION, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_CLAW, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_CLAW, PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, false); // Model particles scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); // Doors scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_DOORS, PHYSICS_COLLISIONGROUP_DOORS, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_DOORS, PHYSICS_COLLISIONGROUP_STATIC, false); // Units and model particles scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_UNITS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_UNITS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false); // Fluids scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); // Fluids w/ detailed collision scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); // Fluid containment scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_STATIC, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_UNITS, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_DOORS, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, PHYSICS_COLLISIONGROUP_FLUIDS_DETAILED, false); // No collision scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_STATIC, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_WO_UNIT_COLL_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_MODEL_PARTICLES_NO_SOUND, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_UNITS, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_DOORS, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_DYNAMIC_TERRAINOBJECTS, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_FLUID_CONTAINMENT_PLANES, false); scene->setGroupCollisionFlag(PHYSICS_COLLISIONGROUP_NOCOLLISION, PHYSICS_COLLISIONGROUP_NOCOLLISION, false); } */ } } }
void InitNx() { // Create a memory allocator gAllocator = new UserAllocator; // Initialize physics SDK gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator); if (!gPhysicsSDK) return; gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05); gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 10); //gPhysicsSDK->setParameter(NX_VISUALIZE_FLUID_POSITION, 1); //gPhysicsSDK->setParameter(NX_VISUALIZE_FLUID_VELOCITY, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_FLUID_PACKETS, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_FLUID_DRAINS, 1); // Create a scene NxSceneDesc sceneDesc; sceneDesc.simType = NX_SIMULATION_SW; sceneDesc.gravity = gDefaultGravity; gScene = gPhysicsSDK->createScene(sceneDesc); // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Initialize cooking NxInitCooking(NULL, &gErrorStream); // Load ASE files int set = 0; #ifdef WIN32 set = SetCurrentDirectory(&fname[0]); if (!set) set = SetCurrentDirectory(&fname1[0]); if (!set) set = SetCurrentDirectory(&fname2[0]); if (!set) set = SetCurrentDirectory(&fname3[0]); if (!set) { char basePath[256]; GetModuleFileName(NULL, basePath, 256); char* pTmp = strrchr(basePath, '\\'); basePath[pTmp-basePath+1] = 0; SetCurrentDirectory(basePath);//for running from start menu set = SetCurrentDirectory(&fname2[0]); } #elif LINUX set = chdir(&fname[0]); if (set != 0) set = chdir(&fname2[0]); if (set != 0) set = chdir(&fname3[0]); #endif bowl = CookASE("fluidSample.ase", gScene, NxVec3(1,0,0)); flume = CookASE("coolFlow.ase", gScene, NxVec3(1,-4,-0), NxVec3(1,0.2,1)); box = CreateBox(NxVec3(2,5-0.75,7), NxVec3(0.75,0.75,0.75), 1); sphere = CreateSphere(NxVec3(0,4-0.4,1), 0.4, 1); capsule = CreateCapsule(NxVec3(3,0-(1+0.5),8), 1, 1, 1); CreateBox(NxVec3(0,-10-1,0), NxVec3(40,1,40), 0); fluid = CreateFluid(NxVec3(0,1.5,0), 19, 0.1, gScene); AddUserDataToActors(gScene); //((ActorUserData*)(drain->userData))->flags |= UD_IS_DRAIN; // Page in the hardware meshes if(bHardwareScene) PageInHardwareMeshes(gScene); gSelectedActor = box; // Initialize HUD InitializeHUD(); // Get the current time getElapsedTime(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
/*********************************************************** init function ***********************************************************/ void PhysXEngine::Init() { // Create the physics SDK gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION); if (!gPhysicsSDK) return; if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger()) gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect("localhost", 5425); // Set the physics parameters gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01f); // Set the debug visualization parameters gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); // Create the scene NxSceneDesc sceneDesc; sceneDesc.simType = NX_SIMULATION_SW; sceneDesc.gravity = NxVec3(0,-9.8f,0); gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) { sceneDesc.simType = NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) return; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // add a cube and a plane //CreatePlane(NxVec3(0, 0, 0), NxVec3(0, 1, 0)); CreateBox(NxVec3(0, 4, 0), 3.0f, 3.0f, 3.0f, 10, false); CreateBox(NxVec3(7, 10, 7), 2.0f, 3.0f, 2.0f, 10, true); CreateBox(NxVec3(20, 1, 20), 30.0f, 1.0f, 30.0f, 10, false); // init time _lasttime = SynchronizedTimeHandler::getInstance()->GetCurrentTimeDouble(); // init character controllers gManager = NxCreateControllerManager(gAllocator); //float TimeStep = 1.0f / 60.0f; gScene->setTiming(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
void InitNx() { // Create a memory allocator gAllocator = new UserAllocator; // Create the physics SDK gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator); if (!gPhysicsSDK) return; // Set the physics parameters gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01); // Set the debug visualization parameters gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.simType = NX_SIMULATION_HW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene){ sceneDesc.simType = NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(!gScene) return; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Create the objects in the scene CreateGroundPlane(); // Slider Joint capsule1 = CreateCapsule(NxVec3(0,5,0), 1, 0.5, 10); capsule1->raiseBodyFlag(NX_BF_KINEMATIC); capsule2 = CreateCapsule(NxVec3(0,3,0), 1, 0.5, 10); capsule2->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); NxVec3 globalAnchor = gJointStartPos; NxVec3 globalAxis = NxVec3(0,1,0); d6Joint = CreateD6Joint(capsule1, capsule2, globalAnchor, globalAxis); ball = CreateFollowBall(gBallStartPos,0.25,1); ball->raiseBodyFlag(NX_BF_KINEMATIC); NxMat33 orient = ball->getGlobalOrientation(); NxMat33 controlOrient; controlOrient.setRow(0, orient.getRow(2)); controlOrient.setRow(1, orient.getRow(0)); controlOrient.setRow(2, orient.getRow(1)); ball->setGlobalOrientation(controlOrient); gSelectedActor = ball; gForceStrength = 1500; gCameraSpeed = 10; box = CreateBox(NxVec3(3,0,0), NxVec3(0.5,1,0.5), 20); sphere = CreateSphere(NxVec3(0,0,3), 1, 10); capsule = CreateCapsule(NxVec3(-3,0,0), 2, 0.5, 10); pyramid = CreatePyramid(NxVec3(0,0,-3), NxVec3(0.75,1.5,0.75), 10); box->setLinearDamping(0.5); sphere->setLinearDamping(0.5); capsule->setLinearDamping(0.5); pyramid->setLinearDamping(0.5); AddUserDataToActors(gScene); // Initialize HUD InitializeHUD(); // Get the current time getElapsedTime(); // Start the first frame of the simulation if (gScene) StartPhysics(); }
void NovodexPhysicSystem::setStaticFriction( float _value ) { NxMaterial * defaultMaterial = m_scene->getMaterialFromIndex(0); defaultMaterial->setStaticFriction(_value); }
int main(int argc, char **argv) { //init and PVD bool initialized = false; NxPhysicsSDK *physicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION); if (!physicsSDK) return 0; else physicsSDK->getFoundationSDK().getRemoteDebugger()->connect("localhost", 5425); physicsSDK->setParameter(NX_CONTINUOUS_CD, true); initialized = true; //create a scene bool sceneInit = false; NxSceneDesc sceneDesc; sceneDesc.gravity.set(0, -9.81f, 0); gScene = physicsSDK->createScene(sceneDesc); if (gScene != NULL) sceneInit = true; //create a plane { NxActorDesc actorDesc; NxPlaneShapeDesc planeDesc; //planeDesc.normal = NxVec3(0, 0, 1); //planeDesc.d = -10.0f; actorDesc.shapes.pushBack(&planeDesc); gScene->createActor(actorDesc); } //create material NxMaterial *defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.3f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); //create a box { NxActorDesc actorDesc; NxBodyDesc bodyDesc; bodyDesc.angularDamping = 0.5; bodyDesc.linearVelocity = NxVec3(1, 0, 0); actorDesc.body = &bodyDesc; NxBoxShapeDesc boxDesc; boxDesc.dimensions = NxVec3(2.0f, 3.0f, 4.0f); actorDesc.shapes.pushBack(&boxDesc); actorDesc.density = 10.0f; actorDesc.globalPose.t = NxVec3(10.0f, 10.0f, 10.0f); gScene->createActor(actorDesc)->userData = NULL; } //create a cloth { // Create the objects in the scene NxActor* sphere1 = CreateSphere(NxVec3(-1, 0, -0.5), 1, 10); NxActor* box1 = CreateBox(NxVec3(1, 0, -1), NxVec3(1, 1, 1), 10); NxActor* box2 = CreateBox(NxVec3(0, 6.5, 0), NxVec3(5, 0.5, 0.5), 10); NxActor* box3 = CreateBox(NxVec3(0, 6.5, -7), NxVec3(5, 0.5, 0.5), 10); box2->setLinearDamping(5); box3->setLinearDamping(5); NxD6JointDesc d6Desc; d6Desc.actor[0] = NULL; d6Desc.actor[1] = box2; NxVec3 globalAnchor(0, 7, 0); d6Desc.localAnchor[0] = globalAnchor; box2->getGlobalPose().multiplyByInverseRT(globalAnchor, d6Desc.localAnchor[1]); box2->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); box3->getGlobalPose().multiplyByInverseRT(globalAnchor, d6Desc.localAnchor[1]); box3->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); d6Desc.localAxis[0] = NxVec3(1, 0, 0); d6Desc.localNormal[0] = NxVec3(0, 1, 0); d6Desc.localAxis[1] = NxVec3(1, 0, 0); d6Desc.localNormal[1] = NxVec3(0, 1, 0); d6Desc.twistMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.swing1Motion = NX_D6JOINT_MOTION_LOCKED; d6Desc.swing2Motion = NX_D6JOINT_MOTION_LOCKED; d6Desc.xMotion = NX_D6JOINT_MOTION_FREE; d6Desc.yMotion = NX_D6JOINT_MOTION_FREE; d6Desc.zMotion = NX_D6JOINT_MOTION_FREE; NxJoint* d6Joint = gScene->createJoint(d6Desc); NxClothDesc clothDesc; clothDesc.globalPose.t = NxVec3(4, 7, 0); clothDesc.thickness = 0.2; //clothDesc.density = 1; clothDesc.bendingStiffness = 0.5; clothDesc.stretchingStiffness = 1; //clothDesc.dampingCoefficient = 0.5; clothDesc.friction = 0.5; //clothDesc.collisionResponseCoefficient = 1; //clothDesc.attachmentResponseCoefficient = 1; //clothDesc.solverIterations = 5; //clothDesc.flags |= NX_CLF_STATIC; //clothDesc.flags |= NX_CLF_DISABLE_COLLISION; //clothDesc.flags |= NX_CLF_VISUALIZATION; //clothDesc.flags |= NX_CLF_GRAVITY; clothDesc.flags |= NX_CLF_BENDING; //clothDesc.flags |= NX_CLF_BENDING_ORTHO; clothDesc.flags |= NX_CLF_DAMPING; //clothDesc.flags |= NX_CLF_COMDAMPING; clothDesc.flags |= NX_CLF_COLLISION_TWOWAY; clothDesc.flags &= ~NX_CLF_HARDWARE; clothDesc.flags |= NX_CLF_FLUID_COLLISION; clothDesc.selfCollisionThickness = 10.0f; NxReal w = 8; NxReal h = 7; NxReal d = 0.05; NxClothMeshDesc meshDesc; bool mInitDone = false; int numX = (int)(w / d) + 1; int numY = (int)(h / d) + 1; meshDesc.numVertices = (numX + 1) * (numY + 1); meshDesc.numTriangles = numX*numY * 2; meshDesc.pointStrideBytes = sizeof(NxVec3); meshDesc.triangleStrideBytes = 3 * sizeof(NxU32); meshDesc.vertexMassStrideBytes = sizeof(NxReal); meshDesc.vertexFlagStrideBytes = sizeof(NxU32); meshDesc.points = (NxVec3*)malloc(sizeof(NxVec3)*meshDesc.numVertices); meshDesc.triangles = (NxU32*)malloc(sizeof(NxU32)*meshDesc.numTriangles * 3); meshDesc.vertexMasses = 0; meshDesc.vertexFlags = 0; meshDesc.flags = 0; int i, j; NxVec3 *p = (NxVec3*)meshDesc.points; for (i = 0; i <= numY; i++) { for (j = 0; j <= numX; j++) { p->set(-d*j, 0.0f, -d*i); p++; } } NxU32 *id = (NxU32*)meshDesc.triangles; for (i = 0; i < numY; i++) { for (j = 0; j < numX; j++) { NxU32 i0 = i * (numX + 1) + j; NxU32 i1 = i0 + 1; NxU32 i2 = i0 + (numX + 1); NxU32 i3 = i2 + 1; if ((j + i) % 2) { *id++ = i0; *id++ = i2; *id++ = i1; *id++ = i1; *id++ = i2; *id++ = i3; } else { *id++ = i0; *id++ = i2; *id++ = i3; *id++ = i0; *id++ = i3; *id++ = i1; } } } // if we want tearing we must tell the cooker // this way it will generate some space for particles that will be generated during tearing if (meshDesc.flags & NX_CLF_TEARABLE) meshDesc.flags |= NX_CLOTH_MESH_TEARABLE; //cooking static NxCookingInterface *gCooking = 0; gCooking = NxGetCookingLib(NX_PHYSICS_SDK_VERSION); gCooking->NxInitCooking(); gCooking->NxCookClothMesh(meshDesc, UserStream("e:\\cooked.bin", false)); //Meshdata Buffers NxMeshData mReceiveBuffers; // here we setup the buffers through which the SDK returns the dynamic cloth data // we reserve more memory for vertices than the initial mesh takes // because tearing creates new vertices // the SDK only tears cloth as long as there is room in these buffers NxU32 numVertices = meshDesc.numVertices; NxU32 numTriangles = meshDesc.numTriangles; NxU32 maxVertices = 2 * numVertices; mReceiveBuffers.verticesPosBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); mReceiveBuffers.verticesNormalBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); mReceiveBuffers.verticesPosByteStride = sizeof(NxVec3); mReceiveBuffers.verticesNormalByteStride = sizeof(NxVec3); mReceiveBuffers.maxVertices = maxVertices; mReceiveBuffers.numVerticesPtr = (NxU32*)malloc(sizeof(NxU32)); // the number of triangles is constant, even if the cloth is torn NxU32 maxIndices = 3 * numTriangles; mReceiveBuffers.indicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxIndices); mReceiveBuffers.indicesByteStride = sizeof(NxU32); mReceiveBuffers.maxIndices = maxIndices; mReceiveBuffers.numIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); // the parent index information would be needed if we used textured cloth NxU32 maxParentIndices = maxVertices; mReceiveBuffers.parentIndicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxParentIndices); mReceiveBuffers.parentIndicesByteStride = sizeof(NxU32); mReceiveBuffers.maxParentIndices = maxParentIndices; mReceiveBuffers.numParentIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); // init the buffers in case we want to draw the mesh // before the SDK as filled in the correct values *mReceiveBuffers.numVerticesPtr = 0; *mReceiveBuffers.numIndicesPtr = 0; clothDesc.clothMesh = physicsSDK->createClothMesh(UserStream("e:\\cooked.bin", true)); clothDesc.meshData = mReceiveBuffers; NxCloth *mCloth; mCloth = gScene->createCloth(clothDesc); mCloth->attachToShape(*box2->getShapes(), NX_CLOTH_ATTACHMENT_TWOWAY); mCloth->attachToShape(*box3->getShapes(), NX_CLOTH_ATTACHMENT_TWOWAY); } //create fluid 1 { //fluid = CreateFluid(NxVec3(0, 12, -3.5), 15, 0.1, gScene); } //create fluid 2 { //Create a set of initial particles ParticleSDK* initParticles = new ParticleSDK[max_particles]; unsigned initParticlesNum = 0; //Create particle filled sphere in buffer. NxVec3 fluidPos(0, 2, 0); NxVec3 offsetPos(0, 12, -3.5); float distance = 0.1f; //#ifdef __PPCGEKKO__ // unsigned sideNum = 12; //#else unsigned sideNum = 16; //#endif //Setup structure to pass initial particles. NxParticleData initParticleData; initParticlesNum = 0; initParticleData.numParticlesPtr = &initParticlesNum; initParticleData.bufferPos = &initParticles[0].position.x; initParticleData.bufferPosByteStride = sizeof(ParticleSDK); initParticleData.bufferVel = &initParticles[0].velocity.x; initParticleData.bufferVelByteStride = sizeof(ParticleSDK); CreateParticleSphere(initParticleData, max_particles, false, offsetPos, NxVec3(0, 0, 0), 0.0f, distance, sideNum); //Setup fluid descriptor NxFluidDesc fluidDesc; fluidDesc.maxParticles = max_particles; fluidDesc.kernelRadiusMultiplier = 2.0f; fluidDesc.restParticlesPerMeter = 10.0f; fluidDesc.motionLimitMultiplier = 3.0f; fluidDesc.packetSizeMultiplier = 8; fluidDesc.collisionDistanceMultiplier = 0.1; fluidDesc.stiffness = 50.0f; fluidDesc.viscosity = 40.0f; fluidDesc.restDensity = 1000.0f; fluidDesc.damping = 0.0f; fluidDesc.restitutionForStaticShapes = 0.0f; fluidDesc.dynamicFrictionForStaticShapes = 0.05f; fluidDesc.simulationMethod = NX_F_SPH; fluidDesc.flags &= ~NX_FF_HARDWARE; //Add initial particles to fluid creation. fluidDesc.initialParticleData = initParticleData; //Create user fluid. //- create NxFluid in NxScene //- setup the buffers to read from data from the SDK //- set NxFluid::userData field to MyFluid instance bool trackUserData = false; bool provideCollisionNormals = false; MyFluid* fluid = new MyFluid(gScene, fluidDesc, trackUserData, provideCollisionNormals, NxVec3(0.4f, 0.5f, 0.9f), 0.03f); assert(fluid); gMyFluids.pushBack(fluid); } //simulate for (int i = 0; i < 3000; i++) { gScene->simulate(1.0f / 60.f); gScene->flushStream(); //GetPhysicsResults gScene->fetchResults(NX_RIGID_BODY_FINISHED, true); // update fluid status if (i == 400) { MyFluid* fluid = gMyFluids[0]; const ParticleSDK* particles = fluid->getParticles(); unsigned particlesNum = fluid->getParticlesNum(); if (!gUpdates) { gUpdates = new ParticleUpdateSDK[max_particles]; } for (unsigned i = 0; i < particlesNum; i++) { ParticleUpdateSDK& update = gUpdates[i]; NxVec3& force = update.force; force.set(0, 0, 0); NxU32& flags = update.flags; if (i >= particlesNum/2) { flags = 0; flags |= NX_FP_DELETE; } else { flags = 0; } } //在这里更改粒子的属性 NxParticleUpdateData updateData; updateData.bufferFlag = &gUpdates[0].flags; updateData.bufferFlagByteStride = sizeof(ParticleUpdateSDK); fluid->getNxFluid()->updateParticles(updateData); } } //release if (physicsSDK != NULL) { if (gScene != NULL) physicsSDK->releaseScene(*gScene); gScene = NULL; NxReleasePhysicsSDK(physicsSDK); physicsSDK = NULL; } return 1; }