diff --git a/Jusin154_Team3D/CleanUp.bat b/Jusin154_Team3D/CleanUp.bat index 92f8c1942..9e7ad2f9e 100644 --- a/Jusin154_Team3D/CleanUp.bat +++ b/Jusin154_Team3D/CleanUp.bat @@ -25,3 +25,6 @@ xcopy /y .\Engine\ThirdPartyLib\DirectXTK\DirectXTK.pdb .\Engine\Default\x xcopy /y .\Engine\ThirdPartyLib\FX11\Effects11d.pdb .\Engine\Default\x64\Debug\ xcopy /y .\Engine\ThirdPartyLib\FX11\Effects11.pdb .\Engine\Default\x64\Release\ + +xcopy /y .\Engine\ThirdPartyLib\PhysX\debug\*.pdb .\Engine\Default\x64\Debug\ +xcopy /y .\Engine\ThirdPartyLib\PhysX\Release\*.pdb .\Engine\Default\x64\Release\ diff --git a/Jusin154_Team3D/Editor/Default/Editor.vcxproj b/Jusin154_Team3D/Editor/Default/Editor.vcxproj index 0555a036c..7baf0829a 100644 --- a/Jusin154_Team3D/Editor/Default/Editor.vcxproj +++ b/Jusin154_Team3D/Editor/Default/Editor.vcxproj @@ -158,6 +158,7 @@ + @@ -200,6 +201,7 @@ + diff --git a/Jusin154_Team3D/Editor/Default/Editor.vcxproj.filters b/Jusin154_Team3D/Editor/Default/Editor.vcxproj.filters index 604444586..c4980c372 100644 --- a/Jusin154_Team3D/Editor/Default/Editor.vcxproj.filters +++ b/Jusin154_Team3D/Editor/Default/Editor.vcxproj.filters @@ -142,6 +142,9 @@ {584466e9-fe1a-4a7d-a4ba-54d62ee1a7c1} + + {943a760b-2861-45b7-87b8-462e1309c172} + @@ -264,6 +267,9 @@ 02.GameObjects\Env\Manger + + 01.Level\60.PhysXLab + @@ -379,6 +385,9 @@ 02.GameObjects\Env\Manger + + 01.Level\60.PhysXLab + diff --git a/Jusin154_Team3D/Editor/Private/Level_PhysXLab.cpp b/Jusin154_Team3D/Editor/Private/Level_PhysXLab.cpp new file mode 100644 index 000000000..a4f23480e --- /dev/null +++ b/Jusin154_Team3D/Editor/Private/Level_PhysXLab.cpp @@ -0,0 +1,2 @@ +#include "pch.h" +#include "Level_PhysXLab.h" \ No newline at end of file diff --git a/Jusin154_Team3D/Editor/Public/Level_PhysXLab.h b/Jusin154_Team3D/Editor/Public/Level_PhysXLab.h new file mode 100644 index 000000000..f01c7977b --- /dev/null +++ b/Jusin154_Team3D/Editor/Public/Level_PhysXLab.h @@ -0,0 +1,5 @@ +#pragma once +class CLevel_PhysXLab +{ +}; + diff --git a/Jusin154_Team3D/Engine/Default/Engine.vcxproj b/Jusin154_Team3D/Engine/Default/Engine.vcxproj index 8e42372f1..92ae827df 100644 --- a/Jusin154_Team3D/Engine/Default/Engine.vcxproj +++ b/Jusin154_Team3D/Engine/Default/Engine.vcxproj @@ -123,8 +123,8 @@ Windows true false - ../ThirdPartyLib/fMod/;../ThirdPartyLib/DirectXTK/;../ThirdPartyLib/FX11/;../ThirdPartyLib/Assimp/;%(AdditionalLibraryDirectories) - d3d11.lib;fmod_vc.lib;dinput8.lib;DirectXTKd.lib;Effects11d.lib;assimp-vc145-mtd.lib;%(AdditionalDependencies) + ../ThirdPartyLib/fMod/;../ThirdPartyLib/DirectXTK/;../ThirdPartyLib/FX11/;../ThirdPartyLib/Assimp/;../ThirdPartyLib/PhysX/$(Configuration)/;%(AdditionalLibraryDirectories) + d3d11.lib;fmod_vc.lib;dinput8.lib;LowLevel_static_64.lib;LowLevelAABB_static_64.lib;LowLevelDynamics_static_64.lib;PhysX_64.lib;PhysXCommon_64.lib;PhysXCooking_64.lib;PhysXExtensions_static_64.lib;PhysXFoundation_64.lib;PhysXPvdSDK_static_64.lib;PhysXTask_static_64.lib;SceneQuery_static_64.lib;SimulationController_static_64.lib;PhysXCharacterKinematic_static_64.lib;DirectXTKd.lib;Effects11d.lib;assimp-vc145-mtd.lib;%(AdditionalDependencies) @@ -146,8 +146,8 @@ Windows true false - ../ThirdPartyLib/fMod/;../ThirdPartyLib/DirectXTK/;../ThirdPartyLib/FX11/;../ThirdPartyLib/Assimp/;%(AdditionalLibraryDirectories) - d3d11.lib;fmod_vc.lib;dinput8.lib;DirectXTK.lib;Effects11.lib;assimp-vc145-mt.lib;%(AdditionalDependencies) + ../ThirdPartyLib/fMod/;../ThirdPartyLib/DirectXTK/;../ThirdPartyLib/FX11/;../ThirdPartyLib/Assimp/;../ThirdPartyLib/PhysX/$(Configuration)/;%(AdditionalLibraryDirectories) + d3d11.lib;fmod_vc.lib;dinput8.lib;LowLevel_static_64.lib;LowLevelAABB_static_64.lib;LowLevelDynamics_static_64.lib;PhysX_64.lib;PhysXCommon_64.lib;PhysXCooking_64.lib;PhysXExtensions_static_64.lib;PhysXFoundation_64.lib;PhysXPvdSDK_static_64.lib;PhysXTask_static_64.lib;SceneQuery_static_64.lib;SimulationController_static_64.lib;PhysXCharacterKinematic_static_64.lib;DirectXTK.lib;Effects11.lib;assimp-vc145-mt.lib;%(AdditionalDependencies) @@ -172,6 +172,10 @@ + + true + true + @@ -248,11 +252,13 @@ Create + + @@ -378,6 +384,10 @@ + + true + true + @@ -453,12 +463,14 @@ + + diff --git a/Jusin154_Team3D/Engine/Default/Engine.vcxproj.filters b/Jusin154_Team3D/Engine/Default/Engine.vcxproj.filters index f8a4515cc..3b97a27f6 100644 --- a/Jusin154_Team3D/Engine/Default/Engine.vcxproj.filters +++ b/Jusin154_Team3D/Engine/Default/Engine.vcxproj.filters @@ -229,6 +229,18 @@ {a60a7ba5-a937-41d7-baac-db67f86f3ba1} + + {5948985e-f67e-4627-aca4-09b8e9edc359} + + + {5e6a85cd-455a-4161-83c8-ba5f4ce2ba41} + + + {5c89d610-7e57-40a5-bc65-04e5fa25df89} + + + {b20c0397-6254-4350-bc83-ee695f9fd012} + @@ -408,6 +420,12 @@ 03.Management\10.Collider_Manager + + 03.Management\21.PhysX_Manager + + + 02.Element\02.Component\07.RigidBody + 02.Element\02.Component\50.UI @@ -426,6 +444,9 @@ 02.Element\02.Component\02.VIBuffer\Terrain + + 03.Management\21.PhysX_Manager\CCT + @@ -989,6 +1010,15 @@ 02.Element\02.Component\02.VIBuffer\Terrain + + 03.Management\21.PhysX_Manager + + + 02.Element\02.Component\07.RigidBody + + + 03.Management\21.PhysX_Manager\CCT + diff --git a/Jusin154_Team3D/Engine/Private/Character_Controller.cpp b/Jusin154_Team3D/Engine/Private/Character_Controller.cpp new file mode 100644 index 000000000..769c2cd50 --- /dev/null +++ b/Jusin154_Team3D/Engine/Private/Character_Controller.cpp @@ -0,0 +1,38 @@ +#include "pch.h" +#include "Character_Controller.h" +#include "GameInstance.h" + +CCharacter_Controller::CCharacter_Controller(ID3D11Device* pDevice, ID3D11DeviceContext* pContext) : + m_pDevice(pDevice), + m_pContext(pContext), + m_pGameInstance(CGameInstance::GetInstance()) +{ + SAFE_ADDREF(m_pDevice); + SAFE_ADDREF(m_pContext); + SAFE_ADDREF(m_pGameInstance); +} + +CCharacter_Controller* CCharacter_Controller::Create(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, PSX::PxScene* pScene) +{ + CCharacter_Controller* pInstance = new CCharacter_Controller(pDevice, pContext); + if (FAILED(pInstance->Initialize(pScene))) { + SAFE_RELEASE(pInstance); + assert(false); + } + return pInstance; +} + +HRESULT CCharacter_Controller::Initialize(PSX::PxScene* pScene) +{ + m_pScene = pScene; + return S_OK; +} + +void CCharacter_Controller::Free() +{ + __super::Free(); + + SAFE_RELEASE(m_pDevice); + SAFE_RELEASE(m_pContext); + SAFE_RELEASE(m_pGameInstance); +} \ No newline at end of file diff --git a/Jusin154_Team3D/Engine/Private/GameInstance.cpp b/Jusin154_Team3D/Engine/Private/GameInstance.cpp index 705911e59..806c47193 100644 --- a/Jusin154_Team3D/Engine/Private/GameInstance.cpp +++ b/Jusin154_Team3D/Engine/Private/GameInstance.cpp @@ -15,6 +15,7 @@ #include "Mouse_Manager.h" #include "Collider_Manager.h" #include "Picking.h" +#include "PhysX_Manager.h" IMPLEMENT_SINGLETON(CGameInstance) @@ -89,6 +90,10 @@ HRESULT CGameInstance::Initialize_Engine(const ENGINE_DESC& EngineDesc, ID3D11De if (nullptr == m_pCollider_Manager) { return E_FAIL; } + m_pPhysX_Manager = CPhysX_Manager::Create(*ppDevice, *ppContext); + if (nullptr == m_pPhysX_Manager) { + return E_FAIL; + } return S_OK; } @@ -112,6 +117,7 @@ void CGameInstance::Update_Engine(_float fTimeDelta) m_pLevel_Manager->Update(fTimeDelta); m_pObject_Manager->Clear_DeadObj(); + m_pPhysX_Manager->Update(fTimeDelta); //m_pObstacle_Manager->Refresh_Region(); } @@ -519,6 +525,30 @@ SaveModel* CGameInstance::Load_SaveModel(const _char* filePath) auto iter = m_sModelMap.find(filePath); return &iter->second; } + +#pragma region PhysX_Manager +PSX::PxMaterial* CGameInstance::Get_Material(_float3& vMatInfo) +{ + return m_pPhysX_Manager->Get_Material(vMatInfo); +} +HRESULT CGameInstance::Create_TriangleMesh(const _wstring& wstrMeshKey, CMesh* pMesh) +{ + return m_pPhysX_Manager->Create_TriangleMesh(wstrMeshKey, pMesh); +} +PSX::PxShape* CGameInstance::Create_Shape(ACTOR eType, _float3& vhalfGeometryInfo, PSX::PxMaterial& pxMaterial, _bool bExclusive, PSX::PxShapeFlags ePxShapeFlag) +{ + return m_pPhysX_Manager->Create_Shape(eType, vhalfGeometryInfo, pxMaterial, bExclusive, ePxShapeFlag); +} +const PSX::PxRigidDynamic* CGameInstance::Add_DynamicActor(CRigidBody& RigidBody) +{ + return m_pPhysX_Manager->Add_DynamicActor(RigidBody); +} +const PSX::PxRigidStatic* CGameInstance::Add_StaticActor(CRigidBody& RigidBody) +{ + return m_pPhysX_Manager->Add_StaticActor(RigidBody); +} +#pragma endregion + bool CGameInstance::Key_Pressing(int _iKey) { if (false == (GUI::IsWindowFocused(ImGuiFocusedFlags_AnyWindow))) { @@ -626,6 +656,7 @@ void CGameInstance::Release_Engine() { DestroyInstance(); + SAFE_RELEASE(m_pPhysX_Manager); SAFE_RELEASE(m_pPicking); SAFE_RELEASE(m_pCollider_Manager); SAFE_RELEASE(m_pShadow); diff --git a/Jusin154_Team3D/Engine/Private/Mesh.cpp b/Jusin154_Team3D/Engine/Private/Mesh.cpp index c4d0320ab..e3b95e636 100644 --- a/Jusin154_Team3D/Engine/Private/Mesh.cpp +++ b/Jusin154_Team3D/Engine/Private/Mesh.cpp @@ -604,6 +604,29 @@ HRESULT CMesh::SaveAsBinary(HANDLE hFile, DWORD& dwByte) return S_OK; } +PSX::PxTriangleMesh* CMesh::ConvertToPxMesh(const PSX::PxCookingParams* pParam) +{ + PSX::PxTriangleMeshDesc Desc; + vector Vertices; + vector Triangles; + { + Desc.points.count = m_iNumVertices; + Desc.points.stride = sizeof(PSX::PxVec3); + Vertices.resize(m_iNumVertices); + memcpy_s(Vertices.data(), sizeof(PSX::PxVec3) * m_iNumVertices, m_pVertexPositions, sizeof(_float3) * m_iNumVertices); + Desc.points.data = Vertices.data(); + } + { + Desc.triangles.count = m_iNumIndices / 3; + Desc.triangles.stride = sizeof(PSX::PxU32) * 3; + Triangles.resize(m_iNumIndices); + memcpy_s(Triangles.data(), sizeof(PSX::PxU32) * m_iNumIndices, m_pIndices, sizeof(PSX::PxU32) * m_iNumIndices); + Desc.triangles.data = Triangles.data(); + } + PSX::PxTriangleMesh* pTriangleMesh = PxCreateTriangleMesh(*pParam, Desc); + return pTriangleMesh; +} + HRESULT CMesh::Ready_VertexBuffer_For_NonAnim(const aiMesh* pAIMesh, _fmatrix PreTransformMatrix) { m_iVertexStride = sizeof(VTXMESH); diff --git a/Jusin154_Team3D/Engine/Private/PhysX_Manager.cpp b/Jusin154_Team3D/Engine/Private/PhysX_Manager.cpp new file mode 100644 index 000000000..f27b72131 --- /dev/null +++ b/Jusin154_Team3D/Engine/Private/PhysX_Manager.cpp @@ -0,0 +1,377 @@ +#include "pch.h" +#include "PhysX_Manager.h" +#include "GameObject.h" +#include "GameInstance.h" +#include "RigidBody.h" +#include "Mesh.h" + +static PSX::PxTransform XMWorldToPx(const _matrix& WorldMatrix) +{ + _vector vPos, vRotq, vScale; + XMMatrixDecompose(&vScale, &vRotq, &vPos, WorldMatrix); + + PSX::PxTransform out; + XMStoreFloat3((_float3*)&out.p, WorldMatrix.r[3]); + XMStoreFloat4((_float4*)&out.q, vRotq); + + return out; +} + +CPhysX_Manager::CPhysX_Manager(ID3D11Device* pDevice, ID3D11DeviceContext* pContext) : + m_pDevice(pDevice), + m_pContext(pContext), + m_pGameInstance(CGameInstance::GetInstance()) +{ + SAFE_ADDREF(m_pDevice); + SAFE_ADDREF(m_pContext); + SAFE_ADDREF(m_pGameInstance); +} + +const PSX::PxRigidDynamic* CPhysX_Manager::Add_DynamicActor(CRigidBody& RigidBody) +{ + _matrix WorldMatrix = RigidBody.Get_PxTransformPtr()->Get_XMWorldMatrix(); + + PSX::PxTransform pxWorldMatrix = XMWorldToPx(WorldMatrix); + + // PxRigidDynamic 씬의 동적 바디 인터페이스 + PSX::PxRigidDynamic* pActorDynamic = m_pPhysics->createRigidDynamic(pxWorldMatrix); + pActorDynamic->userData = &RigidBody; + pActorDynamic->attachShape(*RigidBody.Get_ShapePtr()); + if (RigidBody.Is_Kinematic()) { + pActorDynamic->setRigidBodyFlag(PSX::PxRigidBodyFlag::eKINEMATIC, true); + } + else { + PSX::PxRigidBodyExt::updateMassAndInertia(*pActorDynamic, (PSX::PxReal)RigidBody.Get_Density()); + } + + + m_RigidBodys.emplace_back(&RigidBody, pActorDynamic); + m_pScene->addActor(*pActorDynamic); + + return pActorDynamic; +} + +const PSX::PxRigidStatic* CPhysX_Manager::Add_StaticActor(CRigidBody& RigidBody) +{ + _matrix WorldMatrix = RigidBody.Get_PxTransformPtr()->Get_XMWorldMatrix(); + + PSX::PxTransform pxWorldMatrix = XMWorldToPx(WorldMatrix); + + // PxRigidStatic 씬의 정적 바디 인터페이스 + const PSX::PxTriangleMesh* pPxMesh = { nullptr }; + { + auto iter = m_TriangleMeshes.find(RigidBody.Get_PxMeshKey()); + if (m_TriangleMeshes.end() == iter) { + assert(false); + return nullptr; + } + pPxMesh = iter->second; + } + const PSX::PxTriangleMeshGeometry* pPxMeshGeometry = { nullptr }; + { + auto iter = m_TriangleMeshGeometry.find(RigidBody.Get_PxMeshKey()); + if (m_TriangleMeshGeometry.end() == iter) { + assert(false); + return nullptr; + } + pPxMeshGeometry = iter->second; + } + + + PSX::PxRigidStatic* pActor = m_pPhysics->createRigidStatic(pxWorldMatrix); pPxMeshGeometry; + PSX::PxShape* pShape = PSX::PxRigidActorExt::createExclusiveShape(*pActor, *pPxMeshGeometry, *RigidBody.Get_PxMaterial()); + + pShape->setFlag(PSX::PxShapeFlag::eSCENE_QUERY_SHAPE, true); + pShape->setFlag(PSX::PxShapeFlag::eSIMULATION_SHAPE, true); + + pActor->attachShape(*pShape); + + return pActor; +} + +PSX::PxMaterial* CPhysX_Manager::Get_Material(_float3& vMatInfo) +{ + PSX::PxMaterial* pPxMaterial = m_pPhysics->createMaterial(vMatInfo.x, vMatInfo.y, vMatInfo.z); + return pPxMaterial; +} + +PSX::PxShape* CPhysX_Manager::Create_Shape(ACTOR eType, _float3& vhalfGeometryInfo, PSX::PxMaterial& pxMaterial, _bool bExclusive, PSX::PxShapeFlags ePxShapeFlag) +{ + PSX::PxShape* pShape = { nullptr }; + switch (eType) + { + case Engine::ACTOR::BOX: + pShape = m_pPhysics->createShape(PSX::PxBoxGeometry(vhalfGeometryInfo.x, vhalfGeometryInfo.y, vhalfGeometryInfo.z), pxMaterial, + bExclusive, ePxShapeFlag); + break; + case Engine::ACTOR::CAPSULE: + pShape = m_pPhysics->createShape(PSX::PxCapsuleGeometry(vhalfGeometryInfo.x, vhalfGeometryInfo.y), pxMaterial, + bExclusive, ePxShapeFlag); + break; + case Engine::ACTOR::SPHERE: + pShape = m_pPhysics->createShape(PSX::PxSphereGeometry(vhalfGeometryInfo.x), pxMaterial, + bExclusive, ePxShapeFlag); + break; + default: + break; + } + return pShape; +} + +HRESULT CPhysX_Manager::Create_TriangleMesh(const _wstring& wstrMeshKey, CMesh* pMesh) +{ + + PSX::PxTriangleMesh* pTriangleMesh = pMesh->ConvertToPxMesh(m_pCookingParam); + if (nullptr != pTriangleMesh) { + m_TriangleMeshes.emplace(wstrMeshKey, pTriangleMesh); + + PSX::PxTriangleMeshGeometry* pGeometry = new PSX::PxTriangleMeshGeometry(pTriangleMesh); + pGeometry->meshFlags |= PSX::PxMeshGeometryFlag::eDOUBLE_SIDED; + m_TriangleMeshGeometry.emplace(wstrMeshKey, pGeometry); + return S_OK; + } + return E_FAIL; +} + +PSX::PxTriangleMesh* CPhysX_Manager::Find_TriangleMesh(const _wstring& wstrFilePath) +{ + map<_wstring, PSX::PxTriangleMesh*>::iterator iter = m_TriangleMeshes.find(wstrFilePath); + if (iter != m_TriangleMeshes.end()) { + return iter->second; + } + return nullptr; +} + +void CPhysX_Manager::Update_Kinematic() +{ + for (auto& pairBody : m_RigidBodys) { + PSX::PxRigidDynamic* pActor = pairBody.second->is(); + if (nullptr == pActor) { + continue; + } + + if (pActor->getRigidBodyFlags() & PSX::PxRigidBodyFlag::eKINEMATIC) + { + CRigidBody* pBody = pairBody.first; + const CTransform* pTransform = pBody->Get_PxTransformPtr(); + + pActor->setKinematicTarget(XMWorldToPx(pTransform->Get_XMWorldMatrix())); + } + } +} + +void CPhysX_Manager::Update(_float fTimeDelta) +{ + if (nullptr == m_pScene) { + return; + } + { // Prev + Update_Kinematic(); + } + { // Simulate + m_pScene->simulate((PSX::PxReal)fTimeDelta); + _bool bResult = m_pScene->fetchResults(true); + } + { // Post + Update_Dynamic(); + } +} + +void CPhysX_Manager::Update_Dynamic() +{ + PSX::PxU32 iNumActiveActor = {}; + PSX::PxActor** ppActiveActors = m_pScene->getActiveActors(iNumActiveActor); + + for (PSX::PxU32 i = 0; i < iNumActiveActor; ++i) { + PSX::PxRigidDynamic* pActorDynamic = ppActiveActors[i]->is(); + + if (nullptr != pActorDynamic) { + CTransform* pTransform = ((CRigidBody*)ppActiveActors[i]->userData)->Get_PxTransformPtr(); + + PSX::PxTransform pPrevPxTransform; + PSX::PxTransform pPxTransform = pActorDynamic->getGlobalPose(); + _float3 vOriginalScale = pTransform->Get_Scale(); + _matrix WorldMatrix = {}; + + WorldMatrix = XMMatrixAffineTransformation(XMLoadFloat3(&vOriginalScale), XMVectorZero(), XMLoadFloat4((_float4*)&pPxTransform.q), XMLoadFloat3((_float3*)&pPxTransform.p)); + pTransform->Set_WorldMatrix(WorldMatrix); + + } + } +} + +void CPhysX_Manager::ClearScene() +{ + for (auto& pObject : m_RigidBodys) { + pObject.second->release(); + } m_RigidBodys.clear(); +} + +PSX::PxController* CPhysX_Manager::Add_CapsuleController(PSX::PxCapsuleControllerDesc& Desc) +{ + PSX::PxController* pController = { nullptr }; + + pController = m_pCCTManager->createController(Desc); + return pController; +} + +PSX::PxController* CPhysX_Manager::Add_BoxController(PSX::PxBoxControllerDesc& Desc) +{ + PSX::PxController* pController = { nullptr }; + + pController = m_pCCTManager->createController(Desc); + return pController; +} + +PSX::PxController* CPhysX_Manager::Get_Controller(_uint iControllerIndex) +{ + return nullptr; +} + +void CPhysX_Manager::ReleaseController(_uint iControllerIndex) +{ + if (iControllerIndex >= Get_NumCurrentController()) { + assert(false); + return; + } + + m_pCCTManager->getController((PSX::PxU32)iControllerIndex)->release(); +} + +_uint CPhysX_Manager::Get_NumCurrentController() +{ + return (_uint)m_pCCTManager->getNbControllers(); +} + +HRESULT CPhysX_Manager::PurgeAllController() +{ + m_pCCTManager->purgeControllers(); + return S_OK; +} + + +HRESULT CPhysX_Manager::Initialize() +{ + + m_pFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, m_AllocatorCallBack, m_ErrorCallBack); + if (nullptr == m_pFoundation) { + assert(false); + return E_FAIL; + } + + if (FAILED(Connect_DebugServer())) { + assert(false); + } + + + { // 씬 세팅 + m_ToleranceScale.length = 1.f; + m_ToleranceScale.speed = GRAVITY; + + m_pPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *m_pFoundation, m_ToleranceScale, true, m_pPvd); + + m_pCookingParam = new PSX::PxCookingParams(m_pPhysics->getTolerancesScale()); + PSX::PxSceneDesc sceneDesc = { m_pPhysics->getTolerancesScale() }; + + sceneDesc.gravity = PSX::PxVec3(0.f, GRAVITY, 0.f); + + sceneDesc.cpuDispatcher = m_pDispatcher = PSX::PxDefaultCpuDispatcherCreate(2/*cpu 코어 갯수*/); + + sceneDesc.filterShader = PSX::PxDefaultSimulationFilterShader; + + sceneDesc.flags = PSX::PxSceneFlag::eENABLE_PCM | PSX::PxSceneFlag::eENABLE_ACTIVE_ACTORS | PSX::PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS; + if (false == sceneDesc.isValid()) { + assert(false); + return E_FAIL; + } + m_pScene = m_pPhysics->createScene(sceneDesc); + m_pCCTManager = PxCreateControllerManager(*m_pScene); + + } + + // 디버그서버의 클라 세팅 + PSX::PxPvdSceneClient* pPvdClient = m_pScene->getScenePvdClient(); + if (nullptr != pPvdClient) { + pPvdClient->setScenePvdFlag(PSX::PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); + pPvdClient->setScenePvdFlag(PSX::PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); + pPvdClient->setScenePvdFlag(PSX::PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); + } + + return S_OK; +} + +HRESULT CPhysX_Manager::Connect_DebugServer() +{ + // 네트워크 디버거 전송객체 생성 + PSX::PxPvdTransport* pTransport = PSX::PxDefaultPvdSocketTransportCreate("127.0.0.1", 5425, 10); + if (nullptr == pTransport) { + assert(false); + return E_FAIL; + } + + m_pPvd = PSX::PxCreatePvd(*m_pFoundation); + if (nullptr == m_pPvd) { + pTransport->release(); + assert(false); + return E_FAIL; + } + m_pPvd->connect(*pTransport, PSX::PxPvdInstrumentationFlag::eALL); + pTransport->release(); + return S_OK; +} + +CPhysX_Manager* CPhysX_Manager::Create(ID3D11Device* pDevice, ID3D11DeviceContext* pContext) +{ + CPhysX_Manager* pInstance = new CPhysX_Manager(pDevice, pContext); + if (FAILED(pInstance->Initialize())) { + SAFE_RELEASE(pInstance); + assert(false); + } + return pInstance; +} + +void CPhysX_Manager::Free() +{ + for (auto& pObjects : m_RigidBodys) { + pObjects.second->release(); + } m_RigidBodys.clear(); + + for (auto& pMeshes : m_TriangleMeshes) { + pMeshes.second->release(); + } m_TriangleMeshes.clear(); + + for (auto& pGeometry : m_TriangleMeshGeometry) { + Safe_Delete(pGeometry.second); + } m_TriangleMeshGeometry.clear(); + + if (nullptr != m_pCookingParam) { + Safe_Delete(m_pCookingParam); + } + + if (nullptr != m_pScene) { + m_pScene->release(); m_pScene = nullptr; + } + + if (nullptr != m_pDispatcher) { + m_pDispatcher->release(); m_pDispatcher = nullptr; + } + + if (nullptr != m_pPhysics) { + m_pPhysics->release(); m_pPhysics = nullptr; + } + + if (nullptr != m_pPvd) { + m_pPvd->release(); m_pPvd = nullptr; + } + + if (nullptr != m_pFoundation) { + m_pFoundation->release(); m_pFoundation = nullptr; + } + + + __super::Free(); + + SAFE_RELEASE(m_pDevice); + SAFE_RELEASE(m_pContext); + SAFE_RELEASE(m_pGameInstance); +} diff --git a/Jusin154_Team3D/Engine/Private/RigidBody.cpp b/Jusin154_Team3D/Engine/Private/RigidBody.cpp new file mode 100644 index 000000000..36c12bb51 --- /dev/null +++ b/Jusin154_Team3D/Engine/Private/RigidBody.cpp @@ -0,0 +1,141 @@ +#include "pch.h" +#include "RigidBody.h" +#include "GameInstance.h" +#include "GameObject.h" + +CRigidBody::CRigidBody(ID3D11Device* pDevice, ID3D11DeviceContext* pContext): + CComponent(pDevice, pContext) +{ + SAFE_ADDREF(pDevice); + SAFE_ADDREF(pContext); +} + +CRigidBody::CRigidBody(const CRigidBody& rhs): + CComponent(rhs), + m_pMaterial(rhs.m_pMaterial), + m_eActorType(rhs.m_eActorType), + m_vhalfGeometryInfo(rhs.m_vhalfGeometryInfo), + m_pShape(rhs.m_pShape), + m_pMeshKey(rhs.m_pMeshKey) +{ + m_pMaterial->acquireReference(); + m_pShape->acquireReference(); +} + +HRESULT CRigidBody::Initialize_Prototype(RIGIDBODY_PROTOTYPEDESC& Desc) +{ + m_eActorType = Desc.eType; + switch (m_eActorType) + { + case ACTOR::BOX: + case ACTOR::CAPSULE: + case ACTOR::SPHERE: + m_pMaterial = m_pGameInstance->Get_Material(Desc.tRigidDynamicDesc.vMatInfo); + m_vhalfGeometryInfo = Desc.tRigidDynamicDesc.vhalfGeometryInfo; + m_pShape = m_pGameInstance->Create_Shape(m_eActorType, m_vhalfGeometryInfo, *m_pMaterial, Desc.tRigidDynamicDesc.bExclusive, Desc.tRigidDynamicDesc.ePxShapeFlag); + if (nullptr == m_pShape) { + assert(false); + m_pMaterial->release(); + m_pMaterial = nullptr; + return E_FAIL; + } + break; + case ACTOR::PLANE: + break; + case ACTOR::TRIANGLEMESH: + { + m_pGameInstance->Create_TriangleMesh(Desc.tRigidStaticDesc.pMeshKey, Desc.tRigidStaticDesc.pMesh); + m_pMaterial = m_pGameInstance->Get_Material(Desc.tRigidDynamicDesc.vMatInfo); + m_pMeshKey = Desc.tRigidStaticDesc.pMeshKey; + } + break; + case ACTOR::HEIGHTFIELD: + break; + default: + break; + } + + return S_OK; +} + +HRESULT CRigidBody::Initialize(void* pArg) +{ + RIGIDBODY_DESC* pDesc = (RIGIDBODY_DESC*)pArg; + + if (FAILED(__super::Initialize(pArg))) { + return E_FAIL; + } + + m_pTransform = m_pOwner->Get_Component(); + SAFE_ADDREF(m_pTransform); + + switch (m_eActorType) + { + case Engine::ACTOR::BOX: + case Engine::ACTOR::CAPSULE: + case Engine::ACTOR::SPHERE: + m_fDensity = pDesc->tRigidDynamicDesc.fDensity; + m_bKenematic = pDesc->tRigidDynamicDesc.bIsKinematic; + m_pRigidBody = m_pGameInstance->Add_DynamicActor(*this); + break; + case Engine::ACTOR::PLANE: + break; + case Engine::ACTOR::TRIANGLEMESH: + m_pRigidBody = m_pGameInstance->Add_StaticActor(*this); + break; + case Engine::ACTOR::HEIGHTFIELD: + break; + case Engine::ACTOR::END: + break; + default: + break; + } + + + + return S_OK; +} + +CRigidBody* CRigidBody::Create(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, RIGIDBODY_PROTOTYPEDESC& Desc) +{ + CRigidBody* pInstance = new CRigidBody(pDevice, pContext); + + if (FAILED(pInstance->Initialize_Prototype(Desc))) { + MSG_BOX("CRigidBody Prototype Created Failed"); + SAFE_RELEASE(pInstance); + } + + return pInstance; +} + +CComponent* CRigidBody::Clone(void* pArg, CGameObject* pOwner) +{ + CRigidBody* pInstance = new CRigidBody(*this); + pInstance->m_pOwner = pOwner; + if (FAILED(pInstance->Initialize(pArg))) { + MSG_BOX("CRigidBody Prototype Created Failed"); + SAFE_RELEASE(pInstance); + } + + return pInstance; +} + +void CRigidBody::Free() +{ + __super::Free(); + + if (nullptr != m_pMaterial) { + m_pMaterial->release(); + m_pMaterial = nullptr; + } + if (nullptr != m_pShape) { + m_pShape->release(); + m_pShape = nullptr; + } + + SAFE_RELEASE(m_pTransform); +} + +void CRigidBody::Describe_Entity() +{ +} diff --git a/Jusin154_Team3D/Engine/Public/Assimp/.editorconfig b/Jusin154_Team3D/Engine/Public/Assimp/.editorconfig index 9ea66423a..f3119b937 100644 --- a/Jusin154_Team3D/Engine/Public/Assimp/.editorconfig +++ b/Jusin154_Team3D/Engine/Public/Assimp/.editorconfig @@ -1,4 +1,4 @@ -# See for details +# ASSIMP [*.{h,hpp,inl}] end_of_line = lf diff --git a/Jusin154_Team3D/Engine/Public/Character_Controller.h b/Jusin154_Team3D/Engine/Public/Character_Controller.h new file mode 100644 index 000000000..b83c36a0f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/Character_Controller.h @@ -0,0 +1,27 @@ +#pragma once +#include "Base.h" +NS_BEGIN(Engine) + +class CCharacter_Controller final : public CBase +{ + +private: + CCharacter_Controller(ID3D11Device* pDevice, ID3D11DeviceContext* pContext); + virtual ~CCharacter_Controller() = default; + +private: + class CGameInstance* m_pGameInstance = { nullptr }; + ID3D11Device* m_pDevice = { nullptr }; + ID3D11DeviceContext* m_pContext = { nullptr }; + + PSX::PxScene* m_pScene = { nullptr }; +private: + HRESULT Initialize(PSX::PxScene* pScene); + + +public: + static CCharacter_Controller* Create(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, PSX::PxScene* pScene); + virtual void Free() override; +}; + +NS_END \ No newline at end of file diff --git a/Jusin154_Team3D/Engine/Public/Engine_Enum.h b/Jusin154_Team3D/Engine/Public/Engine_Enum.h index 291953d21..ba6ab196a 100644 --- a/Jusin154_Team3D/Engine/Public/Engine_Enum.h +++ b/Jusin154_Team3D/Engine/Public/Engine_Enum.h @@ -7,6 +7,7 @@ enum class LIGHT { DIRECTIONAL, POINT, SPOT, END }; enum class COLLIDER { AABB, OBB, SPHERE, END }; enum class RENDER { PRIORITY, SHADOW, NONBLEND, BLUR, NONLIGHT, BLEND, UI, END }; enum class RAY { LOCAL, WORLD, END }; +enum class ACTOR { BOX, CAPSULE, SPHERE, PLANE, TRIANGLEMESH, HEIGHTFIELD, END }; enum class TEXTURE_LOAD_TYPE { diff --git a/Jusin154_Team3D/Engine/Public/Engine_Macro.h b/Jusin154_Team3D/Engine/Public/Engine_Macro.h index c4dd670cc..d037b4572 100644 --- a/Jusin154_Team3D/Engine/Public/Engine_Macro.h +++ b/Jusin154_Team3D/Engine/Public/Engine_Macro.h @@ -4,6 +4,10 @@ #define GUI ImGui #endif // !GUI +#ifndef PSX +#define PSX physx +#endif // !PSX + #pragma region ProgrammerInfo #define ASSERT_NURI(expression) @@ -75,7 +79,7 @@ //} #define FLT_EPSILON3 1.192092896e-03F #define FLT_EPSILON5 1.192092896e-05F -#define GRAVITY 9.8f +#define GRAVITY -9.81f constexpr unsigned int g_iMaxShadowWidth = 16384; constexpr unsigned int g_iMaxShadowHeight = 9216; diff --git a/Jusin154_Team3D/Engine/Public/GameInstance.h b/Jusin154_Team3D/Engine/Public/GameInstance.h index 6b8b7b0f8..7c4303e89 100644 --- a/Jusin154_Team3D/Engine/Public/GameInstance.h +++ b/Jusin154_Team3D/Engine/Public/GameInstance.h @@ -175,6 +175,13 @@ class ENGINE_DLL CGameInstance final : public CBase #pragma region PICKING _bool isPicking(_float3* pOut); #pragma endregion +#pragma region PhysX_Manager + PSX::PxMaterial* Get_Material(_float3& vMatInfo); + HRESULT Create_TriangleMesh(const _wstring& wstrMeshKey, CMesh* pMesh); + PSX::PxShape* Create_Shape(ACTOR eType, _float3& vhalfGeometryInfo, PSX::PxMaterial& pxMaterial, _bool bExclusive = false, PSX::PxShapeFlags ePxShapeFlag = PSX::PxShapeFlag::eVISUALIZATION | PSX::PxShapeFlag::eSCENE_QUERY_SHAPE | PSX::PxShapeFlag::eSIMULATION_SHAPE); + const PSX::PxRigidDynamic* Add_DynamicActor(CRigidBody& RigidBody); + const PSX::PxRigidStatic* Add_StaticActor(CRigidBody& RigidBody); +#pragma endregion public: @@ -213,6 +220,7 @@ class ENGINE_DLL CGameInstance final : public CBase class CKey_Manager* m_pKey_Manager = { nullptr }; class CMouse_Manager* m_pMouse_Manager = { nullptr }; class CCollider_Manager* m_pCollider_Manager = { nullptr }; + class CPhysX_Manager* m_pPhysX_Manager = { nullptr }; class CPicking* m_pPicking = { nullptr }; #ifdef _DEBUG diff --git a/Jusin154_Team3D/Engine/Public/Light_Manager.h b/Jusin154_Team3D/Engine/Public/Light_Manager.h index 1ed784f1f..10ce6bc90 100644 --- a/Jusin154_Team3D/Engine/Public/Light_Manager.h +++ b/Jusin154_Team3D/Engine/Public/Light_Manager.h @@ -17,7 +17,7 @@ class CLight_Manager final : public CBase HRESULT Change_Level(_uint iLevel); private: - map<_wstring, list*>* m_pLights = { nullptr };; + map<_wstring, list*>* m_pLights = { nullptr }; _uint m_iNumLevel = {}; private: list* Find_Lights(_uint iLevel, const _wstring& wstrLightKey); diff --git a/Jusin154_Team3D/Engine/Public/Mesh.h b/Jusin154_Team3D/Engine/Public/Mesh.h index 5fede893e..0f13d50a2 100644 --- a/Jusin154_Team3D/Engine/Public/Mesh.h +++ b/Jusin154_Team3D/Engine/Public/Mesh.h @@ -27,13 +27,14 @@ class ENGINE_DLL CMesh final : public CVIBuffer public: static CMesh* Create(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, MODEL eType, vector& Bones, const aiMesh* pAIMesh, _fmatrix& PreTransformMatrix); HRESULT SaveAsBinary(HANDLE hFile, DWORD& dwByte); + PSX::PxTriangleMesh* ConvertToPxMesh(const PSX::PxCookingParams* pParam); #endif // EDITOR_PROJECT public: //인스턴싱 모델 전용 드로우, 바인딩 함수 virtual HRESULT Bind_Resources_Instance(ID3D11Buffer* pVBInstance, _uint iInstanceStride, _uint iBufferCount); virtual HRESULT Render_Instance(_uint iNumInstance); - + private: virtual HRESULT Initialize_Prototype(HANDLE hFile, DWORD& dwByte); virtual HRESULT Initialize(void* pArg) override; @@ -50,7 +51,7 @@ class ENGINE_DLL CMesh final : public CVIBuffer _uint m_iNumBones = { }; vector<_int> m_BoneIndices; - _float4x4* m_pBoneMatrices = { nullptr }; + _float4x4* m_pBoneMatrices = { nullptr }; vector<_float4x4> m_offsetMatrices; // 바이너리 std::vector<_uint> m_Indices; diff --git a/Jusin154_Team3D/Engine/Public/MyTools.h b/Jusin154_Team3D/Engine/Public/MyTools.h index eacb53d88..d6112c40c 100644 --- a/Jusin154_Team3D/Engine/Public/MyTools.h +++ b/Jusin154_Team3D/Engine/Public/MyTools.h @@ -165,6 +165,45 @@ class CMyTools { return fValue; } +#pragma region FileSystem + //static void Folder_Func(/* 재귀적으로 탐색할지 */ _In_ _bool bRecursive, + // /* 탐색할 폴더 경로 */ _In_ const _wstring& TargetPath, + // /* 탐색할 때마다 실행할 로직*/ _In_ function funcLogic, + // /* 탐색할 확장자들 */ _In_ const vector<_wstring>& targetExtentions, + // /* 결과 경로들 */ _Out_ vector<_wstring>& Paths ) + //{ + // // 경로 예시 -> "../Bin/Resources/Models/Environment/Hogwarts/SUB_ClockTowerCourtyard/Static_Mesh_EXT" + // filesystem::path path = TargetPath; + // for (const filesystem::directory_entry& file : filesystem::directory_iterator(path, filesystem::directory_options::skip_permission_denied)) + // { + // if (file.is_directory()){ + // if (true == bRecursive) { + // Folder_Func(bRecursive, file.path().wstring(), funcLogic, targetExtentions, Paths); + // } + // continue; + // } + // if (true == targetExtentions.empty()) { // 확장자 제한 없음 + // Paths.emplace_back(file.path().wstring()); + // funcLogic(file); + // continue; + // } + // for (const _wstring& ext : targetExtentions) { // 확장자 제한 있음 + // if (file.path().extension() == ext) { + // Paths.emplace_back(file.path().wstring()); + // funcLogic(file); + // break; + // } + // } + // // file.path().extension(); // 확장자 + // // file.path().filename(); // 파일명(확장자포함) + // // file.path().stem(); // 파일명(확장자제외) + // // file.path().parent_path(); // 상위 폴더 경로 + // // file.path().wstring(); // 전체 경로 + // // file.path().string(); // 전체 경로 (string) + // } + //} +#pragma endregion + private: inline static void DecodeRGBA(_uint hex, float& r, float& g, float& b, float& a, bool hasAlpha) { diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxActor.h b/Jusin154_Team3D/Engine/Public/PhysX/PxActor.h new file mode 100644 index 000000000..aeb490a4a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxActor.h @@ -0,0 +1,383 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ACTOR_H +#define PX_ACTOR_H + +#include "PxPhysXConfig.h" +#include "foundation/PxBounds3.h" +#include "PxClient.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxRigidActor; +class PxRigidBody; +class PxRigidStatic; +class PxRigidDynamic; +class PxArticulationLink; +class PxScene; + +/** +\brief Group index which allows to specify 1- or 2-way interaction +*/ +typedef PxU8 PxDominanceGroup; // Must be < 32, PxU8. + +/** +\brief Flags which control the behavior of an actor. + +\see PxActorFlags PxActor PxActor.setActorFlag() PxActor.getActorFlags() +*/ +struct PxActorFlag +{ + enum Enum + { + /** + \brief Enable debug renderer for this actor + + \see PxScene.getRenderBuffer() PxRenderBuffer PxVisualizationParameter + */ + eVISUALIZATION = (1<<0), + + /** + \brief Disables scene gravity for this actor + */ + eDISABLE_GRAVITY = (1<<1), + + /** + \brief Enables the sending of PxSimulationEventCallback::onWake() and PxSimulationEventCallback::onSleep() notify events + + \see PxSimulationEventCallback::onWake() PxSimulationEventCallback::onSleep() + */ + eSEND_SLEEP_NOTIFIES = (1<<2), + + /** + \brief Disables simulation for the actor. + + \note This is only supported by PxRigidStatic and PxRigidDynamic actors and can be used to reduce the memory footprint when rigid actors are + used for scene queries only. + + \note Setting this flag will remove all constraints attached to the actor from the scene. + + \note If this flag is set, the following calls are forbidden: + \li PxRigidBody: setLinearVelocity(), setAngularVelocity(), addForce(), addTorque(), clearForce(), clearTorque(), setForceAndTorque() + \li PxRigidDynamic: setKinematicTarget(), setWakeCounter(), wakeUp(), putToSleep() + + \par Sleeping: + Raising this flag will set all velocities and the wake counter to 0, clear all forces, clear the kinematic target, put the actor + to sleep and wake up all touching actors from the previous frame. + */ + eDISABLE_SIMULATION = (1<<3) + }; +}; + +/** +\brief collection of set bits defined in PxActorFlag. + +\see PxActorFlag +*/ +typedef PxFlags PxActorFlags; +PX_FLAGS_OPERATORS(PxActorFlag::Enum,PxU8) + +/** +\brief Identifies each type of actor. +\see PxActor +*/ +struct PxActorType +{ + enum Enum + { + /** + \brief A static rigid body + \see PxRigidStatic + */ + eRIGID_STATIC, + + /** + \brief A dynamic rigid body + \see PxRigidDynamic + */ + eRIGID_DYNAMIC, + + /** + \brief An articulation link + \see PxArticulationLink + */ + eARTICULATION_LINK, + + /** + \brief A deformable surface + \see PxDeformableSurface + */ + eDEFORMABLE_SURFACE, + + /** + \brief A deformable volume + \see PxDeformableVolume + */ + eDEFORMABLE_VOLUME, + + /** + \brief Deprecated + \see eDEFORMABLE_VOLUME + */ + eSOFTBODY PX_DEPRECATED = eDEFORMABLE_VOLUME, + + /** + \brief A PBD ParticleSystem + \see PxPBDParticleSystem + */ + ePBD_PARTICLESYSTEM, + + //! \brief internal use only! + eACTOR_COUNT, + + //! \brief internal use only! + eACTOR_FORCE_DWORD = 0x7fffffff + }; +}; + +/** +\brief PxActor is the base class for the main simulation objects in the physics SDK. + +The actor is owned by and contained in a PxScene. +*/ +class PxActor : public PxBase +{ +public: + /** + \brief Deletes the actor. + + Do not keep a reference to the deleted instance. + + If the actor belongs to a #PxAggregate object, it is automatically removed from the aggregate. + + \see PxBase.release(), PxAggregate + */ + virtual void release() = 0; + + /** + \brief Retrieves the type of actor. + + \return The actor type of the actor. + + \see PxActorType + */ + virtual PxActorType::Enum getType() const = 0; + + /** + \brief Retrieves the scene which this actor belongs to. + + \return Owner Scene. NULL if not part of a scene. + + \see PxScene + */ + virtual PxScene* getScene() const = 0; + + // Runtime modifications + + /** + \brief Sets a name string for the object that can be retrieved with getName(). + + This is for debugging and is not used by the SDK. The string is not copied by the SDK, + only the pointer is stored. + + \param[in] name String to set the objects name to. + + Default: NULL + + \see getName() + */ + virtual void setName(const char* name) = 0; + + /** + \brief Retrieves the name string set with setName(). + + \return Name string associated with object. + + \see setName() + */ + virtual const char* getName() const = 0; + + /** + \brief Retrieves the axis aligned bounding box enclosing the actor. + + \note It is not allowed to use this method while the simulation is running (except during PxScene::collide(), + in PxContactModifyCallback or in contact report callbacks). + + \param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value. + + \return The actor's bounding box. + + \see PxBounds3 + */ + virtual PxBounds3 getWorldBounds(float inflation=1.01f) const = 0; + + /** + \brief Raises or clears a particular actor flag. + + See the list of flags #PxActorFlag + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] flag The PxActor flag to raise(set) or clear. See #PxActorFlag. + \param[in] value The boolean value to assign to the flag. + + \see PxActorFlag getActorFlags() + */ + virtual void setActorFlag(PxActorFlag::Enum flag, bool value) = 0; + + /** + \brief Sets the actor flags. + + See the list of flags #PxActorFlag + \see PxActorFlag setActorFlag() + */ + virtual void setActorFlags( PxActorFlags inFlags ) = 0; + + /** + \brief Reads the PxActor flags. + + See the list of flags #PxActorFlag + + \return The values of the PxActor flags. + + \see PxActorFlag setActorFlag() + */ + virtual PxActorFlags getActorFlags() const = 0; + + /** + \brief Assigns dynamic actors a dominance group identifier. + + PxDominanceGroup is a 5 bit group identifier (legal range from 0 to 31). + + The PxScene::setDominanceGroupPair() lets you set certain behaviors for pairs of dominance groups. + By default every dynamic actor is created in group 0. + + Default: 0 + + Sleeping: Changing the dominance group does NOT wake the actor up automatically. + + \param[in] dominanceGroup The dominance group identifier. Range: [0..31] + + \see getDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair() + */ + virtual void setDominanceGroup(PxDominanceGroup dominanceGroup) = 0; + + /** + \brief Retrieves the value set with setDominanceGroup(). + + \return The dominance group of this actor. + + \see setDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair() + */ + virtual PxDominanceGroup getDominanceGroup() const = 0; + + /** + \brief Sets the owner client of an actor. + + This cannot be done once the actor has been placed into a scene. + + Default: PX_DEFAULT_CLIENT + + \see PxClientID PxScene::createClient() + */ + virtual void setOwnerClient( PxClientID inClient ) = 0; + + /** + \brief Returns the owner client that was specified at creation time. + + This value cannot be changed once the object is placed into the scene. + + \see PxClientID PxScene::createClient() + */ + virtual PxClientID getOwnerClient() const = 0; + + /** + \brief Retrieves the aggregate the actor might be a part of. + + \return The aggregate the actor is a part of, or NULL if the actor does not belong to an aggregate. + + \see PxAggregate + */ + virtual PxAggregate* getAggregate() const = 0; + +/************************************************************************************************/ +/** \name Environment ID +*/ + + /** + \brief Sets the environment ID for this actor. + + The environment ID is an extra built-in filter group for the GPU broadphase. Actors will only collide with each-other if they have the + same environment ID. + + The default value is PX_INVALID_U32. Actors with this ID will collide with other actors, regardless of which environment they are a part of. + + The environment ID must be set before adding the actor to a scene, and cannot change while the actor is in the scene. + + If it is not PX_INVALID_U32, the environment ID must be smaller than 1<<24, i.e. the system does not support more than 1<<24 environments. + + Default: PX_INVALID_U32 + + \note This is not available for CPU broadphases. + + \param[in] envID Environment ID for this actor. + \return True if success. + + \see getEnvironmentID() + */ + virtual bool setEnvironmentID(PxU32 envID) = 0; + + /** + \brief Returns the environment ID for this actor. + + \return Environment ID for this actor. + + \see setEnvironmentID() + */ + virtual PxU32 getEnvironmentID() const = 0; + + //public variables: + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + PX_INLINE PxActor(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {} + PX_INLINE PxActor(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + virtual ~PxActor() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxActor", PxBase); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxAggregate.h b/Jusin154_Team3D/Engine/Public/PhysX/PxAggregate.h new file mode 100644 index 000000000..1603de550 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxAggregate.h @@ -0,0 +1,281 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_AGGREGATE_H +#define PX_AGGREGATE_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxActor; +class PxBVH; +class PxScene; + + struct PxAggregateType + { + enum Enum + { + eGENERIC = 0, //!< Aggregate will contain various actors of unspecified types + eSTATIC = 1, //!< Aggregate will only contain static actors + eKINEMATIC = 2 //!< Aggregate will only contain kinematic actors + }; + }; + + // PxAggregateFilterHint is used for more efficient filtering of aggregates outside of the broadphase. + // It is a combination of a PxAggregateType and a self-collision bit. + typedef PxU32 PxAggregateFilterHint; + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateFilterHint PxGetAggregateFilterHint(PxAggregateType::Enum type, bool enableSelfCollision) + { + const PxU32 selfCollisionBit = enableSelfCollision ? 1 : 0; + return PxAggregateFilterHint((PxU32(type)<<1)|selfCollisionBit); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 PxGetAggregateSelfCollisionBit(PxAggregateFilterHint hint) + { + return hint & 1; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateType::Enum PxGetAggregateType(PxAggregateFilterHint hint) + { + return PxAggregateType::Enum(hint>>1); + } + +/** +\brief Class to aggregate actors into a single broad-phase entry. + +A PxAggregate object is a collection of PxActors, which will exist as a single entry in the +broad-phase structures. This has 3 main benefits: + +1) it reduces "broad phase pollution" by allowing a collection of spatially coherent broad-phase +entries to be replaced by a single aggregated entry (e.g. a ragdoll or a single actor with a +large number of attached shapes). + +2) it reduces broad-phase memory usage + +3) filtering can be optimized a lot if self-collisions within an aggregate are not needed. For + example if you don't need collisions between ragdoll bones, it's faster to simply disable + filtering once and for all, for the aggregate containing the ragdoll, rather than filtering + out each bone-bone collision in the filter shader. + +\see PxActor, PxPhysics.createAggregate +*/ +class PxAggregate : public PxBase +{ +public: + + /** + \brief Deletes the aggregate object. + + Deleting the PxAggregate object does not delete the aggregated actors. If the PxAggregate object + belongs to a scene, the aggregated actors are automatically re-inserted in that scene. If you intend + to delete both the PxAggregate and its actors, it is best to release the actors first, then release + the PxAggregate when it is empty. + */ + virtual void release() = 0; + + /** + \brief Adds an actor to the aggregate object. + + A warning is output if the total number of actors is reached, or if the incoming actor already belongs + to an aggregate. + + If the aggregate belongs to a scene, adding an actor to the aggregate also adds the actor to that scene. + + If the actor already belongs to a scene, a warning is output and the call is ignored. You need to remove + the actor from the scene first, before adding it to the aggregate. + + \note When a BVH is provided the actor shapes are grouped together. + The scene query pruning structure inside PhysX SDK will store/update one + bound per actor. The scene queries against such an actor will query actor + bounds and then make a local space query against the provided BVH, which is in actor's local space. + + \param [in] actor The actor that should be added to the aggregate + \param [in] bvh BVH for actor shapes. + return true if success + */ + virtual bool addActor(PxActor& actor, const PxBVH* bvh = NULL) = 0; + + /** + \brief Removes an actor from the aggregate object. + + A warning is output if the incoming actor does not belong to the aggregate. Otherwise the actor is + removed from the aggregate. If the aggregate belongs to a scene, the actor is reinserted in that + scene. If you intend to delete the actor, it is best to call #PxActor::release() directly. That way + the actor will be automatically removed from its aggregate (if any) and not reinserted in a scene. + + \param [in] actor The actor that should be removed from the aggregate + return true if success + */ + virtual bool removeActor(PxActor& actor) = 0; + + /** + \brief Adds an articulation to the aggregate object. + + A warning is output if the total number of actors is reached (every articulation link counts as an actor), + or if the incoming articulation already belongs to an aggregate. + + If the aggregate belongs to a scene, adding an articulation to the aggregate also adds the articulation to that scene. + + If the articulation already belongs to a scene, a warning is output and the call is ignored. You need to remove + the articulation from the scene first, before adding it to the aggregate. + + \param [in] articulation The articulation that should be added to the aggregate + return true if success + */ + virtual bool addArticulation(PxArticulationReducedCoordinate& articulation) = 0; + + /** + \brief Removes an articulation from the aggregate object. + + A warning is output if the incoming articulation does not belong to the aggregate. Otherwise the articulation is + removed from the aggregate. If the aggregate belongs to a scene, the articulation is reinserted in that + scene. If you intend to delete the articulation, it is best to call #PxArticulationReducedCoordinate::release() directly. That way + the articulation will be automatically removed from its aggregate (if any) and not reinserted in a scene. + + \param [in] articulation The articulation that should be removed from the aggregate + return true if success + */ + virtual bool removeArticulation(PxArticulationReducedCoordinate& articulation) = 0; + + /** + \brief Returns the number of actors contained in the aggregate. + + You can use #getActors() to retrieve the actor pointers. + + \return Number of actors contained in the aggregate. + + \see PxActor getActors() + */ + virtual PxU32 getNbActors() const = 0; + + /** + \brief Retrieves max amount of actors that can be contained in the aggregate. + + \return Max actor size. + + \see PxPhysics::createAggregate() + */ + virtual PxU32 getMaxNbActors() const = 0; + + /** + \brief Retrieves max amount of shapes that can be contained in the aggregate. + + \return Max shape size. + + \see PxPhysics::createAggregate() + */ + virtual PxU32 getMaxNbShapes() const = 0; + + /** + \brief Retrieve all actors contained in the aggregate. + + You can retrieve the number of actor pointers by calling #getNbActors() + + \param[out] userBuffer The buffer to store the actor pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first actor pointer to be retrieved + \return Number of actor pointers written to the buffer. + + \see PxShape getNbShapes() + */ + virtual PxU32 getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Retrieves the scene which this aggregate belongs to. + + \return Owner Scene. NULL if not part of a scene. + + \see PxScene + */ + virtual PxScene* getScene() = 0; + + /** + \brief Retrieves aggregate's self-collision flag. + + \return self-collision flag + */ + virtual bool getSelfCollision() const = 0; + + /** + \brief Sets the environment ID for this aggregate. + + The environment ID is an extra built-in filter group for the GPU broadphase. Aggregates will only collide with actors or aggregates that + have the same environment ID. + + The default value is PX_INVALID_U32. Aggregates with this ID will collide with other actors or aggregates, regardless of which environment + they are a part of. + + The environment ID must be set before adding the aggregate to a scene, and cannot change while the aggregate is in the scene. + + If it is not PX_INVALID_U32, the environment ID must be smaller than 1<<24, i.e. the system does not support more than 1<<24 environments. + + Aggregated actors must have a default environment ID (PX_INVALID_U32). The environment ID of the aggregate is used in the broadphase, not + the environment IDs from aggregated actors. + + Default: PX_INVALID_U32 + + \note This is not available for CPU broadphases. + + \param[in] envID Environment ID for this aggregate. + \return True if success. + + \see getEnvironmentID() + */ + virtual bool setEnvironmentID(PxU32 envID) = 0; + + /** + \brief Returns the environment ID for this aggregate. + + \return Environment ID for this aggregate. + + \see setEnvironmentID() + */ + virtual PxU32 getEnvironmentID() const = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxAggregate"; } + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + PX_INLINE PxAggregate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {} + PX_INLINE PxAggregate(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + virtual ~PxAggregate() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxAggregate", PxBase); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxAnisotropy.h b/Jusin154_Team3D/Engine/Public/PhysX/PxAnisotropy.h new file mode 100644 index 000000000..8baa3ff2f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxAnisotropy.h @@ -0,0 +1,218 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ANISOTROPY_H +#define PX_ANISOTROPY_H + + +#include "cudamanager/PxCudaContext.h" +#include "cudamanager/PxCudaContextManager.h" + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" +#include "PxParticleSystem.h" + +#include "foundation/PxArray.h" +#include "PxParticleGpu.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_SUPPORT_GPU_PHYSX + + class PxgKernelLauncher; + class PxParticleNeighborhoodProvider; + + /** + \brief Computes anisotropy information for a particle system to improve rendering quality + */ + class PxAnisotropyGenerator + { + public: + /** + \brief Schedules the compuation of anisotropy information on the specified cuda stream + + \param[in] gpuParticleSystem A gpu pointer to access particle system data + \param[in] numParticles The number of particles + \param[in] stream The stream on which the cuda call gets scheduled + */ + virtual void generateAnisotropy(PxGpuParticleSystem* gpuParticleSystem, PxU32 numParticles, CUstream stream) = 0; + + /** + \brief Schedules the compuation of anisotropy information on the specified cuda stream + + \param[in] particlePositionsGpu A gpu pointer containing the particle positions + \param[in] neighborhoodProvider A neighborhood provider object that supports fast neighborhood queries + \param[in] numParticles The number of particles + \param[in] particleContactOffset The particle contact offset + \param[in] stream The stream on which the cuda call gets scheduled + */ + virtual void generateAnisotropy(PxVec4* particlePositionsGpu, PxParticleNeighborhoodProvider& neighborhoodProvider, PxU32 numParticles, PxReal particleContactOffset, CUstream stream) = 0; + + /** + \brief Set a host buffer that holds the anisotropy data after the timestep completed + + \param[in] anisotropy1 A host buffer holding the first row of the anisotropy matrix with memory for all particles already allocated + \param[in] anisotropy2 A host buffer holding the second row of the anisotropy matrix with memory for all particles already allocated + \param[in] anisotropy3 A host buffer holding the third row of the anisotropy matrix with memory for all particles already allocated + */ + virtual void setResultBufferHost(PxVec4* anisotropy1, PxVec4* anisotropy2, PxVec4* anisotropy3) = 0; + + /** + \brief Set a device buffer that holds the anisotrpy data after the timestep completed + + \param[in] anisotropy1 A device buffer holding the first row of the anisotropy matrix with memory for all particles already allocated + \param[in] anisotropy2 A device buffer holding the second row of the anisotropy matrix with memory for all particles already allocated + \param[in] anisotropy3 A device buffer holding the third row of the anisotropy matrix with memory for all particles already allocated + */ + virtual void setResultBufferDevice(PxVec4* anisotropy1, PxVec4* anisotropy2, PxVec4* anisotropy3) = 0; + + /** + \brief Sets the maximum value anisotropy can reach in any direction + + \param[in] maxAnisotropy The maximum anisotropy value + */ + virtual void setAnisotropyMax(float maxAnisotropy) = 0; + + /** + \brief Sets the minimum value anisotropy can reach in any direction + + \param[in] minAnisotropy The minimum anisotropy value + */ + virtual void setAnisotropyMin(float minAnisotropy) = 0; + + /** + \brief Sets the anisotropy scale + + \param[in] anisotropyScale The anisotropy scale + */ + virtual void setAnisotropyScale(float anisotropyScale) = 0; + + /** + \brief Gets the maximal number of particles + + \return The maximal number of particles + */ + virtual PxU32 getMaxParticles() const = 0; + + /** + \brief Sets the maximal number of particles + + \param[in] maxParticles The maximal number of particles + */ + virtual void setMaxParticles(PxU32 maxParticles) = 0; + + /** + \brief Gets the device pointer for the anisotropy in x direction. Only available after calling setResultBufferHost or setResultBufferDevice + + \return The device pointer for the anisotropy x direction and scale (w component contains the scale) + */ + virtual PxVec4* getAnisotropy1DevicePointer() const = 0; + + /** + \brief Gets the device pointer for the anisotropy in y direction. Only available after calling setResultBufferHost or setResultBufferDevice + + \return The device pointer for the anisotropy y direction and scale (w component contains the scale) + */ + virtual PxVec4* getAnisotropy2DevicePointer() const = 0; + + /** + \brief Gets the device pointer for the anisotropy in z direction. Only available after calling setResultBufferHost or setResultBufferDevice + + \return The device pointer for the anisotropy z direction and scale (w component contains the scale) + */ + virtual PxVec4* getAnisotropy3DevicePointer() const = 0; + + /** + \brief Enables or disables the anisotropy generator + + \param[in] enabled The boolean to set the generator to enabled or disabled + */ + virtual void setEnabled(bool enabled) = 0; + + /** + \brief Allows to query if the anisotropy generator is enabled + + \return True if enabled, false otherwise + */ + virtual bool isEnabled() const = 0; + + /** + \brief Releases the instance and its data + */ + virtual void release() = 0; + + /** + \brief Destructor + */ + virtual ~PxAnisotropyGenerator() {} + }; + + /** + \brief Default implementation of a particle system callback to trigger anisotropy calculations. A call to fetchResultsParticleSystem() on the + PxScene will synchronize the work such that the caller knows that the post solve task completed. + */ + class PxAnisotropyCallback : public PxParticleSystemCallback + { + public: + /** + \brief Initializes the anisotropy callback + + \param[in] anistropyGenerator The anisotropy generator + */ + void initialize(PxAnisotropyGenerator* anistropyGenerator) + { + mAnistropyGenerator = anistropyGenerator; + } + + virtual void onPostSolve(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) + { + if (mAnistropyGenerator) + { + mAnistropyGenerator->generateAnisotropy(gpuParticleSystem.mDevicePtr, gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream); + } + } + + virtual void onBegin(const PxGpuMirroredPointer& /*gpuParticleSystem*/, CUstream /*stream*/) { } + + virtual void onAdvance(const PxGpuMirroredPointer& /*gpuParticleSystem*/, CUstream /*stream*/) { } + + private: + PxAnisotropyGenerator* mAnistropyGenerator; + }; + +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArrayConverter.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArrayConverter.h new file mode 100644 index 000000000..37bd4ef4b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArrayConverter.h @@ -0,0 +1,74 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ARRAY_CONVERTER_H +#define PX_ARRAY_CONVERTER_H + +#include "cudamanager/PxCudaContext.h" +#include "cudamanager/PxCudaContextManager.h" + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_SUPPORT_GPU_PHYSX + + /** + \brief Utility class to convert gpu arrays to a different memory layout + */ + class PxArrayConverter + { + public: + /** + \brief Helper function to merge two separate PxVec4 arrays into one interleaved PxVec3 array + \param[in] verticesD The vertices device memory buffer + \param[in] normalsD The normals device memory buffer + \param[in] length The number of vertices and normals + \param[out] interleavedResultBufferD The resulting interleaved buffer containing 2*length elements with the format vertex0, normal0, vertex1, normal1... + \param[in] stream The cuda stream on which the conversion is processed + */ + virtual void interleaveGpuBuffers(const PxVec4* verticesD, const PxVec4* normalsD, PxU32 length, PxVec3* interleavedResultBufferD, CUstream stream) = 0; + + /** + \brief Destructor + */ + virtual ~PxArrayConverter() {} + }; + +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationFlag.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationFlag.h new file mode 100644 index 000000000..1fe6f3e25 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationFlag.h @@ -0,0 +1,74 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ARTICULATION_FLAG_H +#define PX_ARTICULATION_FLAG_H + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief These flags determine what data is read or written to the internal articulation data via cache. + + \see PxArticulationCache PxArticulationReducedCoordinate::copyInternalStateToCache PxArticulationReducedCoordinate::applyCache + */ + class PxArticulationCacheFlag + { + public: + enum Enum + { + eVELOCITY = (1 << 0), //!< The joint velocities, see PxArticulationCache::jointVelocity. + eACCELERATION = (1 << 1), //!< The joint accelerations, see PxArticulationCache::jointAcceleration. + ePOSITION = (1 << 2), //!< The joint positions, see PxArticulationCache::jointPosition. + eFORCE = (1 << 3), //!< The joint forces, see PxArticulationCache::jointForce. + eLINK_VELOCITY = (1 << 4), //!< The link velocities, see PxArticulationCache::linkVelocity. Link velocities cannot be set except for the root link velocity via PxArticulationCache::rootLinkData. + eLINK_ACCELERATION = (1 << 5), //!< The link accelerations, see PxArticulationCache::linkAcceleration. + eROOT_TRANSFORM = (1 << 6), //!< The root link transform, see PxArticulationCache::rootLinkData. + eROOT_VELOCITIES = (1 << 7), //!< The root link velocities (read/write) and accelerations (read), see PxArticulationCache::rootLinkData. + eLINK_INCOMING_JOINT_FORCE = (1 << 10), //!< The link incoming joint forces, see PxArticulationCache::linkIncomingJointForce. + eJOINT_TARGET_POSITIONS = (1 << 11), //!< The joint target positions, see PxArticulationCache::jointTargetPositions. + eJOINT_TARGET_VELOCITIES = (1 << 12), //!< The joint target velocities, see PxArticulationCache::jointTargetVelocities. + eLINK_FORCE = (1 << 13), //!< The link forces, see PxArticulationCache::linkForce. + eLINK_TORQUE = (1 << 14), //!< The link torques, see PxArticulationCache::linkTorque. + eALL = (eVELOCITY | eACCELERATION | ePOSITION | eLINK_VELOCITY | eLINK_ACCELERATION | eROOT_TRANSFORM | eROOT_VELOCITIES) + }; + }; + + typedef PxFlags PxArticulationCacheFlags; + PX_FLAGS_OPERATORS(PxArticulationCacheFlag::Enum, PxU32) + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationJointReducedCoordinate.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationJointReducedCoordinate.h new file mode 100644 index 000000000..4e594671b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationJointReducedCoordinate.h @@ -0,0 +1,551 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ARTICULATION_JOINT_RC_H +#define PX_ARTICULATION_JOINT_RC_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" +#include "solver/PxSolverDefs.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief A joint between two links in an articulation. + + \see PxArticulationReducedCoordinate, PxArticulationLink + */ + class PxArticulationJointReducedCoordinate : public PxBase + { + public: + + /** + \brief Gets the parent articulation link of this joint. + + \return The parent link. + */ + virtual PxArticulationLink& getParentArticulationLink() const = 0; + + /** + \brief Sets the joint pose in the parent link actor frame. + + \param[in] pose The joint pose. + Default: The identity transform. + + \note This call is not allowed while the simulation is running. + + \see getParentPose + */ + virtual void setParentPose(const PxTransform& pose) = 0; + + /** + \brief Gets the joint pose in the parent link actor frame. + + \return The joint pose. + + \see setParentPose + */ + virtual PxTransform getParentPose() const = 0; + + /** + \brief Gets the child articulation link of this joint. + + \return The child link. + */ + virtual PxArticulationLink& getChildArticulationLink() const = 0; + + /** + \brief Sets the joint pose in the child link actor frame. + + \param[in] pose The joint pose. + Default: The identity transform. + + \note This call is not allowed while the simulation is running. + + \see getChildPose + */ + virtual void setChildPose(const PxTransform& pose) = 0; + + /** + \brief Gets the joint pose in the child link actor frame. + + \return The joint pose. + + \see setChildPose + */ + virtual PxTransform getChildPose() const = 0; + + /** + \brief Sets the joint type (e.g. revolute). + + \param[in] jointType The joint type to set. + + \note Setting the joint type is not allowed while the articulation is in a scene. + In order to amend the joint type, remove and then re-add the articulation to the scene. + + Default: PxArticulationJointType::eUNDEFINED + + \see PxArticulationJointType, getJointType + */ + virtual void setJointType(PxArticulationJointType::Enum jointType) = 0; + + /** + \brief Gets the joint type. + + \return The joint type. + + \see PxArticulationJointType, setJointType + */ + virtual PxArticulationJointType::Enum getJointType() const = 0; + + /** + \brief Sets the joint motion for a given axis. + + \param[in] axis The target axis. + \param[in] motion The motion type to set. + + \note Setting the motion of joint axes is not allowed while the articulation is in a scene. + In order to set the motion, remove and then re-add the articulation to the scene. + + Default: PxArticulationMotion::eLOCKED + + \see PxArticulationAxis, PxArticulationMotion, getMotion + */ + virtual void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) = 0; + + /** + \brief Returns the joint motion for the given axis. + + \param[in] axis The target axis. + + \return The joint motion of the given axis. + + \see PxArticulationAxis, PxArticulationMotion, setMotion + */ + virtual PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the joint limits for a given axis. + + - The motion of the corresponding axis should be set to PxArticulationMotion::eLIMITED in order for the limits to be enforced. + - The lower limit should be strictly smaller than the higher limit. If the limits should be equal, use PxArticulationMotion::eLOCKED + and an appropriate offset in the parent/child joint frames. + + \param[in] axis The target axis. + \param[in] limit The joint limits. + + \note This call is not allowed while the simulation is running. + + \note For PxArticulationJointType::eSPHERICAL, limit.min and limit.max must both be in range [-Pi, Pi]. + \note For PxArticulationJointType::eREVOLUTE, limit.min and limit.max must both be in range [-2*Pi, 2*Pi]. + \note For PxArticulationJointType::eREVOLUTE_UNWRAPPED, limit.min and limit.max must both be in range [-PX_MAX_REAL, PX_MAX_REAL]. + \note For PxArticulationJointType::ePRISMATIC, limit.min and limit.max must both be in range [-PX_MAX_REAL, PX_MAX_REAL]. + + Default: (0,0) + + \see getLimitParams, PxArticulationAxis, PxArticulationLimit + */ + virtual void setLimitParams(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit) = 0; + + /** + \brief Returns the joint limits for a given axis. + + \param[in] axis The target axis. + + \return The joint limits. + + \see setLimitParams, PxArticulationAxis, PxArticulationLimit + */ + virtual PxArticulationLimit getLimitParams(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Configures a joint drive for the given axis. + + See PxArticulationDrive for parameter details; and the manual for further information, and the drives' implicit spring-damper (i.e. PD control) implementation in particular. + + \param[in] axis The target axis. + \param[in] drive The drive parameters + + \note This call is not allowed while the simulation is running. + + \see getDriveParams, PxArticulationAxis, PxArticulationDrive + + Default: PxArticulationDrive(0.0f, 0.0f, 0.0f, PxArticulationDriveType::eNONE) + */ + virtual void setDriveParams(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) = 0; + + /** + \brief Gets the joint drive configuration for the given axis. + + \param[in] axis The target axis. + \return The drive parameters. + + \see setDriveParams, PxArticulationAxis, PxArticulationDrive + */ + virtual PxArticulationDrive getDriveParams(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the joint drive position target for the given axis. + + The target units are linear units (equivalent to scene units) for a translational axis, or rad for a rotational axis. + + \param[in] axis The target axis. + \param[in] target The target position. + \param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter + to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value. + + \note This call is not allowed while the simulation is running. + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note For spherical joints, target must be in range [-Pi, Pi]. + + \note The target is specified in the parent frame of the joint. If Gp, Gc are the parent and child actor poses in the world frame and Lp, Lc are the parent and child joint frames expressed in the parent and child actor frames then the joint will drive the parent and child links to poses that obey Gp * Lp * J = Gc * Lc. For joints restricted to angular motion, J has the form PxTranfsorm(PxVec3(PxZero), PxExp(PxVec3(twistTarget, swing1Target, swing2Target))). For joints restricted to linear motion, J has the form PxTransform(PxVec3(XTarget, YTarget, ZTarget), PxQuat(PxIdentity)). + + \note For spherical joints with more than 1 degree of freedom, the joint target angles taken together can collectively represent a rotation of greater than Pi around a vector. When this happens the rotation that matches the joint drive target is not the shortest path rotation. The joint pose J that is the outcome after driving to the target pose will always be the equivalent of the shortest path rotation. + + \see PxArticulationAxis, getDriveTarget + + Default: 0.0 + */ + virtual void setDriveTarget(PxArticulationAxis::Enum axis, const PxReal target, bool autowake = true) = 0; + + /** + \brief Returns the joint drive position target for the given axis. + + \param[in] axis The target axis. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \return The target position. + + \see PxArticulationAxis, setDriveTarget + */ + virtual PxReal getDriveTarget(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the joint drive velocity target for the given axis. + + The target units are linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis. + + \param[in] axis The target axis. + \param[in] targetVel The target velocity. + \param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter + to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value. + + \note This call is not allowed while the simulation is running. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationAxis, getDriveVelocity + + Default: 0.0 + */ + virtual void setDriveVelocity(PxArticulationAxis::Enum axis, const PxReal targetVel, bool autowake = true) = 0; + + /** + \brief Returns the joint drive velocity target for the given axis. + + \param[in] axis The target axis. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \return The target velocity. + + \see PxArticulationAxis, setDriveVelocity + */ + virtual PxReal getDriveVelocity(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the joint armature for the given axis. + + - The armature is directly added to the joint-space spatial inertia of the corresponding axis. + - The armature is in mass units for a prismatic (i.e. linear) joint, and in mass units * (scene linear units)^2 for a rotational joint. + + \param[in] axis The target axis. + \param[in] armature The joint axis armature. + + \note This call is not allowed while the simulation is running. + + \see PxArticulationAxis, getArmature + + Default: 0.0 + */ + virtual void setArmature(PxArticulationAxis::Enum axis, const PxReal armature) = 0; + + /** + \brief Gets the joint armature for the given axis. + + \param[in] axis The target axis. + \return The armature set on the given axis. + + \see PxArticulationAxis, setArmature + */ + virtual PxReal getArmature(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the joint friction coefficient, which applies to all joint axes. + + - The joint friction is unitless and relates the magnitude of the spatial force [F_trans, T_trans] transmitted from parent to child link to + the maximal friction force F_resist that may be applied by the solver to resist joint motion, per axis; i.e. |F_resist| <= coefficient * (|F_trans| + |T_trans|), + where F_resist may refer to a linear force or torque depending on the joint axis. + - The simulated friction effect is therefore similar to static and Coulomb friction. In order to simulate dynamic joint friction, use a joint drive with + zero stiffness and zero velocity target, and an appropriately dimensioned damping parameter. + + \param[in] coefficient The joint friction coefficient. + + \note This call is not allowed while the simulation is running. + + \see getFrictionCoefficient + + Default: 0.05 + */ + virtual PX_DEPRECATED void setFrictionCoefficient(const PxReal coefficient) = 0; + + /** + \brief Gets the joint friction coefficient. + + \return The joint friction coefficient. + + \see setFrictionCoefficient + */ + virtual PX_DEPRECATED PxReal getFrictionCoefficient() const = 0; + + /** + \brief Configures joint friction. + + See PxJointFrictionParams for parameter details; and the manual for further information. The new friction model is applied to all axes where setFrictionParams() has been called. + For axes where setFrictionParams() hasn't been used, the deprecated friction model remains in effect. See setFrictionCoefficient(). + + \param[in] axis The target axis. + \param[in] jointFrictionParams The joint friction parameters. + + \note This call is not allowed while the simulation is running. + + Default: PxJointFrictionParams(0.0f, 0.0f, 0.0f) + */ + virtual void setFrictionParams(PxArticulationAxis::Enum axis, const PxJointFrictionParams& jointFrictionParams) = 0; + + /** + \brief Gets per-axis joint friction parameters struct. + + \param[in] axis The target axis. + + \return The joint friction parameters. + + \see setFrictionParams() + */ + virtual PxJointFrictionParams getFrictionParams(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the maximal joint velocity enforced for all axes. + + - The solver will apply appropriate joint-space impulses in order to enforce the per-axis joint-velocity limit. + - The velocity units are linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis. + + \param[in] maxJointV The maximal per-axis joint velocity. + + \note This call is not allowed while the simulation is running. + + \see getMaxJointVelocity + + Default: 100.0 + */ + virtual PX_DEPRECATED void setMaxJointVelocity(const PxReal maxJointV) = 0; + + /** + \brief Gets the maximal joint velocity enforced for all axes. + + \return The maximal per-axis joint velocity. + + \see setMaxJointVelocity + */ + virtual PX_DEPRECATED PxReal getMaxJointVelocity() const = 0; + + /** + \brief Sets the maximal joint velocity enforced for the given axis. + + - The solver will apply appropriate joint-space impulses in order to enforce the per-axis joint-velocity limit. + - The velocity units are linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis. + + \param[in] axis The target axis. + \param[in] maxJointV The maximal per-axis joint velocity. + + \note This call is not allowed while the simulation is running. + + \see getMaxJointVelocity() + + Default: 100.0 + */ + virtual void setMaxJointVelocity(PxArticulationAxis::Enum axis, const PxReal maxJointV) = 0; + + /** + \brief Gets the maximal joint velocity enforced for the given axis. + + \param[in] axis The target axis. + + \return The maximal joint velocity for the given axis. + + \see setMaxJointVelocity() + */ + virtual PxReal getMaxJointVelocity(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the joint position for the given axis. + + - For performance, prefer PxArticulationCache::jointPosition to set joint positions in a batch articulation state update. + - Use PxArticulationReducedCoordinate::updateKinematic after all state updates to the articulation via non-cache API such as this method, + in order to update link states for the next simulation frame or querying. + + \param[in] axis The target axis. + \param[in] jointPos The joint position in linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis. + + \note This call is not allowed while the simulation is running. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note For PxArticulationJointType::eSPHERICAL, jointPos must be in range [-Pi, Pi]. + \note For PxArticulationJointType::eREVOLUTE, jointPos must be in range [-2*Pi, 2*Pi]. + \note For PxArticulationJointType::eREVOLUTE_UNWRAPPED, jointPos must be in range [-PX_MAX_REAL, PX_MAX_REAL]. + \note For PxArticulationJointType::ePRISMATIC, jointPos must be in range [-PX_MAX_REAL, PX_MAX_REAL]. + + \note Joint position is specified in the parent frame of the joint. If Gp, Gc are the parent and child actor poses in the world frame and Lp, Lc are the parent and child joint frames expressed in the parent and child actor frames then the parent and child links will be given poses that obey Gp * Lp * J = Gc * Lc with J denoting the joint pose. For joints restricted to angular motion, J has the form PxTranfsorm(PxVec3(PxZero), PxExp(PxVec3(twistPos, swing1Pos, swing2Pos))). For joints restricted to linear motion, J has the form PxTransform(PxVec3(xPos, yPos, zPos), PxQuat(PxIdentity)). + + \note For spherical joints with more than 1 degree of freedom, the input joint positions taken together can collectively represent a rotation of greater than Pi around a vector. When this happens the rotation that matches the joint positions is not the shortest path rotation. The joint pose J that is the outcome of setting and applying the joint positions will always be the equivalent of the shortest path rotation. + + \see PxArticulationAxis, getJointPosition, PxArticulationCache::jointPosition, PxArticulationReducedCoordinate::updateKinematic + + Default: 0.0 + */ + virtual void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos) = 0; + + /** + \brief Gets the joint position for the given axis, i.e. joint degree of freedom (DOF). + + For performance, prefer PxArticulationCache::jointPosition to get joint positions in a batch query. + + \param[in] axis The target axis. + + \return The joint position in linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis. + + \note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(), + and in PxContactModifyCallback or in contact report callbacks. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationAxis, setJointPosition, PxArticulationCache::jointPosition + */ + virtual PxReal getJointPosition(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Sets the joint velocity for the given axis. + + - For performance, prefer PxArticulationCache::jointVelocity to set joint velocities in a batch articulation state update. + - Use PxArticulationReducedCoordinate::updateKinematic after all state updates to the articulation via non-cache API such as this method, + in order to update link states for the next simulation frame or querying. + + \param[in] axis The target axis. + \param[in] jointVel The joint velocity in linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis. + + \note This call is not allowed while the simulation is running. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationAxis, getJointVelocity, PxArticulationCache::jointVelocity, PxArticulationReducedCoordinate::updateKinematic + + Default: 0.0 + */ + virtual void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel) = 0; + + /** + \brief Gets the joint velocity for the given axis. + + For performance, prefer PxArticulationCache::jointVelocity to get joint velocities in a batch query. + + \param[in] axis The target axis. + + \return The joint velocity in linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis. + + \note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(), + and in PxContactModifyCallback or in contact report callbacks. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationAxis, setJointVelocity, PxArticulationCache::jointVelocity + */ + virtual PxReal getJointVelocity(PxArticulationAxis::Enum axis) const = 0; + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationJointReducedCoordinate"; } + + virtual ~PxArticulationJointReducedCoordinate() {} + + //public variables: + void* userData; //!< The user can assign this to whatever, usually to create a 1:1 relationship with a user object. + + /** + \brief Sets a name string for the object that can be retrieved with getName(). + + This is for debugging and is not used by the SDK. The string is not copied by the SDK, + only the pointer is stored. + + \param[in] name String to set the objects name to. + + Default: NULL + + \see getName() + */ + virtual void setName(const char* name) = 0; + + /** + \brief Retrieves the name string set with setName(). + + \return Name string associated with object. + + \see setName() + */ + virtual const char* getName() const = 0; + + protected: + PX_INLINE PxArticulationJointReducedCoordinate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxArticulationJointReducedCoordinate(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationJointReducedCoordinate", PxBase); } + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationLink.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationLink.h new file mode 100644 index 000000000..f1b3c35ae --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationLink.h @@ -0,0 +1,208 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ARTICULATION_LINK_H +#define PX_ARTICULATION_LINK_H + +#include "PxPhysXConfig.h" +#include "PxRigidBody.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief A component of an articulation that represents a rigid body. + +Articulation links have a restricted subset of the functionality of a PxRigidDynamic: +- They may not be kinematic, and do not support contact-force thresholds. +- Their velocity or global pose cannot be set directly, but must be set via the articulation-root and joint positions/velocities. +- Sleep state and solver iteration counts are properties of the entire articulation rather than the individual links. + +\see PxArticulationReducedCoordinate, PxArticulationReducedCoordinate::createLink, PxArticulationJointReducedCoordinate, PxRigidBody +*/ + +class PxArticulationLink : public PxRigidBody +{ +public: + /** + \brief Releases the link from the articulation. + + \note Only a leaf articulation link can be released. + \note Releasing a link is not allowed while the articulation link is in a scene. In order to release a link, + remove and then re-add the corresponding articulation to the scene. + + \see PxArticulationReducedCoordinate::createLink() + */ + virtual void release() = 0; + + /** + \brief Gets the articulation that the link is a part of. + + \return The articulation. + + \see PxArticulationReducedCoordinate + */ + virtual PxArticulationReducedCoordinate& getArticulation() const = 0; + + /** + \brief Gets the joint which connects this link to its parent. + + \return The joint connecting the link to the parent. NULL for the root link. + + \see PxArticulationJointReducedCoordinate + */ + virtual PxArticulationJointReducedCoordinate* getInboundJoint() const = 0; + + /** + \brief Gets the number of degrees of freedom of the joint which connects this link to its parent. + + - The root link DOF-count is defined to be 0 regardless of PxArticulationFlag::eFIX_BASE. + - The return value is only valid for articulations that are in a scene. + + \return The number of degrees of freedom, or 0xFFFFFFFF if the articulation is not in a scene. + + \see PxArticulationJointReducedCoordinate + */ + virtual PxU32 getInboundJointDof() const = 0; + + /** + \brief Gets the number of child links. + + \return The number of child links. + + \see getChildren + */ + virtual PxU32 getNbChildren() const = 0; + + /** + \brief Gets the low-level link index that may be used to index into members of PxArticulationCache. + + The low-level indices are built after an articulation is added to the scene following a breadth-first approach, + where all the links at the current depth are indexed sequentially before moving to the links at the next depth level. + The root of the articulation has therefore the index 0. + Note that the low-level indices may be different from the order in which the links were originally added to the articulation. + + The return value is only valid for articulations that are in a scene. + + \return The low-level index, or 0xFFFFFFFF if the articulation is not in a scene. + + \see PxArticulationCache + */ + virtual PxU32 getLinkIndex() const = 0; + + /** + \brief Retrieves the child links. + + \param[out] userBuffer The buffer to receive articulation link pointers. + \param[in] bufferSize The size of the provided user buffer, use getNbChildren() for sizing. + \param[in] startIndex The index of the first child pointer to be retrieved. + + \return The number of articulation links written to the buffer. + + \see getNbChildren + */ + virtual PxU32 getChildren(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + + /** + \brief Set the constraint-force-mixing scale term. + + The cfm scale term is a stabilization term that helps avoid instabilities with over-constrained + configurations. It should be a small value that is multiplied by 1/mass internally to produce + an additional bias added to the unit response term in the solver. + + \param[in] cfm The constraint-force-mixing scale term. + + Default: 0.025 + Range: [0, 1] + + \note This call is not allowed while the simulation is running. + + \see getCfmScale + */ + virtual void setCfmScale(const PxReal cfm) = 0; + + /** + \brief Get the constraint-force-mixing scale term. + \return The constraint-force-mixing scale term. + + \see setCfmScale + */ + virtual PxReal getCfmScale() const = 0; + + /** + \brief Get the linear velocity of the link. + + - For performance, prefer PxArticulationCache::linkVelocity to get link spatial velocities in a batch query. + - When the articulation state is updated via non-cache API, use PxArticulationReducedCoordinate::updateKinematic before querying velocity. + + \return The linear velocity of the link. + + \note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(), + and in PxContactModifyCallback or in contact report callbacks. + + \note The linear velocity is reported with respect to the link's center of mass and not the actor frame origin. + + \see PxRigidBody::getCMassLocalPose + */ + virtual PxVec3 getLinearVelocity() const = 0; + + /** + \brief Get the angular velocity of the link. + + - For performance, prefer PxArticulationCache::linkVelocity to get link spatial velocities in a batch query. + - When the articulation state is updated via non-cache API, use PxArticulationReducedCoordinate::updateKinematic before querying velocity. + + \return The angular velocity of the link. + + \note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(), + and in PxContactModifyCallback or in contact report callbacks. + */ + virtual PxVec3 getAngularVelocity() const = 0; + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationLink"; } + +protected: + PX_INLINE PxArticulationLink(PxType concreteType, PxBaseFlags baseFlags) : PxRigidBody(concreteType, baseFlags) {} + PX_INLINE PxArticulationLink(PxBaseFlags baseFlags) : PxRigidBody(baseFlags) {} + virtual ~PxArticulationLink() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationLink", PxRigidBody); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationMimicJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationMimicJoint.h new file mode 100644 index 000000000..109c72e60 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationMimicJoint.h @@ -0,0 +1,166 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef PX_ARTICULATION_MIMIC_JOINT_H +#define PX_ARTICULATION_MIMIC_JOINT_H + +#include "foundation/PxSimpleTypes.h" +#include "solver/PxSolverDefs.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxArticulationReducedCoordinate; +class PxArticulationJointReducedCoordinate; + +/** +* \brief A mimic joint enforces a linear relationship between the positions of two joints of the same articulation instance. +\see PxArticulationReducedCoodinate::createMimicJoint() +*/ +class PxArticulationMimicJoint : public PxBase +{ +public: + + /** + \brief Releases the mimic joint. + + \note Releasing a mimic joint is not allowed while the articulation is in a scene. In order to + release a mimic joint, remove and then re-add the articulation to the scene. + */ + virtual void release() = 0; + + /** + \brief Returns the articulation that this mimic joint is part of. + + \return A reference to the articulation. + */ + virtual PxArticulationReducedCoordinate& getArticulation() const = 0; + + /** + \brief Get the gear of a mimic joint. + \return The gear ratio. + */ + virtual PxReal getGearRatio() const = 0; + + /** + \brief Set the gear ratio of a mimic joint. + \param[in] gearRatio is the new gear ratio to be used in the next simulation step. + */ + virtual void setGearRatio(PxReal gearRatio) = 0; + + /** + \brief Get the offset of a mimic joint. + \return The offset. + */ + virtual PxReal getOffset() const = 0; + + /** + \brief Set the offset of a mimic joint. + \param[in] offset is the new offset to be used in the next simulation step. + */ + virtual void setOffset(PxReal offset) = 0; + + /** + \brief Get the natural frequency of a mimic joint. + \return The natural frequency. + */ + virtual PxReal getNaturalFrequency() const = 0; + + /** + \brief Set the natural frequency of a mimic joint. + \param[in] naturalFrequency is the new natural frequency to be used in the next simulation step. + */ + virtual void setNaturalFrequency(PxReal naturalFrequency) = 0; + + /** + \brief Get the damping ratio of a mimic joint. + \return The damping ratio. + */ + virtual PxReal getDampingRatio() const = 0; + + /** + \brief Set the damping ratio of a mimic joint. + \param[in] dampingRatio is the new damping ratio to be used in the next simulation step. + */ + virtual void setDampingRatio(PxReal dampingRatio) = 0; + + + /** + \brief Return the jointA specified in PxArticulationReducedCoordinate::createMimicJoint() + \return The jointA specified in PxArticulationReducedCoordinate::createMimicJoint() + \see PxArticulationReducedCoordinate::createMimicJoint() + */ + virtual PxArticulationJointReducedCoordinate& getJointA() const = 0; + + /** + \brief Return the jointB specified in PxArticulationReducedCoordinate::createMimicJoint() + \return The jointB specified in PxArticulationReducedCoordinate::createMimicJoint() + \see PxArticulationReducedCoordinate::createMimicJoint() + */ + virtual PxArticulationJointReducedCoordinate& getJointB() const = 0; + + /** + \brief Return the axisA specified in PxArticulationReducedCoordinate::createMimicJoint() + \return The axisA specified in PxArticulationReducedCoordinate::createMimicJoint() + \see PxArticulationReducedCoordinate::createMimicJoint() + */ + + virtual PxArticulationAxis::Enum getAxisA() const = 0; + + /** + \brief Return the axisB specified in PxArticulationReducedCoordinate::createMimicJoint() + \return The axisB specified in PxArticulationReducedCoordinate::createMimicJoint() + \see PxArticulationReducedCoordinate::createMimicJoint() + */ + virtual PxArticulationAxis::Enum getAxisB() const = 0; + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationMimicJoint"; } + + virtual ~PxArticulationMimicJoint() {} + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + PX_INLINE PxArticulationMimicJoint(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxArticulationMimicJoint(PxBaseFlags baseFlags) : PxBase(baseFlags) {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif //PX_ARTICULATION_MIMIC_JOINT_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationReducedCoordinate.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationReducedCoordinate.h new file mode 100644 index 000000000..104ee714e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationReducedCoordinate.h @@ -0,0 +1,1546 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ARTICULATION_RC_H +#define PX_ARTICULATION_RC_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" +#include "foundation/PxVec3.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxTransform.h" +#include "solver/PxSolverDefs.h" +#include "PxArticulationFlag.h" +#include "PxArticulationTendon.h" +#include "PxResidual.h" +#include "PxArticulationMimicJoint.h" +#include "PxArticulationFlag.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + PX_ALIGN_PREFIX(16) + /** + \brief Data structure to represent spatial forces. + */ + struct PxSpatialForce + { + PxVec3 force; + PxReal pad0; + PxVec3 torque; + PxReal pad1; + } + PX_ALIGN_SUFFIX(16); + + PX_ALIGN_PREFIX(16) + /** + \brief Data structure to represent spatial velocities. + */ + struct PxSpatialVelocity + { + PxVec3 linear; + PxReal pad0; + PxVec3 angular; + PxReal pad1; + } + PX_ALIGN_SUFFIX(16); + + class PxConstraint; + class PxScene; + + /** + \brief Data structure used to access the root link state and acceleration. + + \see PxArticulationCache + */ + struct PxArticulationRootLinkData + { + PxTransform transform; //!< Actor transform + // The velocities and accelerations below are with respect to the center of mass (COM) of the root link. The COM and actor frame origin may not coincide. + PxVec3 worldLinVel; //!< Link linear velocity + PxVec3 worldAngVel; //!< Link angular velocity + PxVec3 worldLinAccel; //!< Link classical linear acceleration + PxVec3 worldAngAccel; //!< Link angular acceleration + }; + + /** + \brief Data structure used to read and write internal articulation data. + + \see PxArticulationCacheFlag, PxArticulationReducedCoordinate::createCache, PxArticulationReducedCoordinate::applyCache, + PxArticulationReducedCoordinate::copyInternalStateToCache + */ + class PxArticulationCache + { + public: + PxArticulationCache() : + externalForces (NULL), + denseJacobian (NULL), + massMatrix (NULL), + coriolisForce (NULL), + gravityCompensationForce (NULL), + centroidalMomentumMatrix (NULL), + centroidalMomentumBias (NULL), + jointVelocity (NULL), + jointAcceleration (NULL), + jointPosition (NULL), + jointForce (NULL), + jointTargetPositions (NULL), + jointTargetVelocities (NULL), + linkVelocity (NULL), + linkAcceleration (NULL), + linkIncomingJointForce (NULL), + linkForce (NULL), + linkTorque (NULL), + rootLinkData (NULL), + coefficientMatrix (NULL), + lambda (NULL), + scratchMemory (NULL), + scratchAllocator (NULL), + version (0) + {} + + /** + \brief Releases an articulation cache. + + \see PxArticulationReducedCoordinate::createCache, PxArticulationReducedCoordinate::applyCache, + PxArticulationReducedCoordinate::copyInternalStateToCache + */ + PX_PHYSX_CORE_API void release(); + + /** + \brief External forces acting on the articulation links for inverse dynamics computation. + + - N = getNbLinks(). + - Indexing follows the low-level link indices, see PxArticulationLink::getLinkIndex. + - The forces are with respect to the center of mass of the link. + - This field cannot be used to apply forces to links during the next PxScene::simulate() call. Use PxRigidBody::addForce and related functions instead. + + \see PxArticulationReducedCoordinate::computeGeneralizedExternalForce + */ + PxSpatialForce* externalForces; + + /** + \brief Dense Jacobian data. + + - N = nbRows * nbCols = (6 * getNbLinks()) * (6 + getDofs()) -> size includes possible floating-base DOFs regardless of PxArticulationFlag::eFIX_BASE flag. + - The links, i.e. rows are in order of the low-level link indices (minus one if PxArticulationFlag::eFIX_BASE is true), see PxArticulationLink::getLinkIndex. + The corresponding spatial velocities are stacked [vx; vy; vz; wx; wy; wz], where vx and wx refer to the linear and rotational velocity in world X. + - The DOFs, i.e. column indices correspond to the low-level DOF indices, see PxArticulationCache::jointVelocity. + + \see PxArticulationReducedCoordinate::computeDenseJacobian + */ + PxReal* denseJacobian; + + /** + \brief The generalized mass matrix used in inverse dynamics algorithms. + + - N = (getDofs() + 6) * (getDofs() + 6) -> size includes possible floating-base DOFs regardless of PxArticulationFlag::eFIX_BASE flag. + - If PxArticulationFlag::eFIX_BASE is true, the terms corresponding to the root DoFs are included in the top left block of the matrix. + For these terms, column indices correspond to linear acceleration first then angular acceleration, row indices correspond to force first then torque. + The bottom right block of the matrix corresponds to the joint DoFs terms, column indices correspond to joint acceleration, row indices correspond to joint force. + - If PxArticulationFlag::eFIX_BASE is false, only the terms corresponding to the joint DoFs are included, column indices correspond to joint acceleration, + row indices correspond to joint force. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + - The mass matrix is indexed [nCols * row + column]. + + \see PxArticulationReducedCoordinate::computeMassMatrix, PxArticulationReducedCoordinate::computeGeneralizedMassMatrix + */ + PxReal* massMatrix; + + /** + \brief The Coriolis and centrifugal compensation forces used in inverse dynamics algorithms. + + - N = getDofs() + 6 -> size includes possible floating-base DOFs regardless of PxArticulationFlag::eFIX_BASE flag. + - If PxArticulationFlag::eFIX_BASE is true, the terms corresponding to the root DoFs are included at the start of + the array (force then torque), followed by the joint DoFs terms. + - If PxArticulationFlag::eFIX_BASE is false, only the terms corresponding to the joint DoFs are included. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + + \see PxArticulationReducedCoordinate::computeCoriolisCompensation + */ + PxReal* coriolisForce; + + /** + \brief The gravity compensation forces used in inverse dynamics algorithms. + + - N = getDofs() + 6 -> size includes possible floating-base DOFs regardless of PxArticulationFlag::eFIX_BASE flag. + - If PxArticulationFlag::eFIX_BASE is true, the terms corresponding to the root DoFs are included at the start of + the array (force then torque), followed by the joint DoFs terms. + - If PxArticulationFlag::eFIX_BASE is false, only the terms corresponding to the joint DoFs are included. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + + \see PxArticulationReducedCoordinate::computeGravityCompensation + */ + PxReal* gravityCompensationForce; + + /** + \brief The centroidal momentum matrix that maps velocities to centroidal momentum. + + - N = 6 * (getDofs() + 6). + - Each row includes first the term related to the DOF of the root (linear, then angular), then the joint DOF following the internal DOF index order, + see PxArticulationCache::jointVelocity. + - The centroidal momentum includes first the linear and then the angular contribution. + + \see PxArticulationReducedCoordinate::computeCentroidalMomentumMatrix + */ + PxReal* centroidalMomentumMatrix; + + /** + \brief The centroidal momentum bias force. This is a second-order term to calculate the derivative of the centroidal momentum. + + - N = 6. + - The centroidal momentum includes first the linear and then the angular contribution. + + \see PxArticulationReducedCoordinate::computeCentroidalMomentumMatrix + */ + PxReal* centroidalMomentumBias; + + /** + \brief The articulation joint DOF velocities. + + - N = getDofs(). + - Read/write using PxArticulationCacheFlag::eVELOCITY. + - The indexing follows the internal DOF index order. Therefore, the application should calculate the DOF data indices by summing the joint DOFs in the order of + the links' low-level indices (see the manual Section "Cache Indexing" for a snippet for this calculation): + \verbatim Low-level link index: | link 0 | link 1 | link 2 | link 3 | ... | <- PxArticulationLink::getLinkIndex() \endverbatim + \verbatim Link inbound joint DOF: | 0 | 1 | 2 | 1 | ... | <- PxArticulationLink::getInboundJointDof() \endverbatim + \verbatim Low-level DOF index: | - | 0 | 1, 2 | 3 | ... | \endverbatim + The root link always has low-level index 0 and always has zero inbound joint DOFs. The link DOF indexing follows the order in PxArticulationAxis::Enum. + For example, assume that low-level link 2 has an inbound spherical joint with two DOFs: eSWING1 and eSWING2. The corresponding low-level joint DOF indices + are therefore 1 for eSWING1 and 2 for eSWING2. + */ + PxReal* jointVelocity; + + /** + \brief The articulation joint DOF accelerations. + + - N = getDofs(). + - Read using PxArticulationCacheFlag::eACCELERATION. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + - Delta joint DOF velocities can be computed from acceleration * dt. + */ + PxReal* jointAcceleration; + + /** + \brief The articulation joint DOF positions. + + - N = getDofs(). + - Read/write using PxArticulationCacheFlag::ePOSITION. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + - For spherical joints, the joint position for each axis on the joint must be in range [-Pi, Pi]. + */ + PxReal* jointPosition; + + /** + \brief The articulation joint DOF forces. + + - N = getDofs(). + - Read/Write using PxArticulationCacheFlag::eFORCE. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + - Applied joint forces persist and are applied each frame until changed. + */ + PxReal* jointForce; + + /** + \brief The articulation joint drive target positions. + + - N = getDofs(). + - Write using PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + */ + PxReal* jointTargetPositions; + + /** + \brief The articulation joint drive target velocities. + + - N = getDofs(). + - Write using PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES. + - The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + */ + PxReal* jointTargetVelocities; + + /** + \brief Link spatial velocity. + + - N = getNbLinks(). + - Read using PxArticulationCacheFlag::eLINK_VELOCITY. + - The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex. + - The velocity is with respect to the link's center of mass but represented in world space. + + \see PxRigidBody::getCMassLocalPose + */ + PxSpatialVelocity* linkVelocity; + + /** + \brief Link classical acceleration. + + - N = getNbLinks(). + - Read using PxArticulationCacheFlag::eLINK_ACCELERATION. + - The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex. + - The acceleration is with respect to the link's center of mass. + + \see PxArticulationReducedCoordinate::getLinkAcceleration, PxRigidBody::getCMassLocalPose + */ + PxSpatialVelocity* linkAcceleration; + + /** + \brief Link incoming joint force, i.e. the total force transmitted from the parent link to this link. + + - N = getNbLinks(). + - Read using PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE. + - The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex. + - The force is reported in the child joint frame of the link's incoming joint. + + \see PxArticulationJointReducedCoordinate::getChildPose + \note The root link reports a zero spatial force. + */ + PxSpatialForce* linkIncomingJointForce; + + /** + \brief Link force, i.e. an external force applied to the link's center of mass. + + - N = getNbLinks(). + - Write using PxArticulationCacheFlag::eLINK_FORCE. + - The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex. + - The force is given in world space. + */ + PxVec3* linkForce; + + /** + \brief Link torque, i.e. an external torque applied to the link. + + - N = getNbLinks(). + - Write using PxArticulationCacheFlag::eLINK_TORQUE. + - The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex. + - The torque is given in world space. + */ + PxVec3* linkTorque; + + /** + \brief Root link transform, velocities, and accelerations. + + - N = 1. + - Read/write using PxArticulationCacheFlag::eROOT_TRANSFORM and PxArticulationCacheFlag::eROOT_VELOCITIES (accelerations are read-only). + + \see PxArticulationRootLinkData + */ + PxArticulationRootLinkData* rootLinkData; + + // Members and memory below here are not zeroed when zeroCache is called, and are not included in the size returned by PxArticulationReducedCoordinate::getCacheDataSize. + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Constraint coefficient matrix. + + - N = getCoefficentMatrixSize(). + - The user needs to allocate memory and set this member to the allocated memory. + + \see PxArticulationReducedCoordinate::computeCoefficientMatrix + */ + PX_DEPRECATED PxReal* coefficientMatrix; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Constraint lambda values (impulses applied by the respective constraints). + + - N = getNbLoopJoints(). + - The user needs to allocate memory and set this member to the allocated memory. + + \see PxArticulationReducedCoordinate::computeLambda + */ + PX_DEPRECATED PxReal* lambda; + + void* scratchMemory; //!< The scratch memory is used for internal calculations. + void* scratchAllocator; //!< The scratch allocator is used for internal calculations. + PxU32 version; //!< The cache version used internally to check compatibility with the articulation, i.e. detect if the articulation configuration changed after the cache was created. + }; + + + /** + \brief Flag that configures articulation-state updates by PxArticulationReducedCoordinate::updateKinematic. + */ + struct PxArticulationKinematicFlag + { + enum Enum + { + ePOSITION = 1 << 0, //!< Raise after any changes to the articulation root or joint positions using non-cache API calls. Updates links' positions and velocities. + eVELOCITY = 1 << 1 //!< Raise after velocity-only changes to the articulation root or joints using non-cache API calls. Updates links' velocities. + }; + }; + + typedef physx::PxFlags PxArticulationKinematicFlags; + PX_FLAGS_OPERATORS(PxArticulationKinematicFlag::Enum, PxU8) + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + + /** + \brief A tree structure of bodies connected by joints that is treated as a unit by the dynamics solver. Parametrized in reduced (joint) coordinates. + + \see PxArticulationJointReducedCoordinate, PxArticulationLink, PxPhysics::createArticulationReducedCoordinate + */ + class PxArticulationReducedCoordinate : public PxBase + { + public: + + /** + \brief Returns the scene which this articulation belongs to. + + \return Owner Scene. NULL if not part of a scene. + + \see PxScene + */ + virtual PxScene* getScene() const = 0; + + /** + \brief Sets the solver iteration counts for the articulation. + + The solver iteration count determines how accurately contacts, drives, and limits are resolved. + Setting a higher position iteration count may therefore help in scenarios where the articulation + is subject to many constraints; for example, a manipulator articulation with drives and joint limits + that is grasping objects, or several such articulations interacting through contacts. Other situations + where higher position iterations may improve simulation fidelity are: large mass ratios within the + articulation or between the articulation and an object in contact with it; or strong drives in the + articulation being used to manipulate a light object. + + If intersecting bodies are being depenetrated too violently, increase the number of velocity + iterations. More velocity iterations will drive the relative exit velocity of the intersecting + objects closer to the correct value given the restitution. + + \param[in] minPositionIters Number of position iterations the solver should perform for this articulation. Range: [1,255]. Default: 4. + \param[in] minVelocityIters Number of velocity iterations the solver should perform for this articulation. Range: [0,255]. Default: 1 + + \note This call may not be made during simulation. + + \see getSolverIterationCounts() + */ + virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0; + + /** + \brief Returns the solver iteration counts. + + \see setSolverIterationCounts() + */ + virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0; + + /** + \brief Returns true if this articulation is sleeping. + + When an actor does not move for a period of time, it is no longer simulated in order to reduce computational cost. This state + is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object, + or a sleep-affecting property is changed by the user, the entire sleep mechanism should be transparent to the user. + + An articulation can only go to sleep if all links are ready for sleeping. An articulation is guaranteed to be awake + if at least one of the following holds: + + \li The wake counter of any link in the articulation is positive (see #setWakeCounter()). + \li The mass-normalized energy of any link in the articulation is above a threshold (see #setSleepThreshold()). + \li A non-zero force or torque has been applied to any joint or link. + + If an articulation is sleeping, the following state is guaranteed: + + \li The wake counter is zero. + \li The linear and angular velocity of all links is zero. + \li There is no force update pending. + + When an articulation gets inserted into a scene, it will be considered asleep if all the points above hold, else it will + be treated as awake. + + If an articulation is asleep after the call to #PxScene::fetchResults() returns, it is guaranteed that the poses of the + links were not changed. You can use this information to avoid updating the transforms of associated objects. + + \return True if the articulation is sleeping. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation, + except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance. + + \see wakeUp() putToSleep() getSleepThreshold() setSleepThreshold() + */ + virtual bool isSleeping() const = 0; + + /** + \brief Sets the mass-normalized energy threshold below which the articulation may go to sleep. + + The articulation will sleep if the energy of each link is below this threshold. + + \param[in] threshold Energy below which the articulation may go to sleep. Range: [0, PX_MAX_F32) + + \note This call may not be made during simulation. + + Default: 5e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed; + + \see isSleeping() getSleepThreshold() wakeUp() putToSleep() + */ + virtual void setSleepThreshold(PxReal threshold) = 0; + + /** + \brief Returns the mass-normalized energy below which the articulation may go to sleep. + + \return The energy threshold for sleeping. + + \see isSleeping() wakeUp() putToSleep() setSleepThreshold() + */ + virtual PxReal getSleepThreshold() const = 0; + + /** + \brief Sets the mass-normalized kinetic energy threshold below which the articulation may participate in stabilization. + + Articulations whose kinetic energy divided by their mass is above this threshold will not participate in stabilization. + + This value has no effect if PxSceneFlag::eENABLE_STABILIZATION was not enabled on the PxSceneDesc. + + Default: 5e-6f * PxTolerancesScale::speed * PxTolerancesScale::speed + + \param[in] threshold Energy below which the articulation may participate in stabilization. Range: [0,inf) + + \note This call may not be made during simulation. + + \see getStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION + */ + virtual void setStabilizationThreshold(PxReal threshold) = 0; + + /** + \brief Returns the mass-normalized kinetic energy below which the articulation may participate in stabilization. + + Articulations whose kinetic energy divided by their mass is above this threshold will not participate in stabilization. + + \return The energy threshold for participating in stabilization. + + \see setStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION + */ + virtual PxReal getStabilizationThreshold() const = 0; + + /** + \brief Sets the wake counter for the articulation in seconds. + + - The wake counter value specifies a time threshold used to determine whether an articulation may be put to sleep. + - The articulation will be put to sleep if all links have experienced a mass-normalised energy less than a threshold for at least + a threshold time, as specified by the wake counter. + - Passing in a positive value will wake up the articulation automatically. + + Default: 0.4s (which corresponds to 20 frames for a time step of 0.02s) + + \param[in] wakeCounterValue Wake counter value in seconds. Range: [0, PX_MAX_F32) + + \note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance. + + \see isSleeping() getWakeCounter() + */ + virtual void setWakeCounter(PxReal wakeCounterValue) = 0; + + /** + \brief Returns the wake counter of the articulation in seconds. + + \return The wake counter of the articulation in seconds. + + \note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance. + + \see isSleeping() setWakeCounter() + */ + virtual PxReal getWakeCounter() const = 0; + + /** + \brief Wakes up the articulation if it is sleeping. + + - The articulation will be woken up and might cause other touching objects to wake up as well during the next simulation step. + - This will set the wake counter of the articulation to the value specified in #PxSceneDesc::wakeCounterResetValue. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation, + except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance. + + \see isSleeping() putToSleep() + */ + virtual void wakeUp() = 0; + + /** + \brief Forces the articulation to sleep. + + - The articulation will stay asleep during the next simulation step if not touched by another non-sleeping actor. + - This will set any applied force, the velocity, and the wake counter of all bodies in the articulation to zero. + + \note This call may not be made during simulation, and may only be made on articulations that are in a scene. + + \see isSleeping() wakeUp() + */ + virtual void putToSleep() = 0; + + /** + \brief Adds a link to the articulation with default attribute values. + + \param[in] parent The parent link in the articulation. Must be NULL if (and only if) this is the root link. + \param[in] pose The initial pose of the new link. Must be a valid transform. + + \return The new link, or NULL if the link cannot be created. + + \note Creating a link is not allowed while the articulation is in a scene. In order to add a link, + remove and then re-add the articulation to the scene. + + \note When the articulation is added to a scene, the root link adopts the specified pose. The pose of the + root link is propagated through the ensemble of links from parent to child after accounting for each child's + inbound joint frames and the joint positions set by PxArticulationJointReducedCoordinate::setJointPosition(). + As a consequence, the pose of each non-root link is automatically overwritten when adding the articulation to the scene. + + \see PxArticulationLink + */ + virtual PxArticulationLink* createLink(PxArticulationLink* parent, const PxTransform& pose) = 0; + + /** + \brief Releases the articulation, and all its links and corresponding joints. + + Attached mimic joints and tendons are released automatically when the articulation is released. + + \note This call may not be made during simulation. + + \note This call does not release any PxArticulationCache instance that has been instantiated using #createCache() + */ + virtual void release() = 0; + + /** + \brief Returns the number of links in the articulation. + + \return The number of links. + */ + virtual PxU32 getNbLinks() const = 0; + + /** + \brief Returns the set of links in the articulation in the order that they were added to the articulation using createLink. + + The order of the links may be different from the order in which the data is stored in the cache, see PxArticulationLink::getLinkIndex. + + \param[in] userBuffer Buffer into which to write the array of articulation link pointers. + \param[in] bufferSize The size of the buffer. If the buffer is not large enough to contain all the pointers to links, + only as many as will fit are written. + \param[in] startIndex Index of first link pointer to be retrieved. + + \return The number of links written into the buffer. + + \see PxArticulationLink + */ + virtual PxU32 getLinks(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Returns the number of shapes in the articulation. + + \return The number of shapes. + */ + virtual PxU32 getNbShapes() const = 0; + + /** + \brief Sets a name string for the articulation that can be retrieved with getName(). + + This is for debugging and is not used by the SDK. The string is not copied by the SDK, + only the pointer is stored. + + \param[in] name A pointer to a char buffer used to specify the name of the articulation. + + \see getName() + */ + virtual void setName(const char* name) = 0; + + /** + \brief Returns the name string set with setName(). + + \return Name string associated with the articulation. + + \see setName() + */ + virtual const char* getName() const = 0; + + /** + \brief Returns the axis-aligned bounding box enclosing the articulation. + + \param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value. + + \return The articulation's bounding box. + + \note It is not allowed to use this method while the simulation is running, except in a split simulation + during #PxScene::collide() and up to #PxScene::advance(), and in PxContactModifyCallback or in contact report callbacks. + + \see PxBounds3 + */ + virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const = 0; + + /** + \brief Returns the aggregate associated with the articulation. + + \return The aggregate associated with the articulation or NULL if the articulation does not belong to an aggregate. + + \see PxAggregate + */ + virtual PxAggregate* getAggregate() const = 0; + + /** + \brief Sets flags on the articulation. + + \param[in] flags The articulation flags. + + \note This call may not be made during simulation. + + \see PxArticulationFlag + */ + virtual void setArticulationFlags(PxArticulationFlags flags) = 0; + + /** + \brief Raises or clears a flag on the articulation. + + \param[in] flag The articulation flag. + \param[in] value The value to set the flag to. + + \note This call may not be made during simulation. + + \see PxArticulationFlag + */ + virtual void setArticulationFlag(PxArticulationFlag::Enum flag, bool value) = 0; + + /** + \brief Returns the articulation's flags. + + \return The articulation's flags. + + \see PxArticulationFlag + */ + virtual PxArticulationFlags getArticulationFlags() const = 0; + + /** + \brief Returns the total number of joint degrees-of-freedom (DOFs) of the articulation. + + - The six DOFs of the base of a floating-base articulation are not included in this count. + - Example: Both a fixed-base and a floating-base double-pendulum with two revolute joints will have getDofs() == 2. + - The return value is only valid for articulations that are in a scene. + + \return The number of joint DOFs, or 0xFFFFFFFF if the articulation is not in a scene. + + */ + virtual PxU32 getDofs() const = 0; + + /** + \brief Creates an articulation cache that can be used to read and write internal articulation data. + + - When the structure of the articulation changes (e.g. adding a link) after the cache was created, + the cache needs to be released and recreated. + - Free the memory allocated for the cache by calling the release() method on the cache. + - Caches can only be created by articulations that are in a scene. + + \return The cache, or NULL if the articulation is not in a scene. + + \see applyCache, copyInternalStateToCache + */ + virtual PxArticulationCache* createCache() const = 0; + + /** + \brief Returns the size of the articulation cache in bytes. + + - The size does not include: the user-allocated memory for the coefficient matrix or lambda values; + the scratch-related memory/members; and the cache version. See comment in #PxArticulationCache. + - The return value is only valid for articulations that are in a scene. + + \return The byte size of the cache, or 0xFFFFFFFF if the articulation is not in a scene. + + \see PxArticulationCache + */ + virtual PxU32 getCacheDataSize() const = 0; + + /** + \brief Zeroes all data in the articulation cache, except user-provided and scratch memory, and cache version. + + \note This call may only be made on articulations that are in a scene. + + \see PxArticulationCache + */ + virtual void zeroCache(PxArticulationCache& cache) const = 0; + + /** + \brief Applies the data in the cache to the articulation. + + This call wakes the articulation if it is sleeping, and the autowake parameter is true (default) or: + - a nonzero joint velocity is applied or + - a nonzero joint force is applied or + - a nonzero root velocity is applied + + \param[in] cache The articulation data. + \param[in] flags Indicate which data in the cache to apply to the articulation. + \param[in] autowake If true, the call wakes up the articulation and increases the wake counter to #PxSceneDesc::wakeCounterResetValue + if the counter value is below the reset value. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \note Calling applyCache(cache, PxArticulationCacheFlag::eROOT_TRANSFORM) has the same outcome as calling + PxArticulationReducedCoordinate::setRootGlobalPose() followed by PxArticulationReducedCoordinate::updateKinematic(PxArticulationKinematicFlag::ePOSITION). + Similarly, calling applyCache(cache, PxArticulationCacheFlag::eROOT_VELOCITIES) is the cache equivalent of calling + PxArticulationReducedCoordinate::setRootLinearVelocity() followed by PxArticulationReducedCoordinate::updateKinematic(PxArticulationKinematicFlag::eVELOCITY). + Joint positions follow a similar pattern with applyCache(cache, PxArticulationCacheFlag::ePOSITION) having the same outcome as callling + PxArticulationJointReducedCoordinate::setJointPosition() followed by PxArticulationReducedCoordinate::updateKinematic(PxArticulationKinematicFlag::ePOSITION). + Finally, joint velocities updated with applyCache(PxArticulationCacheFlag::eVELOCITY) will produce the same outcome as calling + PxArticulationJointReducedCoordinate::setJointVelocity() followed by PxArticulationReducedCoordinate::updateKinematic(PxArticulationKinematicFlag::eVELOCITY). + + \note This method should not be used if the direct GPU API is enabled. See #PxDirectGPUAPI for the details. + + \see PxArticulationCache, PxArticulationCacheFlags, createCache, copyInternalStateToCache, PxScene::applyArticulationData + */ + virtual void applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags, bool autowake = true) = 0; + + /** + \brief Copies internal data of the articulation to the cache. + + \param[in] cache The articulation data. + \param[in] flags Indicate which data to copy from the articulation to the cache. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \note This method should not be used if the direct GPU API is enabled. See #PxDirectGPUAPI for the details. + + \see PxArticulationCache, PxArticulationCacheFlags, createCache, applyCache + */ + virtual void copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags) const = 0; + + + /** + \brief Converts maximal-coordinate joint DOF data to reduced coordinates. + + - Indexing into the maximal joint DOF data is via the link's low-level index minus 1 (the root link is not included). + - The reduced-coordinate data follows the cache indexing convention, see PxArticulationCache::jointVelocity. + + \param[in] maximum The maximal-coordinate joint DOF data with minimum array length N = (getNbLinks() - 1) * 6 + \param[out] reduced The reduced-coordinate joint DOF data with minimum array length N = getDofs() + + \note The articulation must be in a scene. + + \note This can be used as a helper function to prepare per joint cache data such as PxArticulationCache::jointVelocity. + + \see unpackJointData + */ + virtual void packJointData(const PxReal* maximum, PxReal* reduced) const = 0; + + /** + \brief Converts reduced-coordinate joint DOF data to maximal coordinates. + + - Indexing into the maximal joint DOF data is via the link's low-level index minus 1 (the root link is not included). + - The reduced-coordinate data follows the cache indexing convention, see PxArticulationCache::jointVelocity. + + \param[in] reduced The reduced-coordinate joint DOF data with minimum array length N = getDofs(). + \param[out] maximum The maximal-coordinate joint DOF data with minimum array length N = (getNbLinks() - 1) * 6. + + \note The articulation must be in a scene. + + \see packJointData + */ + virtual void unpackJointData(const PxReal* reduced, PxReal* maximum) const = 0; + + /** + \brief Prepares common articulation data based on articulation pose for inverse dynamics calculations. + + Usage: + -# Set articulation pose (joint positions and base transform) via articulation cache and applyCache(). + -# Call commonInit. + -# Call inverse dynamics computation method. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see computeGravityCompensation, computeCoriolisCompensation, computeGeneralizedExternalForce, computeJointAcceleration, + computeJointForce, computeDenseJacobian, computeMassMatrix + */ + virtual void commonInit() const = 0; + + /** + \deprecated Please use computeGravityCompensation instead. It provides a more complete gravity compensation force for floating-base articulations. + + \brief Computes the joint DOF forces required to counteract gravitational forces for the given articulation pose. + + - Inputs: Articulation pose (joint positions + base transform). + - Outputs: Joint forces to counteract gravity (in cache). + + - The joint forces returned are determined purely by gravity for the articulation in the current joint and base pose, and joints at rest; + i.e. external forces, joint velocities, and joint accelerations are set to zero. Joint drives are also not considered in the computation. + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[out] cache Out: PxArticulationCache::jointForce. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual void computeGeneralizedGravityForce(PxArticulationCache& cache) const = 0; + + /** + \brief Computes the forces required to counteract gravitational forces for the given articulation pose. + + In the case of a fixed-base articulation, the gravity compensation force accounts for the gravity on all the links and provides + the force required to compensate the gravitational forces for all the joint DoFs. + The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + + In the case of a floating-base articulation, the gravity compensation force also accounts for the gravity on the root link and also provides + the force on the root required to compensate its gravitational force. The indexing is: + | Root force X | Root force Y | Root force Z | Root torque X | Root torque Y | Root torque Z | Force/Torque DOF 0 | ... | Force/Torque DOF N | + + - Inputs: Articulation pose (joint positions + base transform). + - Outputs: Forces to counteract gravity (in cache). + + - The joint forces returned are determined purely by gravity for the articulation in the current joint and base pose, and joints at rest; + i.e. external forces, joint velocities, and joint accelerations are set to zero. Joint drives are also not considered in the computation. + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[out] cache Out: PxArticulationCache::gravityCompensationForce. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual void computeGravityCompensation(PxArticulationCache& cache) const = 0; + + /** + \deprecated Please use computeCoriolisCompensation instead. It provides a more complete Coriolis and centrifugal compensation force for floating-base articulations. + + \brief Computes the joint DOF forces required to counteract Coriolis and centrifugal forces for the given articulation state. + + - Inputs: Articulation state (joint positions and velocities (in cache), and base transform and spatial velocity). + - Outputs: Joint forces to counteract Coriolis and centrifugal forces (in cache). + + - The joint forces returned are determined purely by the articulation's state; i.e. external forces, gravity, and joint accelerations are set to zero. + Joint drives and potential damping terms, such as link angular or linear damping, or joint friction, are also not considered in the computation. + - Prior to the computation, update/set the base spatial velocity with PxArticulationCache::rootLinkData and applyCache(). + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[in,out] cache In: PxArticulationCache::jointVelocity; Out: PxArticulationCache::jointForce. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const = 0; + + /** + \brief Computes the joint DOF forces (and root force) required to counteract Coriolis and centrifugal forces for the given articulation state. + + In the case of a fixed-base articulation, the Coriolis and centrifugal compensation force accounts for forces resulting to the current + joint velocities. The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + + In the case of a floating-base articulation, the Coriolis and centrifugal compensation force also accounts for forces resulting to the current + root velocity. The indexing is: + | Root force X | Root force Y | Root force Z | Root torque X | Root torque Y | Root torque Z | Force/Torque DOF 0 | ... | Force/Torque DOF N | + + - Inputs: Articulation state (joint positions and velocities (in cache), and base transform and spatial velocity). + - Outputs: Joint forces (and root force) to counteract Coriolis and centrifugal forces (in cache). + + - The forces returned are determined purely by the articulation's state; i.e. external forces, gravity, and joint accelerations are set to zero. + Joint drives and potential damping terms, such as link angular or linear damping, or joint friction, are also not considered in the computation. + - Prior to the computation, update/set the base spatial velocity with PxArticulationCache::rootLinkData and applyCache(). + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[in,out] cache In: PxArticulationCache::jointVelocity and PxArticulationCache::linkVelocity; Out: PxArticulationCache::coriolisForce. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual void computeCoriolisCompensation(PxArticulationCache& cache) const = 0; + + /** + \brief Computes the joint DOF forces required to counteract external spatial forces applied to articulation links. + + - Inputs: External forces on links (in cache), articulation pose (joint positions + base transform). + - Outputs: Joint forces to counteract the external forces (in cache). + + - Only the external spatial forces provided in the cache and the articulation pose are considered in the computation. + - The external spatial forces are with respect to the links' centers of mass, and not the actor's origin. + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[in,out] cache In: PxArticulationCache::externalForces; Out: PxArticulationCache::jointForce. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual void computeGeneralizedExternalForce(PxArticulationCache& cache) const = 0; + + /** + \brief Computes the joint accelerations for the given articulation state and joint forces. + + - Inputs: Joint forces (in cache) and articulation state (joint positions and velocities (in cache), and base transform and spatial velocity). + - Outputs: Joint accelerations (in cache). + + - The computation includes Coriolis terms and gravity. However, joint drives, external forces, and potential damping (link damping, friction) terms + are not considered in the computation. + - Prior to the computation, update/set the base spatial velocity with PxArticulationCache::rootLinkData and applyCache(). + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[in,out] cache In: PxArticulationCache::jointForce and PxArticulationCache::jointVelocity; Out: PxArticulationCache::jointAcceleration. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual void computeJointAcceleration(PxArticulationCache& cache) const = 0; + + /** + \brief Computes the joint forces for the given articulation pose and joint accelerations, not considering gravity and velocity. + + - Inputs: Joint accelerations (in cache). + - Outputs: Joint forces (in cache). + + - Gravity, Coriolis effects, joint drives and potential damping terms are not considered in the computation + (for example, linear link damping or joint friction). + - To compute the joint force for a different pose, the joint positions and root transform first need to be applied with applyCache() as this function ignores any values set to joint positions and root transform in the cache + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[in,out] cache In: PxArticulationCache::jointAcceleration; Out: PxArticulationCache::jointForce. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual void computeJointForce(PxArticulationCache& cache) const = 0; + + /** + \brief Compute the dense Jacobian for the articulation in world space, including the DOFs of a potentially floating base. + + This computes the dense representation of an inherently sparse matrix. Multiplication with this matrix maps + joint space velocities to world-space linear and angular (i.e. spatial) velocities of the centers of mass of the links. + + \param[out] cache Sets cache.denseJacobian matrix. The matrix is indexed [nCols * row + column]. + \param[out] nRows Set to number of rows in matrix, which corresponds to nbLinks() * 6, minus 6 if PxArticulationFlag::eFIX_BASE is true. + \param[out] nCols Set to number of columns in matrix, which corresponds to the number of joint DOFs, plus 6 in the case PxArticulationFlag::eFIX_BASE is false. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + */ + virtual void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const = 0; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Computes the coefficient matrix for contact forces. + + - The matrix dimension is getCoefficientMatrixSize() = getDofs() * getNbLoopJoints(), and the DOF (column) indexing follows the internal DOF order, see PxArticulationCache::jointVelocity. + - Each column in the matrix is the joint forces effected by a contact based on impulse strength 1. + - The user must allocate memory for PxArticulationCache::coefficientMatrix where the required size of the PxReal array is equal to getCoefficientMatrixSize(). + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[out] cache Out: PxArticulationCache::coefficientMatrix. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit, getCoefficientMatrixSize + */ + virtual PX_DEPRECATED void computeCoefficientMatrix(PxArticulationCache& cache) const = 0; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Computes the lambda values when the test impulse is 1. + + - The user must allocate memory for PxArticulationCache::lambda where the required size of the PxReal array is equal to getNbLoopJoints(). + - commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[out] cache Out: PxArticulationCache::lambda. + \param[in] initialState The initial state of the articulation system. + \param[in] jointTorque M(q)*qddot + C(q,qdot) + g(q) <- calculate by summing joint forces obtained with computeJointForce and computeGeneralizedGravityForce. + \param[in] maxIter Maximum number of solver iterations to run. If the system converges, fewer iterations may be used. + + \return True if convergence was achieved within maxIter; False if convergence was not achieved or the operation failed otherwise. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit, getNbLoopJoints + */ + virtual PX_DEPRECATED bool computeLambda(PxArticulationCache& cache, PxArticulationCache& initialState, const PxReal* const jointTorque, const PxU32 maxIter) const = 0; + + /** + \deprecated Please use computeMassMatrix instead. It provides a more complete mass matrix for floating-base articulations. + + \brief Compute the joint-space inertia matrix that maps joint accelerations to joint forces: forces = M * accelerations. + + - Inputs: Articulation pose (joint positions and base transform). + - Outputs: Mass matrix (in cache). + + commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[out] cache Out: PxArticulationCache::massMatrix. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see commonInit + */ + virtual PX_DEPRECATED void computeGeneralizedMassMatrix(PxArticulationCache& cache) const = 0; + + /** + \brief Compute the mass matrix M that maps accelerations to forces: forces = M * accelerations. + + In the case of a fixed-base articulation, the mass matrix maps joint accelerations to joint forces. + The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity. + + In the case of a floating-base articulation, the mass matrix also includes terms required to map root accelerations + to root forces. The mass matrix should be used with accelerations and forces that follows the indexing below: + | Root force X | | Root linear acceleration X | + | Root force Y | | Root linear acceleration Y | + | Root force Z | | Root linear acceleration Z | + | Root torque X | | Root angular acceleration X | + | Root torque Y | | Root angular acceleration Y | + | Root torque Z | = M | Root angular acceleration Z | + | Force/Torque DOF 0 | | Joint acceleration 0 | + | Force/Torque DOF 1 | | Joint acceleration 1 | + | ... | | ... | + | Force/Torque DOF N | | Joint acceleration N | + + - Inputs: Articulation pose (joint positions and base transform). + - Outputs: Mass matrix (in cache). + + commonInit() must be called before the computation, and after setting the articulation pose via applyCache(). + + \param[out] cache Out: PxArticulationCache::massMatrix. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + \note The mass matrix is indexed [nCols * row + column]. + + \see commonInit, PxArticulationCache::massMatrix + */ + virtual void computeMassMatrix(PxArticulationCache& cache) const = 0; + + /** + \brief Compute the articulation's center of mass. + + \return The articulation's center of mass given either in the world frame (rootFrame = false) or in the root frame + (rootFrame = true). PxVec3(0.0f) is returned if the articulation is not in a scene or the call is made during simulation. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + */ + virtual PxVec3 computeArticulationCOM(const bool rootFrame = false) const = 0; + + /** + \brief Compute the centroidal momentum matrix and corresponding bias force of an articulation. + + - Inputs: Articulation state (joint positions and velocities, and base transform and spatial velocity), + articulation mass matrix, Coriolis and Centrifugal compensation forces. + - Outputs: Centroidal momentum matrix and bias force (in cache). + + commonInit(), computeMassMatrix() and computeCoriolisCompensation() must be called before the computation, + and after setting the articulation pose and velocities via applyCache(). + + \param[out] cache Out: PxArticulationCache::centroidalMomentumMatrix and PxArticulationCache::centroidalMomentumBias. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + This call may also only be made for floating-base articulations. + + \see commonInit, computeMassMatrix, computeCoriolisCompensation + */ + virtual void computeCentroidalMomentumMatrix(PxArticulationCache& cache) const = 0; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Adds a loop joint to the articulation system for inverse dynamics. + + \param[in] joint The joint to add. + + \note This call may not be made during simulation. + + \see PxFixedJoint, PxSphericalJoint, PxRevoluteJoint, PxPrismaticJoint, PxDistanceJoint, PxD6Joint + */ + virtual PX_DEPRECATED void addLoopJoint(PxConstraint* joint) = 0; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Removes a loop joint from the articulation for inverse dynamics. + + \note This call may not be made during simulation. + + \param[in] joint The joint to remove. + */ + virtual PX_DEPRECATED void removeLoopJoint(PxConstraint* joint) = 0; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Returns the number of loop joints in the articulation for inverse dynamics. + + \return The number of loop joints. + */ + virtual PX_DEPRECATED PxU32 getNbLoopJoints() const = 0; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + \brief Returns the set of loop constraints (i.e. joints) in the articulation. + + \param[in] userBuffer Target buffer for the constraint pointers. + \param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to the constraints, + only as many as will fit are written. Use getNbLoopJoints() to size the buffer for retrieving all constraints. + \param[in] startIndex Index of first constraint pointer to be retrieved. + + \return The number of constraints written into the buffer. + */ + virtual PX_DEPRECATED PxU32 getLoopJoints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \deprecated The API related to loop joints will be removed in a future version once a replacement is made available. + + \brief Returns the required size of the coefficient matrix in the articulation. + + \return Size of the coefficient matrix (equal to getDofs() * getNbLoopJoints()). + + \note This call may only be made on articulations that are in a scene. + + \see computeCoefficientMatrix + */ + virtual PX_DEPRECATED PxU32 getCoefficientMatrixSize() const = 0; + + /** + \brief Sets the root link transform in the world frame. + + - Use updateKinematic() after all state updates to the articulation via non-cache API such as this method, + in order to update link states for the next simulation frame or querying. + + \param[in] pose The new root link transform. + \param[in] autowake If true and the articulation is in a scene, the articulation will be woken up and the wake counter of + each link will be reset to #PxSceneDesc::wakeCounterResetValue. + + \note This call may not be made during simulation. + + \note PxArticulationCache::rootLinkData similarly allows the root link pose to be updated and potentially offers better performance + if the root link pose is to be updated along with other state variables. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getRootGlobalPose, updateKinematic, PxArticulationCache, applyCache + */ + virtual void setRootGlobalPose(const PxTransform& pose, bool autowake = true) = 0; + + /** + \brief Returns the root link transform (world to actor frame). + + \return The root link transform. + + \note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(), + and in PxContactModifyCallback or in contact report callbacks. + + \note PxArticulationCache::rootLinkData similarly allows the root link pose to be queried and potentially offers better performance if the root + link pose is to be queried along with other state variables. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setRootGlobalPose, PxArticulationCache, copyInternalStateToCache + */ + virtual PxTransform getRootGlobalPose() const = 0; + + /** + \brief Sets the root link linear center-of-mass velocity. + + - The linear velocity is with respect to the link's center of mass and not the actor frame origin. + - The articulation is woken up if the input velocity is nonzero (ignoring autowake) and the articulation is in a scene. + - Use updateKinematic() after all state updates to the articulation via non-cache API such as this method, + in order to update link states for the next simulation frame or querying. + + \param[in] linearVelocity The new root link center-of-mass linear velocity. + \param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter + to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value. + + \note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance. + + \note PxArticulationCache::rootLinkData similarly allows the root link linear velocity to be updated and potentially offers better performance + if the root link linear velocity is to be updated along with other state variables. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see updateKinematic, getRootLinearVelocity, setRootAngularVelocity, getRootAngularVelocity, PxRigidBody::getCMassLocalPose, PxArticulationCache, applyCache + */ + virtual void setRootLinearVelocity(const PxVec3& linearVelocity, bool autowake = true) = 0; + + /** + \brief Gets the root link center-of-mass linear velocity. + + - The linear velocity is with respect to the link's center of mass and not the actor frame origin. + + \return The root link center-of-mass linear velocity. + + \note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(), + and in PxContactModifyCallback or in contact report callbacks. + + \note PxArticulationCache::rootLinkData similarly allows the root link linear velocity to be queried and potentially offers better performance + if the root link linear velocity is to be queried along with other state variables. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setRootLinearVelocity, setRootAngularVelocity, getRootAngularVelocity, PxRigidBody::getCMassLocalPose, PxArticulationCache, applyCache + */ + virtual PxVec3 getRootLinearVelocity() const = 0; + + /** + \brief Sets the root link angular velocity. + + - The articulation is woken up if the input velocity is nonzero (ignoring autowake) and the articulation is in a scene. + - Use updateKinematic() after all state updates to the articulation via non-cache API such as this method, + in order to update link states for the next simulation frame or querying. + + \param[in] angularVelocity The new root link angular velocity. + \param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter + to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value. + + \note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance. + + \note PxArticulationCache::rootLinkData similarly allows the root link angular velocity to be updated and potentially offers better performance + if the root link angular velocity is to be updated along with other state variables. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see updateKinematic, getRootAngularVelocity, setRootLinearVelocity, getRootLinearVelocity, PxArticulationCache, applyCache + */ + virtual void setRootAngularVelocity(const PxVec3& angularVelocity, bool autowake = true) = 0; + + /** + \brief Gets the root link angular velocity. + + \return The root link angular velocity. + + \note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(), + and in PxContactModifyCallback or in contact report callbacks. + + \note PxArticulationCache::rootLinkData similarly allows the root link angular velocity to be queried and potentially offers better performance + if the root link angular velocity is to be queried along with other state variables. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setRootAngularVelocity, setRootLinearVelocity, getRootLinearVelocity, PxArticulationCache, applyCache + */ + virtual PxVec3 getRootAngularVelocity() const = 0; + + /** + \brief Returns the (classical) link acceleration in world space for the given low-level link index. + + - The returned acceleration is not a spatial, but a classical, i.e. body-fixed acceleration (https://en.wikipedia.org/wiki/Spatial_acceleration). + - The (linear) acceleration is with respect to the link's center of mass and not the actor frame origin. + + \param[in] linkId The low-level link index, see PxArticulationLink::getLinkIndex. + + \return The link's center-of-mass classical acceleration, or 0 if the call is made before the articulation participated in a first simulation step. + + \note This call may only be made on articulations that are in a scene. It is not allowed to use this method while the simulation + is running. The exceptions to this rule are a split simulation during #PxScene::collide() and up to #PxScene::advance(); + in PxContactModifyCallback; and in contact report callbacks. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationLink::getLinkIndex, PxRigidBody::getCMassLocalPose + */ + virtual PxSpatialVelocity getLinkAcceleration(const PxU32 linkId) = 0; + + /** + \brief Returns the GPU articulation index. + + \return The GPU index, or 0xFFFFFFFF if the articulation is not in a scene. + */ + virtual PxArticulationGPUIndex getGPUIndex() const = 0; + + /** + \brief Creates a spatial tendon to attach to the articulation with default attribute values. + + \return The new spatial tendon. + + \note Creating a spatial tendon is not allowed while the articulation is in a scene. In order to + add the tendon, remove and then re-add the articulation to the scene. + + \note The spatial tendon is released with PxArticulationReducedCoordinate::release() + + \see PxArticulationSpatialTendon + */ + virtual PxArticulationSpatialTendon* createSpatialTendon() = 0; + + /** + \brief Creates a fixed tendon to attach to the articulation with default attribute values. + + \return The new fixed tendon. + + \note Creating a fixed tendon is not allowed while the articulation is in a scene. In order to + add the tendon, remove and then re-add the articulation to the scene. + + \note The fixed tendon is released with PxArticulationReducedCoordinate::release() + + \see PxArticulationFixedTendon + */ + virtual PxArticulationFixedTendon* createFixedTendon() = 0; + + /** + \brief Returns the spatial tendons attached to the articulation. + + The order of the tendons in the buffer is not necessarily identical to the order in which the tendons were added to the articulation. + + \param[in] userBuffer The buffer into which to write the array of pointers to the tendons. + \param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to tendons, + only as many as will fit are written. Use getNbSpatialTendons to size for all attached tendons. + \param[in] startIndex Index of first tendon pointer to be retrieved. + + \return The number of tendons written into the buffer. + + \see PxArticulationSpatialTendon, getNbSpatialTendons + */ + virtual PxU32 getSpatialTendons(PxArticulationSpatialTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Returns the number of spatial tendons in the articulation. + + \return The number of tendons. + */ + virtual PxU32 getNbSpatialTendons() const = 0; + + /** + \brief Returns the fixed tendons attached to the articulation. + + The order of the tendons in the buffer is not necessarily identical to the order in which the tendons were added to the articulation. + + \param[in] userBuffer The buffer into which to write the array of pointers to the tendons. + \param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to tendons, + only as many as will fit are written. Use getNbFixedTendons to size for all attached tendons. + \param[in] startIndex Index of first tendon pointer to be retrieved. + + \return The number of tendons written into the buffer. + + \see PxArticulationFixedTendon, getNbFixedTendons + */ + virtual PxU32 getFixedTendons(PxArticulationFixedTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Returns the number of fixed tendons in the articulation. + + \return The number of tendons. + */ + virtual PxU32 getNbFixedTendons() const = 0; + + /** + \brief Create a mimic joint that will enforce a relationship between two joints. + \param[in] jointA is the first joint of the joint pair controlled by the mimic joint. + \param[in] axisA specifies the degree of freedom of jointA that will be controlled by the mimic joint. + \param[in] jointB is the second joint of the joint pair controlled by the mimic joint. + \param[in] axisB specifies the degree of freedom of jointB that will be controlled by the mimic joint. + \param[in] gearRatio is the gearing ratio enforced by the mimic joint. + \param[in] naturalFrequency specifies the oscillation frequency of the mimic joint's compliance, specified in s^-1. + \param[in] dampingRatio specifies the damping ratio of the mimic joint's compliance. + \param[in] offset is the offset enforced by the mimic joint. + \note If naturalFrequency is less than or equal to zero it is assumed that the mimic joint has no compliance and is a hard constraint. + \note If dampingRatio is less than or equal to zero it is assumed that the mimic joint has no compliance and is a hard constraint. + \note In the absence of compliance, the mimic joint enforces the rule: qA + gearRatio*qB + offset = 0 with qA denoting the + joint position of the specified degree of freedom of jointA and qB denoting the joint position of the specified degree of freedom of jointB. + \note Larger values of naturalFrequency and dampingRatio will make the mimic joint stiffer and more akin to a hard constraint. + \note A damping ratio less than 1.0 is not recommended. + \note If dampingRatio is less than or equal to zero and naturalFrequency greater than zero, the mimic joint will behave as a hard constraint. + If dampingRatio is greater than zero and naturalFrequency less than or equal to zero, the mimic joint will also behave as a hard constraint. + */ + virtual PxArticulationMimicJoint* createMimicJoint( + const PxArticulationJointReducedCoordinate& jointA, PxArticulationAxis::Enum axisA, + const PxArticulationJointReducedCoordinate& jointB, PxArticulationAxis::Enum axisB, + PxReal gearRatio, PxReal offset, + PxReal naturalFrequency = 0.0f, PxReal dampingRatio = 0.0f) = 0; + + /** + \brief Returns the mimic joints added to the articulation. + + The order of the mimic joints in the buffer is not necessarily identical to the order in which the mimic joints were added to the articulation. + + \param[in] userBuffer The buffer into which to write the array of pointers to the mimic joints. + \param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to mimic joints, + only as many as will fit are written. Use getNbMimicJoints() to size for all attached mimic joints. + \param[in] startIndex Index of first mimic joints pointer to be retrieved. + + \return The number of mimic joints written into the buffer. + + \see PxArticulationMimicJoint, getNbMimicJoints + */ + virtual PxU32 getMimicJoints(PxArticulationMimicJoint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Returns the number of mimic joints in the articulation. + \return The number of mimic joints. + */ + virtual PxU32 getNbMimicJoints() const = 0; + + + /** + \brief Update link velocities and/or positions in the articulation. + + An alternative that potentially offers better performance is to use the PxArticulationCache API. + + If the application updates the root state (position and velocity) or joint state via any combination of + the non-cache API calls + + - setRootGlobalPose(), setRootLinearVelocity(), setRootAngularVelocity() + - PxArticulationJointReducedCoordinate::setJointPosition(), PxArticulationJointReducedCoordinate::setJointVelocity() + + the application needs to call this method after the state setting in order to update the link states for + the next simulation frame or querying. + + Use + - PxArticulationKinematicFlag::ePOSITION after any changes to the articulation root or joint positions using non-cache API calls. Updates links' positions and velocities. + - PxArticulationKinematicFlag::eVELOCITY after velocity-only changes to the articulation root or joints using non-cache API calls. Updates links' velocities only. + + \note This call may only be made on articulations that are in a scene, and may not be made during simulation. + + \see PxArticulationKinematicFlags, PxArticulationCache, applyCache + */ + virtual void updateKinematic(PxArticulationKinematicFlags flags) = 0; + + /** + \brief Returns the internal residual for this articulation (does not include collision or external joint residual values). + + The residual represents the current error in this constraint measured as the delta impulse applied in the last velocity or position iteration. + If the solver converges perfectly, the residual should approach zero. + + \return The residual for the articulation solver. + + \see PxArticulationResidual + */ + virtual PxArticulationResidual getSolverResidual() const = 0; + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationReducedCoordinate"; } + + virtual ~PxArticulationReducedCoordinate() {} + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + + protected: + PX_INLINE PxArticulationReducedCoordinate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxArticulationReducedCoordinate(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationReducedCoordinate", PxBase); } + }; + +#if PX_VC +#pragma warning(pop) +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationTendon.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationTendon.h new file mode 100644 index 000000000..062d3f380 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationTendon.h @@ -0,0 +1,630 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef PX_ARTICULATION_TENDON_H +#define PX_ARTICULATION_TENDON_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" +#include "solver/PxSolverDefs.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + class PxArticulationSpatialTendon; + class PxArticulationFixedTendon; + class PxArticulationLink; + /** + \brief Defines the low/high limits of the length of a tendon. + */ + class PxArticulationTendonLimit + { + public: + PxReal lowLimit; + PxReal highLimit; + }; + + /** + \brief Defines a spatial tendon attachment point on a link. + */ + class PxArticulationAttachment : public PxBase + { + + public: + + virtual ~PxArticulationAttachment() {} + /** + \brief Sets the spring rest length for the sub-tendon from the root to this leaf attachment. + + Setting this on non-leaf attachments has no effect. + + \param[in] restLength The rest length of the spring. + Default: 0 + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getRestLength(), isLeaf() + */ + virtual void setRestLength(const PxReal restLength) = 0; + + /** + \brief Gets the spring rest length for the sub-tendon from the root to this leaf attachment. + + \return The rest length. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setRestLength() + */ + virtual PxReal getRestLength() const = 0; + + /** + \brief Sets the low and high limit on the length of the sub-tendon from the root to this leaf attachment. + + Setting this on non-leaf attachments has no effect. + + \param[in] parameters Struct with the low and high limit. + Default: (PX_MAX_F32, -PX_MAX_F32) (i.e. an invalid configuration that can only work if stiffness is zero) + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationTendonLimit, getLimitParameters(), isLeaf() + */ + virtual void setLimitParameters(const PxArticulationTendonLimit& parameters) = 0; + + /** + \brief Gets the low and high limit on the length of the sub-tendon from the root to this leaf attachment. + + \return Struct with the low and high limit. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationTendonLimit, setLimitParameters() + */ + virtual PxArticulationTendonLimit getLimitParameters() const = 0; + + /** + \brief Sets the attachment's relative offset in the link actor frame. + + \param[in] offset The relative offset in the link actor frame. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getRelativeOffset() + */ + virtual void setRelativeOffset(const PxVec3& offset) = 0; + + /** + \brief Gets the attachment's relative offset in the link actor frame. + + \return The relative offset in the link actor frame. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setRelativeOffset() + */ + virtual PxVec3 getRelativeOffset() const = 0; + + /** + \brief Sets the attachment coefficient. + + \param[in] coefficient The scale that the distance between this attachment and its parent is multiplied by when summing up the spatial tendon's length. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getCoefficient() + */ + virtual void setCoefficient(const PxReal coefficient) = 0; + + /** + \brief Gets the attachment coefficient. + + \return The scale that the distance between this attachment and its parent is multiplied by when summing up the spatial tendon's length. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setCoefficient() + */ + virtual PxReal getCoefficient() const = 0; + + /** + \brief Gets the articulation link. + + \return The articulation link that this attachment is attached to. + */ + virtual PxArticulationLink* getLink() const = 0; + + /** + \brief Gets the parent attachment. + + \return The parent attachment. + */ + virtual PxArticulationAttachment* getParent() const = 0; + + /** + \brief Indicates that this attachment is a leaf, and thus defines a sub-tendon from the root to this attachment. + + \return True: This attachment is a leaf and has zero children; False: Not a leaf. + */ + virtual bool isLeaf() const = 0; + + /** + \brief Gets the spatial tendon that the attachment is a part of. + + \return The tendon. + + \see PxArticulationSpatialTendon + */ + virtual PxArticulationSpatialTendon* getTendon() const = 0; + + /** + \brief Releases the attachment. + + \note Releasing the attachment is not allowed while the articulation is in a scene. In order to + release the attachment, remove and then re-add the articulation to the scene. + + \see PxArticulationSpatialTendon::createAttachment() + */ + virtual void release() = 0; + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationAttachment"; } + + protected: + + PX_INLINE PxArticulationAttachment(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxArticulationAttachment(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + }; + + + /** + \brief Defines a fixed-tendon joint on an articulation joint degree of freedom. + */ + class PxArticulationTendonJoint : public PxBase + { + + public: + + virtual ~PxArticulationTendonJoint() {} + + /** + \brief Sets the tendon joint coefficient. + + \param[in] axis The degree of freedom that the tendon joint operates on (must correspond to a degree of freedom of the associated link's incoming joint). + \param[in] coefficient The scale that the axis' joint position is multiplied by when summing up the fixed tendon's length. + \param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint. + + \note RecipCoefficient is commonly expected to be 1/coefficient, but it can be set to different values to tune behavior; for example, zero can be used to + have a joint axis only participate in the length computation of the tendon, but not have any tendon force applied to it. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getCoefficient() + */ + virtual void setCoefficient(const PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient) = 0; + + /** + \brief Gets the tendon joint coefficient. + + \param[out] axis The degree of freedom that the tendon joint operates on. + \param[out] coefficient The scale that the axis' joint position is multiplied by when summing up the fixed tendon's length. + \param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setCoefficient() + */ + virtual void getCoefficient(PxArticulationAxis::Enum& axis, PxReal& coefficient, PxReal& recipCoefficient) const = 0; + + /** + \brief Gets the articulation link. + + \return The articulation link (and its incoming joint in particular) that this tendon joint is associated with. + */ + virtual PxArticulationLink* getLink() const = 0; + + /** + \brief Gets the parent tendon joint. + + \return The parent tendon joint. + */ + virtual PxArticulationTendonJoint* getParent() const = 0; + + /** + \brief Gets the tendon that the joint is a part of. + + \return The tendon. + + \see PxArticulationFixedTendon + */ + virtual PxArticulationFixedTendon* getTendon() const = 0; + + /** + \brief Releases a tendon joint. + + \note Releasing a tendon joint is not allowed while the articulation is in a scene. In order to + release the joint, remove and then re-add the articulation to the scene. + + \see PxArticulationFixedTendon::createTendonJoint() + */ + virtual void release() = 0; + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationTendonJoint"; } + + protected: + + PX_INLINE PxArticulationTendonJoint(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxArticulationTendonJoint(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + }; + + + /** + \brief Common API base class shared by PxArticulationSpatialTendon and PxArticulationFixedTendon. + */ + class PxArticulationTendon : public PxBase + { + public: + /** + \brief Sets the spring stiffness term acting on the tendon length. + + \param[in] stiffness The spring stiffness. + Default: 0 + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getStiffness() + */ + virtual void setStiffness(const PxReal stiffness) = 0; + + /** + \brief Gets the spring stiffness of the tendon. + + \return The spring stiffness. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setStiffness() + */ + virtual PxReal getStiffness() const = 0; + + /** + \brief Sets the damping term acting both on the tendon length and tendon-length limits. + + \param[in] damping The damping term. + Default: 0 + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getDamping() + */ + virtual void setDamping(const PxReal damping) = 0; + + /** + \brief Gets the damping term acting both on the tendon length and tendon-length limits. + + \return The damping term. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setDamping() + */ + virtual PxReal getDamping() const = 0; + + /** + \brief Sets the limit stiffness term acting on the tendon's length limits. + + For spatial tendons, this parameter applies to all its leaf attachments / sub-tendons. + + \param[in] stiffness The limit stiffness term. + Default: 0 + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getLimitStiffness() + */ + virtual void setLimitStiffness(const PxReal stiffness) = 0; + + /** + \brief Gets the limit stiffness term acting on the tendon's length limits. + + For spatial tendons, this parameter applies to all its leaf attachments / sub-tendons. + + \return The limit stiffness term. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setLimitStiffness() + */ + virtual PxReal getLimitStiffness() const = 0; + + /** + \brief Sets the length offset term for the tendon. + + An offset defines an amount to be added to the accumulated length computed for the tendon. It allows the + application to actuate the tendon by shortening or lengthening it. + + \param[in] offset The offset term. Default: 0 + \param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter + to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getOffset() + */ + virtual void setOffset(const PxReal offset, bool autowake = true) = 0; + + /** + \brief Gets the length offset term for the tendon. + + \return The offset term. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setOffset() + */ + virtual PxReal getOffset() const = 0; + + /** + \brief Gets the articulation that the tendon is a part of. + + \return The articulation. + + \see PxArticulationReducedCoordinate + */ + virtual PxArticulationReducedCoordinate* getArticulation() const = 0; + + /** + \brief Releases a tendon to remove it from the articulation and free its associated memory. + + When an articulation is released, its attached tendons are automatically released. + + \note Releasing a tendon is not allowed while the articulation is in a scene. In order to + release the tendon, remove and then re-add the articulation to the scene. + */ + + virtual void release() = 0; + + virtual ~PxArticulationTendon() {} + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + + protected: + PX_INLINE PxArticulationTendon(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxArticulationTendon(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + }; + + /** + \brief A spatial tendon that attaches to an articulation. + + A spatial tendon attaches to multiple links in an articulation using a set of PxArticulationAttachments. + The tendon is defined as a tree of attachment points, where each attachment can have an arbitrary number of children. + Each leaf of the attachment tree defines a subtendon between itself and the root attachment. The subtendon then + applies forces at the leaf, and an equal but opposing force at the root, in order to satisfy the spring-damper and limit + constraints that the user sets up. Attachments in between the root and leaf do not exert any force on the articulation, + but define the geometry of the tendon from which the length is computed together with the attachment coefficients. + */ + class PxArticulationSpatialTendon : public PxArticulationTendon + { + public: + /** + \brief Creates an articulation attachment and adds it to the list of children in the parent attachment. + + Creating an attachment is not allowed while the articulation is in a scene. In order to + add the attachment, remove and then re-add the articulation to the scene. + + \param[in] parent The parent attachment. Can be NULL for the root attachment of a tendon. + \param[in] coefficient A user-defined scale that the accumulated length is scaled by. + \param[in] relativeOffset An offset vector in the link's actor frame to the point where the tendon attachment is attached to the link. + \param[in] link The link that this attachment is associated with. + + \return The newly-created attachment if creation was successful, otherwise a null pointer. + + \see releaseAttachment() + */ + virtual PxArticulationAttachment* createAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link) = 0; + + /** + \brief Fills a user-provided buffer of attachment pointers with the set of attachments. + + \param[in] userBuffer The user-provided buffer. + \param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to attachments, + only as many as can fit are written. Use getNbAttachments to size for all attachments. + \param[in] startIndex Index of first attachment pointer to be retrieved. + + \return The number of attachments that were filled into the user buffer. + + \see getNbAttachments + */ + virtual PxU32 getAttachments(PxArticulationAttachment** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Returns the number of attachments in the tendon. + + \return The number of attachments. + */ + virtual PxU32 getNbAttachments() const = 0; + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationSpatialTendon"; } + + virtual ~PxArticulationSpatialTendon() {} + + protected: + PX_INLINE PxArticulationSpatialTendon(PxType concreteType, PxBaseFlags baseFlags) : PxArticulationTendon(concreteType, baseFlags) {} + PX_INLINE PxArticulationSpatialTendon(PxBaseFlags baseFlags) : PxArticulationTendon(baseFlags) {} + + }; + + /** + \brief A fixed tendon that can be used to link multiple degrees of freedom of multiple articulation joints via length and limit constraints. + + Fixed tendons allow the simulation of coupled relationships between joint degrees of freedom in an articulation. Fixed tendons do not allow + linking arbitrary joint axes of the articulation: The respective joints must all be directly connected to each other in the articulation structure, + i.e. each of the joints in the tendon must be connected by a single articulation link to another joint in the same tendon. This implies both that + 1) fixed tendons can branch along a branching articulation; and 2) they cannot be used to create relationships between axes in a spherical joint with + more than one degree of freedom. Locked joint axes or fixed joints are currently not supported. + */ + class PxArticulationFixedTendon : public PxArticulationTendon + { + public: + /** + \brief Creates an articulation tendon joint and adds it to the list of children in the parent tendon joint. + + Creating a tendon joint is not allowed while the articulation is in a scene. In order to + add the joint, remove and then re-add the articulation to the scene. + + \param[in] parent The parent tendon joint. Can be NULL for the root tendon joint of a tendon. + \param[in] axis The degree of freedom that this tendon joint is associated with. + \param[in] coefficient A user-defined scale that the accumulated tendon length is scaled by. + \param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint. + \param[in] link The link (and the link's incoming joint in particular) that this tendon joint is associated with. + + \return The newly-created tendon joint if creation was successful, otherwise a null pointer. + + \note + - The axis motion must not be configured as PxArticulationMotion::eLOCKED. + - The axis cannot be part of a fixed joint, i.e. joint configured as PxArticulationJointType::eFIX. + + \see PxArticulationTendonJoint PxArticulationAxis + */ + virtual PxArticulationTendonJoint* createTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link) = 0; + + /** + \brief Fills a user-provided buffer of tendon-joint pointers with the set of tendon joints. + + \param[in] userBuffer The user-provided buffer. + \param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to tendon joints, + only as many as can fit are written. Use getNbTendonJoints to size for all tendon joints. + \param[in] startIndex Index of first tendon joint pointer to be retrieved. + + \return The number of tendon joints filled into the user buffer. + + \see getNbTendonJoints + */ + virtual PxU32 getTendonJoints(PxArticulationTendonJoint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Returns the number of tendon joints in the tendon. + + \return The number of tendon joints. + */ + virtual PxU32 getNbTendonJoints() const = 0; + + /** + \brief Sets the spring rest length of the tendon. + + The accumulated "length" of a fixed tendon is a linear combination of the joint axis positions that the tendon is + associated with, scaled by the respective tendon joints' coefficients. As such, when the joint positions of all + joints are zero, the accumulated length of a fixed tendon is zero. + + The spring of the tendon is not exerting any force on the articulation when the rest length is equal to the + tendon's accumulated length plus the tendon offset. + + \param[in] restLength The spring rest length of the tendon. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see getRestLength() + */ + virtual void setRestLength(const PxReal restLength) = 0; + + /** + \brief Gets the spring rest length of the tendon. + + \return The spring rest length of the tendon. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see setRestLength() + */ + virtual PxReal getRestLength() const = 0; + + /** + \brief Sets the low and high limit on the length of the tendon. + + \param[in] parameter Struct with the low and high limit. + + The limits, together with the damping and limit stiffness parameters, act on the accumulated length of the tendon. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationTendonLimit getLimitParameters() setRestLength() + */ + virtual void setLimitParameters(const PxArticulationTendonLimit& parameter) = 0; + + + /** + \brief Gets the low and high limit on the length of the tendon. + + \return Struct with the low and high limit. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \see PxArticulationTendonLimit setLimitParameters() + */ + virtual PxArticulationTendonLimit getLimitParameters() const = 0; + + /** + \brief Returns the string name of the dynamic type. + + \return The string name. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxArticulationFixedTendon"; } + + virtual ~PxArticulationFixedTendon() {} + + protected: + PX_INLINE PxArticulationFixedTendon(PxType concreteType, PxBaseFlags baseFlags) : PxArticulationTendon(concreteType, baseFlags) {} + PX_INLINE PxArticulationFixedTendon(PxBaseFlags baseFlags) : PxArticulationTendon(baseFlags) {} + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationTendonData.h b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationTendonData.h new file mode 100644 index 000000000..7a00bcc97 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxArticulationTendonData.h @@ -0,0 +1,120 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef PX_ARTICULATION_TENDON_DATA_H +#define PX_ARTICULATION_TENDON_DATA_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief PxGpuSpatialTendonData + +This data structure is to be used by the direct GPU API for spatial tendon data updates. + +\see PxArticulationSpatialTendon PxDirectGPUAPI::getArticulationData PxDirectGPUAPI::setArticulationData +*/ +PX_ALIGN_PREFIX(16) +class PxGpuSpatialTendonData +{ +public: + PxReal stiffness; + PxReal damping; + PxReal limitStiffness; + PxReal offset; +} +PX_ALIGN_SUFFIX(16); + +/** +\brief PxGpuFixedTendonData + +This data structure is to be used by the direct GPU API for fixed tendon data updates. + +\see PxArticulationFixedTendon PxDirectGPUAPI::getArticulationData PxDirectGPUAPI::setArticulationData +*/ +PX_ALIGN_PREFIX(16) +class PxGpuFixedTendonData : public PxGpuSpatialTendonData +{ +public: + PxReal lowLimit; + PxReal highLimit; + PxReal restLength; + PxReal padding; +} +PX_ALIGN_SUFFIX(16); + +/** +\brief PxGpuTendonJointCoefficientData + +This data structure is to be used by the direct GPU API for fixed tendon joint data updates. + +\see PxArticulationTendonJoint PxDirectGPUAPI::getArticulationData PxDirectGPUAPI::setArticulationData +*/ +PX_ALIGN_PREFIX(16) +class PxGpuTendonJointCoefficientData +{ +public: + PxReal coefficient; + PxReal recipCoefficient; + PxU32 axis; + PxU32 pad; +} +PX_ALIGN_SUFFIX(16); + +/** +\brief PxGpuTendonAttachmentData + +This data structure is to be used by the direct GPU API for spatial tendon attachment data updates. + +\see PxArticulationAttachment PxDirectGPUAPI::getArticulationData PxDirectGPUAPI::setArticulationData +*/ +PX_ALIGN_PREFIX(16) +class PxGpuTendonAttachmentData +{ +public: + PxVec3 relativeOffset; + PxReal restLength; + + PxReal coefficient; + PxReal lowLimit; + PxReal highLimit; + PxReal padding; +} +PX_ALIGN_SUFFIX(16); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxBaseMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxBaseMaterial.h new file mode 100644 index 000000000..9534992b6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxBaseMaterial.h @@ -0,0 +1,60 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BASE_MATERIAL_H +#define PX_BASE_MATERIAL_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Base material class. + + \see PxPhysics.createMaterial PxPhysics.createDeformableSurfaceMaterial PxPhysics.createDeformableVolumeMaterial PxPhysics.createPBDMaterial + */ + class PxBaseMaterial : public PxRefCounted + { + public: + PX_INLINE PxBaseMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags), userData(NULL) {} + PX_INLINE PxBaseMaterial(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + virtual ~PxBaseMaterial() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBaseMaterial", PxRefCounted); } + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxBroadPhase.h b/Jusin154_Team3D/Engine/Public/PhysX/PxBroadPhase.h new file mode 100644 index 000000000..309e7080f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxBroadPhase.h @@ -0,0 +1,802 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BROAD_PHASE_H +#define PX_BROAD_PHASE_H + +#include "PxPhysXConfig.h" +#include "foundation/PxBounds3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxBaseTask; + class PxCudaContextManager; + class PxAllocatorCallback; + + /** + \brief Broad phase algorithm used in the simulation + + eSAP is a good generic choice with great performance when many objects are sleeping. Performance + can degrade significantly though, when all objects are moving, or when large numbers of objects + are added to or removed from the broad phase. This algorithm does not need world bounds to be + defined in order to work. + + eMBP is an alternative broad phase algorithm that does not suffer from the same performance + issues as eSAP when all objects are moving or when inserting large numbers of objects. However + its generic performance when many objects are sleeping might be inferior to eSAP, and it requires + users to define world bounds in order to work. + + eABP is a revisited implementation of MBP, which automatically manages broad-phase regions. + It offers the convenience of eSAP (no need to define world bounds or regions) and the performance + of eMBP when a lot of objects are moving. While eSAP can remain faster when most objects are + sleeping and eMBP can remain faster when it uses a large number of properly-defined regions, + eABP often gives the best performance on average and the best memory usage. + + ePABP is a parallel implementation of ABP. It can often be the fastest (CPU) broadphase, but it + can use more memory than ABP. + + eGPU is a GPU implementation of the incremental sweep and prune approach. Additionally, it uses a ABP-style + initial pair generation approach to avoid large spikes when inserting shapes. It not only has the advantage + of traditional SAP approch which is good for when many objects are sleeping, but due to being fully parallel, + it also is great when lots of shapes are moving or for runtime pair insertion and removal. It can become a + performance bottleneck if there are a very large number of shapes roughly projecting to the same values + on a given axis. If the scene has a very large number of shapes in an actor, e.g. a humanoid, it is recommended + to use an aggregate to represent multi-shape or multi-body actors to minimize stress placed on the broad phase. + */ + struct PxBroadPhaseType + { + enum Enum + { + eSAP, //!< 3-axes sweep-and-prune + eMBP, //!< Multi box pruning + eABP, //!< Automatic box pruning + ePABP, //!< Parallel automatic box pruning + eGPU, //!< GPU broad phase + eLAST + }; + }; + + /** + \brief "Region of interest" for the broad-phase. + + This is currently only used for the PxBroadPhaseType::eMBP broad-phase, which requires zones or regions to be defined + when the simulation starts in order to work. Regions can overlap and be added or removed at runtime, but at least one + region needs to be defined when the scene is created. + + If objects that do no overlap any region are inserted into the scene, they will not be added to the broad-phase and + thus collisions will be disabled for them. A PxBroadPhaseCallback out-of-bounds notification will be sent for each one + of those objects. + + The total number of regions is limited by PxBroadPhaseCaps::mMaxNbRegions. + + The number of regions has a direct impact on performance and memory usage, so it is recommended to experiment with + various settings to find the best combination for your game. A good default setup is to start with global bounds + around the whole world, and subdivide these bounds into 4*4 regions. The PxBroadPhaseExt::createRegionsFromWorldBounds + function can do that for you. + + \see PxBroadPhaseCallback PxBroadPhaseExt.createRegionsFromWorldBounds + */ + struct PxBroadPhaseRegion + { + PxBounds3 mBounds; //!< Region's bounds + void* mUserData; //!< Region's user-provided data + }; + + /** + \brief Information & stats structure for a region + */ + struct PxBroadPhaseRegionInfo + { + PxBroadPhaseRegion mRegion; //!< User-provided region data + PxU32 mNbStaticObjects; //!< Number of static objects in the region + PxU32 mNbDynamicObjects; //!< Number of dynamic objects in the region + bool mActive; //!< True if region is currently used, i.e. it has not been removed + bool mOverlap; //!< True if region overlaps other regions (regions that are just touching are not considering overlapping) + }; + + /** + \brief Caps class for broad phase. + */ + struct PxBroadPhaseCaps + { + PxU32 mMaxNbRegions; //!< Max number of regions supported by the broad-phase (0 = explicit regions not needed) + }; + + /** + \brief Descriptor for the GPU broad-phase. + + This struct contains parameters that are only relevant for the GPU broad-phase. + + \see PxBroadPhaseType::eGPU + */ + struct PxGpuBroadPhaseDesc + { + PxGpuBroadPhaseDesc() : + gpuBroadPhaseNbBitsShiftX (4), + gpuBroadPhaseNbBitsShiftY (4), + gpuBroadPhaseNbBitsShiftZ (4), + gpuBroadPhaseNbBitsEnvIDX (0), + gpuBroadPhaseNbBitsEnvIDY (0), + gpuBroadPhaseNbBitsEnvIDZ (0) + { + } + + // The GPU broadphase encodes bounds as integers, and then right-shifts the data by this amount of bits. + // This makes the bounds a bit larger, which avoids losing and recreating overlaps over and over when + // two objects are just touching. This effect is similar to what can be achieved with the contact distance + // parameter, and the amount by which the bounds are inflated depends on the distance from the bounds to + // the origin (as the bounds encoding does not use a regular float-to-integer conversion, but instead a + // reinterpretation of the float's bits). The default value in the GPU broadphase has always been 4 bits + // but it is safe to use 0 here for more accurate bounds. + PxU8 gpuBroadPhaseNbBitsShiftX; //!< number of bits used for "snap to grid" on the X axis + PxU8 gpuBroadPhaseNbBitsShiftY; //!< number of bits used for "snap to grid" on the Y axis + PxU8 gpuBroadPhaseNbBitsShiftZ; //!< number of bits used for "snap to grid" on the Z axis + + // The bits lost by the previous shifts (gpuBroadPhaseNbBitsShiftXYZ) can be replaced with bits of the + // environment IDs. This only makes sense when these parameters are used (see PxActor::setEnvironmentID + // and PxAggregate::setEnvironmentID). In this case a number of bits from the environment IDs are stored + // in the MSBs of encoded bounds. This has the effect of virtually spreading the bounds over 3D space, + // which reduces the number of internal overlaps inside the broad-phase. This is mainly useful in RL + // scenarios with "co-located" environments, but it can also provide performance gains with regular grid + // configurations, that also generate a lot of internal overlaps on all coordinate axes. + // + // Beware: when using this feature, each object of each environment should be assigned a proper environment + // ID. Objects shared between all environments (i.e. objects whose environment ID is PX_INVALID_U32) will + // otherwise be internally assigned bounds that cover the entire 3D space, creating a lot of overlaps and + // potential performance issues. This is only a concern when gpuBroadPhaseNbBitsEnvIDX/Y/Z are non zero, + // shared objects are fine otherwise. + PxU8 gpuBroadPhaseNbBitsEnvIDX; //!< number of environment ID bits merged with the bounds on the X axis + PxU8 gpuBroadPhaseNbBitsEnvIDY; //!< number of environment ID bits merged with the bounds on the Y axis + PxU8 gpuBroadPhaseNbBitsEnvIDZ; //!< number of environment ID bits merged with the bounds on the Z axis + + PX_INLINE bool isValid() const + { + // This is used on 32bit data so it makes no sense to shift more than 32 bits. + // It also makes no sense to shift all the bits of source data. + if( gpuBroadPhaseNbBitsShiftX > 31 + || gpuBroadPhaseNbBitsShiftY > 31 + || gpuBroadPhaseNbBitsShiftZ > 31) + return false; + + if( gpuBroadPhaseNbBitsEnvIDX > 31 + || gpuBroadPhaseNbBitsEnvIDY > 31 + || gpuBroadPhaseNbBitsEnvIDZ > 31) + return false; + + // We can only store bits from environment IDs in bits shifted away from the source data. + // So we need to drop (shift) at least as many bits of the source data as we need for env IDs. + if( gpuBroadPhaseNbBitsEnvIDX > gpuBroadPhaseNbBitsShiftX + || gpuBroadPhaseNbBitsEnvIDY > gpuBroadPhaseNbBitsShiftY + || gpuBroadPhaseNbBitsEnvIDZ > gpuBroadPhaseNbBitsShiftZ) + return false; + return true; + } + }; + + /** + \brief Broadphase descriptor. + + This structure is used to create a standalone broadphase. It captures all the parameters needed to + initialize a broadphase. + + For the GPU broadphase (PxBroadPhaseType::eGPU) it is necessary to provide a CUDA context manager. + + The kinematic filtering flags are currently not supported by the GPU broadphase. They are used to + dismiss pairs that involve kinematic objects directly within the broadphase. + + \see PxCreateBroadPhase + */ + class PxBroadPhaseDesc + { + public: + PxBroadPhaseDesc(PxBroadPhaseType::Enum type = PxBroadPhaseType::eLAST) : + mType (type), + mContextID (0), + mContextManager (NULL), + mFoundLostPairsCapacity (256 * 1024), + mDiscardStaticVsKinematic (false), + mDiscardKinematicVsKinematic(false) + {} + + PxBroadPhaseType::Enum mType; //!< Desired broadphase implementation + PxU64 mContextID; //!< Context ID for profiler. See PxProfilerCallback. + + PxCudaContextManager* mContextManager; //!< (GPU) CUDA context manager, must be provided for PxBroadPhaseType::eGPU. + PxU32 mFoundLostPairsCapacity; //!< (GPU) Capacity of found and lost buffers allocated in GPU global memory. This is used for the found/lost pair reports in the BP. + + bool mDiscardStaticVsKinematic; //!< Static-vs-kinematic filtering flag. Not supported by PxBroadPhaseType::eGPU. + bool mDiscardKinematicVsKinematic; //!< kinematic-vs-kinematic filtering flag. Not supported by PxBroadPhaseType::eGPU. + + PX_INLINE bool isValid() const + { + if(PxU32(mType)>=PxBroadPhaseType::eLAST) + return false; + + if(mType==PxBroadPhaseType::eGPU && !mContextManager) + return false; + + return true; + } + }; + + typedef PxU32 PxBpIndex; //!< Broadphase index. Indexes bounds, groups and distance arrays. + typedef PxU32 PxBpFilterGroup; //!< Broadphase filter group. + #define PX_INVALID_BP_FILTER_GROUP 0xffffffff //!< Invalid broadphase filter group + + /** + \brief Retrieves the filter group for static objects. + + Mark static objects with this group when adding them to the broadphase. + Overlaps between static objects will not be detected. All static objects + should have the same group. + + \return Filter group for static objects. + \see PxBpFilterGroup + */ + PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseStaticFilterGroup(); + + /** + \brief Retrieves a filter group for dynamic objects. + + Mark dynamic objects with this group when adding them to the broadphase. + Each dynamic object must have an ID, and overlaps between dynamic objects that have + the same ID will not be detected. This is useful to dismiss overlaps between shapes + of the same (compound) actor directly within the broadphase. + + \param id [in] ID/Index of dynamic object + \return Filter group for the object. + \see PxBpFilterGroup + */ + PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseDynamicFilterGroup(PxU32 id); + + /** + \brief Retrieves a filter group for kinematic objects. + + Mark kinematic objects with this group when adding them to the broadphase. + Each kinematic object must have an ID, and overlaps between kinematic objects that have + the same ID will not be detected. + + \param id [in] ID/Index of kinematic object + \return Filter group for the object. + \see PxBpFilterGroup + */ + PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseKinematicFilterGroup(PxU32 id); + + /** + \brief Broadphase data update structure. + + This structure is used to update the low-level broadphase (PxBroadPhase). All added, updated and removed objects + must be batched and submitted at once to the broadphase. + + Broadphase objects have bounds, a filtering group, and a distance. With the low-level broadphase the data must be + externally managed by the clients of the broadphase API, and passed to the update function. + + The provided bounds are non-inflated "base" bounds that can be further extended by the broadphase using the passed + distance value. These can be contact offsets, or dynamically updated distance values for e.g. speculative contacts. + Either way they are optional and can be left to zero. The broadphase implementations efficiently combine the base + bounds with the per-object distance values at runtime. + + The per-object filtering groups are used to discard some pairs directly within the broadphase, which is more + efficient than reporting the pairs and culling them in a second pass. + + \see PxBpFilterGroup PxBpIndex PxBounds3 PxBroadPhase::update + */ + class PxBroadPhaseUpdateData + { + public: + + PxBroadPhaseUpdateData( const PxBpIndex* created, PxU32 nbCreated, + const PxBpIndex* updated, PxU32 nbUpdated, + const PxBpIndex* removed, PxU32 nbRemoved, + const PxBounds3* bounds, const PxBpFilterGroup* groups, const float* distances, + PxU32 capacity) : + mCreated (created), mNbCreated (nbCreated), + mUpdated (updated), mNbUpdated (nbUpdated), + mRemoved (removed), mNbRemoved (nbRemoved), + mBounds (bounds), mGroups (groups), mDistances (distances), + mCapacity (capacity) + { + } + + PxBroadPhaseUpdateData(const PxBroadPhaseUpdateData& other) : + mCreated (other.mCreated), mNbCreated (other.mNbCreated), + mUpdated (other.mUpdated), mNbUpdated (other.mNbUpdated), + mRemoved (other.mRemoved), mNbRemoved (other.mNbRemoved), + mBounds (other.mBounds), mGroups (other.mGroups), mDistances (other.mDistances), + mCapacity (other.mCapacity) + { + } + + PxBroadPhaseUpdateData& operator=(const PxBroadPhaseUpdateData& other); + + const PxBpIndex* mCreated; //!< Indices of created objects. + const PxU32 mNbCreated; //!< Number of created objects. + + const PxBpIndex* mUpdated; //!< Indices of updated objects. + const PxU32 mNbUpdated; //!< Number of updated objects. + + const PxBpIndex* mRemoved; //!< Indices of removed objects. + const PxU32 mNbRemoved; //!< Number of removed objects. + + const PxBounds3* mBounds; //!< (Persistent) array of bounds. + const PxBpFilterGroup* mGroups; //!< (Persistent) array of groups. + const float* mDistances; //!< (Persistent) array of distances. + const PxU32 mCapacity; //!< Capacity of bounds / groups / distance buffers. + }; + + /** + \brief Broadphase pair. + + A pair of indices returned by the broadphase for found or lost pairs. + + \see PxBroadPhaseResults + */ + struct PxBroadPhasePair + { + PxBpIndex mID0; //!< Index of first object + PxBpIndex mID1; //!< Index of second object + }; + + /** + \brief Broadphase results. + + Set of found and lost pairs after a broadphase update. + + \see PxBroadPhasePair PxBroadPhase::fetchResults PxAABBManager::fetchResults + */ + struct PxBroadPhaseResults + { + PxBroadPhaseResults() : mNbCreatedPairs(0), mCreatedPairs(NULL), mNbDeletedPairs(0), mDeletedPairs(NULL) {} + + PxU32 mNbCreatedPairs; //!< Number of new/found/created pairs. + const PxBroadPhasePair* mCreatedPairs; //!< Array of new/found/created pairs. + + PxU32 mNbDeletedPairs; //!< Number of lost/deleted pairs. + const PxBroadPhasePair* mDeletedPairs; //!< Array of lost/deleted pairs. + }; + + /** + \brief Broadphase regions. + + An API to manage broadphase regions. Only needed for the MBP broadphase (PxBroadPhaseType::eMBP). + + \see PxBroadPhase::getRegions() + */ + class PxBroadPhaseRegions + { + protected: + PxBroadPhaseRegions() {} + virtual ~PxBroadPhaseRegions() {} + public: + + /** + \brief Returns number of regions currently registered in the broad-phase. + + \return Number of regions + */ + virtual PxU32 getNbRegions() const = 0; + + /** + \brief Gets broad-phase regions. + + \param userBuffer [out] Returned broad-phase regions + \param bufferSize [in] Size of provided userBuffer. + \param startIndex [in] Index of first desired region, in [0 ; getNbRegions()[ + \return Number of written out regions. + \see PxBroadPhaseRegionInfo + */ + virtual PxU32 getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Adds a new broad-phase region. + + The total number of regions is limited to PxBroadPhaseCaps::mMaxNbRegions. If that number is exceeded, the call is ignored. + + The newly added region will be automatically populated with already existing objects that touch it, if the + 'populateRegion' parameter is set to true. Otherwise the newly added region will be empty, and it will only be + populated with objects when those objects are added to the simulation, or updated if they already exist. + + Using 'populateRegion=true' has a cost, so it is best to avoid it if possible. In particular it is more efficient + to create the empty regions first (with populateRegion=false) and then add the objects afterwards (rather than + the opposite). + + Objects automatically move from one region to another during their lifetime. The system keeps tracks of what + regions a given object is in. It is legal for an object to be in an arbitrary number of regions. However if an + object leaves all regions, or is created outside of all regions, several things happen: + - collisions get disabled for this object + - the object appears in the getOutOfBoundsObjects() array + + If an out-of-bounds object, whose collisions are disabled, re-enters a valid broadphase region, then collisions + are re-enabled for that object. + + \param region [in] User-provided region data + \param populateRegion [in] True to automatically populate the newly added region with existing objects touching it + \param bounds [in] User-managed array of bounds + \param distances [in] User-managed array of distances + + \return Handle for newly created region, or 0xffffffff in case of failure. + \see PxBroadPhaseRegion getOutOfBoundsObjects() + */ + virtual PxU32 addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* bounds, const float* distances) = 0; + + /** + \brief Removes a broad-phase region. + + If the region still contains objects, and if those objects do not overlap any region any more, they are not + automatically removed from the simulation. Instead, the PxBroadPhaseCallback::onObjectOutOfBounds notification + is used for each object. Users are responsible for removing the objects from the simulation if this is the + desired behavior. + + If the handle is invalid, or if a valid handle is removed twice, an error message is sent to the error stream. + + \param handle [in] Region's handle, as returned by addRegion + \return True if success + */ + virtual bool removeRegion(PxU32 handle) = 0; + + /* + \brief Return the number of objects that are not in any region. + */ + virtual PxU32 getNbOutOfBoundsObjects() const = 0; + + /* + \brief Return an array of objects that are not in any region. + */ + virtual const PxU32* getOutOfBoundsObjects() const = 0; + }; + + /** + \brief Low-level broadphase API. + + This low-level API only supports batched updates and leaves most of the data management to its clients. + + This is useful if you want to use the broadphase with your own memory buffers. Note however that the GPU broadphase + works best with buffers allocated in CUDA memory. The getAllocator() function returns an allocator that is compatible + with the selected broadphase. It is recommended to allocate and deallocate the broadphase data (bounds, groups, distances) + using this allocator. + + Important note: it must be safe to load 4 bytes past the end of the provided bounds array. + + The high-level broadphase API (PxAABBManager) is an easier-to-use interface that automatically deals with these requirements. + + \see PxCreateBroadPhase + */ + class PxBroadPhase + { + protected: + PxBroadPhase() {} + virtual ~PxBroadPhase() {} + public: + + /* + \brief Releases the broadphase. + */ + virtual void release() = 0; + + /** + \brief Gets the broadphase type. + + \return Broadphase type. + \see PxBroadPhaseType::Enum + */ + virtual PxBroadPhaseType::Enum getType() const = 0; + + /** + \brief Gets broad-phase caps. + + \param caps [out] Broad-phase caps + \see PxBroadPhaseCaps + */ + virtual void getCaps(PxBroadPhaseCaps& caps) const = 0; + + /** + \brief Retrieves the regions API if applicable. + + For broadphases that do not use explicit user-defined regions, this call returns NULL. + + \return Region API, or NULL. + \see PxBroadPhaseRegions + */ + virtual PxBroadPhaseRegions* getRegions() = 0; + + /** + \brief Retrieves the broadphase allocator. + + User-provided buffers should ideally be allocated with this allocator, for best performance. + This is especially true for the GPU broadphases, whose buffers need to be allocated in CUDA + host memory. + + \return The broadphase allocator. + \see PxAllocatorCallback + */ + virtual PxAllocatorCallback* getAllocator() = 0; + + /** + \brief Retrieves the profiler's context ID. + + \return The context ID. + \see PxBroadPhaseDesc + */ + virtual PxU64 getContextID() const = 0; + + /** + \brief Sets a scratch buffer + + Some broadphases might take advantage of a scratch buffer to limit runtime allocations. + + All broadphases still work without providing a scratch buffer, this is an optional function + that can potentially reduce runtime allocations. + + \param scratchBlock [in] The scratch buffer + \param size [in] Size of the scratch buffer in bytes + */ + virtual void setScratchBlock(void* scratchBlock, PxU32 size) = 0; + + /** + \brief Updates the broadphase and computes the lists of created/deleted pairs. + + The provided update data describes changes to objects since the last broadphase update. + + To benefit from potentially multithreaded implementations, it is necessary to provide a continuation + task to the function. It is legal to pass NULL there, but the underlying (CPU) implementations will + then run single-threaded. + + \param updateData [in] The update data + \param continuation [in] Continuation task to enable multi-threaded implementations, or NULL. + \see PxBroadPhaseUpdateData PxBaseTask + */ + virtual void update(const PxBroadPhaseUpdateData& updateData, PxBaseTask* continuation=NULL) = 0; + + /** + \brief Retrieves the broadphase results after an update. + + This should be called once after each update call to retrieve the results of the broadphase. The + results are incremental, i.e. the system only returns new and lost pairs, not all current pairs. + + \param results [out] The broadphase results + \see PxBroadPhaseResults + */ + virtual void fetchResults(PxBroadPhaseResults& results) = 0; + + /** + \brief Helper for single-threaded updates. + + This short helper function performs a single-theaded update and reports the results in a single call. + + \param results [out] The broadphase results + \param updateData [in] The update data + \see PxBroadPhaseUpdateData PxBroadPhaseResults + */ + PX_FORCE_INLINE void updateAndFetchResults(PxBroadPhaseResults& results, const PxBroadPhaseUpdateData& updateData) + { + update(updateData); + fetchResults(results); + } + + /** + \brief Helper for single-threaded updates. + + This short helper function performs a single-theaded update and reports the results in a single call. + + \param results [out] The broadphase results + \param updateData [in] The update data + \see PxBroadPhaseUpdateData PxBroadPhaseResults + */ + PX_DEPRECATED PX_FORCE_INLINE void update(PxBroadPhaseResults& results, const PxBroadPhaseUpdateData& updateData) + { + update(updateData); + fetchResults(results); + } + }; + + /** + \brief Broadphase factory function. + + Use this function to create a new standalone broadphase. + + \param desc [in] Broadphase descriptor + \return Newly created broadphase, or NULL + \see PxBroadPhase PxBroadPhaseDesc + */ + PX_C_EXPORT PX_PHYSX_CORE_API PxBroadPhase* PxCreateBroadPhase(const PxBroadPhaseDesc& desc); + + /** + \brief High-level broadphase API. + + The low-level broadphase API (PxBroadPhase) only supports batched updates and has a few non-trivial + requirements for managing the bounds data. + + The high-level broadphase API (PxAABBManager) is an easier-to-use one-object-at-a-time API that + automatically deals with the quirks of the PxBroadPhase data management. + + \see PxCreateAABBManager + */ + class PxAABBManager + { + protected: + PxAABBManager() {} + virtual ~PxAABBManager() {} + public: + + /* + \brief Releases the AABB manager. + */ + virtual void release() = 0; + + /** + \brief Retrieves the underlying broadphase. + + \return The managed broadphase. + \see PxBroadPhase + */ + virtual PxBroadPhase& getBroadPhase() = 0; + + /** + \brief Retrieves the managed bounds. + + This is needed as input parameters to functions like PxBroadPhaseRegions::addRegion. + + \return The managed object bounds. + \see PxBounds3 + */ + virtual const PxBounds3* getBounds() const = 0; + + /** + \brief Retrieves the managed distances. + + This is needed as input parameters to functions like PxBroadPhaseRegions::addRegion. + + \return The managed object distances. + */ + virtual const float* getDistances() const = 0; + + /** + \brief Retrieves the managed filter groups. + + \return The managed object groups. + */ + virtual const PxBpFilterGroup* getGroups() const = 0; + + /** + \brief Retrieves the managed buffers' capacity. + + Bounds, distances and groups buffers have the same capacity. + + \return The managed buffers' capacity. + */ + virtual PxU32 getCapacity() const = 0; + + /** + \brief Adds an object to the manager. + + Objects' indices are externally managed, i.e. they must be provided by users (as opposed to handles + that could be returned by this manager). The design allows users to identify an object by a single ID, + and use the same ID in multiple sub-systems. + + \param index [in] The object's index + \param bounds [in] The object's bounds + \param group [in] The object's filter group + \param distance [in] The object's distance (optional) + \see PxBpIndex PxBounds3 PxBpFilterGroup + */ + virtual void addObject(PxBpIndex index, const PxBounds3& bounds, PxBpFilterGroup group, float distance=0.0f) = 0; + + /** + \brief Removes an object from the manager. + + \param index [in] The object's index + \see PxBpIndex + */ + virtual void removeObject(PxBpIndex index) = 0; + + /** + \brief Updates an object in the manager. + + This call can update an object's bounds, distance, or both. + It is not possible to update an object's filter group. + + \param index [in] The object's index + \param bounds [in] The object's updated bounds, or NULL + \param distance [in] The object's updated distance, or NULL + \see PxBpIndex PxBounds3 + */ + virtual void updateObject(PxBpIndex index, const PxBounds3* bounds=NULL, const float* distance=NULL) = 0; + + /** + \brief Updates the broadphase and computes the lists of created/deleted pairs. + + The data necessary for updating the broadphase is internally computed by the AABB manager. + + To benefit from potentially multithreaded implementations, it is necessary to provide a continuation + task to the function. It is legal to pass NULL there, but the underlying (CPU) implementations will + then run single-threaded. + + \param continuation [in] Continuation task to enable multi-threaded implementations, or NULL. + \see PxBaseTask + */ + virtual void update(PxBaseTask* continuation=NULL) = 0; + + /** + \brief Retrieves the broadphase results after an update. + + This should be called once after each update call to retrieve the results of the broadphase. The + results are incremental, i.e. the system only returns new and lost pairs, not all current pairs. + + \param results [out] The broadphase results + \see PxBroadPhaseResults + */ + virtual void fetchResults(PxBroadPhaseResults& results) = 0; + + /** + \brief Helper for single-threaded updates. + + This short helper function performs a single-theaded update and reports the results in a single call. + + \param results [out] The broadphase results + \see PxBroadPhaseResults + */ + PX_FORCE_INLINE void updateAndFetchResults(PxBroadPhaseResults& results) + { + update(); + fetchResults(results); + } + + /** + \brief Helper for single-threaded updates. + + This short helper function performs a single-theaded update and reports the results in a single call. + + \param results [out] The broadphase results + \see PxBroadPhaseResults + */ + PX_DEPRECATED PX_FORCE_INLINE void update(PxBroadPhaseResults& results) + { + update(); + fetchResults(results); + } + }; + + /** + \brief AABB manager factory function. + + Use this function to create a new standalone high-level broadphase. + + \param broadphase [in] The broadphase that will be managed by the AABB manager + \return Newly created AABB manager, or NULL + \see PxAABBManager PxBroadPhase + */ + PX_C_EXPORT PX_PHYSX_CORE_API PxAABBManager* PxCreateAABBManager(PxBroadPhase& broadphase); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxClient.h b/Jusin154_Team3D/Engine/Public/PhysX/PxClient.h new file mode 100644 index 000000000..3a1f46ba5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxClient.h @@ -0,0 +1,57 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CLIENT_H +#define PX_CLIENT_H + +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief An ID to identify different clients for multiclient support. + +\see PxScene::createClient() +*/ +typedef PxU8 PxClientID; + +/** +\brief The predefined default PxClientID value. + +\see PxClientID PxScene::createClient() +*/ +static const PxClientID PX_DEFAULT_CLIENT = 0; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxConeLimitedConstraint.h b/Jusin154_Team3D/Engine/Public/PhysX/PxConeLimitedConstraint.h new file mode 100644 index 000000000..a2b2a81d5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxConeLimitedConstraint.h @@ -0,0 +1,124 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONE_LIMITED_CONSTRAINT_H +#define PX_CONE_LIMITED_CONSTRAINT_H + + +#include "foundation/PxVec3.h" +#include "foundation/PxVec4.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief A constraint descriptor for limiting movement to a conical region. +*/ +struct PxConeLimitedConstraint +{ + PxConeLimitedConstraint() + { + setToDefault(); + } + + /** + \brief Set values such that constraint is disabled. + */ + PX_INLINE void setToDefault() + { + mAxis = PxVec3(0.f, 0.f, 0.f); + mAngle = -1.f; + mLowLimit = -1.f; + mHighLimit = -1.f; + } + + /** + \brief Checks for valitity. + + \return true if the constaint is valid + */ + PX_INLINE bool isValid() const + { + //disabled + if (mAngle < 0.f && mLowLimit < 0.f && mHighLimit < 0.f) + { + return true; + } + + if (!mAxis.isNormalized()) + { + return false; + } + + //negative signifies that cone is disabled + if (mAngle >= PxPi) + { + return false; + } + + //negative signifies that distance limits are disabled + if (mLowLimit > mHighLimit && mHighLimit >= 0.0f && mLowLimit >= 0.0f) + { + return false; + } + + return true; + } + + PxVec3 mAxis; //!< Axis of the cone in actor space + PxReal mAngle; //!< Opening angle in radians, negative indicates unlimited + PxReal mLowLimit; //!< Minimum distance, negative indicates unlimited + PxReal mHighLimit; //!< Maximum distance, negative indicates unlimited +}; + +/** +\brief Compressed form of cone limit parameters +\see PxConeLimitedConstraint +*/ +PX_ALIGN_PREFIX(16) +struct PxConeLimitParams +{ + PX_CUDA_CALLABLE PxConeLimitParams() {} + + PX_CUDA_CALLABLE PxConeLimitParams(const PxConeLimitedConstraint& coneLimitedConstraint) : + lowHighLimits(coneLimitedConstraint.mLowLimit, coneLimitedConstraint.mHighLimit, 0.0f, 0.0f), + axisAngle(coneLimitedConstraint.mAxis, coneLimitedConstraint.mAngle) + { + } + + PxVec4 lowHighLimits; // [lowLimit, highLimit, unused, unused] + PxVec4 axisAngle; // [axis.x, axis.y, axis.z, angle] +}PX_ALIGN_SUFFIX(16); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxConfig.h b/Jusin154_Team3D/Engine/Public/PhysX/PxConfig.h new file mode 100644 index 000000000..32aa62672 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxConfig.h @@ -0,0 +1,32 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_CONFIG +#define PX_CONFIG + + + +#endif // PX_CONFIG diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxConstraint.h b/Jusin154_Team3D/Engine/Public/PhysX/PxConstraint.h new file mode 100644 index 000000000..4d3b0f7d3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxConstraint.h @@ -0,0 +1,291 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONSTRAINT_H +#define PX_CONSTRAINT_H + + +#include "PxPhysXConfig.h" +#include "PxConstraintDesc.h" +#include "common/PxBase.h" +#include "PxResidual.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxRigidActor; +class PxScene; +class PxConstraintConnector; + +/** +\brief constraint flags + +\note eBROKEN is a read only flag +*/ +struct PxConstraintFlag +{ + enum Enum + { + eBROKEN = 1<<0, //!< whether the constraint is broken + eCOLLISION_ENABLED = 1<<3, //!< whether contacts should be generated between the objects this constraint constrains + eVISUALIZATION = 1<<4, //!< whether this constraint should be visualized, if constraint visualization is turned on + eDRIVE_LIMITS_ARE_FORCES = 1<<5, //!< \deprecated Will be removed in a future version and the limits will always be forces. limits for drive strength are forces rather than impulses + eIMPROVED_SLERP = 1<<7, //!< perform preprocessing for improved accuracy on D6 Slerp Drive (this flag will be removed in a future release when preprocessing is no longer required) + eDISABLE_PREPROCESSING = 1<<8, //!< suppress constraint preprocessing, intended for use with rowResponseThreshold. May result in worse solver accuracy for ill-conditioned constraints. + eENABLE_EXTENDED_LIMITS = 1<<9, //!< enables extended limit ranges for angular limits (e.g., limit values > PxPi or < -PxPi) + eGPU_COMPATIBLE = 1<<10, //!< please do not raise this flag as it is for internal use only + eALWAYS_UPDATE = 1<<11, //!< updates the constraint each frame + eDISABLE_CONSTRAINT = 1<<12 //!< disables the constraint. SolverPrep functions won't be called for this constraint. + }; +}; + +/** +\brief constraint flags +\see PxConstraintFlag +*/ +typedef PxFlags PxConstraintFlags; +PX_FLAGS_OPERATORS(PxConstraintFlag::Enum, PxU16) + +/** +\brief a table of function pointers for a constraint + +\see PxConstraint +*/ +struct PxConstraintShaderTable +{ + PxConstraintSolverPrep solverPrep; //!< solver constraint generation function + PxConstraintVisualize visualize; //!< constraint visualization function + PxConstraintFlag::Enum flag; //!< constraint flags +}; + +/** +\brief A plugin class for implementing constraints + +\see PxPhysics.createConstraint +*/ +class PxConstraint : public PxBase +{ +public: + + /** + \brief Releases a PxConstraint instance. + + \note This call does not wake up the connected rigid bodies. + + \see PxPhysics.createConstraint, PxBase.release() + */ + virtual void release() = 0; + + /** + \brief Retrieves the scene which this constraint belongs to. + + \return Owner Scene. NULL if not part of a scene. + + \see PxScene + */ + virtual PxScene* getScene() const = 0; + + /** + \brief Retrieves the actors for this constraint. + + \param[out] actor0 a reference to the pointer for the first actor + \param[out] actor1 a reference to the pointer for the second actor + + \see PxActor + */ + virtual void getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const = 0; + + /** + \brief Sets the actors for this constraint. + + \param[in] actor0 a reference to the pointer for the first actor + \param[in] actor1 a reference to the pointer for the second actor + + \see PxActor + */ + virtual void setActors(PxRigidActor* actor0, PxRigidActor* actor1) = 0; + + /** + \brief Notify the scene that the constraint shader data has been updated by the application + */ + virtual void markDirty() = 0; + + /** + \brief Retrieve the flags for this constraint + + \return the constraint flags + \see PxConstraintFlags + */ + virtual PxConstraintFlags getFlags() const = 0; + + /** + \brief Set the flags for this constraint + + \param[in] flags the new constraint flags + + default: PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES + + \see PxConstraintFlags + */ + virtual void setFlags(PxConstraintFlags flags) = 0; + + /** + \brief Set a flag for this constraint + + \param[in] flag the constraint flag + \param[in] value the new value of the flag + + \see PxConstraintFlags + */ + virtual void setFlag(PxConstraintFlag::Enum flag, bool value) = 0; + + /** + \brief Retrieve the constraint force most recently applied to maintain this constraint. + + \note It is not allowed to use this method while the simulation is running (except during PxScene::collide(), + in PxContactModifyCallback or in contact report callbacks). + + \param[out] linear the constraint force + \param[out] angular the constraint torque + */ + virtual void getForce(PxVec3& linear, PxVec3& angular) const = 0; + + /** + \brief whether the constraint is valid. + + A constraint is valid if it has at least one dynamic rigid body or articulation link. A constraint that + is not valid may not be inserted into a scene, and therefore a static actor to which an invalid constraint + is attached may not be inserted into a scene. + + Invalid constraints arise only when an actor to which the constraint is attached has been deleted. + */ + virtual bool isValid() const = 0; + + /** + \brief Set the break force and torque thresholds for this constraint. + + If either the force or torque measured at the constraint exceed these thresholds the constraint will break. + + \param[in] linear the linear break threshold + \param[in] angular the angular break threshold + */ + virtual void setBreakForce(PxReal linear, PxReal angular) = 0; + + /** + \brief Retrieve the constraint break force and torque thresholds + + \param[out] linear the linear break threshold + \param[out] angular the angular break threshold + */ + virtual void getBreakForce(PxReal& linear, PxReal& angular) const = 0; + + /** + \brief Set the minimum response threshold for a constraint row + + When using mass modification for a joint or infinite inertia for a jointed body, very stiff solver constraints can be generated which + can destabilize simulation. Setting this value to a small positive value (e.g. 1e-8) will cause constraint rows to be ignored if very + large changes in impulses will generate only small changes in velocity. When setting this value, also set + PxConstraintFlag::eDISABLE_PREPROCESSING. The solver accuracy for this joint may be reduced. + + \param[in] threshold the minimum response threshold + + \see PxConstraintFlag::eDISABLE_PREPROCESSING + */ + virtual void setMinResponseThreshold(PxReal threshold) = 0; + + /** + \brief Retrieve the constraint break force and torque thresholds + + \return the minimum response threshold for a constraint row + */ + virtual PxReal getMinResponseThreshold() const = 0; + + /** + \brief Fetch external owner of the constraint. + + Provides a reference to the external owner of a constraint and a unique owner type ID. + + \param[out] typeID Unique type identifier of the external object. + \return Reference to the external object which owns the constraint. + + \see PxConstraintConnector.getExternalReference() + */ + virtual void* getExternalReference(PxU32& typeID) = 0; + + /** + \brief Set the constraint functions for this constraint + + \param[in] connector the constraint connector object by which the SDK communicates with the constraint. + \param[in] shaders the shader table for the constraint + + \see PxConstraintConnector PxConstraintSolverPrep PxConstraintVisualize + */ + virtual void setConstraintFunctions(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders) = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxConstraint"; } + + /** + \brief Returns the residual for this constraint. + + The residual represents the current error in this constraint measured as the delta impulse applied in the last velocity or position iteration. + If the solver converges perfectly, the residual should approach zero. + + \return The residual for this constraint. + + \see PxConstraintResidual + */ + virtual PxConstraintResidual getSolverResidual() const = 0; + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + PX_INLINE PxConstraint(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {} + PX_INLINE PxConstraint(PxBaseFlags baseFlags) : PxBase(baseFlags), userData(NULL) {} + virtual ~PxConstraint() {} + virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxConstraint", PxBase); } + +public: + /** + \cond + */ + + // for internal use only + virtual PxConstraintGPUIndex getGPUIndex() const = 0; + + /** + \endcond + */ +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxConstraintDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/PxConstraintDesc.h new file mode 100644 index 000000000..4ca1c1738 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxConstraintDesc.h @@ -0,0 +1,491 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONSTRAINT_DESC_H +#define PX_CONSTRAINT_DESC_H + + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" +#include "foundation/PxVec3.h" +#include "foundation/PxTransform.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx { namespace pvdsdk { +#endif + class PvdDataStream; +#if !PX_DOXYGEN +}} +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** + \brief Constraint row flags + + These flags configure the post-processing of constraint rows and the behavior of the solver while solving constraints +*/ +struct Px1DConstraintFlag +{ + PX_CUDA_CALLABLE Px1DConstraintFlag(){} + + enum Type + { + eSPRING = 1<<0, //!< whether the constraint is a spring. Mutually exclusive with eRESTITUTION. If set, eKEEPBIAS is ignored. + eACCELERATION_SPRING = 1<<1, //!< whether the constraint is a force or acceleration spring. Only valid if eSPRING is set. + eRESTITUTION = 1<<2, //!< whether the restitution model should be applied to generate the target velocity. Mutually exclusive with eSPRING. If restitution causes a bounces, eKEEPBIAS is ignored + eKEEPBIAS = 1<<3, //!< whether to keep the error term when solving for velocity. Ignored if restitution generates bounce, or eSPRING is set. + eOUTPUT_FORCE = 1<<4, //!< whether to accumulate the force value from this constraint in the force total that is reported for the constraint and tested for breakage + eHAS_DRIVE_LIMIT = 1<<5, //!< whether the constraint has a drive force limit (which will be scaled by dt unless #PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES is set) + eANGULAR_CONSTRAINT = 1<<6, //!< whether this is an angular or linear constraint + }; +}; + +typedef PxFlags Px1DConstraintFlags; +PX_FLAGS_OPERATORS(Px1DConstraintFlag::Type, PxU16) + +/** +\brief Constraint type hints which the solver uses to optimize constraint handling +*/ +struct PxConstraintSolveHint +{ + enum Enum + { + eNONE = 0, //!< no special properties + eACCELERATION1 = 256, //!< a group of acceleration drive constraints with the same stiffness and drive parameters + eSLERP_SPRING = 258, //!< temporary special value to identify SLERP drive rows + eACCELERATION2 = 512, //!< a group of acceleration drive constraints with the same stiffness and drive parameters + eACCELERATION3 = 768, //!< a group of acceleration drive constraints with the same stiffness and drive parameters + eROTATIONAL_EQUALITY = 1024, //!< for internal purpose only, please do not use. + eROTATIONAL_INEQUALITY = 1025, //!< for internal purpose only, please do not use. + + /** + \brief Mark as equality constraint. + + If a 1D constraint is an equality constraint with [-PX_MAX_FLT, PX_MAX_FLT] force limits and a velocity target equal zero, then this + flag can be raised to allow the solver to internally change the jacobian of this constraint and have it being orthogonalized relative + to other equality constraints in the same PxConstraint (unless PxConstraintFlag::eDISABLE_PREPROCESSING is set). This can improve + the convergence when solving the constraints. + */ + eEQUALITY = 2048, + + /** + \brief Mark as inequality constraint. + + If a 1D constraint is an inequality constraint with [0, PX_MAX_FLT] force limits, then this flag can be raised to allow the solver + to internally change the jacobian of this constraint and have it being orthogonalized relative to the equality constraints in the + same PxConstraint (unless PxConstraintFlag::eDISABLE_PREPROCESSING is set). This can improve the convergence when solving the + constraints. + */ + eINEQUALITY = 2049 + }; +}; + +/** +\brief A one-dimensional constraint that constrains the relative motion of two rigid bodies. + +A constraint is expressed as a set of 1-dimensional constraint rows which define the required constraint +on the objects' velocities. + +The constraint Jacobian J is specified by the parameters linear0, angular0, linear1, angular1 as follows + + J = {linear0, angular0, -linear1, -angular1} + +The velocity target of the constraint is specified by Px1DConstraint::velocityTarget and the geometric error of the constraint +is specified by Px1DConstraint::geometricError. + +The output of the constraint is a velocity state (sdot = ds/dt with s denoting the constraint state) expressed in the world frame: + + sdot = {linearVelocity0, angularVelocity0, linearVelocity1, angularVelocity1} + +with linearVelocity0 and angularVelocity0 denoting the linear and angular velocity of body0 of the constraint; +and linearVelocity1 and angularVelocity1 denoting the linear and angular velocity of body1 of the constraint. + +The constraint seeks an updated sdot that obeys a simple constraint rule: + + J*sdot + BaumgarteTerm*geometricError/dt - velocityTarget = 0 + +where BaumgarteTerm is a multiplier in range (0, 1). The Baumgarte term is not exposed but is instead internally +set according to a simple metric chosen to enhance numerical stability. If the PGS solver is employed then dt is +taken from the scene timestep. + +Another way of expressing the constraint rule is as follows: + + linear0.dot(linearVelocity0) + angular0.dot(angularVelocity0) + - linear1.dot(linearVelocity1) - angular1.dot(angularVelocity1) + + BaumgarteTerm*geometricError/dt - velocityTarget = 0 + +The PhysX solver runs two phases: position iterations followed by velocity iterations. Position iterations derive +the velocity that is used to integrate the transform of a rigid body. Velocity iterations on the other hand derive +the final velocity of a rigid body. The constraint rule presented above only gets applied during position iterations, +during velocity iterations the geometricError term is usually ignored and the applied constraint rule is: + + J*sdot - velocityTarget = 0 + +The flag Px1DConstraintFlag::eKEEPBIAS can be used to have velocity iterations apply the same constraint rule as +position iterations. + +A 1d constraint may be either a restitution constraint or a hard constraint or a spring constraint. + +Restitution constraints have two modes of operation, depending on the speed of the constraint. These two modes are: +a) a bounce mode that employs a restitution value specified by RestitutionModifiers::restitution +b) a non-bounce mode that employs zero restitution and ignores RestitutionModifiers::restitution. +The constraint speed immediately before the solver begins is computed as follows: + constraintPreSolverSpeed = J * sdotPreSolver +with sdotPreSolver denoting the rigid body velocities recorded after applying external forces and torques to the rigid bodies +but before the solver begins. +If the bounce mode is active, the pre solver velocity is expected to flip direction and have restitution applied: + bounceSpeed = -restitution * constraintPreSolverSpeed +Restitution will kick in if the following conditions are met: +\li -constraintPreSolverSpeed exceeds the bounce threshold (RestitutionModifiers::velocityThreshold) +\li (bounceSpeed * Px1DConstraint::geometricError) <= 0 (bounceSpeed points in the +opposite direction of the geometric error) +If these hold, then the provided Px1DConstraint::geometricError and Px1DConstraint::velocityTarget parameter will get overriden +internally. The former will get set to zero, the latter will get set to bounceSpeed. If restitution does not activate because +the listed conditions are not met, then the target velocity will be taken from the value stored in velocityTarget and the +geometric error will be taken from the value stored in geometricError. +RestitutionModifiers::restitution may be greater than 1 and may be less than 0 ie it is not limited to 0 <= restitution <= 1. + +Hard constraints attempt to find sdot that satisfies the constraint equation: + + J*sdot + BaumgarteTerm*geometricError/dt - velocityTarget = 0 + +Spring constraints are quite different from restitution and hard constraints in that they attempt to compute and apply a spring force as follows: + + F = stiffness * -geometricError + damping * (velocityTarget - J*sdot) + +where F is the constraint force or acceleration and J*sdot is the instantaneous constraint speed. Springs are +implemented with a fully implicit time-stepping scheme: that is, the force or acceleration is a function of the position +and velocity after the solve. Note that F gets applied to the first rigid body and -F to the second rigid body. + +All constraints support limits on the minimum or maximum impulse applied. +*/ + +PX_ALIGN_PREFIX(16) +struct Px1DConstraint +{ + PxVec3 linear0; //!< linear component of velocity jacobian in world space + PxReal geometricError; //!< geometric error of the constraint along this axis + PxVec3 angular0; //!< angular component of velocity jacobian in world space + PxReal velocityTarget; //!< velocity target for the constraint along this axis + + PxVec3 linear1; //!< linear component of velocity jacobian in world space + PxReal minImpulse; //!< minimum impulse the solver may apply to enforce this constraint + PxVec3 angular1; //!< angular component of velocity jacobian in world space + PxReal maxImpulse; //!< maximum impulse the solver may apply to enforce this constraint + + union + { + struct SpringModifiers + { + PxReal stiffness; //!< spring parameter, for spring constraints + PxReal damping; //!< damping parameter, for spring constraints + } spring; + struct RestitutionModifiers + { + PxReal restitution; //!< restitution parameter for determining additional "bounce" + PxReal velocityThreshold; //!< minimum impact velocity for bounce + } bounce; + } mods; + + PxU16 flags; //!< a set of Px1DConstraintFlags + PxU16 solveHint; //!< constraint optimization hint, should be an element of PxConstraintSolveHint + + PxU32 pad; // for padding only +} +PX_ALIGN_SUFFIX(16); + +/** +\brief Flags for determining which components of the constraint should be visualized. + +\see PxConstraintVisualize +*/ +struct PxConstraintVisualizationFlag +{ + enum Enum + { + eLOCAL_FRAMES = 1, //!< visualize constraint frames + eLIMITS = 2 //!< visualize constraint limits + }; +}; + +/** +\brief Struct for specifying mass scaling for a pair of rigids +*/ +PX_ALIGN_PREFIX(16) +struct PxConstraintInvMassScale +{ + PxReal linear0; //!< multiplier for inverse mass of body0 + PxReal angular0; //!< multiplier for inverse MoI of body0 + PxReal linear1; //!< multiplier for inverse mass of body1 + PxReal angular1; //!< multiplier for inverse MoI of body1 + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxConstraintInvMassScale(){} + PX_CUDA_CALLABLE PX_FORCE_INLINE PxConstraintInvMassScale(PxReal lin0, PxReal ang0, PxReal lin1, PxReal ang1) : linear0(lin0), angular0(ang0), linear1(lin1), angular1(ang1){} +} +PX_ALIGN_SUFFIX(16); + +/** +\brief Solver constraint generation shader + +This function is called by the constraint solver framework. The function must be reentrant, since it may be called simultaneously +from multiple threads, and should access only the arguments passed into it. + +Developers writing custom constraints are encouraged to read the documentation in the user guide and the implementation code in PhysXExtensions. + +\param[out] constraints An array of solver constraint rows to be filled in +\param[out] bodyAWorldOffset The origin point (offset from the position vector of bodyA's center of mass) at which the constraint is resolved. This value does not affect how constraints are solved, only the constraint force reported. +\param[in] maxConstraints The size of the constraint buffer. At most this many constraints rows may be written +\param[out] invMassScale The inverse mass and inertia scales for the constraint +\param[in] constantBlock The constant data block +\param[in] bodyAToWorld The center of mass frame of the first constrained body (the identity transform if the first actor is static, or if a NULL actor pointer was provided for it) +\param[in] bodyBToWorld The center of mass frame of the second constrained body (the identity transform if the second actor is static, or if a NULL actor pointer was provided for it) +\param[in] useExtendedLimits Enables limit ranges outside of (-PI, PI) +\param[out] cAtW The world space location of body A's joint frame (position only) +\param[out] cBtW The world space location of body B's joint frame (position only) + +\return the number of constraint rows written. +*/ +typedef PxU32 (*PxConstraintSolverPrep)(Px1DConstraint* constraints, + PxVec3p& bodyAWorldOffset, + PxU32 maxConstraints, + PxConstraintInvMassScale& invMassScale, + const void* constantBlock, + const PxTransform& bodyAToWorld, + const PxTransform& bodyBToWorld, + bool useExtendedLimits, + PxVec3p& cAtW, + PxVec3p& cBtW); + +/** +\brief API used to visualize details about a constraint. +*/ +class PxConstraintVisualizer +{ +protected: + virtual ~PxConstraintVisualizer(){} +public: + /** \brief Visualize joint frames + + \param[in] parent Parent transformation + \param[in] child Child transformation + */ + virtual void visualizeJointFrames(const PxTransform& parent, const PxTransform& child) = 0; + + /** \brief Visualize joint linear limit + + \param[in] t0 Base transformation + \param[in] t1 End transformation + \param[in] value Distance + */ + virtual void visualizeLinearLimit(const PxTransform& t0, const PxTransform& t1, PxReal value) = 0; + + /** \brief Visualize joint angular limit + + \param[in] t0 Transformation for the visualization + \param[in] lower Lower limit angle + \param[in] upper Upper limit angle + */ + virtual void visualizeAngularLimit(const PxTransform& t0, PxReal lower, PxReal upper) = 0; + + /** \brief Visualize limit cone + + \param[in] t Transformation for the visualization + \param[in] tanQSwingY Tangent of the quarter Y angle + \param[in] tanQSwingZ Tangent of the quarter Z angle + */ + virtual void visualizeLimitCone(const PxTransform& t, PxReal tanQSwingY, PxReal tanQSwingZ) = 0; + + /** \brief Visualize joint double cone + + \param[in] t Transformation for the visualization + \param[in] angle Limit angle + */ + virtual void visualizeDoubleCone(const PxTransform& t, PxReal angle) = 0; + + /** \brief Visualize line + + \param[in] p0 Start position + \param[in] p1 End postion + \param[in] color Color + */ + virtual void visualizeLine(const PxVec3& p0, const PxVec3& p1, PxU32 color) = 0; +}; + +/** \brief Solver constraint visualization function + +This function is called by the constraint post-solver framework to visualize the constraint + +\param[out] visualizer The render buffer to render to +\param[in] constantBlock The constant data block +\param[in] body0Transform The center of mass frame of the first constrained body (the identity if the actor is static, or a NULL pointer was provided for it) +\param[in] body1Transform The center of mass frame of the second constrained body (the identity if the actor is static, or a NULL pointer was provided for it) +\param[in] flags The visualization flags (PxConstraintVisualizationFlag) + +\see PxRenderBuffer +*/ +typedef void (*PxConstraintVisualize)(PxConstraintVisualizer& visualizer, + const void* constantBlock, + const PxTransform& body0Transform, + const PxTransform& body1Transform, + PxU32 flags); + +/** +\brief Flags for determining how PVD should serialize a constraint update + +\see PxConstraintConnector::updatePvdProperties, PvdSceneClient::updateConstraint +*/ +struct PxPvdUpdateType +{ + enum Enum + { + CREATE_INSTANCE, //!< triggers createPvdInstance call, creates an instance of a constraint + RELEASE_INSTANCE, //!< triggers releasePvdInstance call, releases an instance of a constraint + UPDATE_ALL_PROPERTIES, //!< triggers updatePvdProperties call, updates all properties of a constraint + UPDATE_SIM_PROPERTIES //!< triggers simUpdate call, updates all simulation properties of a constraint + }; +}; + +/** +\brief This class connects a custom constraint to the SDK + +This class connects a custom constraint to the SDK, and functions are called by the SDK +to query the custom implementation for specific information to pass on to the application +or inform the constraint when the application makes calls into the SDK which will update +the custom constraint's internal implementation +*/ +class PxConstraintConnector +{ +public: + /** \brief Pre-simulation data preparation + when the constraint is marked dirty, this function is called at the start of the simulation + step for the SDK to copy the constraint data block. + */ + virtual void* prepareData() = 0; + + /** + \brief this function is called by the SDK to update PVD's view of it + */ + virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream& pvdConnection, + const PxConstraint* c, + PxPvdUpdateType::Enum updateType) const = 0; + + /** + \brief this function is called by the SDK to update OmniPVD's view of it + */ + virtual void updateOmniPvdProperties() const = 0; + + /** + \brief Constraint release callback + + When the SDK deletes a PxConstraint object this function is called by the SDK. In general + custom constraints should not be deleted directly by applications: rather, the constraint + should respond to a release() request by calling PxConstraint::release(), then wait for + this call to release its own resources. + + This function is also called when a PxConstraint object is deleted on cleanup due to + destruction of the PxPhysics object. + */ + virtual void onConstraintRelease() = 0; + + /** + \brief Center-of-mass shift callback + + This function is called by the SDK when the CoM of one of the actors is moved. Since the + API specifies constraint positions relative to actors, and the constraint shader functions + are supplied with coordinates relative to bodies, some synchronization is usually required + when the application moves an object's center of mass. + */ + virtual void onComShift(PxU32 actor) = 0; + + /** + \brief Origin shift callback + + This function is called by the SDK when the scene origin gets shifted and allows to adjust + custom data which contains world space transforms. + + \note If the adjustments affect constraint shader data, it is necessary to call PxConstraint::markDirty() + to make sure that the data gets synced at the beginning of the next simulation step. + + \param[in] shift Translation vector the origin is shifted by. + + \see PxScene.shiftOrigin() + */ + virtual void onOriginShift(const PxVec3& shift) = 0; + + /** + \brief Fetches external data for a constraint. + + This function is used by the SDK to acquire a reference to the owner of a constraint and a unique + owner type ID. This information will be passed on when a breakable constraint breaks or when + #PxConstraint::getExternalReference() is called. + + \param[out] typeID Unique type identifier of the external object. The value 0xffffffff is reserved and should not be used. Furthermore, if the PhysX extensions library is used, some other IDs are reserved already (see PxConstraintExtIDs) + \return Reference to the external object which owns the constraint. + + \see PxConstraintInfo PxSimulationEventCallback.onConstraintBreak() + */ + virtual void* getExternalReference(PxU32& typeID) = 0; + + /** + \brief Obtain a reference to a PxBase interface if the constraint has one. + + If the constraint does not implement the PxBase interface, it should return NULL. + */ + virtual PxBase* getSerializable() = 0; + + /** + \brief Obtain the shader function pointer used to prep rows for this constraint + */ + virtual PxConstraintSolverPrep getPrep() const = 0; + + /** + \brief Obtain the pointer to the constraint's constant data + */ + virtual const void* getConstantBlock() const = 0; + + /** + \brief Let the connector know it has been connected to a constraint. + */ + virtual void connectToConstraint(PxConstraint*) {} + + /** + \brief virtual destructor + */ + virtual ~PxConstraintConnector() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxContact.h b/Jusin154_Team3D/Engine/Public/PhysX/PxContact.h new file mode 100644 index 000000000..1a04e8356 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxContact.h @@ -0,0 +1,844 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTACT_H +#define PX_CONTACT_H + + +#include "foundation/PxVec3.h" +#include "foundation/PxAssert.h" +#include "PxConstraintDesc.h" +#include "PxNodeIndex.h" +#include "PxMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value. +#endif + +#define PXC_CONTACT_NO_FACE_INDEX 0xffffffff + +class PxActor; + +/** +\brief Header for a contact patch where all points share same material and normal +*/ +PX_ALIGN_PREFIX(16) +struct PxContactPatch +{ + enum PxContactPatchFlags + { + eHAS_FACE_INDICES = 1, //!< Indicates this contact stream has face indices. + eMODIFIABLE = 2, //!< Indicates this contact stream is modifiable. + eFORCE_NO_RESPONSE = 4, //!< Indicates this contact stream is notify-only (no contact response). + eHAS_MODIFIED_MASS_RATIOS = 8, //!< Indicates this contact stream has modified mass ratios + eHAS_TARGET_VELOCITY = 16, //!< Indicates this contact stream has target velocities set + eHAS_MAX_IMPULSE = 32, //!< Indicates this contact stream has max impulses set + eREGENERATE_PATCHES = 64, //!< Indicates this contact stream needs patches re-generated. This is required if the application modified either the contact normal or the material properties + eCOMPRESSED_MODIFIED_CONTACT = 128 + }; + + /** + \brief Modifiers for scaling the inertia of the involved bodies + */ + PX_ALIGN(16, PxConstraintInvMassScale mMassModification); + + /** + \brief Contact normal + */ + PX_ALIGN(16, PxVec3 normal); + + /** + \brief Restitution coefficient + */ + PxReal restitution; + + /** + \brief Dynamic friction coefficient + */ + PxReal dynamicFriction; + + /** + \brief Static friction coefficient + */ + PxReal staticFriction; + + /** + \brief Damping coefficient (for compliant contacts) + */ + PxReal damping; + + /** + \brief Index of the first contact in the patch + */ + PxU16 startContactIndex; + + /** + \brief The number of contacts in this patch + */ + PxU8 nbContacts; + + /** + \brief The combined material flag of two actors that come in contact + \see PxMaterialFlag, PxCombineMode + */ + PxU8 materialFlags; + + /** + \brief The PxContactPatchFlags for this patch + */ + PxU16 internalFlags; + + /** + \brief Material index of first body + */ + PxU16 materialIndex0; + + /** + \brief Material index of second body + */ + PxU16 materialIndex1; + + PxU16 pad[5]; +} +PX_ALIGN_SUFFIX(16); + +/** +\brief Contact point data +*/ +PX_ALIGN_PREFIX(16) +struct PxContact +{ + /** + \brief Contact point in world space + */ + PxVec3 contact; + /** + \brief Separation value (negative implies penetration). + */ + PxReal separation; +} +PX_ALIGN_SUFFIX(16); + +/** +\brief Contact point data with additional target and max impulse values +*/ +PX_ALIGN_PREFIX(16) +struct PxExtendedContact : public PxContact +{ + /** + \brief Target velocity + */ + PX_ALIGN(16, PxVec3 targetVelocity); + /** + \brief Maximum impulse + */ + PxReal maxImpulse; +} +PX_ALIGN_SUFFIX(16); + +/** +\brief A modifiable contact point. This has additional fields per-contact to permit modification by user. +\note Not all fields are currently exposed to the user. +*/ +PX_ALIGN_PREFIX(16) +struct PxModifiableContact : public PxExtendedContact +{ + /** + \brief Contact normal + */ + PX_ALIGN(16, PxVec3 normal); + /** + \brief Restitution coefficient + */ + PxReal restitution; + + /** + \brief Material Flags + */ + PxU32 materialFlags; + + /** + \brief Shape A's material index + */ + PxU16 materialIndex0; + /** + \brief Shape B's material index + */ + PxU16 materialIndex1; + /** + \brief static friction coefficient + */ + PxReal staticFriction; + /** + \brief dynamic friction coefficient + */ + PxReal dynamicFriction; +} +PX_ALIGN_SUFFIX(16); + +/** +\brief A class to iterate over a compressed contact stream. This supports read-only access to the various contact formats. +*/ +struct PxContactStreamIterator +{ + enum StreamFormat + { + eSIMPLE_STREAM, + eMODIFIABLE_STREAM, + eCOMPRESSED_MODIFIABLE_STREAM + }; + /** + \brief Utility zero vector to optimize functions returning zero vectors when a certain flag isn't set. + \note This allows us to return by reference instead of having to return by value. Returning by value will go via memory (registers -> stack -> registers), which can + cause performance issues on certain platforms. + */ + PxVec3 zero; + + /** + \brief The patch headers. + */ + const PxContactPatch* patch; + + /** + \brief The contacts + */ + const PxContact* contact; + + /** + \brief The contact triangle face index + */ + const PxU32* faceIndice; + + /** + \brief The total number of patches in this contact stream + */ + PxU32 totalPatches; + + /** + \brief The total number of contact points in this stream + */ + PxU32 totalContacts; + + /** + \brief The current contact index + */ + PxU32 nextContactIndex; + + /** + \brief The current patch Index + */ + PxU32 nextPatchIndex; + + /** + \brief Size of contact patch header + \note This varies whether the patch is modifiable or not. + */ + PxU32 contactPatchHeaderSize; + + /** + \brief Contact point size + \note This varies whether the patch has feature indices or is modifiable. + */ + PxU32 contactPointSize; + + /** + \brief The stream format + */ + StreamFormat mStreamFormat; + + /** + \brief Indicates whether this stream is notify-only or not. + */ + PxU32 forceNoResponse; + + /** + \brief Internal helper for stepping the contact stream iterator + */ + bool pointStepped; + + /** + \brief Specifies if this contactPatch has face indices (handled as bool) + \see faceIndice + */ + PxU32 hasFaceIndices; + + /** + \brief Constructor + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxContactStreamIterator(const PxU8* contactPatches, const PxU8* contactPoints, const PxU32* contactFaceIndices, PxU32 nbPatches, PxU32 nbContacts) + : zero(0.f) + { + bool modify = false; + bool compressedModify = false; + bool response = false; + bool indices = false; + + PxU32 pointSize = 0; + PxU32 patchHeaderSize = sizeof(PxContactPatch); + + const PxContactPatch* patches = reinterpret_cast(contactPatches); + + if(patches) + { + modify = (patches->internalFlags & PxContactPatch::eMODIFIABLE) != 0; + compressedModify = (patches->internalFlags & PxContactPatch::eCOMPRESSED_MODIFIED_CONTACT) != 0; + indices = (patches->internalFlags & PxContactPatch::eHAS_FACE_INDICES) != 0; + + patch = patches; + + contact = reinterpret_cast(contactPoints); + + faceIndice = contactFaceIndices; + + pointSize = compressedModify ? sizeof(PxExtendedContact) : modify ? sizeof(PxModifiableContact) : sizeof(PxContact); + + response = (patch->internalFlags & PxContactPatch::eFORCE_NO_RESPONSE) == 0; + } + + + mStreamFormat = compressedModify ? eCOMPRESSED_MODIFIABLE_STREAM : modify ? eMODIFIABLE_STREAM : eSIMPLE_STREAM; + hasFaceIndices = PxU32(indices); + forceNoResponse = PxU32(!response); + + contactPatchHeaderSize = patchHeaderSize; + contactPointSize = pointSize; + nextPatchIndex = 0; + nextContactIndex = 0; + totalContacts = nbContacts; + totalPatches = nbPatches; + + pointStepped = false; + } + + /** + \brief Returns whether there are more patches in this stream. + \return Whether there are more patches in this stream. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNextPatch() const + { + return nextPatchIndex < totalPatches; + } + + /** + \brief Returns the total contact count. + \return Total contact count. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getTotalContactCount() const + { + return totalContacts; + } + + /** + \brief Returns the total patch count. + \return Total patch count. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getTotalPatchCount() const + { + return totalPatches; + } + + /** + \brief Advances iterator to next contact patch. + */ + PX_CUDA_CALLABLE PX_INLINE void nextPatch() + { + PX_ASSERT(nextPatchIndex < totalPatches); + if(nextPatchIndex) + { + if(nextContactIndex < patch->nbContacts) + { + PxU32 nbToStep = patch->nbContacts - this->nextContactIndex; + contact = reinterpret_cast(reinterpret_cast(contact) + contactPointSize * nbToStep); + } + patch = reinterpret_cast(reinterpret_cast(patch) + contactPatchHeaderSize); + } + nextPatchIndex++; + nextContactIndex = 0; + } + + /** + \brief Returns if the current patch has more contacts. + \return If there are more contacts in the current patch. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNextContact() const + { + return nextContactIndex < (patch->nbContacts); + } + + /** + \brief Advances to the next contact in the patch. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void nextContact() + { + PX_ASSERT(nextContactIndex < patch->nbContacts); + if(pointStepped) + { + contact = reinterpret_cast(reinterpret_cast(contact) + contactPointSize); + faceIndice++; + } + nextContactIndex++; + pointStepped = true; + } + + /** + \brief Gets the current contact's normal + \return The current contact's normal. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getContactNormal() const + { + return getContactPatch().normal; + } + + /** + \brief Gets the inverse mass scale for body 0. + \return The inverse mass scale for body 0. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvMassScale0() const + { + return patch->mMassModification.linear0; + } + + /** + \brief Gets the inverse mass scale for body 1. + \return The inverse mass scale for body 1. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvMassScale1() const + { + return patch->mMassModification.linear1; + } + + /** + \brief Gets the inverse inertia scale for body 0. + \return The inverse inertia scale for body 0. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvInertiaScale0() const + { + return patch->mMassModification.angular0; + } + + /** + \brief Gets the inverse inertia scale for body 1. + \return The inverse inertia scale for body 1. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvInertiaScale1() const + { + return patch->mMassModification.angular1; + } + + /** + \brief Gets the contact's max impulse. + \return The contact's max impulse. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getMaxImpulse() const + { + return mStreamFormat != eSIMPLE_STREAM ? getExtendedContact().maxImpulse : PX_MAX_REAL; + } + + /** + \brief Gets the contact's target velocity. + \return The contact's target velocity. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getTargetVel() const + { + return mStreamFormat != eSIMPLE_STREAM ? getExtendedContact().targetVelocity : zero; + } + + /** + \brief Gets the contact's contact point. + \return The contact's contact point. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getContactPoint() const + { + return contact->contact; + } + + /** + \brief Gets the contact's separation. + \return The contact's separation. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getSeparation() const + { + return contact->separation; + } + + /** + \brief Gets the contact's face index for shape 0. + \return The contact's face index for shape 0. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getFaceIndex0() const + { + return PXC_CONTACT_NO_FACE_INDEX; + } + + /** + \brief Gets the contact's face index for shape 1. + \return The contact's face index for shape 1. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getFaceIndex1() const + { + return hasFaceIndices ? *faceIndice : PXC_CONTACT_NO_FACE_INDEX; + } + + /** + \brief Gets the contact's static friction coefficient. + \return The contact's static friction coefficient. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getStaticFriction() const + { + return getContactPatch().staticFriction; + } + + /** + \brief Gets the contact's dynamic friction coefficient. + \return The contact's dynamic friction coefficient. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getDynamicFriction() const + { + return getContactPatch().dynamicFriction; + } + + /** + \brief Gets the contact's restitution coefficient. + \return The contact's restitution coefficient. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getRestitution() const + { + return getContactPatch().restitution; + } + + /** + \brief Gets the contact's damping value. + \return The contact's damping value. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getDamping() const + { + return getContactPatch().damping; + } + + /** + \brief Gets the contact's material flags. + \return The contact's material flags. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaterialFlags() const + { + return getContactPatch().materialFlags; + } + + /** + \brief Gets the contact's material index for shape 0. + \return The contact's material index for shape 0. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex0() const + { + return PxU16(getContactPatch().materialIndex0); + } + + /** + \brief Gets the contact's material index for shape 1. + \return The contact's material index for shape 1. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex1() const + { + return PxU16(getContactPatch().materialIndex1); + } + + /** + \brief Advances the contact stream iterator to a specific contact index. + \return True if advancing was possible + */ + bool advanceToIndex(const PxU32 initialIndex) + { + PX_ASSERT(this->nextPatchIndex == 0 && this->nextContactIndex == 0); + + PxU32 numToAdvance = initialIndex; + + if(numToAdvance == 0) + { + PX_ASSERT(hasNextPatch()); + nextPatch(); + return true; + } + + while(numToAdvance) + { + while(hasNextPatch()) + { + nextPatch(); + PxU32 patchSize = patch->nbContacts; + if(numToAdvance <= patchSize) + { + contact = reinterpret_cast(reinterpret_cast(contact) + contactPointSize * numToAdvance); + nextContactIndex += numToAdvance; + return true; + } + else + { + numToAdvance -= patchSize; + } + } + } + return false; + } + +private: + + /** + \brief Internal helper + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxContactPatch& getContactPatch() const + { + return *static_cast(patch); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxExtendedContact& getExtendedContact() const + { + PX_ASSERT(mStreamFormat == eMODIFIABLE_STREAM || mStreamFormat == eCOMPRESSED_MODIFIABLE_STREAM); + return *static_cast(contact); + } + +}; + +/** +\brief Contact patch friction information. +*/ +struct PxFrictionPatch +{ + /** + \brief Max anchors per patch + */ + static const PxU32 MAX_ANCHOR_COUNT = 2; + + /** + \brief Friction anchors' positions + */ + PxVec3 anchorPositions[MAX_ANCHOR_COUNT]; + + /** + \brief Friction anchors' impulses + */ + PxVec3 anchorImpulses[MAX_ANCHOR_COUNT]; + + /** + \brief Friction anchor count + */ + PxU32 anchorCount; +}; + +/** +\brief A class to iterate over a friction anchor stream. +*/ +class PxFrictionAnchorStreamIterator +{ +public: + /** + \brief Constructor + \param contactPatches Pointer to first patch header in contact stream containing contact patch data + \param frictionPatches Buffer containing contact patches friction information. + \param patchCount Number of contact patches stored in the contact stream + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxFrictionAnchorStreamIterator(const PxU8* contactPatches, const PxU8* frictionPatches, PxU32 patchCount) + : + mContactPatches(reinterpret_cast(contactPatches)), + mFrictionPatches(reinterpret_cast(frictionPatches)), + mPatchCount(patchCount), + mFrictionAnchorIndex(-1), + mPatchIndex(-1) + {} + + /** + \brief Check if there are more patches. + \return true if there are more patches. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNextPatch() const + { + return isValid() && mPatchIndex < PxI32(mPatchCount) - 1; + } + + /** + \brief Advance to the next patch. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void nextPatch() + { + PX_ASSERT(hasNextPatch()); + ++mPatchIndex; + mFrictionAnchorIndex = -1; + } + + /** + \brief Check if current patch has more friction anchors. + \return true if there are more friction anchors in current patch. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNextFrictionAnchor() const + { + return patchIsValid() && mFrictionAnchorIndex < PxI32(mFrictionPatches[mPatchIndex].anchorCount) - 1; + } + + /** + \brief Advance to the next friction anchor in the patch. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void nextFrictionAnchor() + { + PX_ASSERT(hasNextFrictionAnchor()); + mFrictionAnchorIndex++; + } + + /** + \brief Get the friction anchor's position. + \return The friction anchor's position. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getPosition() const + { + PX_ASSERT(frictionAnchorIsValid()); + return mFrictionPatches[mPatchIndex].anchorPositions[mFrictionAnchorIndex]; + } + + /** + \brief Get the friction anchor's impulse. + \return The friction anchor's impulse. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getImpulse() const + { + PX_ASSERT(frictionAnchorIsValid()); + return mFrictionPatches[mPatchIndex].anchorImpulses[mFrictionAnchorIndex]; + } + + /** + \brief Get the friction anchor's normal. + \return The friction anchor's normal. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getNormal() const + { + PX_ASSERT(patchIsValid()); + return mContactPatches[mPatchIndex].normal; + } + + /** + \brief Get current patch's static friction coefficient. + \return The patch's static friction coefficient. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getStaticFriction() const + { + PX_ASSERT(patchIsValid()); + return mContactPatches[mPatchIndex].staticFriction; + } + + /** + \brief Get current patch's dynamic friction coefficient. + \return The patch's dynamic friction coefficient. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getDynamicFriction() const + { + PX_ASSERT(patchIsValid()); + return mContactPatches[mPatchIndex].dynamicFriction; + } + + /** + \brief Get current patch's combined material flags. + \return The patch's combined material flags. + \see PxMaterialFlag, PxCombineMode + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMaterialFlags getMaterialFlags() const + { + PX_ASSERT(patchIsValid()); + return PxMaterialFlags(mContactPatches[mPatchIndex].materialFlags); + } + +private: + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxFrictionAnchorStreamIterator(); + + /** + \brief Check if valid. + \return true if valid. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isValid() const + { + return mContactPatches && mFrictionPatches; + } + + /** + \brief Check if current patch is valid. + \return true if current patch is valid. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool patchIsValid() const + { + return isValid() && mPatchIndex >= 0 && mPatchIndex < PxI32(mPatchCount); + } + + /** + \brief Check if current friction anchor is valid. + \return true if current friction anchor is valid. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool frictionAnchorIsValid() const + { + return patchIsValid() && mFrictionAnchorIndex >= 0 && mFrictionAnchorIndex < PxI32(mFrictionPatches[mPatchIndex].anchorCount); + } + + const PxContactPatch* mContactPatches; + const PxFrictionPatch* mFrictionPatches; + PxU32 mPatchCount; + PxI32 mFrictionAnchorIndex; + PxI32 mPatchIndex; +}; + +/** +\brief Contains contact information for a contact reported by the direct-GPU contact report API. See PxDirectGPUAPI::copyContactData(). +*/ +struct PxGpuContactPair +{ + PxU8* contactPatches; //!< Ptr to contact patches. Type: PxContactPatch*, size: nbPatches. + PxU8* contactPoints; //!< Ptr to contact points. Type: PxContact*, size: nbContacts. + PxReal* contactForces; //!< Ptr to contact forces. Size: nbContacts. + PxU8* frictionPatches; //!< Ptr to friction patch information. Type: PxFrictionPatch*, size: nbPatches. + PxU32 transformCacheRef0; //!< Ref to shape0's transform in transform cache. + PxU32 transformCacheRef1; //!< Ref to shape1's transform in transform cache. + PxNodeIndex nodeIndex0; //!< Unique Id for actor0 if the actor is dynamic. + PxNodeIndex nodeIndex1; //!< Unique Id for actor1 if the actor is dynamic. + PxActor* actor0; //!< Ptr to PxActor for actor0. + PxActor* actor1; //!< Ptr to PxActor for actor1. + + PxU16 nbContacts; //!< Num contacts. + PxU16 nbPatches; //!< Num patches. +}; + + +#if PX_VC +#pragma warning(pop) +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxContactModifyCallback.h b/Jusin154_Team3D/Engine/Public/PhysX/PxContactModifyCallback.h new file mode 100644 index 000000000..6c52d42bb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxContactModifyCallback.h @@ -0,0 +1,523 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTACT_MODIFY_CALLBACK_H +#define PX_CONTACT_MODIFY_CALLBACK_H + +#include "PxPhysXConfig.h" +#include "PxShape.h" +#include "PxContact.h" +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxShape; + +/** +\brief An array of contact points, as passed to contact modification. + +The word 'set' in the name does not imply that duplicates are filtered in any +way. This initial set of contacts does potentially get reduced to a smaller +set before being passed to the solver. + +You can use the accessors to read and write contact properties. The number of +contacts is immutable, other than being able to disable contacts using ignore(). + +\see PxContactModifyCallback, PxModifiableContact +*/ +class PxContactSet +{ +public: + /** + \brief Get the position of a specific contact point in the set. + \param[in] i Index of the point in the set + \return Position to the requested point in world space + + \see PxModifiableContact.point + */ + PX_FORCE_INLINE const PxVec3& getPoint(PxU32 i) const { return mContacts[i].contact; } + + /** + \brief Alter the position of a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] p The new position in world space + + \see PxModifiableContact.point + */ + PX_FORCE_INLINE void setPoint(PxU32 i, const PxVec3& p) { mContacts[i].contact = p; } + + /** + \brief Get the contact normal of a specific contact point in the set. + \param[in] i Index of the point in the set + \return The requested normal in world space + + \see PxModifiableContact.normal + */ + PX_FORCE_INLINE const PxVec3& getNormal(PxU32 i) const { return mContacts[i].normal; } + + /** + \brief Alter the contact normal of a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] n The new normal in world space + + \note Changing the normal can cause contact points to be ignored. + + \see PxModifiableContact.normal + */ + PX_FORCE_INLINE void setNormal(PxU32 i, const PxVec3& n) + { + PxContactPatch* patch = getPatch(); + patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES; + mContacts[i].normal = n; + } + + /** + \brief Get the separation distance of a specific contact point in the set. + \param[in] i Index of the point in the set + \return The separation. Negative implies penetration. + + \see PxModifiableContact.separation + */ + PX_FORCE_INLINE PxReal getSeparation(PxU32 i) const { return mContacts[i].separation; } + + /** + \brief Alter the separation of a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] s The new separation + + \see PxModifiableContact.separation + */ + PX_FORCE_INLINE void setSeparation(PxU32 i, PxReal s) { mContacts[i].separation = s; } + + /** + \brief Get the target velocity of a specific contact point in the set. + \param[in] i Index of the point in the set + \return The target velocity in world frame + + \see PxModifiableContact.targetVelocity + + */ + PX_FORCE_INLINE const PxVec3& getTargetVelocity(PxU32 i) const { return mContacts[i].targetVelocity; } + + /** + \brief Alter the target velocity of a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] v The new velocity in world frame as seen from the second actor in the contact pair, i.e., the solver will try to achieve targetVel == (vel1 - vel2) + \note The sign of the velocity needs to be flipped depending on the order of the actors in the pair. There is no guarantee about the consistency of the order from frame to frame. + + \see PxModifiableContact.targetVelocity + */ + PX_FORCE_INLINE void setTargetVelocity(PxU32 i, const PxVec3& v) + { + PxContactPatch* patch = getPatch(); + patch->internalFlags |= PxContactPatch::eHAS_TARGET_VELOCITY; + mContacts[i].targetVelocity = v; + } + + /** + \brief Get the face index with respect to the first shape of the pair for a specific contact point in the set. + \param[in] i Index of the point in the set + \return The face index of the first shape + \note At the moment, the first shape is never a tri-mesh, therefore this function always returns PXC_CONTACT_NO_FACE_INDEX + + \see PxModifiableContact.internalFaceIndex0 + */ + PX_FORCE_INLINE PxU32 getInternalFaceIndex0(PxU32 i) const { PX_UNUSED(i); return PXC_CONTACT_NO_FACE_INDEX; } + + /** + \brief Get the face index with respect to the second shape of the pair for a specific contact point in the set. + \param[in] i Index of the point in the set + \return The face index of the second shape + + \see PxModifiableContact.internalFaceIndex1 + */ + PX_FORCE_INLINE PxU32 getInternalFaceIndex1(PxU32 i) const + { + PxContactPatch* patch = getPatch(); + if (patch->internalFlags & PxContactPatch::eHAS_FACE_INDICES) + { + return reinterpret_cast(mContacts + mCount)[mCount + i]; + } + return PXC_CONTACT_NO_FACE_INDEX; + } + + /** + \brief Get the maximum impulse for a specific contact point in the set. + \param[in] i Index of the point in the set + \return The maximum impulse + + \see PxModifiableContact.maxImpulse + */ + PX_FORCE_INLINE PxReal getMaxImpulse(PxU32 i) const { return mContacts[i].maxImpulse; } + + /** + \brief Alter the maximum impulse for a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] s The new maximum impulse + + \note Must be nonnegative. If set to zero, the contact point will be ignored + + \see PxModifiableContact.maxImpulse, ignore() + */ + PX_FORCE_INLINE void setMaxImpulse(PxU32 i, PxReal s) + { + PxContactPatch* patch = getPatch(); + patch->internalFlags |= PxContactPatch::eHAS_MAX_IMPULSE; + mContacts[i].maxImpulse = s; + } + + /** + \brief Get the restitution coefficient for a specific contact point in the set. + \param[in] i Index of the point in the set + \return The restitution coefficient + + \see PxModifiableContact.restitution + */ + PX_FORCE_INLINE PxReal getRestitution(PxU32 i) const { return mContacts[i].restitution; } + + /** + \brief Alter the restitution coefficient for a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] r The new restitution coefficient + + \note Valid ranges [0,1] + + \see PxModifiableContact.restitution + */ + PX_FORCE_INLINE void setRestitution(PxU32 i, PxReal r) + { + PxContactPatch* patch = getPatch(); + patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES; + mContacts[i].restitution = r; + } + + /** + \brief Get the static friction coefficient for a specific contact point in the set. + \param[in] i Index of the point in the set + \return The friction coefficient (dimensionless) + + \see PxModifiableContact.staticFriction + */ + PX_FORCE_INLINE PxReal getStaticFriction(PxU32 i) const { return mContacts[i].staticFriction; } + + /** + \brief Alter the static friction coefficient for a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] f The new friction coefficient (dimensionless), range [0, inf] + + \see PxModifiableContact.staticFriction + */ + PX_FORCE_INLINE void setStaticFriction(PxU32 i, PxReal f) + { + PxContactPatch* patch = getPatch(); + patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES; + mContacts[i].staticFriction = f; + } + + /** + \brief Get the static friction coefficient for a specific contact point in the set. + \param[in] i Index of the point in the set + \return The friction coefficient + + \see PxModifiableContact.dynamicFriction + */ + PX_FORCE_INLINE PxReal getDynamicFriction(PxU32 i) const { return mContacts[i].dynamicFriction; } + + /** + \brief Alter the static dynamic coefficient for a specific contact point in the set. + \param[in] i Index of the point in the set + \param[in] f The new friction coefficient + + \see PxModifiableContact.dynamicFriction + */ + PX_FORCE_INLINE void setDynamicFriction(PxU32 i, PxReal f) + { + PxContactPatch* patch = getPatch(); + patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES; + mContacts[i].dynamicFriction = f; + } + + /** + \brief Ignore the contact point. + \param[in] i Index of the point in the set + + If a contact point is ignored then no force will get applied at this point. This can be used to disable collision in certain areas of a shape, for example. + */ + PX_FORCE_INLINE void ignore(PxU32 i) { setMaxImpulse(i, 0.0f); } + + /** + \brief The number of contact points in the set. + */ + PX_FORCE_INLINE PxU32 size() const { return mCount; } + + /** + \brief Returns the invMassScale of body 0 + + A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact + treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass. + */ + PX_FORCE_INLINE PxReal getInvMassScale0() const + { + PxContactPatch* patch = getPatch(); + return patch->mMassModification.linear0; + } + + /** + \brief Returns the invMassScale of body 1 + + A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact + treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass. + */ + PX_FORCE_INLINE PxReal getInvMassScale1() const + { + PxContactPatch* patch = getPatch(); + return patch->mMassModification.linear1; + } + + /** + \brief Returns the invInertiaScale of body 0 + + A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact + treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia. + */ + PX_FORCE_INLINE PxReal getInvInertiaScale0() const + { + PxContactPatch* patch = getPatch(); + return patch->mMassModification.angular0; + } + + /** + \brief Returns the invInertiaScale of body 1 + + A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact + treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia. + */ + PX_FORCE_INLINE PxReal getInvInertiaScale1() const + { + PxContactPatch* patch = getPatch(); + return patch->mMassModification.angular1; + } + + /** + \brief Sets the invMassScale of body 0 + \param[in] scale The new scale + + This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact + treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass. + */ + PX_FORCE_INLINE void setInvMassScale0(const PxReal scale) + { + PxContactPatch* patch = getPatch(); + patch->mMassModification.linear0 = scale; + patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS; + } + + /** + \brief Sets the invMassScale of body 1 + \param[in] scale The new scale + + This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact + treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass. + */ + PX_FORCE_INLINE void setInvMassScale1(const PxReal scale) + { + PxContactPatch* patch = getPatch(); + patch->mMassModification.linear1 = scale; + patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS; + } + + /** + \brief Sets the invInertiaScale of body 0 + \param[in] scale The new scale + + This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact + treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia. + */ + PX_FORCE_INLINE void setInvInertiaScale0(const PxReal scale) + { + PxContactPatch* patch = getPatch(); + patch->mMassModification.angular0 = scale; + patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS; + } + + /** + \brief Sets the invInertiaScale of body 1 + \param[in] scale The new scale + + This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact + treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia. + */ + PX_FORCE_INLINE void setInvInertiaScale1(const PxReal scale) + { + PxContactPatch* patch = getPatch(); + patch->mMassModification.angular1 = scale; + patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS; + } + +protected: + + PX_FORCE_INLINE PxContactPatch* getPatch() const + { + const size_t headerOffset = sizeof(PxContactPatch)*mCount; + return reinterpret_cast(reinterpret_cast(mContacts) - headerOffset); + } + + PxU32 mCount; //!< Number of contact points in the set + PxModifiableContact* mContacts; //!< The contact points of the set +}; + + + +/** +\brief An array of instances of this class is passed to PxContactModifyCallback::onContactModify(). + +\see PxContactModifyCallback +*/ + +class PxContactModifyPair +{ +public: + + /** + \brief The actors which make up the pair in contact. + + Note that these are the actors as seen by the simulation, and may have been deleted since the simulation step started. + */ + const PxRigidActor* actor[2]; + + /** + \brief The shapes which make up the pair in contact. + + Note that these are the shapes as seen by the simulation, and may have been deleted since the simulation step started. + */ + const PxShape* shape[2]; + + /** + \brief The shape to world transforms of the two shapes. + + These are the transforms as the simulation engine sees them, and may have been modified by the application + since the simulation step started. + */ + PxTransform transform[2]; + + /** + \brief An array of contact points between these two shapes. + */ + PxContactSet contacts; +}; + + +/** +\brief An interface class that the user can implement in order to modify contact constraints. + +Threading: It is necessary to make this class thread safe as it will be called in the context of the +simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded +parts of the physics engine. + +You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in +the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects. + +Please note: ++ Raising the contact modification flag will not wake the actors up automatically. ++ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the + filter shader/callback has to be used to clear the contact modification flag. ++ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping. + +\see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback() +*/ +class PxContactModifyCallback +{ +public: + + /** + \brief Passes modifiable arrays of contacts to the application. + + The initial contacts are regenerated from scratch each frame by collision detection. + + The number of contacts can not be changed, so you cannot add your own contacts. You may however + disable contacts using PxContactSet::ignore(). + + \param[in,out] pairs The contact pairs that may be modified + \param[in] count Number of contact pairs + + \see PxContactModifyPair + */ + virtual void onContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0; + +protected: + virtual ~PxContactModifyCallback(){} +}; + +/** +\brief An interface class that the user can implement in order to modify CCD contact constraints. + +Threading: It is necessary to make this class thread safe as it will be called in the context of the +simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded +parts of the physics engine. + +You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in +the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects. + +Please note: ++ Raising the contact modification flag will not wake the actors up automatically. ++ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the + filter shader/callback has to be used to clear the contact modification flag. ++ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping. + +\see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback() +*/ +class PxCCDContactModifyCallback +{ +public: + + /** + \brief Passes modifiable arrays of contacts to the application. + + The initial contacts are regenerated from scratch each frame by collision detection. + + The number of contacts can not be changed, so you cannot add your own contacts. You may however + disable contacts using PxContactSet::ignore(). + + \param[in,out] pairs The contact pairs that may be modified + \param[in] count Number of contact pairs + */ + virtual void onCCDContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0; + +protected: + virtual ~PxCCDContactModifyCallback(){} +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableAttachment.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableAttachment.h new file mode 100644 index 000000000..6b910d53b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableAttachment.h @@ -0,0 +1,237 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_ATTACHMENT_H +#define PX_DEFORMABLE_ATTACHMENT_H + +#include "PxConeLimitedConstraint.h" +#include "PxFiltering.h" +#include "PxNodeIndex.h" +#include "foundation/PxTransform.h" +#include "common/PxCoreUtilityTypes.h" +#include "common/PxBase.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Struct to specify attachment between a particle/vertex and a rigid +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +struct PX_DEPRECATED PxParticleRigidAttachment : public PxParticleRigidFilterPair +{ + PxParticleRigidAttachment() {} + + PxParticleRigidAttachment(const PxConeLimitedConstraint& coneLimitedConstraint, const PxVec4& localPose0): + PxParticleRigidFilterPair(PxNodeIndex().getInd(), PxNodeIndex().getInd()), + mLocalPose0(localPose0), + mConeLimitParams(coneLimitedConstraint) + { + } + + PX_ALIGN(16, PxVec4 mLocalPose0); //!< local pose in body frame - except for statics, these are using world positions. + PxConeLimitParams mConeLimitParams; //!< Parameters to specify cone constraints +}; + +/** +\brief Identifies the attachment target type for an actor involved in an attachment. + +The target type provides actor related information about what kind of attachment should be created. +\see PxDeformableAttachmentData +*/ +struct PxDeformableAttachmentTargetType +{ + enum Enum + { + eVERTEX, //!< Attachment to vertex points of deformable mesh. + eTRIANGLE, //!< Attachment to points on triangles of deformable mesh. + eTETRAHEDRON, //!< Attachment to points in tetrahedrons of deformable mesh. + eRIGID, //!< Attachment to points in rigid actor local frame. + eWORLD, //!< Attachment to points in global frame. + eUNDEFINED //!< Internal use only. + }; +}; + +/** +\brief Attachment data for a pair of actors where one of the actors must be a deformable. For attaching rigids to rigids or rigids to the world, use joints instead. + +An attachment is created based on a collection of attachment points. The attachment +points are specified relatively to each of the two actors. They can be defined on the basis of +deformable mesh elements, such as vertices, triangles or tetrahedrons. Depending on the deformable mesh element type, +a baricentric coordinate further specifies the location on the element. For rigid or world attachments, the points are +specified using cartesion coordinates. + +The points are specified by: +- Two actor instances and their types +- Two attachment target types +- Two sets of attachment data related to the target types + + +Table 1) The type of an actor limits which target types can be used: + + PxDeformableSurface: eVERTEX, eTRIANGLE + PxDeformableVolume: eVERTEX, eTETRAHEDRON (simulation mesh) + PxRigidActor: eRIGID + NULL: eWORLD + + +Table 2) On the other hand, the target type dictates which per-actor attachment data is needed: + + eVERTEX: indices + eTRIANGLE: indices, coords (barycentric: x, y, z) + eTETRAHEDRON: indices, coords (barycentric: x, y, z, w) + eRIGID: pose, coords (cartesian, local space: x, y, z) + eWORLD: pose, coords (cartesion, world space: x, y, z) + +Each entry pair in (indices, coords) defines an attachment point. Therefore, the size of indices and coords need to match up, if both are required. + +\note The topology of an attachment is fixed once it's been created. To change the attachment points, +the application will need to release the attachment and create a new attachment with the updated attachment points. +The pose for attachments to eRIGID or eWORLD, however, can be updated without re-creating the attachment. + +\see PxDeformableAttachment, PxPhysics::createDeformableAttachment() +*/ +struct PxDeformableAttachmentData +{ + PxDeformableAttachmentData() + { + for (PxU32 i = 0; i < 2; i++) + { + actor[i] = NULL; + type[i] = PxDeformableAttachmentTargetType::eUNDEFINED; + pose[i] = PxTransform(PxIdentity); + } + } + + /** + \brief Actor 0 and Actor 1. At least one of the actors must be a deformable. For attaching statically to the world, one actor is allowed to be NULL while the other is a deformable. + */ + PxActor* actor[2]; + + /** + \brief One target type per actor. + The target type must be supported by the corresponding actor type, see [table 1](#attachment_table1). + */ + PxDeformableAttachmentTargetType::Enum type[2]; + + /** + \brief Indices data per actor. + The content of the two index arrays depends on the corresponding target types 'type[0]' and 'type[1]' + as well as the number of attachments: + For PxDeformableAttachmentTargetType::eVERTEX, eTRIANGLE and eTETRAHEDRON, the corresponding array describes vertex, + triangle or tetrahedon indices, and the size of the array needs to match the number of attachments. + For PxDeformableAttachmentTargetType::eRIGID and eWORLD, the corresponding array needs to be empty. + See [table 2](#attachment_table2). + */ + PxTypedBoundedData indices[2]; + + /** + \brief Coordinate data per actor. + The content of the two coords arrays depends on the corresponding target types 'type[0]' and 'type[1]' + as well as the number of attachments: + For PxDeformableAttachmentTargetType::eVERTEX, the corresponding array needs to be empty. + For PxDeformableAttachmentTargetType::eTRIANGLE and eTETRAHEDRON, the corresponding array descibes barycentric coordinates, + and the size of the array needs to match the number of attachments. + For PxDeformableAttachmentTargetType::eRIGID and eWORLD, the corresponding array describes cartesian coordinates and the size + of the array needs to match the number of attachments. + See [table 2](#attachment_table2). + */ + PxTypedBoundedData coords[2]; + + /** + \brief Pose per actor. + Global pose for PxDeformableAttachmentTargetType::eWORLD or local pose for PxDeformableAttachmentTargetType::eRIGID, see [table 2](#attachment_table2). + The pose represents a coordinate frame for all attachment points specified by the array of euclidean coords in the case of PxDeformableAttachmentTargetType::eRIGID and eWORLD attachments. + It can be updated after the attachment has been created. + + \see PxDeformableAttachment::updatePose() + */ + PxTransform pose[2]; +}; + +/** +\brief PxDeformableAttachment class representing an attachment for deformable actors. + +An attachment is a collection of one or more positional constraints between a point on one actor and a point on another actor. + +\see PxDeformableAttachmentData, PxPhysics::createDeformableAttachment() +*/ +class PxDeformableAttachment : public PxBase +{ +public: + /** + \brief Gets the two actors for this attachment. + + \param[out] actor0 The first actor, may be NULL + \param[out] actor1 The second actor, may be NULL + */ + virtual void getActors(PxActor*& actor0, PxActor*& actor1) const = 0; + + /** + \brief Updates the pose of the attachment. + + \param[in] pose Pose relative to world or rigid actor transform. Valid only for attachment against world or rigid actor. + */ + virtual void updatePose(const PxTransform& pose) = 0; + + /** + \brief Returns string name of PxDeformableAttachment, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxDeformableAttachment"; } + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + virtual ~PxDeformableAttachment() {} + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxDeformableAttachment(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxDeformableAttachment(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxDeformableAttachment", PxBase); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableBody.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableBody.h new file mode 100644 index 000000000..ceaa749f1 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableBody.h @@ -0,0 +1,396 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_BODY_H +#define PX_DEFORMABLE_BODY_H + +#include "PxActor.h" +#include "PxDeformableBodyFlag.h" +#include "PxFEMParameter.h" // deprecated + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + +class PxCudaContextManager; + +/** +\brief Represents a deformable body, a base class for deformable actors +\see PxDeformableSurface, PxDeformableVolume, PxActor +*/ +class PxDeformableBody : public PxActor +{ +public: + + /** + \brief Raises or clears a particular deformable body flag. + + See the list of flags #PxDeformableBodyFlag + + Default: No flags are set + + \param[in] flag The PxDeformableBodyFlag to raise(set) or clear. See #PxDeformableBodyFlag. + \param[in] val The new boolean value for the flag. + */ + virtual void setDeformableBodyFlag(PxDeformableBodyFlag::Enum flag, bool val) = 0; + + /** + \brief Sets deformable body flags. + + See the list of flags #PxDeformableBodyFlag + + Default: No flags are set + + \param[in] flags The PxDeformableBodyFlags to set. + */ + virtual void setDeformableBodyFlags(PxDeformableBodyFlags flags) = 0; + + /** + \brief Reads the deformable body flags. + + See the list of flags #PxDeformableBodyFlag + + \return The values of the deformable body flags. + + \see setDeformableBodyFlag() + */ + virtual PxDeformableBodyFlags getDeformableBodyFlags() const = 0; + + /** + \brief Sets the linear damping parameter. + + After every timestep the velocity is reduced while the magnitude of the + reduction depends on the linearDamping value. + \see PxRigidBody.setLinearDamping + Default: 0.05 + \param[in] linearDamping The linear damping parameter + */ + virtual void setLinearDamping(const PxReal linearDamping) = 0; + + /** + \brief Retrieves linear velocity damping parameter. + \see setLinearDamping + + \return The linear damping parameter + */ + virtual PxReal getLinearDamping() const = 0; + + /** + \brief Sets the maximal velocity vertices can reach + + Allows to limit the vertices' maximal velocity to control the maximal distance a vertex can move per frame + Default: 1.0e32 + \param[in] maxLinearVelocity The maximal linear velocity + */ + virtual void setMaxLinearVelocity(const PxReal maxLinearVelocity) = 0; + + /** + \brief Sets the maximal velocity vertices can reach + + \deprecated Use setMaxLinearVelocity instead. + + Allows to limit the vertices' maximal velocity to control the maximal distance a vertex can move per frame + Default: 1.0e32 + \param[in] maxVelocity The maximal velocity + */ + PX_DEPRECATED PX_FORCE_INLINE void setMaxVelocity(const PxReal maxVelocity) { setMaxLinearVelocity(maxVelocity); } + + /** + \brief Retrieves maximal velocity a vertex can have. + + \return The maximal velocity + */ + virtual PxReal getMaxLinearVelocity() const = 0; + + /** + \brief Retrieves maximal velocity a vertex can have. + + \deprecated Use getMaxLinearVelocity instead. + + \return The maximal velocity + */ + PX_DEPRECATED PX_FORCE_INLINE PxReal getMaxVelocity() const { return getMaxLinearVelocity(); } + + /** + \brief Sets the maximal depenetration velocity vertices can reach + + Allows to limit the vertices' maximal depenetration velocity to avoid that collision responses lead to very high particle velocities + Default: 1.0e32 + \param[in] maxDepenetrationVelocity The maximal depenetration velocity + */ + virtual void setMaxDepenetrationVelocity(const PxReal maxDepenetrationVelocity) = 0; + + /** + \brief Retrieves maximal depenetration velocity a vertex can have. + + \return The maximal depenetration velocity + */ + virtual PxReal getMaxDepenetrationVelocity() const = 0; + + /** + \brief Sets the self collision filter distance. + + Penetration distance that needs to be exceeded before contacts for self collision are generated. + Will only have an effect if self collisions are enabled. + Default: 0.1 + + \param[in] selfCollisionFilterDistance The self collision filter distance + */ + virtual void setSelfCollisionFilterDistance(const PxReal selfCollisionFilterDistance) = 0; + + /** + \brief Retrieves the self collision filter distance. + + \return The self collision filter distance + \see setSelfCollisionFilterDistance + */ + virtual PxReal getSelfCollisionFilterDistance() const = 0; + + /** + \brief Sets the solver iteration count for the deformable body. + + Since deformables are currently implemented using an XPBD solver (extended position based dynamics), minVelocityIters is ignored. + Default: 4 position iterations, 1 velocity iteration + + \param[in] minPositionIters Number of position iterations the solver should perform for this deformable body. Range: [1,255] + \param[in] minVelocityIters Number of velocity iterations, currently ignored. Range: [1,255] + \see getSolverIterationCounts() + */ + virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0; + + /** + \brief Retrieves the solver iteration counts. + + \see setSolverIterationCounts() + */ + virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0; + + /** + \brief Sets the threshold controlling sleeping of the deformable body. + + Threshold that defines the maximal magnitude of the linear motion a deformable body can move in one second + before it becomes a candidate for sleeping. + + \see PxRigidDynamic.setSleepThreshold + Default: 0.05 + + \param[in] sleepThreshold The sleep threshold + */ + virtual void setSleepThreshold(const PxReal sleepThreshold) = 0; + + /** + \brief Retrieves the sleep threshold. + \see setSleepThreshold + + \return The sleep threshold + */ + virtual PxReal getSleepThreshold() const = 0; + + /** + \brief Sets the threshold controlling settling phase before sleeping of the deformable body. + + Threshold that defines the maximal magnitude of the linear motion a deformable body can move + in one second before it becomes a candidate for sleeping and settling damping is engaged. + The settling threshold needs to be higher than the sleep threshold. + Default: 0.1 + \see setSettlingDamping + + \param[in] settlingThreshold The settling threshold + */ + virtual void setSettlingThreshold(const PxReal settlingThreshold) = 0; + + /** + \brief Retrieves the settling threshold. + \see setSettlingThreshold + + \return The settling threshold + */ + virtual PxReal getSettlingThreshold() const = 0; + + /** + \brief Sets the damping parameter used for settling phase. + + If the maximum linear velocity of the deformable body falls below the settling threshold, the deformable body + enters the settling phase in which the settling damping is applied. + + Default: 10.0 + \param[in] settlingDamping The settling damping + \see setLinearDamping, setSettlingThreshold + */ + virtual void setSettlingDamping(const PxReal settlingDamping) = 0; + + /** + \brief Retrieves settling damping parameter. + \see setSettlingDamping + + \return The settling damping parameter + */ + virtual PxReal getSettlingDamping() const = 0; + + /** + \brief Sets the wake counter for the deformable body. + + The wake counter value determines the minimum amount of time until the deformable body can be put to sleep. Please note + that a deformable body will not be put to sleep if any vertex velocity is above the specified threshold + or if other awake objects are touching it. + + \note Passing in a positive value will wake the deformable body up automatically. + + Default: 0.4 (which corresponds to 20 frames for a time step of 0.02) + + \param[in] wakeCounterValue Wake counter value. Range: [0, PX_MAX_F32) + + \see isSleeping() getWakeCounter() + */ + virtual void setWakeCounter(PxReal wakeCounterValue) = 0; + + /** + \brief Returns the wake counter of the deformable body. + + \return The wake counter of the deformable body. + + \see isSleeping() setWakeCounter() + */ + virtual PxReal getWakeCounter() const = 0; + + /** + \brief Returns true if this deformable body is sleeping. + + When an actor does not move for a period of time, it is no longer simulated in order to save time. This state + is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object, + or a sleep-affecting property is changed by the user, the entire sleep mechanism should be transparent to the user. + + A deformable volume can only go to sleep if all vertices are ready for sleeping. A deformable body is guaranteed to be awake + if at least one of the following holds: + + \li The wake counter is positive (\see setWakeCounter()). + \li The velocity of any vertex is above the sleep threshold. + + If a deformable body is sleeping, the following state is guaranteed: + + \li The wake counter is zero. + \li The linear velocity of all vertices is zero. + + When a deformable body gets inserted into a scene, it will be considered asleep if all the points above hold, else it will + be treated as awake. + + \note It is invalid to use this method if the deformable body has not been added to a scene already. + + \return True if the deformable body is sleeping. + + \see isSleeping() + */ + virtual bool isSleeping() const = 0; + + /** + \brief Retrieve a shape pointer belonging to the actor. + + \see PxShape getNbShapes() PxShape::release() + */ + + virtual PxShape* getShape() = 0; + + /** + \brief Attaches a shape + + Attaches the shape to use for collision detection for deformable surfaces and volumes. + Each deformable needs to have exactly one exclusive shape attached for simulation. If a shape has + already been attached to a deformable, detachShape needs to be called prior to attaching + a new shape. + + Deformable surfaces need a shape with triangle mesh geometry, which can be created with + PxPhysics::createShape(const PxGeometry&, const PxDeformableSurfaceMaterial& material, bool, PxShapeFlags), or + PxPhysics::createShape(const PxGeometry&, PxDeformableSurfaceMaterial*const*, PxU16, bool, PxShapeFlags) + Deformable surfaces use the same triangle mesh for collision detection and dynamics computations. + + Deformable volumes need a shape with tetrahedron mesh geometry, which can be created with + PxPhysics::createShape(const PxGeometry&, const PxDeformableVolumeMaterial& material, bool, PxShapeFlags), or + PxPhysics::createShape(const PxGeometry&, PxDeformableVolumeMaterial*const*, PxU16, bool, PxShapeFlags) + Deformable volumes additionally need a separate tetrahedron mesh for dynamics, which can be attached using + PxDeformbleVolume::attachSimulationMesh. + + \param[in] shape The shape to use for collisions, (and dynamics in case of deformable surfaces) + + \return Returns true if the operation was successful + */ + virtual bool attachShape(PxShape& shape) = 0; + + /** + \brief Detaches the shape + + Detaches the shape used for collision detection. + + \see void PxDeformableVolume.detachSimulationMesh() + */ + virtual void detachShape() = 0; + + /** + \brief Returns the cuda context manager + + \return The cuda context manager + */ + virtual PxCudaContextManager* getCudaContextManager() const = 0; + + /** + \brief Deprecated: Sets parameters for FEM internal solve + \param[in] params parameters + \see getParameter() + */ + PX_DEPRECATED virtual void setParameter(const PxFEMParameters& params) = 0; + + /** + \brief Deprecated: Gets parameters for FEM internal solve + \return parameters + \see setParameter() + */ + PX_DEPRECATED virtual PxFEMParameters getParameter() const = 0; + +protected: + PX_INLINE PxDeformableBody(PxType concreteType, PxBaseFlags baseFlags) : PxActor(concreteType, baseFlags) {} + PX_INLINE PxDeformableBody(PxBaseFlags baseFlags) : PxActor(baseFlags) {} + virtual ~PxDeformableBody() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxDeformableBody", PxActor); } +}; + + +#if PX_VC +#pragma warning(pop) +#endif + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_BODY_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableBodyFlag.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableBodyFlag.h new file mode 100644 index 000000000..2714e4287 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableBodyFlag.h @@ -0,0 +1,59 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_BODY_FLAGS_H +#define PX_DEFORMABLE_BODY_FLAGS_H + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Flags to enable or disable special modes of a PxDeformableBody instance +*/ +struct PxDeformableBodyFlag +{ + enum Enum + { + eDISABLE_SELF_COLLISION = 1 << 0, //!< Determines if self collision will be detected and resolved + eENABLE_SPECULATIVE_CCD = 1 << 1, //!< Enables support for speculative contact generation, see #PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD + eKINEMATIC = 1 << 2 //!< Enables support for kinematic motion of the simulation mesh, see #PxRigidBodyFlag::eKINEMATIC + }; +}; + +typedef PxFlags PxDeformableBodyFlags; + +#if !PX_DOXYGEN +} +#endif + +#endif // PX_DEFORMABLE_BODY_FLAGS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableElementFilter.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableElementFilter.h new file mode 100644 index 000000000..b80fa8547 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableElementFilter.h @@ -0,0 +1,169 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_ELEMENT_FILTER_H +#define PX_DEFORMABLE_ELEMENT_FILTER_H + +#include "common/PxCoreUtilityTypes.h" +#include "common/PxBase.h" + +/** \addtogroup physics +@{ +*/ + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Element filter data for a pair of actors where one of the actors must be a deformable. + +An element filter defines mesh element wise collision filtering between two deformable actors, or one deformable actor and +a rigid actor. + +The element types used for collision filtering are implicitely given by the deformable actor type: + + PxDeformableSurface: PxTriangleMesh triangle indices. + PxDeformableVolume: PxTetrahedronMesh tetrahedron indices (collision mesh) + +If the actor is rigid, then filtering always relates to the actor as a whole. + +In order to effectively specify which elements shouldn't collide against which other elements, the following representation is used. +A pair of element groups specifies that none of the elements in the first group collides against any elements of the second group. One group relates +to one actor, and the other group relates to the other actor. The whole collision filter consists of a set of element group pairs. + +In the following we use "A" to denote one of the two actors, so either actor with index 0 or index 1 in the actor array, and "B" for the other actor. + +The element groups are specified for each actor separately: +The groups for actor A are specified by groupElemCounts[A] and groupElemIndices[A] + +The size of groupElemCounts[A] and groupElemCounts[B] specifies the number of group pairs. They need to have the same number of entries (there is an exception, see further below). +Each entry in the groupElemCounts[A] specifies the size of each group of elements in the mesh of actor A. + +The entries in groupElemIndices[A] represent all elements referenced by the groupElemCounts[A], in the order of the groups specified in groupElemCounts[A]. + +Below are some examples to clarify the concept. + +Example 1: Two groups for each actor. +groupElemCounts[0] = [2, 1], groupElemIndices[0] = [3, 4, 6] +groupElemCounts[1] = [2, 3], groupElemIndices[1] = [9, 7, 2, 5, 6] +For the first group, the count is 2 for both actors. So element 3 and 4 of actor[0] is filtered against element 9 and 7 of actor[1]. +For the second group, the element count is 1 for actor[0] and 3 for actor[1]. So element 6 of actor[0] is filtered against element 2, 5 and 6 of actor[1]. + +Example 2: Pairwise filtering. +groupElemCounts[0] = [1, 1], groupElemIndices[0] = [3, 4] +groupElemCounts[1] = [1, 1], groupElemIndices[1] = [9, 7] +For the first group, element 3 of actor[0] is filtered against element 9 of actor[1] +For the second group, element 4 of actor[0] is filtered against element 7 of actor[1] + +There are two special cases that are supported by the element filter. +- groupElemCounts[A] entries that are 0, indicate that elements of the corresponding group of actor B are filtered against all elements of actor A. +- empty groupElemCounts[A], indicates that all groups of actor B are filtered against all elements of actor A. This is always the case if actor A is a rigid. + +\see PxDeformableElementFilter, PxPhysics::createDeformableElementFilter() +*/ +struct PxDeformableElementFilterData +{ + PxDeformableElementFilterData() + { + for (PxU32 i = 0; i < 2; i++) + { + actor[i] = NULL; + } + } + + /** + \brief Actor 0 and Actor 1. NULL actors are not allowed. + */ + PxActor* actor[2]; + + /** + \brief Element counts for all filter groups, per actor. + */ + PxTypedBoundedData groupElementCounts[2]; + + /** + \brief Element indices for all filter groups, per actor. + */ + PxTypedBoundedData groupElementIndices[2]; +}; + +/** +\brief PxDeformableElementFilter class representing an element level collision filter for deformable actors. + +Element filters define how parts of deformable actors are excluded from collisions. +They are usually added to avoid conflicting attachment and contact constraints. + +\see PxDeformableElementFilterData, PxPhysics::createDeformableElementFilter() +*/ +class PxDeformableElementFilter : public PxBase +{ +public: + /** + \brief Gets the actors for this element filter. + + \param[out] actor0 The first actor. + \param[out] actor1 The second actor. + */ + virtual void getActors(PxActor*& actor0, PxActor*& actor1) const = 0; + + /** + \brief Returns string name of PxDeformableElementFilter, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxDeformableElementFilter"; } + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + virtual ~PxDeformableElementFilter() {} + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxDeformableElementFilter(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxDeformableElementFilter(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxDeformableElementFilter", PxBase); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** @} */ +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableMaterial.h new file mode 100644 index 000000000..d1b476a89 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableMaterial.h @@ -0,0 +1,133 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_MATERIAL_H +#define PX_DEFORMABLE_MATERIAL_H + +#include "PxPhysXConfig.h" +#include "PxBaseMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxScene; + +/** +\brief Material class to represent a set of deformable material properties. + +\see PxPhysics.createDeformableVolumeMaterial +*/ +class PxDeformableMaterial : public PxBaseMaterial +{ +public: + + /** + \brief Sets young's modulus which defines the body's stiffness + + Default: 1.e6 + \param[in] young Young's modulus. Range: [0, PX_MAX_F32) + \see getYoungsModulus() + */ + virtual void setYoungsModulus(PxReal young) = 0; + + /** + \brief Retrieves the young's modulus value. + + \return The young's modulus value. + + \see setYoungsModulus() + */ + virtual PxReal getYoungsModulus() const = 0; + + /** + \brief Sets the Poisson's ratio which defines the body's volume preservation. + + Default: 0.45 + \param[in] poisson Poisson's ratio. Range: [0, 0.5] + + \see getPoissons() + */ + virtual void setPoissons(PxReal poisson) = 0; + + /** + \brief Retrieves the Poisson's ratio. + \return The Poisson's ratio. + + \see setPoissons() + */ + virtual PxReal getPoissons() const = 0; + + /** + \brief Sets the dynamic friction value which defines the strength of resistance when two objects slide relative to each other while in contact. + + Default: 0.0 + \param[in] dynamicFriction The dynamic friction value. Range: [0, PX_MAX_F32) + + \see getDynamicFriction() + */ + virtual void setDynamicFriction(PxReal dynamicFriction) = 0; + + /** + \brief Retrieves the dynamic friction value + \return The dynamic friction value + + \see setDynamicFriction() + */ + virtual PxReal getDynamicFriction() const = 0; + + /** + \brief Sets material damping + + \param[in] elasticityDamping Material damping. + + \see getDamping() + */ + virtual void setElasticityDamping(PxReal elasticityDamping) = 0; + + /** + \brief Retrieves the material damping. + \return damping. + + \see setDamping() + */ + virtual PxReal getElasticityDamping() const = 0; + +protected: + PX_INLINE PxDeformableMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {} + PX_INLINE PxDeformableMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {} + virtual ~PxDeformableMaterial() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxDeformableMaterial", PxBaseMaterial); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_MATERIAL_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSkinning.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSkinning.h new file mode 100644 index 000000000..61c3cc7e3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSkinning.h @@ -0,0 +1,224 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef PX_DEFORMABLE_SKINNING_H +#define PX_DEFORMABLE_SKINNING_H + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxVec2.h" +#include "foundation/PxVec3.h" +#include "foundation/PxFlags.h" +#include "PxNodeIndex.h" +#include "cudamanager/PxCudaContextManager.h" +#include "common/PxCoreUtilityTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Structure for triangle mesh skinning embedding information. + */ + PX_ALIGN_PREFIX(16) + struct PxTriangleMeshEmbeddingInfo + { + /** + \brief UV coordinates for skinning. + */ + PxVec2 uv; + + /** + \brief Offset along the interpolated normal. + */ + PxReal offsetAlongInterpolatedNormal; + + /** + \brief ID of the guide triangle. + */ + PxU32 guideTriangleId; + + /** + \brief Constructor for PxTriangleMeshEmbeddingInfo. + \param uv_ UV coordinates. + \param offsetAlongInterpolatedNormal_ Offset along the interpolated normal. + \param guideTriangleId_ ID of the guide triangle. + */ + PxTriangleMeshEmbeddingInfo( + const PxVec2& uv_, + PxReal offsetAlongInterpolatedNormal_, PxU32 guideTriangleId_) : + uv(uv_), offsetAlongInterpolatedNormal(offsetAlongInterpolatedNormal_), guideTriangleId(guideTriangleId_) + {} + } PX_ALIGN_SUFFIX(16); + + /** + \brief Structure for tetrahedron mesh skinning embedding information. + */ + PX_ALIGN_PREFIX(16) + struct PxTetrahedronMeshEmbeddingInfo + { + /** + \brief UVW coordinates for skinning. + */ + PxVec3 uvw; + + /** + \brief ID of the guide tetrahedron. + */ + PxU32 guideTetrahedronId; + + /** + \brief Constructor for PxTetrahedronMeshEmbeddingInfo. + \param uvw_ UVW coordinates. + \param guideTetrahedronId_ ID of the guide tetrahedron. + */ + PxTetrahedronMeshEmbeddingInfo(const PxVec3& uvw_, PxU32 guideTetrahedronId_) : + uvw(uvw_), guideTetrahedronId(guideTetrahedronId_) + {} + } PX_ALIGN_SUFFIX(16); + +#if PX_SUPPORT_GPU_PHYSX + /** + \brief Structure for GPU data related to tetmesh skinning. + */ + struct PxTetmeshSkinningGpuData + { + /** + \brief Pointer to guide vertices data on the GPU. + */ + PxTypedBoundedData guideVerticesD; + + /** + \brief Pointer to guide tetrahedra data on the GPU. + */ + PxU32* guideTetrahedraD; + + /** + \brief Pointer to skinning information per vertex on the GPU. + */ + PxTetrahedronMeshEmbeddingInfo* skinningInfoPerVertexD; + + /** + \brief Pointer to embedded vertices data on the GPU. + */ + PxTypedBoundedData skinnedVerticesD; + }; + + /** + \brief Structure for GPU data related to trimesh skinning. + */ + struct PxTrimeshSkinningGpuData + { + /** + \brief Pointer to guide vertices data on the GPU. + */ + PxTypedBoundedData guideVerticesD; + + /** + \brief Pointer to guide normals data on the GPU. + */ + PxTypedBoundedData guideNormalsD; + + /** + \brief Pointer to guide triangles data on the GPU. + */ + PxU32* guideTrianglesD; + + /** + \brief Pointer to skinning information per vertex on the GPU. + */ + PxTriangleMeshEmbeddingInfo* skinningInfoPerVertexD; + + /** + \brief Pointer to skinned vertices data on the GPU. + */ + PxTypedBoundedData skinnedVerticesD; + + /** + \brief Half of the deformable surface thickness. + */ + PxReal halfSurfaceThickness; + + /** + \brief Number of guide triangles. + */ + PxU32 nbGuideTriangles; + }; + + /** + \brief Abstract base class for deformable skinning operations. + */ + class PxDeformableSkinning + { + public: + /** + \brief Computes normal vectors for cloth skinning data. + \param skinningDataArrayD Array of cloth skinning data structures. + \param arrayLength The number of elements in the skinning data array. + \param stream CUDA stream to be used for computation. + \param nbGpuThreads Number of GPU threads to use per cloth (default is 8192). + */ + virtual void computeNormalVectors( + PxTrimeshSkinningGpuData* skinningDataArrayD, PxU32 arrayLength, + CUstream stream, PxU32 nbGpuThreads = 8192) = 0; + + /** + \brief Evaluates interpolated deformable surface vertices. + \param skinningDataArrayD Array of deformable surface skinning data structures. + \param arrayLength The number of elements in the skinning data array. + \param stream CUDA stream to be used for computation. + \param nbGpuThreads Number of GPU threads to use per deformable surface (default is 8192). + */ + virtual void evaluateVerticesEmbeddedIntoSurface( + PxTrimeshSkinningGpuData* skinningDataArrayD, PxU32 arrayLength, + CUstream stream, PxU32 nbGpuThreads = 8192) = 0; + + /** + \brief Evaluates interpolated deformable volume vertices. + \param skinningDataArrayD Array of deformable volume skinning data structures. + \param arrayLength Length of the skinning data array. + \param stream CUDA stream to be used for computation. + \param nbGpuThreads Number of GPU threads to use per deformable volume (default is 8192). + */ + virtual void evaluateVerticesEmbeddedIntoVolume( + PxTetmeshSkinningGpuData* skinningDataArrayD, PxU32 arrayLength, + CUstream stream, PxU32 nbGpuThreads = 8192) = 0; + + /** + \brief Virtual destructor for PxDeformableSkinning. + */ + virtual ~PxDeformableSkinning() { } + }; +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurface.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurface.h new file mode 100644 index 000000000..860be00bf --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurface.h @@ -0,0 +1,287 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef PX_PHYSICS_DEFORMABLE_SURFACE_H +#define PX_PHYSICS_DEFORMABLE_SURFACE_H + +#include "PxDeformableBody.h" +#include "PxDeformableSurfaceFlag.h" +#include "foundation/PxArray.h" +#include "PxConeLimitedConstraint.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + + +class PxCudaContextManager; + +/** +\brief The maximum number of triangles supported in a surface deformable mesh + +The current limit is 1'048'575. +*/ +#define PX_MAX_NB_DEFORMABLE_SURFACE_TRI 0x000fffff + +/** +\brief The maximum number of vertices supported in a surface deformable mesh + +The current limit is 1'048'575. +*/ +#define PX_MAX_NB_DEFORMABLE_SURFACE_VTX 0x000fffff + +/** +\brief The maximum number of deformable surfaces supported in a scene + +The current limit is 4095. +*/ +#define PX_MAX_NB_DEFORMABLE_SURFACE 0xfff + +/** +\brief Represents a deformable surface + +The deformable surface feature is exclusively supported on GPU. The full GPU pipeline needs to +be enabled in order to make use of deformable bodies, see #PxSceneFlag::eENABLE_GPU_DYNAMICS, +#PxBroadPhaseType::eGPU. +*/ +class PxDeformableSurface : public PxDeformableBody +{ +public: + + /** + \brief Raises or clears a particular deformable surface flag. + + See the list of flags #PxDeformableSurfaceFlag + + Default: No flags are set + + \param[in] flag The PxDeformableSurfaceFlag to raise(set) or clear. See #PxDeformableSurfaceFlag. + \param[in] val The new boolean value for the flag. + */ + virtual void setDeformableSurfaceFlag(PxDeformableSurfaceFlag::Enum flag, bool val) = 0; + + /** + \brief Sets deformable surface flags. + + See the list of flags #PxDeformableSurfaceFlag + + Default: No flags are set + + \param[in] flags The PxDeformableSurfaceFlags to set. + */ + virtual void setDeformableSurfaceFlags(PxDeformableSurfaceFlags flags) = 0; + + /** + \brief Reads the deformable surface flags. + + See the list of flags #PxDeformableSurfaceFlag + + \return The values of the deformable surface flags. + + \see setDeformableSurfaceFlag() + */ + virtual PxDeformableSurfaceFlags getDeformableSurfaceFlags() const = 0; + + /** + \brief Sets the number of collision pair updates per timestep. + + Collision pair is updated at least once per timestep and increasing the frequency provides better collision pairs. + Default: 1 + + \param[in] frequency It sets the number of collision pair updates per timestep. + + \see getNbCollisionPairUpdatesPerTimestep() + */ + virtual void setNbCollisionPairUpdatesPerTimestep(const PxU32 frequency) = 0; + + /** + \brief Retrieves number of collision pair updates per timestep. + + \return The number of collision pair updates per timestep. + \see setNbCollisionPairUpdatesPerTimestep() + */ + virtual PxU32 getNbCollisionPairUpdatesPerTimestep() const = 0; + + /** + \brief Sets the number of collision substeps in each sub-timestep. + + Collision constraints can be applied multiple times in each sub-timestep + Default: 1 + + \param[in] frequency It sets the number of collision substeps in each sub-timestep. + + \see getNbCollisionSubsteps() + */ + virtual void setNbCollisionSubsteps(const PxU32 frequency) = 0; + + /** + \brief Retrieves the number of collision substeps in each sub-timestep. + + \return The number of collision substeps in each sub-timestep. + + \see setNbCollisionSubsteps() + */ + virtual PxU32 getNbCollisionSubsteps() const = 0; + + /** + \brief Gets a pointer to a device buffer containing positions and inverse masses of the + surface deformable. + + This function returns a pointer to device memory for the positions and inverse masses of + the surface deformable. The device memory buffer is used to both initialize/update the vertices of the surface deformable and + read the simulation results. + + \note It is mandatory to call PxDeformableSurface::markDirty() with PxDeformableSurfaceDataFlag::ePOSITION_INVMASS when + updating data in this buffer. + + The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. + The first 3 floats specify the positions and the last float specifies the inverse mass of the vertex. + The size of the buffer is the number of vertices of the surface deformable mesh * sizeof(PxVec4). + \see PxTriangleMesh::getNbVertices(). + + The device memory pointed to by this pointer is allocated when a shape is attached to the + deformable surface. Calling PxDeformableSurface::detachShape() will deallocate the memory. + + It is not allowed to write to this buffer from the start of the PxScene::simulate() call + until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks + have finished, reading the data during a completion task is explicitly allowed. The + simulation will read and write directly from/into this buffer. + + It is the users' responsibility to initialize this buffer with the initial positions of + the vertices of the surface deformable mesh. + + \return PxVec4* A pointer to a device buffer containing positions and inverse masses of + the surface deformable mesh. + */ + virtual PxVec4* getPositionInvMassBufferD() = 0; + + /** + \brief Gets a pointer to a device buffer containing velocities of the deformable surface. + + This function returns a pointer to device memory for the velocities of the deformable surface. This buffer + is used to both initialize/update the vertices of the surface deformable and read the simulation results. + + \note It is mandatory to call PxDeformableSurface::markDirty() with PxDeformableSurfaceDataFlag::eVELOCITY when + updating data in this buffer. + + + The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. The + first 3 floats specify the velocity of the vertex. The final float is unused. The size of + the buffer is the number of vertices of the surface deformable mesh * sizeof(PxVec4). + \see PxTriangleMesh::getNbVertices(). + + The device memory pointed to by this pointer is allocated when a shape is attached to the + deformable surface. Calling PxDeformableSurface::detachShape() will deallocate the memory. + + It is not allowed to write to this buffer from the start of the PxScene::simulate() call + until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks + have finished, reading the data during a completion task is explicitly allowed. The + simulation will read and write directly from/into this buffer. + + It is the users' responsibility to initialize this buffer with the initial velocities of + the vertices of the surface deformable mesh. + + \return PxVec4* A pointer to a device buffer containing the velocities of the surface deformable mesh. + */ + virtual PxVec4* getVelocityBufferD() = 0; + + /** + \brief Gets a pointer to a device buffer containing the rest positions of the deformable surface. + + This function returns a pointer to device memory for the rest positions of the deformable surface. + This buffer is used to initialize/update the rest positions of the vertices of the deformable surface. + + \note It is mandatory to call PxDeformableSurface::markDirty() with PxDeformableSurfaceDataFlag::eREST_POSITION when + updating data in this buffer. + + The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. + The first 3 specify the rest position. The last float is unused. The size of the buffer + is the number of vertices of the surface deformable mesh * sizeof(PxVec4). \see PxTriangleMesh::getNbVertices(). + + The device memory pointed to by this pointer is allocated when a shape is attached to the + deformable surface. Calling PxDeformableSurface::detachShape() will deallocate the memory. + + It is not allowed to write to this buffer from the start of the PxScene::simulate() call + until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks + have finished, reading the data during a completion task is explicitly allowed. The + simulation will read directly from this buffer. + + It is the users' responsibility to initialize this buffer with the initial rest positions of + the vertices of the surface deformable mesh. + + \return PxVec4* A pointer to a device buffer containing the rest positions of the surface deformable mesh. + */ + virtual PxVec4* getRestPositionBufferD() = 0; + + /** + \brief Marks per-vertex simulation state and configuration buffers dirty to signal to the simulation + that changes have been made. + + Calling this function is required to notify the simulation of changes made in the positionInvMass, + velocity and rest position buffers. + + This function can be called multiple times, and dirty flags are accumulated internally until + PxScene::simulate() is called. + + \see getPositionInvMassBufferD, getVelocityBufferD, getRestPositionBufferD + + \param flags The buffers that have been updated. + */ + virtual void markDirty(PxDeformableSurfaceDataFlags flags) = 0; + + /** + \brief Gets the concrete type name. + \return The name of the concrete type. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxDeformableSurface"; } + +protected: + PX_INLINE PxDeformableSurface(PxType concreteType, PxBaseFlags baseFlags) : PxDeformableBody(concreteType, baseFlags) {} + PX_INLINE PxDeformableSurface(PxBaseFlags baseFlags) : PxDeformableBody(baseFlags) {} + virtual ~PxDeformableSurface() {} + virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxDeformableSurface", PxDeformableBody); } +}; + +#if PX_VC +#pragma warning(pop) +#endif + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_PHYSICS_DEFORMABLE_SURFACE_H + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurfaceFlag.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurfaceFlag.h new file mode 100644 index 000000000..166f2d56d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurfaceFlag.h @@ -0,0 +1,73 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSICS_DEFORMABLE_SURFACE_FLAGS_H +#define PX_PHYSICS_DEFORMABLE_SURFACE_FLAGS_H + +#include "foundation/PxFlags.h" +#include "foundation/PxSimpleTypes.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxDeformableSurfaceFlag +{ + enum Enum + { + eUSE_ANISOTROPIC_MODEL = 1 << 0, // 0: use isotropic model, 1: use anistropic model + eENABLE_FLATTENING = 1 << 1 // 0: query rest bending angle from rest shape, 1: use zero rest bending angle + }; +}; + +typedef PxFlags PxDeformableSurfaceFlags; + +/** +\brief Identifies input and output buffers for PxDeformableSurface. +*/ +struct PxDeformableSurfaceDataFlag +{ + enum Enum + { + eNONE = 0, + ePOSITION_INVMASS = 1 << 0, + eVELOCITY = 1 << 1, + eREST_POSITION = 1 << 2, + eALL = ePOSITION_INVMASS | eVELOCITY | eREST_POSITION + }; +}; + +typedef PxFlags PxDeformableSurfaceDataFlags; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_PHYSICS_DEFORMABLE_SURFACE_FLAGS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurfaceMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurfaceMaterial.h new file mode 100644 index 000000000..2d3488447 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableSurfaceMaterial.h @@ -0,0 +1,119 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_SURFACE_MATERIAL_H +#define PX_DEFORMABLE_SURFACE_MATERIAL_H + +#include "PxDeformableMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Material class to represent surface deformable material properties. + +\see PxPhysics.createDeformableSurfaceMaterial +*/ +class PxDeformableSurfaceMaterial : public PxDeformableMaterial +{ +public: + + /** + \brief Sets material thickness + + Default: 0.001 + \param[in] thickness Material thickness. + + \see getThickness() + */ + virtual void setThickness(PxReal thickness) = 0; + + /** + \brief Retrieves the material thickness. + + Default: 0.001 + \return thickness. + \see setThickness() + */ + virtual PxReal getThickness() const = 0; + + /** + \brief Sets material bending stiffness + + Default: 0.0 + \param[in] bendingStiffness Material bending stiffness. + \see getBendingStiffness() + */ + virtual void setBendingStiffness(PxReal bendingStiffness) = 0; + + /** + \brief Retrieves the material bending stiffness. + + \return bendingStiffness. + \see setBendingStiffness() + */ + virtual PxReal getBendingStiffness() const = 0; + + /** + \brief Sets material bending damping + + \param[in] bendingDamping Material bending damping. + + \see getBendingDamping() + */ + virtual void setBendingDamping(PxReal bendingDamping) = 0; + + /** + \brief Retrieves the material bending damping. + \return bending damping. + + \see setBendingDamping() + */ + virtual PxReal getBendingDamping() const = 0; + + + /** + \brief Gets the concrete type name. + \return The name of the concrete type. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxDeformableSurfaceMaterial"; } + +protected: + PX_INLINE PxDeformableSurfaceMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxDeformableMaterial(concreteType, baseFlags) {} + PX_INLINE PxDeformableSurfaceMaterial(PxBaseFlags baseFlags) : PxDeformableMaterial(baseFlags) {} + virtual ~PxDeformableSurfaceMaterial() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxDeformableSurfaceMaterial", PxDeformableMaterial); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_SURFACE_MATERIAL_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolume.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolume.h new file mode 100644 index 000000000..0c6d6fb8c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolume.h @@ -0,0 +1,702 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_VOLUME_H +#define PX_DEFORMABLE_VOLUME_H + +#include "PxDeformableBody.h" +#include "PxDeformableVolumeFlag.h" +#include "PxConeLimitedConstraint.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + +class PxCudaContextManager; +class PxTetrahedronMesh; +class PxDeformableVolumeAuxData; +class PxDeformableSurface; +class PxParticleBuffer; + +/** +\brief The maximum number of tetrahedrons supported in a deformable volume tetrahedron mesh + +The current limit is 1'048'575. +*/ +#define PX_MAX_NB_DEFORMABLE_VOLUME_TET 0x000fffff + +/** +\brief The maximum number of deformable volumes supported in a scene + +The current limit is 4095. +*/ +#define PX_MAX_NB_DEFORMABLE_VOLUME 0xfff + +/** +\brief Represents a deformable volume + +The deformable volume feature is exclusively supported on GPU. The full GPU pipeline needs to +be enabled in order to make use of deformable bodies, see #PxSceneFlag::eENABLE_GPU_DYNAMICS, +#PxBroadPhaseType::eGPU. +*/ +class PxDeformableVolume : public PxDeformableBody +{ +public: + + /** + \brief Raises or clears a particular deformable volume flag. + + See the list of flags #PxDeformableVolumeFlag + + Default: No flags are set + + \param[in] flag The PxDeformableVolumeFlag to raise(set) or clear. See #PxDeformableVolumeFlag. + \param[in] val The new boolean value for the flag. + */ + virtual void setDeformableVolumeFlag(PxDeformableVolumeFlag::Enum flag, bool val) = 0; + + /** + \brief Sets deformable volume flags. + + See the list of flags #PxDeformableVolumeFlag + + Default: No flags are set + + \param[in] flags The PxDeformableVolumeFlags to set. + */ + virtual void setDeformableVolumeFlags(PxDeformableVolumeFlags flags) = 0; + + /** + \brief Reads the deformable volume flags. + + See the list of flags #PxDeformableVolumeFlag + + \return The values of the deformable volume flags. + + \see setDeformableVolumeFlag() + */ + virtual PxDeformableVolumeFlags getDeformableVolumeFlags() const = 0; + + /** + \brief Sets the self collision stress tolerance. + + Stress threshold to deactivate collision contacts in case the local stress magnitude exceeds the threshold. + Default: 0.9 + + \param[in] selfCollisionStressTolerance The maximal depenetration velocity + */ + virtual void setSelfCollisionStressTolerance(const PxReal selfCollisionStressTolerance) = 0; + + /** + \brief Retrieves the self collision stress tolerance. + + \return The self collision filter distance + \see setSelfCollisionFilterDistance + */ + virtual PxReal getSelfCollisionStressTolerance() const = 0; + + /** + \brief Gets a pointer to a device buffer containing positions and inverse masses of the + collision mesh. + + This function returns a pointer to device memory for the positions and inverse masses of + the deformable volume. This buffer is used to both initialize/update the collision mesh vertices + of the deformable volume and read the simulation results. + + \note It is mandatory to call PxDeformableVolume::markDirty() with PxDeformableVolumeDataFlag::ePOSITION_INVMASS + when updating data in this buffer. + + The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. + The first 3 floats specify the vertex position and the last float contains the inverse mass of the + vertex. The size of the buffer is the number of vertices of the collision mesh * sizeof(PxVec4). + \see PxTetrahedronMesh::getNbVertices(). + + The device memory pointed to by this pointer is allocated when a shape is attached to the + deformable volume. Calling PxDeformableVolume::detachShape() will deallocate the memory. + + It is not allowed to write to this buffer from the start of the PxScene::simulate() call + until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks + have finished, reading the data during a completion task is explicitly allowed. The + simulation will read and write directly from/into this buffer. + + It is the users' responsibility to initialize this buffer with the initial positions of + the vertices of the collision mesh. See PxDeformableVolumeExt::allocateAndInitializeHostMirror(), + PxDeformableVolumeExt::copyToDevice(). + + \return PxVec4* A pointer to a device buffer containing positions and inverse masses of + the collision mesh. + */ + virtual PxVec4* getPositionInvMassBufferD() = 0; + + /** + \brief Gets a pointer to a device buffer containing rest positions of the collision mesh vertices. + + This function returns a pointer to device memory for the rest positions of the deformable volume collision + mesh. This buffer is used to initialize the rest positions of the collision mesh vertices. + + \note It is mandatory to call PxDeformableVolume::markDirty() with PxDeformableVolumeDataFlag::eREST_POSITION when + updating data in this buffer. + + The simulation expects 4 floats per vertex, aligned to a 16B boundary. The first 3 specify the + rest position. The last float is unused. The size of the buffer is the number of vertices in + the collision mesh * sizeof(PxVec4). \see PxTetrahedronMesh::getNbVertices(). + + The device memory pointed to by this pointer is allocated when a shape is attached to the deformable volume. + Calling PxDeformableVolume::detachShape() will deallocate the memory. + + It is not allowed to write data into this buffer from the start of PxScene::simulate() until + PxScene::fetchResults() returns. + + It is the users' responsibility to initialize this buffer with the initial rest positions of the + vertices of the collision mesh. See PxDeformableVolumeExt::allocateAndInitializeHostMirror(), + PxDeformableVolumeExt::copyToDevice(). + + \return PxVec4* A pointer to a device buffer containing the rest positions of the collision mesh. + */ + virtual PxVec4* getRestPositionBufferD() = 0; + + /** + \brief Gets a pointer to a device buffer containing the vertex positions of the simulation mesh. + + This function returns a pointer to device memory for the positions and inverse masses of the deformable volume + simulation mesh. This buffer is used to both initialize/update the simulation mesh vertices + of the deformable volume and read the simulation results. + + \note It is mandatory to call PxDeformableVolume::markDirty() with PxDeformableVolumeDataFlag::eSIM_POSITION_INVMASS when + updating data in this buffer. + + The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. The + first 3 floats specify the positions and the last float specifies the inverse mass of the vertex. + The size of the buffer is the number of vertices of the simulation mesh * sizeof(PxVec4). + \see PxTetrahedronMesh::getNbVertices(). + + The device memory pointed to by this pointer is allocated when a simulation mesh is attached to the + deformable volume. Calling PxDeformableVolume::detachSimulationMesh() will deallocate the memory. + + It is not allowed to write to this buffer from the start of the PxScene::simulate() call + until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks + have finished, reading the data during a completion task is explicitly allowed. The + simulation will read and write directly from/into this buffer. + + It is the users' responsibility to initialize this buffer with the initial positions of + the vertices of the simulation mesh. See PxDeformableVolumeExt::allocateAndInitializeHostMirror(), + PxDeformableVolumeExt::copyToDevice(). + + \return PxVec4* A pointer to a device buffer containing the vertex positions of the simulation mesh. + */ + virtual PxVec4* getSimPositionInvMassBufferD() = 0; + + /** + \brief Gets a pointer to a device buffer containing the vertex velocities of the simulation mesh. + + This function returns a pointer to device memory for the velocities of the deformable volume simulation mesh + vertices. This buffer is used to both initialize/update the simulation mesh vertex velocities + of the deformable volume and read the simulation results. + + \note It is mandatory to call PxDeformableVolume::markDirty() with PxDeformableVolumeDataFlag::eSIM_VELOCITY when + updating data in this buffer. + + The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. The + first 3 specify the velocities for each vertex. The final float is unused. The size of the + buffer is the number of vertices of the simulation mesh * sizeof(PxVec4). + \see PxTetrahedronMesh::getNbVertices(). + + The device memory pointed to by this pointer is allocated when a simulation mesh is attached to the + deformable volume. Calling PxDeformableVolume::detachSimulationMesh() will deallocate the memory. + + It is not allowed to write to this buffer from the start of the PxScene::simulate() call + until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks + have finished, reading the data during a completion task is explicitly allowed. The + simulation will read and write directly from/into this buffer. + + It is the users' responsibility to initialize this buffer with the initial velocities of + the vertices of the simulation mesh. See PxDeformableVolumeExt::allocateAndInitializeHostMirror(), + PxDeformableVolumeExt::copyToDevice(). + + \return PxVec4* A pointer to a device buffer containing the vertex velocities of the simulation mesh. + */ + virtual PxVec4* getSimVelocityBufferD() = 0; + + /** + \brief Marks per-vertex simulation state and configuration buffers dirty to signal to the simulation + that changes have been made. + + Calling this function is mandatory to notify the simulation of changes made in the positionInvMass, + simPositionInvMass, simVelocity and rest position buffers. + + This function can be called multiple times, and dirty flags are accumulated internally until + PxScene::simulate() is called. + + \see getPositionInvMassBufferD, getSimVelocityBufferD, getRestPositionBufferD, getSimPositionInvMassBufferD + + \param flags The buffers that have been updated. + */ + virtual void markDirty(PxDeformableVolumeDataFlags flags) = 0; + + /** + \brief Sets the device buffer containing the kinematic targets for this deformable volume. + + This function sets the kinematic targets for a deformable volume to a user-provided device buffer. This buffer is + read by the simulation to obtain the target position for each vertex of the simulation mesh. + + The simulation expects 4 consecutive float for each vertex, aligned to a 16B boundary. The first 3 + floats specify the target positions. The last float determines (together with the flag argument) + if the target is active or not. + For a deformable volume with the flag PxDeformableBodyFlag::eKINEMATIC raised, all target positions are considered + valid. In case a deformable volume has the PxDeformableVolumeFlag::ePARTIALLY_KINEMATIC raised, only target + positions whose corresponding last float has been set to 0.f are considered valid target positions. + \see PxConfigureDeformableVolumeKinematicTarget + Setting the kinematic targets has no effect if neither PxDeformableBodyFlag::eKINEMATIC nor + PxDeformableVolumeFlag::ePARTIALLY_KINEMATIC is set. + + The size of the buffer is the number of vertices of the simulation mesh * sizeof(PxVec4). + \see PxTetrahedronMesh::getNbVertices(). + + It is the users responsibility to manage the memory pointed to by the input to this function, + as well as guaranteeing the integrity of the input data. In particular, this means that it is + not allowed to write this data from from the start of PxScene::simulate() until PxScene::fetchResults() + returns. The memory is not allowed to be deallocated until PxScene::fetchResults() returns. + + Calling this function with a null pointer for the positions will clear the input and resume normal + simulation. PxDeformableBodyFlag::eKINEMATIC or PxDeformableVolumeFlag::ePARTIALLY_KINEMATIC are ignored + if no targets are set. + + This call is persistent across calls to PxScene::simulate(). Once this function is called, the + simulation will look up the target positions from the same buffer for every call to PxScene::simulate(). + The user is allowed to update the target positions without calling this function again, provided that + the synchronization requirements are adhered to (no changes between start of PxScene::simulate() until + PxScene::fetchResults() returns). + + \param positions A pointer to a device buffer containing the kinematic targets for this deformable volume. + */ + virtual void setKinematicTargetBufferD(const PxVec4* positions) = 0; + + /** + \brief Deprecated: Sets the device buffer containing the kinematic targets for this deformable volume. + + This function sets the kinematic targets for a deformable volume to a user-provided device buffer. This buffer is + read by the simulation to obtain the target position for each vertex of the simulation mesh. + + The simulation expects 4 consecutive float for each vertex, aligned to a 16B boundary. The first 3 + floats specify the target positions. The last float determines (together with the flag argument) + if the target is active or not. + For a deformable volume with the flag PxDeformableVolumeFlag::eKINEMATIC raised, all target positions are considered + valid. In case a deformable volume has the PxDeformableVolumeFlag::ePARTIALLY_KINEMATIC raised, only target + positions whose corresponding last float has been set to 0.f are considered valid target positions. + \see PxConfigureDeformableVolumeKinematicTarget + + The size of the buffer is the number of vertices of the simulation mesh * sizeof(PxVec4). + \see PxTetrahedronMesh::getNbVertices(). + + It is the users responsibility to manage the memory pointed to by the input to this function, + as well as guaranteeing the integrity of the input data. In particular, this means that it is + not allowed to write this data from from the start of PxScene::simulate() until PxScene::fetchResults() + returns. The memory is not allowed to be deallocated until PxScene::fetchResults() returns. + + Calling this function with a null pointer for the positions will clear the input and resume normal + simulation. This will also clear both the PxDeformableVolumeFlag::eKINEMATIC and PxDeformableVolumeFlag::ePARTIALLY_KINEMATIC + flags of the deformable volume. + + This call is persistent across calls to PxScene::simulate(). Once this function is called, the + simulation will look up the target positions from the same buffer for every call to PxScene::simulate(). + The user is allowed to update the target positions without calling this function again, provided that + the synchronization requirements are adhered to (no changes between start of PxScene::simulate() until + PxScene::fetchResults() returns). + + \param positions A pointer to a device buffer containing the kinematic targets for this deformable volume. + \param flags Flags specifying the type of kinematic deformable volume: this function ignores all flags except PxDeformableVolumeFlag::eKINEMATIC and PxDeformableVolumeFlag::ePARTIALLY_KINEMATIC. + */ + PX_DEPRECATED virtual void setKinematicTargetBufferD(const PxVec4* positions, PxDeformableVolumeFlags flags) = 0; + + /** + \brief Attaches a simulation mesh + + Attaches the simulation mesh (geometry) and a state containing inverse mass, rest pose + etc. required to compute the deformation. + + \param[in] simulationMesh The tetrahedral mesh used to compute the deformable's deformation + \param[in] deformableVolumeAuxData A state that contain a mapping from simulation to collision mesh, volume information etc. + + \return Returns true if the operation was successful + \see detachSimulationMesh, PxDeformableBody.attachShape + */ + virtual bool attachSimulationMesh(PxTetrahedronMesh& simulationMesh, PxDeformableVolumeAuxData& deformableVolumeAuxData) = 0; + + /** + \brief Detaches the simulation mesh + + Detaches the simulation mesh and simulation state used to compute the deformation. + + \see attachSimulationMesh, PxDeformableBody.detachShape + */ + virtual void detachSimulationMesh() = 0; + + /** + \brief Retrieves the simulation mesh pointer. + + Allows to access the geometry of the tetrahedral mesh used to compute the object's deformation + + \return Pointer to the simulation mesh + */ + virtual PxTetrahedronMesh* getSimulationMesh() = 0; + + //! \brief Const version of getSimulationMesh() + virtual const PxTetrahedronMesh* getSimulationMesh() const = 0; + + /** + \brief Retrieve the collision mesh pointer. + + Allows to access the geometry of the tetrahedral mesh used to perform collision detection + + \return Pointer to the collision mesh + */ + virtual PxTetrahedronMesh* getCollisionMesh() = 0; + + //! \brief Const version of getCollisionMesh() + virtual const PxTetrahedronMesh* getCollisionMesh() const = 0; + + /** + \brief Retrieves the simulation state pointer. + + Allows to access the additional data of the simulation mesh (inverse mass, rest state etc.). + The geometry part of the data is stored in the simulation mesh. + + \return Pointer to the simulation state + */ + virtual PxDeformableVolumeAuxData* getDeformableVolumeAuxData() = 0; + + //! \brief const version of getDeformableVolumeAuxData() + virtual const PxDeformableVolumeAuxData* + getDeformableVolumeAuxData() const = 0; + + /** + \brief Returns the GPU deformable volume index. + + \return The GPU index, or 0xFFFFFFFF if the deformable volume is not in a scene. + */ + virtual PxU32 getGpuDeformableVolumeIndex() = 0; + + /** + \brief Gets the concrete type name. + \return The name of the concrete type. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxDeformableVolume"; } + + /** + \brief Deprecated + \see setDeformableVolumeFlag + */ + PX_DEPRECATED PX_FORCE_INLINE void setSoftBodyFlag(PxDeformableVolumeFlag::Enum flag, bool val) { return setDeformableVolumeFlag(flag, val); } + + /** + \brief Deprecated + \see setDeformableVolumeFlags + */ + PX_DEPRECATED PX_FORCE_INLINE void setSoftBodyFlags(PxDeformableVolumeFlags flags) { return setDeformableVolumeFlags(flags); } + + /** + \brief Deprecated + \see getDeformableVolumeFlags + */ + PX_DEPRECATED PX_FORCE_INLINE PxDeformableVolumeFlags getSoftBodyFlag() const { return getDeformableVolumeFlags(); } + + /** + \brief Deprecated + \see getDeformableVolumeAuxData + */ + PX_DEPRECATED PX_FORCE_INLINE PxDeformableVolumeAuxData* getSoftBodyAuxData() { return getDeformableVolumeAuxData(); } + + /** + \brief Deprecated + \see getDeformableVolumeAuxData + */ + PX_DEPRECATED PX_FORCE_INLINE const PxDeformableVolumeAuxData* getSoftBodyAuxData() const { return getDeformableVolumeAuxData(); } + + /** + \brief Deprecated + Default: 4 position iterations, 1 velocity iteration + \param[in] minPositionIters Minimal number of position iterations the solver should perform for this body. Range: [1,255] + \param[in] minVelocityIters Minimal number of velocity iterations the solver should perform for this body. Range: [1,255] + \see PxDeformableBody.setSolverIterationCounts() + */ + PX_DEPRECATED virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0; + + /** + \brief Deprecated + \see PxDeformableBody.setSolverIterationCount() + */ + PX_DEPRECATED virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0; + + /** + \brief Creates a collision filter between a particle and a tetrahedron in the deformable volume's collision mesh. + + \param[in] particlesystem The particle system used for the collision filter + \param[in] buffer The PxParticleBuffer to which the particle belongs to. + \param[in] particleId The particle whose collisions with the tetrahedron in the deformable volume are filtered. + \param[in] tetId The tetradedron in the deformable volume that is filtered. If tetId is PX_MAX_NB_DEFORMABLE_VOLUME_TET, this particle will filter against all tetrahedra in this deformable volume. + */ + PX_DEPRECATED virtual void addParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) = 0; + + /** + \brief Removes a collision filter between a particle and a tetrahedron in the deformable volume's collision mesh. + + \param[in] particlesystem The particle system used for the collision filter + \param[in] buffer The PxParticleBuffer to which the particle belongs to. + \param[in] particleId The particle whose collisions with the tetrahedron in the deformable volume are filtered. + \param[in] tetId The tetrahedron in the deformable volume is filtered. + */ + PX_DEPRECATED virtual void removeParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) = 0; + + /** + \brief Creates an attachment between a particle and a deformable volume. + Be aware that destroying the particle system before destroying the attachment is illegal and may cause a crash. + The deformable volume keeps track of these attachments but the particle system does not. + + \param[in] particlesystem The particle system used for the attachment + \param[in] buffer The PxParticleBuffer to which the particle belongs to. + \param[in] particleId The particle that is attached to a tetrahedron in the deformable volume's collision mesh. + \param[in] tetId The tetrahedron in the deformable volume's collision mesh to attach the particle to. + \param[in] barycentric The barycentric coordinates of the particle attachment position with respect to the tetrahedron specified with tetId. + \return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later + */ + PX_DEPRECATED virtual PxU32 addParticleAttachment(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId, const PxVec4& barycentric) = 0; + + + /** + \brief Removes an attachment between a particle and a deformable volume. + Be aware that destroying the particle system before destroying the attachment is illegal and may cause a crash. + The deformable volume keeps track of these attachments but the particle system does not. + + \param[in] particlesystem The particle system used for the attachment + \param[in] handle Index that identifies the attachment. This handle gets returned by the addParticleAttachment when the attachment is created + */ + PX_DEPRECATED virtual void removeParticleAttachment(PxPBDParticleSystem* particlesystem, PxU32 handle) = 0; + + /** + \brief Creates a collision filter between a vertex in a deformable volume and a rigid body. + + \param[in] actor The rigid body actor used for the collision filter + \param[in] vertId The index of a vertex in the deformable volume's collision mesh whose collisions with the rigid body are filtered. + */ + PX_DEPRECATED virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId) = 0; + + /** + \brief Removes a collision filter between a vertex in a deformable volume and a rigid body. + + \param[in] actor The rigid body actor used for the collision filter + \param[in] vertId The index of a vertex in the deformable volume's collision mesh whose collisions with the rigid body are filtered. + */ + PX_DEPRECATED virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId) = 0; + + /** + \brief Creates a rigid attachment between a deformable volume and a rigid body. + Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash. + The deformable volume keeps track of these attachments but the rigid body does not. + + This method attaches a vertex on the deformable volume collision mesh to the rigid body. + + \param[in] actor The rigid body actor used for the attachment + \param[in] vertId The index of a vertex in the deformable volume's collision mesh that gets attached to the rigid body. + \param[in] actorSpacePose The location of the attachment point expressed in the rigid body's coordinate system. + \param[in] constraint The user defined cone distance limit constraint to limit the movement between a vertex in the deformable volume and rigid body. + \return Returns a handle that identifies the attachment created. This handle can be used to relese the attachment later + */ + PX_DEPRECATED virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint = NULL) = 0; + + /** + \brief Releases a rigid attachment between a deformable volume and a rigid body. + Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash. + The deformable volume keeps track of these attachments but the rigid body does not. + + This method removes a previously-created attachment between a vertex of the deformable volume collision mesh and the rigid body. + + \param[in] actor The rigid body actor used for the attachment + \param[in] handle Index that identifies the attachment. This handle gets returned by the addRigidAttachment when the attachment is created + */ + PX_DEPRECATED virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle) = 0; + + /** + \brief Creates collision filter between a tetrahedron in a deformable volume and a rigid body. + + \param[in] actor The rigid body actor used for collision filter + \param[in] tetIdx The index of a tetrahedron in the deformable volume's collision mesh whose collisions with the rigid body is filtered. + */ + PX_DEPRECATED virtual void addTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) = 0; + + /** + \brief Removes collision filter between a tetrahedron in a deformable volume and a rigid body. + + \param[in] actor The rigid body actor used for collision filter + \param[in] tetIdx The index of a tetrahedron in the deformable volume's collision mesh whose collisions with the rigid body is filtered. + */ + PX_DEPRECATED virtual void removeTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) = 0; + + /** + \brief Creates a rigid attachment between a deformable volume and a rigid body. + Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash. + The deformable volume keeps track of these attachments but the rigid body does not. + + This method attaches a point inside a tetrahedron of the collision to the rigid body. + + \param[in] actor The rigid body actor used for the attachment + \param[in] tetIdx The index of a tetrahedron in the deformable volume's collision mesh that contains the point to be attached to the rigid body + \param[in] barycentric The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx + \param[in] actorSpacePose The location of the attachment point expressed in the rigid body's coordinate system. + \param[in] constraint The user defined cone distance limit constraint to limit the movement between a tet and rigid body. + \return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later + */ + PX_DEPRECATED virtual PxU32 addTetRigidAttachment(PxRigidActor* actor, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint = NULL) = 0; + + /** + \brief Creates collision filter between a tetrahedron in a deformable volume and a tetrahedron in another deformable volume. + + \param[in] otherDeformableVolume The other deformable volume actor used for collision filter + \param[in] otherTetIdx The index of the tetrahedron in the other deformable volume's collision mesh to be filtered. + \param[in] tetIdx1 The index of the tetrahedron in the deformable volume's collision mesh to be filtered. If tetId1 is PX_MAX_NB_DEFORMABLE_VOLUME_TET, the tetrahedron with index `otherTetIdx' in the other deformable volume will filter against all tetrahedra in this deformable volume. + */ + PX_DEPRECATED virtual void addSoftBodyFilter(PxDeformableVolume* otherDeformableVolume, PxU32 otherTetIdx, PxU32 tetIdx1) = 0; + + /** + \brief Removes collision filter between a tetrahedron in a deformable volume and a tetrahedron in other deformable volume. + + \param[in] otherDeformableVolume The other deformable volume actor used for collision filter + \param[in] otherTetIdx The index of the other tetrahedron in the other deformable volume's collision mesh whose collision with the tetrahedron with the deformable volume is filtered. + \param[in] tetIdx1 The index of the tetrahedron in the deformable volume's collision mesh whose collision with the other tetrahedron with the other deformable volume is filtered. + */ + PX_DEPRECATED virtual void removeSoftBodyFilter(PxDeformableVolume* otherDeformableVolume, PxU32 otherTetIdx, PxU32 tetIdx1) = 0; + + /** + \brief Creates collision filters between a tetrahedron in a deformable volume with another deformable volume. + + \param[in] otherDeformableVolume The other deformable volume actor used for collision filter + \param[in] otherTetIndices The indices of the tetrahedron in the other deformable volume's collision mesh to be filtered. + \param[in] tetIndices The indices of the tetrahedron of the deformable volume's collision mesh to be filtered. + \param[in] tetIndicesSize The size of tetIndices. + */ + PX_DEPRECATED virtual void addSoftBodyFilters(PxDeformableVolume* otherDeformableVolume, PxU32* otherTetIndices, PxU32* tetIndices, PxU32 tetIndicesSize) = 0; + + /** + \brief Removes collision filters between a tetrahedron in a deformable volume with another deformable volume. + + \param[in] otherDeformableVolume The other deformable volume actor used for collision filter + \param[in] otherTetIndices The indices of the tetrahedron in the other deformable volume's collision mesh to be filtered. + \param[in] tetIndices The indices of the tetrahedron of the deformable volume's collision mesh to be filtered. + \param[in] tetIndicesSize The size of tetIndices. + */ + PX_DEPRECATED virtual void removeSoftBodyFilters(PxDeformableVolume* otherDeformableVolume, PxU32* otherTetIndices, PxU32* tetIndices, PxU32 tetIndicesSize) = 0; + + /** + \brief Creates an attachment between two deformable volumes. + + This method attaches a point inside a tetrahedron of the collision mesh to a point in another deformable volume's tetrahedron collision mesh. + + \param[in] deformableVolume0 The deformable volume actor used for the attachment + \param[in] tetIdx0 The index of a tetrahedron in the other deformable volume that contains the point to be attached to the deformable volume + \param[in] tetBarycentric0 The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx0 + \param[in] tetIdx1 The index of a tetrahedron in the deformable volume's collision mesh that contains the point to be attached to the deformableVolume0 + \param[in] tetBarycentric1 The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx1 + \param[in] constraint The user defined cone distance limit constraint to limit the movement between tets. + \param[in] constraintOffset Offsets the cone and distance limit constraint along its axis, in order to specify the location of the cone tip. + \return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later + */ + PX_DEPRECATED virtual PxU32 addSoftBodyAttachment(PxDeformableVolume* deformableVolume0, PxU32 tetIdx0, const PxVec4& tetBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1, + PxConeLimitedConstraint* constraint = NULL, PxReal constraintOffset = 0.0f) = 0; + + /** + \brief Releases an attachment between a deformable volume and the other deformable volume. + Be aware that destroying the deformable volume before destroying the attachment is illegal and may cause a crash. + + This method removes a previously-created attachment between a point inside a tetrahedron of the collision mesh to a point in another deformable volume's tetrahedron collision mesh. + + \param[in] deformableVolume0 The deformable volume actor used for the attachment. + \param[in] handle Index that identifies the attachment. This handle gets returned by the addSoftBodyAttachment when the attachment is created. + */ + PX_DEPRECATED virtual void removeSoftBodyAttachment(PxDeformableVolume* deformableVolume0, PxU32 handle) = 0; + + /** + \brief Deprecated + \see getGpuDeformableVolumeIndex + */ + PX_DEPRECATED PX_FORCE_INLINE PxU32 getGpuSoftBodyIndex() { return getGpuDeformableVolumeIndex(); } + +protected: + PX_INLINE PxDeformableVolume(PxType concreteType, PxBaseFlags baseFlags) : PxDeformableBody(concreteType, baseFlags) {} + PX_INLINE PxDeformableVolume(PxBaseFlags baseFlags) : PxDeformableBody(baseFlags) {} + virtual ~PxDeformableVolume() {} + virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxDeformableVolume", PxDeformableBody); } +}; + +/** +\brief Adjusts a deformable volume kinematic target such that it is properly set as active or inactive. Inactive targets will not affect vertex position, they are ignored by the solver. + +\param[in] target The kinematic target +\param[in] isActive A boolean indicating if the returned target should be marked as active or not +\return The target with adjusted w component +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureDeformableVolumeKinematicTarget(const PxVec4& target, bool isActive) +{ + PxVec4 result = target; + if (isActive) + result.w = 0.0f; + else + { + //Any non-zero value will mark the target as inactive + if (result.w == 0.0f) + result.w = 1.0f; + } + return result; +} + +/** +\brief Sets up a deformable volume kinematic target such that it is properly set as active or inactive. Inactive targets will not affect vertex position, they are ignored by the solver. + +\param[in] target The kinematic target +\param[in] isActive A boolean indicating if the returned target should be marked as active or not +\return The target with configured w component +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureDeformableVolumeKinematicTarget(const PxVec3& target, bool isActive) +{ + return PxConfigureDeformableVolumeKinematicTarget(PxVec4(target, 0.0f), isActive); +} + +#if PX_VC +#pragma warning(pop) +#endif + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_VOLUME_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolumeFlag.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolumeFlag.h new file mode 100644 index 000000000..56ab7d97d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolumeFlag.h @@ -0,0 +1,84 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_VOLUME_FLAGS_H +#define PX_DEFORMABLE_VOLUME_FLAGS_H + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Flags to enable or disable special modes of a PxDeformableVolume instance +*/ +struct PxDeformableVolumeFlag +{ + enum Enum + { + eCOMPUTE_STRESS_TENSOR = 1 << 0, //!< Enables computation of a Cauchy stress tensor for every tetrahedron in the simulation mesh. The tensors can be accessed through the deformable volume direct API + ePARTIALLY_KINEMATIC = 1 << 1, //!< Enables partially kinematic motion of the collision and simulation mesh. + eDISPLAY_SIM_MESH PX_DEPRECATED = 1 << 2, //!< Deprecated + eDISABLE_SELF_COLLISION PX_DEPRECATED = 1 << 3, //!< Deprecated, use PxDeformableBodyFlag::eDISABLE_SELF_COLLISION instead + eENABLE_CCD PX_DEPRECATED = 1 << 4, //!< Deprecated, use PxDeformableBodyFlag::eENABLE_SPECULATIVE_CCD + eKINEMATIC PX_DEPRECATED = 1 << 5 //!< Deprecated, use PxDeformableBodyFlag::eKINEMATIC instead + }; +}; + +typedef PxFlags PxDeformableVolumeFlags; + +/** +\brief Identifies the buffers of a PxDeformableVolume instance. + +\see PxDeformableVolume::markDirty() +*/ +struct PxDeformableVolumeDataFlag +{ + enum Enum + { + eNONE = 0, + + ePOSITION_INVMASS = 1 << 0, //!< The collision mesh's positions + eSIM_POSITION_INVMASS = 1 << 1, //!< The simulation mesh's positions and inverse masses + eSIM_VELOCITY = 1 << 2, //!< The simulation mesh's velocities + eREST_POSITION_INVMASS = 1 << 3, //!< The collision mesh's rest positions + + eALL = ePOSITION_INVMASS | eSIM_POSITION_INVMASS | eSIM_VELOCITY | eREST_POSITION_INVMASS + }; +}; + +typedef PxFlags PxDeformableVolumeDataFlags; + +#if !PX_DOXYGEN +} +#endif + +#endif // PX_DEFORMABLE_VOLUME_FLAGS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolumeMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolumeMaterial.h new file mode 100644 index 000000000..8b9adce0b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeformableVolumeMaterial.h @@ -0,0 +1,136 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_VOLUME_MATERIAL_H +#define PX_DEFORMABLE_VOLUME_MATERIAL_H + +#include "PxDeformableMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxDeformableVolumeMaterialModel +{ + enum Enum + { + eCO_ROTATIONAL, //!< Default model. Well suited for high stiffness. Does need tetrahedra with good shapes (no extreme slivers) in the rest pose. + eNEO_HOOKEAN //!< Well suited for lower stiffness. Robust to any tetrahedron shape. + }; +}; + +class PxScene; +/** +\brief Material class to represent a set of deformable volume material properties. + +\see PxPhysics.createDeformableVolumeMaterial +*/ +class PxDeformableVolumeMaterial : public PxDeformableMaterial +{ +public: + + /** + \brief Sets material velocity damping term + + \deprecated Use setElasticityDamping instead. + + \param[in] damping Material velocity damping term. Range: [0, PX_MAX_F32)
+ + \see getDamping + */ + PX_DEPRECATED virtual void setDamping(PxReal damping) = 0; + + /** + \brief Retrieves velocity damping + + \deprecated Use getElasticityDamping instead. + + \return The velocity damping. + + \see setDamping() + */ + PX_DEPRECATED virtual PxReal getDamping() const = 0; + + /** + \brief Sets material damping scale. A scale of 1 corresponds to default damping, a value of 0 will only apply damping to certain motions leading to special effects that look similar to water filled softbodies. + + \deprecated Damping scale is deprecated. + + \param[in] scale Damping scale term. Default: 1 Range: [0, 1] + + \see getDampingScale + */ + PX_DEPRECATED virtual void setDampingScale(PxReal scale) = 0; + + /** + \brief Retrieves material damping scale. + + \deprecated Damping scale is deprecated. + + \return The damping scale term. + + \see setDamping() + */ + PX_DEPRECATED virtual PxReal getDampingScale() const = 0; + + /** + \brief Sets the material model. + + \param[in] model The material model + + \see getMaterialModel + */ + virtual void setMaterialModel(PxDeformableVolumeMaterialModel::Enum model) = 0; + + /** + \brief Retrieves the material model. + \return The material model. + + \see setMaterialModel() + */ + virtual PxDeformableVolumeMaterialModel::Enum getMaterialModel() const = 0; + + /** + \brief Gets the concrete type name. + \return The name of the concrete type. + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxDeformableVolumeMaterial"; } + +protected: + PX_INLINE PxDeformableVolumeMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxDeformableMaterial(concreteType, baseFlags) {} + PX_INLINE PxDeformableVolumeMaterial(PxBaseFlags baseFlags) : PxDeformableMaterial(baseFlags) {} + virtual ~PxDeformableVolumeMaterial() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxDeformableVolumeMaterial", PxDeformableMaterial); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_VOLUME_MATERIAL_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDeletionListener.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDeletionListener.h new file mode 100644 index 000000000..f1792fdc8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDeletionListener.h @@ -0,0 +1,100 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DELETION_LISTENER_H +#define PX_DELETION_LISTENER_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + +/** +\brief Flags specifying deletion event types. + +\see PxDeletionListener::onRelease PxPhysics.registerDeletionListener() +*/ +struct PxDeletionEventFlag +{ + enum Enum + { + eUSER_RELEASE = (1<<0), //!< The user has called release on an object. + eMEMORY_RELEASE = (1<<1) //!< The destructor of an object has been called and the memory has been released. + }; +}; + +/** +\brief Collection of set bits defined in PxDeletionEventFlag. + +\see PxDeletionEventFlag +*/ +typedef PxFlags PxDeletionEventFlags; +PX_FLAGS_OPERATORS(PxDeletionEventFlag::Enum,PxU8) + + +/** +\brief interface to get notification on object deletion + +*/ +class PxDeletionListener +{ +public: + /** + \brief Notification if an object or its memory gets released + + If release() gets called on a PxBase object, an eUSER_RELEASE event will get fired immediately. The object state can be queried in the callback but + it is not allowed to change the state. Furthermore, when reading from the object it is the user's responsibility to make sure that no other thread + is writing at the same time to the object (this includes the simulation itself, i.e., #PxScene::fetchResults() must not get called at the same time). + + Calling release() on a PxBase object does not necessarily trigger its destructor immediately. For example, the object can be shared and might still + be referenced by other objects or the simulation might still be running and accessing the object state. In such cases the destructor will be called + as soon as it is safe to do so. After the destruction of the object and its memory, an eMEMORY_RELEASE event will get fired. In this case it is not + allowed to dereference the object pointer in the callback. + + \param[in] observed The object for which the deletion event gets fired. + \param[in] userData The user data pointer of the object for which the deletion event gets fired. Not available for all object types in which case it will be set to 0. + \param[in] deletionEvent The type of deletion event. Do not dereference the object pointer argument if the event is eMEMORY_RELEASE. + + */ + virtual void onRelease(const PxBase* observed, void* userData, PxDeletionEventFlag::Enum deletionEvent) = 0; + +protected: + PxDeletionListener() {} + virtual ~PxDeletionListener() {} +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxDirectGPUAPI.h b/Jusin154_Team3D/Engine/Public/PhysX/PxDirectGPUAPI.h new file mode 100644 index 000000000..b6ddd3b34 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxDirectGPUAPI.h @@ -0,0 +1,470 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DIRECT_GPU_API_H +#define PX_DIRECT_GPU_API_H + +#include "cudamanager/PxCudaTypes.h" +#include "foundation/PxVec4.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief This flag specifies the type of data to get when calling PxDirectGPUAPI::getRigidDynamicData(). +*/ +class PxRigidDynamicGPUAPIReadType +{ +public: + enum Enum + { + eGLOBAL_POSE = 0, //!< Get the global poses. Type: 1 PxTransform per PxRigidDynamic. + eLINEAR_VELOCITY, //!< Get the linear velocities. Type: 1 PxVec3 per PxRigidDynamic. + eANGULAR_VELOCITY, //!< Get the angular velocities. Type: 1 PxVec3 per PxRigidDynamic. + // eLINEAR_ACCELERATION and eANGULAR_ACCELERATION are only available if PxSceneFlag::eENABLE_BODY_ACCELERATIONS is enabled. + eLINEAR_ACCELERATION, //!< Get the linear accelerations. Type: 1 PxVec3 per PxRigidDynamic. + eANGULAR_ACCELERATION //!< Get the angular accelerations. Type: 1 PxVec3 per PxRigidDynamic. + }; +}; + +/** +\brief This flag specifies the type of data to set when calling PxDirectGPUAPI::setRigidDynamicData(). +*/ +class PxRigidDynamicGPUAPIWriteType +{ +public: + enum Enum + { + eGLOBAL_POSE = 0, //!< Set the global poses. Type: 1 PxTransform per PxRigidDynamic. + eLINEAR_VELOCITY, //!< Set the linear velocities. Type: 1 PxVec3 per PxRigidDynamic. + eANGULAR_VELOCITY, //!< Set the angular velocities. Type: 1 PxVec3 per PxRigidDynamic. + eFORCE, //!< Set the forces. Will be applied at the center of gravity of the bodies. Type: 1 PxVec3 per PxRigidDynamic. + eTORQUE //!< Set the torques. Will be applied at the center of gravity of the bodies. Type: 1 PxVec3 per PxRigidDynamic. + }; +}; + +/** +\brief This flag specifies the type of data to get when calling PxDirectGPUAPI::getArticulationData(). +*/ +class PxArticulationGPUAPIReadType +{ + public: + enum Enum + { + eJOINT_POSITION = 0, //!< The joint positions. 1 PxReal per dof. Block size per articulation: maxDofs. + eJOINT_VELOCITY, //!< The joint velocities. 1 PxReal per dof. Block size per articulation: maxDofs. + eJOINT_ACCELERATION, //!< The joint accelerations. 1 PxReal per dof. Block size per articulation: maxDofs. + eJOINT_FORCE, //!< The joint forces or torques applied using setArticulationData. 1 PxReal per dof. Block size per articulation: maxDofs. Not updated by the simulation, will return the values set by PxDirectGPUAPI::setArticulationData(). + eJOINT_TARGET_VELOCITY, //!< The velocity targets applied using setArticulationData. 1 PxReal per dof. Block size per articulation: maxDofs. Not updated by the simulation, will return the values set by PxDirectGPUAPI::setArticulationData(). + eJOINT_TARGET_POSITION, //!< The position targets applied using setArticulationData. 1 PxReal per dof. Block size per articulation: maxDofs. Not updated by the simulation, will return the values set by PxDirectGPUAPI::setArticulationData(). + eROOT_GLOBAL_POSE, //!< The root link global pose. 1 PxTransform per articulation. Block size per articulation: 1. + eROOT_LINEAR_VELOCITY, //!< The root link linear velocity. 1 PxVec3 per articulation. Block size per articulation: 1. + eROOT_ANGULAR_VELOCITY, //!< The root link angular velocity. 1 PxVec3 per articulation. Block size per articulation: 1. + eLINK_GLOBAL_POSE, //!< The link global pose including root link. 1 PxTransform per link. Block size per articulation: maxLinks. + eLINK_LINEAR_VELOCITY, //!< The link linear velocities including root link. 1 PxVec3 per link. Block size per articulation: maxLinks. + eLINK_ANGULAR_VELOCITY, //!< The link angular velocities including root link. 1 PxVec3 per link. Block size per articulation: maxLinks. + eLINK_LINEAR_ACCELERATION, //!< The link linear accelerations including root link. 1 PxVec3 per link. Block size per articulation: maxLinks. + eLINK_ANGULAR_ACCELERATION, //!< The link angular accelerations including root link. 1 PxVec3 per link. Block size per articulation: maxLinks. + eLINK_INCOMING_JOINT_FORCE, //!< The link incoming joint forces including root link. The force is reported in the child joint frame of the link's incoming joint. 2 PxVec3 per link. The first PxVec3 contains the force, and the second PxVec3 contains the torque. Block size per articulation: maxLinks. + eFIXED_TENDON, //!< Fixed tendon data. 1 PxGpuFixedTendonData per fixed tendon. Block size per articulation: maxFixedTendons. Not updated by the simulation, will return the values set by PxDirectGPUAPI::setArticulationData(). + eFIXED_TENDON_JOINT, //!< Fixed tendon joint data. 1 PxGpuTendonJointCoefficientData per fixed tendon joint. Block size per articulation: maxFixedTendons * maxFixedTendonJoints. Not updated by the simulation, will return the values set by PxDirectGPUAPI::setArticulationData(). + eSPATIAL_TENDON, //!< Spatial tendon data. 1 PxGpuSpatialTendonData per spatial tendon. Block size per articulation: maxSpatialTendons. Not updated by the simulation, will return the values set by PxDirectGPUAPI::setArticulationData(). + eSPATIAL_TENDON_ATTACHMENT //!< Spatial tendon attachment data. 1 PxGpuTendonAttachmentData per spatial tendon attachment. Block size per articulation: maxSpatialTendons * maxSpatialTendonAttachments. Not updated by the simulation, will return the values set by PxDirectGPUAPI::setArticulationData(). + }; +}; + +/** +\brief This flag specifies the type of data to set when calling PxDirectGPUAPI::setArticulationData(). +*/ +class PxArticulationGPUAPIWriteType +{ +public: + enum Enum + { + eJOINT_POSITION = 0, //!< The joint positions. 1 PxReal per dof. Block size per articulation: maxDofs. + eJOINT_VELOCITY, //!< The joint velocities. 1 PxReal per dof. Block size per articulation: maxDofs. + eJOINT_FORCE, //!< The applied joint forces or torques. 1 PxReal per dof. Block size per articulation: maxDofs. + eJOINT_TARGET_VELOCITY, //!< The velocity targets for the joint drives. 1 PxReal per dof. Block size per articulation: maxDofs. + eJOINT_TARGET_POSITION, //!< The position targets for the joint drives. 1 PxReal per dof. Block size per articulation: maxDofs. + eROOT_GLOBAL_POSE, //!< The root link transform. 1 PxTransform per articulation. Block size per articulation: 1. + eROOT_LINEAR_VELOCITY, //!< The root link linear velocity. 1 PxVec3 per articulation. Block size per articulation: 1. + eROOT_ANGULAR_VELOCITY, //!< The root link angular velocity. 1 PxVec3 per articulation. Block size per articulation: 1. + eLINK_FORCE, //!< The forces to apply to links. 1 PxVec3 per link. Block size per articulation: maxLinks. + eLINK_TORQUE, //!< The torques to apply to links. 1 PxVec3 per link. Block size per articulation: maxLinks. + eFIXED_TENDON, //!< Fixed tendon data. 1 PxGpuFixedTendonData per fixed tendon. Block size per articulation: maxFixedTendons. + eFIXED_TENDON_JOINT, //!< Fixed tendon joint data. 1 PxGpuTendonJointCoefficientData per fixed tendon joint. Block size per articulation: maxFixedTendons * maxFixedTendonJoints. + eSPATIAL_TENDON, //!< Spatial tendon data. 1 PxGpuSpatialTendonData per spatial tendon. Block size per articulation: maxSpatialTendons. + eSPATIAL_TENDON_ATTACHMENT //!< Spatial tendon attachment data. 1 PxGpuTendonAttachmentData per spatial tendon attachment. Block size per articulation: maxSpatialTendons * maxSpatialTendonAttachments. + }; +}; + +/** +\brief This flag specifies the type of operation to perform when calling PxDirectGPUAPI::computeArticulationData. +*/ +class PxArticulationGPUAPIComputeType +{ +public: + enum Enum + { + eUPDATE_KINEMATIC = 0, //!< Updates the link state for all the articulations specified in the index list. This operation can be performed + //!< by the user to propagate changes made to root transform/root velocities/joint positions/joint velocities to + //!< be reflected in the link transforms/velocities. Performing this operation will clear output values calculated by + //!< the simulation, specifically link accelerations, link incoming joint forces, and joint accelerations. Note + //!< that this is only necessary if the user wants to query link state, otherwise it will be performed automatically + //!< at the start of the next call to simulate(). The data input parameter will be ignored and can be set to NULL for + //!< this operation. + eDENSE_JACOBIANS, //!< Computes the dense Jacobian for the articulation in world space, including the dofs of a potentially floating base. + //!< This is the batched, direct-GPU equivalent of PxArticulationReducedCoordinate::computeDenseJacobian. The output data + //!< buffer is laid out into sequential blocks per articulation, where each block has the size + //!< (6 + maxDofs) * (6 + (maxLinks - 1) * 6) * sizeof(float). maxLinks and maxDofs are the maximum link and dof counts + //!< across all the articulations in the scene, and can be queried by calling PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). + //!< The size of the jacobian can vary by articulation, and will be determined using these formulas: + //!< nCols = (fixedBase ? 0 : 6) + dofCount, nRows = (fixedBase ? 0 : 6) + (linkCount - 1) * 6. The matrix is indexed [nCols * row + column]. + eGENERALIZED_MASS_MATRICES PX_DEPRECATED, //!< Deprecated, use PxArticulationGPUAPIComputeType::eMASS_MATRICES instead. + //!< Computes the joint-space inertia matrices that maps joint accelerations to joint forces: forces = M * accelerations on the GPU. + //!< This is the batched, direct-GPU equivalent of PxArticulationReducedCoordinate::computeGeneralizedMassMatrix(). + //!< The output buffer is laid out into sequential blocks per articulation, where each block has the size maxDofs * maxDofs * sizeof(float). + //!< maxDofs is the maximum dof count across all the articulations in the scene, and can be queried by calling + //!< PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). The size of the matrix can vary by articulation, and will be dofCount * dofCount. + //!< The dof indices will be according to the low-level indexing, we refer to the documentation of PxArticulationCache for an explanation. + eGENERALIZED_GRAVITY_FORCES PX_DEPRECATED, //!< Deprecated, use PxArticulationGPUAPIComputeType::eGRAVITY_COMPENSATION instead. + //!< Computes the joint dof forces required to counteract gravitational forces for the given articulation pose. This is the + //!< batched, direct-GPU equivalent of PxArticulationReducedCoordinate::computeGeneralizedGravityForce(). The output data + //!< buffer is laid out into sequential blocks per articulation, where each block has the size maxDofs * sizeof(float). maxDofs + //!< is the maximum dof count across all the articulations in the scene, and can be queried by calling + //!< PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). The data layout within each block follows the PxArticulationCache layout, + //!< for which we refer to the user guide. There will be 1 PxReal per articulation dof. + eCORIOLIS_AND_CENTRIFUGAL_FORCES PX_DEPRECATED, //!< Deprecated, use PxArticulationGPUAPIComputeType::eCORIOLIS_AND_CENTRIFUGAL_COMPENSATION instead. + //!< Computes the joint dof forces required to counteract Coriolis and centrifugal forces for the given articulation pose. + //!< This is the batched, direct-GPU equivalent to PxArticulationReducedCoordinate::computeCoriolisAndCentrifugalForce(). The output data + //!< buffer is laid out into sequential blocks per articulation, where each block has the size maxDofs * sizeof(float). maxDofs + //!< is the maximum dof count across all the articulations in the scene, and can be queried by calling + //!< PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). The data layout within each block follows the PxArticulationCache layout, + //!< for which we refer to the user guide. There will be 1 PxReal per articulation dof. + eMASS_MATRICES, //!< Computes the mass matrices that maps accelerations to forces: forces = M * accelerations on the GPU. + //!< This is the batched, direct-GPU equivalent of PxArticulationReducedCoordinate::computeMassMatrix(). The output buffer is laid + //!< out into sequential blocks per articulation, where each block has the size (maxDofs + 6) * (maxDofs + 6) * sizeof(float). + //!< maxDofs is the maximum dof count across all the articulations in the scene, and can be queried by calling + //!< PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(), The size of the matrix can vary by articulation, and will be dofCount * dofCount + //!< for fixed-base articulations and (dofCount + 6) * (dofCount + 6) for floating-base articulations. + //!< We refer to the documentation of PxArticulationCache and PxArticulationReducedCoordinate::computeMassMatrix() for a more detailed explanation. + eCORIOLIS_AND_CENTRIFUGAL_COMPENSATION, //!< Computes the joint dof forces (and root force) required to counteract Coriolis and centrifugal forces for the given articulation pose. + //!< This is the batched, direct-GPU equivalent to PxArticulationReducedCoordinate::computeCoriolisCompensation(). The output data + //!< buffer is laid out into sequential blocks per articulation, where each block has the size (maxDofs + 6) * sizeof(float). maxDofs + //!< is the maximum dof count across all the articulations in the scene, and can be queried by calling + //!< PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). The size of the output can vary by articulation, and will be dofCount + //!< for fixed-base articulations and (dofCount + 6) for floating-base articulations. We refer to the documentation of + //!< PxArticulationCache and PxArticulationReducedCoordinate::computeCoriolisCompensation() for a more detailed explanation. + eGRAVITY_COMPENSATION, //!< Computes the forces required to counteract gravitational forces for the given articulation pose. This is the batched, + //!< direct-GPU equivalent of PxArticulationReducedCoordinate::computeGravityCompensation(). The output data buffer is laid out + //!< into sequential blocks per articulation, where each block has the size (maxDofs + 6) * sizeof(float). maxDofs + //!< is the maximum dof count across all the articulations in the scene, and can be queried by calling + //!< PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). The size of the output can vary by articulation, and will be dofCount + //!< for fixed-base articulations and (dofCount + 6) for floating-base articulations. We refer to the documentation of + //!< PxArticulationCache and PxArticulationReducedCoordinate::computeGravityCompensation() for a more detailed explanation. + eARTICULATION_COMS_WORLD_FRAME, //!< Computes the articulation's center of mass in the world frame for the given articulation pose. + //!< This is the batched, direct-GPU equivalent to PxArticulationReducedCoordinate::computeArticulationCOM(). The output data + //!< buffer is laid out into sequential blocks per articulation, where each block has the size sizeof(float) * 3. + eARTICULATION_COMS_ROOT_FRAME, //!< Computes the articulation's center of mass in the root frame for the given articulation pose. + //!< This is the batched, direct-GPU equivalent to PxArticulationReducedCoordinate::computeArticulationCOM(). The output data + //!< buffer is laid out into sequential blocks per articulation, where each block has the size sizeof(float) * 3. + eCENTROIDAL_MOMENTUM_MATRICES //!< Computes the centroidal momentum matrix and bias force for a floating-base articulation. + //!< This is the batched, direct-GPU equivalent to PxArticulationReducedCoordinate::computeCentroidalMomentumMatrix(). The data buffer is laid + //!< out into four main blocks. The two first blocks correspond to the input (mass matrix, Coriolis and Centrifugal compensation force), + //!< and the two last blocks correspond to the output (centroidal momentum matrix, bias force). Each block must be organized into sequential + //!< subblocks per articulation. The size of the subblock is (maxDofs + 6) * (maxDofs + 6) * sizeof(float) for the mass matrix, + //!< (maxDofs + 6) * sizeof(float) for the Coriolis and Centrifugal compensation force, 6 * (maxDofs + 6) * sizeof(float) for the centroidal + //!< momentum matrix, and 6 * sizeof(float) for the bias force. maxDofs is the maximum dof count across all the articulations in the scene, + //!< and can be queried by calling PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). The size of the actual data in each subblock can vary by + //!< articulation, and will depend on the value of dofCount. The dof indices will be according to the low-level indexing, we refer to + //!< the documentation of PxArticulationCache for an explanation. + }; +}; + +/** +\brief Container to hold the results of PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). All the quantities are the maximum values +for the PxScene associated with this instance of PxDirectGPUAPI. +*/ +struct PxArticulationGPUAPIMaxCounts +{ + PxU32 maxDofs; + PxU32 maxLinks; + PxU32 maxFixedTendons; + PxU32 maxFixedTendonJoints; + PxU32 maxSpatialTendons; + PxU32 maxSpatialTendonAttachments; + + PxArticulationGPUAPIMaxCounts() : + maxDofs(0), + maxLinks(0), + maxFixedTendons(0), + maxFixedTendonJoints(0), + maxSpatialTendons(0), + maxSpatialTendonAttachments(0) + { } +}; + +/** +\brief This flag specifies the type of data to get when calling #PxDirectGPUAPI::getD6JointData(). +*/ +class PxD6JointGPUAPIReadType +{ +public: + enum Enum + { + /** + \brief The joint forces applied by the solver. + + The forces are in world space. 1 PxVec3 per joint. + + \note Replaces calls to PxConstraint::getForce() which will not work properly anymore if direct GPU API is used. + */ + eJOINT_FORCE, + + /** + \brief The joint torques applied by the solver. + + The torques are in world space. 1 PxVec3 per joint. + + \note Replaces calls to PxConstraint::getForce() which will not work properly anymore if direct GPU API is used. + */ + eJOINT_TORQUE + }; +}; + +/** +\brief PxDirectGPUAPI exposes an API that enables batched direct access to GPU data for a PxScene. + +The functions in this class allow batched direct access to GPU data for PxRigidDynamic, PxArticulationReducedCoordinate, +PxShape and PxD6Joint types. This allows interoperation with GPU post- and preprocessing for users and allows the user +to implement more efficient CPU-GPU data copies based on the specific needs of the application. + +Using this direct-API will disable the existing CPU-based API for all the data exposed in the direct-API. For any API function +that does not have a counterpart in this direct-API, the existing API will continue to work. + +To use this API, PxSceneFlag::eENABLE_DIRECT_GPU_API needs to be raised, in combination with PxSceneFlag::eENABLE_GPU_DYNAMICS +and PxBroadphaseType::eGPU. Note that these options are immutable and cannot be changed after the scene has been created. + +Due to the internal architecture of the GPU-accelerated parts of PhysX, using this API comes with caveats: + +1) All GPU-CPU copies for data exposed in this API will be disabled. This means that the existing CPU-based API will +return outdated data, and any setters for data exposed in the interface will not work. On the other hand, significant +speedups can be achieved because of the reduced amount of GPU-CPU memory copies. + +2) Due to the internal architecture of the GPU-accelerated PhysX, this API will only work after a first simulation step has been +taken. The reason for this is that the PxScene first needs to know all the actors it will have to simulate, and setup the +sizes of the GPU-based structures. For setup, the existing CPU API should be used. + +\note Due to the fact that this API is exposing low-level data, we do reserve the right to change this API without deprecation +in case of changes in the internal implementations. +*/ + +class PxDirectGPUAPI +{ +protected: + PxDirectGPUAPI() {} + virtual ~PxDirectGPUAPI() {} + +public: + + /** + \brief Copies the simulation state for a set of PxRigidDynamic actors into a user-provided GPU data buffer. + + \param[out] data User-provided GPU data buffer which has size nbElements * sizeof(type). For the types, see the dataType options in PxRigidDynamicGPUAPIReadType. + \param[in] gpuIndices User-provided GPU index buffer containing elements of PxRigidDynamicGPUIndex. This buffer contains the GPU indices of the PxRigidDynamic objects that are part of this get operation. See #PxRigidDynamic::getGPUIndex(). The size of this buffer needs to be nbElements * sizeof(PxRigidDynamicGPUIndex). The data requested for the PxRigidDynamic with its GPU index at position x in the gpuIndices array will be located at position x in the data array. + \param[in] dataType The type of data to get. See #PxRigidDynamicGPUAPIReadType. + \param[in] nbElements The number of rigid bodies to be copied. + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the copy immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + + */ + virtual bool getRigidDynamicData(void* data, const PxRigidDynamicGPUIndex* gpuIndices, PxRigidDynamicGPUAPIReadType::Enum dataType, PxU32 nbElements, CUevent startEvent = NULL, CUevent finishEvent = NULL) const = 0; + + /** + \brief Sets the simulation state for a set of PxRigidDynamic actors from a user-provided GPU data buffer. + + \param[in] data User-provided GPU data buffer which has size nbElements * sizeof(type). For the types, see the dataType options in PxRigidDynamicGPUAPIWriteType. + \param[in] gpuIndices User-provided GPU index buffer containing elements of PxRigidDynamicGPUIndex. This buffer contains the GPU indices of the PxRigidDynamic objects that are part of this set operation. See #PxRigidDynamic::getGPUIndex(). The size of this buffer needs to be nbElements * sizeof(PxRigidDynamicGPUIndex). The data for the PxRigidDynamic with its GPU index at position x in the gpuIndices array needs to be located at position x in the data array. + \param[in] dataType The type of data to set. See #PxRigidDynamicGPUAPIWriteType. + \param[in] nbElements The number of rigid bodies to be set. + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the copy immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + */ + virtual bool setRigidDynamicData(const void* data, const PxRigidDynamicGPUIndex* gpuIndices, PxRigidDynamicGPUAPIWriteType::Enum dataType, PxU32 nbElements, CUevent startEvent = NULL, CUevent finishEvent = NULL) = 0; + + /** + \brief Gets the simulation state for a set of articulations, i.e. PxArticulationReducedCoordinate objects and copies into a user-provided GPU data buffer. + + \param[out] data User-provided GPU data buffer that is appropriately sized for the data being requested. The sizing is explained in detail below. + \param[in] gpuIndices User-provided GPU index buffer containing elements of PxArticulationGPUIndex. This buffer contains the GPU indices of the PxArticulationReducedCoordinate objects that are part of this get operation. See #PxArticulationReducedCoordinate::getGPUIndex(). The size of this buffer needs to be nbElements * sizeof(PxArticulationGPUIndex). The data for the PxArticulationReducedCoordinate with its GPU index at position x in the gpuIndices array will have its data block located at position x in the data array. + \param[in] dataType The type of data to get. See #PxArticulationGPUAPIReadType. + \param[in] nbElements The number of articulations to copy data from. + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the copy immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + + The data buffer must be sized according to the maximum component counts across all articulations in the PxScene, as summarised in PxArticulationGPUAPIMaxCounts. The data buffer is split into sequential + blocks that are of equal size and can hold the data for all components of an articulation. For example, for a link-centric data type (PxArticulationGPUAPIReadType::eLINK_GLOBAL_POSE, for example) + each of these blocks has to be maxLinks * sizeof(dataType). The size of the complete buffer would then be nbElements * maxLinks * sizeof(dataType). For a dof-centric data type, + the block size would be maxDofs * sizeof(dataType). The specific layout for each dataType is detailed in the API documentation of PxArticulationGPUAPIReadType. + The max counts for a scene can be obtained by calling PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). + + The link and dof indexing of these blocks then follows the same pattern as the PxArticulationCache API. We refer to the user guide for an explanation. + */ + virtual bool getArticulationData(void* data, const PxArticulationGPUIndex* gpuIndices, PxArticulationGPUAPIReadType::Enum dataType, PxU32 nbElements, CUevent startEvent = NULL, CUevent finishEvent = NULL) const = 0; + + /** + \brief Sets the simulation state for a set of articulations, i.e. PxArticulationReducedCoordinate objects from a user-provided GPU data buffer. + + \param[in] data User-provided GPU data buffer that is appropriately sized for the data to be set. The sizing is explained in detail below. + \param[in] gpuIndices User-provided GPU index buffer containing elements of PxArticulationGPUIndex. This buffer contains the GPU indices of the PxArticulationReducedCoordinate objects that are part of this set operation. See #PxArticulationReducedCoordinate::getGPUIndex(). The size of this buffer needs to be nbElements * sizeof(PxArticulationGPUIndex). The data for the PxArticulationReducedCoordinate with its GPU index at position x in the gpuIndices array needs to have its data block located at position x in the data array. + \param[in] dataType The type of data to set. See #PxArticulationGPUAPIWriteType. + \param[in] nbElements The number of articulations to set data for. + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the copy immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + + The data buffer must be sized according to the maximum component counts across all articulations in the PxScene, as summarised in PxArticulationGPUAPIMaxCounts. The data buffer is split into sequential + blocks that are of equal size and can hold the data for all components of an articulation. For example, for a link-centric data type (PxArticulationGPUAPIWriteType::eLINK_FORCE, for example) + each of these blocks has to be maxLinks * sizeof(dataType). The size of the complete buffer would then be nbElements * maxLinks * sizeof(dataType). For a dof-centric data type, + the block size would be maxDofs * sizeof(dataType). The specific layout for each dataType is detailed in the API documentation of PxArticulationGPUAPIWriteType. + The max counts for a scene can be obtained by calling PxDirectGPUAPI::getArticulationGPUAPIMaxCounts(). + + The internal indexing of these blocks then follows the same pattern as the PxArticulationCache API. We refer to the user guide for an explanation. + */ + virtual bool setArticulationData(const void* data, const PxArticulationGPUIndex* gpuIndices, PxArticulationGPUAPIWriteType::Enum dataType, PxU32 nbElements, CUevent startEvent = NULL, CUevent finishEvent = NULL) = 0; + + /** + \brief performs a compute operation on a set of articulations, i.e. PxArticulationReducedCoordinate objects. + + \param[in,out] data User-provided GPU data buffer that is appropriately sized for the operation to be performed. Depending on the operation, can be input or output data. + \param[in] gpuIndices User-provided GPU index buffer containing elements of PxArticulationGPUIndex. This buffer contains the GPU indices of the PxArticulationReducedCoordinate objects that are part of this compute operation. See #PxArticulationReducedCoordinate::getGPUIndex(). The size of this buffer needs to be nbElements * sizeof(PxArticulationGPUIndex). + \param[in] operation The operation to perform. See PxArticulationGPUAPIComputeType::Enum. + \param[in] nbElements The number of articulations to perform this compute operation on. + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the computation immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the computation to finish before returning. + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + + The appropriate sizing of the data buffer as well as the data layout is documented alongside the compute operations in the API documentation of PxArticulationGPUAPIComputeType. + */ + virtual bool computeArticulationData(void* data, const PxArticulationGPUIndex* gpuIndices, PxArticulationGPUAPIComputeType::Enum operation, PxU32 nbElements, CUevent startEvent = NULL, CUevent finishEvent = NULL) = 0; + + /** + \brief Copy rigid body (PxRigidBody) and articulation (PxArticulationReducedCoordinate) contact data to a user-provided GPU data buffer. + + \note This function only reports contact data for actor pairs where both actors are either rigid bodies or articulations. + \note The contact data contains pointers to internal state and is only valid until the next call to simulate(). + + \param[out] data User-provided GPU data buffer, which should be the size of PxGpuContactPair * maxPairs + \param[out] nbContactPairs User-provided GPU data buffer of 1 * sizeof(PxU32) that contains the actual number of pairs that was written. + \param[in] maxPairs The maximum number of pairs that the buffer can contain. + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the copy immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + */ + virtual bool copyContactData(void* data, PxU32* nbContactPairs, PxU32 maxPairs, CUevent startEvent = NULL, CUevent finishEvent = NULL) const = 0; + + /** + \brief Evaluate sample point distances and gradients on SDF shapes in local space. Local space is the space in which the mesh's raw vertex positions are represented. + \param[out] localGradientAndSignedDistanceConcatenated User-provided GPU buffer where the evaluated gradients and distances in SDF local space get stored. It has the same structure as localSamplePointsConcatenated. The PxVec4 elements contain the gradient and the distance (gradX, gradY, gradZ, distance). + \param[in] shapeIndices User-provided GPU index buffer containing elements of PxShapeGPUIndex. This buffer contains the GPU indices of the PxShape objects that are part of this operation. See #PxShape::getGPUIndex(). The size of this buffer (in bytes) needs to be nbElements * sizeof(PxShapeGPUIndex). The shapes must be triangle mesh shapes with SDFs. + \param[in] localSamplePointsConcatenated User-provided GPU buffer containing the sample point locations for every shape in the shapes' local space. The buffer stride is maxPointCount. + \param[in] samplePointCountPerShape User-provided GPU buffer containing the number of sample points for every shape. + \param[in] nbElements The number of shapes to be queried. + \param[in] maxPointCount The maximum value in the array samplePointCountPerShape. Note that the arrays localGradientAndSignedDistanceConcatenated and localSamplePointsConcatenated must have the size (in bytes) nbElements * maxPointCount * sizeof(PxVec4). + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the computation immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the computation to finish before returning. + + Example: Ten shapes are part of the simulation. Three of them have an SDF (shapeIndices of the SDF meshes are 2, 4 and 6). For the first shape, the SDF distance of 10 sample points should be queried. 20 sample + points for the second mesh and 30 sample points for the third mesh. The slice size (=maxPointCount) is the maximum of sample points required for any shape participating in the query, 30 = max(10, 20, 30) for this example. + The buffers required for the method evaluateSDFDistances are constructed as follows (not including optional parameters): + * localGradientAndSignedDistanceConcatenated[length: 3 * 30]: + * No initialization needed. It will hold the result after the finishEvent occurred. It has the same structure as localSamplePointsConcatenated, see below. + * The format of the written PxVec4 is as follows (gradX, gradY, gradZ, sdfDistance) + * shapeIndices[length: 3] + * The content is {2, 4, 6} which are the shape indices for this example + * localSamplePointsConcatenated[length: 3 * 30]: + * Slice 0...29 has only the first 10 elements set to local sample points (w component is unused) with respect to the coordinate frame of the first shape to be queried + * Slice 30...59 has only the first 20 elements set to local sample points (w component is unused) with respect to the coordinate frame of the second shape to be queried + * Slice 60...89 has all 30 elements set to local sample points (w component is unused) with respect to the coordinate frame of the third shape to be queried + * samplePointCountPerShape[length: 3] + * The content is {10, 20, 30} which are the number of samples to evaluate per shape used in this example. Note that the slice size (=maxPointCount) is the maximum value in this list. + * nbElements: 3 for this example since 3 shapes are participating in the query + * maxPointCount: 30 for this example since 30 is the slice size (= maxPointCount = 30 = max(10, 20, 30)) + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + */ + virtual bool evaluateSDFDistances(PxVec4* localGradientAndSignedDistanceConcatenated, const PxShapeGPUIndex* shapeIndices, const PxVec4* localSamplePointsConcatenated, const PxU32* samplePointCountPerShape, PxU32 nbElements, PxU32 maxPointCount, CUevent startEvent = NULL, CUevent finishEvent = NULL) const = 0; + + /** + \brief Get the maximal articulation index and component counts for a PxScene. + + Get the maximal articulation index and component counts for a PxScene. This is a helper function to ease the derivation of the correct data layout + for the articulation functions in PxDirectGPUAPI. Specifically, this function will return maxLinks, maxDofs, maxFixedTendons, maxFixedTendonJoints, + maxSpatialTendons and maxSpatialTendonAttachments for a scene. See #PxArticulationGPUAPIMaxCounts. + + \see PxDirectGPUAPI::getArticulationData, PxDirectGPUAPI::setArticulationData, PxDirectGPUAPI::computeArticulationData + + \return PxArticulationGPUAPIMaxCounts the max counts across the scene for all articulation indices and components. + */ + virtual PxArticulationGPUAPIMaxCounts getArticulationGPUAPIMaxCounts() const = 0; + + /** + \brief Copies the simulation state for a set of PxD6Joint instances into a user-provided GPU data buffer. + + \param[out] data User-provided GPU data buffer which has size nbElements * sizeof(type). For the types, see the options in #PxD6JointGPUAPIReadType. + \param[in] gpuIndices User-provided GPU index buffer containing elements of PxD6JointGPUIndex. This buffer contains the GPU indices of the PxD6Joint objects that are part of this get operation + (see #PxD6Joint::getGPUIndex()). The size of this buffer needs to be nbElements * sizeof(PxD6JointGPUIndex). The data requested for the PxD6Joint with its GPU index at position x in the + gpuIndices array will be located at position x in the data array. + \param[in] dataType The type of data to get (see #PxD6JointGPUAPIReadType). + \param[in] nbElements The number of provided GPU indices and as such the number of data entries that will be written to the provided GPU data buffer. + \param[in] startEvent User-provided CUDA event that is awaited at the start of this function. Defaults to NULL which means the function will dispatch the copy immediately. + \param[in] finishEvent User-provided CUDA event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \return bool Whether the operation was successful. Note that this might not include asynchronous CUDA errors. + + */ + virtual bool getD6JointData(void* data, const PxD6JointGPUIndex* gpuIndices, PxD6JointGPUAPIReadType::Enum dataType, PxU32 nbElements, CUevent startEvent = NULL, CUevent finishEvent = NULL) const = 0; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxFEMMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxFEMMaterial.h new file mode 100644 index 000000000..303a341fb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxFEMMaterial.h @@ -0,0 +1,49 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FEM_MATERIAL_H +#define PX_FEM_MATERIAL_H + +#include "PxDeformableMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Deprecated + \see PxDeformableMaterial + */ + typedef PX_DEPRECATED PxDeformableMaterial PxFEMMaterial; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_FEM_MATERIAL_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxFEMParameter.h b/Jusin154_Team3D/Engine/Public/PhysX/PxFEMParameter.h new file mode 100644 index 000000000..31260f39e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxFEMParameter.h @@ -0,0 +1,102 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef PX_PHYSICS_FEM_PARAMETER_H +#define PX_PHYSICS_FEM_PARAMETER_H + +#include "foundation/PxSimpleTypes.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Deprecated. Set of parameters to control the sleeping and collision behavior of FEM based objects + \deprecated See methods of PxDeformableBody. + */ + struct PX_DEPRECATED PxFEMParameters + { + public: + /** + \brief Velocity damping value. After every timestep the velocity is reduced while the magnitude of the reduction depends on velocityDamping + Default: 0.05 + \deprecated See PxDeformableBody.setLinearDamping + */ + PX_DEPRECATED PxReal velocityDamping; + /** + \brief Threshold that defines the maximal magnitude of the linear motion a fem body can move in one second before it becomes a candidate for sleeping + Default: 0.1 + \deprecated See PxDeformableBody.setSettlingThreshold + */ + PX_DEPRECATED PxReal settlingThreshold; + /** + \brief Threshold that defines the maximal magnitude of the linear motion a fem body can move in one second such that it can go to sleep in the next frame + Default: 0.05 + \deprecated See PxDeformableBody.setSleepThreshold + */ + PX_DEPRECATED PxReal sleepThreshold; + /** + \brief Damping value that damps the motion of bodies that move slow enough to be candidates for sleeping (see settlingThreshold) + Default: 10 + \deprecated See PxDeformableBody.setSettlingDamping + */ + PX_DEPRECATED PxReal sleepDamping; + /** + \brief Penetration value that needs to get exceeded before contacts for self collision are generated. Will only have an effect if self collisions are enabled. + Default: 0.1 + \deprecated See PxDeformableBody.setSelfCollisionFilterDistance + */ + PX_DEPRECATED PxReal selfCollisionFilterDistance; + /** + \brief Stress threshold to deactivate collision contacts in case the tetrahedron's stress magnitude exceeds the threshold + Default: 0.9 + \deprecated See PxDeformableVolume.setSelfCollisionStressTolerance + */ + PX_DEPRECATED PxReal selfCollisionStressTolerance; + +#if !PX_CUDA_COMPILER + PxFEMParameters() + { + velocityDamping = 0.05f; + settlingThreshold = 0.1f; + sleepThreshold = 0.05f; + sleepDamping = 10.f; + selfCollisionFilterDistance = 0.1f; + selfCollisionStressTolerance = 0.9f; + } +#endif + }; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxFEMSoftBodyMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxFEMSoftBodyMaterial.h new file mode 100644 index 000000000..b9ddcdd81 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxFEMSoftBodyMaterial.h @@ -0,0 +1,56 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FEM_SOFT_BODY_MATERIAL_H +#define PX_FEM_SOFT_BODY_MATERIAL_H + +#include "PxDeformableVolumeMaterial.h" +#include "PxFEMMaterial.h" // deprecated + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Deprecated +\see PxDeformableVolumeMaterialModel +*/ +typedef PX_DEPRECATED PxDeformableVolumeMaterialModel PxFEMSoftBodyMaterialModel; + +/** +\brief Deprecated +\see PxDeformableVolumeMaterial +*/ +typedef PX_DEPRECATED PxDeformableVolumeMaterial PxFEMSoftBodyMaterial; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_FEM_SOFT_BODY_MATERIAL_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxFiltering.h b/Jusin154_Team3D/Engine/Public/PhysX/PxFiltering.h new file mode 100644 index 000000000..7a6f946c3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxFiltering.h @@ -0,0 +1,778 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FILTERING_H +#define PX_FILTERING_H + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxActor; +class PxShape; + +/** +\brief Collection of flags describing the actions to take for a collision pair. + +\see PxPairFlags PxSimulationFilterShader.filter() PxSimulationFilterCallback +*/ +struct PxPairFlag +{ + enum Enum + { + /** + \brief Process the contacts of this collision pair in the dynamics solver. + + \note Only takes effect if the colliding actors are rigid bodies. + */ + eSOLVE_CONTACT = (1<<0), + + /** + \brief Call contact modification callback for this collision pair + + \note Only takes effect if the colliding actors are rigid bodies. + + \see PxContactModifyCallback + */ + eMODIFY_CONTACTS = (1<<1), + + /** + \brief Call contact report callback or trigger callback when this collision pair starts to be in contact. + + If one of the two collision objects is a trigger shape (see #PxShapeFlag::eTRIGGER_SHAPE) + then the trigger callback will get called as soon as the other object enters the trigger volume. + If none of the two collision objects is a trigger shape then the contact report callback will get + called when the actors of this collision pair start to be in contact. + + \note Only takes effect if the colliding actors are rigid bodies. + + \note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised + + \see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger() + */ + eNOTIFY_TOUCH_FOUND = (1<<2), + + /** + \brief Call contact report callback while this collision pair is in contact + + If none of the two collision objects is a trigger shape then the contact report callback will get + called while the actors of this collision pair are in contact. + + \note Triggers do not support this event. Persistent trigger contacts need to be tracked separately by observing eNOTIFY_TOUCH_FOUND/eNOTIFY_TOUCH_LOST events. + + \note Only takes effect if the colliding actors are rigid bodies. + + \note No report will get sent if the objects in contact are sleeping. + + \note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised + + \note If this flag gets enabled while a pair is in touch already, there will be no eNOTIFY_TOUCH_PERSISTS events until the pair loses and regains touch. + + \see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger() + */ + eNOTIFY_TOUCH_PERSISTS = (1<<3), + + /** + \brief Call contact report callback or trigger callback when this collision pair stops to be in contact + + If one of the two collision objects is a trigger shape (see #PxShapeFlag::eTRIGGER_SHAPE) + then the trigger callback will get called as soon as the other object leaves the trigger volume. + If none of the two collision objects is a trigger shape then the contact report callback will get + called when the actors of this collision pair stop to be in contact. + + \note Only takes effect if the colliding actors are rigid bodies. + + \note This event will also get triggered if one of the colliding objects gets deleted. + + \note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised + + \see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger() + */ + eNOTIFY_TOUCH_LOST = (1<<4), + + /** + \brief Call contact report callback when this collision pair is in contact during CCD passes. + + If CCD with multiple passes is enabled, then a fast moving object might bounce on and off the same + object multiple times. Hence, the same pair might be in contact multiple times during a simulation step. + This flag will make sure that all the detected collision during CCD will get reported. For performance + reasons, the system can not always tell whether the contact pair lost touch in one of the previous CCD + passes and thus can also not always tell whether the contact is new or has persisted. eNOTIFY_TOUCH_CCD + just reports when the two collision objects were detected as being in contact during a CCD pass. + + \note Only takes effect if the colliding actors are rigid bodies. + + \note Trigger shapes are not supported. + + \note Only takes effect if eDETECT_CCD_CONTACT is raised + + \see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger() + */ + eNOTIFY_TOUCH_CCD = (1<<5), + + /** + \brief Call contact report callback when the contact force between the actors of this collision pair exceeds one of the actor-defined force thresholds. + + \note Only takes effect if the colliding actors are rigid bodies. + + \note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised + + \note Only works with PGS solver, and only on CPU. + + \see PxSimulationEventCallback.onContact() + */ + eNOTIFY_THRESHOLD_FORCE_FOUND = (1<<6), + + /** + \brief Call contact report callback when the contact force between the actors of this collision pair continues to exceed one of the actor-defined force thresholds. + + \note Only takes effect if the colliding actors are rigid bodies. + + \note If a pair gets re-filtered and this flag has previously been disabled, then the report will not get fired in the same frame even if the force threshold has been reached in the + previous one (unless #eNOTIFY_THRESHOLD_FORCE_FOUND has been set in the previous frame). + + \note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised + + \note Only works with PGS solver, and only on CPU. + + \see PxSimulationEventCallback.onContact() + */ + eNOTIFY_THRESHOLD_FORCE_PERSISTS = (1<<7), + + /** + \brief Call contact report callback when the contact force between the actors of this collision pair falls below one of the actor-defined force thresholds (includes the case where this collision pair stops being in contact). + + \note Only takes effect if the colliding actors are rigid bodies. + + \note If a pair gets re-filtered and this flag has previously been disabled, then the report will not get fired in the same frame even if the force threshold has been reached in the + previous one (unless #eNOTIFY_THRESHOLD_FORCE_FOUND or #eNOTIFY_THRESHOLD_FORCE_PERSISTS has been set in the previous frame). + + \note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised + + \note Only works with PGS solver, and only on CPU. + + \see PxSimulationEventCallback.onContact() + */ + eNOTIFY_THRESHOLD_FORCE_LOST = (1<<8), + + /** + \brief Provide contact points in contact reports for this collision pair. + + \note Only takes effect if the colliding actors are rigid bodies and if used in combination with the flags eNOTIFY_TOUCH_... or eNOTIFY_THRESHOLD_FORCE_... + + \note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised + + \see PxSimulationEventCallback.onContact() PxContactPair PxContactPair.extractContacts() + */ + eNOTIFY_CONTACT_POINTS = (1<<9), + + /** + \brief This flag is used to indicate whether this pair generates discrete collision detection contacts. + + \note Contacts are only responded to if eSOLVE_CONTACT is enabled. + */ + eDETECT_DISCRETE_CONTACT = (1<<10), + + /** + \brief This flag is used to indicate whether this pair generates CCD contacts. + + \note The contacts will only be responded to if eSOLVE_CONTACT is enabled on this pair. + \note The scene must have PxSceneFlag::eENABLE_CCD enabled to use this feature. + \note Non-static bodies of the pair should have PxRigidBodyFlag::eENABLE_CCD specified for this feature to work correctly. + \note This flag is not supported with trigger shapes. However, CCD trigger events can be emulated using non-trigger shapes + and requesting eNOTIFY_TOUCH_FOUND and eNOTIFY_TOUCH_LOST and not raising eSOLVE_CONTACT on the pair. + + \see PxRigidBodyFlag::eENABLE_CCD + \see PxSceneFlag::eENABLE_CCD + */ + eDETECT_CCD_CONTACT = (1<<11), + + /** + \brief Provide pre solver velocities in contact reports for this collision pair. + + If the collision pair has contact reports enabled, the velocities of the rigid bodies before contacts have been solved + will be provided in the contact report callback unless the pair lost touch in which case no data will be provided. + + \note Usually it is not necessary to request these velocities as they will be available by querying the velocity from the provided + PxRigidActor object directly. However, it might be the case that the velocity of a rigid body gets set while the simulation is running + in which case the PxRigidActor would return this new velocity in the contact report callback and not the velocity the simulation used. + + \see PxSimulationEventCallback.onContact(), PxContactPairVelocity, PxContactPairHeader.extraDataStream + */ + ePRE_SOLVER_VELOCITY = (1<<12), + + /** + \brief Provide post solver velocities in contact reports for this collision pair. + + If the collision pair has contact reports enabled, the velocities of the rigid bodies after contacts have been solved + will be provided in the contact report callback unless the pair lost touch in which case no data will be provided. + + \see PxSimulationEventCallback.onContact(), PxContactPairVelocity, PxContactPairHeader.extraDataStream + */ + ePOST_SOLVER_VELOCITY = (1<<13), + + /** + \brief Provide rigid body poses in contact reports for this collision pair. + + If the collision pair has contact reports enabled, the rigid body poses at the contact event will be provided + in the contact report callback unless the pair lost touch in which case no data will be provided. + + \note Usually it is not necessary to request these poses as they will be available by querying the pose from the provided + PxRigidActor object directly. However, it might be the case that the pose of a rigid body gets set while the simulation is running + in which case the PxRigidActor would return this new pose in the contact report callback and not the pose the simulation used. + Another use case is related to CCD with multiple passes enabled, A fast moving object might bounce on and off the same + object multiple times. This flag can be used to request the rigid body poses at the time of impact for each such collision event. + + \see PxSimulationEventCallback.onContact(), PxContactPairPose, PxContactPairHeader.extraDataStream + */ + eCONTACT_EVENT_POSE = (1<<14), + + eNEXT_FREE = (1<<15), //!< For internal use only. + + /** + \brief Provided default flag to do simple contact processing for this collision pair. + */ + eCONTACT_DEFAULT = eSOLVE_CONTACT | eDETECT_DISCRETE_CONTACT, + + /** + \brief Provided default flag to get commonly used trigger behavior for this collision pair. + */ + eTRIGGER_DEFAULT = eNOTIFY_TOUCH_FOUND | eNOTIFY_TOUCH_LOST | eDETECT_DISCRETE_CONTACT + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxPairFlag. + +\see PxPairFlag +*/ +typedef PxFlags PxPairFlags; +PX_FLAGS_OPERATORS(PxPairFlag::Enum, PxU16) + + + +/** +\brief Collection of flags describing the filter actions to take for a collision pair. + +\see PxFilterFlags PxSimulationFilterShader PxSimulationFilterCallback +*/ +struct PxFilterFlag +{ + enum Enum + { + /** + \brief Ignore the collision pair as long as the bounding volumes of the pair objects overlap. + + Killed pairs will be ignored by the simulation and won't run through the filter again until one + of the following occurs: + + \li The bounding volumes of the two objects overlap again (after being separated) + \li The user enforces a re-filtering (see #PxScene::resetFiltering()) + + \see PxScene::resetFiltering() + */ + eKILL = (1<<0), + + /** + \brief Ignore the collision pair as long as the bounding volumes of the pair objects overlap or until filtering relevant data changes for one of the collision objects. + + Suppressed pairs will be ignored by the simulation and won't make another filter request until one + of the following occurs: + + \li Same conditions as for killed pairs (see #eKILL) + \li The filter data or the filter object attributes change for one of the collision objects + + \see PxFilterData PxFilterObjectAttributes + */ + eSUPPRESS = (1<<1), + + /** + \brief Invoke the filter callback (#PxSimulationFilterCallback::pairFound()) for this collision pair. + + \see PxSimulationFilterCallback + */ + eCALLBACK = (1<<2), + + /** + \brief Track this collision pair with the filter callback mechanism. + + When the bounding volumes of the collision pair lose contact, the filter callback #PxSimulationFilterCallback::pairLost() + will be invoked. Furthermore, the filter status of the collision pair can be adjusted through #PxSimulationFilterCallback::statusChange() + once per frame (until a pairLost() notification occurs). + + \see PxSimulationFilterCallback + */ + eNOTIFY = (1<<3) | eCALLBACK, + + /** + \brief Provided default to get standard behavior: + + The application configure the pair's collision properties once when bounding volume overlap is found and + doesn't get asked again about that pair until overlap status or filter properties changes, or re-filtering is requested. + + No notification is provided when bounding volume overlap is lost + + The pair will not be killed or suppressed, so collision detection will be processed + */ + + eDEFAULT = 0 + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxFilterFlag. + +\see PxFilterFlag +*/ +typedef PxFlags PxFilterFlags; +PX_FLAGS_OPERATORS(PxFilterFlag::Enum, PxU16) + + +/** +\brief PxFilterData is user-definable data which gets passed into the collision filtering shader and/or callback. + +\see PxShape.setSimulationFilterData() PxShape.getSimulationFilterData() PxSimulationFilterShader PxSimulationFilterCallback +*/ +struct PxFilterData +{ + PX_INLINE PxFilterData(const PxEMPTY) + { + } + + /** + \brief Default constructor. + */ + PX_INLINE PxFilterData() + { + word0 = word1 = word2 = word3 = 0; + } + + /** + \brief Copy constructor. + */ + PX_INLINE PxFilterData(const PxFilterData& fd) : word0(fd.word0), word1(fd.word1), word2(fd.word2), word3(fd.word3) {} + + /** + \brief Constructor to set filter data initially. + */ + PX_INLINE PxFilterData(PxU32 w0, PxU32 w1, PxU32 w2, PxU32 w3) : word0(w0), word1(w1), word2(w2), word3(w3) {} + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + *this = PxFilterData(); + } + + /** + \brief Assignment operator + */ + PX_INLINE void operator = (const PxFilterData& fd) + { + word0 = fd.word0; + word1 = fd.word1; + word2 = fd.word2; + word3 = fd.word3; + } + + /** + \brief Comparison operator to allow use in Array. + */ + PX_INLINE bool operator == (const PxFilterData& a) const + { + return a.word0 == word0 && a.word1 == word1 && a.word2 == word2 && a.word3 == word3; + } + + /** + \brief Comparison operator to allow use in Array. + */ + PX_INLINE bool operator != (const PxFilterData& a) const + { + return !(a == *this); + } + + PxU32 word0; + PxU32 word1; + PxU32 word2; + PxU32 word3; +}; + + +/** +\brief Identifies each type of filter object. + +\see PxGetFilterObjectType() +*/ +struct PxFilterObjectType +{ + enum Enum + { + /** + \brief A static rigid body + \see PxRigidStatic + */ + eRIGID_STATIC, + + /** + \brief A dynamic rigid body + \see PxRigidDynamic + */ + eRIGID_DYNAMIC, + + /** + \brief An articulation + \see PxArticulationReducedCoordinate + */ + eARTICULATION, + + /** + \brief A deformable surface + \see PxDeformableSurface + */ + eDEFORMABLE_SURFACE, + + /** + \brief A deformable volume + \see PxDeformableVolume + */ + eDEFORMABLE_VOLUME, + + eSOFTBODY PX_DEPRECATED = eDEFORMABLE_VOLUME, //!< \deprecated + + /** + \brief A particle system + \see PxParticleSystem + */ + ePARTICLESYSTEM, + + //! \brief internal use only! + eMAX_TYPE_COUNT = 16, + + //! \brief internal use only! + eUNDEFINED = eMAX_TYPE_COUNT-1 + }; +}; + + +// For internal use only +struct PxFilterObjectFlag +{ + enum Enum + { + eKINEMATIC = (1<<4), + eTRIGGER = (1<<5), + eCUSTOM_GEOMETRY = (1 << 6), + + eNEXT_FREE = (1<<7) // Used internally + }; +}; + + +/** +\brief Structure which gets passed into the collision filtering shader and/or callback providing additional information on objects of a collision pair + +\see PxSimulationFilterShader PxSimulationFilterCallback getActorType() PxFilterObjectIsKinematic() PxFilterObjectIsTrigger() +*/ +typedef PxU32 PxFilterObjectAttributes; + + +/** +\brief Extract filter object type from the filter attributes of a collision pair object + +\param[in] attr The filter attribute of a collision pair object +\return The type of the collision pair object. + +\see PxFilterObjectType +*/ +PX_INLINE PxFilterObjectType::Enum PxGetFilterObjectType(PxFilterObjectAttributes attr) +{ + return PxFilterObjectType::Enum(attr & (PxFilterObjectType::eMAX_TYPE_COUNT-1)); +} + + +/** +\brief Specifies whether the collision object belongs to a kinematic rigid body + +\param[in] attr The filter attribute of a collision pair object +\return True if the object belongs to a kinematic rigid body, else false + +\see PxRigidBodyFlag::eKINEMATIC +*/ +PX_INLINE bool PxFilterObjectIsKinematic(PxFilterObjectAttributes attr) +{ + return (attr & PxFilterObjectFlag::eKINEMATIC) != 0; +} + + +/** +\brief Specifies whether the collision object is a trigger shape + +\param[in] attr The filter attribute of a collision pair object +\return True if the object is a trigger shape, else false + +\see PxShapeFlag::eTRIGGER_SHAPE +*/ +PX_INLINE bool PxFilterObjectIsTrigger(PxFilterObjectAttributes attr) +{ + return (attr & PxFilterObjectFlag::eTRIGGER) != 0; +} + +/** +\brief Filter method to specify how a pair of potentially colliding objects should be processed. + +Collision filtering is a mechanism to specify how a pair of potentially colliding objects should be processed by the +simulation. A pair of objects is potentially colliding if the bounding volumes of the two objects overlap. +In short, a collision filter decides whether a collision pair should get processed, temporarily ignored or discarded. +If a collision pair should get processed, the filter can additionally specify how it should get processed, for instance, +whether contacts should get resolved, which callbacks should get invoked or which reports should be sent etc. +The function returns the PxFilterFlag flags and sets the PxPairFlag flags to define what the simulation should do with the given collision pair. + +\note A default implementation of a filter shader is provided in the PhysX extensions library, see #PxDefaultSimulationFilterShader. + +This methods gets called when: +\li The bounding volumes of two objects start to overlap. +\li The bounding volumes of two objects overlap and the filter data or filter attributes of one of the objects changed +\li A re-filtering was forced through resetFiltering() (see #PxScene::resetFiltering()) +\li Filtering is requested in scene queries + +\note Certain pairs of objects are always ignored and this method does not get called. This is the case for the +following pairs: + +\li Pair of static rigid actors +\li A static rigid actor and a kinematic actor (unless one is a trigger or if explicitly enabled through PxPairFilteringMode::eKEEP) +\li Two kinematic actors (unless one is a trigger or if explicitly enabled through PxPairFilteringMode::eKEEP) +\li Two jointed rigid bodies and the joint was defined to disable collision +\li Two articulation links if connected through an articulation joint + +\note This is a performance critical method and should be stateless. You should neither access external objects +from within this method nor should you call external methods that are not inlined. If you need a more complex +logic to filter a collision pair then use the filter callback mechanism for this pair (see #PxSimulationFilterCallback, +#PxFilterFlag::eCALLBACK, #PxFilterFlag::eNOTIFY). + +\param[in] attributes0 The filter attribute of the first object +\param[in] filterData0 The custom filter data of the first object +\param[in] attributes1 The filter attribute of the second object +\param[in] filterData1 The custom filter data of the second object +\param[out] pairFlags Flags giving additional information on how an accepted pair should get processed +\param[in] constantBlock The constant global filter data (see #PxSceneDesc.filterShaderData) +\param[in] constantBlockSize Size of the global filter data (see #PxSceneDesc.filterShaderDataSize) +\return Filter flags defining whether the pair should be discarded, temporarily ignored, processed and whether the +filter callback should get invoked for this pair. + +\see PxSimulationFilterCallback PxFilterData PxFilterObjectAttributes PxFilterFlag PxFilterFlags PxPairFlag PxPairFlags PxSceneDesc.filterShader +*/ +typedef PxFilterFlags (*PxSimulationFilterShader) + (PxFilterObjectAttributes attributes0, PxFilterData filterData0, + PxFilterObjectAttributes attributes1, PxFilterData filterData1, + PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize); + + + +/** +\brief Filter callback to specify handling of collision pairs. + +This class is provided to implement more complex and flexible collision pair filtering logic, for instance, taking +the state of the user application into account. Filter callbacks also give the user the opportunity to track collision +pairs and update their filter state. + +You might want to check the documentation on #PxSimulationFilterShader as well since it includes more general information +on filtering. + +\note SDK state should not be modified from within the callbacks. In particular objects should not +be created or destroyed. If state modification is needed then the changes should be stored to a buffer +and performed after the simulation step. + +\note The callbacks may execute in user threads or simulation threads, possibly simultaneously. The corresponding objects +may have been deleted by the application earlier in the frame. It is the application's responsibility to prevent race conditions +arising from using the SDK API in the callback while an application thread is making write calls to the scene, and to ensure that +the callbacks are thread-safe. Return values which depend on when the callback is called during the frame will introduce nondeterminism +into the simulation. + +\see PxSceneDesc.filterCallback PxSimulationFilterShader +*/ +class PxSimulationFilterCallback +{ +public: + + /** + \brief Filter method to specify how a pair of potentially colliding objects should be processed. + + This method gets called when the filter flags returned by the filter shader (see #PxSimulationFilterShader) + indicate that the filter callback should be invoked (#PxFilterFlag::eCALLBACK or #PxFilterFlag::eNOTIFY set). + Return the PxFilterFlag flags and set the PxPairFlag flags to define what the simulation should do with the given + collision pair. + + \param[in] pairID Unique ID of the collision pair used to issue filter status changes for the pair (see #statusChange()) + \param[in] attributes0 The filter attribute of the first object + \param[in] filterData0 The custom filter data of the first object + \param[in] a0 Actor pointer of the first object + \param[in] s0 Shape pointer of the first object (NULL if the object has no shapes) + \param[in] attributes1 The filter attribute of the second object + \param[in] filterData1 The custom filter data of the second object + \param[in] a1 Actor pointer of the second object + \param[in] s1 Shape pointer of the second object (NULL if the object has no shapes) + \param[in,out] pairFlags In: Pair flags returned by the filter shader. Out: Additional information on how an accepted pair should get processed + \return Filter flags defining whether the pair should be discarded, temporarily ignored or processed and whether the pair + should be tracked and send a report on pair deletion through the filter callback + + \see PxSimulationFilterShader PxFilterData PxFilterObjectAttributes PxFilterFlag PxPairFlag + */ + virtual PxFilterFlags pairFound( PxU64 pairID, + PxFilterObjectAttributes attributes0, PxFilterData filterData0, const PxActor* a0, const PxShape* s0, + PxFilterObjectAttributes attributes1, PxFilterData filterData1, const PxActor* a1, const PxShape* s1, + PxPairFlags& pairFlags) = 0; + + /** + \brief Callback to inform that a tracked collision pair is gone. + + This method gets called when a collision pair disappears or gets re-filtered. Only applies to + collision pairs which have been marked as filter callback pairs (#PxFilterFlag::eNOTIFY set in #pairFound()). + + \param[in] pairID Unique ID of the collision pair that disappeared + \param[in] attributes0 The filter attribute of the first object + \param[in] filterData0 The custom filter data of the first object + \param[in] attributes1 The filter attribute of the second object + \param[in] filterData1 The custom filter data of the second object + \param[in] objectRemoved True if the pair was lost because one of the objects got removed from the scene + + \see pairFound() PxSimulationFilterShader PxFilterData PxFilterObjectAttributes + */ + virtual void pairLost( PxU64 pairID, + PxFilterObjectAttributes attributes0, PxFilterData filterData0, + PxFilterObjectAttributes attributes1, PxFilterData filterData1, + bool objectRemoved) = 0; + + /** + \brief Callback to give the opportunity to change the filter state of a tracked collision pair. + + This method gets called once per simulation step to let the application change the filter and pair + flags of a collision pair that has been reported in #pairFound() and requested callbacks by + setting #PxFilterFlag::eNOTIFY. To request a change of filter status, the target pair has to be + specified by its ID, the new filter and pair flags have to be provided and the method should return true. + + \note If this method changes the filter status of a collision pair and the pair should keep being tracked + by the filter callbacks then #PxFilterFlag::eNOTIFY has to be set. + + \note The application is responsible to ensure that this method does not get called for pairs that have been + reported as lost, see #pairLost(). + + \param[out] pairID ID of the collision pair for which the filter status should be changed + \param[out] pairFlags The new pairFlags to apply to the collision pair + \param[out] filterFlags The new filterFlags to apply to the collision pair + \return True if the changes should be applied. In this case the method will get called again. False if + no more status changes should be done in the current simulation step. In that case the provided flags will be discarded. + + \see pairFound() pairLost() PxFilterFlag PxPairFlag + */ + virtual bool statusChange(PxU64& pairID, PxPairFlags& pairFlags, PxFilterFlags& filterFlags) = 0; + +protected: + virtual ~PxSimulationFilterCallback() {} +}; + +struct PxPairFilteringMode +{ + enum Enum + { + /** + \brief Output pair from BP, potentially send to user callbacks, create regular interaction object. + + Enable contact pair filtering between kinematic/static or kinematic/kinematic rigid bodies. + + By default contacts between these are suppressed (see #PxFilterFlag::eSUPPRESS) and don't get reported to the filter mechanism. + Use this mode if these pairs should go through the filtering pipeline nonetheless. + + \note This mode is not mutable, and must be set in PxSceneDesc at scene creation. + */ + eKEEP, + + /** + \brief Output pair from BP, create interaction marker. Can be later switched to regular interaction. + */ + eSUPPRESS, + + /** + \brief Don't output pair from BP. Cannot be later switched to regular interaction, needs "resetFiltering" call. + */ + eKILL, + + /** + \brief Default is eSUPPRESS for compatibility with previous PhysX versions. + */ + eDEFAULT = eSUPPRESS + }; +}; + +/** +\brief Struct for storing a particle/vertex - rigid filter pair with comparison operators +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +struct PX_DEPRECATED PxParticleRigidFilterPair +{ + PX_CUDA_CALLABLE PxParticleRigidFilterPair() {} + + PX_CUDA_CALLABLE PxParticleRigidFilterPair(const PxU64 id0, const PxU64 id1): mID0(id0), mID1(id1) {} + + PxU64 mID0; //!< Rigid node index + PxU64 mID1; //!< Particle/vertex id + + PX_CUDA_CALLABLE bool operator<(const PxParticleRigidFilterPair& other) const + { + if(mID0 < other.mID0) + return true; + if(mID0 == other.mID0 && mID1 < other.mID1) + return true; + return false; + } + + PX_CUDA_CALLABLE bool operator>(const PxParticleRigidFilterPair& other) const + { + if(mID0 > other.mID0) + return true; + if(mID0 == other.mID0 && mID1 > other.mID1) + return true; + return false; + } + + PX_CUDA_CALLABLE bool operator==(const PxParticleRigidFilterPair& other) const + { + return (mID0 == other.mID0 && mID1 == other.mID1); + } +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxForceMode.h b/Jusin154_Team3D/Engine/Public/PhysX/PxForceMode.h new file mode 100644 index 000000000..6e31256f5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxForceMode.h @@ -0,0 +1,60 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FORCE_MODE_H +#define PX_FORCE_MODE_H + +#include "foundation/PxPreprocessor.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Parameter to addForce() and addTorque() calls, determines the exact operation that is carried out. + +\see PxRigidBody.addForce() PxRigidBody.addTorque() +*/ +struct PxForceMode +{ + enum Enum + { + eFORCE, //!< parameter has unit of mass * length / time^2, i.e., a force + eIMPULSE, //!< parameter has unit of mass * length / time, i.e., force * time + eVELOCITY_CHANGE, //!< parameter has unit of length / time, i.e., the effect is mass independent: a velocity change. + eACCELERATION //!< parameter has unit of length/ time^2, i.e., an acceleration. It gets treated just like a force except the mass is not divided out before integration. + }; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxImmediateMode.h b/Jusin154_Team3D/Engine/Public/PhysX/PxImmediateMode.h new file mode 100644 index 000000000..40ed8a9f0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxImmediateMode.h @@ -0,0 +1,740 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_IMMEDIATE_MODE_H +#define PX_IMMEDIATE_MODE_H + +#include "PxPhysXConfig.h" +#include "foundation/PxMemory.h" +#include "solver/PxSolverDefs.h" +#include "collision/PxCollisionDefs.h" +#include "PxArticulationReducedCoordinate.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxCudaContextManager; + class PxBaseTask; + class PxGeometry; + +#if !PX_DOXYGEN +namespace immediate +{ +#endif + + typedef void* PxArticulationHandle; + + /** + \brief Structure to store linear and angular components of spatial vector + */ + struct PxSpatialVector + { + PxVec3 top; + PxReal pad0; + PxVec3 bottom; + PxReal pad1; + }; + + /** + \brief Structure to store rigid body properties + */ + struct PxRigidBodyData + { + PX_ALIGN(16, PxVec3 linearVelocity); //!< 12 Linear velocity + PxReal invMass; //!< 16 Inverse mass + PxVec3 angularVelocity; //!< 28 Angular velocity + PxReal maxDepenetrationVelocity; //!< 32 Maximum de-penetration velocity + PxVec3 invInertia; //!< 44 Mass-space inverse interia diagonal vector + PxReal maxContactImpulse; //!< 48 Maximum permissable contact impulse + PxTransform body2World; //!< 76 World space transform + PxReal linearDamping; //!< 80 Linear damping coefficient + PxReal angularDamping; //!< 84 Angular damping coefficient + PxReal maxLinearVelocitySq; //!< 88 Squared maximum linear velocity + PxReal maxAngularVelocitySq; //!< 92 Squared maximum angular velocity + PxU32 pad; //!< 96 Padding for 16-byte alignment + }; + + /** + \brief Callback class to record contact points produced by immediate::PxGenerateContacts + */ + class PxContactRecorder + { + public: + /** + \brief Method to record new contacts + \param [in] contactPoints The contact points produced + \param [in] nbContacts The number of contact points produced + \param [in] index The index of this pair. This is an index from 0-N-1 identifying which pair this relates to from within the array of pairs passed to PxGenerateContacts + \return a boolean to indicate if this callback successfully stored the contacts or not. + */ + virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 index) = 0; + + virtual ~PxContactRecorder(){} + }; + + /** + \brief Constructs a PxSolverBodyData structure based on rigid body properties. Applies gravity, damping and clamps maximum velocity. + \param [in] inRigidData The array rigid body properties + \param [out] outSolverBodyData The array of solverBodyData produced to represent these bodies + \param [in] nbBodies The total number of solver bodies to create + \param [in] gravity The gravity vector + \param [in] dt The timestep + \param [in] gyroscopicForces Indicates whether gyroscopic forces should be integrated + */ + PX_C_EXPORT PX_PHYSX_CORE_API void PxConstructSolverBodies(const PxRigidBodyData* inRigidData, PxSolverBodyData* outSolverBodyData, PxU32 nbBodies, const PxVec3& gravity, PxReal dt, bool gyroscopicForces = false); + + /** + \brief Constructs a PxSolverBodyData structure for a static body at a given pose. + \param [in] globalPose The pose of this static actor + \param [out] solverBodyData The solver body representation of this static actor + */ + PX_C_EXPORT PX_PHYSX_CORE_API void PxConstructStaticSolverBody(const PxTransform& globalPose, PxSolverBodyData& solverBodyData); + + /** + \brief Groups together sets of independent PxSolverConstraintDesc objects to be solved using SIMD SOA approach. + \param [in] solverConstraintDescs The set of solver constraint descs to batch + \param [in] nbConstraints The number of constraints to batch + \param [in,out] solverBodies The array of solver bodies that the constraints reference. Some fields in these structures are written to as scratch memory for the batching. + \param [in] nbBodies The number of bodies + \param [out] outBatchHeaders The batch headers produced by this batching process. This array must have at least 1 entry per input constraint + \param [out] outOrderedConstraintDescs A reordered copy of the constraint descs. This array is referenced by the constraint batches. This array must have at least 1 entry per input constraint. + \param [in,out] articulations The array of articulations that the constraints reference. Some fields in these structures are written to as scratch memory for the batching. + \param [in] nbArticulations The number of articulations + \return The total number of batches produced. This should be less than or equal to nbConstraints. + + \note This method considers all bodies within the range [0, nbBodies-1] to be valid dynamic bodies. A given dynamic body can only be referenced in a batch once. Static or kinematic bodies can be + referenced multiple times within a batch safely because constraints do not affect their velocities. The batching will implicitly consider any bodies outside of the range [0, nbBodies-1] to be + infinite mass (static or kinematic). This means that either appending static/kinematic to the end of the array of bodies or placing static/kinematic bodies at before the start body pointer + will ensure that the minimum number of batches are produced. + */ + PX_C_EXPORT PX_PHYSX_CORE_API PxU32 PxBatchConstraints( const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxSolverBody* solverBodies, PxU32 nbBodies, + PxConstraintBatchHeader* outBatchHeaders, PxSolverConstraintDesc* outOrderedConstraintDescs, + PxArticulationHandle* articulations=NULL, PxU32 nbArticulations=0); + + /** + \brief Creates a set of contact constraint blocks. Note that, depending the results of PxBatchConstraints, each batchHeader may refer to up to 4 solverConstraintDescs. + This function will allocate both constraint and friction patch data via the PxConstraintAllocator provided. Constraint data is only valid until PxSolveConstraints has completed. + Friction data is to be retained and provided by the application for friction correlation. + + \param [in] batchHeaders Array of batch headers to process + \param [in] nbHeaders The total number of headers + \param [in] contactDescs An array of contact descs defining the pair and contact properties of each respective contacting pair + \param [in] allocator An allocator callback to allocate constraint and friction memory + \param [in] invDt The inverse timestep + \param [in] bounceThreshold The bounce threshold. Relative velocities below this will be solved by bias only. Relative velocities above this will be solved by restitution. If restitution is zero + then these pairs will always be solved by bias. + \param [in] frictionOffsetThreshold The friction offset threshold. Contacts whose separations are below this threshold can generate friction constraints. + \param [in] correlationDistance The correlation distance used by friction correlation to identify whether a friction patch is broken on the grounds of relation separation. + \param [out] Z Temporary buffer for impulse propagation. + + \return a boolean to define if this method was successful or not. + */ + PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateContactConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverContactDesc* contactDescs, + PxConstraintAllocator& allocator, PxReal invDt, PxReal bounceThreshold, PxReal frictionOffsetThreshold, PxReal correlationDistance, + PxSpatialVector* Z = NULL); + + /** + \brief Creates a set of joint constraint blocks. Note that, depending the results of PxBatchConstraints, the batchHeader may refer to up to 4 solverConstraintDescs + \param [in] batchHeaders The array of batch headers to be processed. + \param [in] nbHeaders The total number of batch headers to process. + \param [in] jointDescs An array of constraint prep descs defining the properties of the constraints being created. + \param [in] allocator An allocator callback to allocate constraint data. + \param [in] dt The timestep. + \param [in] invDt The inverse timestep. + \param [out] Z Deprecated, no longer used. Any value (including NULL) can be passed. + \return a boolean indicating if this method was successful or not. + */ + PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverConstraintPrepDesc* jointDescs, + PxConstraintAllocator& allocator, PxSpatialVector* Z, PxReal dt, PxReal invDt); + + /** + \brief Creates a set of joint constraint blocks. This function runs joint shaders defined inside PxConstraint** param, fills in joint row information in jointDescs and then calls PxCreateJointConstraints. + \param [in] batchHeaders The set of batchHeaders to be processed. + \param [in] nbBatchHeaders The number of batch headers to process. + \param [in] constraints The set of constraints to be used to produce constraint rows. + \param [in,out] jointDescs An array of constraint prep descs defining the properties of the constraints being created. + \param [in] allocator An allocator callback to allocate constraint data. + \param [in] dt The timestep. + \param [in] invDt The inverse timestep. + \param [out] Z Temporary buffer for impulse propagation. + \return a boolean indicating if this method was successful or not. + \see PxCreateJointConstraints + */ + PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraintsWithShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, PxConstraint** constraints, PxSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z = NULL); + + struct PxImmediateConstraint + { + PxConstraintSolverPrep prep; + const void* constantBlock; + }; + + /** + \brief Creates a set of joint constraint blocks. This function runs joint shaders defined inside PxImmediateConstraint* param, fills in joint row information in jointDescs and then calls PxCreateJointConstraints. + \param [in] batchHeaders The set of batchHeaders to be processed. + \param [in] nbBatchHeaders The number of batch headers to process. + \param [in] constraints The set of constraints to be used to produce constraint rows. + \param [in,out] jointDescs An array of constraint prep descs defining the properties of the constraints being created. + \param [in] allocator An allocator callback to allocate constraint data. + \param [in] dt The timestep. + \param [in] invDt The inverse timestep. + \param [out] Z Temporary buffer for impulse propagation. + \return a boolean indicating if this method was successful or not. + \see PxCreateJointConstraints + */ + PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraintsWithImmediateShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, PxImmediateConstraint* constraints, PxSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z = NULL); + + /** + \brief Iteratively solves the set of constraints defined by the provided PxConstraintBatchHeader and PxSolverConstraintDesc structures. Updates deltaVelocities inside the PxSolverBody structures. Produces resulting linear and angular motion velocities. + \param [in] batchHeaders The set of batch headers to be solved + \param [in] nbBatchHeaders The total number of batch headers to be solved + \param [in] solverConstraintDescs The reordererd set of solver constraint descs referenced by the batch headers + \param [in,out] solverBodies The set of solver bodies the bodies reference + \param [out] linearMotionVelocity The resulting linear motion velocity + \param [out] angularMotionVelocity The resulting angular motion velocity. + \param [in] nbSolverBodies The total number of solver bodies + \param [in] nbPositionIterations The number of position iterations to run + \param [in] nbVelocityIterations The number of velocity iterations to run + \param [in] dt Timestep. Only needed if articulations are sent to the function. + \param [in] invDt Inverse timestep. Only needed if articulations are sent to the function. + \param [in] nbSolverArticulations Number of articulations to solve constraints for. + \param [in] solverArticulations Array of articulations to solve constraints for. + \param [out] Z Deprecated, no longer used. Any value (including NULL) can be passed. + \param [out] deltaV Temporary buffer for velocity change + */ + PX_C_EXPORT PX_PHYSX_CORE_API void PxSolveConstraints(const PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, const PxSolverConstraintDesc* solverConstraintDescs, + const PxSolverBody* solverBodies, PxVec3* linearMotionVelocity, PxVec3* angularMotionVelocity, PxU32 nbSolverBodies, PxU32 nbPositionIterations, PxU32 nbVelocityIterations, + float dt=0.0f, float invDt=0.0f, PxU32 nbSolverArticulations=0, PxArticulationHandle* solverArticulations=NULL, PxSpatialVector* Z = NULL, PxSpatialVector* deltaV = NULL); + + /** + \brief Integrates a rigid body, returning the new velocities and transforms. After this function has been called, solverBodyData stores all the body's velocity data. + + \param [in,out] solverBodyData The array of solver body data to be integrated + \param [in,out] solverBody The bodies' linear and angular velocities + \param [in,out] linearMotionVelocity The bodies' linear motion velocity array + \param [in,out] angularMotionState The bodies' angular motion velocity array + \param [in] nbBodiesToIntegrate The total number of bodies to integrate + \param [in] dt The timestep + */ + PX_C_EXPORT PX_PHYSX_CORE_API void PxIntegrateSolverBodies(PxSolverBodyData* solverBodyData, PxSolverBody* solverBody, PxVec3* linearMotionVelocity, PxVec3* angularMotionState, PxU32 nbBodiesToIntegrate, PxReal dt); + + /** + \brief Performs contact generation for a given pair of geometries at the specified poses. Produced contacts are stored in the provided contact recorder. Information is cached in PxCache structure + to accelerate future contact generation between pairs. This cache data is valid only as long as the memory provided by PxCacheAllocator has not been released/re-used. Recommendation is to + retain that data for a single simulation frame, discarding cached data after 2 frames. If the cached memory has been released/re-used prior to the corresponding pair having contact generation + performed again, it is the application's responsibility to reset the PxCache. + + \param [in] geom0 Array of geometries to perform collision detection on. + \param [in] geom1 Array of geometries to perform collision detection on + \param [in] pose0 Array of poses associated with the corresponding entry in the geom0 array + \param [in] pose1 Array of poses associated with the corresponding entry in the geom1 array + \param [in,out] contactCache Array of contact caches associated with each pair geom0[i] + geom1[i] + \param [in] nbPairs The total number of pairs to process + \param [out] contactRecorder A callback that is called to record contacts for each pair that detects contacts + \param [in] contactDistance The distance at which contacts begin to be generated between the pairs + \param [in] meshContactMargin The mesh contact margin. + \param [in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units + \param [in] allocator A callback to allocate memory for the contact cache + + \return a boolean indicating if the function was successful or not. + */ + PX_C_EXPORT PX_PHYSX_CORE_API bool PxGenerateContacts( const PxGeometry* const * geom0, const PxGeometry* const * geom1, const PxTransform* pose0, const PxTransform* pose1, + PxCache* contactCache, PxU32 nbPairs, PxContactRecorder& contactRecorder, + PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength, PxCacheAllocator& allocator); + + struct PxArticulationJointDataRC + { + PxTransform parentPose; + PxTransform childPose; + PxArticulationMotion::Enum motion[PxArticulationAxis::eCOUNT]; + PxArticulationLimit limits[PxArticulationAxis::eCOUNT]; + PxArticulationDrive drives[PxArticulationAxis::eCOUNT]; + PxReal targetPos[PxArticulationAxis::eCOUNT]; + PxReal targetVel[PxArticulationAxis::eCOUNT]; + PxReal armature[PxArticulationAxis::eCOUNT]; + PxReal jointPos[PxArticulationAxis::eCOUNT]; + PxReal jointVel[PxArticulationAxis::eCOUNT]; + PxReal frictionCoefficient; + PxReal maxJointVelocity[PxArticulationAxis::eCOUNT]; + PxArticulationJointType::Enum type; + + void initData() + { + parentPose = PxTransform(PxIdentity); + childPose = PxTransform(PxIdentity); + frictionCoefficient = 0.05f; + type = PxArticulationJointType::eUNDEFINED; // For root + + for(PxU32 i=0;iRange: [0, 31] + \param[in] operation The operation the modified smoothing will perform + */ + PX_INLINE void setGridFilteringPass(PxU32 passIndex, PxIsosurfaceGridFilteringType::Enum operation) + { + PX_ASSERT(passIndex < 32u); + PxU32 shift = passIndex * 2; + gridFilteringFlags &= ~(PxU64(3) << shift); + gridFilteringFlags |= PxU64(operation) << shift; + } + + /** + \brief Returns the operation of a smoothing pass + + \param[in] passIndex The index of the smoothing pass whose operation is requested Range: [0, 31] + \param[out] operation The operation the requested smoothing pass will perform + \return true if the requested pass performs an operation + */ + PX_INLINE bool getGridFilteringPass(PxU32 passIndex, PxIsosurfaceGridFilteringType::Enum& operation) const + { + PxU32 shift = passIndex * 2; + PxU64 v = gridFilteringFlags >> shift; + v &= 3; //Extract last 2 bits + operation = PxIsosurfaceGridFilteringType::Enum(v); + return operation != PxIsosurfaceGridFilteringType::eNONE; + } + + PxReal particleCenterToIsosurfaceDistance; //!< Distance form a particle center to the isosurface + PxU32 numMeshSmoothingPasses; //!< Number of Taubin mesh postprocessing smoothing passes. Using an even number of passes lead to less shrinking. + PxU32 numMeshNormalSmoothingPasses; //!< Number of mesh normal postprocessing smoothing passes. + PxU64 gridFilteringFlags; //!< Encodes the smoothing steps to apply on the sparse grid. Use setGridSmoothingPass method to set up. + PxReal gridSmoothingRadius; //!< Gaussian blur smoothing kernel radius used for smoothing operations on the grid + }; + + /** + \brief Base class for isosurface extractors. Allows to register the data arrays for the isosurface and to obtain the number vertices/triangles in use. + */ + class PxIsosurfaceExtractor + { + public: + /** + \brief Returns the isosurface parameters. + + \return The isosurfacesettings used for the isosurface extraction + */ + virtual PxIsosurfaceParams getIsosurfaceParams() const = 0; + + /** + \brief Set the isosurface extraction parameters + + Allows to configure the isosurface extraction by controlling threshold value, smoothing options etc. + + \param[in] params A collection of settings to control the isosurface extraction + */ + virtual void setIsosurfaceParams(const PxIsosurfaceParams& params) = 0; + + /** + \brief Returns the number of vertices that the current isosurface triangle mesh uses + + \return The number of vertices currently in use + */ + virtual PxU32 getNumVertices() const = 0; + + /** + \brief Returns the number of triangles that the current isosurface triangle mesh uses + + \return The number of triangles currently in use + */ + virtual PxU32 getNumTriangles() const = 0; + + /** + \brief Returns the maximum number of vertices that the isosurface triangle mesh can contain + + \return The maximum number of vertices that can be genrated + */ + virtual PxU32 getMaxVertices() const = 0; + + /** + \brief Returns the maximum number of triangles that the isosurface triangle mesh can contain + + \return The maximum number of triangles that can be generated + */ + virtual PxU32 getMaxTriangles() const = 0; + + /** + \brief Resizes the internal triangle mesh buffers. + + If the output buffers are device buffers, nothing will get resized but new output buffers can be set using setResultBufferDevice. + For host side output buffers, temporary buffers will get resized. The new host side result buffers with the same size must be set using setResultBufferHost. + + \param[in] maxNumVertices The maximum number of vertices the output buffer can hold + \param[in] maxNumTriangles The maximum number of triangles the ouput buffer can hold + */ + virtual void setMaxVerticesAndTriangles(PxU32 maxNumVertices, PxU32 maxNumTriangles) = 0; + + /** + \brief The maximal number of particles the isosurface extractor can process + + \return The maximal number of particles + */ + virtual PxU32 getMaxParticles() const = 0; + + /** + \brief Sets the maximal number of particles the isosurface extractor can process + + \param[in] maxParticles The maximal number of particles + */ + virtual void setMaxParticles(PxU32 maxParticles) = 0; + + /** + \brief Releases the isosurface extractor instance and its data + */ + virtual void release() = 0; + + /** + \brief Triggers the compuation of a new isosurface based on the specified particle locations + + \param[in] deviceParticlePos A gpu pointer pointing to the start of the particle array + \param[in] numParticles The number of particles + \param[in] stream The stream on which all the gpu work will be performed + \param[in] phases A phase value per particle + \param[in] validPhaseMask A mask that specifies which phases should contribute to the isosurface. If the binary and operation + between this mask and the particle phase is non zero, then the particle will contribute to the isosurface + \param[in] activeIndices Optional array with indices of all active particles + \param[in] anisotropy1 Optional anisotropy information, x axis direction (xyz) and scale in w component + \param[in] anisotropy2 Optional anisotropy information, y axis direction (xyz) and scale in w component + \param[in] anisotropy3 Optional anisotropy information, z axis direction (xyz) and scale in w component + \param[in] anisotropyFactor A factor to multiply with the anisotropy scale + */ + virtual void extractIsosurface(PxVec4* deviceParticlePos, const PxU32 numParticles, CUstream stream, PxU32* phases = NULL, PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid, + PxU32* activeIndices = NULL, PxVec4* anisotropy1 = NULL, PxVec4* anisotropy2 = NULL, PxVec4* anisotropy3 = NULL, PxReal anisotropyFactor = 1.0f) = 0; + + /** + \brief Allows to register the host buffers into which the final isosurface triangle mesh will get stored + + \param[in] vertices A host buffer to store the vertices of the isosurface mesh + \param[in] triIndices A host buffer to store the triangles of the isosurface mesh + \param[in] normals A host buffer to store the normals of the isosurface mesh + */ + virtual void setResultBufferHost(PxVec4* vertices, PxU32* triIndices, PxVec4* normals = NULL) = 0; + + /** + \brief Allows to register the host buffers into which the final isosurface triangle mesh will get stored + + \param[in] vertices A device buffer to store the vertices of the isosurface mesh + \param[in] triIndices A device buffer to store the triangles of the isosurface mesh + \param[in] normals A device buffer to store the normals of the isosurface mesh + */ + virtual void setResultBufferDevice(PxVec4* vertices, PxU32* triIndices, PxVec4* normals) = 0; + + /** + \brief Enables or disables the isosurface extractor + + \param[in] enabled The boolean to set the extractor to enabled or disabled + */ + virtual void setEnabled(bool enabled) = 0; + + /** + \brief Allows to query if the isosurface extractor is enabled + + \return True if enabled, false otherwise + */ + virtual bool isEnabled() const = 0; + + /** + \brief Destructor + */ + virtual ~PxIsosurfaceExtractor() {} + }; + + /** + \brief Base class for sparse grid based isosurface extractors. Allows to register the data arrays for the isosurface and to obtain the number vertices/triangles in use. + */ + class PxSparseGridIsosurfaceExtractor : public PxIsosurfaceExtractor + { + /** + \brief Returns the sparse grid parameters. + + \return The sparse grid settings used for the isosurface extraction + */ + virtual PxSparseGridParams getSparseGridParams() const = 0; + + /** + \brief Set the sparse grid parameters + + Allows to configure cell size, number of subgrids etc. + + \param[in] params A collection of settings to control the isosurface grid + */ + virtual void setSparseGridParams(const PxSparseGridParams& params) = 0; + }; + + /** + \brief Default implementation of a particle system callback to trigger the isosurface extraction. A call to fetchResultsParticleSystem() on the + PxScene will synchronize the work such that the caller knows that the post solve task completed. + */ + class PxIsosurfaceCallback : public PxParticleSystemCallback + { + public: + /** + \brief Initializes the isosurface callback + + \param[in] isosurfaceExtractor The isosurface extractor + \param[in] validPhaseMask The valid phase mask marking the phase bits that particles must have set in order to contribute to the isosurface + */ + void initialize(PxIsosurfaceExtractor* isosurfaceExtractor, PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid) + { + mIsosurfaceExtractor = isosurfaceExtractor; + mValidPhaseMask = validPhaseMask; + } + + virtual void onPostSolve(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) + { + mIsosurfaceExtractor->extractIsosurface(reinterpret_cast(gpuParticleSystem.mHostPtr->mUnsortedPositions_InvMass), + gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream, gpuParticleSystem.mHostPtr->mUnsortedPhaseArray, mValidPhaseMask); + } + + virtual void onBegin(const PxGpuMirroredPointer& /*gpuParticleSystem*/, CUstream /*stream*/) { } + + virtual void onAdvance(const PxGpuMirroredPointer& /*gpuParticleSystem*/, CUstream /*stream*/) { } + + private: + PxIsosurfaceExtractor* mIsosurfaceExtractor; + PxU32 mValidPhaseMask; + }; + +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxLockedData.h b/Jusin154_Team3D/Engine/Public/PhysX/PxLockedData.h new file mode 100644 index 000000000..c29e67bd4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxLockedData.h @@ -0,0 +1,87 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_LOCKED_DATA_H +#define PX_LOCKED_DATA_H + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxDataAccessFlag +{ + enum Enum + { + eREADABLE = (1 << 0), + eWRITABLE = (1 << 1), + eDEVICE = (1 << 2) + }; +}; + +/** +\brief collection of set bits defined in PxDataAccessFlag. + +\see PxDataAccessFlag +*/ +typedef PxFlags PxDataAccessFlags; +PX_FLAGS_OPERATORS(PxDataAccessFlag::Enum,PxU8) + + +/** +\brief Parent class for bulk data that is shared between the SDK and the application. +*/ +class PxLockedData +{ +public: + + /** + \brief Any combination of PxDataAccessFlag::eREADABLE and PxDataAccessFlag::eWRITABLE + \see PxDataAccessFlag + */ + virtual PxDataAccessFlags getDataAccessFlags() = 0; + + /** + \brief Unlocks the bulk data. + */ + virtual void unlock() = 0; + + /** + \brief virtual destructor + */ + virtual ~PxLockedData() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxMaterial.h new file mode 100644 index 000000000..b4d862519 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxMaterial.h @@ -0,0 +1,372 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MATERIAL_H +#define PX_MATERIAL_H + +#include "PxBaseMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxScene; + +/** +\brief Flags which control the behavior of a material. + +\see PxMaterial +*/ +struct PxMaterialFlag +{ + enum Enum + { + /** + \brief If this flag is set, friction computations are always skipped between shapes with this material and any other shape. + */ + eDISABLE_FRICTION = 1 << 0, + + /** + \brief Whether to use strong friction. + The difference between "normal" and "strong" friction is that the strong friction feature + remembers the "friction error" between simulation steps. The friction is a force trying to + hold objects in place (or slow them down) and this is handled in the solver. But since the + solver is only an approximation, the result of the friction calculation can include a small + "error" - e.g. a box resting on a slope should not move at all if the static friction is in + action, but could slowly glide down the slope because of a small friction error in each + simulation step. The strong friction counter-acts this by remembering the small error and + taking it to account during the next simulation step. + + However, in some cases the strong friction could cause problems, and this is why it is + possible to disable the strong friction feature by setting this flag. One example is + raycast vehicles that are sliding fast across the surface, but still need a precise + steering behavior. It may be a good idea to reenable the strong friction when objects + are coming to a rest, to prevent them from slowly creeping down inclines. + + Note: This flag only has an effect if the PxMaterialFlag::eDISABLE_FRICTION bit is 0. + */ + eDISABLE_STRONG_FRICTION = 1 << 1, + + /** + \brief If this flag is raised in combination with negative restitution, the computed spring-damper output will be interpreted as + acceleration instead of force targets, analog to acceleration spring constraints. + The flag has no effect for non-compliant contacts (i.e., if restitution is nonnegative). + In an interaction between a compliant-force and a compliant-acceleration body the latter will dominate. + \see PxMaterial.setRestitution, PxMaterial.setDamping + \see Px1DConstraintFlag.eACCELERATION_SPRING + */ + eCOMPLIANT_ACCELERATION_SPRING = 1 << 4 + }; +}; + +/** +\brief collection of set bits defined in PxMaterialFlag. + +\see PxMaterialFlag +*/ +typedef PxFlags PxMaterialFlags; +PX_FLAGS_OPERATORS(PxMaterialFlag::Enum,PxU16) + + +/** +\brief Enumeration that determines the way in which two material properties will be combined to yield a friction or restitution coefficient for a collision. + +When two actors come in contact with each other, they each have materials with various coefficients, but we only need a single set of coefficients for the pair. + +Physics doesn't have any inherent combinations because the coefficients are determined empirically on a case by case +basis. However, simulating this with a pairwise lookup table is often impractical. + +For this reason the following combine behaviors are available: + +eAVERAGE +eMIN +eMULTIPLY +eMAX + +The effective combine mode for the pair is maximum(material0.combineMode, material1.combineMode). + +Notes that the restitution coefficient is overloaded if it is negative and represents a spring stiffness for compliant contacts. In the compliant contact case, the following rules apply: + * If a compliant (restitution < 0) material interacts with a rigid (restitution >= 0) material, the compliant behavior will be chosen independent + of combine mode. In all other cases (i.e., also for compliant-compliant interactions) the combine mode is used. + * For a compliant-compliant interaction with eMULTIPLY combine mode, we multiply the values but keep the sign negative. + * The material damping follows the same logic, i.e., for the compliant vs non-compliant case, we take the damping value of the compliant material. Otherwise the combine mode is respected. + * In an interaction between a compliant-force and a compliant-acceleration body the latter will dominate and exclusively determine the collision behavior with its parameters. + +\see PxMaterial.setFrictionCombineMode() PxMaterial.getFrictionCombineMode() PxMaterial.setRestitutionCombineMode() PxMaterial.getFrictionCombineMode() +*/ +struct PxCombineMode +{ + enum Enum + { + eAVERAGE = 0, //!< Average: (a + b)/2 + eMIN = 1, //!< Minimum: minimum(a,b) + eMULTIPLY = 2, //!< Multiply: a*b + eMAX = 3, //!< Maximum: maximum(a,b) + eN_VALUES = 4, //!< This is not a valid combine mode, it is a sentinel to denote the number of possible values. We assert that the variable's value is smaller than this. + ePAD_32 = 0x7fffffff //!< This is not a valid combine mode, it is to assure that the size of the enum type is big enough. + }; +}; + +/** +\brief Material class to represent a set of surface properties. + +\see PxPhysics.createMaterial +*/ +class PxMaterial : public PxBaseMaterial +{ +public: + + /** + \brief Sets the coefficient of dynamic friction. + + The coefficient of dynamic friction should be in [0, PX_MAX_F32). If set to greater than staticFriction, the effective value of staticFriction will be increased to match. + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] coef Coefficient of dynamic friction. Range: [0, PX_MAX_F32) + + \see getDynamicFriction() + */ + virtual void setDynamicFriction(PxReal coef) = 0; + + /** + \brief Retrieves the DynamicFriction value. + + \return The coefficient of dynamic friction. + + \see setDynamicFriction + */ + virtual PxReal getDynamicFriction() const = 0; + + /** + \brief Sets the coefficient of static friction + + The coefficient of static friction should be in the range [0, PX_MAX_F32) + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] coef Coefficient of static friction. Range: [0, PX_MAX_F32) + + \see getStaticFriction() + */ + virtual void setStaticFriction(PxReal coef) = 0; + + /** + \brief Retrieves the coefficient of static friction. + \return The coefficient of static friction. + + \see setStaticFriction + */ + virtual PxReal getStaticFriction() const = 0; + + /** + \brief Sets the coefficient of restitution or the spring stiffness for compliant contact + + A coefficient of 0 makes the object bounce as little as possible, higher values up to 1.0 result in more bounce. + If a negative value is provided it is interpreted as stiffness term for an implicit spring + simulated at the contact site, with the spring positional error defined by + the contact separation value. Higher stiffness terms produce stiffer springs that behave more like a rigid contact. + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] rest Coefficient of restitution / negative spring stiffness Range: (-INF,1] + + \see getRestitution() setDamping() + */ + virtual void setRestitution(PxReal rest) = 0; + + /** + \brief Retrieves the coefficient of restitution. + + See #setRestitution. + + \return The coefficient of restitution. + + \see setRestitution() + */ + virtual PxReal getRestitution() const = 0; + + /** + \brief Sets the coefficient of damping + + This property only affects the simulation if compliant contact mode is enabled, i.e., a negative restitution value is set. + Damping works together with spring stiffness. Spring stiffness corrects positional error while + damping resists relative velocity. Setting a high damping coefficient can produce spongy contacts. + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] damping Coefficient of damping. Range: [0,INF) + + \see getDamping() + */ + virtual void setDamping(PxReal damping) = 0; + + /** + \brief Retrieves the coefficient of damping. + + See #setDamping. + + \return The coefficient of damping. + + \see setDamping() + */ + virtual PxReal getDamping() const = 0; + + /** + \brief Raises or clears a particular material flag. + + See the list of flags #PxMaterialFlag + + Default: No flag raised. + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] flag The PxMaterial flag to raise(set) or clear. + \param[in] b New state of the flag + + \see getFlags() setFlags() PxMaterialFlag + */ + virtual void setFlag(PxMaterialFlag::Enum flag, bool b) = 0; + + /** + \brief sets all the material flags. + + See the list of flags #PxMaterialFlag + + Default: No flag raised. + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] flags All PxMaterial flags + + \see getFlags() setFlag() PxMaterialFlag + */ + virtual void setFlags(PxMaterialFlags flags) = 0; + + /** + \brief Retrieves the flags. See #PxMaterialFlag. + + \return The material flags. + + \see PxMaterialFlag setFlags() + */ + virtual PxMaterialFlags getFlags() const = 0; + + /** + \brief Sets the friction combine mode. + + See the enum ::PxCombineMode . + + Default: PxCombineMode::eAVERAGE + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] combMode Friction combine mode to set for this material. See #PxCombineMode. + + \see PxCombineMode getFrictionCombineMode setStaticFriction() setDynamicFriction() + */ + virtual void setFrictionCombineMode(PxCombineMode::Enum combMode) = 0; + + /** + \brief Retrieves the friction combine mode. + + See #setFrictionCombineMode. + + \return The friction combine mode for this material. + + \see PxCombineMode setFrictionCombineMode() + */ + virtual PxCombineMode::Enum getFrictionCombineMode() const = 0; + + /** + \brief Sets the restitution combine mode. + + See the enum ::PxCombineMode . + + Default: PxCombineMode::eAVERAGE + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] combMode Restitution combine mode for this material. See #PxCombineMode. + + \see PxCombineMode getRestitutionCombineMode() setRestitution() + */ + virtual void setRestitutionCombineMode(PxCombineMode::Enum combMode) = 0; + + /** + \brief Retrieves the restitution combine mode. + + See #setRestitutionCombineMode. + + \return The coefficient of restitution combine mode for this material. + + \see PxCombineMode setRestitutionCombineMode getRestitution() + */ + virtual PxCombineMode::Enum getRestitutionCombineMode() const = 0; + + /** + \brief Sets the damping combine mode. + + See the enum ::PxCombineMode . + + Default: PxCombineMode::eAVERAGE + + Sleeping: Does NOT wake any actors which may be affected. + + \param[in] combMode Damping combine mode for this material. See #PxCombineMode. + + \see PxCombineMode getDampingCombineMode() setDamping() + */ + virtual void setDampingCombineMode(PxCombineMode::Enum combMode) = 0; + + /** + \brief Retrieves the damping combine mode. + + \return The damping combine mode for this material. + + \see PxCombineMode setDampingCombineMode() getDamping() + */ + virtual PxCombineMode::Enum getDampingCombineMode() const = 0; + + // PxBase + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxMaterial"; } + //~PxBase + +protected: + PX_INLINE PxMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {} + PX_INLINE PxMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {} + virtual ~PxMaterial() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxMaterial", PxBaseMaterial); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxNodeIndex.h b/Jusin154_Team3D/Engine/Public/PhysX/PxNodeIndex.h new file mode 100644 index 000000000..c12cd3171 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxNodeIndex.h @@ -0,0 +1,102 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_NODEINDEX_H +#define PX_NODEINDEX_H + +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#define PX_INVALID_NODE 0xFFFFFFFFu + + /** + \brief PxNodeIndex + + Node index is the unique index for each actor referenced by the island gen. It contains details like + if the actor is an articulation or rigid body. If it is an articulation, the node index also contains + the link index of the rigid body within the articulation. Also, it contains information to detect whether + the rigid body is static body or not + */ + class PxNodeIndex + { + struct IDs + { + PxU32 mID; + PxU32 mLinkID; + }; + + union + { + IDs mIDs; + PxU64 mInd; + }; + + public: + + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id, PxU32 articLinkId) + { + setIndices(id, articLinkId); + } + + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id = PX_INVALID_NODE) + { + setIndices(id); + } + + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU64 ind) + { + mInd = ind; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 index() const { return mIDs.mID; } + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 articulationLinkId() const { return mIDs.mLinkID >> 1; } + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 isArticulation() const { return mIDs.mLinkID & 1; } + + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isStaticBody() const { return mIDs.mID == PX_INVALID_NODE; } + + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isValid() const { return mIDs.mID != PX_INVALID_NODE; } + + PX_CUDA_CALLABLE PX_FORCE_INLINE void setIndices(PxU32 index, PxU32 articLinkId) { mIDs.mID = index; mIDs.mLinkID = (articLinkId << 1) | 1; } + + PX_CUDA_CALLABLE PX_FORCE_INLINE void setIndices(PxU32 index) { mIDs.mID = index; mIDs.mLinkID = 0; } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU64 getInd() const { return mInd; } + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator < (const PxNodeIndex& other) const { return getInd() < other.getInd(); } + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator <= (const PxNodeIndex& other) const { return getInd() <= other.getInd(); } + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator == (const PxNodeIndex& other) const { return getInd() == other.getInd(); } + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxPBDMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxPBDMaterial.h new file mode 100644 index 000000000..f642e51f8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxPBDMaterial.h @@ -0,0 +1,318 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PBD_MATERIAL_H +#define PX_PBD_MATERIAL_H + +#include "PxBaseMaterial.h" +#include "PxParticleMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxScene; + /** + \brief Material class to represent a set of PBD particle material properties. + + \see #PxPhysics.createPBDMaterial + */ + class PxPBDMaterial : public PxBaseMaterial + { + public: + + /** + \brief Sets friction + + \param[in] friction Friction. Range: [0, PX_MAX_F32) + + \see #getFriction() + */ + virtual void setFriction(PxReal friction) = 0; + + /** + \brief Retrieves the friction value. + + \return The friction value. + + \see #setFriction() + */ + virtual PxReal getFriction() const = 0; + + /** + \brief Sets velocity damping term + + \param[in] damping Velocity damping term. Range: [0, PX_MAX_F32) + + \see #getDamping + */ + virtual void setDamping(PxReal damping) = 0; + + /** + \brief Retrieves the velocity damping term + \return The velocity damping term. + + \see #setDamping() + */ + virtual PxReal getDamping() const = 0; + + /** + \brief Sets adhesion term + + \param[in] adhesion adhesion coefficient. Range: [0, PX_MAX_F32) + + \see #getAdhesion + */ + virtual void setAdhesion(PxReal adhesion) = 0; + + /** + \brief Retrieves the adhesion term + \return The adhesion term. + + \see #setAdhesion() + */ + virtual PxReal getAdhesion() const = 0; + + /** + \brief Sets gravity scale term + + \param[in] scale gravity scale coefficient. Range: (-PX_MAX_F32, PX_MAX_F32) + + \see #getAdhesion + */ + virtual void setGravityScale(PxReal scale) = 0; + + /** + \brief Retrieves the gravity scale term + \return The gravity scale term. + + \see #setAdhesion() + */ + virtual PxReal getGravityScale() const = 0; + + /** + \brief Sets material adhesion radius scale. This is multiplied by the particle rest offset to compute the fall-off distance + at which point adhesion ceases to operate. + + \param[in] scale Material adhesion radius scale. Range: [0, PX_MAX_F32) + + \see #getAdhesionRadiusScale + */ + virtual void setAdhesionRadiusScale(PxReal scale) = 0; + + /** + \brief Retrieves the adhesion radius scale. + \return The adhesion radius scale. + + \see #setAdhesionRadiusScale() + */ + virtual PxReal getAdhesionRadiusScale() const = 0; + + /** + \brief Sets viscosity + + \param[in] viscosity Viscosity. Range: [0, PX_MAX_F32) + + \see #getViscosity() + */ + virtual void setViscosity(PxReal viscosity) = 0; + + /** + \brief Retrieves the viscosity value. + + \return The viscosity value. + + \see #setViscosity() + */ + virtual PxReal getViscosity() const = 0; + + /** + \brief Sets material vorticity confinement coefficient + + \param[in] vorticityConfinement Material vorticity confinement coefficient. Range: [0, PX_MAX_F32) + + \see #getVorticityConfinement() + */ + virtual void setVorticityConfinement(PxReal vorticityConfinement) = 0; + + /** + \brief Retrieves the vorticity confinement coefficient. + \return The vorticity confinement coefficient. + + \see #setVorticityConfinement() + */ + virtual PxReal getVorticityConfinement() const = 0; + + /** + \brief Sets material surface tension coefficient + + \param[in] surfaceTension Material surface tension coefficient. Range: [0, PX_MAX_F32) + + \see #getSurfaceTension() + */ + virtual void setSurfaceTension(PxReal surfaceTension) = 0; + + /** + \brief Retrieves the surface tension coefficient. + \return The surface tension coefficient. + + \see #setSurfaceTension() + */ + virtual PxReal getSurfaceTension() const = 0; + + /** + \brief Sets material cohesion coefficient + + \param[in] cohesion Material cohesion coefficient. Range: [0, PX_MAX_F32) + + \see #getCohesion() + */ + virtual void setCohesion(PxReal cohesion) = 0; + + /** + \brief Retrieves the cohesion coefficient. + \return The cohesion coefficient. + + \see #setCohesion() + */ + virtual PxReal getCohesion() const = 0; + + /** + \brief Sets material lift coefficient + + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + \param[in] lift Material lift coefficient. Range: [0, PX_MAX_F32) + + \see #getLift() + */ + PX_DEPRECATED virtual void setLift(PxReal lift) = 0; + + /** + \brief Retrieves the lift coefficient. + + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + \return The lift coefficient. + + \see #setLift() + */ + PX_DEPRECATED virtual PxReal getLift() const = 0; + + /** + \brief Sets material drag coefficient + + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + \param[in] drag Material drag coefficient. Range: [0, PX_MAX_F32) + + \see #getDrag() + */ + PX_DEPRECATED virtual void setDrag(PxReal drag) = 0; + + /** + \brief Retrieves the drag coefficient. + + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + \return The drag coefficient. + + \see #setDrag() + */ + PX_DEPRECATED virtual PxReal getDrag() const = 0; + + /** + \brief Sets the CFL coefficient. Limits the relative motion between two approaching fluid particles. + + The distance to which the motion is clamped is defined by CFLcoefficient*particleContactOffset*2. + A value of 0.5 will thus limit the appoaching motion to a distance of particleContactOffset. + A value much larger than one will typically not limit the motion of the particles. + + \param[in] coefficient CFL coefficient. Range: [0, PX_MAX_F32), Default: 1.0 + + \see #getCFLCoefficient() + */ + virtual void setCFLCoefficient(PxReal coefficient) = 0; + + /** + \brief Retrieves the CFL coefficient. + \return The CFL coefficient. + + \see #setCFLCoefficient() + */ + virtual PxReal getCFLCoefficient() const = 0; + + /** + \brief Sets material particle friction scale. This allows the application to scale up/down the frictional effect between particles independent of the friction + coefficient, which also defines frictional behavior between the particle and rigid bodies/soft bodies/cloth etc. + + \param[in] scale particle friction scale. Range: [0, PX_MAX_F32) + + \see #getParticleFrictionScale() + */ + virtual void setParticleFrictionScale(PxReal scale) = 0; + + /** + \brief Retrieves the particle friction scale. + \return The particle friction scale. + + \see #setParticleFrictionScale() + */ + virtual PxReal getParticleFrictionScale() const = 0; + + /** + \brief Sets material particle adhesion scale value. This is the adhesive value between particles defined as a scaled multiple of the adhesion parameter. + + \param[in] adhesion particle adhesion scale value. Range: [0, PX_MAX_F32) + + \see #getParticleAdhesionScale() + */ + virtual void setParticleAdhesionScale(PxReal adhesion) = 0; + + /** + \brief Retrieves the particle adhesion scale value. + \return The particle adhesion scale value. + + \see #setParticleAdhesionScale() + */ + virtual PxReal getParticleAdhesionScale() const = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxPBDMaterial"; } + + protected: + PX_INLINE PxPBDMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {} + PX_INLINE PxPBDMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {} + virtual ~PxPBDMaterial() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxPBDMaterial", PxBaseMaterial); } + }; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxPBDParticleSystem.h b/Jusin154_Team3D/Engine/Public/PhysX/PxPBDParticleSystem.h new file mode 100644 index 000000000..7e653422a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxPBDParticleSystem.h @@ -0,0 +1,652 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PBD_PARTICLE_SYSTEM_H +#define PX_PBD_PARTICLE_SYSTEM_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec3.h" +#include "foundation/PxArray.h" +#include "cudamanager/PxCudaTypes.h" +#include "PxParticleSystemFlag.h" +#include "PxFiltering.h" +#include "PxActor.h" +#include "PxParticleSystem.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + +class PxCudaContextManager; +class PxGpuParticleSystem; + +class PxParticleAndDiffuseBuffer; +class PxParticleBuffer; + +/** +\brief Container to hold a pair of corresponding device and host pointers. These pointers should point to GPU / CPU mirrors of the same data, but +this is not enforced. +*/ +template +struct PxGpuMirroredPointer +{ + Type* mDevicePtr; + Type* mHostPtr; + + PxGpuMirroredPointer(Type* devicePtr, Type* hostPtr) : mDevicePtr(devicePtr), mHostPtr(hostPtr) { } +}; + +/** +\brief Particle system callback base class to schedule work that should be done before, while or after the particle system updates. +A call to fetchResultsParticleSystem() on the PxScene will synchronize the work such that the caller knows that all tasks of this callback completed. +*/ +class PxParticleSystemCallback +{ +public: + /** + \brief Method gets called when dirty data from the particle system is uploated to the gpu + + \param[in] gpuParticleSystem Pointers to the particle systems gpu data available as host accessible pointer and as gpu accessible pointer + \param[in] stream The stream on which all cuda kernel calls get scheduled for execution. A call to fetchResultsParticleSystem() on the + PxScene will synchronize the work such that the caller knows that the task completed. + */ + virtual void onBegin(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) = 0; + + /** + \brief Method gets called when the simulation step of the particle system is performed + + \param[in] gpuParticleSystem Pointers to the particle systems gpu data available as host accessible pointer and as gpu accessible pointer + \param[in] stream The stream on which all cuda kernel calls get scheduled for execution. A call to fetchResultsParticleSystem() on the + PxScene will synchronize the work such that the caller knows that the task completed. + */ + virtual void onAdvance(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) = 0; + + /** + \brief Method gets called after the particle system simulation step completed + + \param[in] gpuParticleSystem Pointers to the particle systems gpu data available as host accessible pointer and as gpu accessible pointer + \param[in] stream The stream on which all cuda kernel calls get scheduled for execution. A call to fetchResultsParticleSystem() on the + PxScene will synchronize the work such that the caller knows that the task completed. + */ + virtual void onPostSolve(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) = 0; + + /** + \brief Destructor + */ + virtual ~PxParticleSystemCallback() {} +}; + +/** +\brief Special callback that forwards calls to arbitrarily many sub-callbacks +*/ +class PxMultiCallback : public PxParticleSystemCallback +{ +private: + PxArray mCallbacks; + +public: + PxMultiCallback() : mCallbacks(0) {} + + virtual void onPostSolve(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) PX_OVERRIDE + { + for (PxU32 i = 0; i < mCallbacks.size(); ++i) + mCallbacks[i]->onPostSolve(gpuParticleSystem, stream); + } + + virtual void onBegin(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) PX_OVERRIDE + { + for (PxU32 i = 0; i < mCallbacks.size(); ++i) + mCallbacks[i]->onBegin(gpuParticleSystem, stream); + } + + virtual void onAdvance(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) PX_OVERRIDE + { + for (PxU32 i = 0; i < mCallbacks.size(); ++i) + mCallbacks[i]->onAdvance(gpuParticleSystem, stream); + } + + /** + \brief Adds a callback + + \param[in] callback The callback to add + \return True if the callback was added + */ + bool addCallback(PxParticleSystemCallback* callback) + { + if (mCallbacks.find(callback) != mCallbacks.end()) + return false; + mCallbacks.pushBack(callback); + return true; + } + + /** + \brief Removes a callback + + \param[in] callback The callback to remove + \return True if the callback was removed + */ + bool removeCallback(const PxParticleSystemCallback* callback) + { + for (PxU32 i = 0; i < mCallbacks.size(); ++i) + { + if (mCallbacks[i] == callback) + { + mCallbacks.remove(i); + return true; + } + } + return false; + } +}; + +/** +\brief Flags which control the behaviour of a particle system. + +See #PxPBDParticleSystem::setParticleFlag(), #PxPBDParticleSystem::setParticleFlags(), #PxPBDParticleSystem::getParticleFlags() +*/ +struct PxParticleFlag +{ + enum Enum + { + eDISABLE_SELF_COLLISION = 1 << 0, //!< Disables particle self-collision + eDISABLE_RIGID_COLLISION = 1 << 1, //!< Disables particle-rigid body collision + eFULL_DIFFUSE_ADVECTION = 1 << 2, //!< Enables full advection of diffuse particles. By default, diffuse particles are advected only by particles in the cell they are contained. This flag enables full neighbourhood generation (more expensive). + eENABLE_SPECULATIVE_CCD = 1 << 3 //!< Enables speculative CCD for particle-rigid body collision. \see PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD. + }; +}; + +typedef PxFlags PxParticleFlags; + +/** +\brief Collection of flags providing a mechanism to lock motion along a specific axis. + +\see PxParticleSystem.setParticleLockFlag(), PxParticleSystem.getParticleLockFlags() +*/ +struct PxParticleLockFlag +{ + enum Enum + { + eLOCK_X = (1 << 0), + eLOCK_Y = (1 << 1), + eLOCK_Z = (1 << 2) + }; +}; + +typedef PxFlags PxParticleLockFlags; +PX_FLAGS_OPERATORS(PxParticleLockFlag::Enum, PxU8) + +/** +\brief A particle system that uses the position based dynamics(PBD) solver. + +The position based dynamics solver for particle systems supports behaviors like +fluid, cloth, inflatables etc. + +*/ +class PxPBDParticleSystem : public PxActor +{ +public: + + virtual ~PxPBDParticleSystem() {} + + /** + \brief Sets the solver iteration counts for the body. + + The solver iteration count determines how accurately joints and contacts are resolved. + If you are having trouble with jointed bodies oscillating and behaving erratically, then + setting a higher position iteration count may improve their stability. + + If intersecting bodies are being depenetrated too violently, increase the number of velocity + iterations. More velocity iterations will drive the relative exit velocity of the intersecting + objects closer to the correct value given the restitution. + + Default: 4 position iterations, 1 velocity iteration + + \param[in] minPositionIters Number of position iterations the solver should perform for this body. Range: [1,255] + \param[in] minVelocityIters Number of velocity iterations the solver should perform for this body. Range: [1,255] + + See #getSolverIterationCounts() + */ + virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0; + + /** + \brief Retrieves the solver iteration counts. + + See #setSolverIterationCounts() + */ + virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0; + + /** + \brief Retrieves the collision filter settings. + + \return The filter data + */ + virtual PxFilterData getSimulationFilterData() const = 0; + + /** + \brief Set collision filter settings + + Allows to control with which objects the particle system collides + + \param[in] data The filter data + */ + virtual void setSimulationFilterData(const PxFilterData& data) = 0; + + /** + \brief Set particle flag + + Allows to control self collision etc. + + \param[in] flag The flag to set + \param[in] val The new value of the flag + */ + virtual void setParticleFlag(PxParticleFlag::Enum flag, bool val) = 0; + + /** + \brief Set particle flags + + Allows to control self collision etc. + + \param[in] flags The flags to set + */ + virtual void setParticleFlags(PxParticleFlags flags) = 0; + + /** + \brief Retrieves the particle flags. + + \return The particle flags + */ + virtual PxParticleFlags getParticleFlags() const = 0; + + /** + \brief Set the maximal depenetration velocity particles can reach + + Allows to limit the particles' maximal depenetration velocity to avoid that collision responses lead to very high particle velocities + + \param[in] maxDepenetrationVelocity The maximal depenetration velocity + */ + virtual void setMaxDepenetrationVelocity(PxReal maxDepenetrationVelocity) = 0; + + /** + \brief Retrieves maximal depenetration velocity a particle can have. + + \return The maximal depenetration velocity + */ + virtual PxReal getMaxDepenetrationVelocity() const = 0; + + /** + \brief Set the maximal velocity particles can reach + + Allows to limit the particles' maximal velocity to control the maximal distance a particle can move per frame + + \param[in] maxVelocity The maximal velocity + */ + virtual void setMaxVelocity(PxReal maxVelocity) = 0; + + /** + \brief Retrieves maximal velocity a particle can have. + + \return The maximal velocity + */ + virtual PxReal getMaxVelocity() const = 0; + + + /** + \brief Return the cuda context manager + + \return The cuda context manager + */ + virtual PxCudaContextManager* getCudaContextManager() const = 0; + + /** + \brief Set the rest offset for the collision between particles and rigids or deformable bodies. + + A particle and a rigid or deformable body will come to rest at a distance equal to the sum of their restOffset values. + + \param[in] restOffset Range: (0, contactOffset) + */ + virtual void setRestOffset(PxReal restOffset) = 0; + + /** + \brief Return the rest offset + \return the rest offset + + See #setRestOffset() + */ + virtual PxReal getRestOffset() const = 0; + + /** + \brief Set the contact offset for the collision between particles and rigids or soft bodies + + The contact offset needs to be larger than the rest offset. + Contact constraints are generated for a particle and a rigid or deformable below the distance equal to the sum of their contacOffset values. + + \param[in] contactOffset Range: (restOffset, PX_MAX_F32) + */ + virtual void setContactOffset(PxReal contactOffset) = 0; + + /** + \brief Return the contact offset + \return the contact offset + + See #setContactOffset() + */ + virtual PxReal getContactOffset() const = 0; + + /** + \brief Set the contact offset for the interactions between particles + + The particle contact offset needs to be larger than the fluid rest offset and larger than the solid rest offset. + Interactions for two particles are computed if their distance is below twice the particleContactOffset value. + + \param[in] particleContactOffset Range: (Max(solidRestOffset, fluidRestOffset), PX_MAX_F32) + */ + virtual void setParticleContactOffset(PxReal particleContactOffset) = 0; + + /** + \brief Return the particle contact offset + \return the particle contact offset + + See #setParticleContactOffset() + */ + virtual PxReal getParticleContactOffset() const = 0; + + /** + \brief Set the solid rest offset + + Two solid particles (or a solid and a fluid particle) will come to rest at a distance equal to twice the solidRestOffset value. + + \param[in] solidRestOffset Range: (0, particleContactOffset) + */ + virtual void setSolidRestOffset(PxReal solidRestOffset) = 0; + + /** + \brief Return the solid rest offset + \return the solid rest offset + + See #setSolidRestOffset() + */ + virtual PxReal getSolidRestOffset() const = 0; + + + /** + \brief Creates a rigid attachment between a particle and a rigid actor. + + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + This method creates a symbolic attachment between the particle system and a rigid body for the purpose of island management. + The actual attachments will be contained in the particle buffers. + + Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash. + The particle system keeps track of these attachments but the rigid body does not. + + \param[in] actor The rigid actor used for the attachment + */ + PX_DEPRECATED virtual void addRigidAttachment(PxRigidActor* actor) = 0; + + /** + \brief Removes a rigid attachment between a particle and a rigid body. + + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + This method destroys a symbolic attachment between the particle system and a rigid body for the purpose of island management. + + Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash. + The particle system keeps track of these attachments but the rigid body does not. + + \param[in] actor The rigid body actor used for the attachment + */ + PX_DEPRECATED virtual void removeRigidAttachment(PxRigidActor* actor) = 0; + + + /** + \brief Enable continuous collision detection for particles + + \deprecated Replaced by particle flag, \see PxParticleFlag::eENABLE_SPECULATIVE_CCD. + + \param[in] enable Boolean indicates whether continuous collision detection is enabled. + */ + PX_DEPRECATED virtual void enableCCD(bool enable) = 0; + + + /** + \brief Reads the particle lock flags. + + See the list of flags #PxParticleLockFlag + + \return The values of the particle lock flags. + + \see PxParticleLockFlag setParticleLockFlag() + */ + virtual PxParticleLockFlags getParticleLockFlags() const = 0; + + /** + \brief Raises or clears a particular particle lock flag. + + See the list of flags #PxParticleLockFlag + + Default: no flags are set + + + \param[in] flag The PxParticleLockFlag to raise(set) or clear. + \param[in] value The new boolean value for the flag. + + \see PxParticleLockFlag getParticleLockFlags() + */ + virtual void setParticleLockFlag(PxParticleLockFlag::Enum flag, bool value) = 0; + + /** + \brief Set all particle lock flags. + \see setParticleLockFlag() + */ + virtual void setParticleLockFlags(PxParticleLockFlags flags) = 0; + + + /** + \brief Creates combined particle flag with particle material and particle phase flags. + + \param[in] material A material instance to associate with the new particle group. + \param[in] flags The particle phase flags. + \return The combined particle group index and phase flags. + + See #PxParticlePhaseFlag + */ + virtual PxU32 createPhase(PxPBDMaterial* material, PxParticlePhaseFlags flags) = 0; + + + /** + \brief Returns number of particle materials referenced by particle phases + \return The number of particle materials + */ + virtual PxU32 getNbParticleMaterials() const = 0; + + /** + \brief Returns particle materials referenced by particle phases + \return The particle materials + */ + virtual PxU32 getParticleMaterials(PxPBDMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Sets a user notify object which receives special simulation events when they occur. + + \note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored. + \note A call to fetchResultsParticleSystem() on the PxScene will synchronize the work such that the caller knows that all worke done in the callback completed. + + \param[in] callback User notification callback. See PxSimulationEventCallback. + + See #PxParticleSystemCallback, #getParticleSystemCallback() + */ + virtual void setParticleSystemCallback(PxParticleSystemCallback* callback) = 0; + + /** + \brief Retrieves the simulationEventCallback pointer set with setSimulationEventCallback(). + \return The current user notify pointer. See PxSimulationEventCallback. + + See #PxParticleSystemCallback, #setParticleSystemCallback() + */ + virtual PxParticleSystemCallback* getParticleSystemCallback() const = 0; + + /** + \brief Add an existing particle buffer to the particle system. + \param[in] particleBuffer a PxParticleBuffer*. + + See #PxParticleBuffer. + */ + virtual void addParticleBuffer(PxParticleBuffer* particleBuffer) = 0; + + /** + \brief Remove particle buffer from the particle system. + \param[in] particleBuffer a PxParticleBuffer*. + + See #PxParticleBuffer. + */ + virtual void removeParticleBuffer(PxParticleBuffer* particleBuffer) = 0; + + /** + \brief Returns the GPU particle system index. + \return The GPU index, if the particle system is in a scene and PxSceneFlag::eENABLE_DIRECT_GPU_API is set, or 0xFFFFFFFF otherwise. + */ + virtual PxU32 getGpuParticleSystemIndex() = 0; + + /** + \brief Set wind direction and intensity + + \param[in] wind The wind direction and intensity + */ + virtual void setWind(const PxVec3& wind) = 0; + + /** + \brief Retrieves the wind direction and intensity. + + \return The wind direction and intensity + */ + virtual PxVec3 getWind() const = 0; + + /** + \brief Set the fluid boundary density scale + + Defines how strong of a contribution the boundary (typically a rigid surface) should have on a fluid particle's density. + + \param[in] fluidBoundaryDensityScale Range: (0.0, 1.0) + */ + virtual void setFluidBoundaryDensityScale(PxReal fluidBoundaryDensityScale) = 0; + + /** + \brief Return the fluid boundary density scale + \return the fluid boundary density scale + + See #setFluidBoundaryDensityScale() + */ + virtual PxReal getFluidBoundaryDensityScale() const = 0; + + /** + \brief Set the fluid rest offset + + Two fluid particles will come to rest at a distance equal to twice the fluidRestOffset value. + + \param[in] fluidRestOffset Range: (0, particleContactOffset) + */ + virtual void setFluidRestOffset(PxReal fluidRestOffset) = 0; + + /** + \brief Return the fluid rest offset + \return the fluid rest offset + + See #setFluidRestOffset() + */ + virtual PxReal getFluidRestOffset() const = 0; + + /** + \brief Set the particle system grid size x dimension + + \param[in] gridSizeX x dimension in the particle grid + */ + virtual void setGridSizeX(PxU32 gridSizeX) = 0; + + /** + \brief Get the particle system grid size x dimension + \return[in] the x dimension in the particle grid + + See #setGridSizeX() + */ + virtual PxU32 getGridSizeX() const = 0; + + /** + \brief Set the particle system grid size y dimension + + \param[in] gridSizeY y dimension in the particle grid + */ + virtual void setGridSizeY(PxU32 gridSizeY) = 0; + + /** + \brief Get the particle system grid size y dimension + \return[in] the y dimension in the particle grid + + See #setGridSizeY() + */ + virtual PxU32 getGridSizeY() const = 0; + + /** + \brief Set the particle system grid size z dimension + + \param[in] gridSizeZ z dimension in the particle grid + */ + virtual void setGridSizeZ(PxU32 gridSizeZ) = 0; + + /** + \brief Get the particle system grid size z dimension + \return[in] the z dimension in the particle grid + + See #setGridSizeZ() + */ + virtual PxU32 getGridSizeZ() const = 0; + + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxPBDParticleSystem"; } + +protected: + PX_INLINE PxPBDParticleSystem(PxType concreteType, PxBaseFlags baseFlags) : PxActor(concreteType, baseFlags) {} + PX_INLINE PxPBDParticleSystem(PxBaseFlags baseFlags) : PxActor(baseFlags) {} + virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxPBDParticleSystem", PxActor); } +}; + +#if PX_VC +#pragma warning(pop) +#endif + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxParticleBuffer.h b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleBuffer.h new file mode 100644 index 000000000..0a8d8c2b0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleBuffer.h @@ -0,0 +1,626 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_BUFFER_H +#define PX_PARTICLE_BUFFER_H + +#include "common/PxBase.h" +#include "common/PxPhysXCommonConfig.h" +#include "common/PxTypeInfo.h" + +#include "PxParticleSystemFlag.h" + +#include "foundation/PxBounds3.h" +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + +class PxCudaContextManager; +struct PxParticleRigidFilterPair; +struct PxParticleRigidAttachment; + +/** +\brief Particle volume structure. Used to track the bounding volume of a user-specified set of particles. The particles are required +to be laid out contiguously within the same PxParticleBuffer. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +PX_ALIGN_PREFIX(16) +struct PX_DEPRECATED PxParticleVolume +{ + PxBounds3 bound; //!< The current bounds of the particles contained in this #PxParticleVolume. + PxU32 particleIndicesOffset; //!< The index into the particle list of the #PxParticleBuffer for the first particle of this volume. + PxU32 numParticles; //!< The number of particles contained in this #PxParticleVolume. +} PX_ALIGN_SUFFIX(16); + + +/** +\brief The shared base class for all particle buffers, can be instantiated directly to simulate granular and fluid particles. + +See #PxPhysics::createParticleBuffer. + +A particle buffer is a container that specifies per-particle attributes of a set of particles that will be used during the simulation +of a particle system. It exposes direct access to the underlying GPU buffers and is independent of the scene and particle system. Particle +buffers can be added/removed from a particle system at any time between simulation steps, and transferred from one particle system to another. +*/ +class PxParticleBuffer : public PxBase +{ +public: + + /** + \brief Get positions and inverse masses for this particle buffer. + \return A pointer to a device buffer containing the positions and inverse mass packed as PxVec4(pos.x, pos.y, pos.z, inverseMass). + */ + virtual PxVec4* getPositionInvMasses() const = 0; + + /** + \brief Get velocities for this particle buffer. + \return A pointer to a device buffer containing the velocities packed as PxVec4(vel.x, vel.y, vel.z, 0.0f). + */ + virtual PxVec4* getVelocities() const = 0; + + /** + \brief Get phases for this particle buffer. + + See #PxParticlePhaseFlag + + \return A pointer to a device buffer containing the per-particle phases for this particle buffer. + */ + virtual PxU32* getPhases() const = 0; + + /** + \brief Get particle volumes for this particle buffer. + + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + See #PxParticleVolume + + \return A pointer to a device buffer containing the #PxParticleVolume s for this particle buffer. + */ + PX_DEPRECATED virtual PxParticleVolume* getParticleVolumes() const = 0; + + /** + \brief Set the number of active particles for this particle buffer. + \param[in] nbActiveParticles The number of active particles. + + The number of active particles can be <= PxParticleBuffer::getMaxParticles(). The particle system will simulate the first + x particles in the #PxParticleBuffer, where x is the number of active particles. + */ + virtual void setNbActiveParticles(PxU32 nbActiveParticles) = 0; + + /** + \brief Get the number of active particles for this particle buffer. + \return The number of active particles. + */ + virtual PxU32 getNbActiveParticles() const = 0; + + /** + \brief Get the maximum number particles this particle buffer can hold. + + The maximum number of particles is specified when creating a #PxParticleBuffer. See #PxPhysics::createParticleBuffer. + + \return The maximum number of particles. + */ + virtual PxU32 getMaxParticles() const = 0; + + /** + \brief Get the number of particle volumes in this particle buffer. + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + \return The number of #PxParticleVolume s for this particle buffer. + */ + PX_DEPRECATED virtual PxU32 getNbParticleVolumes() const = 0; + + /** + \brief Set the number of #PxParticleVolume s for this particle buffer. + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + \param[in] nbParticleVolumes The number of particle volumes in this particle buffer. + */ + PX_DEPRECATED virtual void setNbParticleVolumes(PxU32 nbParticleVolumes) = 0; + + /** + \brief Get the maximum number of particle volumes this particle buffer can hold. + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + See #PxParticleVolume. + + \return The maximum number of particle volumes this particle buffer can hold. + */ + PX_DEPRECATED virtual PxU32 getMaxParticleVolumes() const = 0; + + /** + \brief Set the #PxParticleRigidFilterPair s for collision filtering of particles in this buffer with rigid bodies. + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + See #PxParticleRigidFilterPair + + \param[in] filters A device buffer containing #PxParticleRigidFilterPair s. + \param[in] nbFilters The number of particle-rigid body collision filtering pairs. + */ + PX_DEPRECATED virtual void setRigidFilters(PxParticleRigidFilterPair* filters, PxU32 nbFilters) = 0; + + /** + \brief Set the particle-rigid body attachments for particles in this particle buffer. + \deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + + See #PxParticleRigidAttachment + + \param[in] attachments A device buffer containing #PxParticleRigidAttachment s. + \param[in] nbAttachments The number of particle-rigid body attachments. + */ + PX_DEPRECATED virtual void setRigidAttachments(PxParticleRigidAttachment* attachments, PxU32 nbAttachments) = 0; + + /** + \brief Get the start index for the first particle of this particle buffer in the complete list of + particles of the particle system this buffer is used in. + + The return value is only correct if the particle buffer is assigned to a particle system and at least + one call to simulate() has been performed. + + \return The index of the first particle in the complete particle list. + */ + virtual PxU32 getFlatListStartIndex() const = 0; + + /** + \brief Raise dirty flags on this particle buffer to communicate that the corresponding data has been updated + by the user. + \param[in] flags The flag corresponding to the data that is dirty. + + See #PxParticleBufferFlag. + */ + virtual void raiseFlags(PxParticleBufferFlag::Enum flags) = 0; + + /** + \brief Release this buffer and deallocate all the memory. + */ + virtual void release() = 0; + + /** + \deprecated Will be removed in a future version, use getUniqueId() instead. + \brief Unique index that does not change over the lifetime of a PxParticleBuffer. + */ + PX_DEPRECATED PxU32 bufferUniqueId; + + /** + \brief Retrieve unique index that does not change over the lifetime of a PxParticleBuffer. + */ + virtual PxU32 getUniqueId() const = 0; + + //public variables: + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + + virtual ~PxParticleBuffer() { } + PX_INLINE PxParticleBuffer(PxType type) : PxBase(type, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), bufferUniqueId(PX_INVALID_U32), userData(NULL) {} + +private: + PX_NOCOPY(PxParticleBuffer) +}; + +/** +\brief Parameters to configure the behavior of diffuse particles +*/ +class PxDiffuseParticleParams +{ +public: + /** + \brief Construct parameters with default values. + */ + PX_INLINE PxDiffuseParticleParams() + { + threshold = 100.0f; + lifetime = 5.0f; + airDrag = 0.0f; + bubbleDrag = 0.5f; + buoyancy = 0.8f; + kineticEnergyWeight = 0.01f; + pressureWeight = 1.0f; + divergenceWeight = 5.0f; + collisionDecay = 0.5f; + useAccurateVelocity = false; + } + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + *this = PxDiffuseParticleParams(); + } + + PxReal threshold; //!< Particles with potential value greater than the threshold will spawn diffuse particles + PxReal lifetime; //!< Diffuse particle will be removed after the specified lifetime + PxReal airDrag; //!< Air drag force factor for spray particles + PxReal bubbleDrag; //!< Fluid drag force factor for bubble particles + PxReal buoyancy; //!< Buoyancy force factor for bubble particles + PxReal kineticEnergyWeight; //!< Contribution from kinetic energy when deciding diffuse particle creation. + PxReal pressureWeight; //!< Contribution from pressure when deciding diffuse particle creation. + PxReal divergenceWeight; //!< Contribution from divergence when deciding diffuse particle creation. + PxReal collisionDecay; //!< Decay factor of diffuse particles' lifetime after they collide with shapes. + bool useAccurateVelocity; //!< If true, enables accurate velocity estimation when using PBD solver. +}; + +/** +\brief A particle buffer used to simulate diffuse particles. + +See #PxPhysics::createParticleAndDiffuseBuffer. +*/ +class PxParticleAndDiffuseBuffer : public PxParticleBuffer +{ +public: + + /** + \brief Get a device buffer of positions and remaining lifetimes for the diffuse particles. + \return A device buffer containing positions and lifetimes of diffuse particles packed as PxVec4(pos.x, pos.y, pos.z, lifetime). + */ + virtual PxVec4* getDiffusePositionLifeTime() const = 0; + + /** + \brief Get a device buffer of velocities for the diffuse particles. + \return A device buffer containing velocities of diffuse particles. + */ + virtual PxVec4* getDiffuseVelocities() const = 0; + + /** + \brief Get number of currently active diffuse particles. + \return The number of currently active diffuse particles. + */ + virtual PxU32 getNbActiveDiffuseParticles() const = 0; + + /** + \brief Set the maximum possible number of diffuse particles for this buffer. + \param[in] maxActiveDiffuseParticles the maximum number of active diffuse particles. + + \note Must be in the range [0, PxParticleAndDiffuseBuffer::getMaxDiffuseParticles()] + */ + virtual void setMaxActiveDiffuseParticles(PxU32 maxActiveDiffuseParticles) = 0; + + /** + \brief Get maximum possible number of diffuse particles. + \return The maximum possible number diffuse particles. + */ + virtual PxU32 getMaxDiffuseParticles() const = 0; + + /** + \brief Set the parameters for diffuse particle simulation. + \param[in] params The diffuse particle parameters. + + See #PxDiffuseParticleParams + */ + virtual void setDiffuseParticleParams(const PxDiffuseParticleParams& params) = 0; + + /** + \brief Get the parameters currently used for diffuse particle simulation. + \return A PxDiffuseParticleParams structure. + */ + virtual PxDiffuseParticleParams getDiffuseParticleParams() const = 0; + +protected: + + virtual ~PxParticleAndDiffuseBuffer() {} + PX_INLINE PxParticleAndDiffuseBuffer(PxType type) : PxParticleBuffer(type){} + +private: + PX_NOCOPY(PxParticleAndDiffuseBuffer) +}; + +/** +\brief Holds all the information for a spring constraint between two particles. Used for particle cloth simulation. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +struct PX_DEPRECATED PX_ALIGN_PREFIX(8) PxParticleSpring +{ + PxU32 ind0; //!< particle index of first particle + PxU32 ind1; //!< particle index of second particle + PxReal length; //!< spring length + PxReal stiffness; //!< spring stiffness + PxReal damping; //!< spring damping factor + PxReal pad; //!< padding bytes. +} PX_ALIGN_SUFFIX(8); + +/** +\brief Particle cloth structure. Holds information about a single piece of cloth that is part of a #PxParticleClothBuffer. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +struct PX_DEPRECATED PxParticleCloth +{ + PxU32 startVertexIndex; //!< Index of the first particle of this cloth in the position/velocity buffers of the parent #PxParticleClothBuffer + PxU32 numVertices; //!< The number of particles of this piece of cloth + PxReal clothBlendScale; //!< Used internally. + PxReal restVolume; //!< The rest volume of this piece of cloth, used for inflatable simulation. + PxReal pressure; //!< The factor of the rest volume to specify the target volume for this piece of cloth, used for inflatable simulation. + PxU32 startTriangleIndex; //!< The index of the first triangle of this piece of cloth in the triangle list. + PxU32 numTriangles; //!< The number of triangles of this piece of cloth. + + bool operator <= (const PxParticleCloth& other) const { return startVertexIndex <= other.startVertexIndex; } + bool operator >= (const PxParticleCloth& other) const { return startVertexIndex >= other.startVertexIndex; } + bool operator < (const PxParticleCloth& other) const { return startVertexIndex < other.startVertexIndex; } + bool operator > (const PxParticleCloth& other) const { return startVertexIndex > other.startVertexIndex; } + bool operator == (const PxParticleCloth& other) const { return startVertexIndex == other.startVertexIndex; } +}; + +/** +\brief Structure to describe the set of particle cloths in the same #PxParticleClothBuffer. Used an input for the cloth preprocessing. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +struct PX_DEPRECATED PxParticleClothDesc +{ + PxParticleClothDesc() : cloths(NULL), triangles(NULL), springs(NULL), restPositions(NULL), + nbCloths(0), nbSprings(0), nbTriangles(0), nbParticles(0) + { + } + + PxParticleCloth* cloths; //!< List of PxParticleCloth s, describes the individual cloths. + PxU32* triangles; //!< List of triangle indices, 3 consecutive PxU32 that map triangle vertices to particles + PxParticleSpring* springs; //!< List of PxParticleSpring s. + PxVec4* restPositions; //!< List of rest positions for all particles + PxU32 nbCloths; //!< The number of cloths in described using this cloth descriptor + PxU32 nbSprings; //!< The number of springs in this cloth descriptor + PxU32 nbTriangles; //!< The number of triangles in this cloth descriptor + PxU32 nbParticles; //!< The number of particles in this cloth descriptor +}; + +/** +\brief Structure to describe the output of the particle cloth preprocessing. Used as an input to specify cloth data for a #PxParticleClothBuffer. +All the pointers point to pinned host memory. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +See #PxParticleClothPreProcessor +*/ +struct PX_DEPRECATED PX_PHYSX_CORE_API PxPartitionedParticleCloth +{ + PxU32* accumulatedSpringsPerPartitions; //!< The number of springs in each partition. Size: numPartitions. + PxU32* accumulatedCopiesPerParticles; //!< Start index for each particle in the accumulation buffer. Size: numParticles. + PxU32* remapOutput; //!< Index of the next copy of this particle in the next partition, or in the accumulation buffer. Size: numSprings * 2. + PxParticleSpring* orderedSprings; //!< Springs ordered by partition. Size: numSprings. + PxU32* sortedClothStartIndices; //!< The first particle index into the position buffer of the #PxParticleClothBuffer for each cloth. Cloths are sorted by start particle index. Size: numCloths. + PxParticleCloth* cloths; //!< The #PxParticleCloth s sorted by start particle index. + + PxU32 remapOutputSize; //!< Size of remapOutput. + PxU32 nbPartitions; //!< The number of partitions. + PxU32 nbSprings; //!< The number of springs. + PxU32 nbCloths; //!< The number of cloths. + PxU32 maxSpringsPerPartition; //!< The maximum number of springs in a partition. + + PxCudaContextManager* mCudaManager; //!< A cuda context manager. + + PxPartitionedParticleCloth(); + ~PxPartitionedParticleCloth(); + + /** + \brief allocate all the buffers for this #PxPartitionedParticleCloth. + + \param[in] nbParticles the number of particles this #PxPartitionedParticleCloth will be generated for. + \param[in] cudaManager a cuda context manager. + */ + void allocateBuffers(PxU32 nbParticles, PxCudaContextManager* cudaManager); +}; + +/** +\brief A particle buffer used to simulate particle cloth. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +See #PxPhysics::createParticleClothBuffer. +*/ +class PX_DEPRECATED PxParticleClothBuffer : public PxParticleBuffer +{ +public: + + /** + \brief Get rest positions for this particle buffer. + \return A pointer to a device buffer containing the rest positions packed as PxVec4(pos.x, pos.y, pos.z, 0.0f). + */ + virtual PxVec4* getRestPositions() = 0; + + /** + \brief Get the triangle indices for this particle buffer. + \return A pointer to a device buffer containing the triangle indices for this cloth buffer. + */ + virtual PxU32* getTriangles() const = 0; + + /** + \brief Set the number of triangles for this particle buffer. + \param[in] nbTriangles The number of triangles for this particle cloth buffer. + */ + virtual void setNbTriangles(PxU32 nbTriangles) = 0; + + /** + \brief Get the number of triangles for this particle buffer. + \return The number triangles for this cloth buffer. + */ + virtual PxU32 getNbTriangles() const = 0; + + /** + \brief Get the number of springs in this particle buffer. + \return The number of springs in this cloth buffer. + */ + virtual PxU32 getNbSprings() const = 0; + + /** + \brief Get the springs for this particle buffer. + \return A pointer to a device buffer containing the springs for this cloth buffer. + */ + virtual PxParticleSpring* getSprings() = 0; + + /** + \brief Set cloths for this particle buffer. + \param[in] cloths A pointer to a PxPartitionedParticleCloth. + + See #PxPartitionedParticleCloth, #PxParticleClothPreProcessor + */ + virtual void setCloths(PxPartitionedParticleCloth& cloths) = 0; + +protected: + + virtual ~PxParticleClothBuffer() {} + PX_INLINE PxParticleClothBuffer(PxType type) : PxParticleBuffer(type) {} + +private: + PX_NOCOPY(PxParticleClothBuffer) +}; + +/** +\brief A particle buffer used to simulate rigid bodies using shape matching with particles. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +See #PxPhysics::createParticleRigidBuffer. +*/ +class PX_DEPRECATED PxParticleRigidBuffer : public PxParticleBuffer +{ +public: + /** + \brief Get the particle indices of the first particle for each shape matched rigid body. + \return A device buffer containing the list of particle start indices of each shape matched rigid body. + */ + virtual PxU32* getRigidOffsets() const = 0; + + /** + \brief Get the stiffness coefficients for all shape matched rigid bodies in this buffer. + + Stiffness must be in the range [0, 1]. + + \return A device buffer containing the list of stiffness coefficients for each rigid body. + */ + virtual PxReal* getRigidCoefficients() const = 0; + + /** + \brief Get the local position of each particle relative to the rigid body's center of mass. + \return A pointer to a device buffer containing the local position for each particle. + */ + virtual PxVec4* getRigidLocalPositions() const = 0; + + /** + \brief Get the world-space translations for all rigid bodies in this buffer. + \return A pointer to a device buffer containing the world-space translations for all shape-matched rigid bodies in this buffer. + */ + virtual PxVec4* getRigidTranslations() const = 0; + + /** + \brief Get the world-space rotation of every shape-matched rigid body in this buffer. + + Rotations are specified as quaternions. + + \return A pointer to a device buffer containing the world-space rotation for every shape-matched rigid body in this buffer. + */ + virtual PxVec4* getRigidRotations() const = 0; + + /** + \brief Get the local space normals for each particle relative to the shape of the corresponding rigid body. + + The 4th component of every PxVec4 should be the negative signed distance of the particle inside its shape. + + \return A pointer to a device buffer containing the local-space normals for each particle. + */ + virtual PxVec4* getRigidLocalNormals() const = 0; + + /** + \brief Set the number of shape matched rigid bodies in this buffer. + \param[in] nbRigids The number of shape matched rigid bodies + */ + virtual void setNbRigids(PxU32 nbRigids) = 0; + + /** + \brief Get the number of shape matched rigid bodies in this buffer. + \return The number of shape matched rigid bodies in this buffer. + */ + virtual PxU32 getNbRigids() const = 0; + +protected: + + virtual ~PxParticleRigidBuffer() {} + PX_INLINE PxParticleRigidBuffer(PxType type) : PxParticleBuffer(type) {} + +private: + PX_NOCOPY(PxParticleRigidBuffer) +}; + +/** +\brief Preprocessor to prepare particle cloths for simulation. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +Preprocessing is done by calling #PxParticleClothPreProcessor::partitionSprings() on an instance of this class. This will allocate the memory in the +output object, partition the springs and fill all the members of the ouput object. The output can then be passed without +any further modifications to #PxParticleClothBuffer::setCloths(). + +See #PxParticleClothDesc, #PxPartitionedParticleCloth +*/ +class PX_DEPRECATED PxParticleClothPreProcessor +{ +public: + + /** + \brief Release this object and deallocate all the memory. + */ + virtual void release() = 0; + + /** + \brief Partition the spring constraints for particle cloth simulation. + \param[in] clothDesc Reference to a valid #PxParticleClothDesc. + \param[in] output Reference to a #PxPartitionedParticleCloth object. This is the output of the preprocessing and should be passed to a #PxParticleClothBuffer. + */ + virtual void partitionSprings(const PxParticleClothDesc& clothDesc, PxPartitionedParticleCloth& output) = 0; + +protected: + virtual ~PxParticleClothPreProcessor(){} +}; + + +#if PX_VC +#pragma warning(pop) +#endif + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** +\brief Create a particle cloth preprocessor. +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +\param[in] cudaContextManager A cuda context manager. + +See #PxParticleClothDesc, #PxPartitionedParticleCloth. +*/ +PX_DEPRECATED PX_C_EXPORT PX_PHYSX_CORE_API physx::PxParticleClothPreProcessor* PX_CALL_CONV PxCreateParticleClothPreProcessor(physx::PxCudaContextManager* cudaContextManager); + + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxParticleGpu.h b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleGpu.h new file mode 100644 index 000000000..3c8a04bda --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleGpu.h @@ -0,0 +1,188 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GPU_PARTICLE_SYSTEM_H +#define PX_GPU_PARTICLE_SYSTEM_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec3.h" + +#include "PxParticleSystem.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Common material properties for particles. See #PxPBDMaterial. + +Accessed by either integration or particle-rigid collisions +*/ +struct PxsParticleMaterialData +{ + PxReal friction; // 4 + PxReal damping; // 8 + PxReal adhesion; // 12 + PxReal gravityScale; // 16 + PxReal adhesionRadiusScale; // 20 +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#if PX_SUPPORT_GPU_PHYSX + +struct float4; + +PX_CUDA_CALLABLE inline physx::PxU32 PxGetGroup(physx::PxU32 phase) { return phase & physx::PxParticlePhaseFlag::eParticlePhaseGroupMask; } +PX_CUDA_CALLABLE inline bool PxGetFluid(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseFluid) != 0; } +PX_CUDA_CALLABLE inline bool PxGetSelfCollide(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseSelfCollide) != 0; } +PX_CUDA_CALLABLE inline bool PxGetSelfCollideFilter(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseSelfCollideFilter) != 0; } + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief An iterator class to iterate over the neighbors of a particle during particle system simulation. +*/ +class PxNeighborhoodIterator +{ + + const PxU32* PX_RESTRICT mCollisionIndex; //!< Pointer to the current state of the iterator. + PxU32 mMaxParticles; //!< The maximum number of particles of the particle system this iterator is used on. + +public: + PX_CUDA_CALLABLE PxNeighborhoodIterator(const PxU32* PX_RESTRICT collisionIndex, PxU32 maxParticles) : + mCollisionIndex(collisionIndex), mMaxParticles(maxParticles) + { + } + + PX_CUDA_CALLABLE PxU32 getNextIndex() + { + PxU32 result = *mCollisionIndex; + mCollisionIndex += mMaxParticles; + return result; + } + + PX_INLINE PxNeighborhoodIterator(const PxNeighborhoodIterator& params) + { + mCollisionIndex = params.mCollisionIndex; + mMaxParticles = params.mMaxParticles; + } + + PX_INLINE void operator = (const PxNeighborhoodIterator& params) + { + mCollisionIndex = params.mCollisionIndex; + mMaxParticles = params.mMaxParticles; + } +}; + +/** +\brief Structure that holds simulation parameters of a #PxGpuParticleSystem. +*/ +struct PxGpuParticleData +{ + PxReal mGridCellWidth; //!< Grid cell width, derived from particle contact offset * neighborhood scale + PxU32 mGridSizeX; //!< Size of the x-dimension of the background simulation grid. Translates to an absolute size of mGridSizeX * mGridCellWidth. + PxU32 mGridSizeY; //!< Size of the y-dimension of the background simulation grid. Translates to an absolute size of mGridSizeY * mGridCellWidth. + PxU32 mGridSizeZ; //!< Size of the z-dimension of the background simulation grid. Translates to an absolute size of mGridSizeZ * mGridCellWidth. + + PxReal mParticleContactDistance; //!< Two particles start interacting if their distance is lower than mParticleContactDistance. + PxReal mParticleContactDistanceInv; //!< 1.f / mParticleContactDistance. + PxReal mParticleContactDistanceSq; //!< mParticleContactDistance * mParticleContactDistance. + + PxU32 mNumParticles; //!< The number of particles in this particle system. + PxU32 mMaxParticles; //!< The maximum number of particles that can be simulated in this particle system. + PxU32 mMaxNeighborhood; //!< The maximum number of particles considered when computing neighborhood based particle interactions. + PxU32 mMaxDiffuseParticles; //!< The maximum number of diffuse particles that can be simulated using this particle system. + PxU32 mNumParticleBuffers; //!< The number of particle buffers that are simulated in this particle system. +}; + +/** +\brief Container class for a GPU particle system. Used to communicate particle system parameters and simulation state +between the internal SDK simulation and the particle system callbacks. + +See #PxPBDParticleSystem, #PxParticleSystemCallback. +*/ +class PxGpuParticleSystem +{ +public: + + /** + \brief Returns the number of cells of the background simulation grid. + + \return PxU32 the number of cells. + */ + PX_FORCE_INLINE PxU32 getNumCells() { return mCommonData.mGridSizeX * mCommonData.mGridSizeY * mCommonData.mGridSizeZ; } + + /* Unsorted particle state buffers */ + float4* mUnsortedPositions_InvMass; //!< GPU pointer to unsorted particle positions and inverse masses. + float4* mUnsortedVelocities; //!< GPU pointer to unsorted particle velocities. + PxU32* mUnsortedPhaseArray; //!< GPU pointer to unsorted particle phase array. See #PxParticlePhaseFlag. + + /* Sorted particle state buffers. Sorted by increasing hash value in background grid. */ + float4* mSortedPositions_InvMass; //!< GPU pointer to sorted particle positions + float4* mSortedVelocities; //!< GPU pointer to sorted particle velocities + PxU32* mSortedPhaseArray; //!< GPU pointer to sorted particle phase array + + /* Mappings to/from sorted particle states */ + PxU32* mUnsortedToSortedMapping; //!< GPU pointer to the mapping from unsortedParticle ID to sorted particle ID + PxU32* mSortedToUnsortedMapping; //!< GPU pointer to the mapping from sorted particle ID to unsorted particle ID + + /* Neighborhood information */ + PxU32* mParticleSelfCollisionCount; //!< Per-particle neighborhood count + PxU32* mCollisionIndex; //!< Set of sorted particle indices per neighbor + + PxsParticleMaterialData* mParticleMaterials; //!< GPU pointer to the particle materials used in this particle system. + PxGpuParticleData mCommonData; //!< Structure holding simulation parameters and state for this particle system. See #PxGpuParticleData. + + /** + \brief Get a PxNeighborhoodIterator initialized for usage with this particle system. + + \param particleId An initial particle index for the initialization of the iterator. + + \return An initialized PxNeighborhoodIterator. + */ + PX_CUDA_CALLABLE PxNeighborhoodIterator getIterator(PxU32 particleId) const + { + return PxNeighborhoodIterator(mCollisionIndex + particleId, mCommonData.mMaxParticles); + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxParticleMaterial.h b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleMaterial.h new file mode 100644 index 000000000..b13113c22 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleMaterial.h @@ -0,0 +1,47 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_MATERIAL_H +#define PX_PARTICLE_MATERIAL_H + +#include "foundation/PxPreprocessor.h" +#include "PxPBDMaterial.h" + +#if !PX_DOXYGEN +namespace physx +{ + +/** + \deprecated This typedef only serves for deprecation and will be removed in a future version. + */ +typedef PX_DEPRECATED PxPBDMaterial PxParticleMaterial; + +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxParticleNeighborhoodProvider.h b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleNeighborhoodProvider.h new file mode 100644 index 000000000..a2182c375 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleNeighborhoodProvider.h @@ -0,0 +1,130 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H +#define PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H + + +#include "cudamanager/PxCudaContext.h" +#include "cudamanager/PxCudaContextManager.h" + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" +#include "PxParticleSystem.h" + +#include "foundation/PxArray.h" +#include "PxParticleGpu.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_SUPPORT_GPU_PHYSX + + /** + \brief Computes neighborhood information for a point cloud + */ + class PxParticleNeighborhoodProvider + { + public: + /** + \brief Schedules the compuation of neighborhood information on the specified cuda stream + + \param[in] deviceParticlePos A gpu pointer containing the particle positions + \param[in] numParticles The number of particles + \param[in] stream The stream on which the cuda call gets scheduled + \param[in] devicePhases An optional gpu pointer with particle phases + \param[in] validPhaseMask An optional phase mask to define which particles should be included into the neighborhood computation + \param[in] deviceActiveIndices An optional device pointer containing all indices of particles that are currently active + */ + virtual void buildNeighborhood(PxVec4* deviceParticlePos, const PxU32 numParticles, CUstream stream, PxU32* devicePhases = NULL, + PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid, const PxU32* deviceActiveIndices = NULL) = 0; + + /** + \brief Gets the maximal number of particles + + \return The maximal number of particles + */ + virtual PxU32 getMaxParticles() const = 0; + + /** + \brief Sets the maximal number of particles + + \param[in] maxParticles The maximal number of particles + */ + virtual void setMaxParticles(PxU32 maxParticles) = 0; + + /** + \brief Gets the maximal number of grid cells + + \return The maximal number of grid cells + */ + virtual PxU32 getMaxGridCells() const = 0; + + /** + \brief Gets the cell size + + \return The cell size + */ + virtual PxReal getCellSize() const = 0; + + /** + \brief Gets the number of grid cells in use + + \return The number of grid cells in use + */ + virtual PxU32 getNumGridCellsInUse() const = 0; + + /** + \brief Sets the maximal number of particles + + \param[in] maxGridCells The maximal number of grid cells + \param[in] cellSize The cell size. Should be equal to 2*contactOffset for PBD particle systems. + */ + virtual void setCellProperties(PxU32 maxGridCells, PxReal cellSize) = 0; + + /** + \brief Releases the instance and its data + */ + virtual void release() = 0; + + /** + \brief Destructor + */ + virtual ~PxParticleNeighborhoodProvider() {} + }; + +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSolverType.h b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSolverType.h new file mode 100644 index 000000000..8f9912acd --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSolverType.h @@ -0,0 +1,66 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_SOLVER_TYPE_H +#define PX_PARTICLE_SOLVER_TYPE_H + +#include "foundation/PxPreprocessor.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + + +/** +\deprecated The solver type will be removed in a future version without replacement. +\brief Identifies the solver to use for a particle system. +*/ +struct PX_DEPRECATED PxParticleSolverType +{ + enum Enum + { + ePBD = 1 << 0 //!< The position based dynamics solver that can handle fluid, granular material, cloth, inflatables etc. See #PxPBDParticleSystem. + }; +}; + +#if PX_VC +#pragma warning(pop) +#endif + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSystem.h b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSystem.h new file mode 100644 index 000000000..b25745e0c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSystem.h @@ -0,0 +1,47 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_SYSTEM_H +#define PX_PARTICLE_SYSTEM_H + +#include "foundation/PxPreprocessor.h" +#include "PxPBDParticleSystem.h" + +#if !PX_DOXYGEN +namespace physx +{ + +/** + \deprecated This typedef only serves for deprecation and will be removed in a future version. + */ +typedef PX_DEPRECATED PxPBDParticleSystem PxParticleSystem; + +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSystemFlag.h b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSystemFlag.h new file mode 100644 index 000000000..f9df1e0a3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxParticleSystemFlag.h @@ -0,0 +1,104 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_SYSTEM_FLAG_H +#define PX_PARTICLE_SYSTEM_FLAG_H + +#include "foundation/PxFlags.h" +#include "foundation/PxPreprocessor.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Identifies dirty particle buffers that need to be updated in the particle system. + +This flag can be used mark the device user buffers that are dirty and need to be written to the particle system. +*/ +struct PxParticleBufferFlag +{ + enum Enum + { + eNONE = 0, //!< No data specified + + eUPDATE_POSITION = 1 << 0, //!< Specifies the position (first 3 floats) and inverse mass (last float) data (array of PxVec4 * number of particles) + eUPDATE_VELOCITY = 1 << 1, //!< Specifies the velocity (first 3 floats) data (array of PxVec4 * number of particles) + eUPDATE_PHASE = 1 << 2, //!< Specifies the per-particle phase flag data (array of PxU32 * number of particles) + eUPDATE_RESTPOSITION = 1 << 3, //!< Specifies the rest position (first 3 floats) data for cloth buffers + eUPDATE_CLOTH = 1 << 5, //!< Specifies the cloth buffer (see PxParticleClothBuffer) + eUPDATE_RIGID = 1 << 6, //!< Specifies the rigid buffer (see PxParticleRigidBuffer) + eUPDATE_DIFFUSE_PARAM = 1 << 7, //!< Specifies the diffuse particle parameter buffer (see PxDiffuseParticleParams) + eUPDATE_ATTACHMENTS = 1 << 8, //!< Specifies the attachments. + + eALL = + eUPDATE_POSITION | eUPDATE_VELOCITY | eUPDATE_PHASE | eUPDATE_RESTPOSITION | eUPDATE_CLOTH | eUPDATE_RIGID | eUPDATE_DIFFUSE_PARAM | eUPDATE_ATTACHMENTS + }; +}; + +typedef PxFlags PxParticleBufferFlags; + +/** +\brief A pair of particle buffer unique id and GPU particle system index. + +\see PxScene::applyParticleBufferData + +\deprecated There is no replacement. +*/ +PX_DEPRECATED struct PxGpuParticleBufferIndexPair +{ + PxU32 systemIndex; // gpu particle system index + PxU32 bufferIndex; // particle buffer unique id +}; + +/** +\brief Identifies per-particle behavior for a PxParticleSystem. + +See #PxPBDParticleSystem::createPhase(). +*/ +struct PxParticlePhaseFlag +{ + enum Enum + { + eParticlePhaseGroupMask = 0x000fffff, //!< Bits [ 0, 19] represent the particle group for controlling collisions + eParticlePhaseFlagsMask = 0xfff00000, //!< Bits [20, 23] hold flags about how the particle behave + + eParticlePhaseSelfCollide = 1 << 20, //!< If set this particle will interact with particles of the same group + eParticlePhaseSelfCollideFilter = 1 << 21, //!< If set this particle will ignore collisions with particles closer than the radius in the rest pose, this flag should not be specified unless valid rest positions have been specified using setRestParticles() + eParticlePhaseFluid = 1 << 22 //!< If set this particle will generate fluid density constraints for its overlapping neighbors + }; +}; + +typedef PxFlags PxParticlePhaseFlags; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxPhysXConfig.h b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysXConfig.h new file mode 100644 index 000000000..223b8bf56 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysXConfig.h @@ -0,0 +1,46 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSICS_CONFIG_H +#define PX_PHYSICS_CONFIG_H + +/** Configuration include file for PhysX SDK */ + + +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxPhysics.h b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysics.h new file mode 100644 index 000000000..07162f349 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysics.h @@ -0,0 +1,1129 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSICS_H +#define PX_PHYSICS_H + +#include "PxPhysXConfig.h" +#include "PxDeletionListener.h" +#include "foundation/PxTransform.h" +#include "PxShape.h" +#include "PxAggregate.h" +#include "PxParticleSystem.h" +#include "PxDeformableSurface.h" +#include "PxDeformableAttachment.h" +#include "PxDeformableElementFilter.h" +#include "foundation/PxPreprocessor.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxScene; +class PxSceneDesc; +class PxTolerancesScale; +class PxPvd; +class PxOmniPvd; +class PxInsertionCallback; + +class PxRigidActor; +class PxConstraintConnector; +struct PxConstraintShaderTable; + +class PxGeometry; +class PxFoundation; + +class PxPruningStructure; +class PxBVH; + +class PxParticleClothBuffer; +class PxParticleRigidBuffer; + +class PxDeformableVolumeMesh; + +class PxInputStream; + +/** +\brief Abstract singleton factory class used for instancing objects in the Physics SDK. + +In addition you can use PxPhysics to set global parameters which will effect all scenes and create +objects that can be shared across multiple scenes. + +You can get an instance of this class by calling PxCreatePhysics(). + +\see PxCreatePhysics() PxScene +*/ +class PxPhysics +{ +public: + + /** \name Basics + */ + //\{ + + virtual ~PxPhysics() {} + + /** + \brief Destroys the instance it is called on. + + Use this release method to destroy an instance of this class. Be sure + to not keep a reference to this object after calling release. + Avoid release calls while a scene is simulating (in between simulate() and fetchResults() calls). + + Note that this must be called once for each prior call to PxCreatePhysics, as + there is a reference counter. Also note that you mustn't destroy the PxFoundation instance (holding the allocator, error callback etc.) + until after the reference count reaches 0 and the SDK is actually removed. + + Releasing an SDK will also release any objects created through it (scenes, triangle meshes, convex meshes, heightfields, shapes etc.), + provided the user hasn't already done so. + + \note Releasing the PxPhysics instance is a prerequisite to releasing the PxFoundation instance. + + \see PxCreatePhysics() PxFoundation + */ + virtual void release() = 0; + + /** + \brief Retrieves the Foundation instance. + \return A reference to the Foundation object. + */ + virtual PxFoundation& getFoundation() = 0; + + /** + \brief Gets PxPhysics object insertion interface. + + The insertion interface is needed for PxCreateTriangleMesh, PxCooking::createTriangleMesh etc., this allows runtime mesh creation. + + \see PxCreateTriangleMesh PxCreateHeightField PxCreateTetrahedronMesh PxCreateBVH + PxCooking::createTriangleMesh PxCooking::createHeightfield PxCooking::createTetrahedronMesh PxCooking::createBVH + */ + virtual PxInsertionCallback& getPhysicsInsertionCallback() = 0; + + /** + \brief Retrieves the PxOmniPvd instance if there is one registered with PxPhysics. + \return A pointer to a PxOmniPvd object. + */ + virtual PxOmniPvd* getOmniPvd() = 0; + + /** + \brief Returns the simulation tolerance parameters. + \return The current simulation tolerance parameters. + */ + virtual const PxTolerancesScale& getTolerancesScale() const = 0; + + //\} + /** \name Aggregates + */ + //\{ + + /** + \brief Creates an aggregate with the specified maximum size and filtering hint. + + The previous API used "bool enableSelfCollision" which should now silently evaluates + to a PxAggregateType::eGENERIC aggregate with its self-collision bit. + + Use PxAggregateType::eSTATIC or PxAggregateType::eKINEMATIC for aggregates that will + only contain static or kinematic actors. This provides faster filtering when used in + combination with PxPairFilteringMode. + + \param [in] maxActor The maximum number of actors that may be placed in the aggregate. + \param [in] maxShape The maximum number of shapes that may be placed in the aggregate. + \param [in] filterHint The aggregate's filtering hint. + \return The new aggregate. + + \see PxAggregate PxAggregateFilterHint PxAggregateType PxPairFilteringMode + */ + virtual PxAggregate* createAggregate(PxU32 maxActor, PxU32 maxShape, PxAggregateFilterHint filterHint) = 0; + + /** + \brief Return the number of aggregates that currently exist. + + \return Number of aggregates. + */ + virtual PxU32 getNbAggregates() const = 0; + + //\} + /** \name Triangle Meshes + */ + //\{ + + /** + \brief Creates a triangle mesh object. + + This can then be instanced into #PxShape objects. + + \param [in] stream The triangle mesh stream. + \return The new triangle mesh. + + \see PxTriangleMesh PxMeshPreprocessingFlag PxTriangleMesh.release() PxInputStream PxTriangleMeshFlag + */ + virtual PxTriangleMesh* createTriangleMesh(PxInputStream& stream) = 0; + + /** + \brief Return the number of triangle meshes that currently exist. + + \return Number of triangle meshes. + + \see getTriangleMeshes() + */ + virtual PxU32 getNbTriangleMeshes() const = 0; + + /** + \brief Writes the array of triangle mesh pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the triangle meshes in the array is not specified. + + \param [out] userBuffer The buffer to receive triangle mesh pointers. + \param [in] bufferSize The number of triangle mesh pointers which can be stored in the buffer. + \param [in] startIndex Index of first mesh pointer to be retrieved. + \return The number of triangle mesh pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbTriangleMeshes() PxTriangleMesh + */ + virtual PxU32 getTriangleMeshes(PxTriangleMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Tetrahedron Meshes + */ + //\{ + + /** + \brief Creates a tetrahedron mesh object. + + This can then be instanced into #PxShape objects. + + \param[in] stream The tetrahedron mesh stream. + \return The new tetrahedron mesh. + + \see PxTetrahedronMesh PxMeshPreprocessingFlag PxTetrahedronMesh.release() PxInputStream PxTriangleMeshFlag + */ + virtual PxTetrahedronMesh* createTetrahedronMesh(PxInputStream& stream) = 0; + + /** + \brief Return the number of tetrahedron meshes that currently exist. + + \return Number of tetrahedron meshes. + + \see getTetrahedronMeshes() + */ + virtual PxU32 getNbTetrahedronMeshes() const = 0; + + /** + \brief Writes the array of tetrahedron mesh pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the tetrahedron meshes in the array is not specified. + + \param[out] userBuffer The buffer to receive tetrahedron mesh pointers. + \param[in] bufferSize The number of tetrahedron mesh pointers which can be stored in the buffer. + \param[in] startIndex Index of first mesh pointer to be retrieved. + \return The number of tetrahedron mesh pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbTetrahedronMeshes() PxTetrahedronMesh + */ + virtual PxU32 getTetrahedronMeshes(PxTetrahedronMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Heightfields + */ + //\{ + + /** + \brief Creates a heightfield object from previously cooked stream. + + This can then be instanced into #PxShape objects. + + \param [in] stream The heightfield mesh stream. + \return The new heightfield. + + \see PxHeightField PxHeightField.release() PxInputStream + */ + virtual PxHeightField* createHeightField(PxInputStream& stream) = 0; + + /** + \brief Return the number of heightfields that currently exist. + + \return Number of heightfields. + + \see getHeightFields() + */ + virtual PxU32 getNbHeightFields() const = 0; + + /** + \brief Writes the array of heightfield pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the heightfields in the array is not specified. + + \param [out] userBuffer The buffer to receive heightfield pointers. + \param [in] bufferSize The number of heightfield pointers which can be stored in the buffer. + \param [in] startIndex Index of first heightfield pointer to be retrieved. + \return The number of heightfield pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbHeightFields() PxHeightField + */ + virtual PxU32 getHeightFields(PxHeightField** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Convex meshes + */ + //\{ + + /** + \brief Creates a convex mesh object. + + This can then be instanced into #PxShape objects. + + \param [in] stream The stream to load the convex mesh from. + \return The new convex mesh. + + \see PxConvexMesh PxConvexMesh.release() PxInputStream createTriangleMesh() PxConvexMeshGeometry PxShape + */ + virtual PxConvexMesh* createConvexMesh(PxInputStream& stream) = 0; + + /** + \brief Return the number of convex meshes that currently exist. + + \return Number of convex meshes. + + \see getConvexMeshes() + */ + virtual PxU32 getNbConvexMeshes() const = 0; + + /** + \brief Writes the array of convex mesh pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the convex meshes in the array is not specified. + + \param [out] userBuffer The buffer to receive convex mesh pointers. + \param [in] bufferSize The number of convex mesh pointers which can be stored in the buffer. + \param [in] startIndex Index of first convex mesh pointer to be retrieved. + \return The number of convex mesh pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbConvexMeshes() PxConvexMesh + */ + virtual PxU32 getConvexMeshes(PxConvexMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Deformable volume meshes + */ + //\{ + + /** + \brief Creates a deformable volume mesh object. + + \param[in] stream The deformable volume mesh stream. + \return The new deformable volume mesh. + + \see createTetrahedronMesh + */ + virtual PxDeformableVolumeMesh* createDeformableVolumeMesh(PxInputStream& stream) = 0; + + /** + \brief Deprecated + \see createDeformableVolumeMesh + */ + PX_DEPRECATED PX_FORCE_INLINE PxDeformableVolumeMesh* createSoftBodyMesh(PxInputStream& stream) + { + return createDeformableVolumeMesh(stream); + } + + //\} + /** \name BVHs + */ + //\{ + + /** + \brief Creates a bounding volume hierarchy. + + \param [in] stream The stream to load the BVH from. + \return The new BVH. + + \see PxBVH PxInputStream + */ + virtual PxBVH* createBVH(PxInputStream& stream) = 0; + + /** + \brief Return the number of bounding volume hierarchies that currently exist. + + \return Number of bounding volume hierarchies. + + \see PxBVH getBVHs() + */ + virtual PxU32 getNbBVHs() const = 0; + + /** + \brief Writes the array of bounding volume hierarchy pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the BVHs in the array is not specified. + + \param [out] userBuffer The buffer to receive BVH pointers. + \param [in] bufferSize The number of BVH pointers which can be stored in the buffer. + \param [in] startIndex Index of first BVH pointer to be retrieved. + \return The number of BVH pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbBVHs() PxBVH + */ + virtual PxU32 getBVHs(PxBVH** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Scenes + */ + //\{ + + /** + \brief Creates a scene. + + \note Every scene uses a Thread Local Storage slot. This imposes a platform specific limit on the + number of scenes that can be created. + + \param [in] sceneDesc Scene descriptor. See #PxSceneDesc + \return The new scene object. + + \see PxScene PxScene.release() PxSceneDesc + */ + virtual PxScene* createScene(const PxSceneDesc& sceneDesc) = 0; + + /** + \brief Gets number of created scenes. + + \return The number of scenes created. + + \see getScenes() + */ + virtual PxU32 getNbScenes() const = 0; + + /** + \brief Writes the array of scene pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the scene pointers in the array is not specified. + + \param [out] userBuffer The buffer to receive scene pointers. + \param [in] bufferSize The number of scene pointers which can be stored in the buffer. + \param [in] startIndex Index of first scene pointer to be retrieved. + \return The number of scene pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbScenes() PxScene + */ + virtual PxU32 getScenes(PxScene** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Actors + */ + //\{ + + /** + \brief Creates a static rigid actor with the specified pose and all other fields initialized + to their default values. + + \param [in] pose The initial pose of the actor. Must be a valid transform. + + \see PxRigidStatic + */ + virtual PxRigidStatic* createRigidStatic(const PxTransform& pose) = 0; + + /** + \brief Creates a dynamic rigid actor with the specified pose and all other fields initialized + to their default values. + + \param [in] pose The initial pose of the actor. Must be a valid transform. + + \see PxRigidDynamic + */ + virtual PxRigidDynamic* createRigidDynamic(const PxTransform& pose) = 0; + + /** + \brief Creates a pruning structure from actors. + + \note Every provided actor needs at least one shape with the eSCENE_QUERY_SHAPE flag set. + \note Both static and dynamic actors can be provided. + \note It is not allowed to pass in actors which are already part of a scene. + \note Articulation links cannot be provided. + + \param [in] actors Array of actors to add to the pruning structure. Must be non NULL. + \param [in] nbActors Number of actors in the array. Must be >0. + \return Pruning structure created from given actors, or NULL if any of the actors did not comply with the above requirements. + \see PxActor PxPruningStructure + */ + virtual PxPruningStructure* createPruningStructure(PxRigidActor*const* actors, PxU32 nbActors) = 0; + + //\} + /** \name Shapes + */ + //\{ + + /** + \brief Creates a shape which may be attached to multiple actors + + The shape will be created with a reference count of 1. + + \param [in] geometry The geometry for the shape + \param [in] material The material for the shape + \param [in] isExclusive Whether this shape is exclusive to a single actor or maybe be shared + \param [in] shapeFlags The PxShapeFlags to be set + \return The shape + + \note Shared shapes are not mutable when they are attached to an actor + + \see PxShape + */ + PX_FORCE_INLINE PxShape* createShape( const PxGeometry& geometry, + const PxMaterial& material, + bool isExclusive = false, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) + { + PxMaterial* materialPtr = const_cast(&material); + return createShape(geometry, &materialPtr, 1, isExclusive, shapeFlags); + } + + /** + \brief Creates a shape which may be attached to exactly one deformable volume actor + + The shape will be created with a reference count of 1. + + \param [in] geometry The geometry for the shape + \param [in] material The material for the shape + \param [in] isExclusive Whether this shape is exclusive to a single actor or maybe be shared + \param [in] shapeFlags The PxShapeFlags to be set + \return The shape + + \note Shared shapes are not mutable when they are attached to an actor + + \see PxShape + */ + PX_FORCE_INLINE PxShape* createShape( const PxGeometry& geometry, + const PxDeformableVolumeMaterial& material, + bool isExclusive = false, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) + { + PxDeformableVolumeMaterial* materialPtr = const_cast(&material); + return createShape(geometry, &materialPtr, 1, isExclusive, shapeFlags); + } + + /** + \brief Creates a shape which may be attached to exactly one deformable surface actor + + The shape will be created with a reference count of 1. + + \param [in] geometry The geometry for the shape + \param [in] material The material for the shape + \param [in] isExclusive Whether this shape is exclusive to a single actor or maybe be shared + \param [in] shapeFlags The PxShapeFlags to be set + \return The shape + + \note Shared shapes are not mutable when they are attached to an actor + + \see PxShape + */ + PX_FORCE_INLINE PxShape* createShape( const PxGeometry& geometry, + const PxDeformableSurfaceMaterial& material, + bool isExclusive = false, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) + { + PxDeformableSurfaceMaterial* materialPtr = const_cast(&material); + return createShape(geometry, &materialPtr, 1, isExclusive, shapeFlags); + } + + /** + \brief Creates a shape which may be attached to multiple actors + + The shape will be created with a reference count of 1. + + \param [in] geometry The geometry for the shape + \param [in] materials The materials for the shape + \param [in] materialCount The number of materials + \param [in] isExclusive Whether this shape is exclusive to a single actor or may be shared + \param [in] shapeFlags The PxShapeFlags to be set + \return The shape + + \note Shared shapes are not mutable when they are attached to an actor + \note Shapes created from *SDF* triangle-mesh geometries do not support more than one material. + + \see PxShape + */ + virtual PxShape* createShape( const PxGeometry& geometry, + PxMaterial*const * materials, + PxU16 materialCount, + bool isExclusive = false, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) = 0; + + virtual PxShape* createShape( const PxGeometry& geometry, + PxDeformableSurfaceMaterial*const * materials, + PxU16 materialCount, + bool isExclusive = false, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) = 0; + + virtual PxShape* createShape( const PxGeometry& geometry, + PxDeformableVolumeMaterial*const * materials, + PxU16 materialCount, + bool isExclusive = false, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) = 0; + + /** + \brief Return the number of shapes that currently exist. + + \return Number of shapes. + + \see getShapes() + */ + virtual PxU32 getNbShapes() const = 0; + + /** + \brief Writes the array of shape pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the shapes in the array is not specified. + + \param [out] userBuffer The buffer to receive shape pointers. + \param [in] bufferSize The number of shape pointers which can be stored in the buffer. + \param [in] startIndex Index of first shape pointer to be retrieved + \return The number of shape pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbShapes() PxShape + */ + virtual PxU32 getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Constraints and Articulations + */ + //\{ + + /** + \brief Creates a constraint shader. + + \note A constraint shader will get added automatically to the scene the two linked actors belong to. Either, but not both, of actor0 and actor1 may + be NULL to denote attachment to the world. + + \param [in] actor0 The first actor + \param [in] actor1 The second actor + \param [in] connector The connector object, which the SDK uses to communicate with the infrastructure for the constraint + \param [in] shaders The shader functions for the constraint + \param [in] dataSize The size of the data block for the shader + + \return The new constraint shader. + + \see PxConstraint + */ + virtual PxConstraint* createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) = 0; + + /** + \brief Return the number of constraints that currently exist. + + \return Number of constraints. + */ + virtual PxU32 getNbConstraints() const = 0; + + /** + \brief Creates a reduced-coordinate articulation with all fields initialized to their default values. + + \return the new articulation + + \see PxArticulationReducedCoordinate + */ + virtual PxArticulationReducedCoordinate* createArticulationReducedCoordinate() = 0; + + /** + \brief Return the number of articulations that currently exist. + + \return Number of articulations. + */ + virtual PxU32 getNbArticulations() const = 0; + + //\} + /** \name Misc + */ + //\{ + + /** + \brief Creates an attachment between two actors, based on the provided PxDeformableAttachmentData. At least one of the actors must be a deformable. + + An attachment is a collection of one or more positional constraints between a point on one actor and a point on another actor. + Attachments between two rigid objects are not permitted, use joints instead. + + \note The attachment is only active when both actors are added to the same scene or one of the actors is NULL. + + \param[in] data Attachment data. + \return The PxDeformableAttachment created if successful, NULL otherwise. + \see PxDeformableAttachmentData, PxDeformableAttachment + */ + virtual PxDeformableAttachment* createDeformableAttachment(const PxDeformableAttachmentData& data) = 0; + + /** + \brief Creates an element-level collision filter between two actors, based on the provided PxDeformableElementFilterData. At least one of the actors must be a deformable. + + Element filters define how parts of deformable actors are excluded from collisions. + They are usually added to avoid conflicting attachment and contact constraints. + + \note The element filter is only active when both actors are added to the same scene or one of the actors is NULL. + + \param[in] data Element filter data. + \return The PxDeformableElementFilter created if successful, NULL otherwise. + \see PxDeformableElementFilterData, PxDeformableElementFilter + */ + virtual PxDeformableElementFilter* createDeformableElementFilter(const PxDeformableElementFilterData& data) = 0; + + /** + \brief Creates a deformable surface with all fields initialized to their default values. + + \param[in] cudaContextManager The PxCudaContextManager this instance is tied to. + \return the new deformable surface + + \see PxDeformableSurface + */ + virtual PxDeformableSurface* createDeformableSurface(PxCudaContextManager& cudaContextManager) = 0; + + /** + \brief Creates a FEM-based deformable volume with all fields initialized to their default values. + + \param[in] cudaContextManager The PxCudaContextManager this instance is tied to. + \return the new deformable volume + + \see PxDeformableVolume + */ + virtual PxDeformableVolume* createDeformableVolume(PxCudaContextManager& cudaContextManager) = 0; + + /** + \brief Deprecated + \see createDeformableVolume + */ + PX_DEPRECATED PX_FORCE_INLINE PxDeformableVolume* createSoftBody(PxCudaContextManager& cudaContextManager) + { + return createDeformableVolume(cudaContextManager); + } + + /** + \brief Creates a particle system with a position-based dynamics (PBD) solver. + + A PBD particle system can be used to simulate particle systems with fluid and granular particles. It also allows simulating cloth using + mass-spring constraints and rigid bodies by shape matching the bodies with particles. + + In order to accelerate neighborhood finding for particle-particle interactions (e.g.: for fluid density constraints) a regular grid is used. + This grid is built every time step but may provide inaccurate neighborhood information during the solver iterations. The neighborhood scale + parameter can be used to configure the grid such that it provides a more conservative neighborhood at the cost of run-time performance. + The grid cell width is defined as 2*particleContactOffset*neighborhoodScale. \see PxParticleSystem::setParticleContactOffset. + The neighborhood scale parameter should typically not be much larger than 1. + + The maxNeighborhood defines how many particles fit into the neighborhood, at the cost of memory. + + Both maxNeighborhood and neighborhoodScale should be set as low as possible for performance, but high enough to not cause any behavioral degredation. + + \param[in] cudaContextManager The PxCudaContextManager this instance is tied to. + \param[in] maxNeighborhood The maximum number of particles considered in neighborhood-based particle interaction calculations. + \param[in] neighborhoodScale Scale applied to the particle contact offset used to define the particle neighborhood size spatially. Range: (1.0, PX_MAX_F32) + \return the new particle system + + \see PxPBDParticleSystem + */ + virtual PxPBDParticleSystem* createPBDParticleSystem(PxCudaContextManager& cudaContextManager, PxU32 maxNeighborhood = 96, PxReal neighborhoodScale = 1.01f) = 0; + + /** + \brief Create particle buffer to simulate fluid/granular material. + + \param[in] maxParticles The maximum number of particles in this buffer. + \param[in] maxVolumes The maximum number of volumes in this buffer. See PxParticleVolume. + \param[in] cudaContextManager The PxCudaContextManager this buffer is tied to. + \return PxParticleBuffer instance + + \see PxParticleBuffer + */ + virtual PxParticleBuffer* createParticleBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager) = 0; + + /** + \brief Create a particle buffer for fluid dynamics with diffuse particles. Diffuse particles are used to simulate fluid effects + such as foam, spray and bubbles. + + \param[in] maxParticles The maximum number of particles in this buffer. + \param[in] maxVolumes The maximum number of volumes in this buffer. See #PxParticleVolume. + \param[in] maxDiffuseParticles The max number of diffuse particles int this buffer. + \param[in] cudaContextManager The PxCudaContextManager this buffer is tied to. + \return PxParticleAndDiffuseBuffer instance + + \see PxParticleAndDiffuseBuffer, PxDiffuseParticleParams + */ + virtual PxParticleAndDiffuseBuffer* createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager) = 0; + + /** + \brief Create a particle buffer to simulate particle cloth. + + \param[in] maxParticles The maximum number of particles in this buffer. + \param[in] maxNumVolumes The maximum number of volumes in this buffer. See #PxParticleVolume. + \param[in] maxNumCloths The maximum number of cloths in this buffer. See #PxParticleCloth. + \param[in] maxNumTriangles The maximum number of triangles for aerodynamics. + \param[in] maxNumSprings The maximum number of springs to connect particles. See #PxParticleSpring. + \param[in] cudaContextManager The PxCudaContextManager this buffer is tied to. + \return PxParticleClothBuffer instance + + \see PxParticleClothBuffer + */ + virtual PxParticleClothBuffer* createParticleClothBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager) = 0; + + /** + \brief Create a particle buffer to simulate rigid bodies using shape matching with particles. + + \param[in] maxParticles The maximum number of particles in this buffer. + \param[in] maxNumVolumes The maximum number of volumes in this buffer. See #PxParticleVolume. + \param[in] maxNumRigids The maximum number of rigid bodies this buffer is used to simulate. + \param[in] cudaContextManager The PxCudaContextManager this buffer is tied to. + \return PxParticleRigidBuffer instance + + \see PxParticleRigidBuffer + */ + virtual PxParticleRigidBuffer* createParticleRigidBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager) = 0; + + //\} + /** \name Materials + */ + //\{ + + /** + \brief Creates a new rigid body material with certain default properties. + + \return The new rigid body material. + + \param [in] staticFriction The coefficient of static friction + \param [in] dynamicFriction The coefficient of dynamic friction + \param [in] restitution The coefficient of restitution (if in range [0,1]) or the spring stiffness for compliant contact (if in range (-PX_MAX_REAL, 0)) + + \see PxMaterial + */ + virtual PxMaterial* createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution) = 0; + + /** + \brief Return the number of rigid body materials that currently exist. + + \return Number of rigid body materials. + + \see getMaterials() + */ + virtual PxU32 getNbMaterials() const = 0; + + /** + \brief Writes the array of rigid body material pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the materials in the array is not specified. + + \param [out] userBuffer The buffer to receive material pointers. + \param [in] bufferSize The number of material pointers which can be stored in the buffer. + \param [in] startIndex Index of first material pointer to be retrieved. + \return The number of material pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbMaterials() PxMaterial + */ + virtual PxU32 getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Creates a new surface deformable material with certain default properties. + + \return The new surface deformable material. + + \param [in] youngs The young's modulus + \param [in] poissons The poissons's ratio + \param [in] dynamicFriction The dynamic friction coefficient + \param [in] thickness The thickness of the surface + \param [in] bendingStiffness The bending stiffness of the surface + \param [in] elasticityDamping The damping of the surface with respect to stretch and shear + \param [in] bendingDamping The damping of the surface with respect to bending + + \see PxDeformableSurfaceMaterial + */ + virtual PxDeformableSurfaceMaterial* createDeformableSurfaceMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, + PxReal thickness = 0.001f, PxReal bendingStiffness = 0.0f, PxReal elasticityDamping = 0.0f, PxReal bendingDamping = 0.0f) = 0; + + /** + \brief Return the number of deformable surface materials that currently exist. + + \return Number of deformable surface materials. + + \see getDeformableSurfaceMaterials() + */ + virtual PxU32 getNbDeformableSurfaceMaterials() const = 0; + + /** + \brief Writes the array of deformable surface material pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the materials in the array is not specified. + + \param [out] userBuffer The buffer to receive material pointers. + \param [in] bufferSize The number of material pointers which can be stored in the buffer. + \param [in] startIndex Index of first material pointer to be retrieved. + \return The number of material pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbDeformableSurfaceMaterials() PxDeformableSurfaceMaterial + */ + virtual PxU32 getDeformableSurfaceMaterials(PxDeformableSurfaceMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Creates a new deformable volume material with certain default properties. + + \return The new deformable volume material. + + \param [in] youngs The young's modulus + \param [in] poissons The poissons's ratio + \param [in] dynamicFriction The dynamic friction coefficient + \param [in] elasticityDamping The elasticity damping + + \see PxDeformableVolumeMaterial + */ + virtual PxDeformableVolumeMaterial* createDeformableVolumeMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, PxReal elasticityDamping = 0.0f) = 0; + + /** + \brief Deprecated + \see createDeformableVolumeMaterial + */ + PX_DEPRECATED PX_FORCE_INLINE PxDeformableVolumeMaterial* createFEMSoftBodyMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction) + { + return createDeformableVolumeMaterial(youngs, poissons, dynamicFriction); + } + + /** + \brief Return the number of deformable volume materials that currently exist. + + \return Number of materials. + + \see getDeformableVolumeMaterials() + */ + virtual PxU32 getNbDeformableVolumeMaterials() const = 0; + + /** + \brief Deprecated + \see getNbDeformableVolumeMaterials + */ + PX_DEPRECATED PX_FORCE_INLINE PxU32 getNbFEMSoftBodyMaterials() const + { + return getNbDeformableVolumeMaterials(); + } + + /** + \brief Writes the array of deformable volume material pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the materials in the array is not specified. + + \param [out] userBuffer The buffer to receive material pointers. + \param [in] bufferSize The number of material pointers which can be stored in the buffer. + \param [in] startIndex Index of first material pointer to be retrieved. + \return The number of material pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbDeformableVolumeMaterials() PxDeformableVolumeMaterial + */ + virtual PxU32 getDeformableVolumeMaterials(PxDeformableVolumeMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Deprecated + \see getDeformableVolumeMaterials + */ + PX_DEPRECATED PX_FORCE_INLINE PxU32 getFEMSoftBodyMaterials(PxDeformableVolumeMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const + { + return getDeformableVolumeMaterials(userBuffer, bufferSize, startIndex); + } + + /** + \brief Creates a new PBD material with certain default properties. + + \param [in] friction The friction parameter + \param [in] damping The velocity damping parameter + \param [in] adhesion The adhesion parameter + \param [in] viscosity The viscosity parameter + \param [in] vorticityConfinement The vorticity confinement coefficient + \param [in] surfaceTension The surface tension coefficient + \param [in] cohesion The cohesion parameter + \param [in] lift The lift parameter + \param [in] drag The drag parameter + \param [in] cflCoefficient The Courant-Friedrichs-Lewy(cfl) coefficient + \param [in] gravityScale The gravity scale + \return The new PBD material. + + \see PxPBDMaterial + */ + virtual PxPBDMaterial* createPBDMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal vorticityConfinement, PxReal surfaceTension, PxReal cohesion, PxReal lift, PxReal drag, PxReal cflCoefficient = 1.f, PxReal gravityScale = 1.f) = 0; + + /** + \brief Return the number of PBD materials that currently exist. + + \return Number of PBD materials. + + \see getPBDMaterials() + */ + virtual PxU32 getNbPBDMaterials() const = 0; + + /** + \brief Writes the array of PBD material pointers to a user buffer. + + Returns the number of pointers written. + + The ordering of the materials in the array is not specified. + + \param [out] userBuffer The buffer to receive material pointers. + \param [in] bufferSize The number of material pointers which can be stored in the buffer. + \param [in] startIndex Index of first material pointer to be retrieved. + \return The number of material pointers written to userBuffer, this should be less or equal to bufferSize. + + \see getNbPBDMaterials() PxPBDMaterial + */ + virtual PxU32 getPBDMaterials(PxPBDMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + //\} + /** \name Deletion Listeners + */ + //\{ + + /** + \brief Register a deletion listener. Listeners will be called whenever an object is deleted. + + It is illegal to register or unregister a deletion listener while deletions are being processed. + + \note By default a registered listener will receive events from all objects. Set the restrictedObjectSet parameter to true on registration and use #registerDeletionListenerObjects to restrict the received events to specific objects. + + \note The deletion events are only supported on core PhysX objects. In general, objects in extension modules do not provide this functionality, however, in the case of PxJoint objects, the underlying PxConstraint will send the events. + + \param [in] observer Observer object to send notifications to. + \param [in] deletionEvents The deletion event types to get notified of. + \param [in] restrictedObjectSet If false, the deletion listener will get events from all objects, else the objects to receive events from have to be specified explicitly through #registerDeletionListenerObjects. + + \see PxDeletionListener unregisterDeletionListener + */ + virtual void registerDeletionListener(PxDeletionListener& observer, const PxDeletionEventFlags& deletionEvents, bool restrictedObjectSet = false) = 0; + + /** + \brief Unregister a deletion listener. + + It is illegal to register or unregister a deletion listener while deletions are being processed. + + \param [in] observer Observer object to stop sending notifications to. + + \see PxDeletionListener registerDeletionListener + */ + virtual void unregisterDeletionListener(PxDeletionListener& observer) = 0; + + /** + \brief Register specific objects for deletion events. + + This method allows for a deletion listener to limit deletion events to specific objects only. + + \note It is illegal to register or unregister objects while deletions are being processed. + + \note The deletion listener has to be registered through #registerDeletionListener() and configured to support restricted object sets prior to this method being used. + + \param [in] observer Observer object to send notifications to. + \param [in] observables List of objects for which to receive deletion events. Only PhysX core objects are supported. In the case of PxJoint objects, the underlying PxConstraint can be used to get the events. + \param [in] observableCount Size of the observables list. + + \see PxDeletionListener unregisterDeletionListenerObjects + */ + virtual void registerDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) = 0; + + /** + \brief Unregister specific objects for deletion events. + + This method allows to clear previously registered objects for a deletion listener (see #registerDeletionListenerObjects()). + + \note It is illegal to register or unregister objects while deletions are being processed. + + \note The deletion listener has to be registered through #registerDeletionListener() and configured to support restricted object sets prior to this method being used. + + \param [in] observer Observer object to stop sending notifications to. + \param [in] observables List of objects for which to not receive deletion events anymore. + \param [in] observableCount Size of the observables list. + + \see PxDeletionListener registerDeletionListenerObjects + */ + virtual void unregisterDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) = 0; + + //\} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** +\brief Creates an instance of the physics SDK. + +Creates an instance of this class. May not be a class member to avoid name mangling. +Pass the constant #PX_PHYSICS_VERSION as the argument. +There may be only one instance of this class per process. Calling this method after an instance +has been created already will result in an error message and NULL will be returned. + +\param version Version number we are expecting (should be #PX_PHYSICS_VERSION) +\param foundation Foundation instance (see PxFoundation) +\param scale values used to determine default tolerances for objects at creation time +\param trackOutstandingAllocations true if you want to track memory allocations + so a debugger connection partway through your physics simulation will get + an accurate map of everything that has been allocated so far. This could have a memory + and performance impact on your simulation hence it defaults to off. +\param pvd When pvd points to a valid PxPvd instance (PhysX Visual Debugger), a connection to the specified PxPvd instance is created. + If pvd is NULL no connection will be attempted. +\param omniPvd When omniPvd points to a valid PxOmniPvd instance PhysX will sample its internal structures to the defined OmniPvd output streams + set in the PxOmniPvd object. +\return PxPhysics instance on success, NULL if operation failed + +\see PxPhysics +*/ +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxPhysics* PxCreatePhysics(physx::PxU32 version, + physx::PxFoundation& foundation, + const physx::PxTolerancesScale& scale, + bool trackOutstandingAllocations = false, + physx::PxPvd* pvd = NULL, + physx::PxOmniPvd* omniPvd = NULL); + +/** +\brief Retrieves the Physics SDK after it has been created. + +Before using this function the user must call #PxCreatePhysics(). + +\note The behavior of this method is undefined if the Physics SDK instance has not been created already. +*/ +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreturn-type-c-linkage" +#endif + +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxPhysics& PX_CALL_CONV PxGetPhysics(); + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxPhysicsAPI.h b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysicsAPI.h new file mode 100644 index 000000000..9a7f41f3e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysicsAPI.h @@ -0,0 +1,225 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSICS_API_H +#define PX_PHYSICS_API_H + +/** +This is the main include header for the Physics SDK, for users who +want to use a single #include file. + +Alternatively, one can instead directly #include a subset of the below files. +*/ + +// Foundation SDK +#include "foundation/PxAlignedMalloc.h" +#include "foundation/PxAlloca.h" +#include "foundation/PxAllocatorCallback.h" +#include "foundation/PxArray.h" +#include "foundation/PxAssert.h" +#include "foundation/PxAtomic.h" +#include "foundation/PxBasicTemplates.h" +#include "foundation/PxBitAndData.h" +#include "foundation/PxBitMap.h" +#include "foundation/PxBitUtils.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxBroadcast.h" +#include "foundation/PxConstructor.h" +#include "foundation/PxErrorCallback.h" +#include "foundation/PxErrors.h" +#include "foundation/PxFlags.h" +#include "foundation/PxFoundation.h" +#include "foundation/PxFoundationConfig.h" +#include "foundation/PxFPU.h" +#include "foundation/PxHash.h" +#include "foundation/PxHashMap.h" +#include "foundation/PxHashSet.h" +#include "foundation/PxInlineAllocator.h" +#include "foundation/PxInlineArray.h" +#include "foundation/PxIntrinsics.h" +#include "foundation/PxIO.h" +#include "foundation/PxMat33.h" +#include "foundation/PxMat44.h" +#include "foundation/PxMath.h" +#include "foundation/PxMathIntrinsics.h" +#include "foundation/PxMathUtils.h" +#include "foundation/PxMemory.h" +#include "foundation/PxMutex.h" +#include "foundation/PxPhysicsVersion.h" +#include "foundation/PxPlane.h" +#include "foundation/PxPool.h" +#include "foundation/PxPreprocessor.h" +#include "foundation/PxProfiler.h" +#include "foundation/PxQuat.h" +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxSList.h" +#include "foundation/PxSocket.h" +#include "foundation/PxSort.h" +#include "foundation/PxStrideIterator.h" +#include "foundation/PxString.h" +#include "foundation/PxSync.h" +#include "foundation/PxTempAllocator.h" +#include "foundation/PxThread.h" +#include "foundation/PxTime.h" +#include "foundation/PxTransform.h" +#include "foundation/PxUnionCast.h" +#include "foundation/PxUserAllocated.h" +#include "foundation/PxUtilities.h" +#include "foundation/PxVec2.h" +#include "foundation/PxVec3.h" +#include "foundation/PxVec4.h" +#include "foundation/PxVecMath.h" +#include "foundation/PxVecQuat.h" +#include "foundation/PxVecTransform.h" + + +//Not physics specific utilities and common code +#include "common/PxCoreUtilityTypes.h" +#include "common/PxPhysXCommonConfig.h" +#include "common/PxRenderBuffer.h" +#include "common/PxBase.h" +#include "common/PxTolerancesScale.h" +#include "common/PxTypeInfo.h" +#include "common/PxStringTable.h" +#include "common/PxSerializer.h" +#include "common/PxSerialFramework.h" +#include "common/PxInsertionCallback.h" + +//Task Manager +#include "task/PxTask.h" + +// Cuda Mananger +#if PX_SUPPORT_GPU_PHYSX +#include "gpu/PxGpu.h" +#endif + +//Geometry Library +#include "geometry/PxBoxGeometry.h" +#include "geometry/PxBVH.h" +#include "geometry/PxBVHBuildStrategy.h" +#include "geometry/PxCapsuleGeometry.h" +#include "geometry/PxConvexMesh.h" +#include "geometry/PxConvexMeshGeometry.h" +#include "geometry/PxGeometry.h" +#include "geometry/PxGeometryHelpers.h" +#include "geometry/PxGeometryQuery.h" +#include "geometry/PxHeightField.h" +#include "geometry/PxHeightFieldDesc.h" +#include "geometry/PxHeightFieldFlag.h" +#include "geometry/PxHeightFieldGeometry.h" +#include "geometry/PxHeightFieldSample.h" +#include "geometry/PxMeshQuery.h" +#include "geometry/PxMeshScale.h" +#include "geometry/PxPlaneGeometry.h" +#include "geometry/PxSimpleTriangleMesh.h" +#include "geometry/PxSphereGeometry.h" +#include "geometry/PxTriangle.h" +#include "geometry/PxTriangleMesh.h" +#include "geometry/PxTriangleMeshGeometry.h" +#include "geometry/PxTetrahedron.h" +#include "geometry/PxTetrahedronMesh.h" +#include "geometry/PxTetrahedronMeshGeometry.h" + +// PhysX Core SDK +#include "PxActor.h" +#include "PxAggregate.h" +#include "PxArticulationReducedCoordinate.h" +#include "PxArticulationJointReducedCoordinate.h" +#include "PxArticulationLink.h" +#include "PxClient.h" +#include "PxConeLimitedConstraint.h" +#include "PxConstraint.h" +#include "PxConstraintDesc.h" +#include "PxContact.h" +#include "PxContactModifyCallback.h" +#include "PxDeformableSurface.h" +#include "PxDeformableSurfaceMaterial.h" +#include "PxDeformableVolume.h" +#include "PxDeformableVolumeMaterial.h" +#include "PxDeletionListener.h" +#include "PxFEMSoftBodyMaterial.h" // deprecated, include PxDeformableVolumeMaterial.h +#include "PxFiltering.h" +#include "PxForceMode.h" +#include "PxLockedData.h" +#include "PxMaterial.h" +#include "PxParticleBuffer.h" +#include "PxParticleSystem.h" +#include "PxPBDParticleSystem.h" +#include "PxPBDMaterial.h" +#include "PxPhysics.h" +#include "PxPhysXConfig.h" +#include "PxQueryFiltering.h" +#include "PxQueryReport.h" +#include "PxRigidActor.h" +#include "PxRigidBody.h" +#include "PxRigidDynamic.h" +#include "PxRigidStatic.h" +#include "PxScene.h" +#include "PxSceneDesc.h" +#include "PxSceneLock.h" +#include "PxShape.h" +#include "PxSimulationEventCallback.h" +#include "PxSimulationStatistics.h" +#include "PxSoftBody.h" //deprecated, include PxDeformableVolume.h +#include "PxVisualizationParameter.h" +#include "PxPruningStructure.h" + +//Character Controller +#include "characterkinematic/PxBoxController.h" +#include "characterkinematic/PxCapsuleController.h" +#include "characterkinematic/PxController.h" +#include "characterkinematic/PxControllerBehavior.h" +#include "characterkinematic/PxControllerManager.h" +#include "characterkinematic/PxControllerObstacles.h" +#include "characterkinematic/PxExtended.h" + +//Cooking (data preprocessing) +#include "cooking/Pxc.h" +#include "cooking/PxConvexMeshDesc.h" +#include "cooking/PxCooking.h" +#include "cooking/PxTriangleMeshDesc.h" +#include "cooking/PxBVH33MidphaseDesc.h" +#include "cooking/PxBVH34MidphaseDesc.h" +#include "cooking/PxMidphaseDesc.h" + +//Extensions to the SDK +#include "extensions/PxDefaultStreams.h" +#include "extensions/PxExtensionsAPI.h" + +//Serialization +#include "extensions/PxSerialization.h" +#include "extensions/PxRepXSerializer.h" + +//Vehicle Simulation +#include "vehicle2/PxVehicleAPI.h" + +//Connecting the SDK to Visual Debugger +#include "pvd/PxPvdSceneClient.h" +#include "pvd/PxPvd.h" +#include "pvd/PxPvdTransport.h" +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxPhysicsSerialization.h b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysicsSerialization.h new file mode 100644 index 000000000..ae623c0e6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxPhysicsSerialization.h @@ -0,0 +1,67 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSICS_SERIALIZATION_H +#define PX_PHYSICS_SERIALIZATION_H + +#include "common/PxSerialFramework.h" +#include "PxPhysXConfig.h" + +#if !PX_DOXYGEN + +/** +\brief Registers physics classes for serialization. +This function is used to implement PxSerialization.createSerializationRegistry() and is not intended to be needed otherwise. +\see PxSerializationRegistry +*/ +PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxRegisterPhysicsSerializers(physx::PxSerializationRegistry& sr); + +/** +\brief Unregisters physics classes for serialization. +This function is used in the release implementation of PxSerializationRegistry and in not intended to be used otherwise. +\see PxSerializationRegistry +*/ +PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxUnregisterPhysicsSerializers(physx::PxSerializationRegistry& sr); + + +/** +\brief Adds collected objects to PxPhysics. + +This function adds all objects contained in the input collection to the PxPhysics instance. This is used after deserializing +the collection, to populate the physics with inplace deserialized objects. This function is used in the implementation of +PxSerialization.createCollectionFromBinary and is not intended to be needed otherwise. +\param[in] collection Objects to add to the PxPhysics instance. + +\see PxCollection, PxSerialization.createCollectionFromBinary +*/ +PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxAddCollectionToPhysics(const physx::PxCollection& collection); + +#endif // !PX_DOXYGEN + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxPruningStructure.h b/Jusin154_Team3D/Engine/Public/PhysX/PxPruningStructure.h new file mode 100644 index 000000000..b0a950fb4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxPruningStructure.h @@ -0,0 +1,129 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PRUNING_STRUCTURE_H +#define PX_PRUNING_STRUCTURE_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + +/** +\brief A precomputed pruning structure to accelerate scene queries against newly added actors. + +The pruning structure can be provided to #PxScene:: addActors() in which case it will get merged +directly into the scene query optimization AABB tree, thus leading to improved performance when +doing queries against the newly added actors. This applies to both static and dynamic actors. + +\note PxPruningStructure objects can be added to a collection and get serialized. +\note Adding a PxPruningStructure object to a collection will also add the actors that were used to build the pruning structure. + +\note PxPruningStructure must be released before its rigid actors. +\note PxRigidBody objects can be in one PxPruningStructure only. +\note Changing the bounds of PxRigidBody objects assigned to a pruning structure that has not been added to a scene yet will +invalidate the pruning structure. Same happens if shape scene query flags change or shape gets removed from an actor. + +\see PxScene::addActors PxCollection +*/ +class PxPruningStructure : public PxBase +{ +public: + /** + \brief Release this object. + */ + virtual void release() = 0; + + /** + \brief Retrieve rigid actors in the pruning structure. + + You can retrieve the number of rigid actor pointers by calling #getNbRigidActors() + + \param[out] userBuffer The buffer to store the actor pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first actor pointer to be retrieved + \return Number of rigid actor pointers written to the buffer. + + \see PxRigidActor + */ + virtual PxU32 getRigidActors(PxRigidActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Returns the number of rigid actors in the pruning structure. + + You can use #getRigidActors() to retrieve the rigid actor pointers. + + \return Number of rigid actors in the pruning structure. + + \see PxRigidActor + */ + virtual PxU32 getNbRigidActors() const = 0; + + /** + \brief Gets the merge data for static actors + + This is mainly called by the PxSceneQuerySystem::merge() function to merge a PxPruningStructure + with the internal data-structures of the scene-query system. + + \return Implementation-dependent merge data for static actors. + + \see PxSceneQuerySystem::merge() + */ + virtual const void* getStaticMergeData() const = 0; + + /** + \brief Gets the merge data for dynamic actors + + This is mainly called by the PxSceneQuerySystem::merge() function to merge a PxPruningStructure + with the internal data-structures of the scene-query system. + + \return Implementation-dependent merge data for dynamic actors. + + \see PxSceneQuerySystem::merge() + */ + virtual const void* getDynamicMergeData() const = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxPruningStructure"; } +protected: + PX_INLINE PxPruningStructure(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxPruningStructure(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + virtual ~PxPruningStructure() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxPruningStructure", PxBase); } +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxQueryFiltering.h b/Jusin154_Team3D/Engine/Public/PhysX/PxQueryFiltering.h new file mode 100644 index 000000000..97c200c36 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxQueryFiltering.h @@ -0,0 +1,208 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_QUERY_FILTERING_H +#define PX_QUERY_FILTERING_H + +#include "PxPhysXConfig.h" +#include "PxFiltering.h" +#include "PxQueryReport.h" +#include "PxClient.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxShape; +class PxRigidActor; +struct PxQueryHit; + +/** +\brief Filtering flags for scene queries. + +\see PxQueryFilterData.flags +*/ +struct PxQueryFlag +{ + enum Enum + { + eSTATIC = (1<<0), //!< Traverse static shapes + + eDYNAMIC = (1<<1), //!< Traverse dynamic shapes + + ePREFILTER = (1<<2), //!< Run the pre-intersection-test filter (see #PxQueryFilterCallback::preFilter()) + + ePOSTFILTER = (1<<3), //!< Run the post-intersection-test filter (see #PxQueryFilterCallback::postFilter()) + + eANY_HIT = (1<<4), //!< Abort traversal as soon as any hit is found and return it via callback.block. + //!< Helps query performance. Both eTOUCH and eBLOCK hitTypes are considered hits with this flag. + + eNO_BLOCK = (1<<5), //!< All hits are reported as touching. Overrides eBLOCK returned from user filters with eTOUCH. + //!< This is also an optimization hint that may improve query performance. + + eBATCH_QUERY_LEGACY_BEHAVIOUR = (1<<6), //!< Run with legacy batch query filter behavior. Raising this flag ensures that + //!< the hardcoded filter equation is neglected. This guarantees that any provided PxQueryFilterCallback + //!< will be utilised, as specified by the ePREFILTER and ePOSTFILTER flags. + + eDISABLE_HARDCODED_FILTER = (1<<6), //!< Same as eBATCH_QUERY_LEGACY_BEHAVIOUR, more explicit name making it clearer that this can also be used + //!< with regular/non-batched queries if needed. + + eRESERVED = (1<<15) //!< Reserved for internal use + }; +}; +PX_COMPILE_TIME_ASSERT(PxQueryFlag::eSTATIC==(1<<0)); +PX_COMPILE_TIME_ASSERT(PxQueryFlag::eDYNAMIC==(1<<1)); +PX_COMPILE_TIME_ASSERT(PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR==PxQueryFlag::eDISABLE_HARDCODED_FILTER); + +/** +\brief Flags typedef for the set of bits defined in PxQueryFlag. + +*/ +typedef PxFlags PxQueryFlags; +PX_FLAGS_OPERATORS(PxQueryFlag::Enum,PxU16) + +/** +\brief Classification of scene query hits (intersections). + + - eNONE: Returning this hit type means that the hit should not be reported. + - eBLOCK: For all raycast, sweep and overlap queries the nearest eBLOCK type hit will always be returned in PxHitCallback::block member. + - eTOUCH: Whenever a raycast, sweep or overlap query was called with non-zero PxHitCallback::nbTouches and PxHitCallback::touches + parameters, eTOUCH type hits that are closer or same distance (touchDistance <= blockDistance condition) + as the globally nearest eBLOCK type hit, will be reported. + - For example, to record all hits from a raycast query, always return eTOUCH. + +All hits in overlap() queries are treated as if the intersection distance were zero. +This means the hits are unsorted and all eTOUCH hits are recorded by the callback even if an eBLOCK overlap hit was encountered. +Even though all overlap() blocking hits have zero length, only one (arbitrary) eBLOCK overlap hit is recorded in PxHitCallback::block. +All overlap() eTOUCH type hits are reported (zero touchDistance <= zero blockDistance condition). + +For raycast/sweep/overlap calls with zero touch buffer or PxHitCallback::nbTouches member, +only the closest hit of type eBLOCK is returned. All eTOUCH hits are discarded. + +\see PxQueryFilterCallback.preFilter PxQueryFilterCallback.postFilter PxScene.raycast PxScene.sweep PxScene.overlap +*/ +struct PxQueryHitType +{ + enum Enum + { + eNONE = 0, //!< the query should ignore this shape + eTOUCH = 1, //!< a hit on the shape touches the intersection geometry of the query but does not block it + eBLOCK = 2 //!< a hit on the shape blocks the query (does not block overlap queries) + }; +}; + +/** +\brief Scene query filtering data. + +Whenever the scene query intersects a shape, filtering is performed in the following order: + +\li For non-batched queries only:
If the data field is non-zero, and the bitwise-AND value of data AND the shape's +queryFilterData is zero, the shape is skipped +\li If filter callbacks are enabled in flags field (see #PxQueryFlags) they will get invoked accordingly. +\li If neither #PxQueryFlag::ePREFILTER or #PxQueryFlag::ePOSTFILTER is set, the hit defaults +to type #PxQueryHitType::eBLOCK when the value of PxHitCallback::nbTouches provided with the query is zero and to type +#PxQueryHitType::eTOUCH when PxHitCallback::nbTouches is positive. + +\see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlag::eANY_HIT +*/ +struct PxQueryFilterData +{ + /** \brief default constructor */ + explicit PX_INLINE PxQueryFilterData() : flags(PxQueryFlag::eDYNAMIC | PxQueryFlag::eSTATIC) {} + + /** \brief constructor to set both filter data and filter flags */ + explicit PX_INLINE PxQueryFilterData(const PxFilterData& fd, PxQueryFlags f) : data(fd), flags(f) {} + + /** \brief constructor to set filter flags only */ + explicit PX_INLINE PxQueryFilterData(PxQueryFlags f) : flags(f) {} + + PxFilterData data; //!< Filter data associated with the scene query + PxQueryFlags flags; //!< Filter flags (see #PxQueryFlags) +}; + +/** +\brief Scene query filtering callbacks. + +Custom filtering logic for scene query intersection candidates. If an intersection candidate object passes the data based filter +(see #PxQueryFilterData), filtering callbacks are executed if requested (see #PxQueryFilterData.flags) + +\li If #PxQueryFlag::ePREFILTER is set, the preFilter function runs before exact intersection tests. +If this function returns #PxQueryHitType::eTOUCH or #PxQueryHitType::eBLOCK, exact testing is performed to +determine the intersection location. + +The preFilter function may overwrite the copy of queryFlags it receives as an argument to specify any of #PxHitFlag::eMODIFIABLE_FLAGS +on a per-shape basis. Changes apply only to the shape being filtered, and changes to other flags are ignored. + +\li If #PxQueryFlag::ePREFILTER is not set, precise intersection testing is performed using the original query's filterData.flags. + +\li If #PxQueryFlag::ePOSTFILTER is set, the postFilter function is called for each intersection to determine the touch/block status. +This overrides any touch/block status previously returned from the preFilter function for this shape. + +Filtering calls are not guaranteed to be sorted along the ray or sweep direction. + +\see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlags PxHitFlags +*/ +class PxQueryFilterCallback +{ +public: + + /** + \brief This filter callback is executed before the exact intersection test if PxQueryFlag::ePREFILTER flag was set. + + \param[in] filterData custom filter data specified as the query's filterData.data parameter. + \param[in] shape A shape that has not yet passed the exact intersection test. + \param[in] actor The shape's actor. + \param[in,out] queryFlags scene query flags from the query's function call (only flags from PxHitFlag::eMODIFIABLE_FLAGS bitmask can be modified) + \return the updated type for this hit (see #PxQueryHitType) + */ + virtual PxQueryHitType::Enum preFilter(const PxFilterData& filterData, const PxShape* shape, const PxRigidActor* actor, PxHitFlags& queryFlags) = 0; + + /** + \brief This filter callback is executed if the exact intersection test returned true and PxQueryFlag::ePOSTFILTER flag was set. + + \param[in] filterData custom filter data of the query + \param[in] hit Scene query hit information. faceIndex member is not valid for overlap queries. For sweep and raycast queries the hit information can be cast to #PxSweepHit and #PxRaycastHit respectively. + \param[in] shape Hit shape + \param[in] actor Hit actor + \return the updated hit type for this hit (see #PxQueryHitType) + */ + virtual PxQueryHitType::Enum postFilter(const PxFilterData& filterData, const PxQueryHit& hit, const PxShape* shape, const PxRigidActor* actor) = 0; + + /** + \brief virtual destructor + */ + virtual ~PxQueryFilterCallback() {} +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxQueryReport.h b/Jusin154_Team3D/Engine/Public/PhysX/PxQueryReport.h new file mode 100644 index 000000000..06e66e6dd --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxQueryReport.h @@ -0,0 +1,281 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_QUERY_REPORT_H +#define PX_QUERY_REPORT_H +#include "foundation/PxVec3.h" +#include "foundation/PxFlags.h" +#include "foundation/PxAssert.h" +#include "geometry/PxGeometryHit.h" +#include "geometry/PxGeometryQueryContext.h" +#include "PxPhysXConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxShape; +class PxRigidActor; + +/** +\brief Combines a shape pointer and the actor the shape belongs to into one memory location. + +Serves as a base class for PxQueryHit. + +\see PxQueryHit +*/ +struct PxActorShape +{ + PX_INLINE PxActorShape() : actor(NULL), shape(NULL) {} + PX_INLINE PxActorShape(PxRigidActor* a, PxShape* s) : actor(a), shape(s) {} + + PxRigidActor* actor; + PxShape* shape; +}; + +// Extends geom hits with Px object pointers +struct PxRaycastHit : PxGeomRaycastHit, PxActorShape {}; +struct PxOverlapHit : PxGeomOverlapHit, PxActorShape {}; +struct PxSweepHit : PxGeomSweepHit, PxActorShape {}; + +/** +\brief Describes query behavior after returning a partial query result via a callback. + +If callback returns true, traversal will continue and callback can be issued again. +If callback returns false, traversal will stop, callback will not be issued again. + +\see PxHitCallback +*/ +typedef bool PxAgain; + +/** +\brief This callback class facilitates reporting scene query hits (intersections) to the user. + +User overrides the virtual processTouches function to receive hits in (possibly multiple) fixed size blocks. + +\note PxHitBuffer derives from this class and is used to receive touching hits in a fixed size buffer. +\note Since the compiler doesn't look in template dependent base classes when looking for non-dependent names +\note with some compilers it will be necessary to use "this->hasBlock" notation to access a parent variable +\note in a child callback class. +\note Pre-made typedef shorthands, such as ::PxRaycastCallback can be used for raycast, overlap and sweep queries. + +\see PxHitBuffer PxRaycastHit PxSweepHit PxOverlapHit PxRaycastCallback PxOverlapCallback PxSweepCallback +*/ +template +struct PxHitCallback : PxQueryThreadContext +{ + HitType block; //!< Holds the closest blocking hit result for the query. Invalid if hasBlock is false. + bool hasBlock; //!< Set to true if there was a blocking hit during query. + + HitType* touches; //!< User specified buffer for touching hits. + + /** + \brief Size of the user specified touching hits buffer. + \note If set to 0 all hits will default to PxQueryHitType::eBLOCK, otherwise to PxQueryHitType::eTOUCH + \note Hit type returned from pre-filter overrides this default */ + PxU32 maxNbTouches; + + /** + \brief Number of touching hits returned by the query. Used with PxHitBuffer. + \note If true (PxAgain) is returned from the callback, nbTouches will be reset to 0. */ + PxU32 nbTouches; + + /** + \brief Initializes the class with user provided buffer. + + \param[in] aTouches Optional buffer for recording PxQueryHitType::eTOUCH type hits. + \param[in] aMaxNbTouches Size of touch buffer. + + \note if aTouches is NULL and aMaxNbTouches is 0, only the closest blocking hit will be recorded by the query. + \note If PxQueryFlag::eANY_HIT flag is used as a query parameter, hasBlock will be set to true and blockingHit will be used to receive the result. + \note Both eTOUCH and eBLOCK hits will be registered as hasBlock=true and stored in PxHitCallback.block when eANY_HIT flag is used. + + \see PxHitCallback.hasBlock PxHitCallback.block */ + PxHitCallback(HitType* aTouches, PxU32 aMaxNbTouches) + : hasBlock(false), touches(aTouches), maxNbTouches(aMaxNbTouches), nbTouches(0) + {} + + /** + \brief virtual callback function used to communicate query results to the user. + + This callback will always be invoked with #touches as a buffer if #touches was specified as non-NULL. + All reported touch hits are guaranteed to be closer than the closest blocking hit. + + \param[in] buffer Callback will report touch hits to the user in this buffer. This pointer will be the same as #touches. + \param[in] nbHits Number of touch hits reported in buffer. This number will not exceed #maxNbTouches. + + \note There is a significant performance penalty in case multiple touch callbacks are issued (up to 2x) + \note to avoid the penalty use a bigger buffer so that all touching hits can be reported in a single buffer. + \note If true (again) is returned from the callback, nbTouches will be reset to 0, + \note If false is returned, nbTouched will remain unchanged. + \note By the time processTouches is first called, the globally closest blocking hit is already determined, + \note values of hasBlock and block are final and all touch hits are guaranteed to be closer than the blocking hit. + \note touches and maxNbTouches can be modified inside of processTouches callback. + + \return true to continue receiving callbacks in case there are more hits or false to stop. + + \see PxAgain PxRaycastHit PxSweepHit PxOverlapHit */ + virtual PxAgain processTouches(const HitType* buffer, PxU32 nbHits) = 0; + + virtual void finalizeQuery() {} //!< Query finalization callback, called after the last processTouches callback. + + virtual ~PxHitCallback() {} + + /** \brief Returns true if any blocking or touching hits were encountered during a query. */ + PX_FORCE_INLINE bool hasAnyHits() { return (hasBlock || (nbTouches > 0)); } +}; + +/** +\brief Returns scene query hits (intersections) to the user in a preallocated buffer. + +Will clip touch hits to maximum buffer capacity. When clipped, an arbitrary subset of touching hits will be discarded. +Overflow does not trigger warnings or errors. block and hasBlock will be valid in finalizeQuery callback and after query completion. +Touching hits are guaranteed to have closer or same distance ( <= condition) as the globally nearest blocking hit at the time any processTouches() +callback is issued. + +\note Pre-made typedef shorthands, such as ::PxRaycastBuffer can be used for raycast, overlap and sweep queries. + +\see PxHitCallback +\see PxRaycastBuffer PxOverlapBuffer PxSweepBuffer PxRaycastBufferN PxOverlapBufferN PxSweepBufferN +*/ +template +struct PxHitBuffer : public PxHitCallback +{ + /** + \brief Initializes the buffer with user memory. + + The buffer is initialized with 0 touch hits by default => query will only report a single closest blocking hit. + Use PxQueryFlag::eANY_HIT to tell the query to abort and return any first hit encoutered as blocking. + + \param[in] aTouches Optional buffer for recording PxQueryHitType::eTOUCH type hits. + \param[in] aMaxNbTouches Size of touch buffer. + + \see PxHitCallback */ + PxHitBuffer(HitType* aTouches = NULL, PxU32 aMaxNbTouches = 0) : PxHitCallback(aTouches, aMaxNbTouches) {} + + /** \brief Computes the number of any hits in this result, blocking or touching. */ + PX_INLINE PxU32 getNbAnyHits() const { return getNbTouches() + PxU32(this->hasBlock); } + /** \brief Convenience iterator used to access any hits in this result, blocking or touching. */ + PX_INLINE const HitType& getAnyHit(const PxU32 index) const { PX_ASSERT(index < getNbTouches() + PxU32(this->hasBlock)); + return index < getNbTouches() ? getTouches()[index] : this->block; } + + PX_INLINE PxU32 getNbTouches() const { return this->nbTouches; } + PX_INLINE const HitType* getTouches() const { return this->touches; } + PX_INLINE const HitType& getTouch(const PxU32 index) const { PX_ASSERT(index < getNbTouches()); return getTouches()[index]; } + PX_INLINE PxU32 getMaxNbTouches() const { return this->maxNbTouches; } + + virtual ~PxHitBuffer() {} + +protected: + // stops after the first callback + virtual PxAgain processTouches(const HitType* buffer, PxU32 nbHits) { PX_UNUSED(buffer); PX_UNUSED(nbHits); return false; } +}; + +/** \brief Raycast query callback. */ +typedef PxHitCallback PxRaycastCallback; + +/** \brief Overlap query callback. */ +typedef PxHitCallback PxOverlapCallback; + +/** \brief Sweep query callback. */ +typedef PxHitCallback PxSweepCallback; + +/** \brief Raycast query buffer. */ +typedef PxHitBuffer PxRaycastBuffer; + +/** \brief Overlap query buffer. */ +typedef PxHitBuffer PxOverlapBuffer; + +/** \brief Sweep query buffer. */ +typedef PxHitBuffer PxSweepBuffer; + +/** \brief Returns touching raycast hits to the user in a fixed size array embedded in the buffer class. **/ +template +struct PxRaycastBufferN : public PxHitBuffer +{ + PxRaycastHit hits[N]; + PxRaycastBufferN() : PxHitBuffer(hits, N) {} +}; + +/** \brief Returns touching overlap hits to the user in a fixed size array embedded in the buffer class. **/ +template +struct PxOverlapBufferN : public PxHitBuffer +{ + PxOverlapHit hits[N]; + PxOverlapBufferN() : PxHitBuffer(hits, N) {} +}; + +/** \brief Returns touching sweep hits to the user in a fixed size array embedded in the buffer class. **/ +template +struct PxSweepBufferN : public PxHitBuffer +{ + PxSweepHit hits[N]; + PxSweepBufferN() : PxHitBuffer(hits, N) {} +}; + +/** +\brief single hit cache for scene queries. + +If a cache object is supplied to a scene query, the cached actor/shape pair is checked for intersection first. +\note Filters are not executed for the cached shape. +\note If intersection is found, the hit is treated as blocking. +\note Typically actor and shape from the last PxHitCallback.block query result is used as a cached actor/shape pair. +\note Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. +\note Cache is only used if no touch buffer was provided, for single nearest blocking hit queries and queries using eANY_HIT flag. +\note if non-zero touch buffer was provided, cache will be ignored + +\note It is the user's responsibility to ensure that the shape and actor are valid, so care must be taken +when deleting shapes to invalidate cached references. + +The faceIndex field is an additional hint for a mesh or height field which is not currently used. + +\see PxScene.raycast +*/ +struct PxQueryCache +{ + /** + \brief constructor sets to default + */ + PX_INLINE PxQueryCache() : shape(NULL), actor(NULL), faceIndex(0xffffffff) {} + + /** + \brief constructor to set properties + */ + PX_INLINE PxQueryCache(PxShape* s, PxU32 findex) : shape(s), actor(NULL), faceIndex(findex) {} + + PxShape* shape; //!< Shape to test for intersection first + PxRigidActor* actor; //!< Actor to which the shape belongs + PxU32 faceIndex; //!< Triangle index to test first - NOT CURRENTLY SUPPORTED +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxResidual.h b/Jusin154_Team3D/Engine/Public/PhysX/PxResidual.h new file mode 100644 index 000000000..5041ab7ad --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxResidual.h @@ -0,0 +1,83 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RESIDUAL_H +#define PX_RESIDUAL_H + +#include "PxPhysXConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Structure representing residual values. + + This struct holds residual values, typically used in physics simulations to measure error or discrepancy. + */ + struct PxResidual + { + PxReal rmsResidual; //!< Root mean square residual value. + PxReal maxResidual; //!< Maximum residual value. + + PxResidual() : rmsResidual(0.0f), maxResidual(0.0f) {} + }; + + /** + \brief Structure representing residual values + + This struct holds residual values for both position and velocity iterations. + */ + struct PxResiduals + { + PxResidual positionIterationResidual; //!< Residual values for position iteration. + PxResidual velocityIterationResidual; //!< Residual values for velocity iteration. + }; + + typedef PxResiduals PxArticulationResidual; + typedef PxResiduals PxSceneResidual; + + /** + \brief Structure representing residual values for a constraint. + + This struct holds residual values for both position and velocity iterations specific to a constraint. + */ + struct PxConstraintResidual + { + PxReal positionIterationResidual; //!< Residual value for position iteration. + PxReal velocityIterationResidual; //!< Residual value for velocity iteration. + + PxConstraintResidual() : positionIterationResidual(0.0f), velocityIterationResidual(0.0f) {} + }; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxRigidActor.h b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidActor.h new file mode 100644 index 000000000..056b76ec0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidActor.h @@ -0,0 +1,238 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RIGID_ACTOR_H +#define PX_RIGID_ACTOR_H + +#include "PxActor.h" +#include "PxShape.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxConstraint; + +/** +\brief PxRigidActor represents a base class shared between dynamic and static rigid bodies in the physics SDK. + +PxRigidActor objects specify the geometry of the object by defining a set of attached shapes (see #PxShape). + +\see PxActor +*/ +class PxRigidActor : public PxActor +{ +public: + /** + \brief Deletes the rigid actor object. + + Also releases any shapes associated with the actor. + + Releasing an actor will affect any objects that are connected to the actor (constraint shaders like joints etc.). + Such connected objects will be deleted upon scene deletion, or explicitly by the user by calling release() + on these objects. It is recommended to always remove all objects that reference actors before the actors + themselves are removed. It is not possible to retrieve list of dead connected objects. + + Sleeping: This call will awaken any sleeping actors contacting the deleted actor (directly or indirectly). + + Calls #PxActor::release() so you might want to check the documentation of that method as well. + + \see PxActor::release() + */ + virtual void release() = 0; + + /** + \brief Returns the internal actor index. + + \warning This is only defined for actors that have been added to a scene. + + \return The internal actor index, or 0xffffffff if the actor is not part of a scene. + */ + virtual PxU32 getInternalActorIndex() const = 0; + +/************************************************************************************************/ +/** \name Global Pose Manipulation +*/ + + /** + \brief Retrieves the actors world space transform. + + The getGlobalPose() method retrieves the actor's current actor space to world space transformation. + + \note It is not allowed to use this method while the simulation is running (except during PxScene::collide(), + in PxContactModifyCallback or in contact report callbacks). + + \note If this actor is a PxRigidDynamic or PxArticulationLink, this method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \return Global pose of object. + + \see PxRigidDynamic.setGlobalPose() PxRigidStatic.setGlobalPose() + */ + virtual PxTransform getGlobalPose() const = 0; + + /** + \brief Method for setting an actor's pose in the world. + + This method instantaneously changes the actor space to world space transformation. + + This method is mainly for dynamic rigid bodies (see #PxRigidDynamic). Calling this method on static actors is + likely to result in a performance penalty, since internal optimization structures for static actors may need to be + recomputed. In addition, moving static actors will not interact correctly with dynamic actors or joints. + + To directly control an actor's position and have it correctly interact with dynamic bodies and joints, create a dynamic + body with the PxRigidBodyFlag::eKINEMATIC flag, then use the setKinematicTarget() commands to define its path. + + Even when moving dynamic actors, exercise restraint in making use of this method. Where possible, avoid: + + \li moving actors into other actors, thus causing overlap (an invalid physical state) + + \li moving an actor that is connected by a joint to another away from the other (thus causing joint error) + + \note It is not allowed to use this method if the actor is part of a #PxPruningStructure that has not been + added to a scene yet. + + \note If this actor is a PxRigidDynamic or PxArticulationLink, this method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + Sleeping: This call wakes dynamic actors if they are sleeping and the autowake parameter is true (default). + + \param[in] pose Transformation from the actors local frame to the global frame. Range: rigid body transform. + \param[in] autowake whether to wake the object if it is dynamic. This parameter has no effect for static or kinematic actors. If true and the current wake counter value is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value. + + \see getGlobalPose() + */ + virtual void setGlobalPose(const PxTransform& pose, bool autowake = true) = 0; + +/************************************************************************************************/ +/** \name Shapes +*/ + + /** + \brief Attach a shape to an actor + + This call will increment the reference count of the shape. + + \note Mass properties of dynamic rigid actors will not automatically be recomputed + to reflect the new mass distribution implied by the shape. Follow this call with a call to + the PhysX extensions method #PxRigidBodyExt::updateMassAndInertia() to do that. + + Attaching a triangle mesh, heightfield or plane geometry shape configured as eSIMULATION_SHAPE is not supported for + non-kinematic PxRigidDynamic instances. + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] shape the shape to attach. + + \return True if success. + */ + virtual bool attachShape(PxShape& shape) = 0; + + /** + \brief Detach a shape from an actor. + + This will also decrement the reference count of the PxShape, and if the reference count is zero, will cause it to be deleted. + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] shape the shape to detach. + \param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCoordinate and PxRigidActor types. + */ + virtual void detachShape(PxShape& shape, bool wakeOnLostTouch = true) = 0; + + /** + \brief Returns the number of shapes assigned to the actor. + + You can use #getShapes() to retrieve the shape pointers. + + \return Number of shapes associated with this actor. + + \see PxShape getShapes() + */ + virtual PxU32 getNbShapes() const = 0; + + /** + \brief Retrieve all the shape pointers belonging to the actor. + + These are the shapes used by the actor for collision detection. + + You can retrieve the number of shape pointers by calling #getNbShapes() + + Note: Removing shapes with #PxShape::release() will invalidate the pointer of the released shape. + + \param[out] userBuffer The buffer to store the shape pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first shape pointer to be retrieved + \return Number of shape pointers written to the buffer. + + \see PxShape getNbShapes() PxShape::release() + */ + virtual PxU32 getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + +/************************************************************************************************/ +/** \name Constraints +*/ + + /** + \brief Returns the number of constraint shaders attached to the actor. + + You can use #getConstraints() to retrieve the constraint shader pointers. + + \return Number of constraint shaders attached to this actor. + + \see PxConstraint getConstraints() + */ + virtual PxU32 getNbConstraints() const = 0; + + /** + \brief Retrieve all the constraint shader pointers belonging to the actor. + + You can retrieve the number of constraint shader pointers by calling #getNbConstraints() + + Note: Removing constraint shaders with #PxConstraint::release() will invalidate the pointer of the released constraint. + + \param[out] userBuffer The buffer to store the constraint shader pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first constraint pointer to be retrieved + \return Number of constraint shader pointers written to the buffer. + + \see PxConstraint getNbConstraints() PxConstraint::release() + */ + virtual PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + +protected: + PX_INLINE PxRigidActor(PxType concreteType, PxBaseFlags baseFlags) : PxActor(concreteType, baseFlags) {} + PX_INLINE PxRigidActor(PxBaseFlags baseFlags) : PxActor(baseFlags) {} + virtual ~PxRigidActor() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidActor", PxActor); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxRigidBody.h b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidBody.h new file mode 100644 index 000000000..560f3a7ca --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidBody.h @@ -0,0 +1,779 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RIGID_BODY_H +#define PX_RIGID_BODY_H + +#include "PxRigidActor.h" +#include "PxForceMode.h" +#include "PxNodeIndex.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Collection of flags describing the behavior of a rigid body. + +\see PxRigidBody.setRigidBodyFlag(), PxRigidBody.getRigidBodyFlags() +*/ +struct PxRigidBodyFlag +{ + enum Enum + { + /** + \brief Enables kinematic mode for the actor. + + Kinematic actors are special dynamic actors that are not + influenced by forces (such as gravity), and have no momentum. They are considered to have infinite + mass and can be moved around the world using the setKinematicTarget() method. They will push + regular dynamic actors out of the way. Kinematics will not collide with static or other kinematic objects. + + Kinematic actors are great for moving platforms or characters, where direct motion control is desired. + + You can not connect Reduced joints to kinematic actors. Lagrange joints work ok if the platform + is moving with a relatively low, uniform velocity. + + Sleeping: + \li Setting this flag on a dynamic actor will put the actor to sleep and set the velocities to 0. + \li If this flag gets cleared, the current sleep state of the actor will be kept. + + \note kinematic actors are incompatible with CCD so raising this flag will automatically clear eENABLE_CCD + + \see PxRigidDynamic.setKinematicTarget() + */ + eKINEMATIC = (1<<0), //!< Enable kinematic mode for the body. + + /** + \brief Use the kinematic target transform for scene queries. + + If this flag is raised, then scene queries will treat the kinematic target transform as the current pose + of the body (instead of using the actual pose). Without this flag, the kinematic target will only take + effect with respect to scene queries after a simulation step. + + \see PxRigidDynamic.setKinematicTarget() + */ + eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES = (1<<1), + + /** + \brief Enables swept integration for the actor. + + If this flag is raised and CCD is enabled on the scene, then this body will be simulated by the CCD system to ensure that collisions are not missed due to + high-speed motion. Note individual shape pairs still need to enable PxPairFlag::eDETECT_CCD_CONTACT in the collision filtering to enable the CCD to respond to + individual interactions. + + \note kinematic actors are incompatible with CCD so this flag will be cleared automatically when raised on a kinematic actor + \note PxConvexCoreGeometry geometry type only supports eENABLE_SPECULATIVE_CCD at the moment. eENABLE_CCD will be ignored + */ + eENABLE_CCD = (1<<2), //!< Enable CCD for the body. + + /** + \brief Enabled CCD in swept integration for the actor. + + If this flag is raised and CCD is enabled, CCD interactions will simulate friction. By default, friction is disabled in CCD interactions because + CCD friction has been observed to introduce some simulation artifacts. CCD friction was enabled in previous versions of the SDK. Raising this flag will result in behavior + that is a closer match for previous versions of the SDK. + + \note This flag requires PxRigidBodyFlag::eENABLE_CCD to be raised to have any effect. + */ + eENABLE_CCD_FRICTION = (1<<3), + + /** + \brief Register a rigid body to dynamically adjust contact offset based on velocity. This can be used to achieve a CCD effect. + + If both eENABLE_CCD and eENABLE_SPECULATIVE_CCD are set on the same body, then angular motions are handled by speculative + contacts (eENABLE_SPECULATIVE_CCD) while linear motions are handled by sweeps (eENABLE_CCD). + */ + eENABLE_SPECULATIVE_CCD = (1<<4), + + /** + \brief Register a rigid body for reporting pose changes by the simulation at an early stage. + + Sometimes it might be advantageous to get access to the new pose of a rigid body as early as possible and + not wait until the call to fetchResults() returns. Setting this flag will schedule the rigid body to get reported + in #PxSimulationEventCallback::onAdvance(). Please refer to the documentation of that callback to understand + the behavior and limitations of this functionality. + + \see PxSimulationEventCallback::onAdvance() + */ + eENABLE_POSE_INTEGRATION_PREVIEW = (1<<5), + + /** + \brief Permit CCD to limit maxContactImpulse. This is useful for use-cases like a destruction system but can cause visual artefacts so is not enabled by default. + */ + eENABLE_CCD_MAX_CONTACT_IMPULSE = (1<<6), + + /** + \brief Carries over forces/torques between frames, rather than clearing them + + If this flag is raised, forces and torques will carry over between frames. Impulses applied with PxForceMode::eIMPULSE will not be retained. + + \note Clearing this flag will retain the accelerations for an additional frame before clearing them. To reset the forces immediately for the next frame, + a call to PxRigidBody::clearForce() / PxRigidBody::clearTorque() is needed. + + \see PxRigidBody::addForce(), PxRigidBody::AddTorque(), PxRigidBody::setForceAndTorque(), PxRigidBody::clearForce(), PxRigidBody::clearTorque() + */ + eRETAIN_ACCELERATIONS = (1<<7), + + /** + \brief Forces kinematic-kinematic pairs notifications for this actor. + + This flag overrides the global scene-level PxPairFilteringMode setting for kinematic actors. + This is equivalent to having PxPairFilteringMode::eKEEP for pairs involving this actor. + + A particular use case is when you have a large amount of kinematic actors, but you are only + interested in interactions between a few of them. In this case it is best to use + PxSceneDesc.kineKineFilteringMode = PxPairFilteringMode::eKILL, and then raise the + eFORCE_KINE_KINE_NOTIFICATIONS flag on the small set of kinematic actors that need + notifications. + + \note This has no effect if PxRigidBodyFlag::eKINEMATIC is not set. + + \warning Changing this flag at runtime will not have an effect until you remove and re-add the actor to the scene. + + \see PxPairFilteringMode PxSceneDesc.kineKineFilteringMode + */ + eFORCE_KINE_KINE_NOTIFICATIONS = (1<<8), + + /** + \brief Forces static-kinematic pairs notifications for this actor. + + Similar to eFORCE_KINE_KINE_NOTIFICATIONS, but for static-kinematic interactions. + + \note This has no effect if PxRigidBodyFlag::eKINEMATIC is not set. + + \warning Changing this flag at runtime will not have an effect until you remove and re-add the actor to the scene. + + \see PxPairFilteringMode PxSceneDesc.staticKineFilteringMode + */ + eFORCE_STATIC_KINE_NOTIFICATIONS = (1<<9), + + /** + \brief Enables computation of gyroscopic forces on the rigid body. + */ + eENABLE_GYROSCOPIC_FORCES = (1<<10), + + /** + \brief Reserved for internal usage + */ + eRESERVED = (1<<15) + }; +}; + +/** +\brief collection of set bits defined in PxRigidBodyFlag. + +\see PxRigidBodyFlag +*/ +typedef PxFlags PxRigidBodyFlags; +PX_FLAGS_OPERATORS(PxRigidBodyFlag::Enum,PxU16) + +/** +\brief PxRigidBody is a base class shared between dynamic rigid body objects. + +\see PxRigidActor +*/ + +class PxRigidBody : public PxRigidActor +{ +public: + // Runtime modifications + +/************************************************************************************************/ +/** \name Mass Manipulation +*/ + + /** + \brief Sets the pose of the center of mass relative to the actor. + + \note Changing this transform will not move the actor in the world! + + \note Setting an unrealistic center of mass which is a long way from the body can make it difficult for + the SDK to solve constraints. Perhaps leading to instability and jittering bodies. + + \note Changing this transform will not update the linear velocity reported by getLinearVelocity() to account + for the shift in center of mass. If the shift should be accounted for, the user should update the velocity + using setLinearVelocity(). + + Default: the identity transform + + \param[in] pose Mass frame offset transform relative to the actor frame. Range: rigid body transform. + + \see getCMassLocalPose() getLinearVelocity() + */ + virtual void setCMassLocalPose(const PxTransform& pose) = 0; + + /** + \brief Retrieves the center of mass pose relative to the actor frame. + + \return The center of mass pose relative to the actor frame. + + \see setCMassLocalPose() + */ + virtual PxTransform getCMassLocalPose() const = 0; + + /** + \brief Sets the mass of a dynamic actor. + + The mass must be non-negative. + + setMass() does not update the inertial properties of the body, to change the inertia tensor + use setMassSpaceInertiaTensor() or the PhysX extensions method #PxRigidBodyExt::updateMassAndInertia(). + + \note A value of 0 is interpreted as infinite mass. + \note Values of 0 are not permitted for instances of PxArticulationLink but are permitted for instances of PxRigidDynamic. + + Default: 1.0 + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] mass New mass value for the actor. Range: [0, PX_MAX_F32) + + \see getMass() setMassSpaceInertiaTensor() + */ + virtual void setMass(PxReal mass) = 0; + + /** + \brief Retrieves the mass of the actor. + + \note A value of 0 is interpreted as infinite mass. + + \return The mass of this actor. + + \see setMass() setMassSpaceInertiaTensor() + */ + virtual PxReal getMass() const = 0; + + /** + \brief Retrieves the inverse mass of the actor. + + \return The inverse mass of this actor. + + \see setMass() setMassSpaceInertiaTensor() + */ + virtual PxReal getInvMass() const = 0; + + /** + \brief Sets the inertia tensor, using a parameter specified in mass space coordinates. + + Note that such matrices are diagonal -- the passed vector is the diagonal. + + If you have a non diagonal world/actor space inertia tensor(3x3 matrix). Then you need to + diagonalize it and set an appropriate mass space transform. See #setCMassLocalPose(). + + The inertia tensor elements must be non-negative. + + \note A value of 0 in an element is interpreted as infinite inertia along that axis. + \note Values of 0 are not permitted for instances of PxArticulationLink but are permitted for instances of PxRigidDynamic. + + Default: (1.0, 1.0, 1.0) + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] m New mass space inertia tensor for the actor. + + \see getMassSpaceInertia() setMass() setCMassLocalPose() + */ + virtual void setMassSpaceInertiaTensor(const PxVec3& m) = 0; + + /** + \brief Retrieves the diagonal inertia tensor of the actor relative to the mass coordinate frame. + + This method retrieves a mass frame inertia vector. + + \return The mass space inertia tensor of this actor. + + \note A value of 0 in an element is interpreted as infinite inertia along that axis. + + \see setMassSpaceInertiaTensor() setMass() setCMassLocalPose() + */ + virtual PxVec3 getMassSpaceInertiaTensor() const = 0; + + /** + \brief Retrieves the diagonal inverse inertia tensor of the actor relative to the mass coordinate frame. + + This method retrieves a mass frame inverse inertia vector. + + \note A value of 0 in an element is interpreted as infinite inertia along that axis. + + \return The mass space inverse inertia tensor of this actor. + + \see setMassSpaceInertiaTensor() setMass() setCMassLocalPose() + */ + virtual PxVec3 getMassSpaceInvInertiaTensor() const = 0; + + /************************************************************************************************/ + /** \name Damping + */ + + /** + \brief Sets the linear damping coefficient. + + Zero represents no damping. The damping coefficient must be nonnegative. + + Default: 0.05 for PxArticulationLink, 0.0 for PxRigidDynamic + + \param[in] linDamp Linear damping coefficient. Range: [0, PX_MAX_F32) + + \see getLinearDamping() setAngularDamping() + */ + virtual void setLinearDamping(PxReal linDamp) = 0; + + /** + \brief Retrieves the linear damping coefficient. + + \return The linear damping coefficient associated with this actor. + + \see setLinearDamping() getAngularDamping() + */ + virtual PxReal getLinearDamping() const = 0; + + /** + \brief Sets the angular damping coefficient. + + Zero represents no damping. + + The angular damping coefficient must be nonnegative. + + Default: 0.05 + + \param[in] angDamp Angular damping coefficient. Range: [0, PX_MAX_F32) + + \see getAngularDamping() setLinearDamping() + */ + virtual void setAngularDamping(PxReal angDamp) = 0; + + /** + \brief Retrieves the angular damping coefficient. + + \return The angular damping coefficient associated with this actor. + + \see setAngularDamping() getLinearDamping() + */ + virtual PxReal getAngularDamping() const = 0; + + +/************************************************************************************************/ +/** \name Velocity +*/ + + /** + \brief Retrieves the linear velocity of an actor. + + \note It is not allowed to use this method while the simulation is running (except during PxScene::collide(), + in PxContactModifyCallback or in contact report callbacks). + + \note The linear velocity is reported with respect to the rigid body's center of mass and not the actor frame origin. + + \return The linear velocity of the actor. + + \see PxRigidDynamic.setLinearVelocity() getAngularVelocity() + */ + virtual PxVec3 getLinearVelocity() const = 0; + + /** + \brief Retrieves the angular velocity of the actor. + + \note It is not allowed to use this method while the simulation is running (except during PxScene::collide(), + in PxContactModifyCallback or in contact report callbacks). + + \return The angular velocity of the actor. + + \see PxRigidDynamic.setAngularVelocity() getLinearVelocity() + */ + virtual PxVec3 getAngularVelocity() const = 0; + + /** + \brief Lets you set the maximum linear velocity permitted for this actor. + + With this function, you can set the maximum linear velocity permitted for this rigid body. + Higher linear velocities are clamped to this value. + + Note: The linear velocity is clamped to the set value before the solver, which means that + the limit may still be momentarily exceeded. + + \note Enforcing the limit introduces momentum into the simulation, causing potentially unphysical behavior. + For articulation links, consider using joint damping and limits instead, which preserve momentum. + + Default: 100 * PxTolerancesScale::length /s for PxArticulationLink, 1e^16 lengthUnits/s for PxRigidDynamic + + \param[in] maxLinVel Max allowable linear velocity for actor. Range: [0, 1e^16) lengthUnits/s + + \see getMaxAngularVelocity() + */ + virtual void setMaxLinearVelocity(PxReal maxLinVel) = 0; + + /** + \brief Retrieves the maximum angular velocity permitted for this actor. + + \return The maximum allowed angular velocity for this actor. + + \see setMaxLinearVelocity + */ + virtual PxReal getMaxLinearVelocity() const = 0; + + /** + \brief Lets you set the maximum angular velocity permitted for this actor. + + For various internal computations, very quickly rotating actors introduce error + into the simulation, which leads to undesired results. + + With this function, you can set the maximum angular velocity permitted for this rigid body. + Higher angular velocities are clamped to this value. + + Note: The angular velocity is clamped to the set value before the solver, which means that + the limit may still be momentarily exceeded. + + \note Enforcing the limit introduces momentum into the simulation, causing potentially unphysical behavior. + For articulation links, consider using joint damping and limits instead, which preserve momentum. + + Default: 50.0 rad/s for PxArticulationLink, 100.0 rad/s for PxRigidDynamic + + Range: [0, 1e^16) rad/s + + \param[in] maxAngVel Max allowable angular velocity for actor. + + \see getMaxAngularVelocity() + */ + virtual void setMaxAngularVelocity(PxReal maxAngVel) = 0; + + /** + \brief Retrieves the maximum angular velocity permitted for this actor. + + \return The maximum allowed angular velocity for this actor. + + \see setMaxAngularVelocity + */ + virtual PxReal getMaxAngularVelocity() const = 0; + +/************************************************************************************************/ +/** \name Acceleration +*/ + + /** + \brief Retrieves the linear acceleration of an actor. + + For PxArticulationLink objects, this function is always available. + + For PxRigidDynamic actors, this function only returns valid results if PxSceneFlag::eENABLE_BODY_ACCELERATIONS is enabled. + If that flag is not enabled, the function returns zero for PxRigidDynamic actors. + + \return The linear acceleration of the actor, or zero if PxSceneFlag::eENABLE_BODY_ACCELERATIONS is disabled and the object is a PxRigidDynamic. + + \see PxRigidBody.getAngularAcceleration() PxSceneFlag::eENABLE_BODY_ACCELERATIONS + */ + virtual PxVec3 getLinearAcceleration() const = 0; + + /** + \brief Retrieves the angular acceleration of an actor. + + For PxArticulationLink objects, this function is always available. + + For PxRigidDynamic actors, this function only returns valid results if PxSceneFlag::eENABLE_BODY_ACCELERATIONS is enabled. + If that flag is not enabled, the function returns zero for PxRigidDynamic actors. + + \return The angular acceleration of the actor, or zero if PxSceneFlag::eENABLE_BODY_ACCELERATIONS is disabled and the object is a PxRigidDynamic. + + \see PxRigidBody.getLinearAcceleration() PxSceneFlag::eENABLE_BODY_ACCELERATIONS + */ + virtual PxVec3 getAngularAcceleration() const = 0; + +/************************************************************************************************/ +/** \name Forces +*/ + + /** + \brief Applies a force (or impulse) defined in the global coordinate frame to the actor at its center of mass. + + This will not induce a torque. + + ::PxForceMode determines if the force is to be conventional or impulsive. + + Each actor has an acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION + and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same + accumulators and are just short hand for multiplying the vector parameter by inverse mass and then using PxForceMode::eACCELERATION and + PxForceMode::eVELOCITY_CHANGE respectively. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links. + + \note if this is called on an articulation link, only the link is updated, not the entire articulation. + + \note see #PxRigidBodyExt::computeVelocityDeltaFromImpulse for details of how to compute the change in linear velocity that + will arise from the application of an impulsive force, where an impulsive force is applied force multiplied by a timestep. + + \note Forces will be cleared automatically after they are applied during the next simulation step. If the forces should be retained for + the following steps, PxRigidBodyFlag::eRETAIN_ACCELERATIONS should be raised. + + Sleeping: This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the force is non-zero. + + \param[in] force Force/Impulse to apply defined in the global frame. + \param[in] mode The mode to use when applying the force/impulse(see #PxForceMode) + \param[in] autowake Specify if the call should wake up the actor if it is currently asleep. If true and the current wake counter value + is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value. + + \see PxForceMode addTorque + */ + virtual void addForce(const PxVec3& force, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true) = 0; + + /** + \brief Applies an impulsive torque defined in the global coordinate frame to the actor. + + ::PxForceMode determines if the torque is to be conventional or impulsive. + + Each actor has an angular acceleration and an angular velocity change accumulator which are directly modified using the modes + PxForceMode::eACCELERATION and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE + also modify these same accumulators and are just short hand for multiplying the vector parameter by inverse inertia and then + using PxForceMode::eACCELERATION and PxForceMode::eVELOCITY_CHANGE respectively. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links. + + \note if this called on an articulation link, only the link is updated, not the entire articulation. + + \note see #PxRigidBodyExt::computeVelocityDeltaFromImpulse for details of how to compute the change in angular velocity that + will arise from the application of an impulsive torque, where an impulsive torque is an applied torque multiplied by a timestep. + + \note Torques will be cleared after they are applied during the next simulation step. If the Torques should be retained for the following + steps, PxRigidBodyFlag::eRETAIN_ACCELERATIONS should be raised. + + Sleeping: This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the torque is non-zero. + + \param[in] torque Torque to apply defined in the global frame. Range: torque vector + \param[in] mode The mode to use when applying the force/impulse(see #PxForceMode). + \param[in] autowake Specify if the call should wake up the actor if it is currently asleep. If true and the current wake counter value + is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value. + + \see PxForceMode addForce() + */ + virtual void addTorque(const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true) = 0; + + /** + \brief Clears the accumulated forces (sets the accumulated force back to zero). + + Each actor has an acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION + and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same + accumulators (see PxRigidBody::addForce() for details); therefore the effect of calling clearForce(PxForceMode::eFORCE) is equivalent to calling + clearForce(PxForceMode::eACCELERATION), and the effect of calling clearForce(PxForceMode::eIMPULSE) is equivalent to calling + clearForce(PxForceMode::eVELOCITY_CHANGE). + + ::PxForceMode determines if the cleared force is to be conventional or impulsive. + + \note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + \param[in] mode The mode to use when clearing the force/impulse(see #PxForceMode) + + \see PxForceMode addForce + */ + virtual void clearForce(PxForceMode::Enum mode = PxForceMode::eFORCE) = 0; + + /** + \brief Clears the impulsive torque defined in the global coordinate frame to the actor. + + ::PxForceMode determines if the cleared torque is to be conventional or impulsive. + + Each actor has an angular acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION + and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same + accumulators (see PxRigidBody::addTorque() for details); therefore the effect of calling clearTorque(PxForceMode::eFORCE) is equivalent to calling + clearTorque(PxForceMode::eACCELERATION), and the effect of calling clearTorque(PxForceMode::eIMPULSE) is equivalent to calling + clearTorque(PxForceMode::eVELOCITY_CHANGE). + + \note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + \param[in] mode The mode to use when clearing the force/impulse(see #PxForceMode). + + \see PxForceMode addTorque + */ + virtual void clearTorque(PxForceMode::Enum mode = PxForceMode::eFORCE) = 0; + + /** + \brief Sets the impulsive force and torque defined in the global coordinate frame to the actor. + + ::PxForceMode determines if the cleared torque is to be conventional or impulsive. + + \note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + \note Forces and torques will be cleared after they are applied during the next simulation step. If they should be retained for the following + steps, PxRigidBodyFlag::eRETAIN_ACCELERATIONS should be raised. + + \see PxForceMode addTorque + */ + virtual void setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE) = 0; + + /** + \brief Raises or clears a particular rigid body flag. + + See the list of flags #PxRigidBodyFlag + + Default: no flags are set + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] flag The PxRigidBody flag to raise(set) or clear. See #PxRigidBodyFlag. + \param[in] value The new boolean value for the flag. + + \see PxRigidBodyFlag getRigidBodyFlags() + */ + virtual void setRigidBodyFlag(PxRigidBodyFlag::Enum flag, bool value) = 0; + virtual void setRigidBodyFlags(PxRigidBodyFlags inFlags) = 0; + + /** + \brief Reads the PxRigidBody flags. + + See the list of flags #PxRigidBodyFlag + + \return The values of the PxRigidBody flags. + + \see PxRigidBodyFlag setRigidBodyFlag() + */ + virtual PxRigidBodyFlags getRigidBodyFlags() const = 0; + + /** + \brief Sets the CCD minimum advance coefficient. + + The CCD minimum advance coefficient is a value in the range [0, 1] that is used to control the minimum amount of time a body is integrated when + it has a CCD contact. The actual minimum amount of time that is integrated depends on various properties, including the relative speed and collision shapes + of the bodies involved in the contact. From these properties, a numeric value is calculated that determines the maximum distance (and therefore maximum time) + which these bodies could be integrated forwards that would ensure that these bodies did not pass through each-other. This value is then scaled by CCD minimum advance + coefficient to determine the amount of time that will be consumed in the CCD pass. + + Things to consider: + A large value (approaching 1) ensures that the objects will always advance some time. However, larger values increase the chances of objects gently drifting through each-other in + scenes which the constraint solver can't converge, e.g. scenes where an object is being dragged through a wall with a constraint. + A value of 0 ensures that the pair of objects stop at the exact time-of-impact and will not gently drift through each-other. However, with very small/thin objects initially in + contact, this can lead to a large amount of time being dropped and increases the chances of jamming. Jamming occurs when the an object is persistently in contact with an object + such that the time-of-impact is 0, which results in no time being advanced for those objects in that CCD pass. + + The chances of jamming can be reduced by increasing the number of CCD mass \see PxSceneDesc.ccdMaxPasses. However, increasing this number increases the CCD overhead. + + \param[in] advanceCoefficient The CCD min advance coefficient. Range: [0, 1] Default: 0.15 + */ + virtual void setMinCCDAdvanceCoefficient(PxReal advanceCoefficient) = 0; + + /** + \brief Gets the CCD minimum advance coefficient. + + \return The value of the CCD min advance coefficient. + + \see setMinCCDAdvanceCoefficient + */ + virtual PxReal getMinCCDAdvanceCoefficient() const = 0; + + /** + \brief Sets the maximum depenetration velocity permitted to be introduced by the solver. + This value controls how much velocity the solver can introduce to correct for penetrations in contacts. + \param[in] biasClamp The maximum velocity to de-penetrate by Range: (0, PX_MAX_F32]. + */ + virtual void setMaxDepenetrationVelocity(PxReal biasClamp) = 0; + + /** + \brief Returns the maximum depenetration velocity the solver is permitted to introduced. + This value controls how much velocity the solver can introduce to correct for penetrations in contacts. + \return The maximum penetration bias applied by the solver. + */ + virtual PxReal getMaxDepenetrationVelocity() const = 0; + + /** + \brief Sets a limit on the impulse that may be applied at a contact. The maximum impulse at a contact between two dynamic or kinematic + bodies will be the minimum of the two limit values. For a collision between a static and a dynamic body, the impulse is limited + by the value for the dynamic body. + + \param[in] maxImpulse the maximum contact impulse. Range: [0, PX_MAX_F32] Default: PX_MAX_F32 + + \see getMaxContactImpulse + */ + virtual void setMaxContactImpulse(PxReal maxImpulse) = 0; + + /** + \brief Returns the maximum impulse that may be applied at a contact. + + \return The maximum impulse that may be applied at a contact + + \see setMaxContactImpulse + */ + virtual PxReal getMaxContactImpulse() const = 0; + + /** + \brief Sets a distance scale whereby the angular influence of a contact on the normal constraint in a contact is + zeroed if normal.cross(offset) falls below this tolerance. Rather than acting as an absolute value, this tolerance + is scaled by the ratio rXn.dot(angVel)/normal.dot(linVel) such that contacts that have relatively larger angular velocity + than linear normal velocity (e.g. rolling wheels) achieve larger slop values as the angular velocity increases. + + \param[in] slopCoefficient the Slop coefficient. Range: [0, PX_MAX_F32] Default: 0 + + \see getContactSlopCoefficient + */ + virtual void setContactSlopCoefficient(PxReal slopCoefficient) = 0; + + /** + \brief Returns the contact slop coefficient. + + \return The contact slop coefficient. + + \see setContactSlopCoefficient + */ + virtual PxReal getContactSlopCoefficient() const = 0; + + /** + \brief Returns the island node index + + \return The island node index. + */ + virtual PxNodeIndex getInternalIslandNodeIndex() const = 0; + +protected: + PX_INLINE PxRigidBody(PxType concreteType, PxBaseFlags baseFlags) : PxRigidActor(concreteType, baseFlags) {} + PX_INLINE PxRigidBody(PxBaseFlags baseFlags) : PxRigidActor(baseFlags) {} + virtual ~PxRigidBody() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidBody", PxRigidActor); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxRigidDynamic.h b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidDynamic.h new file mode 100644 index 000000000..642de486a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidDynamic.h @@ -0,0 +1,476 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RIGID_DYNAMIC_H +#define PX_RIGID_DYNAMIC_H + +#include "PxRigidBody.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Collection of flags providing a mechanism to lock motion along/around a specific axis. + +\see PxRigidDynamic.setRigidDynamicLockFlag(), PxRigidBody.getRigidDynamicLockFlags() +*/ +struct PxRigidDynamicLockFlag +{ + enum Enum + { + eLOCK_LINEAR_X = (1 << 0), + eLOCK_LINEAR_Y = (1 << 1), + eLOCK_LINEAR_Z = (1 << 2), + eLOCK_ANGULAR_X = (1 << 3), + eLOCK_ANGULAR_Y = (1 << 4), + eLOCK_ANGULAR_Z = (1 << 5) + }; +}; + +typedef PxFlags PxRigidDynamicLockFlags; +PX_FLAGS_OPERATORS(PxRigidDynamicLockFlag::Enum, PxU8) + +/** +\brief PxRigidDynamic represents a dynamic rigid simulation object in the physics SDK. + +

Creation

+Instances of this class are created by calling #PxPhysics::createRigidDynamic() and deleted with #release(). + +

Visualizations

+\li #PxVisualizationParameter::eACTOR_AXES +\li #PxVisualizationParameter::eBODY_AXES +\li #PxVisualizationParameter::eBODY_MASS_AXES +\li #PxVisualizationParameter::eBODY_LIN_VELOCITY +\li #PxVisualizationParameter::eBODY_ANG_VELOCITY + +\see PxRigidBody PxPhysics.createRigidDynamic() release() +*/ + +class PxRigidDynamic : public PxRigidBody +{ +public: + // Runtime modifications + +/************************************************************************************************/ +/** \name Kinematic Actors +*/ + + /** + \brief Moves kinematically controlled dynamic actors through the game world. + + You set a dynamic actor to be kinematic using the PxRigidBodyFlag::eKINEMATIC flag + with setRigidBodyFlag(). + + The move command will result in a velocity that will move the body into + the desired pose. After the move is carried out during a single time step, + the velocity is returned to zero. Thus, you must continuously call + this in every time step for kinematic actors so that they move along a path. + + This function simply stores the move destination until the next simulation + step is processed, so consecutive calls will simply overwrite the stored target variable. + + The motion is always fully carried out. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + Sleeping: This call wakes the actor if it is sleeping and will set the wake counter to #PxSceneDesc::wakeCounterResetValue. + + \param[in] destination The desired pose for the kinematic actor, in the global frame. Range: rigid body transform. + + \see getKinematicTarget() PxRigidBodyFlag setRigidBodyFlag() + */ + virtual void setKinematicTarget(const PxTransform& destination) = 0; + + /** + \brief Get target pose of a kinematically controlled dynamic actor. + + \param[out] target Transform to write the target pose to. Only valid if the method returns true. + \return True if the actor is a kinematically controlled dynamic and the target has been set, else False. + + \see setKinematicTarget() PxRigidBodyFlag setRigidBodyFlag() + */ + virtual bool getKinematicTarget(PxTransform& target) const = 0; + +/************************************************************************************************/ +/** \name Sleeping +*/ + + /** + \brief Returns true if this body is sleeping. + + When an actor does not move for a period of time, it is no longer simulated in order to save time. This state + is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object, + or one of its properties is changed by the user, the entire sleep mechanism should be transparent to the user. + + In general, a dynamic rigid actor is guaranteed to be awake if at least one of the following holds: + + \li The wake counter is positive (see #setWakeCounter()). + \li The linear or angular velocity is non-zero. + \li A non-zero force or torque has been applied. + + If a dynamic rigid actor is sleeping, the following state is guaranteed: + + \li The wake counter is zero. + \li The linear and angular velocity is zero. + \li There is no force update pending. + + When an actor gets inserted into a scene, it will be considered asleep if all the points above hold, else it will be treated as awake. + + If an actor is asleep after the call to PxScene::fetchResults() returns, it is guaranteed that the pose of the actor + was not changed. You can use this information to avoid updating the transforms of associated objects. + + \note A kinematic actor is asleep unless a target pose has been set (in which case it will stay awake until two consecutive + simulation steps without a target pose being set have passed). The wake counter will get set to zero or to the reset value + #PxSceneDesc::wakeCounterResetValue in the case where a target pose has been set to be consistent with the definitions above. + + \note It is invalid to use this method if the actor has not been added to a scene already. + + \note It is not allowed to use this method while the simulation is running. + + \return True if the actor is sleeping. + + \see isSleeping() wakeUp() putToSleep() getSleepThreshold() + */ + virtual bool isSleeping() const = 0; + + /** + \brief Sets the mass-normalized kinetic energy threshold below which an actor may go to sleep. + + Actors whose kinetic energy divided by their mass is below this threshold will be candidates for sleeping. + + Default: 5e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed + + \param[in] threshold Energy below which an actor may go to sleep. Range: [0, PX_MAX_F32) + + \see isSleeping() getSleepThreshold() wakeUp() putToSleep() PxTolerancesScale + */ + virtual void setSleepThreshold(PxReal threshold) = 0; + + /** + \brief Returns the mass-normalized kinetic energy below which an actor may go to sleep. + + \return The energy threshold for sleeping. + + \see isSleeping() wakeUp() putToSleep() setSleepThreshold() + */ + virtual PxReal getSleepThreshold() const = 0; + + /** + \brief Sets the mass-normalized kinetic energy threshold below which an actor may participate in stabilization. + + Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization. + + This value has no effect if PxSceneFlag::eENABLE_STABILIZATION was not enabled on the PxSceneDesc. + + Default: 1e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed + + \param[in] threshold Energy below which an actor may participate in stabilization. Range: [0,inf) + + \see getStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION + */ + virtual void setStabilizationThreshold(PxReal threshold) = 0; + + /** + \brief Returns the mass-normalized kinetic energy below which an actor may participate in stabilization. + + Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization. + + \return The energy threshold for participating in stabilization. + + \see setStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION + */ + virtual PxReal getStabilizationThreshold() const = 0; + + /** + \brief Sets the wake counter for the actor. + + The wake counter value determines the minimum amount of time until the body can be put to sleep. Please note + that a body will not be put to sleep if the energy is above the specified threshold (see #setSleepThreshold()) + or if other awake bodies are touching it. + + \note Passing in a positive value will wake the actor up automatically. + + \note It is invalid to use this method for kinematic actors since the wake counter for kinematics is defined + based on whether a target pose has been set (see the comment in #isSleeping()). + + \note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set. + + Default: 0.4 (which corresponds to 20 frames for a time step of 0.02) + + \param[in] wakeCounterValue Wake counter value. Range: [0, PX_MAX_F32) + + \see isSleeping() getWakeCounter() + */ + virtual void setWakeCounter(PxReal wakeCounterValue) = 0; + + /** + \brief Returns the wake counter of the actor. + + \note It is not allowed to use this method while the simulation is running. + + \return The wake counter of the actor. + + \see isSleeping() setWakeCounter() + */ + virtual PxReal getWakeCounter() const = 0; + + /** + \brief Wakes up the actor if it is sleeping. + + The actor will get woken up and might cause other touching actors to wake up as well during the next simulation step. + + \note This will set the wake counter of the actor to the value specified in #PxSceneDesc::wakeCounterResetValue. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + \note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined + based on whether a target pose has been set (see the comment in #isSleeping()). + + \see isSleeping() putToSleep() + */ + virtual void wakeUp() = 0; + + /** + \brief Forces the actor to sleep. + + The actor will stay asleep during the next simulation step if not touched by another non-sleeping actor. + + \note Any applied force will be cleared and the velocity and the wake counter of the actor will be set to 0. + + \note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set. + + \note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined + based on whether a target pose has been set (see the comment in #isSleeping()). + + \see isSleeping() wakeUp() + */ + virtual void putToSleep() = 0; + +/************************************************************************************************/ +/** \name Lock flags +*/ + + /** + \brief Reads the PxRigidDynamic lock flags. + + See the list of flags #PxRigidDynamicLockFlag + + \return The values of the PxRigidDynamic lock flags. + + \see PxRigidDynamicLockFlag setRigidDynamicLockFlag() + */ + virtual PxRigidDynamicLockFlags getRigidDynamicLockFlags() const = 0; + + /** + \brief Raises or clears a particular PxRigidDynamic lock flag. + + See the list of flags #PxRigidDynamicLockFlag + + Default: no flags are set + + \param[in] flag The PxRigidDynamicLockFlag to raise(set) or clear. See #PxRigidBodyFlag. + \param[in] value The new boolean value for the flag. + + \see PxRigidDynamicLockFlag getRigidDynamicLockFlags() + */ + virtual void setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value) = 0; + + /** + \brief Set all PxRigidDynamic lock flags. + \see setRigidDynamicLockFlag() + */ + virtual void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) = 0; + + /** + \brief Retrieves the actor's center-of-mass linear velocity. + + \note It is not allowed to use this method while the simulation is running (except during PxScene::collide(), + in PxContactModifyCallback or in contact report callbacks). + + \note The linear velocity is reported with respect to the actor's center of mass and not the actor frame origin. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \return The actor's center-of-mass linear velocity. + + \see PxRigidDynamic.setLinearVelocity() getAngularVelocity() + */ + virtual PxVec3 getLinearVelocity() const = 0; + + /** + \brief Sets the actor's center-of-mass linear velocity. + + Note that if you continuously set the velocity of an actor yourself, + forces such as gravity or friction will not be able to manifest themselves, because forces directly + influence only the velocity/momentum of an actor. + + Default: (0.0, 0.0, 0.0) + + Sleeping: This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the + new velocity is non-zero. + + \note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \note The linear velocity is applied with respect to the actor's center of mass and not the actor frame origin. + + \param[in] linVel New center-of-mass linear velocity of the actor. Range: velocity vector + \param[in] autowake Whether to wake the object up if it is asleep. If true and the current wake counter value is + smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value. + + \see getLinearVelocity() setAngularVelocity() + */ + virtual void setLinearVelocity(const PxVec3& linVel, bool autowake = true) = 0; + + /** + \brief Retrieves the angular velocity of the actor. + + \note It is not allowed to use this method while the simulation is running (except during PxScene::collide(), + in PxContactModifyCallback or in contact report callbacks). + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \return The angular velocity of the actor. + + \see PxRigidDynamic.setAngularVelocity() getLinearVelocity() + */ + virtual PxVec3 getAngularVelocity() const = 0; + + /** + \brief Sets the angular velocity of the actor. + + Note that if you continuously set the angular velocity of an actor yourself, + forces such as friction will not be able to rotate the actor, because forces directly influence only the velocity/momentum. + + Default: (0.0, 0.0, 0.0) + + Sleeping: This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the + new velocity is non-zero. + + \note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set. + + \note This method should not be used after the direct GPU API has been enabled and initialized. See #PxDirectGPUAPI for the details. + + \param[in] angVel New angular velocity of actor. Range: angular velocity vector + \param[in] autowake Whether to wake the object up if it is asleep. If true and the current wake counter value is + smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value. + + \see getAngularVelocity() setLinearVelocity() + */ + virtual void setAngularVelocity(const PxVec3& angVel, bool autowake = true) = 0; + +/************************************************************************************************/ + + /** + \brief Sets the solver iteration counts for the body. + + The solver iteration count determines how accurately joints and contacts are resolved. + If you are having trouble with jointed bodies oscillating and behaving erratically, then + setting a higher position iteration count may improve their stability. + + If intersecting bodies are being depenetrated too violently, increase the number of velocity + iterations. More velocity iterations will drive the relative exit velocity of the intersecting + objects closer to the correct value given the restitution. + + Default: 4 position iterations, 1 velocity iteration + + \param[in] minPositionIters Number of position iterations the solver should perform for this body. Range: [1,255] + \param[in] minVelocityIters Number of velocity iterations the solver should perform for this body. Range: [0,255] + + \see getSolverIterationCounts() + */ + virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0; + + /** + \brief Retrieves the solver iteration counts. + + \see setSolverIterationCounts() + */ + virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0; + + /** + \brief Retrieves the force threshold for contact reports. + + The contact report threshold is a force threshold. If the force between + two actors exceeds this threshold for either of the two actors, a contact report + will be generated according to the contact report threshold flags provided by + the filter shader/callback. + See #PxPairFlag. + + The threshold used for a collision between a dynamic actor and the static environment is + the threshold of the dynamic actor, and all contacts with static actors are summed to find + the total normal force. + + Default: PX_MAX_F32 + + \return Force threshold for contact reports. + + \see setContactReportThreshold PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback + */ + virtual PxReal getContactReportThreshold() const = 0; + + /** + \brief Sets the force threshold for contact reports. + + See #getContactReportThreshold(). + + \param[in] threshold Force threshold for contact reports. Range: [0, PX_MAX_F32) + + \see getContactReportThreshold PxPairFlag + */ + virtual void setContactReportThreshold(PxReal threshold) = 0; + + /** + \brief Returns the GPU rigid dynamic index. + + \note This function only returns valid results if GPU dynamics is enabled. + + \return The GPU index, or 0xFFFFFFFF if the actor is not inserted into a PxScene. + + \see PxDirectGPUAPI::getRigidDynamicData(), PxDirectGPUAPI::setRigidDynamicData(). + */ + virtual PxRigidDynamicGPUIndex getGPUIndex() const = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxRigidDynamic"; } + +protected: + PX_INLINE PxRigidDynamic(PxType concreteType, PxBaseFlags baseFlags) : PxRigidBody(concreteType, baseFlags) { } + PX_INLINE PxRigidDynamic(PxBaseFlags baseFlags) : PxRigidBody(baseFlags) {} + virtual ~PxRigidDynamic() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidDynamic", PxRigidBody); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxRigidStatic.h b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidStatic.h new file mode 100644 index 000000000..0b03baa85 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxRigidStatic.h @@ -0,0 +1,71 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RIGID_STATIC_H +#define PX_RIGID_STATIC_H + +#include "PxPhysXConfig.h" +#include "PxRigidActor.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief PxRigidStatic represents a static rigid body simulation object in the physics SDK. + +PxRigidStatic objects are static rigid physics entities. They shall be used to define solid objects which are fixed in the world. + +

Creation

+Instances of this class are created by calling #PxPhysics::createRigidStatic() and deleted with #release(). + +

Visualizations

+\li #PxVisualizationParameter::eACTOR_AXES + +\see PxRigidActor PxPhysics.createRigidStatic() release() +*/ + +class PxRigidStatic : public PxRigidActor +{ +public: + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxRigidStatic"; } + +protected: + PX_INLINE PxRigidStatic(PxType concreteType, PxBaseFlags baseFlags) : PxRigidActor(concreteType, baseFlags) {} + PX_INLINE PxRigidStatic(PxBaseFlags baseFlags) : PxRigidActor(baseFlags){} + virtual ~PxRigidStatic() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidStatic", PxRigidActor); } + +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSDFBuilder.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSDFBuilder.h new file mode 100644 index 000000000..ee1c5a530 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSDFBuilder.h @@ -0,0 +1,120 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SDF_BUILDER_H +#define PX_SDF_BUILDER_H + +#include "cudamanager/PxCudaContext.h" +#include "cudamanager/PxCudaContextManager.h" + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" +#include "foundation/PxArray.h" +#include "cooking/PxSDFDesc.h" +#include "cudamanager/PxCudaTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Utility class to compute an SDF on the GPU +*/ +class PxSDFBuilder +{ +public: + + /** + \brief Constructs a dense grid SDF for a triangle mesh using the GPU + \param[in] vertices The vertices of the triangle mesh + \param[in] numVertices The number of vertices + \param[in] indices The triangle indices + \param[in] numTriangleIndices The number of triangle indices + \param[in] width The number of samples along the x direction of the resulting SDF volume + \param[in] height The number of samples along the y direction of the resulting SDF volume + \param[in] depth The number of samples along the z direction of the resulting SDF volume + \param[in] minExtents The minimum corner location of the axis aligned box containing the SDF samples + \param[in] maxExtents The maximum corner location of the axis aligned box containing the SDF samples + \param[in] cellCenteredSamples Determines if the sample points are located at the center of a SDF cell or at the lower left (=min) corner of a cell + \param[out] sdf The distance values. Must provide space for width*height*depth distance samples. Negative distance means the sample point is located inside of the triangle mesh + \param[in] stream The cuda stream on which the conversion is processed. If the default stream (0) is used, a temporary stream will be created internally + + \return A boolean that indicates whether the SDF creation succeeded + */ + virtual bool buildSDF(const PxVec3* vertices, PxU32 numVertices, const PxU32* indices, PxU32 numTriangleIndices, PxU32 width, PxU32 height, PxU32 depth, + const PxVec3& minExtents, const PxVec3& maxExtents, bool cellCenteredSamples, PxReal* sdf, CUstream stream = 0) = 0; + + /** + \brief Constructs a sparse grid SDF for a triangle mesh using the GPU + \param[in] vertices The vertices of the triangle mesh + \param[in] numVertices The number of vertices + \param[in] indices The triangle indices + \param[in] numTriangleIndices The number of triangle indices + \param[in] width The number of samples along the x direction of the resulting SDF volume + \param[in] height The number of samples along the y direction of the resulting SDF volume + \param[in] depth The number of samples along the z direction of the resulting SDF volume + \param[in] minExtents The minimum corner location of the axis aligned box containing the SDF samples + \param[in] maxExtents The maximum corner location of the axis aligned box containing the SDF samples + \param[in] narrowBandThickness The thickness of the narrow band + \param[in] cellsPerSubgrid The number of cells in a sparse subgrid block (full block has mSubgridSize^3 cells and (mSubgridSize+1)^3 samples) + \param[in] bitsPerSubgridPixel Subgrid pixel compression + \param[out] sdfCoarse Used to store the lower resolution, dense backround SDF to provide distance information further away from the mesh's surface + \param[out] sdfSubgridsStartSlots Used to store the subgrids start indices + \param[out] sdfDataSubgrids Used to store the subgrids + \param[out] subgridsMinSdfValue Used to store the minimum sdf value over all subgrids + \param[out] subgridsMaxSdfValue Used to store the maximum sdf value over all subgrids + \param[out] sdfSubgrids3DTexBlockDimX Used to store x dimension of the texture block that stores the subgrids + \param[out] sdfSubgrids3DTexBlockDimY Used to store y dimension of the texture block that stores the subgrids + \param[out] sdfSubgrids3DTexBlockDimZ Used to store z dimension of the texture block that stores the subgrids + \param[in] stream The cuda stream on which the conversion is processed. If the default stream (0) is used, a temporary stream will be created internally + + \return A boolean that indicates whether the SDF creation succeeded + */ + virtual bool buildSparseSDF(const PxVec3* vertices, PxU32 numVertices, const PxU32* indices, PxU32 numTriangleIndices, PxU32 width, PxU32 height, PxU32 depth, + const PxVec3& minExtents, const PxVec3& maxExtents, PxReal narrowBandThickness, PxU32 cellsPerSubgrid, PxSdfBitsPerSubgridPixel::Enum bitsPerSubgridPixel, + PxArray& sdfCoarse, PxArray& sdfSubgridsStartSlots, PxArray& sdfDataSubgrids, + PxReal& subgridsMinSdfValue, PxReal& subgridsMaxSdfValue, + PxU32& sdfSubgrids3DTexBlockDimX, PxU32& sdfSubgrids3DTexBlockDimY, PxU32& sdfSubgrids3DTexBlockDimZ, CUstream stream = 0) = 0; + + /** + \brief Releases the memory including the this pointer + */ + virtual void release() = 0; + + /** + \brief Destructor + */ + virtual ~PxSDFBuilder() { } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxScene.h b/Jusin154_Team3D/Engine/Public/PhysX/PxScene.h new file mode 100644 index 000000000..ab8ce1f02 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxScene.h @@ -0,0 +1,1802 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SCENE_H +#define PX_SCENE_H + +#include "PxActor.h" +#include "PxDirectGPUAPI.h" +#include "PxSceneQuerySystem.h" +#include "PxSceneDesc.h" +#include "PxVisualizationParameter.h" +#include "PxSimulationStatistics.h" +#include "PxClient.h" +#include "task/PxTask.h" +#include "PxArticulationFlag.h" +#include "PxSoftBodyFlag.h" // deprecated +#include "PxParticleSystemFlag.h" +#include "PxParticleSolverType.h" +#include "PxResidual.h" + +#include "cudamanager/PxCudaTypes.h" + +#include "pvd/PxPvdSceneClient.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxCollection; +class PxConstraint; +class PxSimulationEventCallback; +class PxPhysics; +class PxAggregate; +class PxRenderBuffer; +class PxArticulationReducedCoordinate; + +struct PxContactPairHeader; + +class PxPvdSceneClient; + +class PxDeformableSurface; +class PxDeformableVolume; +class PxPBDParticleSystem; + +/** +\brief Expresses the dominance relationship of a contact. +For the time being only three settings are permitted: + +(1, 1), (0, 1), and (1, 0). + +\see getDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair() +*/ +struct PxDominanceGroupPair +{ + PxDominanceGroupPair(PxU8 a, PxU8 b) + : dominance0(a), dominance1(b) {} + PxU8 dominance0; + PxU8 dominance1; +}; + +/** +\brief Identifies each type of actor for retrieving actors from a scene. + +\note #PxArticulationLink objects are not supported. Use the #PxArticulationReducedCoordinate object to retrieve all its links. + +\see PxScene::getActors(), PxScene::getNbActors() +*/ +struct PxActorTypeFlag +{ + enum Enum + { + /** + \brief A static rigid body + \see PxRigidStatic + */ + eRIGID_STATIC = (1 << 0), + + /** + \brief A dynamic rigid body + \see PxRigidDynamic + */ + eRIGID_DYNAMIC = (1 << 1) + }; +}; + +/** +\brief Collection of set bits defined in PxActorTypeFlag. + +\see PxActorTypeFlag +*/ +typedef PxFlags PxActorTypeFlags; +PX_FLAGS_OPERATORS(PxActorTypeFlag::Enum,PxU16) + +class PxActor; + +/** +\brief Broad-phase callback to receive broad-phase related events. + +Each broadphase callback object is associated with a PxClientID. It is possible to register different +callbacks for different clients. The callback functions are called this way: +- for shapes/actors, the callback assigned to the actors' clients are used +- for aggregates, the callbacks assigned to clients from aggregated actors are used + +\note SDK state should not be modified from within the callbacks. In particular objects should not +be created or destroyed. If state modification is needed then the changes should be stored to a buffer +and performed after the simulation step. + +Threading: It is not necessary to make this class thread safe as it will only be called in the context of the +user thread. + +\see PxSceneDesc PxScene.setBroadPhaseCallback() PxScene.getBroadPhaseCallback() +*/ +class PxBroadPhaseCallback +{ + public: + virtual ~PxBroadPhaseCallback() {} + + /** + \brief Out-of-bounds notification. + + This function is called when an object leaves the broad-phase. + + \param[in] shape Shape that left the broad-phase bounds + \param[in] actor Owner actor + */ + virtual void onObjectOutOfBounds(PxShape& shape, PxActor& actor) = 0; + + /** + \brief Out-of-bounds notification. + + This function is called when an aggregate leaves the broad-phase. + + \param[in] aggregate Aggregate that left the broad-phase bounds + */ + virtual void onObjectOutOfBounds(PxAggregate& aggregate) = 0; +}; + +/** +\brief Abstract base class for post-solve callback functionality. +*/ +class PxPostSolveCallback +{ +public: + /** + \brief Callback function called after a solve event. + \param startEvent CUDA event that should be waited for on the user stream. Once the event happened, the user can safely read the solver's results. + */ + virtual void onPostSolve(CUevent startEvent) = 0; + + virtual ~PxPostSolveCallback() {} +}; + +/** + \brief A scene is a collection of bodies and constraints which can interact. + + The scene simulates the behavior of these objects over time. Several scenes may exist + at the same time, but each body or constraint is specific to a scene + -- they may not be shared. + + \see PxSceneDesc PxPhysics.createScene() release() +*/ +class PxScene : public PxSceneSQSystem +{ + protected: + + /************************************************************************************************/ + + /** \name Basics + */ + //\{ + + PxScene() : userData(NULL) {} + virtual ~PxScene() {} + + public: + + /** + \brief Deletes the scene. + + Removes any actors and constraint shaders from this scene + (if the user hasn't already done so). + + Be sure to not keep a reference to this object after calling release. + Avoid release calls while the scene is simulating (in between simulate() and fetchResults() calls). + + \see PxPhysics.createScene() + */ + virtual void release() = 0; + + /** + \brief Sets a scene flag. You can only set one flag at a time. + + \note Not all flags are mutable and changing some will result in an error. Please check #PxSceneFlag to see which flags can be changed. + + \see PxSceneFlag + */ + virtual void setFlag(PxSceneFlag::Enum flag, bool value) = 0; + + /** + \brief Get the scene flags. + + \return The scene flags. See #PxSceneFlag + + \see PxSceneFlag + */ + virtual PxSceneFlags getFlags() const = 0; + + /** + \brief Set new scene limits. + + \note Increase the maximum capacity of various data structures in the scene. The new capacities will be + at least as large as required to deal with the objects currently in the scene. Further, these values + are for preallocation and do not represent hard limits. + + \param[in] limits Scene limits. + \see PxSceneLimits + */ + virtual void setLimits(const PxSceneLimits& limits) = 0; + + /** + \brief Get current scene limits. + \return Current scene limits. + \see PxSceneLimits + */ + virtual PxSceneLimits getLimits() const = 0; + + /** + \brief Call this method to retrieve the Physics SDK. + + \return The physics SDK this scene is associated with. + + \see PxPhysics + */ + virtual PxPhysics& getPhysics() = 0; + + /** + \brief Retrieves the scene's internal timestamp, increased each time a simulation step is completed. + + \return scene timestamp + */ + virtual PxU32 getTimestamp() const = 0; + + /** + \brief Sets a name string for the Scene that can be retrieved with getName(). + + This is for debugging and is not used by the SDK. The string is not copied by the SDK, + only the pointer is stored. + + \param[in] name String to set the objects name to. + + Default: NULL + + \see getName() + */ + virtual void setName(const char* name) = 0; + + /** + \brief Retrieves the name string set with setName(). + + \return Name string associated with the Scene. + + \see setName() + */ + virtual const char* getName() const = 0; + + //\} + /************************************************************************************************/ + + /** \name Add/Remove Articulations + */ + //\{ + /** + \brief Adds an articulation to this scene. + + \note If the articulation is already assigned to a scene (see #PxArticulationReducedCoordinate::getScene), the call is ignored and an error is issued. + + \param[in] articulation The articulation to add to the scene. + \return True if success + + \see PxArticulationReducedCoordinate + */ + virtual bool addArticulation(PxArticulationReducedCoordinate& articulation) = 0; + + /** + \brief Removes an articulation from this scene. + + \note If the articulation is not part of this scene (see #PxArticulationReducedCoordinate::getScene), the call is ignored and an error is issued. + + \note If the articulation is in an aggregate it will be removed from the aggregate. + + \param[in] articulation The articulation to remove from the scene. + \param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. + Only applies to PxArticulationReducedCoordinate and PxRigidActor types. + + \see PxArticulationReducedCoordinate, PxAggregate + */ + virtual void removeArticulation(PxArticulationReducedCoordinate& articulation, bool wakeOnLostTouch = true) = 0; + + //\} + /************************************************************************************************/ + + /** \name Add/Remove Actors + */ + //\{ + /** + \brief Adds an actor to this scene. + + \note If the actor is already assigned to a scene (see #PxActor::getScene), the call is ignored and an error is issued. + \note If the actor has an invalid constraint, in checked builds the call is ignored and an error is issued. + + \note You can not add individual articulation links (see #PxArticulationLink) to the scene. Use #addArticulation() instead. + + \note If the actor is a PxRigidActor then each assigned PxConstraint object will get added to the scene automatically if + it connects to another actor that is part of the scene already. + + \note When a BVH is provided the actor shapes are grouped together. + The scene query pruning structure inside PhysX SDK will store/update one + bound per actor. The scene queries against such an actor will query actor + bounds and then make a local space query against the provided BVH, which is in actor's local space. + + \param[in] actor Actor to add to scene. + \param[in] bvh BVH for actor shapes. + \return True if success + + \see PxActor, PxConstraint::isValid(), PxBVH + */ + virtual bool addActor(PxActor& actor, const PxBVH* bvh = NULL) = 0; + + /** + \brief Adds actors to this scene. Only supports actors of type PxRigidStatic and PxRigidDynamic. + + \note This method only supports actors of type PxRigidStatic and PxRigidDynamic. For other actors, use addActor() instead. + For articulation links, use addArticulation(). + + \note If one of the actors is already assigned to a scene (see #PxActor::getScene), the call is ignored and an error is issued. + + \note If an actor in the array contains an invalid constraint, in checked builds the call is ignored and an error is issued. + \note If an actor in the array is a PxRigidActor then each assigned PxConstraint object will get added to the scene automatically if + it connects to another actor that is part of the scene already. + + \note this method is optimized for high performance. + + \param[in] actors Array of actors to add to scene. + \param[in] nbActors Number of actors in the array. + \return True if success + + \see PxActor, PxConstraint::isValid() + */ + virtual bool addActors(PxActor*const* actors, PxU32 nbActors) = 0; + + /** + \brief Adds a pruning structure together with its actors to this scene. Only supports actors of type PxRigidStatic and PxRigidDynamic. + + \note This method only supports actors of type PxRigidStatic and PxRigidDynamic. For other actors, use addActor() instead. + For articulation links, use addArticulation(). + + \note If an actor in the pruning structure contains an invalid constraint, in checked builds the call is ignored and an error is issued. + \note For all actors in the pruning structure each assigned PxConstraint object will get added to the scene automatically if + it connects to another actor that is part of the scene already. + + \note This method is optimized for high performance. + + \note Merging a PxPruningStructure into an active scene query optimization AABB tree might unbalance the tree. A typical use case for + PxPruningStructure is a large world scenario where blocks of closely positioned actors get streamed in. The merge process finds the + best node in the active scene query optimization AABB tree and inserts the PxPruningStructure. Therefore using PxPruningStructure + for actors scattered throughout the world will result in an unbalanced tree. + + \param[in] pruningStructure Pruning structure for a set of actors. + \return True if success + + \see PxPhysics::createPruningStructure, PxPruningStructure + */ + virtual bool addActors(const PxPruningStructure& pruningStructure) = 0; + + /** + \brief Removes an actor from this scene. + + \note If the actor is not part of this scene (see #PxActor::getScene), the call is ignored and an error is issued. + + \note You can not remove individual articulation links (see #PxArticulationLink) from the scene. Use #removeArticulation() instead. + + \note If the actor is a PxRigidActor then all assigned PxConstraint objects will get removed from the scene automatically. + + \note If the actor is in an aggregate it will be removed from the aggregate. + + \param[in] actor Actor to remove from scene. + \param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCoordinate and PxRigidActor types. + + \see PxActor, PxAggregate + */ + virtual void removeActor(PxActor& actor, bool wakeOnLostTouch = true) = 0; + + /** + \brief Removes actors from this scene. Only supports actors of type PxRigidStatic and PxRigidDynamic. + + \note This method only supports actors of type PxRigidStatic and PxRigidDynamic. For other actors, use removeActor() instead. + For articulation links, use removeArticulation(). + + \note If some actor is not part of this scene (see #PxActor::getScene), the actor remove is ignored and an error is issued. + + \note You can not remove individual articulation links (see #PxArticulationLink) from the scene. Use #removeArticulation() instead. + + \note If the actor is a PxRigidActor then all assigned PxConstraint objects will get removed from the scene automatically. + + \param[in] actors Array of actors to add to scene. + \param[in] nbActors Number of actors in the array. + \param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCooridnate and PxRigidActor types. + + \see PxActor + */ + virtual void removeActors(PxActor*const* actors, PxU32 nbActors, bool wakeOnLostTouch = true) = 0; + + /** + \brief Adds an aggregate to this scene. + + \note If the aggregate is already assigned to a scene (see #PxAggregate::getScene), the call is ignored and an error is issued. + \note If the aggregate contains an actor with an invalid constraint, in checked builds the call is ignored and an error is issued. + + \note If the aggregate already contains actors, those actors are added to the scene as well. + + \param[in] aggregate Aggregate to add to scene. + \return True if success + + \see PxAggregate, PxConstraint::isValid() + */ + virtual bool addAggregate(PxAggregate& aggregate) = 0; + + /** + \brief Removes an aggregate from this scene. + + \note If the aggregate is not part of this scene (see #PxAggregate::getScene), the call is ignored and an error is issued. + + \note If the aggregate contains actors, those actors are removed from the scene as well. + + \param[in] aggregate Aggregate to remove from scene. + \param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCoordinate and PxRigidActor types. + + \see PxAggregate + */ + virtual void removeAggregate(PxAggregate& aggregate, bool wakeOnLostTouch = true) = 0; + + /** + \brief Adds objects in the collection to this scene. + + This function adds the following types of objects to this scene: PxRigidActor (except PxArticulationLink), PxAggregate, PxArticulationReducedCoordinate. + This method is typically used after deserializing the collection in order to populate the scene with deserialized objects. + + \note If the collection contains an actor with an invalid constraint, in checked builds the call is ignored and an error is issued. + + \param[in] collection Objects to add to this scene. See #PxCollection + \return True if success + + \see PxCollection, PxConstraint::isValid() + */ + virtual bool addCollection(const PxCollection& collection) = 0; + //\} + /************************************************************************************************/ + + /** \name Contained Object Retrieval + */ + //\{ + + /** + \brief Retrieve the number of actors of certain types in the scene. For supported types, see PxActorTypeFlags. + + \param[in] types Combination of actor types. + \return the number of actors. + + \see getActors() + */ + virtual PxU32 getNbActors(PxActorTypeFlags types) const = 0; + + /** + \brief Retrieve an array of all the actors of certain types in the scene. For supported types, see PxActorTypeFlags. + + \param[in] types Combination of actor types to retrieve. + \param[out] userBuffer The buffer to receive actor pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first actor pointer to be retrieved + \return Number of actors written to the buffer. + + \see getNbActors() + */ + virtual PxU32 getActors(PxActorTypeFlags types, PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Queries the PxScene for a list of the PxActors whose transforms have been + updated during the previous simulation step. Only includes actors of type PxRigidDynamic and PxArticulationLink. + + \note PxSceneFlag::eENABLE_ACTIVE_ACTORS must be set. + + \note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored and NULL will be returned. + + \note This list may contain actors that have been released after fetchResults() of the previous simulation step. It is the user's + responsibility to track such actors and avoid dereferencing the corresponding pointers. + + \param[out] nbActorsOut The number of actors returned. + + \return A pointer to the list of active PxActors generated during the last call to fetchResults(). + + \see PxActor + */ + virtual PxActor** getActiveActors(PxU32& nbActorsOut) = 0; + + /** + \brief Retrieve the number of deformable surfaces in the scene. + + \return the number of deformable surfaces. + + See getDeformableSurfaces() + */ + virtual PxU32 getNbDeformableSurfaces() const = 0; + + /** + \brief Retrieve an array of all the deformable surfaces in the scene. + + \param[out] userBuffer The buffer to write the deformable surface pointers to + \param[in] bufferSize Size of the provided user buffer + \param[in] startIndex Index of first deformable surface pointer to be retrieved + \return Number of deformable surfaces written to the buffer + */ + virtual PxU32 getDeformableSurfaces(PxDeformableSurface** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Retrieve the number of deformable volumes in the scene. + + \return the number of deformable volumes. + + \see getActors() + */ + virtual PxU32 getNbDeformableVolumes() const = 0; + + /** + \brief Deprecated + \see getNbDeformableVolumes + */ + PX_DEPRECATED PX_FORCE_INLINE PxU32 getNbSoftBodies() const + { + return getNbDeformableVolumes(); + } + + /** + \brief Retrieve an array of all the deformable volumes in the scene. + + \param[out] userBuffer The buffer to receive actor pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first actor pointer to be retrieved + \return Number of actors written to the buffer. + + \see getNbActors() + */ + virtual PxU32 getDeformableVolumes(PxDeformableVolume** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Deprecated + \see getDeformableVolumes + */ + PX_DEPRECATED PX_FORCE_INLINE PxU32 getSoftBodies(PxDeformableVolume** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const + { + return getDeformableVolumes(userBuffer, bufferSize, startIndex); + } + + /** + \deprecated Use getNbPBDParticleSystems() instead. + \brief Retrieve the number of particle systems of the requested type in the scene. + + \param[in] type The particle system type. See PxParticleSolverType. Only one type can be requested per function call. + \return the number particle systems. + + See getPBDParticleSystems(), PxParticleSolverType + */ + PX_DEPRECATED virtual PxU32 getNbParticleSystems(PxParticleSolverType::Enum type) const = 0; + + /** + \deprecated Use getPBDParticleSystems() instead. + \brief Retrieve an array of all the particle systems of the requested type in the scene. + + \param[in] type The particle system type. See PxParticleSolverType. Only one type can be requested per function call. + \param[out] userBuffer The buffer to receive particle system pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first particle system pointer to be retrieved + \return Number of particle systems written to the buffer. + + See getNbPBDParticleSystems(), PxParticleSolverType + */ + PX_DEPRECATED virtual PxU32 getParticleSystems(PxParticleSolverType::Enum type, class PxPBDParticleSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Retrieve the number of particle systems of the requested type in the scene. + + \return the number particle systems. + + \see getPBDParticleSystems() + */ + virtual PxU32 getNbPBDParticleSystems() const = 0; + + /** + \brief Retrieve an array of all the particle systems of the requested type in the scene. + + \param[out] userBuffer The buffer to receive particle system pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first particle system pointer to be retrieved + \return Number of particle systems written to the buffer. + + \see getNbPBDParticleSystems() + */ + virtual PxU32 getPBDParticleSystems(class PxPBDParticleSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Returns the number of articulations in the scene. + + \return the number of articulations in this scene. + + \see getArticulations() + */ + virtual PxU32 getNbArticulations() const = 0; + + /** + \brief Retrieve all the articulations in the scene. + + \param[out] userBuffer The buffer to receive articulations pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first articulations pointer to be retrieved + \return Number of articulations written to the buffer. + + \see getNbArticulations() + */ + virtual PxU32 getArticulations(PxArticulationReducedCoordinate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Returns the number of constraint shaders in the scene. + + \return the number of constraint shaders in this scene. + + \see getConstraints() + */ + virtual PxU32 getNbConstraints() const = 0; + + /** + \brief Retrieve all the constraint shaders in the scene. + + \param[out] userBuffer The buffer to receive constraint shader pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first constraint pointer to be retrieved + \return Number of constraint shaders written to the buffer. + + \see getNbConstraints() + */ + virtual PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Returns the number of aggregates in the scene. + + \return the number of aggregates in this scene. + + \see getAggregates() + */ + virtual PxU32 getNbAggregates() const = 0; + + /** + \brief Retrieve all the aggregates in the scene. + + \param[out] userBuffer The buffer to receive aggregates pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first aggregate pointer to be retrieved + \return Number of aggregates written to the buffer. + + \see getNbAggregates() + */ + virtual PxU32 getAggregates(PxAggregate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + //\} + /************************************************************************************************/ + + /** \name Dominance + */ + //\{ + + /** + \brief Specifies the dominance behavior of contacts between two actors with two certain dominance groups. + + It is possible to assign each actor to a dominance groups using #PxActor::setDominanceGroup(). + + With dominance groups one can have all contacts created between actors act in one direction only. This is useful, for example, if you + want an object to push debris out of its way and be unaffected,while still responding physically to forces and collisions + with non-debris objects. + + Whenever a contact between two actors (a0, a1) needs to be solved, the groups (g0, g1) of both + actors are retrieved. Then the PxDominanceGroupPair setting for this group pair is retrieved with getDominanceGroupPair(g0, g1). + + In the contact, PxDominanceGroupPair::dominance0 becomes the dominance setting for a0, and + PxDominanceGroupPair::dominance1 becomes the dominance setting for a1. A dominanceN setting of 1.0f, the default, + will permit aN to be pushed or pulled by a(1-N) through the contact. A dominanceN setting of 0.0f, will however + prevent aN to be pushed by a(1-N) via the contact. Thus, a PxDominanceGroupPair of (1.0f, 0.0f) makes + the interaction one-way. + + + The matrix sampled by getDominanceGroupPair(g1, g2) is initialised by default such that: + + if g1 == g2, then (1.0f, 1.0f) is returned + if g1 < g2, then (0.0f, 1.0f) is returned + if g1 > g2, then (1.0f, 0.0f) is returned + + In other words, we permit actors in higher groups to be pushed around by actors in lower groups by default. + + These settings should cover most applications, and in fact not overriding these settings may likely result in higher performance. + + It is not possible to make the matrix asymetric, or to change the diagonal. In other words: + + * it is not possible to change (g1, g2) if (g1==g2) + * if you set + + (g1, g2) to X, then (g2, g1) will implicitly and automatically be set to ~X, where: + + ~(1.0f, 1.0f) is (1.0f, 1.0f) + ~(0.0f, 1.0f) is (1.0f, 0.0f) + ~(1.0f, 0.0f) is (0.0f, 1.0f) + + These two restrictions are to make sure that contacts between two actors will always evaluate to the same dominance + setting, regardless of the order of the actors. + + Dominance settings are currently specified as floats 0.0f or 1.0f because in the future we may permit arbitrary + fractional settings to express 'partly-one-way' interactions. + + Sleeping: Does NOT wake actors up automatically. + + \see getDominanceGroupPair() PxDominanceGroup PxDominanceGroupPair PxActor::setDominanceGroup() PxActor::getDominanceGroup() + */ + virtual void setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance) = 0; + + /** + \brief Samples the dominance matrix. + + \see setDominanceGroupPair() PxDominanceGroup PxDominanceGroupPair PxActor::setDominanceGroup() PxActor::getDominanceGroup() + */ + virtual PxDominanceGroupPair getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const = 0; + + //\} + /************************************************************************************************/ + + /** \name Dispatcher + */ + //\{ + + /** + \brief Return the cpu dispatcher that was set in PxSceneDesc::cpuDispatcher when creating the scene with PxPhysics::createScene + + \see PxSceneDesc::cpuDispatcher, PxPhysics::createScene + */ + virtual PxCpuDispatcher* getCpuDispatcher() const = 0; + + /** + \brief Return the CUDA context manager that was set in PxSceneDesc::cudaContextManager when creating the scene with PxPhysics::createScene + + Platform specific: Applies to PC GPU only. + + \see PxSceneDesc::cudaContextManager, PxPhysics::createScene + */ + virtual PxCudaContextManager* getCudaContextManager() const = 0; + + //\} + /************************************************************************************************/ + /** \name Multiclient + */ + //\{ + /** + \brief Reserves a new client ID. + + PX_DEFAULT_CLIENT is always available as the default clientID. + Additional clients are returned by this function. Clients cannot be released once created. + An error is reported when more than a supported number of clients (currently 128) are created. + + \see PxClientID + */ + virtual PxClientID createClient() = 0; + + //\} + + /************************************************************************************************/ + + /** \name Callbacks + */ + //\{ + + /** + \brief Sets a user notify object which receives special simulation events when they occur. + + \note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored. + + \param[in] callback User notification callback. See #PxSimulationEventCallback. + + \see PxSimulationEventCallback getSimulationEventCallback + */ + virtual void setSimulationEventCallback(PxSimulationEventCallback* callback) = 0; + + /** + \brief Retrieves the simulationEventCallback pointer set with setSimulationEventCallback(). + + \return The current user notify pointer. See #PxSimulationEventCallback. + + \see PxSimulationEventCallback setSimulationEventCallback() + */ + virtual PxSimulationEventCallback* getSimulationEventCallback() const = 0; + + /** + \brief Sets a user callback object, which receives callbacks on all contacts generated for specified actors. + + \note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored. + + \param[in] callback Asynchronous user contact modification callback. See #PxContactModifyCallback. + */ + virtual void setContactModifyCallback(PxContactModifyCallback* callback) = 0; + + /** + \brief Sets a user callback object, which receives callbacks on all CCD contacts generated for specified actors. + + \note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored. + + \param[in] callback Asynchronous user contact modification callback. See #PxCCDContactModifyCallback. + */ + virtual void setCCDContactModifyCallback(PxCCDContactModifyCallback* callback) = 0; + + /** + \brief Retrieves the PxContactModifyCallback pointer set with setContactModifyCallback(). + + \return The current user contact modify callback pointer. See #PxContactModifyCallback. + + \see PxContactModifyCallback setContactModifyCallback() + */ + virtual PxContactModifyCallback* getContactModifyCallback() const = 0; + + /** + \brief Retrieves the PxCCDContactModifyCallback pointer set with setContactModifyCallback(). + + \return The current user contact modify callback pointer. See #PxContactModifyCallback. + + \see PxContactModifyCallback setContactModifyCallback() + */ + virtual PxCCDContactModifyCallback* getCCDContactModifyCallback() const = 0; + + /** + \brief Sets a broad-phase user callback object. + + \note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored. + + \param[in] callback Asynchronous broad-phase callback. See #PxBroadPhaseCallback. + */ + virtual void setBroadPhaseCallback(PxBroadPhaseCallback* callback) = 0; + + /** + \brief Retrieves the PxBroadPhaseCallback pointer set with setBroadPhaseCallback(). + + \return The current broad-phase callback pointer. See #PxBroadPhaseCallback. + + \see PxBroadPhaseCallback setBroadPhaseCallback() + */ + virtual PxBroadPhaseCallback* getBroadPhaseCallback() const = 0; + + //\} + /************************************************************************************************/ + + /** \name Collision Filtering + */ + //\{ + + /** + \brief Sets the shared global filter data which will get passed into the filter shader. + + \note It is the user's responsibility to ensure that changing the shared global filter data does not change the filter output value for existing pairs. + If the filter output for existing pairs does change nonetheless then such a change will not take effect until the pair gets refiltered. + resetFiltering() can be used to explicitly refilter the pairs of specific objects. + + \note The provided data will get copied to internal buffers and this copy will be used for filtering calls. + + \note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored. + + \param[in] data The shared global filter shader data. + \param[in] dataSize Size of the shared global filter shader data (in bytes). + + \see getFilterShaderData() PxSceneDesc.filterShaderData PxSimulationFilterShader + */ + virtual void setFilterShaderData(const void* data, PxU32 dataSize) = 0; + + /** + \brief Gets the shared global filter data in use for this scene. + + \note The reference points to a copy of the original filter data specified in #PxSceneDesc.filterShaderData or provided by #setFilterShaderData(). + + \return Shared filter data for filter shader. + + \see getFilterShaderDataSize() setFilterShaderData() PxSceneDesc.filterShaderData PxSimulationFilterShader + */ + virtual const void* getFilterShaderData() const = 0; + + /** + \brief Gets the size of the shared global filter data (#PxSceneDesc.filterShaderData) + + \return Size of shared filter data [bytes]. + + \see getFilterShaderData() PxSceneDesc.filterShaderDataSize PxSimulationFilterShader + */ + virtual PxU32 getFilterShaderDataSize() const = 0; + + /** + \brief Gets the custom collision filter shader in use for this scene. + + \return Filter shader class that defines the collision pair filtering. + + \see PxSceneDesc.filterShader PxSimulationFilterShader + */ + virtual PxSimulationFilterShader getFilterShader() const = 0; + + /** + \brief Gets the custom collision filter callback in use for this scene. + + \return Filter callback class that defines the collision pair filtering. + + \see PxSceneDesc.filterCallback PxSimulationFilterCallback + */ + virtual PxSimulationFilterCallback* getFilterCallback() const = 0; + + /** + \brief Marks the object to reset interactions and re-run collision filters in the next simulation step. + + This call forces the object to remove all existing collision interactions, to search anew for existing contact + pairs and to run the collision filters again for found collision pairs. + + \note The operation is supported for PxRigidActor objects only. + + \note All persistent state of existing interactions will be lost and can not be retrieved even if the same collison pair + is found again in the next step. This will mean, for example, that you will not get notified about persistent contact + for such an interaction (see #PxPairFlag::eNOTIFY_TOUCH_PERSISTS), the contact pair will be interpreted as newly found instead. + + \note Lost touch contact reports will be sent for every collision pair which includes this shape, if they have + been requested through #PxPairFlag::eNOTIFY_TOUCH_LOST or #PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST. + + \note This is an expensive operation, don't use it if you don't have to. + + \note Can be used to retrieve collision pairs that were killed by the collision filters (see #PxFilterFlag::eKILL) + + \note It is invalid to use this method if the actor has not been added to a scene already. + + \note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set. + + \note Do not use this method while the simulation is running. + + Sleeping: Does wake up the actor. + + \param[in] actor The actor for which to re-evaluate interactions. + \return True if success + + \see PxSimulationFilterShader PxSimulationFilterCallback + */ + virtual bool resetFiltering(PxActor& actor) = 0; + + /** + \brief Marks the object to reset interactions and re-run collision filters for specified shapes in the next simulation step. + + This is a specialization of the resetFiltering(PxActor& actor) method and allows to reset interactions for specific shapes of + a PxRigidActor. + + \note Do not use this method while the simulation is running. + + Sleeping: Does wake up the actor. + + \param[in] actor The actor for which to re-evaluate interactions. + \param[in] shapes The shapes for which to re-evaluate interactions. + \param[in] shapeCount Number of shapes in the list. + + \see PxSimulationFilterShader PxSimulationFilterCallback + */ + virtual bool resetFiltering(PxRigidActor& actor, PxShape*const* shapes, PxU32 shapeCount) = 0; + + /** + \brief Gets the pair filtering mode for kinematic-kinematic pairs. + + \return Filtering mode for kinematic-kinematic pairs. + + \see PxPairFilteringMode PxSceneDesc + */ + virtual PxPairFilteringMode::Enum getKinematicKinematicFilteringMode() const = 0; + + /** + \brief Gets the pair filtering mode for static-kinematic pairs. + + \return Filtering mode for static-kinematic pairs. + + \see PxPairFilteringMode PxSceneDesc + */ + virtual PxPairFilteringMode::Enum getStaticKinematicFilteringMode() const = 0; + + //\} + /************************************************************************************************/ + + /** \name Simulation + */ + //\{ + /** + \brief Advances the simulation by an elapsedTime time. + + \note Large elapsedTime values can lead to instabilities. In such cases elapsedTime + should be subdivided into smaller time intervals and simulate() should be called + multiple times for each interval. + + Calls to simulate() should pair with calls to fetchResults(): + Each fetchResults() invocation corresponds to exactly one simulate() + invocation; calling simulate() twice without an intervening fetchResults() + or fetchResults() twice without an intervening simulate() causes an error + condition. + + scene->simulate(); + ...do some processing until physics is computed... + scene->fetchResults(); + ...now results of run may be retrieved. + + + \param[in] elapsedTime Amount of time to advance simulation by. The parameter has to be larger than 0, else the resulting behavior will be undefined. Range: (0, PX_MAX_F32) + \param[in] completionTask if non-NULL, this task will have its refcount incremented in simulate(), then + decremented when the scene is ready to have fetchResults called. So the task will not run until the + application also calls removeReference(). + \param[in] scratchMemBlock a memory region for physx to use for temporary data during simulation. This block may be reused by the application + after fetchResults returns. Must be aligned on a 16-byte boundary + \param[in] scratchMemBlockSize the size of the scratch memory block. Must be a multiple of 16K. + \param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave + true unless the application is calling the PxTaskManager start/stopSimulation() methods itself. + \return True if success + + \see fetchResults() checkResults() + */ + virtual bool simulate(PxReal elapsedTime, physx::PxBaseTask* completionTask = NULL, + void* scratchMemBlock = 0, PxU32 scratchMemBlockSize = 0, bool controlSimulation = true) = 0; + + /** + \brief Performs dynamics phase of the simulation pipeline. + + \note Calls to advance() should follow calls to fetchCollision(). An error message will be issued if this sequence is not followed. + + \param[in] completionTask if non-NULL, this task will have its refcount incremented in advance(), then + decremented when the scene is ready to have fetchResults called. So the task will not run until the + application also calls removeReference(). + \return True if success + */ + virtual bool advance(physx::PxBaseTask* completionTask = 0) = 0; + + /** + \brief Performs collision detection for the scene over elapsedTime + + \note Calls to collide() should be the first method called to simulate a frame. + + + \param[in] elapsedTime Amount of time to advance simulation by. The parameter has to be larger than 0, else the resulting behavior will be undefined. Range: (0, PX_MAX_F32) + \param[in] completionTask if non-NULL, this task will have its refcount incremented in collide(), then + decremented when the scene is ready to have fetchResults called. So the task will not run until the + application also calls removeReference(). + \param[in] scratchMemBlock a memory region for physx to use for temporary data during simulation. This block may be reused by the application + after fetchResults returns. Must be aligned on a 16-byte boundary + \param[in] scratchMemBlockSize the size of the scratch memory block. Must be a multiple of 16K. + \param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave + true unless the application is calling the PxTaskManager start/stopSimulation() methods itself. + \return True if success + */ + virtual bool collide(PxReal elapsedTime, physx::PxBaseTask* completionTask = 0, void* scratchMemBlock = 0, + PxU32 scratchMemBlockSize = 0, bool controlSimulation = true) = 0; + + /** + \brief This checks to see if the simulation run has completed. + + This does not cause the data available for reading to be updated with the results of the simulation, it is simply a status check. + The bool will allow it to either return immediately or block waiting for the condition to be met so that it can return true + + \param[in] block When set to true will block until the condition is met. + \return True if the results are available. + + \see simulate() fetchResults() + */ + virtual bool checkResults(bool block = false) = 0; + + /** + This method must be called after collide() and before advance(). It will wait for the collision phase to finish. If the user makes an illegal simulation call, the SDK will issue an error + message. + + \param[in] block When set to true will block until the condition is met, which is collision must finish running. + */ + virtual bool fetchCollision(bool block = false) = 0; + + /** + This is the big brother to checkResults() it basically does the following: + + \code + if ( checkResults(block) ) + { + fire appropriate callbacks + swap buffers + return true + } + else + return false + + \endcode + + \param[in] block When set to true will block until results are available. + \param[out] errorState Used to retrieve hardware error codes. A non zero value indicates an error. + \return True if the results have been fetched. + + \see simulate() checkResults() + */ + virtual bool fetchResults(bool block = false, PxU32* errorState = 0) = 0; + + /** + This call performs the first section of fetchResults, and returns a pointer to the contact streams output by the simulation. It can be used to process contact pairs in parallel, which is often a limiting factor + for fetchResults() performance. + + After calling this function and processing the contact streams, call fetchResultsFinish(). Note that writes to the simulation are not + permitted between the start of fetchResultsStart() and the end of fetchResultsFinish(). + + \param[in] block When set to true will block until results are available. + \param[out] contactPairs an array of pointers to contact pair headers + \param[out] nbContactPairs the number of contact pairs + \return True if the results have been fetched. + + \see simulate() checkResults() fetchResults() fetchResultsFinish() + */ + virtual bool fetchResultsStart(const PxContactPairHeader*& contactPairs, PxU32& nbContactPairs, bool block = false) = 0; + + /** + This call processes all event callbacks in parallel. It takes a continuation task, which will be executed once all callbacks have been processed. + + This is a utility function to make it easier to process callbacks in parallel using the PhysX task system. It can only be used in conjunction with + fetchResultsStart(...) and fetchResultsFinish(...) + + \param[in] continuation The task that will be executed once all callbacks have been processed. + */ + virtual void processCallbacks(physx::PxBaseTask* continuation) = 0; + + /** + This call performs the second section of fetchResults. + + It must be called after fetchResultsStart() returns and contact reports have been processed. + + Note that once fetchResultsFinish() has been called, the contact streams returned in fetchResultsStart() will be invalid. + + \param[out] errorState Used to retrieve hardware error codes. A non zero value indicates an error. + + \see simulate() checkResults() fetchResults() fetchResultsStart() + */ + virtual void fetchResultsFinish(PxU32* errorState = 0) = 0; + + /** + This call performs the synchronization of particle system data copies. + */ + virtual void fetchResultsParticleSystem() = 0; + + /** + \brief Clear internal buffers and free memory. + + This method can be used to clear buffers and free internal memory without having to destroy the scene. Can be useful if + the physics data gets streamed in and a checkpoint with a clean state should be created. + + \note It is not allowed to call this method while the simulation is running. The call will fail. + + \param[in] sendPendingReports When set to true pending reports will be sent out before the buffers get cleaned up (for instance lost touch contact/trigger reports due to deleted objects). + */ + virtual void flushSimulation(bool sendPendingReports = false) = 0; + + /** + \brief Sets a constant gravity for the entire scene. + + \note Do not use this method while the simulation is running. + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] vec A new gravity vector(e.g. PxVec3(0.0f,-9.8f,0.0f) ) Range: force vector + + \see PxSceneDesc.gravity getGravity() + */ + virtual void setGravity(const PxVec3& vec) = 0; + + /** + \brief Retrieves the current gravity setting. + + \return The current gravity for the scene. + + \see setGravity() PxSceneDesc.gravity + */ + virtual PxVec3 getGravity() const = 0; + + /** + \brief Set the bounce threshold velocity. Collision speeds below this threshold will not cause a bounce. + + \note Do not use this method while the simulation is running. + + \see PxSceneDesc::bounceThresholdVelocity, getBounceThresholdVelocity + */ + virtual void setBounceThresholdVelocity(const PxReal t) = 0; + + /** + \brief Return the bounce threshold velocity. + + \see PxSceneDesc.bounceThresholdVelocity, setBounceThresholdVelocity + */ + virtual PxReal getBounceThresholdVelocity() const = 0; + + /** + \brief Sets the maximum number of CCD passes + + \note Do not use this method while the simulation is running. + + \param[in] ccdMaxPasses Maximum number of CCD passes + + \see PxSceneDesc.ccdMaxPasses getCCDMaxPasses() + */ + virtual void setCCDMaxPasses(PxU32 ccdMaxPasses) = 0; + + /** + \brief Gets the maximum number of CCD passes. + + \return The maximum number of CCD passes. + + \see PxSceneDesc::ccdMaxPasses setCCDMaxPasses() + */ + virtual PxU32 getCCDMaxPasses() const = 0; + + /** + \brief Set the maximum CCD separation. + + \note Do not use this method while the simulation is running. + + \see PxSceneDesc::ccdMaxSeparation, getCCDMaxSeparation + */ + virtual void setCCDMaxSeparation(const PxReal t) = 0; + + /** + \brief Gets the maximum CCD separation. + + \return The maximum CCD separation. + + \see PxSceneDesc::ccdMaxSeparation setCCDMaxSeparation() + */ + virtual PxReal getCCDMaxSeparation() const = 0; + + /** + \brief Set the CCD threshold. + + \note Do not use this method while the simulation is running. + + \see PxSceneDesc::ccdThreshold, getCCDThreshold + */ + virtual void setCCDThreshold(const PxReal t) = 0; + + /** + \brief Gets the CCD threshold. + + \return The CCD threshold. + + \see PxSceneDesc::ccdThreshold setCCDThreshold() + */ + virtual PxReal getCCDThreshold() const = 0; + + /** + \brief Set the max bias coefficient. + + \note Do not use this method while the simulation is running. + + \see PxSceneDesc::maxBiasCoefficient, getMaxBiasCoefficient + */ + virtual void setMaxBiasCoefficient(const PxReal t) = 0; + + /** + \brief Gets the max bias coefficient. + + \return The max bias coefficient. + + \see PxSceneDesc::maxBiasCoefficient setMaxBiasCoefficient() + */ + virtual PxReal getMaxBiasCoefficient() const = 0; + + /** + \brief Set the friction offset threshold. + + \note Do not use this method while the simulation is running. + + \see PxSceneDesc::frictionOffsetThreshold, getFrictionOffsetThreshold + */ + virtual void setFrictionOffsetThreshold(const PxReal t) = 0; + + /** + \brief Gets the friction offset threshold. + + \see PxSceneDesc::frictionOffsetThreshold, setFrictionOffsetThreshold + */ + virtual PxReal getFrictionOffsetThreshold() const = 0; + + /** + \brief Set the friction correlation distance. + + \note Do not use this method while the simulation is running. + + \see PxSceneDesc::frictionCorrelationDistance, getFrictionCorrelationDistance + */ + virtual void setFrictionCorrelationDistance(const PxReal t) = 0; + + /** + \brief Gets the friction correlation distance. + + \see PxSceneDesc::frictionCorrelationDistance, setFrictionCorrelationDistance + */ + virtual PxReal getFrictionCorrelationDistance() const = 0; + + /** + \brief Return the friction model. + + \deprecated Since only the patch friction model is supported now, the friction type option is obsolete. + + \see PxFrictionType, PxSceneDesc::frictionType + */ + PX_DEPRECATED virtual PxFrictionType::Enum getFrictionType() const = 0; + + /** + \brief Return the solver model. + \see PxSolverType, PxSceneDesc::solverType + */ + virtual PxSolverType::Enum getSolverType() const = 0; + + //\} + /************************************************************************************************/ + + /** \name Visualization and Statistics + */ + //\{ + /** + \brief Function that lets you set debug visualization parameters. + + Returns false if the value passed is out of range for usage specified by the enum. + + \note Do not use this method while the simulation is running. + + \param[in] param Parameter to set. See #PxVisualizationParameter + \param[in] value The value to set, see #PxVisualizationParameter for allowable values. Setting to zero disables visualization for the specified property, setting to a positive value usually enables visualization and defines the scale factor. + \return False if the parameter is out of range. + + \see getVisualizationParameter PxVisualizationParameter getRenderBuffer() + */ + virtual bool setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value) = 0; + + /** + \brief Function that lets you query debug visualization parameters. + + \param[in] paramEnum The Parameter to retrieve. + \return The value of the parameter. + + \see setVisualizationParameter PxVisualizationParameter + */ + virtual PxReal getVisualizationParameter(PxVisualizationParameter::Enum paramEnum) const = 0; + + /** + \brief Defines a box in world space to which visualization geometry will be (conservatively) culled. Use a non-empty culling box to enable the feature, and an empty culling box to disable it. + + \note Do not use this method while the simulation is running. + + \param[in] box the box to which the geometry will be culled. Empty box to disable the feature. + \see setVisualizationParameter getVisualizationCullingBox getRenderBuffer() + */ + virtual void setVisualizationCullingBox(const PxBounds3& box) = 0; + + /** + \brief Retrieves the visualization culling box. + + \return the box to which the geometry will be culled. + \see setVisualizationParameter setVisualizationCullingBox + */ + virtual PxBounds3 getVisualizationCullingBox() const = 0; + + /** + \brief Retrieves the render buffer. + + This will contain the results of any active visualization for this scene. + + \note Do not use this method while the simulation is running. Calls to this method while the simulation is running will result in undefined behaviour. + + \return The render buffer. + + \see PxRenderBuffer + */ + virtual const PxRenderBuffer& getRenderBuffer() = 0; + + /** + \brief Call this method to retrieve statistics for the current simulation step. + + \note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored. + + \param[out] stats Used to retrieve statistics for the current simulation step. + + \see PxSimulationStatistics + */ + virtual void getSimulationStatistics(PxSimulationStatistics& stats) const = 0; + + //\} + + /************************************************************************************************/ + /** \name Broad-phase + */ + //\{ + + /** + \brief Returns broad-phase type. + + \return Broad-phase type + */ + virtual PxBroadPhaseType::Enum getBroadPhaseType() const = 0; + + /** + \brief Gets broad-phase caps. + + \param[out] caps Broad-phase caps + \return True if success + */ + virtual bool getBroadPhaseCaps(PxBroadPhaseCaps& caps) const = 0; + + /** + \brief Returns number of regions currently registered in the broad-phase. + + \return Number of regions + */ + virtual PxU32 getNbBroadPhaseRegions() const = 0; + + /** + \brief Gets broad-phase regions. + + \param[out] userBuffer Returned broad-phase regions + \param[in] bufferSize Size of userBuffer + \param[in] startIndex Index of first desired region, in [0 ; getNbRegions()[ + \return Number of written out regions + */ + virtual PxU32 getBroadPhaseRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Adds a new broad-phase region. + + The bounds for the new region must be non-empty, otherwise an error occurs and the call is ignored. + + Note that by default, objects already existing in the SDK that might touch this region will not be automatically + added to the region. In other words the newly created region will be empty, and will only be populated with new + objects when they are added to the simulation, or with already existing objects when they are updated. + + It is nonetheless possible to override this default behavior and let the SDK populate the new region automatically + with already existing objects overlapping the incoming region. This has a cost though, and it should only be used + when the game can not guarantee that all objects within the new region will be added to the simulation after the + region itself. + + Objects automatically move from one region to another during their lifetime. The system keeps tracks of what + regions a given object is in. It is legal for an object to be in an arbitrary number of regions. However if an + object leaves all regions, or is created outside of all regions, several things happen: + - collisions get disabled for this object + - if a PxBroadPhaseCallback object is provided, an "out-of-bounds" event is generated via that callback + - if a PxBroadPhaseCallback object is not provided, a warning/error message is sent to the error stream + + If an object goes out-of-bounds and user deletes it during the same frame, neither the out-of-bounds event nor the + error message is generated. + + \param[in] region User-provided region data + \param[in] populateRegion Automatically populate new region with already existing objects overlapping it + \return Handle for newly created region, or 0xffffffff in case of failure. + \see PxBroadPhaseRegion PxBroadPhaseCallback + */ + virtual PxU32 addBroadPhaseRegion(const PxBroadPhaseRegion& region, bool populateRegion=false) = 0; + + /** + \brief Removes a new broad-phase region. + + If the region still contains objects, and if those objects do not overlap any region any more, they are not + automatically removed from the simulation. Instead, the PxBroadPhaseCallback::onObjectOutOfBounds notification + is used for each object. Users are responsible for removing the objects from the simulation if this is the + desired behavior. + + If the handle is invalid, or if a valid handle is removed twice, an error message is sent to the error stream. + + \param[in] handle Region's handle, as returned by PxScene::addBroadPhaseRegion. + \return True if success + */ + virtual bool removeBroadPhaseRegion(PxU32 handle) = 0; + + //\} + + /************************************************************************************************/ + + /** \name Threads and Memory + */ + //\{ + + /** + \brief Get the task manager associated with this scene + + \return the task manager associated with the scene + */ + virtual PxTaskManager* getTaskManager() const = 0; + + /** + \brief Lock the scene for reading from the calling thread. + + When the PxSceneFlag::eREQUIRE_RW_LOCK flag is enabled lockRead() must be + called before any read calls are made on the scene. + + Multiple threads may read at the same time, no threads may read while a thread is writing. + If a call to lockRead() is made while another thread is holding a write lock + then the calling thread will be blocked until the writing thread calls unlockWrite(). + + \note Lock upgrading is *not* supported, that means it is an error to + call lockRead() followed by lockWrite(). + + \note Recursive locking is supported but each lockRead() call must be paired with an unlockRead(). + + \param file String representing the calling file, for debug purposes + \param line The source file line number, for debug purposes + */ + virtual void lockRead(const char* file=NULL, PxU32 line=0) = 0; + + /** + \brief Unlock the scene from reading. + + \note Each unlockRead() must be paired with a lockRead() from the same thread. + */ + virtual void unlockRead() = 0; + + /** + \brief Lock the scene for writing from this thread. + + When the PxSceneFlag::eREQUIRE_RW_LOCK flag is enabled lockWrite() must be + called before any write calls are made on the scene. + + Only one thread may write at a time and no threads may read while a thread is writing. + If a call to lockWrite() is made and there are other threads reading then the + calling thread will be blocked until the readers complete. + + Writers have priority. If a thread is blocked waiting to write then subsequent calls to + lockRead() from other threads will be blocked until the writer completes. + + \note If multiple threads are waiting to write then the thread that is first + granted access depends on OS scheduling. + + \note Recursive locking is supported but each lockWrite() call must be paired + with an unlockWrite(). + + \note If a thread has already locked the scene for writing then it may call + lockRead(). + + \param file String representing the calling file, for debug purposes + \param line The source file line number, for debug purposes + */ + virtual void lockWrite(const char* file=NULL, PxU32 line=0) = 0; + + /** + \brief Unlock the scene from writing. + + \note Each unlockWrite() must be paired with a lockWrite() from the same thread. + */ + virtual void unlockWrite() = 0; + + /** + \brief set the cache blocks that can be used during simulate(). + + Each frame the simulation requires memory to store contact, friction, and contact cache data. This memory is used in blocks of 16K. + Each frame the blocks used by the previous frame are freed, and may be retrieved by the application using PxScene::flushSimulation() + + This call will force allocation of cache blocks if the numBlocks parameter is greater than the currently allocated number + of blocks, and less than the max16KContactDataBlocks parameter specified at scene creation time. + + \note Do not use this method while the simulation is running. + + \param[in] numBlocks The number of blocks to allocate. + + \see PxSceneDesc.nbContactDataBlocks PxSceneDesc.maxNbContactDataBlocks flushSimulation() getNbContactDataBlocksUsed getMaxNbContactDataBlocksUsed + */ + virtual void setNbContactDataBlocks(PxU32 numBlocks) = 0; + + /** + \brief get the number of cache blocks currently used by the scene + + This function may not be called while the scene is simulating + + \return the number of cache blocks currently used by the scene + + \see PxSceneDesc.nbContactDataBlocks PxSceneDesc.maxNbContactDataBlocks flushSimulation() setNbContactDataBlocks() getMaxNbContactDataBlocksUsed() + */ + virtual PxU32 getNbContactDataBlocksUsed() const = 0; + + /** + \brief get the maximum number of cache blocks used by the scene + + This function may not be called while the scene is simulating + + \return the maximum number of cache blocks everused by the scene + + \see PxSceneDesc.nbContactDataBlocks PxSceneDesc.maxNbContactDataBlocks flushSimulation() setNbContactDataBlocks() getNbContactDataBlocksUsed() + */ + virtual PxU32 getMaxNbContactDataBlocksUsed() const = 0; + + /** + \brief Return the value of PxSceneDesc::contactReportStreamBufferSize that was set when creating the scene with PxPhysics::createScene + + \see PxSceneDesc::contactReportStreamBufferSize, PxPhysics::createScene + */ + virtual PxU32 getContactReportStreamBufferSize() const = 0; + + /** + \brief Sets the number of actors required to spawn a separate rigid body solver thread. + + \note Do not use this method while the simulation is running. + + \param[in] solverBatchSize Number of actors required to spawn a separate rigid body solver thread. + + \see PxSceneDesc.solverBatchSize getSolverBatchSize() + */ + virtual void setSolverBatchSize(PxU32 solverBatchSize) = 0; + + /** + \brief Retrieves the number of actors required to spawn a separate rigid body solver thread. + + \return Current number of actors required to spawn a separate rigid body solver thread. + + \see PxSceneDesc.solverBatchSize setSolverBatchSize() + */ + virtual PxU32 getSolverBatchSize() const = 0; + + /** + \brief Sets the number of articulations required to spawn a separate rigid body solver thread. + + \note Do not use this method while the simulation is running. + + \param[in] solverBatchSize Number of articulations required to spawn a separate rigid body solver thread. + + \see PxSceneDesc.solverBatchSize getSolverArticulationBatchSize() + */ + virtual void setSolverArticulationBatchSize(PxU32 solverBatchSize) = 0; + + /** + \brief Retrieves the number of articulations required to spawn a separate rigid body solver thread. + + \return Current number of articulations required to spawn a separate rigid body solver thread. + + \see PxSceneDesc.solverBatchSize setSolverArticulationBatchSize() + */ + virtual PxU32 getSolverArticulationBatchSize() const = 0; + + //\} + + /** + \brief Returns the wake counter reset value. + + \return Wake counter reset value + + \see PxSceneDesc.wakeCounterResetValue + */ + virtual PxReal getWakeCounterResetValue() const = 0; + + /** + \brief Shift the scene origin by the specified vector. + + The poses of all objects in the scene and the corresponding data structures will get adjusted to reflect the new origin location + (the shift vector will get subtracted from all object positions). + + \note It is the user's responsibility to keep track of the summed total origin shift and adjust all input/output to/from PhysX accordingly. + + \note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored. + + \note Make sure to propagate the origin shift to other dependent modules (for example, the character controller module etc.). + + \note This is an expensive operation and we recommend to use it only in the case where distance related precision issues may arise in areas far from the origin. + + \param[in] shift Translation vector to shift the origin by. + */ + virtual void shiftOrigin(const PxVec3& shift) = 0; + + /** + \brief Returns the Pvd client associated with the scene. + \return the client, NULL if no PVD supported. + */ + virtual PxPvdSceneClient* getScenePvdClient() = 0; + + /** + \brief Get the PxGpuDynamicsMemoryConfig that was passed into PxPhysics::createScene() as part of PxSceneDesc. + + \note This will return the values passed as initial configuration, for the actual minimal configuration that would be needed + for a specific simulation of a scene, see PxSimulationStatistics::gpuDynamicsMemoryConfigStatistics. + + \return The PxGpuDynamicsMemoryConfig used during scene creation. + + \see PxSceneDesc::gpuDynamicsConfig, PxSimulationStatistics::gpuDynamicsMemoryConfigStatistics + */ + virtual PxGpuDynamicsMemoryConfig getGpuDynamicsConfig() const = 0; + + /** + \brief Get the direct-GPU API instance for this scene. + + \see PxDirectGPUAPI for the supported direct-GPU operations. + + Each object of PxDirectGPUAPI is directly associated with a PxScene, and there is only one PxDirectGPUAPI object per scene. + */ + virtual PxDirectGPUAPI& getDirectGPUAPI() = 0; + + /** + \brief Provides a metric that describes how well the solver converged. The smaller the returned error, the more accurate the solution. + + \note The scene flag eENABLE_SOLVER_RESIDUAL_REPORTING must be set, otherwise the residual will not be computed and the function will return zero. + + \return The residual as a root mean squared or max value of the all corrections applied by the solver in the last position and in the last velocity iteration. + */ + virtual PxSceneResidual getSolverResidual() const = 0; + + /** + \brief Sets the post-solve callback for deformable surface GPU computations. Allows to schedule custom work to be done by the GPU as soon as possible after the deformable surface solver finishes. + \param postSolveCallback Pointer to the callback implementation. + */ + virtual void setDeformableSurfaceGpuPostSolveCallback(PxPostSolveCallback* postSolveCallback) = 0; + + /** + \brief Sets the post-solve callback for deformable volume GPU computations. Allows to schedule custom work to be done by the GPU as soon as possible after the deformable volume solver finishes. + \param postSolveCallback Pointer to the callback implementation. + */ + virtual void setDeformableVolumeGpuPostSolveCallback(PxPostSolveCallback* postSolveCallback) = 0; + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + + /** + \brief Copy GPU deformable volume data from the internal GPU buffer to a user-provided device buffer. + \param[in] data User-provided gpu buffer containing a pointer to another gpu buffer for every deformable volume to process + \param[in] dataSizes The size of every buffer in bytes + \param[in] deformableVolumeIndices User provided gpu index buffer. This buffer stores the deformable volume index which the user want to copy. + \param[in] maxSize The largest size stored in dataSizes. Used internally to decide how many threads to launch for the copy process. + \param[in] flag Flag defining which data the user wants to read back from the deformable volume system + \param[in] nbCopyDeformableVolumes The number of deformable volumes to be copied. + \param[in] copyEvent User-provided event for the user to sync data. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \deprecated There is no direct replacement. Most of the data is exposed in the PxDeformableVolume interface. + */ + PX_DEPRECATED virtual void copySoftBodyData(void** data, void* dataSizes, void* deformableVolumeIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbCopyDeformableVolumes, const PxU32 maxSize, CUevent copyEvent = NULL) = 0; + + /** + \brief Apply user-provided data to the internal deformable volume system. + \param[in] data User-provided gpu buffer containing a pointer to another gpu buffer for every deformable volume to process + \param[in] dataSizes The size of every buffer in bytes + \param[in] deformableVolumeIndices User provided gpu index buffer. This buffer stores the updated deformable volume index. + \param[in] flag Flag defining which data the user wants to write to the deformable volume system + \param[in] maxSize The largest size stored in dataSizes. Used internally to decide how many threads to launch for the copy process. + \param[in] nbUpdatedDeformableVolumes The number of updated deformable volumes + \param[in] applyEvent User-provided event for the deformable volume stream to wait for data. + \param[in] signalEvent User-provided event for the deformable volume stream to signal when the read from the user buffer has completed. Defaults to NULL which means the function will wait for the copy to finish before returning. + + \deprecated There is no direct replacement. Most of the data is exposed in the PxDeformableVolume interface. + */ + PX_DEPRECATED virtual void applySoftBodyData(void** data, void* dataSizes, void* deformableVolumeIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbUpdatedDeformableVolumes, const PxU32 maxSize, CUevent applyEvent = NULL, CUevent signalEvent = NULL) = 0; + + /** + \brief Apply user-provided data to particle buffers. + + This function should be used if the particle buffer flags are already on the device. Otherwise, use PxParticleBuffer::raiseFlags() + from the CPU. + + This assumes the data has been changed directly in the PxParticleBuffer. + + \param[in] indices User-provided index buffer that indexes into the BufferIndexPair and flags list. + \param[in] bufferIndexPair User-provided index pair buffer specifying the unique id and GPU particle system for each PxParticleBuffer. See PxGpuParticleBufferIndexPair. + \param[in] flags Flags to mark what data needs to be updated. See PxParticleBufferFlags. + \param[in] nbUpdatedBuffers The number of particle buffers to update. + \param[in] waitEvent User-provided event for the particle stream to wait for data. Defaults to NULL which means the operation will start immediately. + \param[in] signalEvent User-provided event for the particle stream to signal when the data read from the user buffer has completed. Defaults to NULL which means the function will wait for copy to finish before returning. + + \deprecated There is no direct replacement. The data is exposed in the PxParticleBuffer/PxParticleSystem interface. + */ + PX_DEPRECATED virtual void applyParticleBufferData(const PxU32* indices, const PxGpuParticleBufferIndexPair* bufferIndexPair, const PxParticleBufferFlags* flags, PxU32 nbUpdatedBuffers, CUevent waitEvent = NULL, CUevent signalEvent = NULL) = 0; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSceneDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneDesc.h new file mode 100644 index 000000000..f72edc4a3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneDesc.h @@ -0,0 +1,1165 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SCENE_DESC_H +#define PX_SCENE_DESC_H + +#include "PxSceneQueryDesc.h" +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxBitUtils.h" +#include "PxFiltering.h" +#include "PxBroadPhase.h" +#include "common/PxTolerancesScale.h" +#include "task/PxTask.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxBroadPhaseCallback; + class PxCudaContextManager; + class PxPostSolveCallback; + +/** +\brief Enum for selecting the friction algorithm used for simulation. + +\deprecated Since only the patch friction model is supported now, the friction type option is obsolete. + +#PxFrictionType::ePATCH is the default friction logic (Couloumb type friction model). Friction gets computed per contact patch. +Up to two contact points lying in the contact patch area are selected as friction anchors to which friction impulses are applied. If there +are more than two contact points, to select anchors from, the anchors are selected using a heuristic that tries to maximize the distance +between the anchors within the contact patch area. For each contact patch, two perpendicular axes of the contact patch plane are selected. +A 1D-constraint along each of the two axes is used to implement friction at a friction anchor point. Note that the two axes are processed +separately when the PGS solver type is selected. This can lead to asymmetries when transitioning from dynamic to static friction and vice +versa in certain edge cases. The TGS solver type, on the other hand, works with the combined impulse along the two axes and as such avoids +this potential problem, but this is slightly more computationally expensive. Another difference between TGS and PGS is that TGS applies +friction throughout all position and all velocity iterations, while PGS by default applies friction throughout the last 3 position iterations +and all velocity iterations (unless #PxSceneFlag::eENABLE_FRICTION_EVERY_ITERATION is used). + +#PxFrictionType::eFRICTION_COUNT is the total number of friction models supported by the SDK. +*/ +struct PX_DEPRECATED PxFrictionType +{ + enum Enum + { + ePATCH, //!< Select default patch-friction model. + eFRICTION_COUNT //!< The total number of friction models supported by the SDK. + }; +}; + +/** +\brief Enum for selecting the type of solver used for the simulation. + +#PxSolverType::ePGS selects the iterative sequential impulse solver. This is the same kind of solver used in PhysX 3.4 and earlier releases. + +#PxSolverType::eTGS selects a non linear iterative solver. This kind of solver can lead to improved convergence and handle large mass ratios, long chains and jointed systems better. It is slightly more expensive than the default solver and can introduce more energy to correct joint and contact errors. +*/ +struct PxSolverType +{ + enum Enum + { + ePGS, //!< Projected Gauss-Seidel iterative solver + eTGS //!< Temporal Gauss-Seidel solver + }; +}; + +/** +\brief flags for configuring properties of the scene + +\see PxScene +*/ +struct PxSceneFlag +{ + enum Enum + { + /** + \brief Enable Active Actors Notification. + + This flag enables the Active Actor Notification feature for a scene. This + feature defaults to disabled. When disabled, the function + PxScene::getActiveActors() will always return a NULL list. + + \note There may be a performance penalty for enabling the Active Actor Notification, hence this flag should + only be enabled if the application intends to use the feature. + + Default: False + */ + eENABLE_ACTIVE_ACTORS = (1<<0), + + /** + \brief Enables a second broad phase check after integration that makes it possible to prevent objects from tunneling through eachother. + + PxPairFlag::eDETECT_CCD_CONTACT requires this flag to be specified. + + \note For this feature to be effective for bodies that can move at a significant velocity, the user should raise the flag PxRigidBodyFlag::eENABLE_CCD for them. + \note This flag is not mutable, and must be set in PxSceneDesc at scene creation. + + Default: False + + \see PxRigidBodyFlag::eENABLE_CCD, PxPairFlag::eDETECT_CCD_CONTACT, eDISABLE_CCD_RESWEEP + */ + eENABLE_CCD = (1<<1), + + /** + \brief Enables a simplified swept integration strategy, which sacrifices some accuracy for improved performance. + + This simplified swept integration approach makes certain assumptions about the motion of objects that are not made when using a full swept integration. + These assumptions usually hold but there are cases where they could result in incorrect behavior between a set of fast-moving rigid bodies. A key issue is that + fast-moving dynamic objects may tunnel through each-other after a rebound. This will not happen if this mode is disabled. However, this approach will be potentially + faster than a full swept integration because it will perform significantly fewer sweeps in non-trivial scenes involving many fast-moving objects. This approach + should successfully resist objects passing through the static environment. + + PxPairFlag::eDETECT_CCD_CONTACT requires this flag to be specified. + + \note This scene flag requires eENABLE_CCD to be enabled as well. If it is not, this scene flag will do nothing. + \note For this feature to be effective for bodies that can move at a significant velocity, the user should raise the flag PxRigidBodyFlag::eENABLE_CCD for them. + \note This flag is not mutable, and must be set in PxSceneDesc at scene creation. + + Default: False + + \see PxRigidBodyFlag::eENABLE_CCD, PxPairFlag::eDETECT_CCD_CONTACT, eENABLE_CCD + */ + eDISABLE_CCD_RESWEEP = (1<<2), + + /** + \brief Enable GJK-based distance collision detection system. + + \note This flag is not mutable, and must be set in PxSceneDesc at scene creation. + + Default: true + */ + eENABLE_PCM = (1 << 6), + + /** + \brief Disable contact report buffer resize. Once the contact buffer is full, the rest of the contact reports will + not be buffered and sent. + + \note This flag is not mutable, and must be set in PxSceneDesc at scene creation. + + Default: false + */ + eDISABLE_CONTACT_REPORT_BUFFER_RESIZE = (1 << 7), + + /** + \brief Disable contact cache. + + Contact caches are used internally to provide faster contact generation. You can disable all contact caches + if memory usage for this feature becomes too high. + + \note This flag is not mutable, and must be set in PxSceneDesc at scene creation. + + Default: false + */ + eDISABLE_CONTACT_CACHE = (1 << 8), + + /** + \brief Require scene-level locking + + When set to true this requires that threads accessing the PxScene use the + multi-threaded lock methods. + + \note This flag is not mutable, and must be set in PxSceneDesc at scene creation. + + \see PxScene::lockRead + \see PxScene::unlockRead + \see PxScene::lockWrite + \see PxScene::unlockWrite + + Default: false + */ + eREQUIRE_RW_LOCK = (1 << 9), + + /** + \brief Enables additional stabilization pass in solver + + When set to true, this enables additional stabilization processing to improve that stability of complex interactions between large numbers of bodies. + + Note that this flag is not mutable and must be set in PxSceneDesc at scene creation. Also, this is an experimental feature which does result in some loss of momentum. + */ + eENABLE_STABILIZATION = (1 << 10), + + /** + \brief Enables average points in contact manifolds + + When set to true, this enables additional contacts to be generated per manifold to represent the average point in a manifold. This can stabilize stacking when only a small + number of solver iterations is used. + + Note that this flag is not mutable and must be set in PxSceneDesc at scene creation. + */ + eENABLE_AVERAGE_POINT = (1 << 11), + + /** + \brief Do not report kinematics in list of active actors. + + Since the target pose for kinematics is set by the user, an application can track the activity state directly and use + this flag to avoid that kinematics get added to the list of active actors. + + \note This flag has only an effect in combination with eENABLE_ACTIVE_ACTORS. + + \see eENABLE_ACTIVE_ACTORS + + Default: false + */ + eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS = (1 << 12), + + /*\brief Enables the GPU dynamics pipeline + + When set to true, a CUDA ARCH 3.0 or above-enabled NVIDIA GPU is present and the CUDA context manager has been configured, this will run the GPU dynamics pipelin instead of the CPU dynamics pipeline. + + Note that this flag is not mutable and must be set in PxSceneDesc at scene creation. + */ + eENABLE_GPU_DYNAMICS = (1 << 13), + + /** + \brief Provides improved determinism at the expense of performance. + + By default, PhysX provides limited determinism guarantees. Specifically, PhysX guarantees that the exact scene (same actors created in the same order) and simulated using the same + time-stepping scheme should provide the exact same behaviour. + + However, if additional actors are added to the simulation, this can affect the behaviour of the existing actors in the simulation, even if the set of new actors do not interact with + the existing actors. + + This flag provides an additional level of determinism that guarantees that the simulation will not change if additional actors are added to the simulation, provided those actors do not interfere + with the existing actors in the scene. Determinism is only guaranteed if the actors are inserted in a consistent order each run in a newly-created scene and simulated using a consistent time-stepping + scheme. + + Note that this flag is not mutable and must be set at scene creation. + + Note that enabling this flag can have a negative impact on performance. + + Note that this feature is not currently supported on GPU. + + Default false + */ + eENABLE_ENHANCED_DETERMINISM = (1<<14), + + /** + \brief Controls processing friction in all solver iterations + + By default, PhysX processes friction only in the final 3 position iterations, and all velocity + iterations. This flag enables friction processing in all position and velocity iterations. + + The default behaviour provides a good trade-off between performance and stability and is aimed + primarily at game development. + + When simulating more complex frictional behaviour, such as grasping of complex geometries with + a robotic manipulator, better results can be achieved by enabling friction in all solver iterations. + + \note This flag only has effect with the default solver. The TGS solver always performs friction per-iteration. + */ + eENABLE_FRICTION_EVERY_ITERATION = (1 << 15), + + /** + \brief Controls application of gravity and other external forces per TGS solver position iterations + + By default, external forces such as gravity are applied just once at the beginning of each simulate() call. With this + flag enabled the same forces are applied in each sub time step (position iteration) of the TGS solver, leading to greater stability and better solver convergence. + One consequence is that a body in freefall will move a shorter distance over the entire simulation step if the flag is raised. + + Note that raising this flag makes the distance traveled under freefall dependent on the number of solver iterations. + Since solver iterations are determined per-island, bodies assigned to an island with fewer solver iterations will travel a larger distance than bodies assigned to an island with more iterations. + + \note This feature is only supported for the TGS solver. + + Default false + */ + eENABLE_EXTERNAL_FORCES_EVERY_ITERATION_TGS = (1 << 16), + + /* + \brief Enables the direct-GPU API. Raising this flag is only allowed if eENABLE_GPU_DYNAMICS is raised and + PxBroadphaseType::eGPU is used. + + This is useful if your application only needs to communicate to the GPU via GPU buffers. Can be significantly + faster. + + \note Enabling the direct-GPU API will disable the readback of simulation state from GPU to CPU. Simulation outputs + can only be accessed using the direct-GPU API functions in PxDirectGPUAPI (PxDirectGPUAPI::getRigidDynamicData(), + PxDirectGPUAPI::getArticulationData(), PxDirectGPUAPI::copyContactData()), and reading state directly from the actor + is not allowed. + + \note This flag is not mutable and must be set in PxSceneDesc at scene creation. + \see PxScene::getDirectGPUAPI() PxDirectGPUAPI + + Default false + */ + eENABLE_DIRECT_GPU_API = (1 << 17), + + /** + \brief Enables the computation of body accelerations for PxRigidDynamic actors. + + By default PhysX does not compute per-body accelerations for PxRigidDynamic actors (only for articulation links). + This flag tells the system to compute them. + + Retrieve the accelerations using PxRigidBody::getLinearAcceleration() and PxRigidBody::getAngularAcceleration(). + + If the flag is not enabled these functions will return valid accelerations for PxArticulationLink objects, but + it will return zero for PxRigidDynamic actors. + + If the flag is enabled, these functions will return valid accelerations for both PxArticulationLink and + PxRigidDynamic objects. + + This flag also enables PxRigidDynamicGPUAPIReadType::eLINEAR_ACCELERATION and PxRigidDynamicGPUAPIReadType::eANGULAR_ACCELERATION + in the direct GPU API. + + \note This flag is not mutable and must be set in PxSceneDesc at scene creation. + \see PxRigidBody::getLinearAcceleration() PxRigidBody::getAngularAcceleration() PxRigidDynamicGPUAPIReadType PxDirectGPUAPI + + Default false + */ + eENABLE_BODY_ACCELERATIONS = (1 << 18), + + /* + \brief Enables the solver residual reporting. + + \note Enabling this flag can have a negative impact on the performance but the impact should be small. + */ + eENABLE_SOLVER_RESIDUAL_REPORTING = (1 << 19), + + /** + \brief Reorders articulation contact constraints and articulation joint maximum velocity constraints in the solver. + + When this flag is raised, the solver will observe the following order: + - joint friction, joint drive, joint position limit + - link dynamic contact + - link static contact + - joint max velocity + + When the flag is lowered, the solver will observe a modified order: + - link dynamic contact + - joint friction, joint drive, joint position limit + - joint max velocity + - link static contact + + Raising the flag can be useful for certain simulation scenarios such as gripping, where it is desirable for dynamic contact + to be resolved after joint drive but before max joint velocity. + + \note Raising this flag may have a negative effect on simulation performance. + + \note A goal of raising this flag is shallower contact penetration. This will in turn result in a reduced force + reported by PxArticulationCache::linkIncomingJointForce. + + Default false + */ + eSOLVE_ARTICULATION_CONTACT_LAST = (1 << 20), + + eMUTABLE_FLAGS = eENABLE_ACTIVE_ACTORS|eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS + }; +}; + +/** +\brief collection of set bits defined in PxSceneFlag. + +\see PxSceneFlag +*/ +typedef PxFlags PxSceneFlags; +PX_FLAGS_OPERATORS(PxSceneFlag::Enum,PxU32) + +class PxSimulationEventCallback; +class PxContactModifyCallback; +class PxCCDContactModifyCallback; +class PxSimulationFilterCallback; + +/** +\brief Class used to retrieve limits(e.g. maximum number of bodies) for a scene. The limits +are used as a hint to the size of the scene, not as a hard limit (i.e. it will be possible +to create more objects than specified in the scene limits). + +0 indicates no limit. Using limits allows the SDK to preallocate various arrays, leading to +less re-allocations and faster code at runtime. +*/ +class PxSceneLimits +{ +public: + PxU32 maxNbActors; //!< Expected maximum number of actors + PxU32 maxNbBodies; //!< Expected maximum number of dynamic rigid bodies + PxU32 maxNbStaticShapes; //!< Expected maximum number of static shapes + PxU32 maxNbDynamicShapes; //!< Expected maximum number of dynamic shapes + PxU32 maxNbAggregates; //!< Expected maximum number of aggregates + PxU32 maxNbConstraints; //!< Expected maximum number of constraint shaders + PxU32 maxNbRegions; //!< Expected maximum number of broad-phase regions + PxU32 maxNbBroadPhaseOverlaps; //!< Expected maximum number of broad-phase overlaps + + /** + \brief constructor sets to default + */ + PX_INLINE PxSceneLimits(); + + /** + \brief (re)sets the structure to the default + */ + PX_INLINE void setToDefault(); + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + PX_INLINE bool isValid() const; +}; + +PX_INLINE PxSceneLimits::PxSceneLimits() : //constructor sets to default + maxNbActors (0), + maxNbBodies (0), + maxNbStaticShapes (0), + maxNbDynamicShapes (0), + maxNbAggregates (0), + maxNbConstraints (0), + maxNbRegions (0), + maxNbBroadPhaseOverlaps (0) +{ +} + +PX_INLINE void PxSceneLimits::setToDefault() +{ + *this = PxSceneLimits(); +} + +PX_INLINE bool PxSceneLimits::isValid() const +{ + if(maxNbRegions>256) // max number of regions is currently limited + return false; + + return true; +} + +//#if PX_SUPPORT_GPU_PHYSX +/** +\brief Sizes of pre-allocated buffers use for GPU dynamics +*/ + +struct PxGpuDynamicsMemoryConfig +{ + PxU64 tempBufferCapacity; //!< Initial capacity of temp solver buffer allocated in pinned host memory. This buffer will grow if more memory is needed than specified here. + PxU32 maxRigidContactCount; //!< Size of contact stream buffer allocated in pinned host memory. This is double-buffered so total allocation size = 2* contactStreamCapacity * sizeof(PxContact). + PxU32 maxRigidPatchCount; //!< Size of the contact patch stream buffer allocated in pinned host memory. This is double-buffered so total allocation size = 2 * patchStreamCapacity * sizeof(PxContactPatch). + PxU32 heapCapacity; //!< Initial capacity of the GPU and pinned host memory heaps. Additional memory will be allocated if more memory is required. + PxU32 foundLostPairsCapacity; //!< Capacity of found and lost buffers allocated in GPU global memory. This is used for the found/lost pair reports in the BP. + PxU32 foundLostAggregatePairsCapacity; //!< Capacity of found and lost buffers in aggregate system allocated in GPU global memory. This is used for the found/lost pair reports in AABB manager. + PxU32 totalAggregatePairsCapacity; //!< Capacity of aggregate pair buffer allocated in GPU global memory. + PxU32 maxDeformableSurfaceContacts; //!< Capacity of deformable surface contact buffer allocated in GPU global memory. + PX_DEPRECATED PxU32 maxFemClothContacts;//!< Deprecated, replace with maxDeformableSurfaceContacts. + PxU32 maxDeformableVolumeContacts; //!< Capacity of deformable volume contact buffer allocated in GPU global memory. + PX_DEPRECATED PxU32 maxSoftBodyContacts;//!< Deprecated, replace with maxDeformableVolumeContacts. + PxU32 maxParticleContacts; //!< Capacity of particle contact buffer allocated in GPU global memory. + PxU32 collisionStackSize; //!< Capacity of the collision stack buffer, used as scratch space during narrowphase collision detection. + + PxGpuDynamicsMemoryConfig() : + tempBufferCapacity(16 * 1024 * 1024), + maxRigidContactCount(1024 * 512), + maxRigidPatchCount(1024 * 80), + heapCapacity(64 * 1024 * 1024), + foundLostPairsCapacity(256 * 1024), + foundLostAggregatePairsCapacity(1024), + totalAggregatePairsCapacity(1024), + maxDeformableSurfaceContacts(1 * 1024 * 1024), + maxFemClothContacts(0), // deprecated, if > 0, used instead of maxDeformableSurfaceContacts + maxDeformableVolumeContacts(1 * 1024 * 1024), + maxSoftBodyContacts(0), // deprecated, if > 0, used instead of maxDeformableVolumeContacts + maxParticleContacts(1*1024*1024), + collisionStackSize(64*1024*1024) + { + } + + PX_PHYSX_CORE_API bool isValid() const; +}; + +PX_INLINE bool PxGpuDynamicsMemoryConfig::isValid() const +{ + const bool isPowerOfTwo = PxIsPowerOfTwo(heapCapacity); + return isPowerOfTwo; +} + +//#endif + +/** +\brief Descriptor class for scenes. See #PxScene. + +This struct must be initialized with the same PxTolerancesScale values used to initialize PxPhysics. + +\see PxScene PxPhysics.createScene PxTolerancesScale +*/ +class PxSceneDesc : public PxSceneQueryDesc +{ +public: + + /** + \brief Gravity vector. + + Range: force vector
+ Default: Zero + + \see PxScene.setGravity() PxScene.getGravity() + + When setting gravity, you should probably also set bounce threshold. + */ + PxVec3 gravity; + + /** + \brief Possible notification callback. + + Default: NULL + + \see PxSimulationEventCallback PxScene.setSimulationEventCallback() PxScene.getSimulationEventCallback() + */ + PxSimulationEventCallback* simulationEventCallback; + + /** + \brief Possible asynchronous callback for contact modification. + + Default: NULL + + \see PxContactModifyCallback PxScene.setContactModifyCallback() PxScene.getContactModifyCallback() + */ + PxContactModifyCallback* contactModifyCallback; + + /** + \brief Possible asynchronous callback for contact modification. + + Default: NULL + + \see PxContactModifyCallback PxScene.setContactModifyCallback() PxScene.getContactModifyCallback() + */ + PxCCDContactModifyCallback* ccdContactModifyCallback; + + /** + \brief Possible asynchronous callback for post-solve operations on deformable surfaces. + + Default: NULL + + \see PxPostSolveCallback + */ + PxPostSolveCallback* deformableSurfacePostSolveCallback; + + /** + \brief Possible asynchronous callback for post-solve operations on deformable volumes. + + Default: NULL + + \see PxPostSolveCallback + */ + PxPostSolveCallback* deformableVolumePostSolveCallback; + + /** + \brief Shared global filter data which will get passed into the filter shader. + + \note The provided data will get copied to internal buffers and this copy will be used for filtering calls. + + Default: NULL + + \see PxSimulationFilterShader PxScene.setFilterShaderData() PxScene.getFilterShaderData() + */ + const void* filterShaderData; + + /** + \brief Size (in bytes) of the shared global filter data #filterShaderData. + + Default: 0 + + \see PxSimulationFilterShader filterShaderData PxScene.getFilterShaderDataSize() + */ + PxU32 filterShaderDataSize; + + /** + \brief The custom filter shader to use for collision filtering. + + \note This parameter is compulsory. If you don't want to define your own filter shader you can + use the default shader #PxDefaultSimulationFilterShader which can be found in the PhysX extensions + library. + + \see PxSimulationFilterShader PxScene.getFilterShader() + */ + PxSimulationFilterShader filterShader; + + /** + \brief A custom collision filter callback which can be used to implement more complex filtering operations which need + access to the simulation state, for example. + + Default: NULL + + \see PxSimulationFilterCallback PxScene.getFilterCallback() + */ + PxSimulationFilterCallback* filterCallback; + + /** + \brief Filtering mode for kinematic-kinematic pairs in the broadphase. + + Default: PxPairFilteringMode::eDEFAULT + + \see PxPairFilteringMode PxScene.getKinematicKinematicFilteringMode() + */ + PxPairFilteringMode::Enum kineKineFilteringMode; + + /** + \brief Filtering mode for static-kinematic pairs in the broadphase. + + Default: PxPairFilteringMode::eDEFAULT + + \see PxPairFilteringMode PxScene.getStaticKinematicFilteringMode() + */ + PxPairFilteringMode::Enum staticKineFilteringMode; + + /** + \brief Selects the broad-phase algorithm to use. + + Default: PxBroadPhaseType::ePABP + + \see PxBroadPhaseType PxScene.getBroadPhaseType() + */ + PxBroadPhaseType::Enum broadPhaseType; + + /** + \brief Broad-phase callback + + Default: NULL + + \see PxBroadPhaseCallback PxScene.getBroadPhaseCallback() PxScene.setBroadPhaseCallback() + */ + PxBroadPhaseCallback* broadPhaseCallback; + + /** + \brief Optional GPU broad-phase descriptor. + + This is only used for the GPU broadphase (PxBroadPhaseType::eGPU). + + Default: NULL + + \see PxBroadPhaseType + */ + PxGpuBroadPhaseDesc* gpuBroadPhaseDesc; + + /** + \brief Expected scene limits. + + \see PxSceneLimits PxScene.getLimits() + */ + PxSceneLimits limits; + + /** + \brief Selects the friction algorithm to use for simulation. + + \deprecated Since only the patch friction model is supported now, the frictionType parameter is obsolete. + + Default: PxFrictionType::ePATCH + + \see PxFrictionType PxScene.getFrictionType() + */ + PX_DEPRECATED PxFrictionType::Enum frictionType; + + /** + \brief Selects the solver algorithm to use. + + Default: PxSolverType::ePGS + + \see PxSolverType PxScene.getSolverType() + */ + PxSolverType::Enum solverType; + + /** + \brief A contact with a relative velocity below this will not bounce. A typical value for simulation. + stability is about 0.2 * gravity. + + Range: (0, PX_MAX_F32)
+ Default: 0.2 * PxTolerancesScale::speed + + \see PxMaterial PxScene.setBounceThresholdVelocity() PxScene.getBounceThresholdVelocity() + */ + PxReal bounceThresholdVelocity; + + /** + \brief A threshold of contact separation distance used to decide if a contact point will experience friction forces. + + \note If the separation distance of a contact point is greater than the threshold then the contact point will not experience friction forces. + + \note If the aggregated contact offset of a pair of shapes is large it might be desirable to neglect friction + for contact points whose separation distance is sufficiently large that the shape surfaces are clearly separated. + + \note This parameter can be used to tune the separation distance of contact points at which friction starts to have an effect. + + Range: [0, PX_MAX_F32)
+ Default: 0.04 * PxTolerancesScale::length + + \see PxScene.setFrictionOffsetThreshold() PxScene.getFrictionOffsetThreshold() + */ + PxReal frictionOffsetThreshold; + + /** + \brief Friction correlation distance used to decide whether contacts are close enough to be merged into a single friction anchor point or not. + + \note If the correlation distance is larger than the distance between contact points generated between a pair of shapes, some of the contacts may not experience frictional forces. + + \note This parameter can be used to tune the correlation distance used in the solver. Contact points can be merged into a single friction anchor if the distance between the contacts is smaller than correlation distance. + + Range: [0, PX_MAX_F32)
+ Default: 0.025f * PxTolerancesScale::length + + \see PxScene.setFrictionCorrelationDistance() PxScene.getFrictionCorrelationDistance() + */ + PxReal frictionCorrelationDistance; + + /** + \brief Flags used to select scene options. + + Default: PxSceneFlag::eENABLE_PCM + + \see PxSceneFlag PxSceneFlags PxScene.getFlags() PxScene.setFlag() + */ + PxSceneFlags flags; + + /** + \brief The CPU task dispatcher for the scene. + + \see PxCpuDispatcher, PxScene::getCpuDispatcher + */ + PxCpuDispatcher* cpuDispatcher; + + /** + \brief The CUDA context manager for the scene. + + Platform specific: Applies to PC GPU only. + + \see PxCudaContextManager, PxScene::getCudaContextManager + */ + PxCudaContextManager* cudaContextManager; + + /** + \brief Will be copied to PxScene::userData. + + Default: NULL + */ + void* userData; + + /** + \brief Defines the number of actors required to spawn a separate rigid body solver island task chain. + + This parameter defines the minimum number of actors required to spawn a separate rigid body solver task chain. Setting a low value + will potentially cause more task chains to be generated. This may result in the overhead of spawning tasks can become a limiting performance factor. + Setting a high value will potentially cause fewer islands to be generated. This may reduce thread scaling (fewer task chains spawned) and may + detrimentally affect performance if some bodies in the scene have large solver iteration counts because all constraints in a given island are solved by the + maximum number of solver iterations requested by any body in the island. + + Note that a rigid body solver task chain is spawned as soon as either a sufficient number of rigid bodies or articulations are batched together. + + Default: 128 + + \see PxScene.setSolverBatchSize() PxScene.getSolverBatchSize() + */ + PxU32 solverBatchSize; + + /** + \brief Defines the number of articulations required to spawn a separate rigid body solver island task chain. + + This parameter defines the minimum number of articulations required to spawn a separate rigid body solver task chain. Setting a low value + will potentially cause more task chains to be generated. This may result in the overhead of spawning tasks can become a limiting performance factor. + Setting a high value will potentially cause fewer islands to be generated. This may reduce thread scaling (fewer task chains spawned) and may + detrimentally affect performance if some bodies in the scene have large solver iteration counts because all constraints in a given island are solved by the + maximum number of solver iterations requested by any body in the island. + + Note that a rigid body solver task chain is spawned as soon as either a sufficient number of rigid bodies or articulations are batched together. + + Default: 16 + + \see PxScene.setSolverArticulationBatchSize() PxScene.getSolverArticulationBatchSize() + */ + PxU32 solverArticulationBatchSize; + + /** + \brief Setting to define the number of 16K blocks that will be initially reserved to store contact, friction, and contact cache data. + This is the number of 16K memory blocks that will be automatically allocated from the user allocator when the scene is instantiated. Further 16k + memory blocks may be allocated during the simulation up to maxNbContactDataBlocks. + + \note This value cannot be larger than maxNbContactDataBlocks because that defines the maximum number of 16k blocks that can be allocated by the SDK. + + Default: 0 + + Range: [0, PX_MAX_U32]
+ + \see PxPhysics::createScene PxScene::setNbContactDataBlocks + */ + PxU32 nbContactDataBlocks; + + /** + \brief Setting to define the maximum number of 16K blocks that can be allocated to store contact, friction, and contact cache data. + As the complexity of a scene increases, the SDK may require to allocate new 16k blocks in addition to the blocks it has already + allocated. This variable controls the maximum number of blocks that the SDK can allocate. + + In the case that the scene is sufficiently complex that all the permitted 16K blocks are used, contacts will be dropped and + a warning passed to the error stream. + + If a warning is reported to the error stream to indicate the number of 16K blocks is insufficient for the scene complexity + then the choices are either (i) re-tune the number of 16K data blocks until a number is found that is sufficient for the scene complexity, + (ii) to simplify the scene or (iii) to opt to not increase the memory requirements of physx and accept some dropped contacts. + + Default: 65536 + + Range: [0, PX_MAX_U32]
+ + \see nbContactDataBlocks PxScene.setNbContactDataBlocks() + */ + PxU32 maxNbContactDataBlocks; + + /** + \brief The maximum bias coefficient used in the constraint solver + + When geometric errors are found in the constraint solver, either as a result of shapes penetrating + or joints becoming separated or violating limits, a bias is introduced in the solver position iterations + to correct these errors. This bias is proportional to 1/dt, meaning that the bias becomes increasingly + strong as the time-step passed to PxScene::simulate(...) becomes smaller. This coefficient allows the + application to restrict how large the bias coefficient is, to reduce how violent error corrections are. + This can improve simulation quality in cases where either variable time-steps or extremely small time-steps + are used. + + Default: PX_MAX_F32 + + Range [0, PX_MAX_F32]
+ + \see PxScene.setMaxBiasCoefficient() PxScene.getMaxBiasCoefficient() + */ + PxReal maxBiasCoefficient; + + /** + \brief Size of the contact report stream (in bytes). + + The contact report stream buffer is used during the simulation to store all the contact reports. + If the size is not sufficient, the buffer will grow by a factor of two. + It is possible to disable the buffer growth by setting the flag PxSceneFlag::eDISABLE_CONTACT_REPORT_BUFFER_RESIZE. + In that case the buffer will not grow but contact reports not stored in the buffer will not get sent in the contact report callbacks. + + Default: 8192 + + Range: (0, PX_MAX_U32]
+ + \see PxScene.getContactReportStreamBufferSize() + */ + PxU32 contactReportStreamBufferSize; + + /** + \brief Maximum number of CCD passes + + The CCD performs multiple passes, where each pass every object advances to its time of first impact. This value defines how many passes the CCD system should perform. + + \note The CCD system is a multi-pass best-effort conservative advancement approach. After the defined number of passes has been completed, any remaining time is dropped. + \note This defines the maximum number of passes the CCD can perform. It may perform fewer if additional passes are not necessary. + + Default: 1 + Range: [1, PX_MAX_U32]
+ + \see PxScene.setCCDMaxPasses() PxScene.getCCDMaxPasses() + */ + PxU32 ccdMaxPasses; + + /** + \brief CCD threshold + + CCD performs sweeps against shapes if and only if the relative motion of the shapes is fast-enough that a collision would be missed + by the discrete contact generation. However, in some circumstances, e.g. when the environment is constructed from large convex shapes, this + approach may produce undesired simulation artefacts. This parameter defines the minimum relative motion that would be required to force CCD between shapes. + The smaller of this value and the sum of the thresholds calculated for the shapes involved will be used. + + \note It is not advisable to set this to a very small value as this may lead to CCD "jamming" and detrimentally effect performance. This value should be at least larger than the translation caused by a single frame's gravitational effect + + Default: PX_MAX_F32 + Range: [Eps, PX_MAX_F32]
+ + \see PxScene.setCCDThreshold() PxScene.getCCDThreshold() + */ + PxReal ccdThreshold; + + /** + \brief A threshold for speculative CCD. Used to control whether bias, restitution or a combination of the two are used to resolve the contacts. + + \note This only has any effect on contacting pairs where one of the bodies has PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD raised. + + Range: [0, PX_MAX_F32)
+ Default: 0.04 * PxTolerancesScale::length + + \see PxScene.setCCDMaxSeparation() PxScene.getCCDMaxSeparation() + */ + PxReal ccdMaxSeparation; + + /** + \brief The wake counter reset value + + Calling wakeUp() on objects which support sleeping will set their wake counter value to the specified reset value. + + Range: (0, PX_MAX_F32)
+ Default: 0.4 (which corresponds to 20 frames for a time step of 0.02) + + \see PxRigidDynamic::wakeUp() PxArticulationReducedCoordinate::wakeUp() PxScene.getWakeCounterResetValue() + */ + PxReal wakeCounterResetValue; + + /** + \brief The bounds used to sanity check user-set positions of actors and articulation links + + These bounds are used to check the position values of rigid actors inserted into the scene, and positions set for rigid actors + already within the scene. + + Range: any valid PxBounds3
+ Default: (-PX_MAX_BOUNDS_EXTENTS, PX_MAX_BOUNDS_EXTENTS) on each axis + */ + PxBounds3 sanityBounds; + + /** + \brief The pre-allocations performed in the GPU dynamics pipeline. + */ + PxGpuDynamicsMemoryConfig gpuDynamicsConfig; + + /** + \brief Limitation for the partitions in the GPU dynamics pipeline. + This variable must be power of 2. + A value greater than 32 is currently not supported. + Range: (1, 32)
+ */ + PxU32 gpuMaxNumPartitions; + + /** + \brief Limitation for the number of static rigid body partitions in the GPU dynamics pipeline. + Range: (1, 255)
+ Default: 16 + */ + PxU32 gpuMaxNumStaticPartitions; + + /** + \brief Defines which compute version the GPU dynamics should target. DO NOT MODIFY + */ + PxU32 gpuComputeVersion; + + /** + \brief Defines the size of a contact pool slab. + Contact pairs and associated data are allocated using a pool allocator. Increasing the slab size can trade + off some performance spikes when a large number of new contacts are found for an increase in overall memory + usage. + + Range:(1, PX_MAX_U32)
+ Default: 256 + */ + PxU32 contactPairSlabSize; + + /** + \brief The scene query sub-system for the scene. + + If left to NULL, PxScene will use its usual internal sub-system. If non-NULL, all SQ-related calls + will be re-routed to the user-provided implementation. An external SQ implementation is available + in the Extensions library (see PxCreateExternalSceneQuerySystem). This can also be fully re-implemented by users if needed. + + \see PxSceneQuerySystem + */ + PxSceneQuerySystem* sceneQuerySystem; + +private: + /** + \cond + */ + // For internal use only + PxTolerancesScale tolerancesScale; + /** + \endcond + */ + +public: + /** + \brief constructor sets to default. + + \param[in] scale scale values for the tolerances in the scene, these must be the same values passed into + PxCreatePhysics(). The affected tolerances are bounceThresholdVelocity and frictionOffsetThreshold. + + \see PxCreatePhysics() PxTolerancesScale bounceThresholdVelocity frictionOffsetThreshold + */ + PX_INLINE PxSceneDesc(const PxTolerancesScale& scale); + + /** + \brief (re)sets the structure to the default. + + \param[in] scale scale values for the tolerances in the scene, these must be the same values passed into + PxCreatePhysics(). The affected tolerances are bounceThresholdVelocity and frictionOffsetThreshold. + + \see PxCreatePhysics() PxTolerancesScale bounceThresholdVelocity frictionOffsetThreshold + */ + PX_INLINE void setToDefault(const PxTolerancesScale& scale); + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + PX_INLINE bool isValid() const; + + /** + \cond + */ + // For internal use only + PX_INLINE const PxTolerancesScale& getTolerancesScale() const { return tolerancesScale; } + /** + \endcond + */ +}; + +PX_INLINE PxSceneDesc::PxSceneDesc(const PxTolerancesScale& scale): + gravity (PxVec3(0.0f)), + simulationEventCallback (NULL), + contactModifyCallback (NULL), + ccdContactModifyCallback (NULL), + deformableSurfacePostSolveCallback(NULL), + deformableVolumePostSolveCallback(NULL), + + filterShaderData (NULL), + filterShaderDataSize (0), + filterShader (NULL), + filterCallback (NULL), + + kineKineFilteringMode (PxPairFilteringMode::eDEFAULT), + staticKineFilteringMode (PxPairFilteringMode::eDEFAULT), + + broadPhaseType (PxBroadPhaseType::ePABP), + broadPhaseCallback (NULL), + gpuBroadPhaseDesc (NULL), + + frictionType (PxFrictionType::ePATCH), + solverType (PxSolverType::ePGS), + bounceThresholdVelocity (0.2f * scale.speed), + frictionOffsetThreshold (0.04f * scale.length), + frictionCorrelationDistance (0.025f * scale.length), + + flags (PxSceneFlag::eENABLE_PCM), + + cpuDispatcher (NULL), + cudaContextManager (NULL), + + userData (NULL), + + solverBatchSize (128), + solverArticulationBatchSize (16), + + nbContactDataBlocks (0), + maxNbContactDataBlocks (1<<16), + maxBiasCoefficient (PX_MAX_F32), + contactReportStreamBufferSize (8192), + ccdMaxPasses (1), + ccdThreshold (PX_MAX_F32), + ccdMaxSeparation (0.04f * scale.length), + wakeCounterResetValue (20.0f*0.02f), + sanityBounds (PxBounds3(PxVec3(-PX_MAX_BOUNDS_EXTENTS), PxVec3(PX_MAX_BOUNDS_EXTENTS))), + gpuMaxNumPartitions (8), + gpuMaxNumStaticPartitions (16), + gpuComputeVersion (0), + contactPairSlabSize (256), + sceneQuerySystem (NULL), + tolerancesScale (scale) +{ +} + +PX_INLINE void PxSceneDesc::setToDefault(const PxTolerancesScale& scale) +{ + *this = PxSceneDesc(scale); +} + +PX_INLINE bool PxSceneDesc::isValid() const +{ + if(!PxSceneQueryDesc::isValid()) + return false; + + if(!filterShader) + return false; + + if( ((filterShaderDataSize == 0) && (filterShaderData != NULL)) || + ((filterShaderDataSize > 0) && (filterShaderData == NULL)) ) + return false; + + if(!limits.isValid()) + return false; + + if(bounceThresholdVelocity <= 0.0f) + return false; + if(frictionOffsetThreshold < 0.0f) + return false; + if(frictionCorrelationDistance <= 0) + return false; + + if(maxBiasCoefficient < 0.0f) + return false; + + if(!ccdMaxPasses) + return false; + if(ccdThreshold <= 0.0f) + return false; + if(ccdMaxSeparation < 0.0f) + return false; + + if(!cpuDispatcher) + return false; + + if(!contactReportStreamBufferSize) + return false; + + if(maxNbContactDataBlocks < nbContactDataBlocks) + return false; + + if(wakeCounterResetValue <= 0.0f) + return false; + + if(!sanityBounds.isValid()) + return false; + + if(solverType == PxSolverType::ePGS && (flags & PxSceneFlag::eENABLE_EXTERNAL_FORCES_EVERY_ITERATION_TGS)) + return false; + +#if PX_SUPPORT_GPU_PHYSX + if(!PxIsPowerOfTwo(gpuMaxNumPartitions)) + return false; + if(gpuMaxNumPartitions > 32) + return false; + if (gpuMaxNumPartitions == 0) + return false; + if(!gpuDynamicsConfig.isValid()) + return false; + + if(flags & PxSceneFlag::eENABLE_DIRECT_GPU_API) + { + if(!(flags & PxSceneFlag::eENABLE_GPU_DYNAMICS && broadPhaseType == PxBroadPhaseType::eGPU)) + return false; + + if(flags & PxSceneFlag::eENABLE_CCD) + return false; + } + + if(gpuBroadPhaseDesc && broadPhaseType != PxBroadPhaseType::eGPU) + return false; +#endif + + if(contactPairSlabSize == 0) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSceneLock.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneLock.h new file mode 100644 index 000000000..eb4facdb2 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneLock.h @@ -0,0 +1,123 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SCENE_LOCK_H +#define PX_SCENE_LOCK_H + +#include "PxPhysXConfig.h" +#include "PxScene.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief RAII wrapper for the PxScene read lock. + +Use this class as follows to lock the scene for reading by the current thread +for the duration of the enclosing scope: + + PxSceneReadLock lock(sceneRef); + +\see PxScene::lockRead(), PxScene::unlockRead(), PxSceneFlag::eREQUIRE_RW_LOCK +*/ +class PxSceneReadLock +{ + PxSceneReadLock(const PxSceneReadLock&); + PxSceneReadLock& operator=(const PxSceneReadLock&); + +public: + + /** + \brief Constructor + \param scene The scene to lock for reading + \param file Optional string for debugging purposes + \param line Optional line number for debugging purposes + */ + PxSceneReadLock(PxScene& scene, const char* file=NULL, PxU32 line=0) + : mScene(scene) + { + mScene.lockRead(file, line); + } + + ~PxSceneReadLock() + { + mScene.unlockRead(); + } + +private: + + PxScene& mScene; +}; + +/** +\brief RAII wrapper for the PxScene write lock. + +Use this class as follows to lock the scene for writing by the current thread +for the duration of the enclosing scope: + + PxSceneWriteLock lock(sceneRef); + +\see PxScene::lockWrite(), PxScene::unlockWrite(), PxSceneFlag::eREQUIRE_RW_LOCK +*/ +class PxSceneWriteLock +{ + PxSceneWriteLock(const PxSceneWriteLock&); + PxSceneWriteLock& operator=(const PxSceneWriteLock&); + +public: + + /** + \brief Constructor + \param scene The scene to lock for writing + \param file Optional string for debugging purposes + \param line Optional line number for debugging purposes + */ + PxSceneWriteLock(PxScene& scene, const char* file=NULL, PxU32 line=0) + : mScene(scene) + { + mScene.lockWrite(file, line); + } + + ~PxSceneWriteLock() + { + mScene.unlockWrite(); + } + +private: + + PxScene& mScene; +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSceneQueryDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneQueryDesc.h new file mode 100644 index 000000000..5452b1ed3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneQueryDesc.h @@ -0,0 +1,324 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SCENE_QUERY_DESC_H +#define PX_SCENE_QUERY_DESC_H + +#include "PxPhysXConfig.h" +#include "geometry/PxBVHBuildStrategy.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxSceneQuerySystem; + +/** +\brief Pruning structure used to accelerate scene queries. + +eNONE uses a simple data structure that consumes less memory than the alternatives, +but generally has slower query performance. + +eDYNAMIC_AABB_TREE usually provides the fastest queries. However there is a +constant per-frame management cost associated with this structure. How much work should +be done per frame can be tuned via the #PxSceneQueryDesc::dynamicTreeRebuildRateHint +parameter. + +eSTATIC_AABB_TREE is typically used for static objects. It is the same as the +dynamic AABB tree, without the per-frame overhead. This can be a good choice for static +objects, if no static objects are added, moved or removed after the scene has been +created. If there is no such guarantee (e.g. when streaming parts of the world in and out), +then the dynamic version is a better choice even for static objects. +*/ +struct PxPruningStructureType +{ + enum Enum + { + eNONE, //!< Using a simple data structure + eDYNAMIC_AABB_TREE, //!< Using a dynamic AABB tree + eSTATIC_AABB_TREE, //!< Using a static AABB tree + + eLAST + }; +}; + +/** +\brief Secondary pruning structure used for newly added objects in dynamic trees. + +Dynamic trees (PxPruningStructureType::eDYNAMIC_AABB_TREE) are slowly rebuilt +over several frames. A secondary pruning structure holds and manages objects +added to the scene while this rebuild is in progress. + +eNONE ignores newly added objects. This means that for a number of frames (roughly +defined by PxSceneQueryDesc::dynamicTreeRebuildRateHint) newly added objects will +be ignored by scene queries. This can be acceptable when streaming large worlds, e.g. +when the objects added at the boundaries of the game world don't immediately need to be +visible from scene queries (it would be equivalent to streaming that data in a few frames +later). The advantage of this approach is that there is no CPU cost associated with +inserting the new objects in the scene query data structures, and no extra runtime cost +when performing queries. + +eBUCKET uses a structure similar to PxPruningStructureType::eNONE. Insertion is fast but +query cost can be high. + +eINCREMENTAL uses an incremental AABB-tree, with no direct PxPruningStructureType equivalent. +Query time is fast but insertion cost can be high. + +eBVH uses a PxBVH structure. This usually offers the best overall performance. +*/ +struct PxDynamicTreeSecondaryPruner +{ + enum Enum + { + eNONE, //!< no secondary pruner, new objects aren't visible to SQ for a few frames + eBUCKET , //!< bucket-based secondary pruner, faster updates, slower query time + eINCREMENTAL, //!< incremental-BVH secondary pruner, faster query time, slower updates + eBVH, //!< PxBVH-based secondary pruner, good overall performance + + eLAST + }; +}; + +/** +\brief Scene query update mode + +This enum controls what work is done when the scene query system is updated. The updates traditionally happen when PxScene::fetchResults +is called. This function then calls PxSceneQuerySystem::finalizeUpdates, where the update mode is used. + +fetchResults/finalizeUpdates will sync changed bounds during simulation and update the scene query bounds in pruners, this work is mandatory. + +eBUILD_ENABLED_COMMIT_ENABLED does allow to execute the new AABB tree build step during fetchResults/finalizeUpdates, additionally +the pruner commit is called where any changes are applied. During commit PhysX refits the dynamic scene query tree and if a new tree +was built and the build finished the tree is swapped with current AABB tree. + +eBUILD_ENABLED_COMMIT_DISABLED does allow to execute the new AABB tree build step during fetchResults/finalizeUpdates. Pruner commit +is not called, this means that refit will then occur during the first scene query following fetchResults/finalizeUpdates, or may be forced +by the method PxScene::flushQueryUpdates() / PxSceneQuerySystemBase::flushUpdates(). + +eBUILD_DISABLED_COMMIT_DISABLED no further scene query work is executed. The scene queries update needs to be called manually, see +PxScene::sceneQueriesUpdate (see that function's doc for the equivalent PxSceneQuerySystem sequence). It is recommended to call +PxScene::sceneQueriesUpdate right after fetchResults/finalizeUpdates as the pruning structures are not updated. +*/ +struct PxSceneQueryUpdateMode +{ + enum Enum + { + eBUILD_ENABLED_COMMIT_ENABLED, //!< Both scene query build and commit are executed. + eBUILD_ENABLED_COMMIT_DISABLED, //!< Scene query build only is executed. + eBUILD_DISABLED_COMMIT_DISABLED //!< No work is done, no update of scene queries + }; +}; + +/** +\brief Descriptor class for scene query system. See #PxSceneQuerySystem. +*/ +class PxSceneQueryDesc +{ +public: + + /** + \brief Defines the structure used to store static objects (PxRigidStatic actors). + + There are usually a lot more static actors than dynamic actors in a scene, so they are stored + in a separate structure. The idea is that when dynamic actors move each frame, the static structure + remains untouched and does not need updating. + + Default: PxPruningStructureType::eDYNAMIC_AABB_TREE + + \note Only PxPruningStructureType::eSTATIC_AABB_TREE and PxPruningStructureType::eDYNAMIC_AABB_TREE are allowed here. + + \see PxPruningStructureType PxSceneSQSystem.getStaticStructure() + */ + PxPruningStructureType::Enum staticStructure; + + /** + \brief Defines the structure used to store dynamic objects (non-PxRigidStatic actors). + + Default: PxPruningStructureType::eDYNAMIC_AABB_TREE + + \see PxPruningStructureType PxSceneSQSystem.getDynamicStructure() + */ + PxPruningStructureType::Enum dynamicStructure; + + /** + \brief Hint for how much work should be done per simulation frame to rebuild the pruning structures. + + This parameter gives a hint on the distribution of the workload for rebuilding the dynamic AABB tree + pruning structure #PxPruningStructureType::eDYNAMIC_AABB_TREE. It specifies the desired number of simulation frames + the rebuild process should take. Higher values will decrease the workload per frame but the pruning + structure will get more and more outdated the longer the rebuild takes (which can make + scene queries less efficient). + + \note Only used for #PxPruningStructureType::eDYNAMIC_AABB_TREE pruning structures. + + \note Both staticStructure & dynamicStructure can use a PxPruningStructureType::eDYNAMIC_AABB_TREE, in which case + this parameter is used for both. + + \note This parameter gives only a hint. The rebuild process might still take more or less time depending on the + number of objects involved. + + Range: [4, PX_MAX_U32)
+ Default: 100 + + \see PxSceneQuerySystemBase.setDynamicTreeRebuildRateHint() PxSceneQuerySystemBase.getDynamicTreeRebuildRateHint() + */ + PxU32 dynamicTreeRebuildRateHint; + + /** + \brief Secondary pruner for dynamic tree. + + This is used for PxPruningStructureType::eDYNAMIC_AABB_TREE structures, to control how objects added to the system + at runtime are managed. + + \note Both staticStructure & dynamicStructure can use a PxPruningStructureType::eDYNAMIC_AABB_TREE, in which case + this parameter is used for both. + + Default: PxDynamicTreeSecondaryPruner::eINCREMENTAL + + \see PxDynamicTreeSecondaryPruner + */ + PxDynamicTreeSecondaryPruner::Enum dynamicTreeSecondaryPruner; + + /** + \brief Build strategy for PxSceneQueryDesc::staticStructure. + + This parameter is used to refine / control the build strategy of PxSceneQueryDesc::staticStructure. This is only + used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE. + + Default: PxBVHBuildStrategy::eFAST + + \see PxBVHBuildStrategy PxSceneQueryDesc::staticStructure + */ + PxBVHBuildStrategy::Enum staticBVHBuildStrategy; + + /** + \brief Build strategy for PxSceneQueryDesc::dynamicStructure. + + This parameter is used to refine / control the build strategy of PxSceneQueryDesc::dynamicStructure. This is only + used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE. + + Default: PxBVHBuildStrategy::eFAST + + \see PxBVHBuildStrategy PxSceneQueryDesc::dynamicStructure + */ + PxBVHBuildStrategy::Enum dynamicBVHBuildStrategy; + + /** + \brief Number of objects per node for PxSceneQueryDesc::staticStructure. + + This parameter is used to refine / control the number of objects per node for PxSceneQueryDesc::staticStructure. + This is only used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE. + + This parameter has an impact on how quickly the structure gets built, and on the per-frame cost of maintaining + the structure. Increasing this value gives smaller AABB-trees that use less memory, are faster to build and + update, but it can lead to slower queries. + + Default: 4 + + \see PxSceneQueryDesc::staticStructure + */ + PxU32 staticNbObjectsPerNode; + + /** + \brief Number of objects per node for PxSceneQueryDesc::dynamicStructure. + + This parameter is used to refine / control the number of objects per node for PxSceneQueryDesc::dynamicStructure. + This is only used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE. + + This parameter has an impact on how quickly the structure gets built, and on the per-frame cost of maintaining + the structure. Increasing this value gives smaller AABB-trees that use less memory, are faster to build and + update, but it can lead to slower queries. + + Default: 4 + + \see PxSceneQueryDesc::dynamicStructure + */ + PxU32 dynamicNbObjectsPerNode; + + /** + \brief Defines the scene query update mode. + + Default: PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED + + \see PxSceneQuerySystemBase.setUpdateMode() PxSceneQuerySystemBase.getUpdateMode() + */ + PxSceneQueryUpdateMode::Enum sceneQueryUpdateMode; + +public: + /** + \brief constructor sets to default. + */ + PX_INLINE PxSceneQueryDesc(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + PX_INLINE bool isValid() const; +}; + +PX_INLINE PxSceneQueryDesc::PxSceneQueryDesc(): + staticStructure (PxPruningStructureType::eDYNAMIC_AABB_TREE), + dynamicStructure (PxPruningStructureType::eDYNAMIC_AABB_TREE), + dynamicTreeRebuildRateHint (100), + dynamicTreeSecondaryPruner (PxDynamicTreeSecondaryPruner::eINCREMENTAL), + staticBVHBuildStrategy (PxBVHBuildStrategy::eFAST), + dynamicBVHBuildStrategy (PxBVHBuildStrategy::eFAST), + staticNbObjectsPerNode (4), + dynamicNbObjectsPerNode (4), + sceneQueryUpdateMode (PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED) +{ +} + +PX_INLINE void PxSceneQueryDesc::setToDefault() +{ + *this = PxSceneQueryDesc(); +} + +PX_INLINE bool PxSceneQueryDesc::isValid() const +{ + if(staticStructure!=PxPruningStructureType::eSTATIC_AABB_TREE && staticStructure!=PxPruningStructureType::eDYNAMIC_AABB_TREE) + return false; + + if(dynamicTreeRebuildRateHint < 4) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSceneQuerySystem.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneQuerySystem.h new file mode 100644 index 000000000..f3c62b492 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSceneQuerySystem.h @@ -0,0 +1,654 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SCENE_QUERY_SYSTEM_H +#define PX_SCENE_QUERY_SYSTEM_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxBitMap.h" +#include "foundation/PxTransform.h" +#include "PxSceneQueryDesc.h" +#include "PxQueryReport.h" +#include "PxQueryFiltering.h" +#include "geometry/PxGeometryQueryFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxBaseTask; + class PxRenderOutput; + class PxGeometry; + class PxRigidActor; + class PxShape; + class PxBVH; + class PxPruningStructure; + class PxBounds3; + + /** + \brief Built-in enum for default PxScene pruners + + This is passed as a pruner index to various functions in the following APIs. + + \see PxSceneQuerySystemBase::forceRebuildDynamicTree PxSceneQuerySystem::preallocate + \see PxSceneQuerySystem::visualize PxSceneQuerySystem::sync PxSceneQuerySystem::prepareSceneQueryBuildStep + */ + enum PxScenePrunerIndex + { + PX_SCENE_PRUNER_STATIC = 0, + PX_SCENE_PRUNER_DYNAMIC = 1, + PX_SCENE_COMPOUND_PRUNER = 0xffffffff + }; + + /** + \brief Base class for the scene-query system. + + Methods defined here are common to both the traditional PxScene API and the PxSceneQuerySystem API. + + \see PxScene PxSceneQuerySystem + */ + class PxSceneQuerySystemBase + { + protected: + PxSceneQuerySystemBase() {} + virtual ~PxSceneQuerySystemBase() {} + + public: + + /** \name Scene Query + */ + //\{ + + /** + \brief Sets the rebuild rate of the dynamic tree pruning structures. + + \param[in] dynamicTreeRebuildRateHint Rebuild rate of the dynamic tree pruning structures. + + \see PxSceneQueryDesc.dynamicTreeRebuildRateHint getDynamicTreeRebuildRateHint() forceRebuildDynamicTree() + */ + virtual void setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint) = 0; + + /** + \brief Retrieves the rebuild rate of the dynamic tree pruning structures. + + \return The rebuild rate of the dynamic tree pruning structures. + + \see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() forceRebuildDynamicTree() + */ + virtual PxU32 getDynamicTreeRebuildRateHint() const = 0; + + /** + \brief Forces dynamic trees to be immediately rebuilt. + + \param[in] prunerIndex Index of pruner containing the dynamic tree to rebuild + + \note PxScene will call this function with the PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC value. + + \see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint() + */ + virtual void forceRebuildDynamicTree(PxU32 prunerIndex) = 0; + + /** + \brief Sets scene query update mode + + \param[in] updateMode Scene query update mode. + + \see PxSceneQueryUpdateMode::Enum + */ + virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) = 0; + + /** + \brief Gets scene query update mode + + \return Current scene query update mode. + + \see PxSceneQueryUpdateMode::Enum + */ + virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const = 0; + + /** + \brief Retrieves the system's internal scene query timestamp, increased each time a change to the + static scene query structure is performed. + + \return scene query static timestamp + */ + virtual PxU32 getStaticTimestamp() const = 0; + + /** + \brief Flushes any changes to the scene query representation. + + This method updates the state of the scene query representation to match changes in the scene state. + + By default, these changes are buffered until the next query is submitted. Calling this function will not change + the results from scene queries, but can be used to ensure that a query will not perform update work in the course of + its execution. + + A thread performing updates will hold a write lock on the query structure, and thus stall other querying threads. In multithread + scenarios it can be useful to explicitly schedule the period where this lock may be held for a significant period, so that + subsequent queries issued from multiple threads will not block. + */ + virtual void flushUpdates() = 0; + + /** + \brief Performs a raycast against objects in the scene, returns results in a PxRaycastBuffer object + or via a custom user callback implementation inheriting from PxRaycastCallback. + + \note Touching hits are not ordered. + \note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in user guide article SceneQuery. User can ignore such objects by employing one of the provided filter mechanisms. + + \param[in] origin Origin of the ray. + \param[in] unitDir Normalized direction of the ray. + \param[in] distance Length of the ray. Has to be in the [0, inf) range. + \param[out] hitCall Raycast hit buffer or callback object used to report raycast hits. + \param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback. + \param[in] filterData Filtering data passed to the filter shader. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Ray is tested against cached shape first. If no hit is found the ray gets queried against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \param[in] queryFlags Optional flags controlling the query. + + \return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified. + + \see PxRaycastCallback PxRaycastBuffer PxQueryFilterData PxQueryFilterCallback PxQueryCache PxRaycastHit PxQueryFlag PxQueryFlag::eANY_HIT PxGeometryQueryFlag + */ + virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, + PxRaycastCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT, + const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL, + const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0; + + /** + \brief Performs a sweep test against objects in the scene, returns results in a PxSweepBuffer object + or via a custom user callback implementation inheriting from PxSweepCallback. + + \note Touching hits are not ordered. + \note If a shape from the scene is already overlapping with the query shape in its starting position, + the hit is returned unless eASSUME_NO_INITIAL_OVERLAP was specified. + + \param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex core, convex mesh). + \param[in] pose Pose of the sweep object. + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be in [0, inf) range and >0 if eASSUME_NO_INITIAL_OVERLAP was specified. Will be clamped to PX_MAX_SWEEP_DISTANCE. + \param[out] hitCall Sweep hit buffer or callback object used to report sweep hits. + \param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Sweep is performed against cached shape first. If no hit is found the sweep gets queried against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + Note: ePRECISE_SWEEP doesn't support inflation. Therefore the sweep will be performed with zero inflation. + \param[in] queryFlags Optional flags controlling the query. + + \return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified. + + \see PxSweepCallback PxSweepBuffer PxQueryFilterData PxQueryFilterCallback PxSweepHit PxQueryCache PxGeometryQueryFlag + */ + virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, + PxSweepCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT, + const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL, + const PxQueryCache* cache = NULL, const PxReal inflation = 0.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0; + + /** + \brief Performs an overlap test of a given geometry against objects in the scene, returns results in a PxOverlapBuffer object + or via a custom user callback implementation inheriting from PxOverlapCallback. + + \note Filtering: returning eBLOCK from user filter for overlap queries will cause a warning (see #PxQueryHitType). + + \param[in] geometry Geometry of object to check for overlap (supported types are: box, sphere, capsule, convex core, convex mesh). + \param[in] pose Pose of the object. + \param[out] hitCall Overlap hit buffer or callback object used to report overlap hits. + \param[in] filterData Filtering data and simple logic. See #PxQueryFilterData #PxQueryFilterCallback + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to overlap. + \param[in] cache Cached hit shape (optional). Overlap is performed against cached shape first. If no hit is found the overlap gets queried against the scene. + \param[in] queryFlags Optional flags controlling the query. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + + \return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified. + + \note eBLOCK should not be returned from user filters for overlap(). Doing so will result in undefined behavior, and a warning will be issued. + \note If the PxQueryFlag::eNO_BLOCK flag is set, the eBLOCK will instead be automatically converted to an eTOUCH and the warning suppressed. + + \see PxOverlapCallback PxOverlapBuffer PxHitFlags PxQueryFilterData PxQueryFilterCallback PxGeometryQueryFlag + */ + virtual bool overlap(const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hitCall, + const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL, + const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0; + //\} + }; + + /** + \brief Traditional SQ system for PxScene. + + Methods defined here are only available through the traditional PxScene API. + Thus PxSceneSQSystem effectively captures the scene-query related part of the PxScene API. + + \see PxScene PxSceneQuerySystemBase + */ + class PxSceneSQSystem : public PxSceneQuerySystemBase + { + protected: + PxSceneSQSystem() {} + virtual ~PxSceneSQSystem() {} + + public: + + /** \name Scene Query + */ + //\{ + + /** + \brief Sets scene query update mode + + \param[in] updateMode Scene query update mode. + + \see PxSceneQueryUpdateMode::Enum + */ + PX_FORCE_INLINE void setSceneQueryUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) { setUpdateMode(updateMode); } + + /** + \brief Gets scene query update mode + + \return Current scene query update mode. + + \see PxSceneQueryUpdateMode::Enum + */ + PX_FORCE_INLINE PxSceneQueryUpdateMode::Enum getSceneQueryUpdateMode() const { return getUpdateMode(); } + + /** + \brief Retrieves the scene's internal scene query timestamp, increased each time a change to the + static scene query structure is performed. + + \return scene query static timestamp + */ + PX_FORCE_INLINE PxU32 getSceneQueryStaticTimestamp() const { return getStaticTimestamp(); } + + /** + \brief Flushes any changes to the scene query representation. + + \see flushUpdates + */ + PX_FORCE_INLINE void flushQueryUpdates() { flushUpdates(); } + + /** + \brief Forces dynamic trees to be immediately rebuilt. + + \param[in] rebuildStaticStructure True to rebuild the dynamic tree containing static objects + \param[in] rebuildDynamicStructure True to rebuild the dynamic tree containing dynamic objects + + \see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint() + */ + PX_FORCE_INLINE void forceDynamicTreeRebuild(bool rebuildStaticStructure, bool rebuildDynamicStructure) + { + if(rebuildStaticStructure) + forceRebuildDynamicTree(PX_SCENE_PRUNER_STATIC); + if(rebuildDynamicStructure) + forceRebuildDynamicTree(PX_SCENE_PRUNER_DYNAMIC); + } + + /** + \brief Return the value of PxSceneQueryDesc::staticStructure that was set when creating the scene with PxPhysics::createScene + + \see PxSceneQueryDesc::staticStructure, PxPhysics::createScene + */ + virtual PxPruningStructureType::Enum getStaticStructure() const = 0; + + /** + \brief Return the value of PxSceneQueryDesc::dynamicStructure that was set when creating the scene with PxPhysics::createScene + + \see PxSceneQueryDesc::dynamicStructure, PxPhysics::createScene + */ + virtual PxPruningStructureType::Enum getDynamicStructure() const = 0; + + /** + \brief Executes scene queries update tasks. + + This function will refit dirty shapes within the pruner and will execute a task to build a new AABB tree, which is + build on a different thread. The new AABB tree is built based on the dynamic tree rebuild hint rate. Once + the new tree is ready it will be commited in next fetchQueries call, which must be called after. + + This function is equivalent to the following PxSceneQuerySystem calls: + Synchronous calls: + - PxSceneQuerySystemBase::flushUpdates() + - handle0 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_STATIC) + - handle1 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_DYNAMIC) + Asynchronous calls: + - PxSceneQuerySystem::sceneQueryBuildStep(handle0); + - PxSceneQuerySystem::sceneQueryBuildStep(handle1); + + This function is part of the PxSceneSQSystem interface because it uses the PxScene task system under the hood. But + it calls PxSceneQuerySystem functions, which are independent from this system and could be called in a similar + fashion by a separate, possibly user-defined task manager. + + \note If PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED is used, it is required to update the scene queries + using this function. + + \param[in] completionTask if non-NULL, this task will have its refcount incremented in sceneQueryUpdate(), then + decremented when the scene is ready to have fetchQueries called. So the task will not run until the + application also calls removeReference(). + \param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave + true unless the application is calling the PxTaskManager start/stopSimulation() methods itself. + + \see PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED + */ + virtual void sceneQueriesUpdate(PxBaseTask* completionTask = NULL, bool controlSimulation = true) = 0; + + /** + \brief This checks to see if the scene queries update has completed. + + This does not cause the data available for reading to be updated with the results of the scene queries update, it is simply a status check. + The bool will allow it to either return immediately or block waiting for the condition to be met so that it can return true + + \param[in] block When set to true will block until the condition is met. + \return True if the results are available. + + \see sceneQueriesUpdate() fetchResults() + */ + virtual bool checkQueries(bool block = false) = 0; + + /** + This method must be called after sceneQueriesUpdate. It will wait for the scene queries update to finish. If the user makes an illegal scene queries update call, + the SDK will issue an error message. + + If a new AABB tree build finished, then during fetchQueries the current tree within the pruning structure is swapped with the new tree. + + \param[in] block When set to true will block until the condition is met, which is tree built task must finish running. + */ + virtual bool fetchQueries(bool block = false) = 0; + //\} + }; + + typedef PxU32 PxSQCompoundHandle; + typedef PxU32 PxSQPrunerHandle; + typedef void* PxSQBuildStepHandle; + + /** + \brief Scene-queries external sub-system for PxScene-based objects. + + The default PxScene has hardcoded support for 2 regular pruners + 1 compound pruner, but these interfaces + should work with multiple pruners. + + Regular shapes are traditional PhysX shapes that belong to an actor. That actor can be a compound, i.e. it has + more than one shape. *All of these go to the regular pruners*. This is important because it might be misleading: + by default all shapes go to one of the two regular pruners, even shapes that belong to compound actors. + + For compound actors, adding all the actor's shapes individually to the SQ system can be costly, since all the + corresponding bounds will always move together and remain close together - that can put a lot of stress on the + code that updates the SQ spatial structures. In these cases it can be more efficient to add the compound's bounds + (i.e. the actor's bounds) to the system, as the first level of a bounds hierarchy. The scene queries would then + be performed against the actor's bounds first, and only visit the shapes' bounds second. This is only useful + for actors that have more than one shape, i.e. compound actors. Such actors added to the SQ system are thus + called "SQ compounds". These objects are managed by the "compound pruner", which is only used when an explicit + SQ compound is added to the SQ system via the addSQCompound call. So in the end one has to distinguish between: + + - a "compound shape", which is added to regular pruners as its own individual entity. + - an "SQ compound shape", which is added to the compound pruner as a subpart of an SQ compound actor. + + A compound shape has an invalid compound ID, since it does not belong to an SQ compound. + An SQ compound shape has a valid compound ID, that identifies its SQ compound owner. + + \see PxScene PxSceneQuerySystemBase + */ + class PxSceneQuerySystem : public PxSceneQuerySystemBase + { + protected: + PxSceneQuerySystem() {} + virtual ~PxSceneQuerySystem() {} + public: + + /** + \brief Decrements the reference count of the object and releases it if the new reference count is zero. + */ + virtual void release() = 0; + + /** + \brief Acquires a counted reference to this object. + + This method increases the reference count of the object by 1. Decrement the reference count by calling release() + */ + virtual void acquireReference() = 0; + + /** + \brief Preallocates internal arrays to minimize the amount of reallocations. + + The system does not prevent more allocations than given numbers. It is legal to not call this function at all, + or to add more shapes to the system than the preallocated amounts. + + \param[in] prunerIndex Index of pruner to preallocate (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene). + \param[in] nbShapes Expected number of (regular) shapes + */ + virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) = 0; + + /** + \brief Frees internal memory that may not be in-use anymore. + + This is an entry point for reclaiming transient memory allocated at some point by the SQ system, + but which wasn't been immediately freed for performance reason. Calling this function might free + some memory, but it might also produce a new set of allocations in the next frame. + */ + virtual void flushMemory() = 0; + + /** + \brief Adds a shape to the SQ system. + + The same function is used to add either a regular shape, or a SQ compound shape. + + \param[in] actor The shape's actor owner + \param[in] shape The shape itself + \param[in] bounds Shape bounds, in world-space for regular shapes, in local-space for SQ compound shapes. + \param[in] transform Shape transform, in world-space for regular shapes, in local-space for SQ compound shapes. + \param[in] compoundHandle Handle of SQ compound owner, or NULL for regular shapes. + \param[in] hasPruningStructure True if the shape is part of a pruning structure. The structure will be merged later, adding the objects will not invalidate the pruner. + + \see merge() PxPruningStructure + */ + virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds, + const PxTransform& transform, const PxSQCompoundHandle* compoundHandle=NULL, bool hasPruningStructure=false) = 0; + + /** + \brief Removes a shape from the SQ system. + + The same function is used to remove either a regular shape, or a SQ compound shape. + + \param[in] actor The shape's actor owner + \param[in] shape The shape itself + */ + virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape) = 0; + + /** + \brief Updates a shape in the SQ system. + + The same function is used to update either a regular shape, or a SQ compound shape. + + The transforms are eager-evaluated, but the bounds are lazy-evaluated. This means that + the updated transform has to be passed to the update function, while the bounds are automatically + recomputed by the system whenever needed. + + \param[in] actor The shape's actor owner + \param[in] shape The shape itself + \param[in] transform New shape transform, in world-space for regular shapes, in local-space for SQ compound shapes. + */ + virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform) = 0; + + /** + \brief Adds a compound to the SQ system. + + \param[in] actor The compound actor + \param[in] shapes The compound actor's shapes + \param[in] bvh BVH structure containing the compound's shapes in local space + \param[in] transforms Shape transforms, in local-space + + \return SQ compound handle + + \see PxBVH PxCooking::createBVH + */ + virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& bvh, const PxTransform* transforms) = 0; + + /** + \brief Removes a compound from the SQ system. + + \param[in] compoundHandle SQ compound handle (returned by addSQCompound) + */ + virtual void removeSQCompound(PxSQCompoundHandle compoundHandle) = 0; + + /** + \brief Updates a compound in the SQ system. + + The compound structures are immediately updated when the call occurs. + + \param[in] compoundHandle SQ compound handle (returned by addSQCompound) + \param[in] compoundTransform New actor/compound transform, in world-space + */ + virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform) = 0; + + /** + \brief Shift the data structures' origin by the specified vector. + + Please refer to the notes of the similar function in PxScene. + + \param[in] shift Translation vector to shift the origin by. + */ + virtual void shiftOrigin(const PxVec3& shift) = 0; + + /** + \brief Visualizes the system's internal data-structures, for debugging purposes. + + \param[in] prunerIndex Index of pruner to visualize (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene). + + \param[out] out Filled with render output data + + \see PxRenderOutput + */ + virtual void visualize(PxU32 prunerIndex, PxRenderOutput& out) const = 0; + + /** + \brief Merges a pruning structure with the SQ system's internal pruners. + + \param[in] pruningStructure The pruning structure to merge + + \see PxPruningStructure + */ + virtual void merge(const PxPruningStructure& pruningStructure) = 0; + + /** + \brief Shape to SQ-pruner-handle mapping function. + + This function finds and returns the SQ pruner handle associated with a given (actor/shape) couple + that was previously added to the system. This is needed for the sync function. + + \param[in] actor The shape's actor owner + \param[in] shape The shape itself + \param[out] prunerIndex Index of pruner the shape belongs to + + \return Associated SQ pruner handle. + */ + virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const = 0; + + /** + \brief Synchronizes the scene-query system with another system that references the same objects. + + This function is used when the scene-query objects also exist in another system that can also update them. For example the scene-query objects + (used for raycast, overlap or sweep queries) might be driven by equivalent objects in an external rigid-body simulation engine. In this case + the rigid-body simulation engine computes the new poses and transforms, and passes them to the scene-query system using this function. It is + more efficient than calling updateSQShape on each object individually, since updateSQShape would end up recomputing the bounds already available + in the rigid-body engine. + + \param[in] prunerIndex Index of pruner being synched (PX_SCENE_PRUNER_DYNAMIC for regular PhysX usage) + \param[in] handles Handles of updated objects + \param[in] indices Bounds & transforms indices of updated objects, i.e. object handles[i] has bounds[indices[i]] and transforms[indices[i]] + \param[in] bounds Array of bounds for all objects (not only updated bounds) + \param[in] transforms Array of transforms for all objects (not only updated transforms) + \param[in] count Number of updated objects + \param[in] ignoredIndices Optional bitmap of ignored indices, i.e. update is skipped if ignoredIndices[indices[i]] is set. + + \see PxBounds3 PxTransform32 PxBitMap + */ + virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) = 0; + + /** + \brief Finalizes updates made to the SQ system. + + This function should be called after updates have been made to the SQ system, to fully reflect the changes + inside the internal pruners. In particular it should be called: + - after calls to updateSQShape + - after calls to sync + + This function: + - recomputes bounds of manually updated shapes (i.e. either regular or SQ compound shapes modified by updateSQShape) + - updates dynamic pruners (refit operations) + - incrementally rebuilds AABB-trees + + The amount of work performed in this function depends on PxSceneQueryUpdateMode. + + \see PxSceneQueryUpdateMode updateSQShape() sync() + */ + virtual void finalizeUpdates() = 0; + + /** + \brief Prepares asynchronous build step. + + This is directly called (synchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there. + + This function is called to let the system execute any necessary synchronous operation before the + asynchronous sceneQueryBuildStep() function is called. + + If there is any work to do for the specific pruner, the function returns a pruner-specific handle that + will be passed to the corresponding, asynchronous sceneQueryBuildStep function. + + \return A pruner-specific handle that will be sent to sceneQueryBuildStep if there is any work to do, i.e. to execute the corresponding sceneQueryBuildStep() call. + + \param[in] prunerIndex Index of pruner being built. (PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC when called by PxScene). + + \return Null if there is no work to do, otherwise a pruner-specific handle. + + \see PxSceneSQSystem::sceneQueriesUpdate sceneQueryBuildStep + */ + virtual PxSQBuildStepHandle prepareSceneQueryBuildStep(PxU32 prunerIndex) = 0; + + /** + \brief Executes asynchronous build step. + + This is directly called (asynchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there. + + This function incrementally builds the internal trees/pruners. It is called asynchronously, i.e. this can be + called from different threads for building multiple trees at the same time. + + \param[in] handle Pruner-specific handle previously returned by the prepareSceneQueryBuildStep function. + + \see PxSceneSQSystem::sceneQueriesUpdate prepareSceneQueryBuildStep + */ + virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle) = 0; + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxShape.h b/Jusin154_Team3D/Engine/Public/PhysX/PxShape.h new file mode 100644 index 000000000..657c907f3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxShape.h @@ -0,0 +1,613 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SHAPE_H +#define PX_SHAPE_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" +#include "foundation/PxSimpleTypes.h" +#include "geometry/PxGeometry.h" +#include "geometry/PxGeometryHelpers.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxBoxGeometry; +class PxSphereGeometry; +class PxCapsuleGeometry; +class PxPlaneGeometry; +class PxConvexMeshGeometry; +class PxTriangleMeshGeometry; +class PxTetrahedronMeshGeometry; +class PxHeightFieldGeometry; +class PxParticleSystemGeometry; +class PxRigidActor; +struct PxFilterData; +class PxBaseMaterial; +class PxMaterial; +class PxDeformableSurfaceMaterial; +class PxDeformableVolumeMaterial; + +/** +\brief Flags which affect the behavior of PxShapes. + +\see PxShape PxShape.setFlag() +*/ +struct PxShapeFlag +{ + enum Enum + { + /** + \brief The shape will partake in collision in the physical simulation. + + \note It is illegal to raise the eSIMULATION_SHAPE and eTRIGGER_SHAPE flags. + In the event that one of these flags is already raised the sdk will reject any + attempt to raise the other. To raise the eSIMULATION_SHAPE first ensure that + eTRIGGER_SHAPE is already lowered. + + \note This flag has no effect if simulation is disabled for the corresponding actor (see #PxActorFlag::eDISABLE_SIMULATION). + + \see PxSimulationEventCallback.onContact() PxScene.setSimulationEventCallback() PxShape.setFlag(), PxShape.setFlags() + */ + eSIMULATION_SHAPE = (1<<0), + + /** + \brief The shape will partake in scene queries (ray casts, overlap tests, sweeps, ...). + */ + eSCENE_QUERY_SHAPE = (1<<1), + + /** + \brief The shape is a trigger which can send reports whenever other shapes enter/leave its volume. + + \note Triangle meshes and heightfields can not be triggers. Shape creation will fail in these cases. + + \note Shapes marked as triggers do not collide with other objects. If an object should act both + as a trigger shape and a collision shape then create a rigid body with two shapes, one being a + trigger shape and the other a collision shape. It is illegal to raise the eTRIGGER_SHAPE and + eSIMULATION_SHAPE flags on a single PxShape instance. In the event that one of these flags is already + raised the sdk will reject any attempt to raise the other. To raise the eTRIGGER_SHAPE flag first + ensure that eSIMULATION_SHAPE flag is already lowered. + + \note Trigger shapes will no longer send notification events for interactions with other trigger shapes. + + \note Shapes marked as triggers are allowed to participate in scene queries, provided the eSCENE_QUERY_SHAPE flag is set. + + \note This flag has no effect if simulation is disabled for the corresponding actor (see #PxActorFlag::eDISABLE_SIMULATION). + + \see PxSimulationEventCallback.onTrigger() PxScene.setSimulationEventCallback() PxShape.setFlag(), PxShape.setFlags() + */ + eTRIGGER_SHAPE = (1<<2), + + /** + \brief Enable debug renderer for this shape + + \see PxScene.getRenderBuffer() PxRenderBuffer PxVisualizationParameter + */ + eVISUALIZATION = (1<<3) + }; +}; + +/** +\brief collection of set bits defined in PxShapeFlag. + +\see PxShapeFlag +*/ +typedef PxFlags PxShapeFlags; +PX_FLAGS_OPERATORS(PxShapeFlag::Enum,PxU8) + +/** +\brief Abstract class for collision shapes. + +Shapes are shared, reference counted objects. + +An instance can be created by calling the createShape() method of the PxRigidActor class, or +the createShape() method of the PxPhysics class. + +

Visualizations

+\li PxVisualizationParameter::eCOLLISION_AABBS +\li PxVisualizationParameter::eCOLLISION_SHAPES +\li PxVisualizationParameter::eCOLLISION_AXES + +\see PxPhysics.createShape() PxRigidActor.createShape() PxBoxGeometry PxSphereGeometry PxCapsuleGeometry PxPlaneGeometry PxConvexMeshGeometry +PxTriangleMeshGeometry PxHeightFieldGeometry +*/ +class PxShape : public PxRefCounted +{ +public: + /** + \brief Adjust the geometry of the shape. + + \note The type of the passed in geometry must match the geometry type of the shape. + \note It is not allowed to change the geometry type of a shape. + \note This function does not guarantee correct/continuous behavior when objects are resting on top of old or new geometry. + + \param[in] geometry New geometry of the shape. + + \see PxGeometry PxGeometryType getGeometryType() + */ + virtual void setGeometry(const PxGeometry& geometry) = 0; + + /** + \brief Retrieve a reference to the shape's geometry. + + \warning The returned reference has the same lifetime as the PxShape it comes from. + + \return Reference to internal PxGeometry object. + + \see PxGeometry PxGeometryType getGeometryType() setGeometry() + */ + virtual const PxGeometry& getGeometry() const = 0; + + /** + \brief Retrieves the actor which this shape is associated with. + + \return The actor this shape is associated with, if it is an exclusive shape, else NULL + + \see PxRigidStatic, PxRigidDynamic, PxArticulationLink + */ + virtual PxRigidActor* getActor() const = 0; + +/************************************************************************************************/ + +/** \name Pose Manipulation +*/ +//\{ + + /** + \brief Sets the pose of the shape in actor space, i.e. relative to the actors to which they are attached. + + This transformation is identity by default. + + The local pose is an attribute of the shape, and so will apply to all actors to which the shape is attached. + + Sleeping: Does NOT wake the associated actor up automatically. + + Note: Does not automatically update the inertia properties of the owning actor (if applicable); use the + PhysX extensions method #PxRigidBodyExt::updateMassAndInertia() to do this. + + Default: the identity transform + + \param[in] pose The new transform from the actor frame to the shape frame. Range: rigid body transform + + \see getLocalPose() + */ + virtual void setLocalPose(const PxTransform& pose) = 0; + + /** + \brief Retrieves the pose of the shape in actor space, i.e. relative to the actor they are owned by. + + This transformation is identity by default. + + \return Pose of shape relative to the actor's frame. + + \see setLocalPose() + */ + virtual PxTransform getLocalPose() const = 0; + +//\} +/************************************************************************************************/ + +/** \name Collision Filtering +*/ +//\{ + + /** + \brief Sets the user definable collision filter data. + + Sleeping: Does wake up the actor if the filter data change causes a formerly suppressed + collision pair to be enabled. + + Default: (0,0,0,0) + + \see getSimulationFilterData() + */ + virtual void setSimulationFilterData(const PxFilterData& data) = 0; + + /** + \brief Retrieves the shape's collision filter data. + + \see setSimulationFilterData() + */ + virtual PxFilterData getSimulationFilterData() const = 0; + + /** + \brief Sets the user definable query filter data. + + Default: (0,0,0,0) + + \see getQueryFilterData() + */ + virtual void setQueryFilterData(const PxFilterData& data) = 0; + + /** + \brief Retrieves the shape's Query filter data. + + \see setQueryFilterData() + */ + virtual PxFilterData getQueryFilterData() const = 0; + +//\} +/************************************************************************************************/ + + /** + \brief Assigns material(s) to the shape. Will remove existing materials from the shape. + + Sleeping: Does NOT wake the associated actor up automatically. + + \param[in] materials List of material pointers to assign to the shape. See #PxMaterial + \param[in] materialCount The number of materials provided. + + \see PxPhysics.createMaterial() getMaterials() + */ + virtual void setMaterials(PxMaterial*const* materials, PxU16 materialCount) = 0; + + /** + \brief Assigns surface deformable material(s) to the shape. Will remove existing materials from the shape. + + Sleeping: Does NOT wake the associated actor up automatically. + + \param[in] materials List of material pointers to assign to the shape. See #PxDeformableSurfaceMaterial + \param[in] materialCount The number of materials provided. + + \see PxPhysics.createDeformableSurfaceMaterial() getDeformableSurfaceMaterials() + */ + virtual void setDeformableSurfaceMaterials(PxDeformableSurfaceMaterial*const* materials, PxU16 materialCount) = 0; + + /** + \brief Assigns deformable volume material(s) to the shape. Will remove existing materials from the shape. + + Sleeping: Does NOT wake the associated actor up automatically. + + \param[in] materials List of material pointers to assign to the shape. See #PxDeformableVolumeMaterial + \param[in] materialCount The number of materials provided. + + \see PxPhysics.createDeformableVolumeMaterial() getDeformableVolumeMaterials() + */ + virtual void setDeformableVolumeMaterials(PxDeformableVolumeMaterial* const* materials, PxU16 materialCount) = 0; + + /** + \brief Deprecated + \see setDeformableVolumeMaterials + */ + PX_DEPRECATED PX_FORCE_INLINE void setSoftBodyMaterials(PxDeformableVolumeMaterial* const* materials, PxU16 materialCount) + { + setDeformableVolumeMaterials(materials, materialCount); + } + + /** + \brief Returns the number of materials assigned to the shape. + + You can use #getMaterials() to retrieve the material pointers. + + \return Number of materials associated with this shape. + + \see PxMaterial getMaterials() + */ + virtual PxU16 getNbMaterials() const = 0; + + /** + \brief Retrieve all the material pointers associated with the shape. + + You can retrieve the number of material pointers by calling #getNbMaterials() + + Note: The returned data may contain invalid pointers if you release materials using #PxMaterial::release(). + + \param[out] userBuffer The buffer to store the material pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first material pointer to be retrieved + \return Number of material pointers written to the buffer. + + \see PxMaterial getNbMaterials() PxMaterial::release() + */ + virtual PxU32 getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Retrieve all the surface deformable material pointers associated with the shape. + + You can retrieve the number of material pointers by calling #getNbMaterials() + + Note: The returned data may contain invalid pointers if you release materials using #PxMaterial::release(). + + \param[out] userBuffer The buffer to store the material pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first material pointer to be retrieved + \return Number of material pointers written to the buffer. + + \see PxDeformableSurfaceMaterial getNbMaterials() PxMaterial::release() + */ + virtual PxU32 getDeformableSurfaceMaterials(PxDeformableSurfaceMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Retrieve all the deformable volume material pointers associated with the shape. + + You can retrieve the number of material pointers by calling #getNbMaterials() + + Note: The returned data may contain invalid pointers if you release materials using #PxMaterial::release(). + + \param[out] userBuffer The buffer to store the material pointers. + \param[in] bufferSize Size of provided user buffer. + \param[in] startIndex Index of first material pointer to be retrieved + \return Number of material pointers written to the buffer. + + \see PxDeformableVolumeMaterial getNbMaterials() PxMaterial::release() + */ + virtual PxU32 getDeformableVolumeMaterials(PxDeformableVolumeMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; + + /** + \brief Deprecated + \see getDeformableVolumeMaterials + */ + PX_DEPRECATED PX_FORCE_INLINE PxU32 getSoftBodyMaterials(PxDeformableVolumeMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const + { + return getDeformableVolumeMaterials(userBuffer, bufferSize, startIndex); + } + + /** + \brief Retrieve material from given triangle index. + + The input index is the internal triangle index as used inside the SDK. This is the index + returned to users by various SDK functions such as raycasts. + + This function is only useful for triangle meshes or heightfields, which have per-triangle + materials. For other shapes or SDF triangle meshes, the function returns the single material + associated with the shape, regardless of the index. + + \param[in] faceIndex The internal triangle index whose material you want to retrieve. + \return Material from input triangle + + \note If faceIndex value of 0xFFFFffff is passed as an input for mesh and heightfield shapes, this function will issue a warning and return NULL. + \note Scene queries set the value of PxQueryHit::faceIndex to 0xFFFFffff whenever it is undefined or does not apply. + + \see PxMaterial getNbMaterials() PxMaterial::release() + */ + virtual PxBaseMaterial* getMaterialFromInternalFaceIndex(PxU32 faceIndex) const = 0; + + /** + \brief Sets the contact offset. + + Shapes whose distance is less than the sum of their contactOffset values will generate contacts. The contact offset must be positive and + greater than the rest offset. Having a contactOffset greater than than the restOffset allows the collision detection system to + predictively enforce the contact constraint even when the objects are slightly separated. This prevents jitter that would occur + if the constraint were enforced only when shapes were within the rest distance. + + Default: 0.02f * PxTolerancesScale::length + + Sleeping: Does NOT wake the associated actor up automatically. + + \param[in] contactOffset Range: [maximum(0,restOffset), PX_MAX_F32) + + \see getContactOffset PxTolerancesScale setRestOffset + */ + virtual void setContactOffset(PxReal contactOffset) = 0; + + /** + \brief Retrieves the contact offset. + + \return The contact offset of the shape. + + \see setContactOffset() + */ + virtual PxReal getContactOffset() const = 0; + + /** + \brief Sets the rest offset. + + Two shapes will come to rest at a distance equal to the sum of their restOffset values. If the restOffset is 0, they should converge to touching + exactly. Having a restOffset greater than zero is useful to have objects slide smoothly, so that they do not get hung up on irregularities of + each others' surfaces. + + Default: 0.0f + + Sleeping: Does NOT wake the associated actor up automatically. + + \param[in] restOffset Range: (-PX_MAX_F32, contactOffset) + + \see getRestOffset setContactOffset + */ + virtual void setRestOffset(PxReal restOffset) = 0; + + /** + \brief Retrieves the rest offset. + + \return The rest offset of the shape. + + \see setRestOffset() + */ + virtual PxReal getRestOffset() const = 0; + + /** + \brief Sets the density used to interact with fluids. + + To be physically accurate, the density of a rigid body should be computed as its mass divided by its volume. To + simplify tuning the interaction of fluid and rigid bodies, the density for fluid can differ from the real density. This + allows to create floating bodies, even if they are supposed to sink with their mass and volume. + + Default: 800.0f + + \param[in] densityForFluid Range: (0, PX_MAX_F32) + + \see getDensityForFluid + */ + virtual void setDensityForFluid(PxReal densityForFluid) = 0; + + /** + \brief Retrieves the density used to interact with fluids. + + \return The density of the body when interacting with fluid. + + \see setDensityForFluid() + */ + virtual PxReal getDensityForFluid() const = 0; + + /** + \brief Sets torsional patch radius. + + This defines the radius of the contact patch used to apply torsional friction. If the radius is 0 (and minTorsionalPatchRadius + is 0 too, see #setMinTorsionalPatchRadius), no torsional friction will be applied. If the radius is > 0, some torsional friction + will be applied. This is proportional to the penetration depth so, if the shapes are separated or penetration is zero, no + torsional friction will be applied. It is used to approximate rotational friction introduced by the compression of contacting surfaces. + + \note Will only be active, if the friction patch has a single anchor point only. This is for example the case, if a contact patch + has a single contact point. + + \note Only supported in combination with solver type PxSolverType::eTGS. + + Default: 0.0 + + \param[in] radius Range: [0, PX_MAX_F32) + */ + virtual void setTorsionalPatchRadius(PxReal radius) = 0; + + /** + \brief Gets torsional patch radius. + + See #setTorsionalPatchRadius for more info. + + \return The torsional patch radius of the shape. + */ + virtual PxReal getTorsionalPatchRadius() const = 0; + + /** + \brief Sets minimum torsional patch radius. + + This defines the minimum radius of the contact patch used to apply torsional friction. If the radius is 0, the amount of torsional friction + that will be applied will be entirely dependent on the value of torsionalPatchRadius. + + If the radius is > 0, some torsional friction will be applied regardless of the value of torsionalPatchRadius or the amount of penetration. + + \note Will only be active in certain cases, see #setTorsionalPatchRadius for details. + + Default: 0.0 + + \param[in] radius Range: [0, PX_MAX_F32) + */ + virtual void setMinTorsionalPatchRadius(PxReal radius) = 0; + + /** + \brief Gets minimum torsional patch radius. + + See #setMinTorsionalPatchRadius for more info. + + \return The minimum torsional patch radius of the shape. + */ + virtual PxReal getMinTorsionalPatchRadius() const = 0; + + /** + \brief Returns the GPU shape index. + + \note This function only returns valid results if GPU dynamics is enabled. + + \return The GPU index, or 0xFFFFFFFF if the shape is not attached to a PxActor that is inserted into a PxScene. + + \see PxDirectGPUAPI::evaluateSDFDistances(). + */ + virtual PxShapeGPUIndex getGPUIndex() const = 0; + +/************************************************************************************************/ + + /** + \brief Sets shape flags + + Sleeping: Does NOT wake the associated actor up automatically. + + \param[in] flag The shape flag to enable/disable. See #PxShapeFlag. + \param[in] value True to set the flag. False to clear the flag specified in flag. + + Default: PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE + + \see PxShapeFlag getFlags() + */ + virtual void setFlag(PxShapeFlag::Enum flag, bool value) = 0; + + /** + \brief Sets shape flags + + \see PxShapeFlag getFlags() + */ + virtual void setFlags(PxShapeFlags inFlags) = 0; + + /** + \brief Retrieves shape flags. + + \return The values of the shape flags. + + \see PxShapeFlag setFlag() + */ + virtual PxShapeFlags getFlags() const = 0; + + /** + \brief Returns true if the shape is exclusive to an actor. + + \see PxPhysics::createShape() + */ + virtual bool isExclusive() const = 0; + + /** + \brief Sets a name string for the object that can be retrieved with #getName(). + + This is for debugging and is not used by the SDK. + The string is not copied by the SDK, only the pointer is stored. + + Default: NULL + + \param[in] name The name string to set the objects name to. + + \see getName() + */ + virtual void setName(const char* name) = 0; + + /** + \brief retrieves the name string set with setName(). + \return The name associated with the shape. + + \see setName() + */ + virtual const char* getName() const = 0; + + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxShape"; } + +/************************************************************************************************/ + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + PX_INLINE PxShape(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + PX_INLINE PxShape(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags), userData(NULL) {} + virtual ~PxShape() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxShape", PxRefCounted); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSimulationEventCallback.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSimulationEventCallback.h new file mode 100644 index 000000000..54f91e5fc --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSimulationEventCallback.h @@ -0,0 +1,963 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SIMULATION_EVENT_CALLBACK_H +#define PX_SIMULATION_EVENT_CALLBACK_H + +#include "foundation/PxVec3.h" +#include "foundation/PxTransform.h" +#include "foundation/PxMemory.h" +#include "PxPhysXConfig.h" +#include "PxFiltering.h" +#include "PxContact.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxShape; +class PxActor; +class PxRigidActor; +class PxRigidBody; +class PxConstraint; + + +/** +\brief Extra data item types for contact pairs. + +\see PxContactPairExtraDataItem.type +*/ +struct PxContactPairExtraDataType +{ + enum Enum + { + ePRE_SOLVER_VELOCITY, //!< see #PxContactPairVelocity + ePOST_SOLVER_VELOCITY, //!< see #PxContactPairVelocity + eCONTACT_EVENT_POSE, //!< see #PxContactPairPose + eCONTACT_PAIR_INDEX //!< see #PxContactPairIndex + }; +}; + + +/** +\brief Base class for items in the extra data stream of contact pairs + +\see PxContactPairHeader.extraDataStream +*/ +struct PxContactPairExtraDataItem +{ +public: + PX_FORCE_INLINE PxContactPairExtraDataItem() {} + + /** + \brief The type of the extra data stream item + */ + PxU8 type; +}; + + +/** +\brief Velocities of the contact pair rigid bodies + +This struct is shared by multiple types of extra data items. The #type field allows to distinguish between them: +\li PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY: see #PxPairFlag::ePRE_SOLVER_VELOCITY +\li PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY: see #PxPairFlag::ePOST_SOLVER_VELOCITY + +\note For static rigid bodies, the velocities will be set to zero. + +\see PxContactPairHeader.extraDataStream +*/ +struct PxContactPairVelocity : public PxContactPairExtraDataItem +{ +public: + PX_FORCE_INLINE PxContactPairVelocity() {} + + /** + \brief The linear velocity of the rigid bodies + */ + PxVec3 linearVelocity[2]; + + /** + \brief The angular velocity of the rigid bodies + */ + PxVec3 angularVelocity[2]; +}; + + +/** +\brief World space actor poses of the contact pair rigid bodies + +\see PxContactPairHeader.extraDataStream PxPairFlag::eCONTACT_EVENT_POSE +*/ +struct PxContactPairPose : public PxContactPairExtraDataItem +{ +public: + PX_FORCE_INLINE PxContactPairPose() {} + + /** + \brief The world space pose of the rigid bodies + */ + PxTransform globalPose[2]; +}; + + +/** +\brief Marker for the beginning of a new item set in the extra data stream. + +If CCD with multiple passes is enabled, then a fast moving object might bounce on and off the same +object multiple times. Also, different shapes of the same actor might gain and lose contact with an other +object over multiple passes. This marker allows to separate the extra data items for each collision case, as well as +distinguish the shape pair reports of different CCD passes. + +Example: +Let us assume that an actor a0 with shapes s0_0 and s0_1 hits another actor a1 with shape s1. +First s0_0 will hit s1, then a0 will slightly rotate and s0_1 will hit s1 while s0_0 will lose contact with s1. +Furthermore, let us say that contact event pose information is requested as extra data. +The extra data stream will look like this: + +PxContactPairIndexA | PxContactPairPoseA | PxContactPairIndexB | PxContactPairPoseB + +The corresponding array of PxContactPair events (see #PxSimulationEventCallback.onContact()) will look like this: + +PxContactPair(touch_found: s0_0, s1) | PxContactPair(touch_lost: s0_0, s1) | PxContactPair(touch_found: s0_1, s1) + +The #index of PxContactPairIndexA will point to the first entry in the PxContactPair array, for PxContactPairIndexB, +#index will point to the third entry. + +\see PxContactPairHeader.extraDataStream +*/ +struct PxContactPairIndex : public PxContactPairExtraDataItem +{ +public: + PX_FORCE_INLINE PxContactPairIndex() {} + + /** + \brief The next item set in the extra data stream refers to the contact pairs starting at #index in the reported PxContactPair array. + */ + PxU16 index; +}; + + +/** +\brief A class to iterate over a contact pair extra data stream. + +\see PxContactPairHeader.extraDataStream +*/ +struct PxContactPairExtraDataIterator +{ + /** + \brief Constructor + \param[in] stream Pointer to the start of the stream. + \param[in] size Size of the stream in bytes. + */ + PX_FORCE_INLINE PxContactPairExtraDataIterator(const PxU8* stream, PxU32 size) + : currPtr(stream), endPtr(stream + size), contactPairIndex(0) + { + clearDataPtrs(); + } + + /** + \brief Advances the iterator to next set of extra data items. + + The contact pair extra data stream contains sets of items as requested by the corresponding #PxPairFlag flags + #PxPairFlag::ePRE_SOLVER_VELOCITY, #PxPairFlag::ePOST_SOLVER_VELOCITY, #PxPairFlag::eCONTACT_EVENT_POSE. A set can contain one + item of each plus the PxContactPairIndex item. This method parses the stream and points the iterator + member variables to the corresponding items of the current set, if they are available. If CCD is not enabled, + you should only get one set of items. If CCD with multiple passes is enabled, you might get more than one item + set. + + \note Even though contact pair extra data is requested per shape pair, you will not get an item set per shape pair + but one per actor pair. If, for example, an actor has two shapes and both collide with another actor, then + there will only be one item set (since it applies to both shape pairs). + + \return True if there was another set of extra data items in the stream, else false. + + \see PxContactPairVelocity PxContactPairPose PxContactPairIndex + */ + PX_INLINE bool nextItemSet() + { + clearDataPtrs(); + + bool foundEntry = false; + bool endOfItemSet = false; + while ((currPtr < endPtr) && (!endOfItemSet)) + { + const PxContactPairExtraDataItem* edItem = reinterpret_cast(currPtr); + PxU8 type = edItem->type; + + switch(type) + { + case PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY: + { + PX_ASSERT(!preSolverVelocity); + preSolverVelocity = static_cast(edItem); + currPtr += sizeof(PxContactPairVelocity); + foundEntry = true; + } + break; + + case PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY: + { + postSolverVelocity = static_cast(edItem); + currPtr += sizeof(PxContactPairVelocity); + foundEntry = true; + } + break; + + case PxContactPairExtraDataType::eCONTACT_EVENT_POSE: + { + eventPose = static_cast(edItem); + currPtr += sizeof(PxContactPairPose); + foundEntry = true; + } + break; + + case PxContactPairExtraDataType::eCONTACT_PAIR_INDEX: + { + if (!foundEntry) + { + contactPairIndex = static_cast(edItem)->index; + currPtr += sizeof(PxContactPairIndex); + foundEntry = true; + } + else + endOfItemSet = true; + } + break; + + default: + return foundEntry; + } + } + + return foundEntry; + } + +private: + /** + \brief Internal helper + */ + PX_FORCE_INLINE void clearDataPtrs() + { + preSolverVelocity = NULL; + postSolverVelocity = NULL; + eventPose = NULL; + } + +public: + /** + \brief Current pointer in the stream. + */ + const PxU8* currPtr; + + /** + \brief Pointer to the end of the stream. + */ + const PxU8* endPtr; + + /** + \brief Pointer to the current pre solver velocity item in the stream. NULL if there is none. + + \see PxContactPairVelocity + */ + const PxContactPairVelocity* preSolverVelocity; + + /** + \brief Pointer to the current post solver velocity item in the stream. NULL if there is none. + + \see PxContactPairVelocity + */ + const PxContactPairVelocity* postSolverVelocity; + + /** + \brief Pointer to the current contact event pose item in the stream. NULL if there is none. + + \see PxContactPairPose + */ + const PxContactPairPose* eventPose; + + /** + \brief The contact pair index of the current item set in the stream. + + \see PxContactPairIndex + */ + PxU32 contactPairIndex; +}; + + +/** +\brief Collection of flags providing information on contact report pairs. + +\see PxContactPairHeader +*/ +struct PxContactPairHeaderFlag +{ + enum Enum + { + eREMOVED_ACTOR_0 = (1<<0), //!< The actor with index 0 has been removed from the scene. + eREMOVED_ACTOR_1 = (1<<1) //!< The actor with index 1 has been removed from the scene. + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxContactPairHeaderFlag. + +\see PxContactPairHeaderFlag +*/ +typedef PxFlags PxContactPairHeaderFlags; +PX_FLAGS_OPERATORS(PxContactPairHeaderFlag::Enum, PxU16) + + +/** +\brief An Instance of this class is passed to PxSimulationEventCallback.onContact(). + +\see PxSimulationEventCallback.onContact() +*/ +struct PxContactPairHeader +{ + public: + PX_INLINE PxContactPairHeader() {} + + /** + \brief The two actors of the notification shape pairs. + + \note The actor pointers might reference deleted actors. This will be the case if PxPairFlag::eNOTIFY_TOUCH_LOST + or PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved actors + gets deleted or removed from the scene. Check the #flags member to see whether that is the case. + Do not dereference a pointer to a deleted actor. The pointer to a deleted actor is only provided + such that user data structures which might depend on the pointer value can be updated. + + \see PxActor + */ + PxActor* actors[2]; + + /** + \brief Stream containing extra data as requested in the PxPairFlag flags of the simulation filter. + + This pointer is only valid if any kind of extra data information has been requested for the contact report pair (see #PxPairFlag::ePOST_SOLVER_VELOCITY etc.), + else it will be NULL. + + \see PxPairFlag + */ + const PxU8* extraDataStream; + + /** + \brief Size of the extra data stream [bytes] + */ + PxU16 extraDataStreamSize; + + /** + \brief Additional information on the contact report pair. + + \see PxContactPairHeaderFlag + */ + PxContactPairHeaderFlags flags; + + /** + \brief pointer to the contact pairs + */ + const struct PxContactPair* pairs; + + /** + \brief number of contact pairs + */ + PxU32 nbPairs; +}; + + +/** +\brief Collection of flags providing information on contact report pairs. + +\see PxContactPair +*/ +struct PxContactPairFlag +{ + enum Enum + { + /** + \brief The shape with index 0 has been removed from the actor/scene. + */ + eREMOVED_SHAPE_0 = (1<<0), + + /** + \brief The shape with index 1 has been removed from the actor/scene. + */ + eREMOVED_SHAPE_1 = (1<<1), + + /** + \brief First actor pair contact. + + The provided shape pair marks the first contact between the two actors, no other shape pair has been touching prior to the current simulation frame. + + \note: This info is only available if #PxPairFlag::eNOTIFY_TOUCH_FOUND has been declared for the pair. + */ + eACTOR_PAIR_HAS_FIRST_TOUCH = (1<<2), + + /** + \brief All contact between the actor pair was lost. + + All contact between the two actors has been lost, no shape pairs remain touching after the current simulation frame. + */ + eACTOR_PAIR_LOST_TOUCH = (1<<3), + + /** + \brief Internal flag, used by #PxContactPair.extractContacts() + + The applied contact impulses are provided for every contact point. + This is the case if #PxPairFlag::eSOLVE_CONTACT has been set for the pair. + */ + eINTERNAL_HAS_IMPULSES = (1<<4), + + /** + \brief Internal flag, used by #PxContactPair.extractContacts() + + The provided contact point information is flipped with regards to the shapes of the contact pair. This mainly concerns the order of the internal triangle indices. + */ + eINTERNAL_CONTACTS_ARE_FLIPPED = (1<<5) + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxContactPairFlag. + +\see PxContactPairFlag +*/ +typedef PxFlags PxContactPairFlags; +PX_FLAGS_OPERATORS(PxContactPairFlag::Enum, PxU16) + + +/** +\brief A contact point as used by contact notification +*/ +struct PxContactPairPoint +{ + /** + \brief The position of the contact point between the shapes, in world space. + */ + PxVec3 position; + + /** + \brief The separation of the shapes at the contact point. A negative separation denotes a penetration. + */ + PxReal separation; + + /** + \brief The normal of the contacting surfaces at the contact point. The normal direction points from the second shape to the first shape. + */ + PxVec3 normal; + + /** + \brief The surface index of shape 0 at the contact point. This is used to identify the surface material. + */ + PxU32 internalFaceIndex0; + + /** + \brief The impulse applied at the contact point, in world space. Divide by the simulation time step to get a force value. + */ + PxVec3 impulse; + + /** + \brief The surface index of shape 1 at the contact point. This is used to identify the surface material. + */ + PxU32 internalFaceIndex1; +}; + +/** +\brief A friction anchor as used by contact notification +*/ +struct PxContactPairFrictionAnchor +{ + /** + \brief The position of the friction anchor in world space. + */ + PxVec3 position; + + /** + \brief The impulse applied at the friction anchor, in world space. Divide by the simulation time step to get a force value. + */ + PxVec3 impulse; +}; + +/** +\brief Contact report pair information. + +Instances of this class are passed to PxSimulationEventCallback.onContact(). If contact reports have been requested for a pair of shapes (see #PxPairFlag), +then the corresponding contact information will be provided through this structure. + +\see PxSimulationEventCallback.onContact() +*/ +struct PxContactPair +{ + public: + PX_INLINE PxContactPair() {} + + /** + \brief The two shapes that make up the pair. + + \note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST + or #PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved shapes + gets deleted. Check the #flags member to see whether that is the case. Do not dereference a pointer to a + deleted shape. The pointer to a deleted shape is only provided such that user data structures which might + depend on the pointer value can be updated. + + \see PxShape + */ + PxShape* shapes[2]; + + /** + \brief Pointer to first patch header in contact stream containing contact patch data + + This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS). + Use #extractContacts() as a reference for the data layout of the stream. + */ + const PxU8* contactPatches; + + /** + \brief Pointer to first contact point in contact stream containing contact data + + This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS). + Use #extractContacts() as a reference for the data layout of the stream. + */ + const PxU8* contactPoints; + + /** + \brief Buffer containing applied impulse data. + + This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS). + Use #extractContacts() as a reference for the data layout of the stream. + */ + const PxReal* contactImpulses; + + /** + \brief Buffer containing contact patches friction information. + */ + const PxU8* frictionPatches; + + /** + \brief Size of the contact stream [bytes] including force buffer + */ + PxU32 requiredBufferSize; + + /** + \brief Number of contact points stored in the contact stream + */ + PxU8 contactCount; + + /** + \brief Number of contact patches stored in the contact stream + */ + PxU8 patchCount; + + /** + \brief Size of the contact stream [bytes] not including force buffer + */ + PxU16 contactStreamSize; + + /** + \brief Additional information on the contact report pair. + + \see PxContactPairFlag + */ + PxContactPairFlags flags; + + /** + \brief Flags raised due to the contact. + + The events field is a combination of: + +
    +
  • PxPairFlag::eNOTIFY_TOUCH_FOUND,
  • +
  • PxPairFlag::eNOTIFY_TOUCH_PERSISTS,
  • +
  • PxPairFlag::eNOTIFY_TOUCH_LOST,
  • +
  • PxPairFlag::eNOTIFY_TOUCH_CCD,
  • +
  • PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND,
  • +
  • PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS,
  • +
  • PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST
  • +
+ + See the documentation of #PxPairFlag for an explanation of each. + + \note eNOTIFY_TOUCH_CCD can get raised even if the pair did not request this event. However, in such a case it will only get + raised in combination with one of the other flags to point out that the other event occured during a CCD pass. + + \see PxPairFlag + */ + PxPairFlags events; + + PxU32 internalData[2]; // For internal use only + + /** + \brief Extracts the contact points from the stream and stores them in a convenient format. + + \param[out] userBuffer Array of PxContactPairPoint structures to extract the contact points to. The number of contacts for a pair is defined by #contactCount + \param[in] bufferSize Number of PxContactPairPoint structures the provided buffer can store. + \return Number of contact points written to the buffer. + + \see PxContactPairPoint + */ + PX_INLINE PxU32 extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const; + + /** + \brief Extracts the friction anchors from the stream and stores them in a convenient format. + + \param[out] userBuffer Array of PxContactPairFrictionAnchor structures to extract the friction anchors to. + \param[in] bufferSize Number of PxContactPairFrictionAnchor structures the provided buffer can store. + \return Number of friction anchors written to the buffer. + + \see PxContactPairFrictionAnchor + */ + PX_INLINE PxU32 extractFrictionAnchors(PxContactPairFrictionAnchor* userBuffer, PxU32 bufferSize) const; + + /** + \brief Helper method to clone the contact pair and copy the contact data stream into a user buffer. + + The contact data stream is only accessible during the contact report callback. This helper function provides copy functionality + to buffer the contact stream information such that it can get accessed at a later stage. + + \param[out] newPair The contact pair info will get copied to this instance. The contact data stream pointer of the copy will be redirected to the provided user buffer. Use NULL to skip the contact pair copy operation. + \param[out] bufferMemory Memory block to store the contact data stream to. At most #requiredBufferSize bytes will get written to the buffer. + */ + PX_INLINE void bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const; + + PX_INLINE const PxU32* getInternalFaceIndices() const; +}; + + +PX_INLINE PxU32 PxContactPair::extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const +{ + PxU32 nbContacts = 0; + + if(contactCount && bufferSize) + { + PxContactStreamIterator iter(contactPatches, contactPoints, getInternalFaceIndices(), patchCount, contactCount); + + const PxReal* impulses = contactImpulses; + + const PxU32 flippedContacts = (flags & PxContactPairFlag::eINTERNAL_CONTACTS_ARE_FLIPPED); + const PxU32 hasImpulses = (flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES); + + while(iter.hasNextPatch()) + { + iter.nextPatch(); + while(iter.hasNextContact()) + { + iter.nextContact(); + PxContactPairPoint& dst = userBuffer[nbContacts]; + dst.position = iter.getContactPoint(); + dst.separation = iter.getSeparation(); + dst.normal = iter.getContactNormal(); + if(!flippedContacts) + { + dst.internalFaceIndex0 = iter.getFaceIndex0(); + dst.internalFaceIndex1 = iter.getFaceIndex1(); + } + else + { + dst.internalFaceIndex0 = iter.getFaceIndex1(); + dst.internalFaceIndex1 = iter.getFaceIndex0(); + } + + if(hasImpulses) + { + const PxReal impulse = impulses[nbContacts]; + dst.impulse = dst.normal * impulse; + } + else + dst.impulse = PxVec3(0.0f); + ++nbContacts; + if(nbContacts == bufferSize) + return nbContacts; + } + } + } + + return nbContacts; +} + +PX_INLINE PxU32 PxContactPair::extractFrictionAnchors(PxContactPairFrictionAnchor* userBuffer, PxU32 bufferSize) const +{ + PxU32 nbAnchors = 0; + + if(bufferSize) + { + PxFrictionAnchorStreamIterator iter(contactPatches, frictionPatches, patchCount); + + while(iter.hasNextPatch()) + { + iter.nextPatch(); + while(iter.hasNextFrictionAnchor()) + { + iter.nextFrictionAnchor(); + PxContactPairFrictionAnchor& dst = userBuffer[nbAnchors]; + + dst.position = iter.getPosition(); + dst.impulse = iter.getImpulse(); + + ++nbAnchors; + if(nbAnchors == bufferSize) + return nbAnchors; + } + } + } + + return nbAnchors; +} + + +PX_INLINE void PxContactPair::bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const +{ + PxU8* patches = bufferMemory; + PxU8* contacts = NULL; + if(patches) + { + contacts = bufferMemory + patchCount * sizeof(PxContactPatch); + PxMemCopy(patches, contactPatches, sizeof(PxContactPatch)*patchCount); + PxMemCopy(contacts, contactPoints, contactStreamSize - (sizeof(PxContactPatch)*patchCount)); + } + + if(contactImpulses) + { + PxMemCopy(bufferMemory + ((contactStreamSize + 15) & (~15)), contactImpulses, sizeof(PxReal) * contactCount); + } + + if (newPair) + { + *newPair = *this; + newPair->contactPatches = patches; + newPair->contactPoints = contacts; + } +} + + +PX_INLINE const PxU32* PxContactPair::getInternalFaceIndices() const +{ + return reinterpret_cast(contactImpulses + contactCount); +} + +/** +\brief Collection of flags providing information on trigger report pairs. + +\see PxTriggerPair +*/ +struct PxTriggerPairFlag +{ + enum Enum + { + eREMOVED_SHAPE_TRIGGER = (1<<0), //!< The trigger shape has been removed from the actor/scene. + eREMOVED_SHAPE_OTHER = (1<<1), //!< The shape causing the trigger event has been removed from the actor/scene. + eNEXT_FREE = (1<<2) //!< For internal use only. + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxTriggerPairFlag. + +\see PxTriggerPairFlag +*/ +typedef PxFlags PxTriggerPairFlags; +PX_FLAGS_OPERATORS(PxTriggerPairFlag::Enum, PxU8) + + +/** +\brief Descriptor for a trigger pair. + +An array of these structs gets passed to the PxSimulationEventCallback::onTrigger() report. + +\note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST + events were requested for the pair and one of the involved shapes gets deleted. Check the #flags member to see + whether that is the case. Do not dereference a pointer to a deleted shape. The pointer to a deleted shape is + only provided such that user data structures which might depend on the pointer value can be updated. + +\see PxSimulationEventCallback.onTrigger() +*/ +struct PxTriggerPair +{ + PX_INLINE PxTriggerPair() {} + + PxShape* triggerShape; //!< The shape that has been marked as a trigger. + PxActor* triggerActor; //!< The actor to which triggerShape is attached + PxShape* otherShape; //!< The shape causing the trigger event. \deprecated (see #PxSimulationEventCallback::onTrigger()) If collision between trigger shapes is enabled, then this member might point to a trigger shape as well. + PxActor* otherActor; //!< The actor to which otherShape is attached + PxPairFlag::Enum status; //!< Type of trigger event (eNOTIFY_TOUCH_FOUND or eNOTIFY_TOUCH_LOST). eNOTIFY_TOUCH_PERSISTS events are not supported. + PxTriggerPairFlags flags; //!< Additional information on the pair (see #PxTriggerPairFlag) +}; + + +/** +\brief Descriptor for a broken constraint. + +An array of these structs gets passed to the PxSimulationEventCallback::onConstraintBreak() report. + +\see PxConstraint PxSimulationEventCallback.onConstraintBreak() +*/ +struct PxConstraintInfo +{ + PX_INLINE PxConstraintInfo() {} + PX_INLINE PxConstraintInfo(PxConstraint* c, void* extRef, PxU32 t) : constraint(c), externalReference(extRef), type(t) {} + + PxConstraint* constraint; //!< The broken constraint. + void* externalReference; //!< The external object which owns the constraint (see #PxConstraintConnector::getExternalReference()) + PxU32 type; //!< Unique type ID of the external object. Allows to cast the provided external reference to the appropriate type +}; + + +/** +\brief An interface class that the user can implement in order to receive simulation events. + +With the exception of onAdvance(), the events get sent during the call to either #PxScene::fetchResults() or +#PxScene::flushSimulation() with sendPendingReports=true. onAdvance() gets called while the simulation +is running (that is between PxScene::simulate() or PxScene::advance() and PxScene::fetchResults()). + +\note SDK state should not be modified from within the callbacks. In particular objects should not +be created or destroyed. If state modification is needed then the changes should be stored to a buffer +and performed after the simulation step. + +Threading: With the exception of onAdvance(), it is not necessary to make these callbacks thread safe as +they will only be called in the context of the user thread. + +\see PxScene.setSimulationEventCallback() PxScene.getSimulationEventCallback() +*/ +class PxSimulationEventCallback + { + public: + /** + \brief This is called when a breakable constraint breaks. + + \note The user should not release the constraint shader inside this call! + + \note No event will get reported if the constraint breaks but gets deleted while the time step is still being simulated. + + \param[in] constraints - The constraints which have been broken. + \param[in] count - The number of constraints + + \see PxConstraint PxConstraintDesc.linearBreakForce PxConstraintDesc.angularBreakForce + */ + virtual void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) = 0; + + /** + \brief This is called with the actors which have just been woken up. + + \note Only supported by rigid bodies yet. + \note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set. + \note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame + will get reported. For example, let us assume actor A is awake, then A->putToSleep() gets called, then later A->wakeUp() gets called. + At the next simulate/fetchResults() step only an onWake() event will get triggered because that was the last transition. + \note If an actor gets newly added to a scene with properties such that it is awake and the sleep state does not get changed by + the user or simulation, then an onWake() event will get sent at the next simulate/fetchResults() step. + + \param[in] actors - The actors which just woke up. + \param[in] count - The number of actors + + \see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag() + */ + virtual void onWake(PxActor** actors, PxU32 count) = 0; + + /** + \brief This is called with the actors which have just been put to sleep. + + \note Only supported by rigid bodies yet. + \note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set. + \note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame + will get reported. For example, let us assume actor A is asleep, then A->wakeUp() gets called, then later A->putToSleep() gets called. + At the next simulate/fetchResults() step only an onSleep() event will get triggered because that was the last transition (assuming the simulation + does not wake the actor up). + \note If an actor gets newly added to a scene with properties such that it is asleep and the sleep state does not get changed by + the user or simulation, then an onSleep() event will get sent at the next simulate/fetchResults() step. + + \param[in] actors - The actors which have just been put to sleep. + \param[in] count - The number of actors + + \see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag() + */ + virtual void onSleep(PxActor** actors, PxU32 count) = 0; + + /** + \brief This is called when certain contact events occur. + + The method will be called for a pair of actors if one of the colliding shape pairs requested contact notification. + You request which events are reported using the filter shader/callback mechanism (see #PxSimulationFilterShader, + #PxSimulationFilterCallback, #PxPairFlag). + + Do not keep references to the passed objects, as they will be + invalid after this function returns. + + \param[in] pairHeader Information on the two actors whose shapes triggered a contact report. + \param[in] pairs The contact pairs of two actors for which contact reports have been requested. See #PxContactPair. + \param[in] nbPairs The number of provided contact pairs. + + \see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxContactPair PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback + */ + virtual void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) = 0; + + /** + \brief This is called with the current trigger pair events. + + Shapes which have been marked as triggers using PxShapeFlag::eTRIGGER_SHAPE will send events + according to the pair flag specification in the filter shader (see #PxPairFlag, #PxSimulationFilterShader). + + \note Trigger shapes will no longer send notification events for interactions with other trigger shapes. + + \param[in] pairs - The trigger pair events. + \param[in] count - The number of trigger pair events. + + \see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxPairFlag PxSimulationFilterShader PxShapeFlag PxShape.setFlag() + */ + virtual void onTrigger(PxTriggerPair* pairs, PxU32 count) = 0; + + /** + \brief Provides early access to the new pose of moving rigid bodies. + + When this call occurs, rigid bodies having the #PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW + flag set, were moved by the simulation and their new poses can be accessed through the provided buffers. + + \note The provided buffers are valid and can be read until the next call to #PxScene::simulate() or #PxScene::collide(). + + \note This callback gets triggered while the simulation is running. If the provided rigid body references are used to + read properties of the object, then the callback has to guarantee no other thread is writing to the same body at the same + time. + + \note The code in this callback should be lightweight as it can block the simulation, that is, the + #PxScene::fetchResults() call. + + \param[in] bodyBuffer The rigid bodies that moved and requested early pose reporting. + \param[in] poseBuffer The integrated rigid body poses of the bodies listed in bodyBuffer. + \param[in] count The number of entries in the provided buffers. + + \see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW + */ + virtual void onAdvance(const PxRigidBody*const* bodyBuffer, const PxTransform* poseBuffer, const PxU32 count) = 0; + + virtual ~PxSimulationEventCallback() {} + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSimulationStatistics.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSimulationStatistics.h new file mode 100644 index 000000000..6f39ca2a6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSimulationStatistics.h @@ -0,0 +1,499 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SIMULATION_STATISTICS_H +#define PX_SIMULATION_STATISTICS_H + +#include "foundation/PxAssert.h" +#include "PxPhysXConfig.h" +#include "foundation/PxSimpleTypes.h" +#include "geometry/PxGeometry.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Structure used to retrieve actual sizes/counts for the configuration parameters provided in PxGpuDynamicsMemoryConfig. + +\note All the values in this structure are reported as the maximum over the lifetime of a PxScene. + +\see PxScene::getSimulationStatistics(), PxSimulationStatistics, PxSceneDesc::PxGpuDynamicsMemoryConfig +*/ +struct PxGpuDynamicsMemoryConfigStatistics +{ + PxU64 tempBufferCapacity; //!< actual size needed (bytes) for PxGpuDynamicsMemoryConfig::tempBufferCapacity. + PxU32 rigidContactCount; //!< actual number of rigid contacts needed - see PxGpuDynamicsMemoryConfig::maxRigidContactCount. + PxU32 rigidPatchCount; //!< actual number of rigid contact patches needed - see PxGpuDynamicsMemoryConfig::maxRigidPatchCount. + PxU32 foundLostPairs; //!< actual number of lost/found pairs needed - see PxGpuDynamicsMemoryConfig::foundLostPairsCapacity. + PxU32 foundLostAggregatePairs; //!< actual number of lost/found aggregate pairs needed - see PxGpuDynamicsMemoryConfig::foundLostAggregatePairsCapacity. + PxU32 totalAggregatePairs; //!< actual number of aggregate pairs needed - see PxGpuDynamicsMemoryConfig::totalAggregatePairsCapacity. + PxU32 deformableSurfaceContacts; //!< actual number of deformable surface contacts needed - see PxGpuDynamicsMemoryConfig::maxDeformableSurfaceContacts. + PxU32 deformableVolumeContacts; //!< actual number of deformable volume contact needed - see PxGpuDynamicsMemoryConfig::maxDeformableVolumeContacts. + PxU32 softbodyContacts; //!< deprecated, use deformableVolumeContacts. + PxU32 particleContacts; //!< actual number of particle contacts needed - see PxGpuDynamicsMemoryConfig::maxParticleContacts. + PxU32 collisionStackSize; //!< actual size (bytes) needed for the collision stack - see PxGpuDynamicsMemoryConfig::collisionStackSize. + + PxGpuDynamicsMemoryConfigStatistics() : + tempBufferCapacity (0), + rigidContactCount (0), + rigidPatchCount (0), + foundLostPairs (0), + foundLostAggregatePairs (0), + totalAggregatePairs (0), + deformableSurfaceContacts (0), + deformableVolumeContacts (0), + softbodyContacts (0), // deprecated + particleContacts (0), + collisionStackSize (0) + { } +}; + +/** +\brief Class used to retrieve statistics for a simulation step. + +\see PxScene::getSimulationStatistics() +*/ +class PxSimulationStatistics +{ +public: + + /** + \brief Different types of rigid body collision pair statistics. + \see getRbPairStats + */ + enum RbPairStatsType + { + /** + \brief Shape pairs processed as discrete contact pairs for the current simulation step. + */ + eDISCRETE_CONTACT_PAIRS, + + /** + \brief Shape pairs processed as swept integration pairs for the current simulation step. + + \note Counts the pairs for which special CCD (continuous collision detection) work was actually done and NOT the number of pairs which were configured for CCD. + Furthermore, there can be multiple CCD passes and all processed pairs of all passes are summed up, hence the number can be larger than the amount of pairs which have been configured for CCD. + + \see PxPairFlag::eDETECT_CCD_CONTACT, + */ + eCCD_PAIRS, + + /** + \brief Shape pairs processed with user contact modification enabled for the current simulation step. + + \see PxContactModifyCallback + */ + eMODIFIED_CONTACT_PAIRS, + + /** + \brief Trigger shape pairs processed for the current simulation step. + + \see PxShapeFlag::eTRIGGER_SHAPE + */ + eTRIGGER_PAIRS + }; + + +//objects: + /** + \brief Number of active PxConstraint objects (joints etc.) for the current simulation step. + */ + PxU32 nbActiveConstraints; + + /** + \brief Number of active dynamic bodies for the current simulation step. + + \note Does not include active kinematic bodies + */ + PxU32 nbActiveDynamicBodies; + + /** + \brief Number of active kinematic bodies for the current simulation step. + + \note Kinematic deactivation occurs at the end of the frame after the last call to PxRigidDynamic::setKinematicTarget() was called so kinematics that are + deactivated in a given frame will be included by this counter. + */ + PxU32 nbActiveKinematicBodies; + + /** + \brief Number of static bodies for the current simulation step. + */ + PxU32 nbStaticBodies; + + /** + \brief Number of dynamic bodies for the current simulation step. + + \note Includes inactive bodies and articulation links + \note Does not include kinematic bodies + */ + PxU32 nbDynamicBodies; + + /** + \brief Number of kinematic bodies for the current simulation step. + + \note Includes inactive bodies + */ + PxU32 nbKinematicBodies; + + /** + \brief Number of shapes of each geometry type. + */ + + PxU32 nbShapes[PxGeometryType::eGEOMETRY_COUNT]; + + /** + \brief Number of aggregates in the scene. + */ + PxU32 nbAggregates; + + /** + \brief Number of articulations in the scene. + */ + PxU32 nbArticulations; + +//solver: + /** + \brief The number of 1D axis constraints(joints+contact) present in the current simulation step. + */ + PxU32 nbAxisSolverConstraints; + + /** + \brief The size (in bytes) of the compressed contact stream in the current simulation step + */ + PxU32 compressedContactSize; + + /** + \brief The total required size (in bytes) of the contact constraints in the current simulation step + */ + PxU32 requiredContactConstraintMemory; + + /** + \brief The peak amount of memory (in bytes) that was allocated for constraints (this includes joints) in the current simulation step + */ + PxU32 peakConstraintMemory; + +//broadphase: + /** + \brief Get number of broadphase volumes added for the current simulation step. + + \return Number of broadphase volumes added. + */ + PX_FORCE_INLINE PxU32 getNbBroadPhaseAdds() const + { + return nbBroadPhaseAdds; + } + + /** + \brief Get number of broadphase volumes removed for the current simulation step. + + \return Number of broadphase volumes removed. + */ + PX_FORCE_INLINE PxU32 getNbBroadPhaseRemoves() const + { + return nbBroadPhaseRemoves; + } + +//collisions: + /** + \brief Get number of shape collision pairs of a certain type processed for the current simulation step. + + There is an entry for each geometry pair type. + + \note entry[i][j] = entry[j][i], hence, if you want the sum of all pair + types, you need to discard the symmetric entries + + \param[in] pairType The type of pair for which to get information + \param[in] g0 The geometry type of one pair object + \param[in] g1 The geometry type of the other pair object + \return Number of processed pairs of the specified geometry types. + */ + PxU32 getRbPairStats(RbPairStatsType pairType, PxGeometryType::Enum g0, PxGeometryType::Enum g1) const + { + PX_ASSERT_WITH_MESSAGE( (pairType >= eDISCRETE_CONTACT_PAIRS) && + (pairType <= eTRIGGER_PAIRS), + "Invalid pairType in PxSimulationStatistics::getRbPairStats"); + + if (g0 >= PxGeometryType::eGEOMETRY_COUNT || g1 >= PxGeometryType::eGEOMETRY_COUNT) + { + PX_ASSERT(false); + return 0; + } + + PxU32 nbPairs = 0; + switch(pairType) + { + case eDISCRETE_CONTACT_PAIRS: + nbPairs = nbDiscreteContactPairs[g0][g1]; + break; + case eCCD_PAIRS: + nbPairs = nbCCDPairs[g0][g1]; + break; + case eMODIFIED_CONTACT_PAIRS: + nbPairs = nbModifiedContactPairs[g0][g1]; + break; + case eTRIGGER_PAIRS: + nbPairs = nbTriggerPairs[g0][g1]; + break; + } + return nbPairs; + } + + /** + \brief Total number of (non CCD) pairs reaching narrow phase + */ + PxU32 nbDiscreteContactPairsTotal; + + /** + \brief Total number of (non CCD) pairs for which contacts are successfully cached (<=nbDiscreteContactPairsTotal) + \note This includes pairs for which no contacts are generated, it still counts as a cache hit. + */ + PxU32 nbDiscreteContactPairsWithCacheHits; + + /** + \brief Total number of (non CCD) pairs for which at least 1 contact was generated (<=nbDiscreteContactPairsTotal) + */ + PxU32 nbDiscreteContactPairsWithContacts; + + /** + \brief Number of new pairs found by BP this frame + */ + PxU32 nbNewPairs; + + /** + \brief Number of lost pairs from BP this frame + */ + PxU32 nbLostPairs; + + /** + \brief Number of new touches found by NP this frame + */ + PxU32 nbNewTouches; + + /** + \brief Number of lost touches from NP this frame + */ + PxU32 nbLostTouches; + + /** + \brief Number of partitions used by the solver this frame + */ + PxU32 nbPartitions; + + /** + \brief GPU device memory in bytes allocated for particle state accessible through API + */ + PxU64 gpuMemParticles; + + /** + \brief GPU device memory in bytes allocated for deformable surface state accessible through API + */ + PxU64 gpuMemDeformableSurfaces; + + /** + \brief GPU device memory in bytes allocated for deformable volume state accessible through API + */ + PxU64 gpuMemDeformableVolumes; + + /** + \brief Deprecated + \see gpuMemDeformableVolumes + */ + PX_DEPRECATED PxU64 gpuMemSoftBodies; + + /** + \brief GPU device memory in bytes allocated for internal heap allocation + */ + PxU64 gpuMemHeap; + + /** + \brief GPU device heap memory used for broad phase in bytes + */ + PxU64 gpuMemHeapBroadPhase; + + /** + \brief GPU device heap memory used for narrow phase in bytes + */ + PxU64 gpuMemHeapNarrowPhase; + + /** + \brief GPU device heap memory used for solver in bytes + */ + PxU64 gpuMemHeapSolver; + + /** + \brief GPU device heap memory used for articulations in bytes + */ + PxU64 gpuMemHeapArticulation; + + /** + \brief GPU device heap memory used for simulation pipeline in bytes + */ + PxU64 gpuMemHeapSimulation; + + /** + \brief GPU device heap memory used for articulations in the simulation pipeline in bytes + */ + PxU64 gpuMemHeapSimulationArticulation; + + /** + \brief GPU device heap memory used for particles in the simulation pipeline in bytes + */ + PxU64 gpuMemHeapSimulationParticles; + + /** + \brief GPU device heap memory used for deformable surfaces in the simulation pipeline in bytes + */ + PxU64 gpuMemHeapSimulationDeformableSurface; + + /** + \brief GPU device heap memory used for deformable volumes in the simulation pipeline in bytes + */ + PxU64 gpuMemHeapSimulationDeformableVolume; + + /** + \brief Deprecated + \see gpuMemHeapSimulationDeformableVolume + */ + PX_DEPRECATED PxU64 gpuMemHeapSimulationSoftBody; + + /** + \brief GPU device heap memory used for shared buffers in the particles pipeline in bytes + */ + PxU64 gpuMemHeapParticles; + + /** + \brief GPU device heap memory used for shared buffers in the deformable surface pipeline in bytes + */ + PxU64 gpuMemHeapDeformableSurfaces; + + /** + \brief GPU device heap memory used for shared buffers in the deformable volume pipeline in bytes + */ + PxU64 gpuMemHeapDeformableVolumes; + + /** + \brief Deprecated + \see gpuMemHeapDeformableVolumes + */ + PX_DEPRECATED PxU64 gpuMemHeapSoftBodies; + + /** + \brief GPU device heap memory not covered by other stats in bytes + */ + PxU64 gpuMemHeapOther; + + /** + \brief Structure containing statistics about actual count/sizes used for the configuration parameters in PxGpuDynamicsMemoryConfig + */ + PxGpuDynamicsMemoryConfigStatistics gpuDynamicsMemoryConfigStatistics; + + + PxSimulationStatistics() : + nbActiveConstraints (0), + nbActiveDynamicBodies (0), + nbActiveKinematicBodies (0), + nbStaticBodies (0), + nbDynamicBodies (0), + nbKinematicBodies (0), + nbAggregates (0), + nbArticulations (0), + nbAxisSolverConstraints (0), + compressedContactSize (0), + requiredContactConstraintMemory (0), + peakConstraintMemory (0), + nbDiscreteContactPairsTotal (0), + nbDiscreteContactPairsWithCacheHits (0), + nbDiscreteContactPairsWithContacts (0), + nbNewPairs (0), + nbLostPairs (0), + nbNewTouches (0), + nbLostTouches (0), + nbPartitions (0), + gpuMemParticles (0), + gpuMemDeformableSurfaces (0), + gpuMemDeformableVolumes (0), + gpuMemSoftBodies (0), // deprecated + gpuMemHeap (0), + gpuMemHeapBroadPhase (0), + gpuMemHeapNarrowPhase (0), + gpuMemHeapSolver (0), + gpuMemHeapArticulation (0), + gpuMemHeapSimulation (0), + gpuMemHeapSimulationArticulation (0), + gpuMemHeapSimulationParticles (0), + gpuMemHeapSimulationDeformableSurface (0), + gpuMemHeapSimulationDeformableVolume (0), + gpuMemHeapSimulationSoftBody (0), // deprecated + gpuMemHeapParticles (0), + gpuMemHeapDeformableSurfaces (0), + gpuMemHeapDeformableVolumes (0), + gpuMemHeapSoftBodies (0), // deprecated + gpuMemHeapOther (0) + { + nbBroadPhaseAdds = 0; + nbBroadPhaseRemoves = 0; + + for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++) + { + for(PxU32 j=0; j < PxGeometryType::eGEOMETRY_COUNT; j++) + { + nbDiscreteContactPairs[i][j] = 0; + nbModifiedContactPairs[i][j] = 0; + nbCCDPairs[i][j] = 0; + nbTriggerPairs[i][j] = 0; + } + } + + for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++) + { + nbShapes[i] = 0; + } + } + + + // + // We advise to not access these members directly. Use the provided accessor methods instead. + // +//broadphase: + PxU32 nbBroadPhaseAdds; + PxU32 nbBroadPhaseRemoves; + +//collisions: + PxU32 nbDiscreteContactPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT]; + PxU32 nbCCDPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT]; + PxU32 nbModifiedContactPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT]; + PxU32 nbTriggerPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT]; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSmoothing.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSmoothing.h new file mode 100644 index 000000000..9f1acf064 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSmoothing.h @@ -0,0 +1,186 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SMOOTHING_H +#define PX_SMOOTHING_H + + +#include "cudamanager/PxCudaContext.h" +#include "cudamanager/PxCudaContextManager.h" + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" +#include "PxParticleSystem.h" + +#include "foundation/PxArray.h" +#include "PxParticleGpu.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_SUPPORT_GPU_PHYSX + + class PxgKernelLauncher; + class PxParticleNeighborhoodProvider; + + /** + \brief Ccomputes smoothed positions for a particle system to improve rendering quality + */ + class PxSmoothedPositionGenerator + { + public: + /** + \brief Schedules the compuation of smoothed positions on the specified cuda stream + + \param[in] gpuParticleSystem A gpu pointer to access particle system data + \param[in] numParticles The number of particles + \param[in] stream The stream on which the cuda call gets scheduled + */ + virtual void generateSmoothedPositions(PxGpuParticleSystem* gpuParticleSystem, PxU32 numParticles, CUstream stream) = 0; + + /** + \brief Schedules the compuation of smoothed positions on the specified cuda stream + + \param[in] particlePositionsGpu A gpu pointer containing the particle positions + \param[in] neighborhoodProvider A neighborhood provider object that supports fast neighborhood queries + \param[in] numParticles The number of particles + \param[in] particleContactOffset The particle contact offset + \param[in] stream The stream on which the cuda call gets scheduled + */ + virtual void generateSmoothedPositions(PxVec4* particlePositionsGpu, PxParticleNeighborhoodProvider& neighborhoodProvider, PxU32 numParticles, PxReal particleContactOffset, CUstream stream) = 0; + + /** + \brief Set a host buffer that holds the smoothed position data after the timestep completed + + \param[in] smoothedPositions A host buffer with memory for all particles already allocated + */ + virtual void setResultBufferHost(PxVec4* smoothedPositions) = 0; + + /** + \brief Set a device buffer that holds the smoothed position data after the timestep completed + + \param[in] smoothedPositions A device buffer with memory for all particles already allocated + */ + virtual void setResultBufferDevice(PxVec4* smoothedPositions) = 0; + + /** + \brief Sets the intensity of the position smoothing effect + + \param[in] smoothingStrenght The strength of the smoothing effect + */ + virtual void setSmoothing(float smoothingStrenght) = 0; + + /** + \brief Gets the maximal number of particles + + \return The maximal number of particles + */ + virtual PxU32 getMaxParticles() const = 0; + + /** + \brief Sets the maximal number of particles + + \param[in] maxParticles The maximal number of particles + */ + virtual void setMaxParticles(PxU32 maxParticles) = 0; + + /** + \brief Gets the device pointer for the smoothed positions. Only available after calling setResultBufferHost or setResultBufferDevice + + \return The device pointer for the smoothed positions + */ + virtual PxVec4* getSmoothedPositionsDevicePointer() const = 0; + + /** + \brief Enables or disables the smoothed position generator + + \param[in] enabled The boolean to set the generator to enabled or disabled + */ + virtual void setEnabled(bool enabled) = 0; + + /** + \brief Allows to query if the smoothed position generator is enabled + + \return True if enabled, false otherwise + */ + virtual bool isEnabled() const = 0; + + /** + \brief Releases the instance and its data + */ + virtual void release() = 0; + + /** + \brief Destructor + */ + virtual ~PxSmoothedPositionGenerator() {} + }; + + /** + \brief Default implementation of a particle system callback to trigger smoothed position calculations. A call to fetchResultsParticleSystem() on the + PxScene will synchronize the work such that the caller knows that the post solve task completed. + */ + class PxSmoothedPositionCallback : public PxParticleSystemCallback + { + public: + /** + \brief Initializes the smoothing callback + + \param[in] smoothedPositionGenerator The smoothed position generator + */ + void initialize(PxSmoothedPositionGenerator* smoothedPositionGenerator) + { + mSmoothedPositionGenerator = smoothedPositionGenerator; + } + + virtual void onPostSolve(const PxGpuMirroredPointer& gpuParticleSystem, CUstream stream) + { + if (mSmoothedPositionGenerator) + { + mSmoothedPositionGenerator->generateSmoothedPositions(gpuParticleSystem.mDevicePtr, gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream); + } + } + + virtual void onBegin(const PxGpuMirroredPointer& /*gpuParticleSystem*/, CUstream /*stream*/) { } + + virtual void onAdvance(const PxGpuMirroredPointer& /*gpuParticleSystem*/, CUstream /*stream*/) { } + + private: + PxSmoothedPositionGenerator* mSmoothedPositionGenerator; + }; + +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSoftBody.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSoftBody.h new file mode 100644 index 000000000..ed71d7fad --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSoftBody.h @@ -0,0 +1,105 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SOFT_BODY_H +#define PX_SOFT_BODY_H + +#include "PxDeformableVolume.h" +#include "PxDeformableVolumeFlag.h" +#include "PxFEMParameter.h" +#include "PxSoftBodyFlag.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4435) +#endif + + + /** + \brief Deprecated + \see PX_MAX_NB_DEFORMABLE_VOLUME_TET + */ + #define PX_MAX_NB_SOFTBODY_TET PX_MAX_NB_DEFORMABLE_VOLUME_TET + + /** + \brief Deprecated + \see PX_MAX_NB_DEFORMABLE_VOLUME + */ + #define PX_MAX_NB_SOFTBODY PX_MAX_NB_DEFORMABLE_VOLUME + + /** + \brief Deprecated + \see PxDeformableVolumeFlag + */ + typedef PX_DEPRECATED PxDeformableVolumeFlag PxSoftBodyFlag; + + /** + \brief Deprecated + \see PxDeformableVolumeFlags + */ + typedef PX_DEPRECATED PxDeformableVolumeFlags PxSoftBodyFlags; + + /** + \brief Deprecated + \see PxDeformableVolume + */ + typedef PX_DEPRECATED PxDeformableVolume PxSoftBody; + + /** + \brief Deprecated + \see PxConfigureDeformableVolumeKinematicTarget + */ + PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureSoftBodyKinematicTarget(const PxVec4& target, bool isActive) + { + return PxConfigureDeformableVolumeKinematicTarget(target, isActive); + } + + /** + \brief Deprecated + \see PxConfigureDeformableVolumeKinematicTarget + */ + PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureSoftBodyKinematicTarget(const PxVec3& target, bool isActive) + { + return PxConfigureDeformableVolumeKinematicTarget(PxVec4(target, 0.0f), isActive); + } + +#if PX_VC +#pragma warning(pop) +#endif + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSoftBodyFlag.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSoftBodyFlag.h new file mode 100644 index 000000000..0bd96dda8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSoftBodyFlag.h @@ -0,0 +1,80 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SOFT_BODY_FLAG_H +#define PX_SOFT_BODY_FLAG_H + +#include "PxDeformableVolumeFlag.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Deprecated +\see PxDeformableVolumeDataFlag +*/ +typedef PX_DEPRECATED PxDeformableVolumeDataFlag PxSoftBodyDataFlag; + +/** +\brief Deprecated +\see PxDeformableVolumeDataFlags +*/ +typedef PX_DEPRECATED PxDeformableVolumeDataFlags PxSoftBodyDataFlags; + +/** +\brief These flags determine what data is read or written when using PxScene::copySoftBodyData() +or PxScene::applySoftBodyData. + +\see PxScene::copySoftBodyData, PxScene::applySoftBodyData + +\deprecated There is no direct replacement. The data is exposed in the PxSoftBody interface, accessible directly from GPU. +There is no replacement for eTET_REST_POSES, as the data is constant and can be derived from the input collision mesh. +*/ +PX_DEPRECATED class PxSoftBodyGpuDataFlag +{ +public: + enum Enum + { + eTET_INDICES = 0, //!< The collision mesh tetrahedron indices (quadruples of int32) + eTET_REST_POSES = 1, //!< The collision mesh tetrahedron rest poses (float 3x3 matrices) + eTET_ROTATIONS = 2, //!< The collision mesh tetrahedron orientations (quaternions, quadruples of float) + eTET_POSITION_INV_MASS = 3, //!< The collision mesh vertex positions and their inverted mass in the 4th component (quadruples of float) + eSIM_TET_INDICES = 4, //!< The simulation mesh tetrahedron indices (quadruples of int32) + eSIM_TET_ROTATIONS = 5, //!< The simulation mesh tetrahedron orientations (quaternions, quadruples of float) + eSIM_VELOCITY_INV_MASS = 6, //!< The simulation mesh vertex velocities and their inverted mass in the 4th component (quadruples of float) + eSIM_POSITION_INV_MASS = 7 //!< The simulation mesh vertex positions and their inverted mass in the 4th component (quadruples of float) + }; +}; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxSparseGridParams.h b/Jusin154_Team3D/Engine/Public/PhysX/PxSparseGridParams.h new file mode 100644 index 000000000..915978724 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxSparseGridParams.h @@ -0,0 +1,116 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SPARSE_GRID_PARAMS_H +#define PX_SPARSE_GRID_PARAMS_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxMath.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Parameters to define the sparse grid settings like grid spacing, maximal number of subgrids etc. + */ + struct PxSparseGridParams + { + /** + \brief Default constructor. + */ + PX_INLINE PxSparseGridParams() + { + maxNumSubgrids = 512; + subgridSizeX = 32; + subgridSizeY = 32; + subgridSizeZ = 32; + gridSpacing = 0.2f; + haloSize = 1; + } + + /** + \brief Copy constructor. + */ + PX_CUDA_CALLABLE PX_INLINE PxSparseGridParams(const PxSparseGridParams& params) + { + maxNumSubgrids = params.maxNumSubgrids; + subgridSizeX = params.subgridSizeX; + subgridSizeY = params.subgridSizeY; + subgridSizeZ = params.subgridSizeZ; + gridSpacing = params.gridSpacing; + haloSize = params.haloSize; + } + + PX_CUDA_CALLABLE PX_INLINE PxU32 getNumCellsPerSubgrid() const + { + return subgridSizeX * subgridSizeY * subgridSizeZ; + } + + PX_CUDA_CALLABLE PX_INLINE PxReal getSqrt3dx() const + { + return PxSqrt(3.0f) * gridSpacing; + } + + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + *this = PxSparseGridParams(); + } + + /** + \brief Assignment operator + */ + PX_INLINE void operator = (const PxSparseGridParams& params) + { + maxNumSubgrids = params.maxNumSubgrids; + subgridSizeX = params.subgridSizeX; + subgridSizeY = params.subgridSizeY; + subgridSizeZ = params.subgridSizeZ; + gridSpacing = params.gridSpacing; + haloSize = params.haloSize; + } + + PxU32 maxNumSubgrids; //!< Maximum number of subgrids + PxReal gridSpacing; //!< Grid spacing for the grid + PxU16 subgridSizeX; //!< Subgrid resolution in x dimension (must be an even number) + PxU16 subgridSizeY; //!< Subgrid resolution in y dimension (must be an even number) + PxU16 subgridSizeZ; //!< Subgrid resolution in z dimension (must be an even number) + PxU16 haloSize; //!< Number of halo cell layers around every subgrid cell. Only 0 and 1 are valid values + }; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/PxVisualizationParameter.h b/Jusin154_Team3D/Engine/Public/PhysX/PxVisualizationParameter.h new file mode 100644 index 000000000..92c863215 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/PxVisualizationParameter.h @@ -0,0 +1,271 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VISUALIZATION_PARAMETER_H +#define PX_VISUALIZATION_PARAMETER_H + +#include "foundation/PxPreprocessor.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/* +NOTE: Parameters should NOT be conditionally compiled out. Even if a particular feature is not available. +Otherwise the parameter values get shifted about and the numeric values change per platform. This causes problems +when trying to serialize parameters. + +New parameters should also be added to the end of the list for this reason. Also make sure to update +eNUM_VALUES, which should be one higher than the maximum value in the enum. +*/ + +/** +\brief Debug visualization parameters. + +#PxVisualizationParameter::eSCALE is the master switch for enabling visualization, please read the corresponding documentation +for further details. + +\see PxScene.setVisualizationParameter() PxScene.getVisualizationParameter() PxScene.getRenderBuffer() +*/ +struct PxVisualizationParameter +{ + enum Enum + { + /* RigidBody-related parameters */ + + /** + \brief This overall visualization scale gets multiplied with the individual scales. Setting to zero ignores all visualizations. Default is 0. + + The below settings permit the debug visualization of various simulation properties. + The setting is either zero, in which case the property is not drawn. Otherwise it is a scaling factor + that determines the size of the visualization widgets. + + Only objects for which visualization is turned on using setFlag(eVISUALIZATION) are visualized (see #PxActorFlag::eVISUALIZATION, #PxShapeFlag::eVISUALIZATION, ...). + Default is 0. + + Notes: + - to see any visualization, you have to set PxVisualizationParameter::eSCALE to nonzero first. + - the scale factor has been introduced because it's difficult (if not impossible) to come up with a + good scale for 3D vectors. Normals are normalized and their length is always 1. But it doesn't mean + we should render a line of length 1. Depending on your objects/scene, this might be completely invisible + or extremely huge. That's why the scale factor is here, to let you tune the length until it's ok in + your scene. + - however, things like collision shapes aren't ambiguous. They are clearly defined for example by the + triangles & polygons themselves, and there's no point in scaling that. So the visualization widgets + are only scaled when it makes sense. + + Range: [0, PX_MAX_F32)
+ Default: 0 + */ + eSCALE, + + /** + \brief Visualize the world axes. + */ + eWORLD_AXES, + + /* Body visualizations */ + + /** + \brief Visualize a bodies axes. + + \see PxActor.globalPose PxActor + */ + eBODY_AXES, + + /** + \brief Visualize a body's mass axes. + + This visualization is also useful for visualizing the sleep state of bodies. Sleeping bodies are drawn in + black, while awake bodies are drawn in white. If the body is sleeping and part of a sleeping group, it is + drawn in red. + + \see PxBodyDesc.massLocalPose PxActor + */ + eBODY_MASS_AXES, + + /** + \brief Visualize the bodies linear velocity. + + \see PxBodyDesc.linearVelocity PxActor + */ + eBODY_LIN_VELOCITY, + + /** + \brief Visualize the bodies angular velocity. + + \see PxBodyDesc.angularVelocity PxActor + */ + eBODY_ANG_VELOCITY, + + /* Contact visualisations */ + + /** + \brief Visualize contact points. Will enable contact information. + */ + eCONTACT_POINT, + + /** + \brief Visualize contact normals. Will enable contact information. + */ + eCONTACT_NORMAL, + + /** + \brief Visualize contact errors. Will enable contact information. + */ + eCONTACT_ERROR, + + /** + \brief Visualize Contact impulses. Will enable contact information. + */ + eCONTACT_IMPULSE, + + /** + \brief Visualize Contact forces. Will enable contact information. + \deprecated Use eCONTACT_IMPULSE instead. + */ + eCONTACT_FORCE PX_DEPRECATED = eCONTACT_IMPULSE, + + /** + \brief Visualize friction points. Will enable contact information. + */ + eFRICTION_POINT, + + /** + \brief Visualize friction normals. Will enable contact information. + */ + eFRICTION_NORMAL, + + /** + \brief Visualize friction impulses. Will enable contact information. + */ + eFRICTION_IMPULSE, + + /** + \brief Visualize actor axes. + + \see PxRigidStatic PxRigidDynamic PxArticulationLink + */ + eACTOR_AXES, + + /** + \brief Visualize bounds (AABBs in world space) + */ + eCOLLISION_AABBS, + + /** + \brief Shape visualization + + \see PxShape + */ + eCOLLISION_SHAPES, + + /** + \brief Shape axis visualization + + \see PxShape + */ + eCOLLISION_AXES, + + /** + \brief Compound visualization (compound AABBs in world space) + */ + eCOLLISION_COMPOUNDS, + + /** + \brief Mesh & convex face normals + + \see PxTriangleMesh PxConvexMesh + */ + eCOLLISION_FNORMALS, + + /** + \brief Active edges for meshes + + \see PxTriangleMesh + */ + eCOLLISION_EDGES, + + /** + \brief Static pruning structures + */ + eCOLLISION_STATIC, + + /** + \brief Dynamic pruning structures + */ + eCOLLISION_DYNAMIC, + + /** + \brief Joint local axes + */ + eJOINT_LOCAL_FRAMES, + + /** + \brief Joint limits + */ + eJOINT_LIMITS, + + /** + \brief Visualize culling box + */ + eCULL_BOX, + + /** + \brief MBP regions + */ + eMBP_REGIONS, + + /** + \brief Renders the simulation mesh instead of the collision mesh (only available for tetmeshes) + + Deformable visualization is currently not supported. + */ + eSIMULATION_MESH, + + /** + \brief Renders the SDF of a mesh instead of the collision mesh (only available for triangle meshes with SDFs) + */ + eSDF, + + /** + \brief This is not a parameter, it just records the current number of parameters (as maximum(PxVisualizationParameter)+1) for use in loops. + */ + eNUM_VALUES, + + eFORCE_DWORD = 0x7fffffff + }; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxBoxController.h b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxBoxController.h new file mode 100644 index 000000000..cb1cfdf1b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxBoxController.h @@ -0,0 +1,223 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BOX_CONTROLLER_H +#define PX_BOX_CONTROLLER_H + +#include "characterkinematic/PxController.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Descriptor for a box character controller. + +\see PxBoxController PxControllerDesc +*/ +class PxBoxControllerDesc : public PxControllerDesc +{ +public: + /** + \brief constructor sets to default. + */ + PX_INLINE PxBoxControllerDesc(); + PX_INLINE virtual ~PxBoxControllerDesc() {} + + /** + \brief copy constructor. + */ + PX_INLINE PxBoxControllerDesc(const PxBoxControllerDesc&); + + /** + \brief assignment operator. + */ + PX_INLINE PxBoxControllerDesc& operator=(const PxBoxControllerDesc&); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE virtual void setToDefault(); + + /** + \brief returns true if the current settings are valid + + \return True if the descriptor is valid. + */ + PX_INLINE virtual bool isValid() const; + + /** + \brief Half height + + Default: 1.0 + */ + PxF32 halfHeight; // Half-height in the "up" direction + + /** + \brief Half side extent + + Default: 0.5 + */ + PxF32 halfSideExtent; // Half-extent in the "side" direction + + /** + \brief Half forward extent + + Default: 0.5 + */ + PxF32 halfForwardExtent; // Half-extent in the "forward" direction + +protected: + PX_INLINE void copy(const PxBoxControllerDesc&); +}; + +PX_INLINE PxBoxControllerDesc::PxBoxControllerDesc() : + PxControllerDesc (PxControllerShapeType::eBOX), + halfHeight (1.0f), + halfSideExtent (0.5f), + halfForwardExtent (0.5f) +{ +} + +PX_INLINE PxBoxControllerDesc::PxBoxControllerDesc(const PxBoxControllerDesc& other) : PxControllerDesc(other) +{ + copy(other); +} + +PX_INLINE PxBoxControllerDesc& PxBoxControllerDesc::operator=(const PxBoxControllerDesc& other) +{ + PxControllerDesc::operator=(other); + copy(other); + return *this; +} + +PX_INLINE void PxBoxControllerDesc::copy(const PxBoxControllerDesc& other) +{ + halfHeight = other.halfHeight; + halfSideExtent = other.halfSideExtent; + halfForwardExtent = other.halfForwardExtent; +} + +PX_INLINE void PxBoxControllerDesc::setToDefault() +{ + *this = PxBoxControllerDesc(); +} + +PX_INLINE bool PxBoxControllerDesc::isValid() const +{ + if(!PxControllerDesc::isValid()) return false; + if(halfHeight<=0.0f) return false; + if(halfSideExtent<=0.0f) return false; + if(halfForwardExtent<=0.0f) return false; + if(stepOffset>2.0f*halfHeight) return false; // Prevents obvious mistakes + return true; +} + +/** +\brief Box character controller. + +\see PxBoxControllerDesc PxController +*/ +class PxBoxController : public PxController +{ +public: + + /** + \brief Gets controller's half height. + + \return The half height of the controller. + + \see PxBoxControllerDesc.halfHeight setHalfHeight() + */ + virtual PxF32 getHalfHeight() const = 0; + + /** + \brief Gets controller's half side extent. + + \return The half side extent of the controller. + + \see PxBoxControllerDesc.halfSideExtent setHalfSideExtent() + */ + virtual PxF32 getHalfSideExtent() const = 0; + + /** + \brief Gets controller's half forward extent. + + \return The half forward extent of the controller. + + \see PxBoxControllerDesc.halfForwardExtent setHalfForwardExtent() + */ + virtual PxF32 getHalfForwardExtent() const = 0; + + /** + \brief Sets controller's half height. + + \warning this doesn't check for collisions. + + \param[in] halfHeight The new half height for the controller. + \return Currently always true. + + \see PxBoxControllerDesc.halfHeight getHalfHeight() + */ + virtual bool setHalfHeight(PxF32 halfHeight) = 0; + + /** + \brief Sets controller's half side extent. + + \warning this doesn't check for collisions. + + \param[in] halfSideExtent The new half side extent for the controller. + \return Currently always true. + + \see PxBoxControllerDesc.halfSideExtent getHalfSideExtent() + */ + virtual bool setHalfSideExtent(PxF32 halfSideExtent) = 0; + + /** + \brief Sets controller's half forward extent. + + \warning this doesn't check for collisions. + + \param[in] halfForwardExtent The new half forward extent for the controller. + \return Currently always true. + + \see PxBoxControllerDesc.halfForwardExtent getHalfForwardExtent() + */ + virtual bool setHalfForwardExtent(PxF32 halfForwardExtent) = 0; + +protected: + PX_INLINE PxBoxController() {} + virtual ~PxBoxController() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxCapsuleController.h b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxCapsuleController.h new file mode 100644 index 000000000..d8e624ecb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxCapsuleController.h @@ -0,0 +1,244 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CAPSULE_CONTROLLER_H +#define PX_CAPSULE_CONTROLLER_H + +#include "characterkinematic/PxController.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxCapsuleClimbingMode +{ + enum Enum + { + eEASY, //!< Standard mode, let the capsule climb over surfaces according to impact normal + eCONSTRAINED, //!< Constrained mode, try to limit climbing according to the step offset + + eLAST + }; +}; + +/** +\brief A descriptor for a capsule character controller. + +\see PxCapsuleController PxControllerDesc +*/ +class PxCapsuleControllerDesc : public PxControllerDesc +{ +public: + /** + \brief constructor sets to default. + */ + PX_INLINE PxCapsuleControllerDesc (); + PX_INLINE virtual ~PxCapsuleControllerDesc () {} + + /** + \brief copy constructor. + */ + PX_INLINE PxCapsuleControllerDesc(const PxCapsuleControllerDesc&); + + /** + \brief assignment operator. + */ + PX_INLINE PxCapsuleControllerDesc& operator=(const PxCapsuleControllerDesc&); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE virtual void setToDefault(); + /** + \brief returns true if the current settings are valid + + \return True if the descriptor is valid. + */ + PX_INLINE virtual bool isValid() const; + + /** + \brief The radius of the capsule + + Default: 0.0 + + \see PxCapsuleController + */ + PxF32 radius; + + /** + \brief The height of the controller + + Default: 0.0 + + \see PxCapsuleController + */ + PxF32 height; + + /** + \brief The climbing mode + + Default: PxCapsuleClimbingMode::eEASY + + \see PxCapsuleController + */ + PxCapsuleClimbingMode::Enum climbingMode; + +protected: + PX_INLINE void copy(const PxCapsuleControllerDesc&); +}; + +PX_INLINE PxCapsuleControllerDesc::PxCapsuleControllerDesc () : PxControllerDesc(PxControllerShapeType::eCAPSULE) +{ + radius = height = 0.0f; + climbingMode = PxCapsuleClimbingMode::eEASY; +} + +PX_INLINE PxCapsuleControllerDesc::PxCapsuleControllerDesc(const PxCapsuleControllerDesc& other) : PxControllerDesc(other) +{ + copy(other); +} + +PX_INLINE PxCapsuleControllerDesc& PxCapsuleControllerDesc::operator=(const PxCapsuleControllerDesc& other) +{ + PxControllerDesc::operator=(other); + copy(other); + return *this; +} + +PX_INLINE void PxCapsuleControllerDesc::copy(const PxCapsuleControllerDesc& other) +{ + radius = other.radius; + height = other.height; + climbingMode = other.climbingMode; +} + +PX_INLINE void PxCapsuleControllerDesc::setToDefault() +{ + *this = PxCapsuleControllerDesc(); +} + +PX_INLINE bool PxCapsuleControllerDesc::isValid() const +{ + if(!PxControllerDesc::isValid()) return false; + if(radius<=0.0f) return false; + if(height<=0.0f) return false; + if(stepOffset>height+radius*2.0f) return false; // Prevents obvious mistakes + return true; +} +/** +\brief A capsule character controller. + +The capsule is defined as a position, a vertical height, and a radius. +The height is the distance between the two sphere centers at the end of the capsule. +In other words: + +p = pos (returned by controller)
+h = height
+r = radius
+ +p = center of capsule
+top sphere center = p.y + h*0.5
+bottom sphere center = p.y - h*0.5
+top capsule point = p.y + h*0.5 + r
+bottom capsule point = p.y - h*0.5 - r
+*/ +class PxCapsuleController : public PxController +{ +public: + + /** + \brief Gets controller's radius. + + \return The radius of the controller. + + \see PxCapsuleControllerDesc.radius setRadius() + */ + virtual PxF32 getRadius() const = 0; + + /** + \brief Sets controller's radius. + + \warning this doesn't check for collisions. + + \param[in] radius The new radius for the controller. + \return Currently always true. + + \see PxCapsuleControllerDesc.radius getRadius() + */ + virtual bool setRadius(PxF32 radius) = 0; + + /** + \brief Gets controller's height. + + \return The height of the capsule controller. + + \see PxCapsuleControllerDesc.height setHeight() + */ + virtual PxF32 getHeight() const = 0; + + /** + \brief Resets controller's height. + + \warning this doesn't check for collisions. + + \param[in] height The new height for the controller. + \return Currently always true. + + \see PxCapsuleControllerDesc.height getHeight() + */ + virtual bool setHeight(PxF32 height) = 0; + + /** + \brief Gets controller's climbing mode. + + \return The capsule controller's climbing mode. + + \see PxCapsuleControllerDesc.climbingMode setClimbingMode() + */ + virtual PxCapsuleClimbingMode::Enum getClimbingMode() const = 0; + + /** + \brief Sets controller's climbing mode. + + \param[in] mode The capsule controller's climbing mode. + + \see PxCapsuleControllerDesc.climbingMode getClimbingMode() + */ + virtual bool setClimbingMode(PxCapsuleClimbingMode::Enum mode) = 0; + +protected: + PX_INLINE PxCapsuleController() {} + virtual ~PxCapsuleController() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxController.h b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxController.h new file mode 100644 index 000000000..6eb2e45d4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxController.h @@ -0,0 +1,926 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTROLLER_H +#define PX_CONTROLLER_H + +#include "characterkinematic/PxExtended.h" +#include "characterkinematic/PxControllerObstacles.h" +#include "PxQueryFiltering.h" +#include "foundation/PxErrorCallback.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief The type of controller, eg box, sphere or capsule. +*/ +struct PxControllerShapeType +{ + enum Enum + { + /** + \brief A box controller. + + \see PxBoxController PxBoxControllerDesc + */ + eBOX, + + /** + \brief A capsule controller + + \see PxCapsuleController PxCapsuleControllerDesc + */ + eCAPSULE, + + eFORCE_DWORD = 0x7fffffff + }; +}; + +class PxShape; +class PxScene; +class PxController; +class PxRigidDynamic; +class PxMaterial; +struct PxFilterData; +class PxQueryFilterCallback; +class PxControllerBehaviorCallback; +class PxObstacleContext; +class PxObstacle; + +/** +\brief specifies how a CCT interacts with non-walkable parts. + +This is only used when slopeLimit is non zero. It is currently enabled for static actors only, and not supported for spheres or capsules. +*/ +struct PxControllerNonWalkableMode +{ + enum Enum + { + ePREVENT_CLIMBING, //!< Stops character from climbing up non-walkable slopes, but doesn't move it otherwise + ePREVENT_CLIMBING_AND_FORCE_SLIDING //!< Stops character from climbing up non-walkable slopes, and forces it to slide down those slopes + }; +}; + +/** +\brief specifies which sides a character is colliding with. +*/ +struct PxControllerCollisionFlag +{ + enum Enum + { + eCOLLISION_SIDES = (1<<0), //!< Character is colliding to the sides. + eCOLLISION_UP = (1<<1), //!< Character has collision above. + eCOLLISION_DOWN = (1<<2) //!< Character has collision below. + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxControllerCollisionFlag. + +\see PxControllerCollisionFlag +*/ +typedef PxFlags PxControllerCollisionFlags; +PX_FLAGS_OPERATORS(PxControllerCollisionFlag::Enum, PxU8) + +/** +\brief Describes a controller's internal state. +*/ +struct PxControllerState +{ + PxVec3 deltaXP; //!< delta position vector for the object the CCT is standing/riding on. Not always match the CCT delta when variable timesteps are used. + PxShape* touchedShape; //!< Shape on which the CCT is standing + PxRigidActor* touchedActor; //!< Actor owning 'touchedShape' + PxObstacleHandle touchedObstacleHandle; // Obstacle on which the CCT is standing + PxU32 collisionFlags; //!< Last known collision flags (PxControllerCollisionFlag) + bool standOnAnotherCCT; //!< Are we standing on another CCT? + bool standOnObstacle; //!< Are we standing on a user-defined obstacle? + bool isMovingUp; //!< is CCT moving up or not? (i.e. explicit jumping) +}; + +/** +\brief Describes a controller's internal statistics. +*/ +struct PxControllerStats +{ + PxU16 nbIterations; + PxU16 nbFullUpdates; + PxU16 nbPartialUpdates; + PxU16 nbTessellation; +}; + +/** +\brief Describes a generic CCT hit. +*/ +struct PxControllerHit +{ + PxController* controller; //!< Current controller + PxExtendedVec3 worldPos; //!< Contact position in world space + PxVec3 worldNormal; //!< Contact normal in world space + PxVec3 dir; //!< Motion direction + PxF32 length; //!< Motion length +}; + +/** +\brief Describes a hit between a CCT and a shape. Passed to onShapeHit() + +\see PxUserControllerHitReport.onShapeHit() +*/ +struct PxControllerShapeHit : public PxControllerHit +{ + PxShape* shape; //!< Touched shape + PxRigidActor* actor; //!< Touched actor + PxU32 triangleIndex; //!< touched triangle index (only for meshes/heightfields) +}; + +/** +\brief Describes a hit between a CCT and another CCT. Passed to onControllerHit(). + +\see PxUserControllerHitReport.onControllerHit() +*/ +struct PxControllersHit : public PxControllerHit +{ + PxController* other; //!< Touched controller +}; + +/** +\brief Describes a hit between a CCT and a user-defined obstacle. Passed to onObstacleHit(). + +\see PxUserControllerHitReport.onObstacleHit() PxObstacleContext +*/ +struct PxControllerObstacleHit : public PxControllerHit +{ + const void* userData; +}; + +/** +\brief User callback class for character controller events. + +\note Character controller hit reports are only generated when move is called. + +\see PxControllerDesc.callback +*/ +class PxUserControllerHitReport +{ +public: + + /** + \brief Called when current controller hits a shape. + + This is called when the CCT moves and hits a shape. This will not be called when a moving shape hits a non-moving CCT. + + \param[in] hit Provides information about the hit. + + \see PxControllerShapeHit + */ + virtual void onShapeHit(const PxControllerShapeHit& hit) = 0; + + /** + \brief Called when current controller hits another controller. + + \param[in] hit Provides information about the hit. + + \see PxControllersHit + */ + virtual void onControllerHit(const PxControllersHit& hit) = 0; + + /** + \brief Called when current controller hits a user-defined obstacle. + + \param[in] hit Provides information about the hit. + + \see PxControllerObstacleHit PxObstacleContext + */ + virtual void onObstacleHit(const PxControllerObstacleHit& hit) = 0; + +protected: + virtual ~PxUserControllerHitReport(){} +}; + + +/** +\brief Dedicated filtering callback for CCT vs CCT. + +This controls collisions between CCTs (one CCT vs anoter CCT). + +To make each CCT collide against all other CCTs, just return true - or simply avoid defining a callback. +To make each CCT freely go through all other CCTs, just return false. +Otherwise create a custom filtering logic in this callback. + +\see PxControllerFilters +*/ +class PxControllerFilterCallback +{ +public: + virtual ~PxControllerFilterCallback(){} + + /** + \brief Filtering method for CCT-vs-CCT. + + \param[in] a First CCT + \param[in] b Second CCT + \return true to keep the pair, false to filter it out + */ + virtual bool filter(const PxController& a, const PxController& b) = 0; +}; + +/** +\brief Filtering data for "move" call. + +This class contains all filtering-related parameters for the PxController::move() call. + +Collisions between a CCT and the world are filtered using the mFilterData, mFilterCallback and mFilterFlags +members. These parameters are internally passed to PxScene::overlap() to find objects touched by the CCT. +Please refer to the PxScene::overlap() documentation for details. + +Collisions between a CCT and another CCT are filtered using the mCCTFilterCallback member. If this filter +callback is not defined, none of the CCT-vs-CCT collisions are filtered, and each CCT will collide against +all other CCTs. + +\note PxQueryFlag::eANY_HIT and PxQueryFlag::eNO_BLOCK are ignored in mFilterFlags. + +\see PxController.move() PxControllerFilterCallback +*/ +class PxControllerFilters +{ + public: + + PX_INLINE PxControllerFilters(const PxFilterData* filterData=NULL, PxQueryFilterCallback* cb=NULL, PxControllerFilterCallback* cctFilterCb=NULL) : + mFilterData (filterData), + mFilterCallback (cb), + mFilterFlags (PxQueryFlag::eSTATIC|PxQueryFlag::eDYNAMIC|PxQueryFlag::ePREFILTER), + mCCTFilterCallback (cctFilterCb) + {} + + // CCT-vs-shapes: + const PxFilterData* mFilterData; //!< Data for internal PxQueryFilterData structure. Passed to PxScene::overlap() call. + //!< This can be NULL, in which case a default PxFilterData is used. + PxQueryFilterCallback* mFilterCallback; //!< Custom filter logic (can be NULL). Passed to PxScene::overlap() call. + PxQueryFlags mFilterFlags; //!< Flags for internal PxQueryFilterData structure. Passed to PxScene::overlap() call. + // CCT-vs-CCT: + PxControllerFilterCallback* mCCTFilterCallback; //!< CCT-vs-CCT filter callback. If NULL, all CCT-vs-CCT collisions are kept. +}; + +/** +\brief Descriptor class for a character controller. + +\see PxBoxController PxCapsuleController +*/ +class PxControllerDesc +{ +public: + + /** + \brief returns true if the current settings are valid + + \return True if the descriptor is valid. + */ + PX_INLINE virtual bool isValid() const; + + /** + \brief Returns the character controller type + + \return The controllers type. + + \see PxControllerType PxCapsuleControllerDesc PxBoxControllerDesc + */ + PX_INLINE PxControllerShapeType::Enum getType() const { return mType; } + + /** + \brief The position of the character + + \note The character's initial position must be such that it does not overlap the static geometry. + + Default: Zero + */ + PxExtendedVec3 position; + + /** + \brief Specifies the 'up' direction + + In order to provide stepping functionality the SDK must be informed about the up direction. + + Default: (0, 1, 0) + + */ + PxVec3 upDirection; + + /** + \brief The maximum slope which the character can walk up. + + In general it is desirable to limit where the character can walk, in particular it is unrealistic + for the character to be able to climb arbitary slopes. + + The limit is expressed as the cosine of desired limit angle. A value of 0 disables this feature. + + \warning It is currently enabled for static actors only (not for dynamic/kinematic actors), and not supported for spheres or capsules. + + Default: 0.707 + + \see upDirection invisibleWallHeight maxJumpHeight + */ + PxF32 slopeLimit; + + /** + \brief Height of invisible walls created around non-walkable triangles + + The library can automatically create invisible walls around non-walkable triangles defined + by the 'slopeLimit' parameter. This defines the height of those walls. If it is 0.0, then + no extra triangles are created. + + Default: 0.0 + + \see upDirection slopeLimit maxJumpHeight + */ + PxF32 invisibleWallHeight; + + /** + \brief Maximum height a jumping character can reach + + This is only used if invisible walls are created ('invisibleWallHeight' is non zero). + + When a character jumps, the non-walkable triangles he might fly over are not found + by the collision queries (since the character's bounding volume does not touch them). + Thus those non-walkable triangles do not create invisible walls, and it is possible + for a jumping character to land on a non-walkable triangle, while he wouldn't have + reached that place by just walking. + + The 'maxJumpHeight' variable is used to extend the size of the collision volume + downward. This way, all the non-walkable triangles are properly found by the collision + queries and it becomes impossible to 'jump over' invisible walls. + + If the character in your game can not jump, it is safe to use 0.0 here. Otherwise it + is best to keep this value as small as possible, since a larger collision volume + means more triangles to process. + + Default: 0.0 + + \see upDirection slopeLimit invisibleWallHeight + */ + PxF32 maxJumpHeight; + + /** + \brief The contact offset used by the controller. + + Specifies a skin around the object within which contacts will be generated. + Use it to avoid numerical precision issues. + + This is dependant on the scale of the users world, but should be a small, positive + non zero value. + + Default: 0.1 + */ + PxF32 contactOffset; + + /** + \brief Defines the maximum height of an obstacle which the character can climb. + + A small value will mean that the character gets stuck and cannot walk up stairs etc, + a value which is too large will mean that the character can climb over unrealistically + high obstacles. + + Default: 0.5 + + \see upDirection + */ + PxF32 stepOffset; + + /** + \brief Density of underlying kinematic actor + + The CCT creates a PhysX's kinematic actor under the hood. This controls its density. + + Default: 10.0 + */ + PxF32 density; + + /** + \brief Scale coefficient for underlying kinematic actor + + The CCT creates a PhysX's kinematic actor under the hood. This controls its scale factor. + This should be a number a bit smaller than 1.0. + + This scale factor affects how the character interacts with dynamic rigid bodies around it (e.g. pushing them, etc). + + With a scale factor < 1, the underlying kinematic actor will not touch surrounding rigid bodies - they will + only interact with the character controller's shapes (capsules or boxes), and users will have full control + over the interactions (i.e. they will have to push the objects with explicit forces themselves). + + With a scale factor >=1, the underlying kinematic actor will touch and push surrounding rigid bodies based + on PhysX's computations, as if there would be no character controller involved. This works fine except + when you push objects into a wall. PhysX has no control over kinematic actors (since they are kinematic) + so they would freely push dynamic objects into walls, and make them tunnel / explode / behave badly. + + With a smaller kinematic actor however, the character controller's swept shape touches dynamic rigid bodies + first, and can apply forces to them to move them away (or not, depending on what the gameplay needs). + Meanwhile the character controller's swept shape itself is stopped by these dynamic bodies. + + Setting the scale factor to 1 could still work, but it is unreliable. Depending on FPU accuracy you could + end up with either the CCT's volume or the underlying kinematic actor touching the dynamic bodies first, + and this could change from one moment to the next. + + Default: 0.8 + */ + PxF32 scaleCoeff; + + /** + \brief Cached volume growth + + Amount of space around the controller we cache to improve performance. This is a scale factor + that should be higher than 1.0f but not too big, ideally lower than 2.0f. + + Default: 1.5 + */ + PxF32 volumeGrowth; + + /** + \brief Specifies a user report callback. + + This report callback is called when the character collides with shapes and other characters. + + Setting this to NULL disables the callback. + + Default: NULL + + \see PxUserControllerHitReport + */ + PxUserControllerHitReport* reportCallback; + + /** + \brief Specifies a user behavior callback. + + This behavior callback is called to customize the controller's behavior w.r.t. touched shapes. + + Setting this to NULL disables the callback. + + Default: NULL + + \see PxControllerBehaviorCallback + */ + PxControllerBehaviorCallback* behaviorCallback; + + /** + \brief The non-walkable mode controls if a character controller slides or not on a non-walkable part. + + This is only used when slopeLimit is non zero. + + Default: PxControllerNonWalkableMode::ePREVENT_CLIMBING + + \see PxControllerNonWalkableMode + */ + PxControllerNonWalkableMode::Enum nonWalkableMode; + + /** + \brief The material for the actor associated with the controller. + + The controller internally creates a rigid body actor. This parameter specifies the material of the actor. + + Default: NULL + + \see PxMaterial + */ + PxMaterial* material; + + /** + \brief Use a deletion listener to get informed about released objects and clear internal caches if needed. + + If a character controller registers a deletion listener, it will get informed about released objects. That allows the + controller to invalidate cached data that connects to a released object. If a deletion listener is not + registered, PxController::invalidateCache has to be called manually after objects have been released. + + \see PxController::invalidateCache + + Default: true + */ + bool registerDeletionListener; + + /** + \brief Client ID for associated actor. + + \see PxClientID PxActor::setOwnerClient + + Default: PX_DEFAULT_CLIENT + */ + PxClientID clientID; + + /** + \brief User specified data associated with the controller. + + Default: NULL + */ + void* userData; + +protected: + const PxControllerShapeType::Enum mType; //!< The type of the controller. This gets set by the derived class' ctor, the user should not have to change it. + + /** + \brief constructor sets to default. + */ + PX_INLINE PxControllerDesc(PxControllerShapeType::Enum); + PX_INLINE virtual ~PxControllerDesc(); + + /** + \brief copy constructor. + */ + PX_INLINE PxControllerDesc(const PxControllerDesc&); + + /** + \brief assignment operator. + */ + PX_INLINE PxControllerDesc& operator=(const PxControllerDesc&); + + PX_INLINE void copy(const PxControllerDesc&); +}; + +PX_INLINE PxControllerDesc::PxControllerDesc(PxControllerShapeType::Enum t) : + position (PxExtended(0.0), PxExtended(0.0), PxExtended(0.0)), + upDirection (0.0f, 1.0f, 0.0f), + slopeLimit (0.707f), + invisibleWallHeight (0.0f), + maxJumpHeight (0.0f), + contactOffset (0.1f), + stepOffset (0.5f), + density (10.0f), + scaleCoeff (0.8f), + volumeGrowth (1.5f), + reportCallback (NULL), + behaviorCallback (NULL), + nonWalkableMode (PxControllerNonWalkableMode::ePREVENT_CLIMBING), + material (NULL), + registerDeletionListener (true), + clientID (PX_DEFAULT_CLIENT), + userData (NULL), + mType (t) +{ +} + +PX_INLINE PxControllerDesc::PxControllerDesc(const PxControllerDesc& other) : mType(other.mType) +{ + copy(other); +} + +PX_INLINE PxControllerDesc& PxControllerDesc::operator=(const PxControllerDesc& other) +{ + copy(other); + return *this; +} + +PX_INLINE void PxControllerDesc::copy(const PxControllerDesc& other) +{ + upDirection = other.upDirection; + slopeLimit = other.slopeLimit; + contactOffset = other.contactOffset; + stepOffset = other.stepOffset; + density = other.density; + scaleCoeff = other.scaleCoeff; + volumeGrowth = other.volumeGrowth; + reportCallback = other.reportCallback; + behaviorCallback = other.behaviorCallback; + userData = other.userData; + nonWalkableMode = other.nonWalkableMode; + position.x = other.position.x; + position.y = other.position.y; + position.z = other.position.z; + material = other.material; + invisibleWallHeight = other.invisibleWallHeight; + maxJumpHeight = other.maxJumpHeight; + registerDeletionListener = other.registerDeletionListener; + clientID = other.clientID; +} + +PX_INLINE PxControllerDesc::~PxControllerDesc() +{ +} + +PX_INLINE bool PxControllerDesc::isValid() const +{ + if( mType!=PxControllerShapeType::eBOX + && mType!=PxControllerShapeType::eCAPSULE) + return false; + if(scaleCoeff<0.0f) + return false; + if(volumeGrowth<1.0f) + return false; + if(density<0.0f) + return false; + if(slopeLimit<0.0f) + return false; + if(stepOffset<0.0f) + return false; + if(contactOffset<=0.0f) + return false; + if(!material) + return false; + if(!toVec3(position).isFinite()) + return false; //the float version needs to be finite otherwise actor creation will fail. + + return true; +} + + +/** +\brief Base class for character controllers. + +\see PxCapsuleController PxBoxController +*/ +class PxController +{ +public: + /** + \brief Return the type of controller + + \see PxControllerType + */ + virtual PxControllerShapeType::Enum getType() const = 0; + + /** + \brief Releases the controller. + */ + virtual void release() = 0; + + /** + \brief Moves the character using a "collide-and-slide" algorithm. + + \param[in] disp Displacement vector + \param[in] minDist The minimum travelled distance to consider. If travelled distance is smaller, the character doesn't move. + This is used to stop the recursive motion algorithm when remaining distance to travel is small. + \param[in] elapsedTime Time elapsed since last call + \param[in] filters User-defined filters for this move + \param[in] obstacles Potential additional obstacles the CCT should collide with. + \return Collision flags, collection of ::PxControllerCollisionFlags + */ + virtual PxControllerCollisionFlags move(const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles=NULL) = 0; + + /** + \brief Sets controller's position. + + The position controlled by this function is the center of the collision shape. + + \warning This is a 'teleport' function, it doesn't check for collisions. + \warning The character's position must be such that it does not overlap the static geometry. + + To move the character under normal conditions use the #move() function. + + \param[in] position The new (center) positon for the controller. + \return Currently always returns true. + + \see PxControllerDesc.position getPosition() getFootPosition() setFootPosition() move() + */ + virtual bool setPosition(const PxExtendedVec3& position) = 0; + + /** + \brief Retrieve the raw position of the controller. + + The position retrieved by this function is the center of the collision shape. To retrieve the bottom position of the shape, + a.k.a. the foot position, use the getFootPosition() function. + + The position is updated by calls to move(). Calling this method without calling + move() will return the last position or the initial position of the controller. + + \return The controller's center position + + \see PxControllerDesc.position setPosition() getFootPosition() setFootPosition() move() + */ + virtual const PxExtendedVec3& getPosition() const = 0; + + /** + \brief Set controller's foot position. + + The position controlled by this function is the bottom of the collision shape, a.k.a. the foot position. + + \note The foot position takes the contact offset into account + + \warning This is a 'teleport' function, it doesn't check for collisions. + + To move the character under normal conditions use the #move() function. + + \param[in] position The new (bottom) positon for the controller. + \return Currently always returns true. + + \see PxControllerDesc.position setPosition() getPosition() getFootPosition() move() + */ + virtual bool setFootPosition(const PxExtendedVec3& position) = 0; + + /** + \brief Retrieve the "foot" position of the controller, i.e. the position of the bottom of the CCT's shape. + + \note The foot position takes the contact offset into account + + \return The controller's foot position + + \see PxControllerDesc.position setPosition() getPosition() setFootPosition() move() + */ + virtual PxExtendedVec3 getFootPosition() const = 0; + + /** + \brief Get the rigid body actor associated with this controller (see PhysX documentation). + The behavior upon manually altering this actor is undefined, you should primarily + use it for reading const properties. + + \return the actor associated with the controller. + */ + virtual PxRigidDynamic* getActor() const = 0; + + /** + \brief The step height. + + \param[in] offset The new step offset for the controller. + + \see PxControllerDesc.stepOffset + */ + virtual void setStepOffset(const PxF32 offset) =0; + + /** + \brief Retrieve the step height. + + \return The step offset for the controller. + + \see setStepOffset() + */ + virtual PxF32 getStepOffset() const =0; + + /** + \brief Sets the non-walkable mode for the CCT. + + \param[in] flag The new value of the non-walkable mode. + + \see PxControllerNonWalkableMode + */ + virtual void setNonWalkableMode(PxControllerNonWalkableMode::Enum flag) = 0; + + /** + \brief Retrieves the non-walkable mode for the CCT. + + \return The current non-walkable mode. + + \see PxControllerNonWalkableMode + */ + virtual PxControllerNonWalkableMode::Enum getNonWalkableMode() const = 0; + + /** + \brief Retrieve the contact offset. + + \return The contact offset for the controller. + + \see PxControllerDesc.contactOffset + */ + virtual PxF32 getContactOffset() const =0; + + /** + \brief Sets the contact offset. + + \param[in] offset The contact offset for the controller. + + \see PxControllerDesc.contactOffset + */ + virtual void setContactOffset(PxF32 offset) =0; + + /** + \brief Retrieve the 'up' direction. + + \return The up direction for the controller. + + \see PxControllerDesc.upDirection + */ + virtual PxVec3 getUpDirection() const =0; + + /** + \brief Sets the 'up' direction. + + \param[in] up The up direction for the controller. + + \see PxControllerDesc.upDirection + */ + virtual void setUpDirection(const PxVec3& up) =0; + + /** + \brief Retrieve the slope limit. + + \return The slope limit for the controller. + + \see PxControllerDesc.slopeLimit + */ + virtual PxF32 getSlopeLimit() const =0; + + /** + \brief Sets the slope limit. + + \note This feature can not be enabled at runtime, i.e. if the slope limit is zero when creating the CCT + (which disables the feature) then changing the slope limit at runtime will not have any effect, and the call + will be ignored. + + \param[in] slopeLimit The slope limit for the controller. + + \see PxControllerDesc.slopeLimit + */ + virtual void setSlopeLimit(PxF32 slopeLimit) =0; + + /** + \brief Flushes internal geometry cache. + + The character controller uses caching in order to speed up collision testing. The cache is + automatically flushed when a change to static objects is detected in the scene. For example when a + static shape is added, updated, or removed from the scene, the cache is automatically invalidated. + + However there may be situations that cannot be automatically detected, and those require manual + invalidation of the cache. Currently the user must call this when the filtering behavior changes (the + PxControllerFilters parameter of the PxController::move call). While the controller in principle + could detect a change in these parameters, it cannot detect a change in the behavior of the filtering + function. + + \see PxController.move + */ + virtual void invalidateCache() = 0; + + /** + \brief Retrieve the scene associated with the controller. + + \return The physics scene + */ + virtual PxScene* getScene() = 0; + + /** + \brief Returns the user data associated with this controller. + + \return The user pointer associated with the controller. + + \see PxControllerDesc.userData + */ + virtual void* getUserData() const = 0; + + /** + \brief Sets the user data associated with this controller. + + \param[in] userData The user pointer associated with the controller. + + \see PxControllerDesc.userData + */ + virtual void setUserData(void* userData) = 0; + + /** + \brief Returns information about the controller's internal state. + + \param[out] state The controller's internal state + + \see PxControllerState + */ + virtual void getState(PxControllerState& state) const = 0; + + /** + \brief Returns the controller's internal statistics. + + \param[out] stats The controller's internal statistics + + \see PxControllerStats + */ + virtual void getStats(PxControllerStats& stats) const = 0; + + /** + \brief Resizes the controller. + + This function attempts to resize the controller to a given size, while making sure the bottom + position of the controller remains constant. In other words the function modifies both the + height and the (center) position of the controller. This is a helper function that can be used + to implement a 'crouch' functionality for example. + + \param[in] height Desired controller's height + */ + virtual void resize(PxReal height) = 0; + +protected: + PX_INLINE PxController() {} + virtual ~PxController() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerBehavior.h b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerBehavior.h new file mode 100644 index 000000000..0bb3cd593 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerBehavior.h @@ -0,0 +1,125 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTROLLER_BEHAVIOR_H +#define PX_CONTROLLER_BEHAVIOR_H + +#include "PxFiltering.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxShape; + class PxObstacle; + class PxController; + + /** + \brief specifies controller behavior + */ + struct PxControllerBehaviorFlag + { + enum Enum + { + eCCT_CAN_RIDE_ON_OBJECT = (1<<0), //!< Controller can ride on touched object (i.e. when this touched object is moving horizontally). \note The CCT vs. CCT case is not supported. + eCCT_SLIDE = (1<<1), //!< Controller should slide on touched object + eCCT_USER_DEFINED_RIDE = (1<<2) //!< Disable all code dealing with controllers riding on objects, let users define it outside of the SDK. + }; + }; + + /** + \brief Bitfield that contains a set of raised flags defined in PxControllerBehaviorFlag. + + \see PxControllerBehaviorFlag + */ + typedef PxFlags PxControllerBehaviorFlags; + PX_FLAGS_OPERATORS(PxControllerBehaviorFlag::Enum, PxU8) + + /** + \brief User behavior callback. + + This behavior callback is called to customize the controller's behavior w.r.t. touched shapes. + */ + class PxControllerBehaviorCallback + { + public: + /** + \brief Retrieve behavior flags for a shape. + + When the CCT touches a shape, the CCT's behavior w.r.t. this shape can be customized by users. + This function retrieves the desired PxControllerBehaviorFlag flags capturing the desired behavior. + + \param[in] shape The shape the CCT is currently touching + \param[in] actor The actor owning the shape + + \return Desired behavior flags for the given shape + + \see PxControllerBehaviorFlag + */ + virtual PxControllerBehaviorFlags getBehaviorFlags(const PxShape& shape, const PxActor& actor) = 0; + + /** + \brief Retrieve behavior flags for a controller. + + When the CCT touches a controller, the CCT's behavior w.r.t. this controller can be customized by users. + This function retrieves the desired PxControllerBehaviorFlag flags capturing the desired behavior. + + \note The flag PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT is not supported. + + \param[in] controller The controller the CCT is currently touching + + \return Desired behavior flags for the given controller + + \see PxControllerBehaviorFlag + */ + virtual PxControllerBehaviorFlags getBehaviorFlags(const PxController& controller) = 0; + + /** + \brief Retrieve behavior flags for an obstacle. + + When the CCT touches an obstacle, the CCT's behavior w.r.t. this obstacle can be customized by users. + This function retrieves the desired PxControllerBehaviorFlag flags capturing the desired behavior. + + \param[in] obstacle The obstacle the CCT is currently touching + + \return Desired behavior flags for the given obstacle + + \see PxControllerBehaviorFlag + */ + virtual PxControllerBehaviorFlags getBehaviorFlags(const PxObstacle& obstacle) = 0; + + protected: + virtual ~PxControllerBehaviorCallback(){} + }; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerManager.h b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerManager.h new file mode 100644 index 000000000..70198bb65 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerManager.h @@ -0,0 +1,296 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTROLLER_MANAGER_H +#define PX_CONTROLLER_MANAGER_H + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" +#include "foundation/PxErrorCallback.h" +#include "common/PxRenderBuffer.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxPhysics; +class PxScene; +class PxController; +class PxControllerDesc; +class PxObstacleContext; +class PxControllerFilterCallback; + +/** +\brief specifies debug-rendering flags +*/ +struct PxControllerDebugRenderFlag +{ + enum Enum + { + eTEMPORAL_BV = (1<<0), //!< Temporal bounding volume around controllers + eCACHED_BV = (1<<1), //!< Cached bounding volume around controllers + eOBSTACLES = (1<<2), //!< User-defined obstacles + + eNONE = 0, + eALL = 0xffffffff + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxControllerDebugRenderFlag. + +\see PxControllerDebugRenderFlag +*/ +typedef PxFlags PxControllerDebugRenderFlags; +PX_FLAGS_OPERATORS(PxControllerDebugRenderFlag::Enum, PxU32) + + +/** +\brief Manages an array of character controllers. + +\see PxController PxBoxController PxCapsuleController +*/ +class PxControllerManager +{ +public: + /** + \brief Releases the controller manager. + + \note This will release all associated controllers and obstacle contexts. + + \note This function is required to be called to release foundation usage. + + */ + virtual void release() = 0; + + /** + \brief Returns the scene the manager is adding the controllers to. + + \return The associated physics scene. + */ + virtual PxScene& getScene() const = 0; + + /** + \brief Returns the number of controllers that are being managed. + + \return The number of controllers. + */ + virtual PxU32 getNbControllers() const = 0; + + /** + \brief Retrieve one of the controllers in the manager. + + \param index the index of the controller to return + \return The controller with the specified index. + */ + virtual PxController* getController(PxU32 index) = 0; + + /** + \brief Creates a new character controller. + + \param[in] desc The controllers descriptor + \return The new controller + + \see PxController PxController.release() PxControllerDesc + */ + virtual PxController* createController(const PxControllerDesc& desc) = 0; + + /** + \brief Releases all the controllers that are being managed. + */ + virtual void purgeControllers() = 0; + + /** + \brief Retrieves debug data. + + \return The render buffer filled with debug-render data + + \see PxControllerManager.setDebugRenderingFlags() + */ + virtual PxRenderBuffer& getRenderBuffer() = 0; + + /** + \brief Sets debug rendering flags + + \param[in] flags The debug rendering flags (combination of PxControllerDebugRenderFlags) + + \see PxControllerManager.getRenderBuffer() PxControllerDebugRenderFlags + */ + virtual void setDebugRenderingFlags(PxControllerDebugRenderFlags flags) = 0; + + /** + \brief Returns the number of obstacle contexts that are being managed. + + \return The number of obstacle contexts. + */ + virtual PxU32 getNbObstacleContexts() const = 0; + + /** + \brief Retrieve one of the obstacle contexts in the manager. + + \param index The index of the obstacle context to retrieve. + \return The obstacle context with the specified index. + */ + virtual PxObstacleContext* getObstacleContext(PxU32 index) = 0; + + /** + \brief Creates an obstacle context. + + \return New obstacle context + + \see PxObstacleContext + */ + virtual PxObstacleContext* createObstacleContext() = 0; + + /** + \brief Computes character-character interactions. + + This function is an optional helper to properly resolve interactions between characters, in case they overlap (which can happen for gameplay reasons, etc). + + You should call this once per frame, before your PxController::move() calls. The function will not move the characters directly, but it will + compute overlap information for each character that will be used in the next move() call. + + You need to provide a proper time value here so that interactions are resolved in a way that do not depend on the framerate. + + If you only have one character in the scene, or if you can guarantee your characters will never overlap, then you do not need to call this function. + + \note Releasing the manager will automatically release all the associated obstacle contexts. + + \param[in] elapsedTime Elapsed time since last call + \param[in] cctFilterCb Filtering callback for CCT-vs-CCT interactions + */ + virtual void computeInteractions(PxF32 elapsedTime, PxControllerFilterCallback* cctFilterCb=NULL) = 0; + + /** + \brief Enables or disables runtime tessellation. + + Large triangles can create accuracy issues in the sweep code, which in turn can lead to characters not sliding smoothly + against geometries, or even penetrating them. This feature allows one to reduce those issues by tessellating large + triangles at runtime, before performing sweeps against them. The amount of tessellation is controlled by the 'maxEdgeLength' parameter. + Any triangle with at least one edge length greater than the maxEdgeLength will get recursively tessellated, until resulting triangles are small enough. + + This features only applies to triangle meshes, convex meshes, heightfields and boxes. + + \param[in] flag True/false to enable/disable runtime tessellation. + \param[in] maxEdgeLength Max edge length allowed before tessellation kicks in. + */ + virtual void setTessellation(bool flag, float maxEdgeLength) = 0; + + /** + \brief Enables or disables the overlap recovery module. + + The overlap recovery module can be used to depenetrate CCTs from static objects when an overlap is detected. This can happen + in three main cases: + - when the CCT is directly spawned or teleported in another object + - when the CCT algorithm fails due to limited FPU accuracy + - when the "up vector" is modified, making the rotated CCT shape overlap surrounding objects + + When activated, the CCT module will automatically try to resolve the penetration, and move the CCT to a safe place where it does + not overlap other objects anymore. This only concerns static objects, dynamic objects are ignored by the recovery module. + + When the recovery module is not activated, it is possible for the CCTs to go through static objects. By default, the recovery + module is enabled. + + The recovery module currently works with all geometries except heightfields. + + \param[in] flag True/false to enable/disable overlap recovery module. + */ + virtual void setOverlapRecoveryModule(bool flag) = 0; + + /** + \brief Enables or disables the precise sweeps. + + Precise sweeps are more accurate, but also potentially slower than regular sweeps. + + By default, precise sweeps are enabled. + + \param[in] flag True/false to enable/disable precise sweeps. + */ + virtual void setPreciseSweeps(bool flag) = 0; + + /** + \brief Enables or disables vertical sliding against ceilings. + + Geometry is seen as "ceilings" when the following condition is met: + + dot product(contact normal, up direction)<0.0f + + This flag controls whether characters should slide vertically along the geometry in that case. + + By default, sliding is allowed. + + \param[in] flag True/false to enable/disable sliding. + */ + virtual void setPreventVerticalSlidingAgainstCeiling(bool flag) = 0; + + /** + \brief Shift the origin of the character controllers and obstacle objects by the specified vector. + + The positions of all character controllers, obstacle objects and the corresponding data structures will get adjusted to reflect the shifted origin location + (the shift vector will get subtracted from all character controller and obstacle object positions). + + \note It is the user's responsibility to keep track of the summed total origin shift and adjust all input/output to/from PhysXCharacterKinematic accordingly. + + \note This call will not automatically shift the PhysX scene and its objects. You need to call PxScene::shiftOrigin() separately to keep the systems in sync. + + \param[in] shift Translation vector to shift the origin by. + */ + virtual void shiftOrigin(const PxVec3& shift) = 0; + +protected: + PxControllerManager() {} + virtual ~PxControllerManager() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + + /** + \brief Creates the controller manager. + + \param[in] scene PhysX scene. You can only create one PxControllerManager per scene. + \param[in] lockingEnabled Enables/disables internal locking. + + \return New controller manager, or NULL in case of failure (e.g. when a manager has already been created for that scene) + + The character controller is informed by #PxDeletionListener::onRelease() when actors or shapes are released, and updates its internal + caches accordingly. If character controller movement or a call to #PxControllerManager::shiftOrigin() may overlap with actor/shape releases, + internal data structures must be guarded against concurrent access. + + Locking guarantees thread safety in such scenarios. + + \note locking may result in significant slowdown for release of actors or shapes. + + By default, locking is disabled. + */ +PX_C_EXPORT physx::PxControllerManager* PX_CALL_CONV PxCreateControllerManager(physx::PxScene& scene, bool lockingEnabled = false); + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerObstacles.h b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerObstacles.h new file mode 100644 index 000000000..1095725fb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxControllerObstacles.h @@ -0,0 +1,186 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTROLLER_OBSTACLES_H +#define PX_CONTROLLER_OBSTACLES_H + +#include "characterkinematic/PxExtended.h" +#include "geometry/PxGeometry.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxControllerManager; + + #define PX_INVALID_OBSTACLE_HANDLE 0xffffffff + + /** + \brief Base class for obstacles. + + \see PxBoxObstacle PxCapsuleObstacle PxObstacleContext + */ + class PxObstacle + { + protected: + PxObstacle() : + mType (PxGeometryType::eINVALID), + mUserData (NULL), + mPos (0.0, 0.0, 0.0), + mRot (PxQuat(PxIdentity)) + {} + + PxGeometryType::Enum mType; + public: + + PX_FORCE_INLINE PxGeometryType::Enum getType() const { return mType; } + + void* mUserData; + PxExtendedVec3 mPos; + PxQuat mRot; + }; + + /** + \brief A box obstacle. + + \see PxObstacle PxCapsuleObstacle PxObstacleContext + */ + class PxBoxObstacle : public PxObstacle + { + public: + PxBoxObstacle() : + mHalfExtents(0.0f) + { mType = PxGeometryType::eBOX; } + + PxVec3 mHalfExtents; + }; + + /** + \brief A capsule obstacle. + + \see PxBoxObstacle PxObstacle PxObstacleContext + */ + class PxCapsuleObstacle : public PxObstacle + { + public: + PxCapsuleObstacle() : + mHalfHeight (0.0f), + mRadius (0.0f) + { mType = PxGeometryType::eCAPSULE; } + + PxReal mHalfHeight; + PxReal mRadius; + }; + + typedef PxU32 PxObstacleHandle; + + /** + \brief Context class for obstacles. + + An obstacle context class contains and manages a set of user-defined obstacles. + + \see PxBoxObstacle PxCapsuleObstacle PxObstacle + */ + class PxObstacleContext + { + public: + PxObstacleContext() {} + virtual ~PxObstacleContext() {} + + /** + \brief Releases the context. + */ + virtual void release() = 0; + + /** + \brief Retrieves the controller manager associated with this context. + + \return The associated controller manager + */ + virtual PxControllerManager& getControllerManager() const = 0; + + /** + \brief Adds an obstacle to the context. + + \param [in] obstacle Obstacle data for the new obstacle. The data gets copied. + + \return Handle for newly-added obstacle + */ + virtual PxObstacleHandle addObstacle(const PxObstacle& obstacle) = 0; + + /** + \brief Removes an obstacle from the context. + + \param [in] handle Handle for the obstacle object that needs to be removed. + + \return True if success + */ + virtual bool removeObstacle(PxObstacleHandle handle) = 0; + + /** + \brief Updates data for an existing obstacle. + + \param [in] handle Handle for the obstacle object that needs to be updated. + \param [in] obstacle New obstacle data + + \return True if success + */ + virtual bool updateObstacle(PxObstacleHandle handle, const PxObstacle& obstacle) = 0; + + /** + \brief Retrieves number of obstacles in the context. + + \return Number of obstacles in the context + */ + virtual PxU32 getNbObstacles() const = 0; + + /** + \brief Retrieves desired obstacle. + + \param [in] i Obstacle index + + \return Desired obstacle + */ + virtual const PxObstacle* getObstacle(PxU32 i) const = 0; + + /** + \brief Retrieves desired obstacle by given handle. + + \param [in] handle Obstacle handle + + \return Desired obstacle + */ + virtual const PxObstacle* getObstacleByHandle(PxObstacleHandle handle) const = 0; + }; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxExtended.h b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxExtended.h new file mode 100644 index 000000000..dc24107e2 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/characterkinematic/PxExtended.h @@ -0,0 +1,82 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_EXTENDED_H +#define PX_EXTENDED_H + +// This needs to be included in Foundation just for the debug renderer + +#include "PxPhysXConfig.h" +#include "foundation/PxTransform.h" +#include "foundation/PxAssert.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +// This has to be done here since it also changes the top-level "Px" and "Np" APIs +#define PX_BIG_WORLDS + +#ifdef PX_BIG_WORLDS + typedef PxVec3d PxExtendedVec3; + typedef double PxExtended; + #define PX_MAX_EXTENDED PX_MAX_F64 + + PX_FORCE_INLINE PxVec3 toVec3(const PxExtendedVec3& v) + { + return PxVec3(float(v.x), float(v.y), float(v.z)); + } + + // Computes the single-precision difference between two extended-precision points + PX_INLINE PxVec3 diff(const PxExtendedVec3& p1, const PxExtendedVec3& p0) + { + return PxVec3(float(p1.x - p0.x), float(p1.y - p0.y), float(p1.z - p0.z)); + } +#else + typedef PxVec3 PxExtendedVec3; + typedef float PxExtended; + #define PX_MAX_EXTENDED PX_MAX_F32 + + PX_FORCE_INLINE PxVec3 toVec3(const PxExtendedVec3& v) + { + return v; + } + + // Computes the single-precision difference between two extended-precision points + PX_INLINE PxVec3 diff(const PxExtendedVec3& p1, const PxExtendedVec3& p0) + { + return p1 - p0; + } +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/collision/PxCollisionDefs.h b/Jusin154_Team3D/Engine/Public/PhysX/collision/PxCollisionDefs.h new file mode 100644 index 000000000..d2cfe71c5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/collision/PxCollisionDefs.h @@ -0,0 +1,92 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_COLLISION_DEFS_H +#define PX_COLLISION_DEFS_H + +#include "PxPhysXConfig.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief A callback class to allocate memory to cache information used in contact generation. +*/ +class PxCacheAllocator +{ +public: + /** + \brief Allocates cache data for contact generation. This data is stored inside PxCache objects. + The application can retain and provide this information for future contact generation passes + for a given pair to improve contact generation performance. It is the application's responsibility + to release this memory appropriately. If the memory is released, the application must ensure that + this memory is no longer referenced by any PxCache objects passed to PxGenerateContacts. + + \param byteSize [in] size of the allocation in bytes + + \return the newly-allocated memory. The returned address must be 16-byte aligned. + + \see PxCache, PxGenerateContacts + */ + virtual PxU8* allocateCacheData(const PxU32 byteSize) = 0; + + virtual ~PxCacheAllocator() {} +}; + +/** +\brief A structure to cache contact information produced by low-level contact generation functions. +*/ +struct PxCache +{ + PxU8* mCachedData; //!< Cached data pointer. Allocated via PxCacheAllocator + PxU16 mCachedSize; //!< The total size of the cached data + PxU8 mPairData; //!< Pair data information used and cached internally by some contact generation functions to accelerate performance. + PxU8 mManifoldFlags; //!< Manifold flags used to identify the format the cached data is stored in. + + PX_FORCE_INLINE PxCache() : mCachedData(NULL), mCachedSize(0), mPairData(0), mManifoldFlags(0) + { + } + + PX_FORCE_INLINE void reset() + { + mCachedData = NULL; + mCachedSize = 0; + mPairData = 0; + mManifoldFlags = 0; + } +}; + +#if !PX_DOXYGEN +} +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxBase.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxBase.h new file mode 100644 index 000000000..69f5c9a4d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxBase.h @@ -0,0 +1,236 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BASE_H +#define PX_BASE_H + + +#include "foundation/PxFlags.h" +#include "foundation/PxString.h" +#include "foundation/PxFoundation.h" +#include "common/PxSerialFramework.h" +#include "common/PxCollection.h" +#include "common/PxTypeInfo.h" +#include "foundation/PxAssert.h" + +#define PX_IS_KIND_OF(query, classname, baseclass) \ + PX_ASSERT(query != NULL); \ + if(query == NULL) \ + { \ + PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "isKindOf called with invalid string"); \ + return false; \ + } \ + return !Pxstrcmp(classname, query) || baseclass::isKindOf(query) + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +typedef PxU16 PxType; + +/** +\brief Flags for PxBase. +*/ +struct PxBaseFlag +{ + enum Enum + { + eOWNS_MEMORY = (1<<0), + eIS_RELEASABLE = (1<<1) + }; +}; + +typedef PxFlags PxBaseFlags; +PX_FLAGS_OPERATORS(PxBaseFlag::Enum, PxU16) + +/** +\brief Base class for objects that can be members of a PxCollection. + +All PxBase sub-classes can be serialized. + +\see PxCollection +*/ +class PxBase +{ +public: + /** + \brief Releases the PxBase instance, please check documentation of release in derived class. + */ + virtual void release() = 0; + + /** + \brief Returns string name of dynamic type. + \return Class name of most derived type of this object. + */ + virtual const char* getConcreteTypeName() const = 0; + + /* brief Implements dynamic cast functionality. + + Example use: + + if(actor->is()) {...} + + \return A pointer to the specified type if object matches, otherwise NULL + */ + template T* is() { return typeMatch() ? static_cast(this) : NULL; } + + /* brief Implements dynamic cast functionality for const objects. + + Example use: + + if(actor->is()) {...} + + \return A pointer to the specified type if object matches, otherwise NULL + */ + template const T* is() const { return typeMatch() ? static_cast(this) : NULL; } + + /** + \brief Returns concrete type of object. + \return PxConcreteType::Enum of serialized object + + \see PxConcreteType + */ + PX_FORCE_INLINE PxType getConcreteType() const { return mConcreteType; } + + /** + \brief Set PxBaseFlag + + \param[in] flag The flag to be set + \param[in] value The flags new value + */ + PX_FORCE_INLINE void setBaseFlag(PxBaseFlag::Enum flag, bool value) { mBaseFlags = value ? mBaseFlags|flag : mBaseFlags&~flag; } + + /** + \brief Set PxBaseFlags + + \param[in] inFlags The flags to be set + + \see PxBaseFlags + */ + PX_FORCE_INLINE void setBaseFlags(PxBaseFlags inFlags) { mBaseFlags = inFlags; } + + /** + \brief Returns PxBaseFlags + + \return PxBaseFlags + + \see PxBaseFlags + */ + PX_FORCE_INLINE PxBaseFlags getBaseFlags() const { return mBaseFlags; } + + /** + \brief Whether the object is subordinate. + + A class is subordinate, if it can only be instantiated in the context of another class. + + \return Whether the class is subordinate + + \see PxSerialization::isSerializable + */ + virtual bool isReleasable() const { return mBaseFlags & PxBaseFlag::eIS_RELEASABLE; } + +protected: + /** + \brief Constructor setting concrete type and base flags. + */ + PX_INLINE PxBase(PxType concreteType, PxBaseFlags baseFlags) + : mConcreteType(concreteType), mBaseFlags(baseFlags), mBuiltInRefCount(1) {} + + /** + \brief Deserialization constructor setting base flags. + */ + PX_INLINE PxBase(PxBaseFlags baseFlags) : mBaseFlags(baseFlags) + { + PX_ASSERT(mBuiltInRefCount == 1); + } + /** + \brief Destructor. + */ + virtual ~PxBase() {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* superClass) const { return !Pxstrcmp(superClass, "PxBase"); } + + template bool typeMatch() const + { + return PxU32(PxTypeInfo::eFastTypeId)!=PxU32(PxConcreteType::eUNDEFINED) ? + PxU32(getConcreteType()) == PxU32(PxTypeInfo::eFastTypeId) : isKindOf(PxTypeInfo::name()); + } + +protected: + PxType mConcreteType; // concrete type identifier - see PxConcreteType. + PxBaseFlags mBaseFlags; // internal flags + PxU32 mBuiltInRefCount; +}; + +/** +\brief Base class for ref-counted objects. +*/ +class PxRefCounted : public PxBase +{ +public: + + /** + \brief Decrements the reference count of the object and releases it if the new reference count is zero. + */ + virtual void release() = 0; + + /** + \brief Returns the reference count of the object. + + At creation, the reference count of the object is 1. Every other object referencing this object increments the + count by 1. When the reference count reaches 0, and only then, the object gets destroyed automatically. + + \return the current reference count. + */ + virtual PxU32 getReferenceCount() const = 0; + + /** + \brief Acquires a counted reference to this object. + + This method increases the reference count of the object by 1. Decrement the reference count by calling release() + */ + virtual void acquireReference() = 0; + +protected: + virtual void onRefCountZero() { delete this; } + + PX_INLINE PxRefCounted(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxRefCounted(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + virtual ~PxRefCounted() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRefCounted", PxBase); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxCollection.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxCollection.h new file mode 100644 index 000000000..ebf28a7d4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxCollection.h @@ -0,0 +1,273 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_COLLECTION_H +#define PX_COLLECTION_H + +#include "common/PxSerialFramework.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxBase; + +/** +\brief Collection class for serialization. + +A collection is a set of PxBase objects. PxBase objects can be added to the collection +regardless of other objects they depend on. Objects may be named using PxSerialObjectId values in order +to resolve dependencies between objects of different collections. + +Serialization and deserialization only work through collections. + +A scene is typically serialized using the following steps: + + -# create a serialization registry + -# create a collection for scene objects + -# complete the scene objects (adds all dependent objects, e.g. meshes) + -# serialize collection + -# release collection + -# release serialization registry + +For example the code may look like this: + +\code + PxPhysics* physics; // The physics + PxScene* scene; // The physics scene + SerialStream s; // The user-defined stream doing the actual write to disk + + PxSerializationRegistry* registry = PxSerialization::createSerializationRegistry(*physics); // step 1) + PxCollection* collection = PxSerialization::createCollection(*scene); // step 2) + PxSerialization::complete(*collection, *registry); // step 3) + PxSerialization::serializeCollectionToBinary(s, *collection, *registry); // step 4) + collection->release(); // step 5) + registry->release(); // step 6) +\endcode + +A scene is typically deserialized using the following steps: + + -# load a serialized collection into memory + -# create a serialization registry + -# create a collection by passing the serialized memory block + -# add collected objects to scene + -# release collection + -# release serialization registry + +For example the code may look like this: + +\code + PxPhysics* physics; // The physics + PxScene* scene; // The physics scene + void* memory128; // a 128-byte aligned buffer previously loaded from disk by the user - step 1) + + PxSerializationRegistry* registry = PxSerialization::createSerializationRegistry(*physics); // step 2) + PxCollection* collection = PxSerialization::createCollectionFromBinary(memory128, *registry); // step 3) + scene->addCollection(*collection); // step 4) + collection->release(); // step 5) + registry->release(); // step 6) +\endcode + +\see PxBase, PxCreateCollection() +*/ +class PxCollection +{ +public: + + /** + \brief Adds a PxBase object to the collection. + + Adds a PxBase object to the collection. Optionally a PxSerialObjectId can be provided + in order to resolve dependencies between collections. A PxSerialObjectId value of PX_SERIAL_OBJECT_ID_INVALID + means the object remains without id. Objects can be added regardless of other objects they require. If the object + is already in the collection, the ID will be set if it was PX_SERIAL_OBJECT_ID_INVALID previously, otherwise the + operation fails. + + + \param[in] object Object to be added to the collection + \param[in] id Optional PxSerialObjectId id + */ + virtual void add(PxBase& object, PxSerialObjectId id = PX_SERIAL_OBJECT_ID_INVALID) = 0; + + /** + \brief Removes a PxBase member object from the collection. + + Object needs to be contained by the collection. + + \param[in] object PxBase object to be removed + */ + virtual void remove(PxBase& object) = 0; + + /** + \brief Returns whether the collection contains a certain PxBase object. + + \param[in] object PxBase object + \return Whether object is contained. + */ + virtual bool contains(PxBase& object) const = 0; + + /** + \brief Adds an id to a member PxBase object. + + If the object is already associated with an id within the collection, the id is replaced. + May only be called for objects that are members of the collection. The id needs to be unique + within the collection. + + \param[in] object Member PxBase object + \param[in] id PxSerialObjectId id to be given to the object + */ + virtual void addId(PxBase& object, PxSerialObjectId id) = 0; + + /** + \brief Removes id from a contained PxBase object. + + May only be called for ids that are associated with an object in the collection. + + \param[in] id PxSerialObjectId value + */ + virtual void removeId(PxSerialObjectId id) = 0; + + /** + \brief Adds all PxBase objects and their ids of collection to this collection. + + PxBase objects already in this collection are ignored. Object ids need to be conflict + free, i.e. the same object may not have two different ids within the two collections. + + \param[in] collection Collection to be added + */ + virtual void add(PxCollection& collection) = 0; + + /** + \brief Removes all PxBase objects of collection from this collection. + + PxBase objects not present in this collection are ignored. Ids of objects + which are removed are also removed. + + \param[in] collection Collection to be removed + */ + virtual void remove(PxCollection& collection) = 0; + + /** + \brief Gets number of PxBase objects in this collection. + + \return Number of objects in this collection + */ + virtual PxU32 getNbObjects() const = 0; + + /** + \brief Gets the PxBase object of this collection given its index. + + \param[in] index PxBase index in [0, getNbObjects()) + \return PxBase object at index index + */ + virtual PxBase& getObject(PxU32 index) const = 0; + + /** + \brief Copies member PxBase pointers to a user specified buffer. + + \param[out] userBuffer Array of PxBase pointers + \param[in] bufferSize Capacity of userBuffer + \param[in] startIndex Offset into list of member PxBase objects + \return number of members PxBase objects that have been written to the userBuffer + */ + virtual PxU32 getObjects(PxBase** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Looks for a PxBase object given a PxSerialObjectId value. + + If there is no PxBase object in the collection with the given id, NULL is returned. + + \param[in] id PxSerialObjectId value to look for + \return PxBase object with the given id value or NULL + */ + virtual PxBase* find(PxSerialObjectId id) const = 0; + + /** + \brief Gets number of PxSerialObjectId names in this collection. + + \return Number of PxSerialObjectId names in this collection + */ + virtual PxU32 getNbIds() const = 0; + + /** + \brief Copies member PxSerialObjectId values to a user specified buffer. + + \param[out] userBuffer Array of PxSerialObjectId values + \param[in] bufferSize Capacity of userBuffer + \param[in] startIndex Offset into list of member PxSerialObjectId values + \return number of members PxSerialObjectId values that have been written to the userBuffer + */ + virtual PxU32 getIds(PxSerialObjectId* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0; + + /** + \brief Gets the PxSerialObjectId name of a PxBase object within the collection. + + The PxBase object needs to be a member of the collection. + + \param[in] object PxBase object to get id for + \return PxSerialObjectId name of the object or PX_SERIAL_OBJECT_ID_INVALID if the object is unnamed + */ + virtual PxSerialObjectId getId(const PxBase& object) const = 0; + + /** + \brief Deletes a collection object. + + This function only deletes the collection object, i.e. the container class. It doesn't delete objects + that are part of the collection. + + \see PxCreateCollection() + */ + + virtual void release() = 0; + +protected: + PxCollection() {} + virtual ~PxCollection() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** +\brief Creates a collection object. + +Objects can only be serialized or deserialized through a collection. +For serialization, users must add objects to the collection and serialize the collection as a whole. +For deserialization, the system gives back a collection of deserialized objects to users. + +\return The new collection object. + +\see PxCollection, PxCollection::release() +*/ +PX_C_EXPORT PX_PHYSX_COMMON_API physx::PxCollection* PX_CALL_CONV PxCreateCollection(); + + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxCoreUtilityTypes.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxCoreUtilityTypes.h new file mode 100644 index 000000000..918957014 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxCoreUtilityTypes.h @@ -0,0 +1,242 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CORE_UTILITY_TYPES_H +#define PX_CORE_UTILITY_TYPES_H + +#include "foundation/PxAssert.h" +#include "foundation/PxMemory.h" +#include "foundation/PxIO.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + +struct PxBoundedData +{ + /** + \brief The offset in bytes between consecutive samples in the data. + + Default: 0 + */ + const void* data; + PxU32 stride; + PxU32 count; + + PxBoundedData() : data( NULL ), stride(0), count(0) {} + + PxBoundedData(void* data_, PxU32 stride_ = 0, PxU32 count_ = 0) + : data(data_) + , stride(stride_) + , count(count_) + { + } + + template + PX_INLINE const TDataType& at( PxU32 idx ) const + { + PxU32 theStride( stride ); + if ( theStride == 0 ) + theStride = sizeof( TDataType ); + PxU32 offset( theStride * idx ); + return *(reinterpret_cast( reinterpret_cast< const PxU8* >( data ) + offset )); + } +}; + +typedef PX_DEPRECATED PxBoundedData PxStridedData; + +template +struct PxTypedBoundedData +{ + TDataType* data; + PxU32 stride; + PxU32 count; + + PxTypedBoundedData() + : data(NULL) + , stride(0) + , count(0) + { + } + + PxTypedBoundedData(TDataType* data_, PxU32 stride_ = 0, PxU32 count_ = 0) + : data(data_) + , stride(stride_) + , count(count_) + { + } + + PX_CUDA_CALLABLE PX_INLINE const TDataType& at(PxU32 idx) const + { + PxU32 theStride(stride); + if (theStride == 0) + theStride = sizeof(TDataType); + PxU32 offset(theStride * idx); + return *(reinterpret_cast(reinterpret_cast(data) + offset)); + } + + PX_CUDA_CALLABLE PX_INLINE TDataType& atRef(PxU32 idx) + { + PxU32 theStride(stride); + if (theStride == 0) + theStride = sizeof(TDataType); + PxU32 offset(theStride * idx); + return *(reinterpret_cast(reinterpret_cast(data) + offset)); + } +}; + +template +PX_DEPRECATED struct PxTypedStridedData : public PxTypedBoundedData +{ + PxTypedStridedData() : PxTypedBoundedData() + { + } + + PxTypedStridedData(TDataType* data_, PxU32 stride_ = 0) : PxTypedBoundedData(data_, stride_) + { + } +}; + +template +struct PxPadding +{ + PxU8 mPadding[TNumBytes]; + PxPadding() + { + for ( PxU8 idx =0; idx < TNumBytes; ++idx ) + mPadding[idx] = 0; + } +}; + +template class PxFixedSizeLookupTable +{ +public: + + PxFixedSizeLookupTable() + : mNbDataPairs(0) + { + } + + PxFixedSizeLookupTable(const PxEMPTY) {} + + PxFixedSizeLookupTable(const PxReal* dataPairs, const PxU32 numDataPairs) + { + PxMemCopy(mDataPairs,dataPairs,sizeof(PxReal)*2*numDataPairs); + mNbDataPairs=numDataPairs; + } + + PxFixedSizeLookupTable(const PxFixedSizeLookupTable& src) + { + PxMemCopy(mDataPairs,src.mDataPairs,sizeof(PxReal)*2*src.mNbDataPairs); + mNbDataPairs=src.mNbDataPairs; + } + + ~PxFixedSizeLookupTable() + { + } + + PxFixedSizeLookupTable& operator=(const PxFixedSizeLookupTable& src) + { + PxMemCopy(mDataPairs,src.mDataPairs,sizeof(PxReal)*2*src.mNbDataPairs); + mNbDataPairs=src.mNbDataPairs; + return *this; + } + + PX_FORCE_INLINE void addPair(const PxReal x, const PxReal y) + { + PX_ASSERT(mNbDataPairs=x0)&&(x=getX(mNbDataPairs-1)); + return getY(mNbDataPairs-1); + } + + PxU32 getNbDataPairs() const {return mNbDataPairs;} + + void clear() + { + PxMemSet(mDataPairs, 0, NB_ELEMENTS*2*sizeof(PxReal)); + mNbDataPairs = 0; + } + + PX_FORCE_INLINE PxReal getX(const PxU32 i) const + { + return mDataPairs[2*i]; + } + PX_FORCE_INLINE PxReal getY(const PxU32 i) const + { + return mDataPairs[2*i+1]; + } + + PxReal mDataPairs[2*NB_ELEMENTS]; + PxU32 mNbDataPairs; + PxU32 mPad[3]; + + +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxInsertionCallback.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxInsertionCallback.h new file mode 100644 index 000000000..6effa5125 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxInsertionCallback.h @@ -0,0 +1,75 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_INSERTION_CALLBACK_H +#define PX_INSERTION_CALLBACK_H + +#include "common/PxBase.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Callback interface that permits TriangleMesh, Heightfield, ConvexMesh or BVH to be used + directly without the need to store the cooking results into a stream. + + Using this is advised only if real-time cooking is required; using "offline" cooking and + streams is otherwise preferred. + + The default PxInsertionCallback implementations must be used. The PxPhysics + default callback can be obtained using the PxPhysics::getPhysicsInsertionCallback(). + The PxCooking default callback can be obtained using the PxCooking::getStandaloneInsertionCallback(). + + \see PxCooking PxPhysics + */ + class PxInsertionCallback + { + public: + PxInsertionCallback() {} + + /** + \brief Builds object (TriangleMesh, Heightfield, ConvexMesh or BVH) from given data in PxPhysics. + + \param type Object type to build. + \param data Object data + \return PxBase Created object in PxPhysics. + */ + virtual PxBase* buildObjectFromData(PxConcreteType::Enum type, void* data) = 0; + + protected: + virtual ~PxInsertionCallback() {} + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxPhysXCommonConfig.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxPhysXCommonConfig.h new file mode 100644 index 000000000..30eefb207 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxPhysXCommonConfig.h @@ -0,0 +1,126 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSX_COMMON_CONFIG_H +#define PX_PHYSX_COMMON_CONFIG_H + +#include "foundation/PxSimpleTypes.h" + +//Fills almost all allocated (host and device memory) with 0xcdcdcdcd (=3452816845) +#define PX_STOMP_ALLOCATED_MEMORY 0 + +/*Disable support for VS2017 prior version 15.5.1 for windows platform, because of a compiler bug: +https://developercommunity.visualstudio.com/content/problem/66047/possible-compiler-bug.html +*/ +#if (PX_VC == 15) && PX_WINDOWS && (_MSC_FULL_VER < 191225830) +#error Visual studio 2017 prior to 15.5.1 is not supported because of a compiler bug. +#endif + +// define API function declaration (public API only needed because of extensions) +#if defined PX_PHYSX_STATIC_LIB + #define PX_PHYSX_CORE_API +#else + #if PX_WINDOWS_FAMILY + #if defined PX_PHYSX_CORE_EXPORTS + #define PX_PHYSX_CORE_API __declspec(dllexport) + #else + #define PX_PHYSX_CORE_API __declspec(dllimport) + #endif + #elif PX_UNIX_FAMILY + #define PX_PHYSX_CORE_API PX_UNIX_EXPORT + #else + #define PX_PHYSX_CORE_API + #endif +#endif + +#if PX_SUPPORT_GPU_PHYSX +// define API function declaration +#if defined PX_PHYSX_GPU_STATIC + #define PX_PHYSX_GPU_API +#else + #if PX_WINDOWS + #if defined PX_PHYSX_GPU_EXPORTS + #define PX_PHYSX_GPU_API __declspec(dllexport) + #else + #define PX_PHYSX_GPU_API __declspec(dllimport) + #endif + #elif PX_UNIX_FAMILY + #define PX_PHYSX_GPU_API PX_UNIX_EXPORT + #else + #define PX_PHYSX_GPU_API + #endif +#endif + +#else // PX_SUPPORT_GPU_PHYSX +#define PX_PHYSX_GPU_API +#endif // PX_SUPPORT_GPU_PHYSX + +#if defined PX_PHYSX_STATIC_LIB + #define PX_PHYSX_COMMON_API +#else + #if PX_WINDOWS_FAMILY && !PX_CUDA_COMPILER + #if defined PX_PHYSX_COMMON_EXPORTS + #define PX_PHYSX_COMMON_API __declspec(dllexport) + #else + #define PX_PHYSX_COMMON_API __declspec(dllimport) + #endif + #elif PX_UNIX_FAMILY + #define PX_PHYSX_COMMON_API PX_UNIX_EXPORT + #else + #define PX_PHYSX_COMMON_API + #endif +#endif + +// PT: typical "invalid" value in various CD algorithms +#define PX_INVALID_U32 0xffffffff +#define PX_INVALID_U16 0xffff + +// Changing these parameters requires recompilation of the SDK + +// Enable debug visualization +#define PX_ENABLE_DEBUG_VISUALIZATION 1 +#define PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION + +// Enable simulation statistics generation +#define PX_ENABLE_SIM_STATS 1 +#define PX_CATCH_UNDEFINED_ENABLE_SIM_STATS + +#if !PX_DOXYGEN +namespace physx +{ +#endif + typedef PxU32 PxTriangleID; + typedef PxU16 PxMaterialTableIndex; + typedef PxU16 PxDeformableMaterialTableIndex; + typedef PX_DEPRECATED PxU16 PxFEMMaterialTableIndex; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxProfileZone.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxProfileZone.h new file mode 100644 index 000000000..a01e246d5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxProfileZone.h @@ -0,0 +1,56 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_PROFILE_ZONE_H +#define PX_PROFILE_ZONE_H + +#include "foundation/PxProfiler.h" +#include "foundation/PxFoundation.h" + +#if PX_DEBUG || PX_CHECKED || PX_PROFILE + #define PX_PROFILE_ZONE(x, y) \ + physx::PxProfileScoped PX_CONCAT(_scoped, __LINE__)(PxGetProfilerCallback(), x, false, y) + #define PX_PROFILE_START_CROSSTHREAD(x, y) \ + if(PxGetProfilerCallback()) \ + PxGetProfilerCallback()->zoneStart(x, true, y) + #define PX_PROFILE_STOP_CROSSTHREAD(x, y) \ + if(PxGetProfilerCallback()) \ + PxGetProfilerCallback()->zoneEnd(NULL, x, true, y) + #define PX_PROFILE_VALUE(x, y, z) \ + if(PxGetProfilerCallback()) \ + PxGetProfilerCallback()->recordData(x, y, z) + #define PX_PROFILE_FRAME(x, y) \ + if(PxGetProfilerCallback()) \ + PxGetProfilerCallback()->recordFrame(x, y) +#else + #define PX_PROFILE_ZONE(x, y) + #define PX_PROFILE_START_CROSSTHREAD(x, y) + #define PX_PROFILE_STOP_CROSSTHREAD(x, y) + #define PX_PROFILE_VALUE(x, y, z) + #define PX_PROFILE_FRAME(x, y) +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxRenderBuffer.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxRenderBuffer.h new file mode 100644 index 000000000..1ae2ef495 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxRenderBuffer.h @@ -0,0 +1,163 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RENDER_BUFFER_H +#define PX_RENDER_BUFFER_H + + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxVec3.h" +#include "foundation/PxMat33.h" +#include "foundation/PxBounds3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Default color values used for debug rendering. +*/ +struct PxDebugColor +{ + enum Enum + { + eARGB_BLACK = 0xff000000, + eARGB_RED = 0xffff0000, + eARGB_GREEN = 0xff00ff00, + eARGB_BLUE = 0xff0000ff, + eARGB_YELLOW = 0xffffff00, + eARGB_MAGENTA = 0xffff00ff, + eARGB_CYAN = 0xff00ffff, + eARGB_WHITE = 0xffffffff, + eARGB_GREY = 0xff808080, + eARGB_DARKRED = 0xff880000, + eARGB_DARKGREEN = 0xff008800, + eARGB_DARKBLUE = 0xff000088 + }; +}; + + +/** +\brief Used to store a single point and colour for debug rendering. +*/ +struct PxDebugPoint +{ + PxDebugPoint(const PxVec3& p, const PxU32& c) + : pos(p), color(c) {} + + PxVec3 pos; + PxU32 color; +}; + +/** +\brief Used to store a single line and colour for debug rendering. +*/ +struct PxDebugLine +{ + PxDebugLine(const PxVec3& p0, const PxVec3& p1, const PxU32& c) + : pos0(p0), color0(c), pos1(p1), color1(c) {} + + PxVec3 pos0; + PxU32 color0; + PxVec3 pos1; + PxU32 color1; +}; + +/** +\brief Used to store a single triangle and colour for debug rendering. +*/ +struct PxDebugTriangle +{ + PxDebugTriangle(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxU32& c) + : pos0(p0), color0(c), pos1(p1), color1(c), pos2(p2), color2(c) {} + + PxVec3 pos0; + PxU32 color0; + PxVec3 pos1; + PxU32 color1; + PxVec3 pos2; + PxU32 color2; +}; + +/** +\brief Used to store a text for debug rendering. Doesn't own 'string' array. +*/ +struct PxDebugText +{ + PxDebugText() : string(0) + { + } + + PxDebugText(const PxVec3& pos, const PxReal& sz, const PxU32& clr, const char* str) + : position(pos), size(sz), color(clr), string(str) + { + } + + PxVec3 position; + PxReal size; + PxU32 color; + const char* string; +}; + + +/** +\brief Interface for points, lines, triangles, and text buffer. +*/ +class PxRenderBuffer +{ +public: + virtual ~PxRenderBuffer() {} + + virtual PxU32 getNbPoints() const = 0; + virtual const PxDebugPoint* getPoints() const = 0; + virtual void addPoint(const PxDebugPoint& point) = 0; + + virtual PxU32 getNbLines() const = 0; + virtual const PxDebugLine* getLines() const = 0; + virtual void addLine(const PxDebugLine& line) = 0; + virtual PxDebugLine* reserveLines(const PxU32 nbLines) = 0; + virtual PxDebugPoint* reservePoints(const PxU32 nbLines) = 0; + + virtual PxU32 getNbTriangles() const = 0; + virtual const PxDebugTriangle* getTriangles() const = 0; + virtual void addTriangle(const PxDebugTriangle& triangle) = 0; + + virtual void append(const PxRenderBuffer& other) = 0; + virtual void clear() = 0; + + virtual void shift(const PxVec3& delta) = 0; + + virtual bool empty() const = 0; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxRenderOutput.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxRenderOutput.h new file mode 100644 index 000000000..25d43599d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxRenderOutput.h @@ -0,0 +1,404 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RENDER_OUTPUT_H +#define PX_RENDER_OUTPUT_H + +#include "foundation/PxMat44.h" +#include "foundation/PxBasicTemplates.h" +#include "PxRenderBuffer.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_VC +#pragma warning(push) +#pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class +#endif + + /** + Output stream to fill RenderBuffer + */ + class PxRenderOutput + { + public: + + enum Primitive + { + POINTS, + LINES, + LINESTRIP, + TRIANGLES, + TRIANGLESTRIP + }; + + PxRenderOutput(PxRenderBuffer& buffer) + : mPrim(POINTS), + mColor(0), + mVertex0(0.0f), + mVertex1(0.0f), + mVertexCount(0), + mTransform(PxIdentity), + mBuffer(buffer) + { + } + + PX_INLINE PxRenderOutput& operator<<(Primitive prim); + + PX_INLINE PxRenderOutput& operator<<(PxU32 color) ; + + PX_INLINE PxRenderOutput& operator<<(const PxMat44& transform); + + PX_INLINE PxRenderOutput& operator<<(const PxTransform& t); + + PX_INLINE PxRenderOutput& operator<<(const PxVec3& vertex); + + PX_INLINE PxDebugLine* reserveSegments(PxU32 nbSegments); + + PX_INLINE PxDebugPoint* reservePoints(PxU32 nbSegments); + + PX_INLINE void outputSegment(const PxVec3& v0, const PxVec3& v1); + + PX_INLINE PxRenderOutput& outputCapsule(PxF32 radius, PxF32 halfHeight, const PxMat44& absPose); + + private: + + PxRenderOutput& operator=(const PxRenderOutput&); + + Primitive mPrim; + PxU32 mColor; + PxVec3 mVertex0, mVertex1; + PxU32 mVertexCount; + PxMat44 mTransform; + PxRenderBuffer& mBuffer; + }; + + struct PxDebugBox + { + explicit PxDebugBox(const PxVec3& extents, bool wireframe_ = true) + : minimum(-extents), maximum(extents), wireframe(wireframe_) {} + + explicit PxDebugBox(const PxVec3& pos, const PxVec3& extents, bool wireframe_ = true) + : minimum(pos - extents), maximum(pos + extents), wireframe(wireframe_) {} + + explicit PxDebugBox(const PxBounds3& bounds, bool wireframe_ = true) + : minimum(bounds.minimum), maximum(bounds.maximum), wireframe(wireframe_) {} + + PxVec3 minimum, maximum; + bool wireframe; + }; + PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugBox& box) + { + if (box.wireframe) + { + out << PxRenderOutput::LINESTRIP; + out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z); + out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z); + out << PxVec3(box.maximum.x, box.maximum.y, box.minimum.z); + out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z); + out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z); + out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z); + out << PxVec3(box.maximum.x, box.minimum.y, box.maximum.z); + out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z); + out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z); + out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z); + out << PxRenderOutput::LINES; + out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z); + out << PxVec3(box.maximum.x, box.minimum.y, box.maximum.z); + out << PxVec3(box.maximum.x, box.maximum.y, box.minimum.z); + out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z); + out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z); + out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z); + } + else + { + out << PxRenderOutput::TRIANGLESTRIP; + out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z); // 0 + out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z); // 2 + out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z); // 1 + out << PxVec3(box.maximum.x, box.maximum.y, box.minimum.z); // 3 + out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z); // 7 + out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z); // 2 + out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z); // 6 + out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z); // 0 + out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z); // 4 + out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z); // 1 + out << PxVec3(box.maximum.x, box.minimum.y, box.maximum.z); // 5 + out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z); // 7 + out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z); // 4 + out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z); // 6 + } + return out; + } + + struct PxDebugArrow + { + PxDebugArrow(const PxVec3& pos, const PxVec3& vec) + : base(pos), tip(pos + vec), headLength(vec.magnitude()*0.15f) {} + + PxDebugArrow(const PxVec3& pos, const PxVec3& vec, PxReal headLength_) + : base(pos), tip(pos + vec), headLength(headLength_) {} + + PxVec3 base, tip; + PxReal headLength; + }; + PX_FORCE_INLINE void normalToTangents(const PxVec3& normal, PxVec3& tangent0, PxVec3& tangent1) + { + tangent0 = PxAbs(normal.x) < 0.70710678f ? PxVec3(0, -normal.z, normal.y) : PxVec3(-normal.y, normal.x, 0); + tangent0.normalize(); + tangent1 = normal.cross(tangent0); + } + PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugArrow& arrow) + { + PxVec3 t0 = arrow.tip - arrow.base, t1, t2; + + t0.normalize(); + normalToTangents(t0, t1, t2); + + const PxReal tipAngle = 0.25f; + t1 *= arrow.headLength * tipAngle; + t2 *= arrow.headLength * tipAngle * PxSqrt(3.0f); + PxVec3 headBase = arrow.tip - t0 * arrow.headLength; + + out << PxRenderOutput::LINES; + out << arrow.base << arrow.tip; + + out << PxRenderOutput::TRIANGLESTRIP; + out << arrow.tip; + out << headBase + t1 + t1; + out << headBase - t1 - t2; + out << headBase - t1 + t2; + out << arrow.tip; + out << headBase + t1 + t1; + return out; + } + + struct PxDebugBasis + { + PxDebugBasis(const PxVec3& ext, PxU32 cX = PxU32(PxDebugColor::eARGB_RED), + PxU32 cY = PxU32(PxDebugColor::eARGB_GREEN), PxU32 cZ = PxU32(PxDebugColor::eARGB_BLUE)) + : extends(ext), colorX(cX), colorY(cY), colorZ(cZ) {} + PxVec3 extends; + PxU32 colorX, colorY, colorZ; + }; + PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugBasis& basis) + { + const PxReal headLength = basis.extends.magnitude() * 0.15f; + out << basis.colorX << PxDebugArrow(PxVec3(0.0f), PxVec3(basis.extends.x, 0, 0), headLength); + out << basis.colorY << PxDebugArrow(PxVec3(0.0f), PxVec3(0, basis.extends.y, 0), headLength); + out << basis.colorZ << PxDebugArrow(PxVec3(0.0f), PxVec3(0, 0, basis.extends.z), headLength); + return out; + } + + struct PxDebugCircle + { + PxDebugCircle(PxU32 s, PxReal r) + : nSegments(s), radius(r) {} + PxU32 nSegments; + PxReal radius; + }; + PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugCircle& circle) + { + const PxF32 step = PxTwoPi / PxF32(circle.nSegments); + PxF32 angle = 0; + out << PxRenderOutput::LINESTRIP; + for (PxU32 i = 0; i < circle.nSegments; i++, angle += step) + out << PxVec3(circle.radius * PxSin(angle), circle.radius * PxCos(angle), 0); + out << PxVec3(0, circle.radius, 0); + return out; + } + + struct PxDebugArc + { + PxDebugArc(PxU32 s, PxReal r, PxReal minAng, PxReal maxAng) + : nSegments(s), radius(r), minAngle(minAng), maxAngle(maxAng) {} + PxU32 nSegments; + PxReal radius; + PxReal minAngle, maxAngle; + }; + PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugArc& arc) + { + const PxF32 step = (arc.maxAngle - arc.minAngle) / PxF32(arc.nSegments); + PxF32 angle = arc.minAngle; + out << PxRenderOutput::LINESTRIP; + for (PxU32 i = 0; i < arc.nSegments; i++, angle += step) + out << PxVec3(arc.radius * PxSin(angle), arc.radius * PxCos(angle), 0); + out << PxVec3(arc.radius * PxSin(arc.maxAngle), arc.radius * PxCos(arc.maxAngle), 0); + return out; + } + + PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(Primitive prim) + { + mPrim = prim; + mVertexCount = 0; + return *this; + } + + PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(PxU32 color) + { + mColor = color; + return *this; + } + + PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(const PxMat44& transform) + { + mTransform = transform; + return *this; + } + + PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(const PxTransform& t) + { + mTransform = PxMat44(t); + return *this; + } + + PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(const PxVec3& vertexIn) + { + // apply transformation + const PxVec3 vertex = mTransform.transform(vertexIn); + ++mVertexCount; + + // add primitive to render buffer + switch (mPrim) + { + case POINTS: + mBuffer.addPoint(PxDebugPoint(vertex, mColor)); break; + case LINES: + if (mVertexCount == 2) + { + mBuffer.addLine(PxDebugLine(mVertex0, vertex, mColor)); + mVertexCount = 0; + } + break; + case LINESTRIP: + if (mVertexCount >= 2) + mBuffer.addLine(PxDebugLine(mVertex0, vertex, mColor)); + break; + case TRIANGLES: + if (mVertexCount == 3) + { + mBuffer.addTriangle(PxDebugTriangle(mVertex1, mVertex0, vertex, mColor)); + mVertexCount = 0; + } + break; + case TRIANGLESTRIP: + if (mVertexCount >= 3) + mBuffer.addTriangle(PxDebugTriangle( + (mVertexCount & 0x1) ? mVertex0 : mVertex1, + (mVertexCount & 0x1) ? mVertex1 : mVertex0, vertex, mColor)); + break; + } + + // cache the last 2 vertices (for strips) + if (1 < mVertexCount) + { + mVertex1 = mVertex0; + mVertex0 = vertex; + } + else + { + mVertex0 = vertex; + } + return *this; + } + + PX_INLINE PxDebugLine* PxRenderOutput::reserveSegments(PxU32 nbSegments) + { + return mBuffer.reserveLines(nbSegments); + } + + PX_INLINE PxDebugPoint* PxRenderOutput::reservePoints(PxU32 nbPoints) + { + return mBuffer.reservePoints(nbPoints); + } + + // PT: using the operators is just too slow. + PX_INLINE void PxRenderOutput::outputSegment(const PxVec3& v0, const PxVec3& v1) + { + PxDebugLine* segment = mBuffer.reserveLines(1); + segment->pos0 = v0; + segment->pos1 = v1; + segment->color0 = segment->color1 = mColor; + } + + PX_INLINE PxRenderOutput& PxRenderOutput::outputCapsule(PxF32 radius, PxF32 halfHeight, const PxMat44& absPose) + { + PxRenderOutput& out = *this; + + const PxVec3 vleft2(-halfHeight, 0.0f, 0.0f); + PxMat44 left2 = absPose; + left2.column3 += PxVec4(left2.rotate(vleft2), 0.0f); + out << left2 << PxDebugArc(100, radius, PxPi, PxTwoPi); + + PxMat44 rotPose = left2; + PxSwap(rotPose.column1, rotPose.column2); + rotPose.column1 = -rotPose.column1; + out << rotPose << PxDebugArc(100, radius, PxPi, PxTwoPi); + + PxSwap(rotPose.column0, rotPose.column2); + rotPose.column0 = -rotPose.column0; + out << rotPose << PxDebugCircle(100, radius); + + const PxVec3 vright2(halfHeight, 0.0f, 0.0f); + PxMat44 right2 = absPose; + right2.column3 += PxVec4(right2.rotate(vright2), 0.0f); + out << right2 << PxDebugArc(100, radius, 0.0f, PxPi); + + rotPose = right2; + PxSwap(rotPose.column1, rotPose.column2); + rotPose.column1 = -rotPose.column1; + out << rotPose << PxDebugArc(100, radius, 0.0f, PxPi); + + PxSwap(rotPose.column0, rotPose.column2); + rotPose.column0 = -rotPose.column0; + out << rotPose << PxDebugCircle(100, radius); + + out << absPose; + out.outputSegment(absPose.transform(PxVec3(-halfHeight, radius, 0)), + absPose.transform(PxVec3(halfHeight, radius, 0))); + out.outputSegment(absPose.transform(PxVec3(-halfHeight, -radius, 0)), + absPose.transform(PxVec3(halfHeight, -radius, 0))); + out.outputSegment(absPose.transform(PxVec3(-halfHeight, 0, radius)), + absPose.transform(PxVec3(halfHeight, 0, radius))); + out.outputSegment(absPose.transform(PxVec3(-halfHeight, 0, -radius)), + absPose.transform(PxVec3(halfHeight, 0, -radius))); + + return *this; + } + +#if PX_VC +#pragma warning(pop) +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxSerialFramework.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxSerialFramework.h new file mode 100644 index 000000000..1101a1698 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxSerialFramework.h @@ -0,0 +1,385 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SERIAL_FRAMEWORK_H +#define PX_SERIAL_FRAMEWORK_H + + +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if !PX_DOXYGEN // need to exclude, confuses api doc build about duplicate declaration +typedef PxU16 PxType; +#endif + +class PxBase; +class PxSerializationContext; +class PxRepXSerializer; +class PxSerializer; +class PxPhysics; +class PxCollection; +class PxOutputStream; + +//! Default serialization alignment +#define PX_SERIAL_ALIGN 16 + +//! Serialized input data must be aligned to this value +#define PX_SERIAL_FILE_ALIGN 128 + +//! PxSerialObjectId value for objects that do not have an ID +#define PX_SERIAL_OBJECT_ID_INVALID 0 + +//! ID type for PxBase objects in a PxCollection +typedef PxU64 PxSerialObjectId; + +//! Bit to mark pointer type references, \see PxDeserializationContext +#define PX_SERIAL_REF_KIND_PTR_TYPE_BIT (1u<<31) + +//! Reference kind value for PxBase objects +#define PX_SERIAL_REF_KIND_PXBASE (0 | PX_SERIAL_REF_KIND_PTR_TYPE_BIT) + +//! Reference kind value for material indices +#define PX_SERIAL_REF_KIND_MATERIAL_IDX (1) + +//! Used to fix multi-byte characters warning from gcc for situations like: PxU32 foo = 'CCTS'; +#define PX_MAKE_FOURCC(a, b, c, d) ( (a) | ((b)<<8) | ((c)<<16) | ((d)<<24) ) + +/** +\brief Callback class used to process PxBase objects. + +\see PxSerializer::requires +*/ +class PxProcessPxBaseCallback +{ +public: + virtual ~PxProcessPxBaseCallback() {} + virtual void process(PxBase&) = 0; +}; + + +/** +\brief Binary serialization context class. + +This class is used to register reference values and write object +and object extra data during serialization. +It is mainly used by the serialization framework. Except for custom +serializable types, users should not have to worry about it. + +\see PxDeserializationContext +*/ +class PxSerializationContext +{ +public: + + /** + \brief Registers a reference value corresponding to a PxBase object. + + This method is assumed to be called in the implementation of PxSerializer::registerReferences for serialized + references that need to be resolved on deserialization. + + A reference needs to be associated with exactly one PxBase object in either the collection or the + external references collection. + + Different kinds of references are supported and need to be specified. In the most common case + (PX_SERIAL_REF_KIND_PXBASE) the PxBase object matches the reference value (which is the pointer + to the PxBase object). Integer references maybe registered as well (used for internal material + indices with PX_SERIAL_REF_KIND_MATERIAL_IDX). Other kinds could be added with the restriction that + for pointer types the kind value needs to be marked with the PX_SERIAL_REF_KIND_PTR_TYPE_BIT. + + \param[in] base PxBase object associated with the reference + \param[in] kind What kind of reference this is (PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX or custom kind) + \param[in] reference Value of reference + + \see PxDeserializationContext::resolveReference, PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX, PxSerializer::registerReferences + */ + virtual void registerReference(PxBase& base, PxU32 kind, size_t reference) = 0; + + /** + \brief Returns the collection that is being serialized. + */ + virtual const PxCollection& getCollection() const = 0; + + /** + \brief Serializes object data and object extra data. + + This function is assumed to be called within the implementation of PxSerializer::exportData and PxSerializer::exportExtraData. + + \see PxSerializer::exportData, PxSerializer::exportExtraData, PxSerializer::createObject, PxDeserializationContext::readExtraData + */ + virtual void writeData(const void* data, PxU32 size) = 0; + + /** + \brief Aligns the serialized data. + + This function is assumed to be called within the implementation of PxSerializer::exportData and PxSerializer::exportExtraData. + + \see PxSerializer::exportData, PxSerializer::exportExtraData, PxDeserializationContext::alignExtraData + */ + virtual void alignData(PxU32 alignment = PX_SERIAL_ALIGN) = 0; + + /** + \brief Helper function to write a name to the extraData if serialization is configured to save names. + + This function is assumed to be called within the implementation of PxSerializer::exportExtraData. + + \see PxSerialization::serializeCollectionToBinary, PxDeserializationContext::readName + */ + virtual void writeName(const char* name) = 0; + +protected: + + PxSerializationContext() {} + virtual ~PxSerializationContext() {} +}; + + +/** +\brief Binary deserialization context class. + +This class is used to resolve references and access extra data during deserialization. +It is mainly used by the serialization framework. Except for custom +serializable types, users should not have to worry about it. + +\see PxSerializationContext +*/ +class PxDeserializationContext +{ +public: + + /** + \brief Retrieves a pointer to a deserialized PxBase object given a corresponding deserialized reference value + + This method is assumed to be called in the implementation of PxSerializer::createObject in order + to update reference values on deserialization. + + To update a PxBase reference the corresponding deserialized pointer value needs to be provided in order to retrieve + the location of the corresponding deserialized PxBase object. (PxDeserializationContext::translatePxBase simplifies + this common case). + + For other kinds of references the reverence values need to be updated by deduction given the corresponding PxBase instance. + + \param[in] kind What kind of reference this is (PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX or custom kind) + \param[in] reference Deserialized reference value + \return PxBase object associated with the reference value + + \see PxSerializationContext::registerReference, PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX, translatePxBase + */ + virtual PxBase* resolveReference(PxU32 kind, size_t reference) const = 0; + + /** + \brief Helper function to update PxBase pointer on deserialization + + \see resolveReference, PX_SERIAL_REF_KIND_PXBASE + */ + template + void translatePxBase(T*& base) { if (base) { base = static_cast(resolveReference(PX_SERIAL_REF_KIND_PXBASE, size_t(base))); } } + + /** + \brief Helper function to read a name from the extra data during deserialization. + + This function is assumed to be called within the implementation of PxSerializer::createObject. + + \see PxSerializationContext::writeName + */ + PX_INLINE void readName(const char*& name) + { + PxU32 len = *reinterpret_cast(mExtraDataAddress); + mExtraDataAddress += sizeof(len); + name = len ? reinterpret_cast(mExtraDataAddress) : NULL; + mExtraDataAddress += len; + } + + /** + \brief Function to read extra data during deserialization. + + This function is assumed to be called within the implementation of PxSerializer::createObject. + + \see PxSerializationContext::writeData, PxSerializer::createObject + */ + template + PX_INLINE T* readExtraData(PxU32 count=1) + { + T* data = reinterpret_cast(mExtraDataAddress); + mExtraDataAddress += sizeof(T)*count; + return data; + } + + /** + \brief Function to read extra data during deserialization optionally aligning the extra data stream before reading. + + This function is assumed to be called within the implementation of PxSerializer::createObject. + + \see PxSerializationContext::writeData, PxDeserializationContext::alignExtraData, PxSerializer::createObject + */ + template + PX_INLINE T* readExtraData(PxU32 count=1) + { + alignExtraData(alignment); + return readExtraData(count); + } + + /** + \brief Function to align the extra data stream to a power of 2 alignment + + This function is assumed to be called within the implementation of PxSerializer::createObject. + + \see PxSerializationContext::alignData, PxSerializer::createObject + */ + PX_INLINE void alignExtraData(PxU32 alignment = PX_SERIAL_ALIGN) + { + size_t addr = size_t(mExtraDataAddress); + addr = (addr+alignment-1)&~size_t(alignment-1); + mExtraDataAddress = reinterpret_cast(addr); + } + +protected: + + PxDeserializationContext() {} + virtual ~PxDeserializationContext() {} + + PxU8* mExtraDataAddress; +}; + +/** +\brief Class serving as a registry for XML (RepX) and binary serializable types. + +In order to serialize and deserialize objects the application needs +to maintain an instance of this class. It can be created with +PxSerialization::createSerializationRegistry() and released with +PxSerializationRegistry::release(). + +\see PxSerialization::createSerializationRegistry +*/ +class PxSerializationRegistry +{ +public: + /************************************************************************************************/ + + /** \name Binary Serialization Functionality + */ + //\{ + + /** + \brief Register a serializer for a concrete type + + \param type PxConcreteType corresponding to the serializer + \param serializer The PxSerializer to be registered + + \see PxConcreteType, PxSerializer, PxSerializationRegistry::unregisterSerializer + */ + virtual void registerSerializer(PxType type, PxSerializer& serializer) = 0; + + /** + \brief Unregister a serializer for a concrete type, and retrieves the corresponding serializer object. + + \param type PxConcreteType for which the serializer should be unregistered + \return Unregistered serializer corresponding to type, NULL for types for which no serializer has been registered. + + \see PxConcreteType, PxSerializationRegistry::registerSerializer, PxSerializationRegistry::release + */ + virtual PxSerializer* unregisterSerializer(PxType type) = 0; + + /** + \brief Returns PxSerializer corresponding to type + + \param type PxConcreteType of the serializer requested. + \return Registered PxSerializer object corresponding to type + + \see PxConcreteType + */ + virtual const PxSerializer* getSerializer(PxType type) const = 0; + + //\} + /************************************************************************************************/ + + /** \name RepX (XML) Serialization Functionality + */ + //\{ + + /** + \brief Register a RepX serializer for a concrete type + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + \param type PxConcreteType corresponding to the RepX serializer + \param serializer The PxRepXSerializer to be registered + + \see PxConcreteType, PxRepXSerializer + */ + PX_DEPRECATED virtual void registerRepXSerializer(PxType type, PxRepXSerializer& serializer) = 0; + + /** + \brief Unregister a RepX serializer for a concrete type, and retrieves the corresponding serializer object. + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + \param type PxConcreteType for which the RepX serializer should be unregistered + \return Unregistered PxRepxSerializer corresponding to type, NULL for types for which no RepX serializer has been registered. + + \see PxConcreteType, PxSerializationRegistry::registerRepXSerializer, PxSerializationRegistry::release + */ + PX_DEPRECATED virtual PxRepXSerializer* unregisterRepXSerializer(PxType type) = 0; + + /** + \brief Returns RepX serializer given the corresponding type name + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + \param typeName Name of the type + \return Registered PxRepXSerializer object corresponding to type name + + \see PxRepXSerializer, PxTypeInfo, PX_DEFINE_TYPEINFO + */ + PX_DEPRECATED virtual PxRepXSerializer* getRepXSerializer(const char* typeName) const = 0; + + //\} + /************************************************************************************************/ + + /** + \brief Releases PxSerializationRegistry instance. + + This unregisters all PhysX and PhysXExtension serializers. Make sure to unregister all custom type + serializers before releasing the PxSerializationRegistry. + + \see PxSerializationRegistry::unregisterSerializer, PxSerializationRegistry::unregisterRepXSerializer + */ + virtual void release() = 0; + +protected: + virtual ~PxSerializationRegistry(){} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxSerializer.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxSerializer.h new file mode 100644 index 000000000..988eeadd5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxSerializer.h @@ -0,0 +1,259 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SERIALIZER_H +#define PX_SERIALIZER_H + +#include "foundation/PxAssert.h" +#include "foundation/PxAllocatorCallback.h" +#include "foundation/PxFoundation.h" +#include "common/PxSerialFramework.h" +#include "common/PxCollection.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** + \brief Serialization interface class. + + PxSerializer is used to extend serializable PxBase classes with serialization functionality. The + interface is structured such that per-class adapter instances can be used as opposed to per-object + adapter instances, avoiding per object allocations. Hence the methods take a reference to PxBase as a parameter. + + The PxSerializer interface needs to be implemented for binary or RepX serialization to work on custom + types. If only RepX serialization is needed, some methods can be left empty, as they are only needed + for binary serialization. + + A default implementation is available as a template adapter (PxSerializerDefaultAdapter). + + \see PxSerializerDefaultAdapter, PX_NEW_SERIALIZER_ADAPTER, PxSerializationRegistry::registerSerializer +*/ +class PxSerializer +{ +public: + + /**********************************************************************************************************************/ + + /** \name Basics needed for Binary- and RepX-Serialization + */ + //\{ + + /** + \brief Returns string name of dynamic type. + + \return Class name of most derived type of this object. + */ + virtual const char* getConcreteTypeName() const = 0; + + /** + \brief Adds required objects to the collection. + + This method does not add the required objects recursively, e.g. objects required by required objects. + + \see PxCollection, PxSerialization::complete + */ + virtual void requiresObjects(PxBase&, PxProcessPxBaseCallback&) const = 0; + + /** + \brief Whether the object is subordinate. + + A class is subordinate, if it can only be instantiated in the context of another class. + + \return Whether the class is subordinate + + \see PxSerialization::isSerializable + */ + virtual bool isSubordinate() const = 0; + + //\} + /**********************************************************************************************************************/ + + /**********************************************************************************************************************/ + + /** \name Functionality needed for Binary Serialization only + */ + //\{ + + /** + \brief Exports object's extra data to stream. + */ + virtual void exportExtraData(PxBase&, PxSerializationContext&) const = 0; + + /** + \brief Exports object's data to stream. + */ + virtual void exportData(PxBase&, PxSerializationContext&) const = 0; + + /** + \brief Register references that the object maintains to other objects. + */ + virtual void registerReferences(PxBase& obj, PxSerializationContext& s) const = 0; + + /** + \brief Returns size needed to create the class instance. + + \return sizeof class instance. + */ + virtual size_t getClassSize() const = 0; + + /** + \brief Create object at a given address, resolve references and import extra data. + + \param address Location at which object is created. Address is increased by the size of the created object. + \param context Context for reading external data and resolving references. + \return Created PxBase pointer (needs to be identical to address before increment). + */ + virtual PxBase* createObject(PxU8*& address, PxDeserializationContext& context) const = 0; + + //\} + /**********************************************************************************************************************/ + virtual ~PxSerializer() {} +}; + + +/** + \brief Default PxSerializer implementation. +*/ +template +class PxSerializerDefaultAdapter : public PxSerializer +{ +public: + + /************************************************************************************************/ + + /** \name Basics needed for Binary- and RepX-Serialization + */ + //\{ + + PxSerializerDefaultAdapter(const char* name) : mTypeName(name){} + + virtual const char* getConcreteTypeName() const + { + return mTypeName; + } + + virtual void requiresObjects(PxBase& obj, PxProcessPxBaseCallback& c) const + { + T& t = static_cast(obj); + t.requiresObjects(c); + } + + virtual bool isSubordinate() const + { + return false; + } + + //\} + /************************************************************************************************/ + + /** \name Functionality needed for Binary Serialization only + */ + //\{ + + // object methods + + virtual void exportExtraData(PxBase& obj, PxSerializationContext& s) const + { + T& t = static_cast(obj); + t.exportExtraData(s); + } + + virtual void exportData(PxBase& obj, PxSerializationContext& s) const + { + PxAllocatorCallback& allocator = *PxGetAllocatorCallback(); + T* copy = reinterpret_cast(allocator.allocate(sizeof(T), "TmpAllocExportData", PX_FL)); + PxMemCopy(copy, &obj, sizeof(T)); + copy->preExportDataReset(); + s.writeData(copy, sizeof(T)); + allocator.deallocate(copy); + } + + virtual void registerReferences(PxBase& obj, PxSerializationContext& s) const + { + T& t = static_cast(obj); + + s.registerReference(obj, PX_SERIAL_REF_KIND_PXBASE, size_t(&obj)); + + struct RequiresCallback : public PxProcessPxBaseCallback + { + RequiresCallback(PxSerializationContext& c) : context(c) {} + RequiresCallback& operator=(RequiresCallback&) { PX_ASSERT(0); return *this; } + void process(physx::PxBase& base) + { + context.registerReference(base, PX_SERIAL_REF_KIND_PXBASE, size_t(&base)); + } + PxSerializationContext& context; + }; + + RequiresCallback callback(s); + t.requiresObjects(callback); + } + + // class methods + + virtual size_t getClassSize() const + { + return sizeof(T); + } + + virtual PxBase* createObject(PxU8*& address, PxDeserializationContext& context) const + { + return T::createObject(address, context); + } + + + //\} + /************************************************************************************************/ + +private: + const char* mTypeName; +}; + +/** + \brief Preprocessor Macro to simplify adapter creation. + + Note: that the allocator used for creation needs to match with the one used in PX_DELETE_SERIALIZER_ADAPTER. +*/ +#define PX_NEW_SERIALIZER_ADAPTER(x) \ + *new( PxGetAllocatorCallback()->allocate(sizeof(PxSerializerDefaultAdapter), \ + "PxSerializerDefaultAdapter", PX_FL)) PxSerializerDefaultAdapter(#x) + +/** + \brief Preprocessor Macro to simplify adapter deletion. +*/ +#define PX_DELETE_SERIALIZER_ADAPTER(x) \ + { PxSerializer* s = x; if (s) { s->~PxSerializer(); PxGetAllocatorCallback()->deallocate(s); } } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxStringTable.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxStringTable.h new file mode 100644 index 000000000..f01766cf6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxStringTable.h @@ -0,0 +1,67 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_STRING_TABLE_H +#define PX_STRING_TABLE_H + +#include "foundation/PxPreprocessor.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** + * \brief a table to manage strings. Strings allocated through this object are expected to be owned by this object. + */ +class PxStringTable +{ +protected: + virtual ~PxStringTable(){} +public: + /** + * \brief Allocate a new string. + * + * \param[in] inSrc Source string, null terminated or null. + * + * \return *Always* a valid null terminated string. "" is returned if "" or null is passed in. + */ + virtual const char* allocateStr( const char* inSrc ) = 0; + + /** + * Release the string table and all the strings associated with it. + */ + virtual void release() = 0; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxTolerancesScale.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxTolerancesScale.h new file mode 100644 index 000000000..70bd5a8d6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxTolerancesScale.h @@ -0,0 +1,103 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TOLERANCES_SCALE_H +#define PX_TOLERANCES_SCALE_H + + +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Class to define the scale at which simulation runs. Most simulation tolerances are +calculated in terms of the values here. + +\note if you change the simulation scale, you will probably also wish to change the scene's +default value of gravity, and stable simulation will probably require changes to the scene's +bounceThreshold also. +*/ + +class PxTolerancesScale +{ +public: + + /** + \brief The approximate size of objects in the simulation. + + For simulating roughly human-sized in metric units, 1 is a good choice. + If simulation is done in centimetres, use 100 instead. This is used to + estimate certain length-related tolerances. + */ + PxReal length; + + /** + \brief The typical magnitude of velocities of objects in simulation. This is used to estimate + whether a contact should be treated as bouncing or resting based on its impact velocity, + and a kinetic energy threshold below which the simulation may put objects to sleep. + + For normal physical environments, a good choice is the approximate speed of an object falling + under gravity for one second. + */ + PxReal speed; + + /** + \brief constructor sets to default + + \param[in] defaultLength Default length + \param[in] defaultSpeed Default speed + */ + PX_INLINE explicit PxTolerancesScale(float defaultLength=1.0f, float defaultSpeed=10.0f); + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid (returns always true). + */ + PX_INLINE bool isValid() const; + +}; + +PX_INLINE PxTolerancesScale::PxTolerancesScale(float defaultLength, float defaultSpeed) : + length (defaultLength), + speed (defaultSpeed) + { + } + +PX_INLINE bool PxTolerancesScale::isValid() const +{ + return length>0.0f; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/PxTypeInfo.h b/Jusin154_Team3D/Engine/Public/PhysX/common/PxTypeInfo.h new file mode 100644 index 000000000..59d615bd0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/PxTypeInfo.h @@ -0,0 +1,156 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TYPE_INFO_H +#define PX_TYPE_INFO_H + + +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief an enumeration of concrete classes inheriting from PxBase + +Enumeration space is reserved for future PhysX core types, PhysXExtensions, +PhysXVehicle and Custom application types. + +\see PxBase, PxTypeInfo +*/ + +struct PxConcreteType +{ + enum Enum + { + eUNDEFINED, + + eHEIGHTFIELD, + eCONVEX_MESH, + eTRIANGLE_MESH_BVH33 PX_DEPRECATED, //!< \deprecated Will be removed together with deprecated BVH33. + eTRIANGLE_MESH_BVH34, + eTETRAHEDRON_MESH, + eDEFORMABLE_VOLUME_MESH, + eSOFTBODY_MESH PX_DEPRECATED = eDEFORMABLE_VOLUME_MESH, //!< \deprecated + + eRIGID_DYNAMIC, + eRIGID_STATIC, + eSHAPE, + eMATERIAL, + eDEFORMABLE_SURFACE_MATERIAL, + eDEFORMABLE_VOLUME_MATERIAL, + eSOFTBODY_MATERIAL PX_DEPRECATED = eDEFORMABLE_VOLUME_MATERIAL, //!< \deprecated + ePBD_MATERIAL, + eCONSTRAINT, + eAGGREGATE, + eARTICULATION_REDUCED_COORDINATE, + eARTICULATION_LINK, + eARTICULATION_JOINT_REDUCED_COORDINATE, + eARTICULATION_SPATIAL_TENDON, + eARTICULATION_FIXED_TENDON, + eARTICULATION_ATTACHMENT, + eARTICULATION_TENDON_JOINT, + eARTICULATION_MIMIC_JOINT, + ePRUNING_STRUCTURE, + eBVH, + eDEFORMABLE_VOLUME, + eSOFT_BODY PX_DEPRECATED = eDEFORMABLE_VOLUME, //!< \deprecated + eDEFORMABLE_VOLUME_STATE, + eSOFT_BODY_STATE PX_DEPRECATED = eDEFORMABLE_VOLUME_STATE, //!< \deprecated + ePBD_PARTICLESYSTEM, + eDEFORMABLE_SURFACE, + eDEFORMABLE_ATTACHMENT, + eDEFORMABLE_ELEMENT_FILTER, + ePARTICLE_BUFFER, + ePARTICLE_DIFFUSE_BUFFER, + ePARTICLE_CLOTH_BUFFER, + ePARTICLE_RIGID_BUFFER, + + ePHYSX_CORE_COUNT, + eFIRST_PHYSX_EXTENSION = 256, + eFIRST_VEHICLE_EXTENSION = 512, + eFIRST_USER_EXTENSION = 1024 + }; +}; + +/** +\brief a structure containing per-type information for types inheriting from PxBase + +\see PxBase, PxConcreteType +*/ + +template struct PxTypeInfo {}; + +#define PX_DEFINE_TYPEINFO(_name, _fastType) \ + class _name; \ + template <> struct PxTypeInfo<_name> { static const char* name() { return #_name; } enum { eFastTypeId = _fastType }; }; + +/* the semantics of the fastType are as follows: an object A can be cast to a type B if B's fastType is defined, and A has the same fastType. + * This implies that B has no concrete subclasses or superclasses. + */ + +PX_DEFINE_TYPEINFO(PxBase, PxConcreteType::eUNDEFINED) +PX_DEFINE_TYPEINFO(PxMaterial, PxConcreteType::eMATERIAL) +PX_DEFINE_TYPEINFO(PxDeformableSurfaceMaterial, PxConcreteType::eDEFORMABLE_SURFACE_MATERIAL) +PX_DEFINE_TYPEINFO(PxDeformableVolumeMaterial, PxConcreteType::eDEFORMABLE_VOLUME_MATERIAL) +PX_DEFINE_TYPEINFO(PxPBDMaterial, PxConcreteType::ePBD_MATERIAL) +PX_DEFINE_TYPEINFO(PxConvexMesh, PxConcreteType::eCONVEX_MESH) +PX_DEFINE_TYPEINFO(PxTriangleMesh, PxConcreteType::eUNDEFINED) +PX_DEFINE_TYPEINFO(PxBVH33TriangleMesh, PxConcreteType::eTRIANGLE_MESH_BVH33) +PX_DEFINE_TYPEINFO(PxBVH34TriangleMesh, PxConcreteType::eTRIANGLE_MESH_BVH34) +PX_DEFINE_TYPEINFO(PxTetrahedronMesh, PxConcreteType::eTETRAHEDRON_MESH) +PX_DEFINE_TYPEINFO(PxHeightField, PxConcreteType::eHEIGHTFIELD) +PX_DEFINE_TYPEINFO(PxActor, PxConcreteType::eUNDEFINED) +PX_DEFINE_TYPEINFO(PxRigidActor, PxConcreteType::eUNDEFINED) +PX_DEFINE_TYPEINFO(PxRigidBody, PxConcreteType::eUNDEFINED) +PX_DEFINE_TYPEINFO(PxRigidDynamic, PxConcreteType::eRIGID_DYNAMIC) +PX_DEFINE_TYPEINFO(PxRigidStatic, PxConcreteType::eRIGID_STATIC) +PX_DEFINE_TYPEINFO(PxArticulationLink, PxConcreteType::eARTICULATION_LINK) +PX_DEFINE_TYPEINFO(PxArticulationJointReducedCoordinate, PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) +PX_DEFINE_TYPEINFO(PxArticulationReducedCoordinate, PxConcreteType::eARTICULATION_REDUCED_COORDINATE) +PX_DEFINE_TYPEINFO(PxAggregate, PxConcreteType::eAGGREGATE) +PX_DEFINE_TYPEINFO(PxConstraint, PxConcreteType::eCONSTRAINT) +PX_DEFINE_TYPEINFO(PxShape, PxConcreteType::eSHAPE) +PX_DEFINE_TYPEINFO(PxPruningStructure, PxConcreteType::ePRUNING_STRUCTURE) +PX_DEFINE_TYPEINFO(PxPBDParticleSystem, PxConcreteType::ePBD_PARTICLESYSTEM) +PX_DEFINE_TYPEINFO(PxDeformableSurface, PxConcreteType::eDEFORMABLE_SURFACE) +PX_DEFINE_TYPEINFO(PxDeformableVolume, PxConcreteType::eDEFORMABLE_VOLUME) +PX_DEFINE_TYPEINFO(PxDeformableAttachment, PxConcreteType::eDEFORMABLE_ATTACHMENT) +PX_DEFINE_TYPEINFO(PxDeformableElementFilter, PxConcreteType::eDEFORMABLE_ELEMENT_FILTER) +PX_DEFINE_TYPEINFO(PxParticleBuffer, PxConcreteType::ePARTICLE_BUFFER) +PX_DEFINE_TYPEINFO(PxParticleAndDiffuseBuffer, PxConcreteType::ePARTICLE_DIFFUSE_BUFFER) +PX_DEFINE_TYPEINFO(PxParticleClothBuffer, PxConcreteType::ePARTICLE_CLOTH_BUFFER) +PX_DEFINE_TYPEINFO(PxParticleRigidBuffer, PxConcreteType::ePARTICLE_RIGID_BUFFER) + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/common/windows/PxWindowsDelayLoadHook.h b/Jusin154_Team3D/Engine/Public/PhysX/common/windows/PxWindowsDelayLoadHook.h new file mode 100644 index 000000000..064e3779d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/common/windows/PxWindowsDelayLoadHook.h @@ -0,0 +1,96 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_DELAY_LOAD_HOOK_H +#define PX_WINDOWS_DELAY_LOAD_HOOK_H + +#include "foundation/PxPreprocessor.h" +#include "common/PxPhysXCommonConfig.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + /** + \brief PxDelayLoadHook + + This is a helper class for delay loading the PhysXCommon dll and PhysXFoundation dll. + If a PhysXCommon dll or PhysXFoundation dll with a non-default file name needs to be loaded, + PxDelayLoadHook can be sub-classed to provide the custom filenames. + + Once the names are set, the instance must be set for use by PhysX.dll using PxSetPhysXDelayLoadHook(), + PhysXCooking.dll using PxSetPhysXCookingDelayLoadHook() or by PhysXCommon.dll using PxSetPhysXCommonDelayLoadHook(). + + \see PxSetPhysXDelayLoadHook(), PxSetPhysXCookingDelayLoadHook(), PxSetPhysXCommonDelayLoadHook() + */ + class PxDelayLoadHook + { + public: + PxDelayLoadHook() {} + virtual ~PxDelayLoadHook() {} + + virtual const char* getPhysXFoundationDllName() const = 0; + + virtual const char* getPhysXCommonDllName() const = 0; + + protected: + private: + }; + + /** + \brief Sets delay load hook instance for PhysX dll. + + \param[in] hook Delay load hook. + + \see PxDelayLoadHook + */ + PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXDelayLoadHook(const physx::PxDelayLoadHook* hook); + + /** + \brief Sets delay load hook instance for PhysXCooking dll. + + \param[in] hook Delay load hook. + + \see PxDelayLoadHook + */ + PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXCookingDelayLoadHook(const physx::PxDelayLoadHook* hook); + + /** + \brief Sets delay load hook instance for PhysXCommon dll. + + \param[in] hook Delay load hook. + + \see PxDelayLoadHook + */ + PX_C_EXPORT PX_PHYSX_COMMON_API void PX_CALL_CONV PxSetPhysXCommonDelayLoadHook(const physx::PxDelayLoadHook* hook); + +#if !PX_DOXYGEN +} // namespace physx +#endif +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVH33MidphaseDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVH33MidphaseDesc.h new file mode 100644 index 000000000..26729fa02 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVH33MidphaseDesc.h @@ -0,0 +1,110 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BVH_33_MIDPHASE_DESC_H +#define PX_BVH_33_MIDPHASE_DESC_H + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\deprecated This is only used for BVH33 which is deprecated and will be removed in a future version. Use BVH34 instead. + +\brief Enumeration for mesh cooking hints. +*/ +struct PX_DEPRECATED PxMeshCookingHint +{ + enum Enum + { + eSIM_PERFORMANCE = 0, //!< Default value. Favors higher quality hierarchy with higher runtime performance over cooking speed. + eCOOKING_PERFORMANCE = 1 //!< Enables fast cooking path at the expense of somewhat lower quality hierarchy construction. + }; +}; + +/** +\deprecated BVH33 is deprecated and will be removed in a future version. Use BVH34 instead. + +\brief Structure describing parameters affecting BVH33 midphase mesh structure. + +\see PxCookingParams, PxMidphaseDesc +*/ +struct PX_DEPRECATED PxBVH33MidphaseDesc +{ + /** + \brief Controls the trade-off between mesh size and runtime performance. + + Using a value of 1.0 will produce a larger cooked mesh with generally higher runtime performance, + using 0.0 will produce a smaller cooked mesh, with generally lower runtime performance. + + Values outside of [0,1] range will be clamped and cause a warning when any mesh gets cooked. + + Default value: 0.55 + Range: [0.0f, 1.0f] + */ + PxF32 meshSizePerformanceTradeOff; + + /** + \brief Mesh cooking hint. Used to specify mesh hierarchy construction preference. + + Default value: PxMeshCookingHint::eSIM_PERFORMANCE + */ + PxMeshCookingHint::Enum meshCookingHint; + + /** + \brief Desc initialization to default value. + */ + void setToDefault() + { + meshSizePerformanceTradeOff = 0.55f; + meshCookingHint = PxMeshCookingHint::eSIM_PERFORMANCE; + } + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + bool isValid() const + { + if(meshSizePerformanceTradeOff < 0.0f || meshSizePerformanceTradeOff > 1.0f) + return false; + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVH34MidphaseDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVH34MidphaseDesc.h new file mode 100644 index 000000000..7b5d96e2d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVH34MidphaseDesc.h @@ -0,0 +1,124 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BVH_34_MIDPHASE_DESC_H +#define PX_BVH_34_MIDPHASE_DESC_H + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Desired build strategy for PxMeshMidPhase::eBVH34 +*/ +struct PxBVH34BuildStrategy +{ + enum Enum + { + eFAST = 0, //!< Fast build strategy. Fast build speed, good runtime performance in most cases. Recommended for runtime mesh cooking. + eDEFAULT = 1, //!< Default build strategy. Medium build speed, good runtime performance in all cases. + eSAH = 2, //!< SAH build strategy. Slower builds, slightly improved runtime performance in some cases. + + eLAST + }; +}; + + +/** + +\brief Structure describing parameters affecting BVH34 midphase mesh structure. + +\see PxCookingParams, PxMidphaseDesc +*/ +struct PxBVH34MidphaseDesc +{ + /** + \brief Mesh cooking hint for max primitives per leaf limit. + Less primitives per leaf produces larger meshes with better runtime performance + and worse cooking performance. More triangles per leaf results in faster cooking speed and + smaller mesh sizes, but with worse runtime performance. + + Default value: 4 + Range: <2, 15> + */ + PxU32 numPrimsPerLeaf; + + /** + \brief Desired build strategy for the BVH + + Default value: eDEFAULT + */ + PxBVH34BuildStrategy::Enum buildStrategy; + + /** + \brief Whether the tree should be quantized or not + + Quantized trees use up less memory, but the runtime dequantization (to retrieve the node bounds) might have + a measurable performance cost. In most cases the cost is too small to matter, and using less memory is more + important. Hence, the default is true. + + One important use case for non-quantized trees is deformable meshes. The refit function for the BVH is not + supported for quantized trees. + + Default value: true + */ + bool quantized; + + /** + \brief Desc initialization to default value. + */ + void setToDefault() + { + numPrimsPerLeaf = 4; + buildStrategy = PxBVH34BuildStrategy::eDEFAULT; + quantized = true; + } + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + bool isValid() const + { + if(numPrimsPerLeaf < 2 || numPrimsPerLeaf > 15) + return false; + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVHDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVHDesc.h new file mode 100644 index 000000000..236a2bfdf --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxBVHDesc.h @@ -0,0 +1,135 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BVH_DESC_H +#define PX_BVH_DESC_H + +#include "common/PxCoreUtilityTypes.h" +#include "foundation/PxTransform.h" +#include "foundation/PxBounds3.h" +#include "geometry/PxBVHBuildStrategy.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Descriptor class for #PxBVH. + +\see PxBVH +*/ +class PxBVHDesc +{ +public: + PX_INLINE PxBVHDesc(); + + /** + \brief Pointer to first bounding box. + */ + PxBoundedData bounds; + + /** + \brief Bounds enlargement + + Passed bounds are slightly enlarged before creating the BVH. This is done to avoid numerical issues when + e.g. raycasts just graze the bounds. The performed operation is: + + extents = (bounds.maximum - bounds.minimum)/2 + enlagedBounds.minimum = passedBounds.minium - extents * enlargement + enlagedBounds.maximum = passedBounds.maxium + extents * enlargement + + Users can pass pre-enlarged bounds to the BVH builder, in which case just set the enlargement value to zero. + + Default value: 0.01 + */ + float enlargement; + + /** + \brief Max primitives per leaf limit. + + Range: [0, 16)
+ Default value: 4 + */ + PxU32 numPrimsPerLeaf; + + /** + \brief Desired build strategy for the BVH + + Default value: eDEFAULT + */ + PxBVHBuildStrategy::Enum buildStrategy; + + /** + \brief Initialize the BVH descriptor + */ + PX_INLINE void setToDefault(); + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + PX_INLINE bool isValid() const; + +protected: +}; + +PX_INLINE PxBVHDesc::PxBVHDesc() : enlargement(0.01f), numPrimsPerLeaf(4), buildStrategy(PxBVHBuildStrategy::eDEFAULT) +{ +} + +PX_INLINE void PxBVHDesc::setToDefault() +{ + *this = PxBVHDesc(); +} + +PX_INLINE bool PxBVHDesc::isValid() const +{ + // Check BVH desc data + if(!bounds.data) + return false; + if(bounds.stride < sizeof(PxBounds3)) //should be at least one bounds' worth of data + return false; + + if(bounds.count == 0) + return false; + + if(enlargement<0.0f) + return false; + + if(numPrimsPerLeaf>=16) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxConvexMeshDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxConvexMeshDesc.h new file mode 100644 index 000000000..8dfd22501 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxConvexMeshDesc.h @@ -0,0 +1,333 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONVEX_MESH_DESC_H +#define PX_CONVEX_MESH_DESC_H + +#include "foundation/PxVec3.h" +#include "foundation/PxFlags.h" +#include "common/PxCoreUtilityTypes.h" +#include "geometry/PxConvexMesh.h" +#include "PxSDFDesc.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +/** +\brief Flags which describe the format and behavior of a convex mesh. +*/ +struct PxConvexFlag +{ + enum Enum + { + /** + Denotes the use of 16-bit vertex indices in PxConvexMeshDesc::triangles or PxConvexMeshDesc::polygons. + (otherwise, 32-bit indices are assumed) + \see #PxConvexMeshDesc.indices + */ + e16_BIT_INDICES = (1<<0), + + /** + Automatically recomputes the hull from the vertices. If this flag is not set, you must provide the entire geometry manually. + + \note For the specific algorithm used in hull computation, please see PxConvexMeshCookingType. + + \see PxConvexMeshCookingType + */ + eCOMPUTE_CONVEX = (1<<1), + + /** + \brief Checks and removes almost zero-area triangles during convex hull computation. + The rejected area size is specified in PxCookingParams::areaTestEpsilon + + \note This flag is only used in combination with eCOMPUTE_CONVEX. + + \see PxCookingParams PxCookingParams::areaTestEpsilon + */ + eCHECK_ZERO_AREA_TRIANGLES = (1<<2), + + /** + \brief Quantizes the input vertices using the k-means clustering + + \note The input vertices are quantized to PxConvexMeshDesc::quantizedCount + see http://en.wikipedia.org/wiki/K-means_clustering + + */ + eQUANTIZE_INPUT = (1 << 3), + + /** + \brief Disables the convex mesh validation to speed-up hull creation. Please use separate validation + function in checked/debug builds. Creating a convex mesh with invalid input data without prior validation + may result in undefined behavior. + + \see PxCooking::validateConvexMesh + */ + eDISABLE_MESH_VALIDATION = (1 << 4), + + /** + \brief Enables plane shifting vertex limit algorithm. + + Plane shifting is an alternative algorithm for the case when the computed hull has more vertices + than the specified vertex limit. + + The default algorithm computes the full hull, and an OBB around the input vertices. This OBB is then sliced + with the hull planes until the vertex limit is reached.The default algorithm requires the vertex limit + to be set to at least 8, and typically produces results that are much better quality than are produced + by plane shifting. + + When plane shifting is enabled, the hull computation stops when vertex limit is reached. The hull planes + are then shifted to contain all input vertices, and the new plane intersection points are then used to + generate the final hull with the given vertex limit.Plane shifting may produce sharp edges to vertices + very far away from the input cloud, and does not guarantee that all input vertices are inside the resulting + hull.However, it can be used with a vertex limit as low as 4. + */ + ePLANE_SHIFTING = (1 << 5), + + /** + \brief Inertia tensor computation is faster using SIMD code, but the precision is lower, which may result + in incorrect inertia for very thin hulls. + */ + eFAST_INERTIA_COMPUTATION = (1 << 6), + + /** + \brief Convex hull input vertices are shifted to be around origin to provide better computation stability. + It is recommended to provide input vertices around the origin, otherwise use this flag to improve + numerical stability. + \note Is used only with eCOMPUTE_CONVEX flag. + */ + eSHIFT_VERTICES = (1 << 8) + }; +}; + +/** +\brief collection of set bits defined in PxConvexFlag. + +\see PxConvexFlag +*/ +typedef PxFlags PxConvexFlags; +PX_FLAGS_OPERATORS(PxConvexFlag::Enum,PxU16) + +/** +\brief Descriptor class for #PxConvexMesh. +\note The number of vertices and the number of convex polygons in a cooked convex mesh is limited to 256. +\note The number of vertices and the number of convex polygons in a GPU compatible convex mesh is limited to 64, +and the number of faces per vertex is limited to 32. + +\see PxConvexMesh PxConvexMeshGeometry PxShape PxPhysics.createConvexMesh() + +*/ +class PxConvexMeshDesc +{ +public: + + /** + \brief Vertex positions data in PxBoundedData format. + + Default: NULL + */ + PxBoundedData points; + + /** + \brief Polygons data in PxBoundedData format. +

Pointer to first polygon.

+ + Default: NULL + + \see PxHullPolygon + */ + PxBoundedData polygons; + + /** + \brief Polygon indices data in PxBoundedData format. +

Pointer to first index.

+ + Default: NULL + +

This is declared as a void pointer because it is actually either an PxU16 or a PxU32 pointer.

+ + \see PxHullPolygon PxConvexFlag::e16_BIT_INDICES + */ + PxBoundedData indices; + + /** + \brief Flags bits, combined from values of the enum ::PxConvexFlag + + Default: 0 + */ + PxConvexFlags flags; + + /** + \brief Limits the number of vertices of the result convex mesh. Hard maximum limit is 255 + and minimum limit is 4 if PxConvexFlag::ePLANE_SHIFTING is used, otherwise the minimum + limit is 8. + + \note The please see PxConvexFlag::ePLANE_SHIFTING for algorithm explanation + \note The maximum limit for GPU compatible convex meshes is 64. + + \see PxConvexFlag::ePLANE_SHIFTING + + Range: [4, 255]
+ Default: 255 + */ + PxU16 vertexLimit; + + /** + \brief Limits the number of polygons of the result convex mesh. Hard maximum limit is 255 + and minimum limit is 4. + + \note The maximum limit for GPU compatible convex meshes is 64. + + Range: [4, 255]
+ Default: 255 + */ + PxU16 polygonLimit; + + /** + \brief Maximum number of vertices after quantization. The quantization is done during the vertex cleaning phase. + The quantization is applied when PxConvexFlag::eQUANTIZE_INPUT is specified. + + \see PxConvexFlag::eQUANTIZE_INPUT + + Range: [4, 65535]
+ Default: 255 + */ + PxU16 quantizedCount; + + /** + \brief SDF descriptor. When this descriptor is set, signed distance field is calculated for this convex mesh. + + Default: NULL + */ + PxSDFDesc* sdfDesc; + + /** + \brief constructor sets to default. + */ + PX_INLINE PxConvexMeshDesc(); + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + + /** + \brief Returns true if the descriptor is valid. + + \return True if the current settings are valid + */ + PX_INLINE bool isValid() const; +}; + +PX_INLINE PxConvexMeshDesc::PxConvexMeshDesc() //constructor sets to default +: vertexLimit(255), polygonLimit(255), quantizedCount(255), sdfDesc(NULL) +{ + +} + +PX_INLINE void PxConvexMeshDesc::setToDefault() +{ + *this = PxConvexMeshDesc(); +} + +PX_INLINE bool PxConvexMeshDesc::isValid() const +{ + // Check geometry + if(points.count < 3 || //at least 1 trig's worth of points + (points.count > 0xffff && flags & PxConvexFlag::e16_BIT_INDICES)) + return false; + if(!points.data) + return false; + if(points.stride < sizeof(PxVec3)) //should be at least one point's worth of data + return false; + if (quantizedCount < 4) + return false; + + // Check topology + if(polygons.data) + { + if(polygons.count < 4) // we require 2 neighbors for each vertex - 4 polygons at least + return false; + + if(!indices.data) // indices must be provided together with polygons + return false; + + PxU32 limit = (flags & PxConvexFlag::e16_BIT_INDICES) ? sizeof(PxU16) : sizeof(PxU32); + if(indices.stride < limit) + return false; + + limit = sizeof(PxHullPolygon); + if(polygons.stride < limit) + return false; + } + else + { + // We can compute the hull from the vertices + if(!(flags & PxConvexFlag::eCOMPUTE_CONVEX)) + return false; // If the mesh is convex and we're not allowed to compute the hull, + // you have to provide it completely (geometry & topology). + } + + if((flags & PxConvexFlag::ePLANE_SHIFTING) && vertexLimit < 4) + { + return false; + } + + if (!(flags & PxConvexFlag::ePLANE_SHIFTING) && vertexLimit < 8) + { + return false; + } + + if(vertexLimit > 255) + { + return false; + } + + if (polygonLimit < 4) + { + return false; + } + + if (polygonLimit > 255) + { + return false; + } + + if (sdfDesc && !sdfDesc->isValid()) + { + return false; + } + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxCooking.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxCooking.h new file mode 100644 index 000000000..4bfef7c9c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxCooking.h @@ -0,0 +1,908 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_COOKING_H +#define PX_COOKING_H +#include "common/PxPhysXCommonConfig.h" +#include "common/PxTolerancesScale.h" +#include "cooking/Pxc.h" + +#include "cooking/PxConvexMeshDesc.h" +#include "cooking/PxTriangleMeshDesc.h" +#include "cooking/PxTetrahedronMeshDesc.h" +#include "cooking/PxMidphaseDesc.h" +#include "cooking/PxBVHDesc.h" +#include "geometry/PxTriangleMesh.h" +#include "geometry/PxTetrahedronMesh.h" +#include "geometry/PxBVH.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxInsertionCallback; +class PxFoundation; +class PxAllocatorCallback; +class PxHeightFieldDesc; + +/** +\brief Result from convex cooking. +*/ +struct PxConvexMeshCookingResult +{ + enum Enum + { + /** + \brief Convex mesh cooking succeeded. + */ + eSUCCESS, + + /** + \brief Convex mesh cooking failed, algorithm couldn't find 4 initial vertices without a small triangle. + + \see PxCookingParams::areaTestEpsilon PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES + */ + eZERO_AREA_TEST_FAILED, + + /** + \brief Convex mesh cooking succeeded, but the algorithm has reached the 255 polygons limit. + The produced hull does not contain all input vertices. Try to simplify the input vertices + or try to use the eINFLATE_CONVEX or the eQUANTIZE_INPUT flags. + + \see PxConvexFlag::eINFLATE_CONVEX PxConvexFlag::eQUANTIZE_INPUT + */ + ePOLYGONS_LIMIT_REACHED, + + /** + \brief Something unrecoverable happened. Check the error stream to find out what. + */ + eFAILURE, + + /** + \brief Convex mesh cooking succeeded, but the algorithm could not make the mesh GPU compatible because the + in-sphere radius is more than 100x smaller than the largest extent. Collision detection for any pair involving + this convex mesh will fall back to CPU. + */ + eNON_GPU_COMPATIBLE + }; +}; + +/** \brief Enumeration for convex mesh cooking algorithms. */ +struct PxConvexMeshCookingType +{ + enum Enum + { + /** + \brief The Quickhull algorithm constructs the hull from the given input points. The resulting hull + will only contain a subset of the input points. + + */ + eQUICKHULL + }; +}; + +/** +\brief Result from triangle mesh cooking +*/ +struct PxTriangleMeshCookingResult +{ + enum Enum + { + /** + \brief Everything is A-OK. + */ + eSUCCESS = 0, + + /** + \brief A triangle is too large for well-conditioned results. Tessellate the mesh for better behavior, see the user guide section on cooking for more details. + */ + eLARGE_TRIANGLE, + + /** + \brief The mesh cleaning operation removed all triangles, resulting in an empty mesh. + */ + eEMPTY_MESH, + + /** + \brief Something unrecoverable happened. Check the error stream to find out what. + */ + eFAILURE + }; +}; + +/** +\brief Enum for the set of mesh pre-processing parameters. +*/ +struct PxMeshPreprocessingFlag +{ + enum Enum + { + /** + \brief When set, mesh welding is performed. See PxCookingParams::meshWeldTolerance. Mesh cleaning must be enabled. + */ + eWELD_VERTICES = 1 << 0, + + /** + \brief When set, mesh cleaning is disabled. This makes cooking faster. + + When mesh cleaning is disabled, mesh welding is also disabled. + + It is recommended to use only meshes that passed during validateTriangleMesh. + */ + eDISABLE_CLEAN_MESH = 1 << 1, + + /** + \brief When set, active edges are not computed and just enabled for all edges. This makes cooking faster but contact generation slower. + */ + eDISABLE_ACTIVE_EDGES_PRECOMPUTE = 1 << 2, + + /** + \brief When set, 32-bit indices will always be created regardless of triangle count. + + \note By default mesh will be created with 16-bit indices for triangle count <= 0xFFFF and 32-bit otherwise. + */ + eFORCE_32BIT_INDICES = 1 << 3, + + /** + \brief When set, a list of triangles will be created for each associated vertex in the mesh. + */ + eENABLE_VERT_MAPPING = 1 << 4, + + /** + \brief When set, inertia data is calculated for the mesh, assuming unit density. + */ + eENABLE_INERTIA = 1 << 5 + }; +}; + +typedef PxFlags PxMeshPreprocessingFlags; + +/** +\brief Structure describing parameters affecting mesh cooking. + +\see PxSetCookingParams() PxGetCookingParams() +*/ +struct PxCookingParams +{ + /** + \brief Zero-size area epsilon used in convex hull computation. + + If the area of a triangle of the hull is below this value, the triangle will be rejected. This test + is done only if PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES is used. + + \see PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES + + Default value: 0.06f*PxTolerancesScale.length*PxTolerancesScale.length + + Range: (0.0f, PX_MAX_F32) + */ + float areaTestEpsilon; + + /** + \brief Plane tolerance used in convex hull computation. + + The value is used during hull construction. When a new point is about to be added to the hull it + gets dropped when the point is closer to the hull than the planeTolerance. The planeTolerance + is increased according to the hull size. + + If 0.0f is set all points are accepted when the convex hull is created. This may lead to edge cases + where the new points may be merged into an existing polygon and the polygons plane equation might + slightly change therefore. This might lead to failures during polygon merging phase in the hull computation. + + It is recommended to use the default value, however if it is required that all points needs to be + accepted or huge thin convexes are created, it might be required to lower the default value. + + \note The plane tolerance is used only within PxConvexMeshCookingType::eQUICKHULL algorithm. + + Default value: 0.0007f + + Range: <0.0f, PX_MAX_F32) + */ + float planeTolerance; + + /** + \brief Convex hull creation algorithm. + + Default value: PxConvexMeshCookingType::eQUICKHULL + + \see PxConvexMeshCookingType + */ + PxConvexMeshCookingType::Enum convexMeshCookingType; + + /** + \brief When true, the face remap table is not created. This saves a significant amount of memory, but the SDK will + not be able to provide the remap information for internal mesh triangles returned by collisions, + sweeps or raycasts hits. + + Default value: false + */ + bool suppressTriangleMeshRemapTable; + + /** + \brief When true, the triangle adjacency information is created. You can get the adjacency triangles + for a given triangle from getTriangle. + + Default value: false + */ + bool buildTriangleAdjacencies; + + /** + \brief When true, additional information required for GPU-accelerated rigid body simulation is created. This can increase memory usage and cooking times for convex meshes and triangle meshes. + + Default value: false + */ + bool buildGPUData; + + /** + \brief Tolerance scale is used to check if cooked triangles are not too huge. This check will help with simulation stability. + + \note The PxTolerancesScale values have to match the values used when creating a PxPhysics or PxScene instance. + + \see PxTolerancesScale + */ + PxTolerancesScale scale; + + /** + \brief Mesh pre-processing parameters. Used to control options like whether the mesh cooking performs vertex welding before cooking. + + Default value: 0 + */ + PxMeshPreprocessingFlags meshPreprocessParams; + + /** + \brief Mesh weld tolerance. If mesh welding is enabled, this controls the distance at which vertices are welded. + If mesh welding is not enabled, this value defines the acceptance distance for mesh validation. Provided no two vertices are within this distance, the mesh is considered to be + clean. If not, a warning will be emitted. Having a clean, welded mesh is required to achieve the best possible performance. + + The default vertex welding uses a snap-to-grid approach. This approach effectively truncates each vertex to integer values using meshWeldTolerance. + Once these snapped vertices are produced, all vertices that snap to a given vertex on the grid are remapped to reference a single vertex. Following this, + all triangles' indices are remapped to reference this subset of clean vertices. It should be noted that the vertices that we do not alter the + position of the vertices; the snap-to-grid is only performed to identify nearby vertices. + + The mesh validation approach also uses the same snap-to-grid approach to identify nearby vertices. If more than one vertex snaps to a given grid coordinate, + we ensure that the distance between the vertices is at least meshWeldTolerance. If this is not the case, a warning is emitted. + + Default value: 0.0 + */ + PxReal meshWeldTolerance; + + /** + \brief "Zero-area" epsilon used in mesh cleaning. + + This is similar to areaTestEpsilon, but for the mesh cleaning operation. + + If the area of a triangle is below this value, the triangle will be removed. This is only done when mesh cleaning is enabled, + i.e. when PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH is not set. + + Default value is 0.0f to be consistent with previous PhysX versions, which only removed triangles whose area + was exactly zero. + + \see PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH + + Default value: 0.0f + + Range: (0.0f, PX_MAX_F32) + */ + PxReal meshAreaMinLimit; + + /** + \brief Maximum edge length. + + If an edge of a triangle is above this value, a warning is sent to the error stream. This is only a check, + corresponding triangles are not removed. + + This is only done when mesh cleaning is enabled, i.e. when PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH is not set. + + Default value is 500.0f to be consistent with previous PhysX versions. This value is internally multiplied by + PxTolerancesScale::length before being used. Use 0.0f to disable the checks. + + \see PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH + + Default value: 500.0f + + Range: (0.0f, PX_MAX_F32) + */ + PxReal meshEdgeLengthMaxLimit; + + /** + \brief Controls the desired midphase desc structure for triangle meshes. + + \see PxBVH33MidphaseDesc, PxBVH34MidphaseDesc, PxMidphaseDesc + + Default value: PxMeshMidPhase::eBVH34 + */ + PxMidphaseDesc midphaseDesc; + + /** + \brief Vertex limit beyond which additional acceleration structures are computed for each convex mesh. Increase that limit to reduce memory usage. + Computing the extra structures all the time does not guarantee optimal performance. There is a per-platform break-even point below which the + extra structures actually hurt performance. + + Default value: 32 + */ + PxU32 gaussMapLimit; + + /** + \brief Maximum mass ratio allowed on vertices touched by a single tet. If a any tetrahedron exceeds the mass ratio, the masses will get smoothed locally + until the maximum mass ratio is matched. Value should not be below 1. Smoothing might not fully converge for values <1.5. The smaller the maximum + allowed ratio, the better the stability during simulation. + + Default value: FLT_MAX + */ + PxReal maxWeightRatioInTet; + + PxCookingParams(const PxTolerancesScale& sc): + areaTestEpsilon (0.06f*sc.length*sc.length), + planeTolerance (0.0007f), + convexMeshCookingType (PxConvexMeshCookingType::eQUICKHULL), + suppressTriangleMeshRemapTable (false), + buildTriangleAdjacencies (false), + buildGPUData (false), + scale (sc), + meshPreprocessParams (0), + meshWeldTolerance (0.0f), + meshAreaMinLimit (0.0f), + meshEdgeLengthMaxLimit (500.0f), + gaussMapLimit (32), + maxWeightRatioInTet (FLT_MAX) + { + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +// Immediate cooking + +/** +\brief Gets standalone object insertion interface. + +This interface allows the creation of standalone objects that can exist without a PxPhysics or PxScene object. + +\see PxCreateTriangleMesh PxCreateHeightfield PxCreateTetrahedronMesh PxCreateBVH +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxInsertionCallback* PxGetStandaloneInsertionCallback(); + +// ==== BVH ==== + +/** +\brief Cooks a bounding volume hierarchy. The results are written to the stream. + +PxCookBVH() allows a BVH description to be cooked into a binary stream +suitable for loading and performing BVH detection at runtime. + +\param[in] desc The BVH descriptor. +\param[in] stream User stream to output the cooked data. +\return true on success. + +\see PxBVH PxRigidActorExt::getRigidActorShapeLocalBoundsList +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookBVH(const physx::PxBVHDesc& desc, physx::PxOutputStream& stream); + +/** +\brief Cooks and creates a bounding volume hierarchy without going through a stream. + +\note This method does the same as PxCookBVH, but the produced BVH is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback() +or PxGetStandaloneInsertionCallback(). + +\param[in] desc The BVH descriptor. +\param[in] insertionCallback The insertion interface. +\return PxBVH pointer on success + +\see PxCookBVH() PxInsertionCallback +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxBVH* PxCreateBVH(const physx::PxBVHDesc& desc, physx::PxInsertionCallback& insertionCallback); + +/** +\brief Cooks and creates a bounding volume hierarchy without going through a stream. Convenience function for standalone objects. + +\note This method does the same as PxCookBVH, but the produced BVH is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\param[in] desc The BVH descriptor. +\return PxBVH pointer on success + +\see PxCookBVH() PxInsertionCallback +*/ +PX_FORCE_INLINE physx::PxBVH* PxCreateBVH(const physx::PxBVHDesc& desc) +{ + return PxCreateBVH(desc, *PxGetStandaloneInsertionCallback()); +} + +// ==== Heightfield ==== + +/** +\brief Cooks a heightfield. The results are written to the stream. + +To create a heightfield object there is an option to precompute some of calculations done while loading the heightfield data. + +PxCookHeightField() allows a heightfield description to be cooked into a binary stream +suitable for loading and performing collision detection at runtime. + +\param[in] desc The heightfield descriptor to read the HF from. +\param[in] stream User stream to output the cooked data. +\return true on success + +\see PxPhysics.createHeightField() +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookHeightField(const physx::PxHeightFieldDesc& desc, physx::PxOutputStream& stream); + +/** +\brief Cooks and creates a heightfield mesh and inserts it into PxPhysics. + +\param[in] desc The heightfield descriptor to read the HF from. +\param[in] insertionCallback The insertion interface from PxPhysics. +\return PxHeightField pointer on success + +\see PxCookHeightField() PxPhysics.createHeightField() PxInsertionCallback +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxHeightField* PxCreateHeightField(const physx::PxHeightFieldDesc& desc, physx::PxInsertionCallback& insertionCallback); + +/** +\brief Cooks and creates a heightfield mesh and inserts it into PxPhysics. Convenience function for standalone objects. + +\param[in] desc The heightfield descriptor to read the HF from. +\return PxHeightField pointer on success + +\see PxCookHeightField() PxPhysics.createHeightField() PxInsertionCallback +*/ +PX_FORCE_INLINE physx::PxHeightField* PxCreateHeightField(const physx::PxHeightFieldDesc& desc) +{ + return PxCreateHeightField(desc, *PxGetStandaloneInsertionCallback()); +} + +// ==== Convex meshes ==== + +/** +\brief Cooks a convex mesh. The results are written to the stream. + +To create a triangle mesh object it is necessary to first 'cook' the mesh data into +a form which allows the SDK to perform efficient collision detection. + +PxCookConvexMesh() allows a mesh description to be cooked into a binary stream +suitable for loading and performing collision detection at runtime. + +\note The number of vertices and the number of convex polygons in a cooked convex mesh is limited to 255. +\note If those limits are exceeded in either the user-provided data or the final cooked mesh, an error is reported. + +\param[in] params The cooking parameters +\param[in] desc The convex mesh descriptor to read the mesh from. +\param[in] stream User stream to output the cooked data. +\param[out] condition Result from convex mesh cooking. +\return true on success. + +\see PxCookTriangleMesh() PxConvexMeshCookingResult::Enum +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc, physx::PxOutputStream& stream, physx::PxConvexMeshCookingResult::Enum* condition=NULL); + +/** +\brief Cooks and creates a convex mesh without going through a stream. + +\note This method does the same as PxCookConvexMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback() +or PxGetStandaloneInsertionCallback(). + +\param[in] params The cooking parameters +\param[in] desc The convex mesh descriptor to read the mesh from. +\param[in] insertionCallback The insertion interface from PxPhysics. +\param[out] condition Result from convex mesh cooking. +\return PxConvexMesh pointer on success + +\see PxCookConvexMesh() PxInsertionCallback +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxConvexMesh* PxCreateConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc, physx::PxInsertionCallback& insertionCallback, physx::PxConvexMeshCookingResult::Enum* condition=NULL); + +/** +\brief Cooks and creates a convex mesh without going through a stream. Convenience function for standalone objects. + +\note This method does the same as cookConvexMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\param[in] params The cooking parameters +\param[in] desc The convex mesh descriptor to read the mesh from. +\return PxConvexMesh pointer on success + +\see PxCookConvexMesh() PxInsertionCallback +*/ +PX_FORCE_INLINE physx::PxConvexMesh* PxCreateConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc) +{ + return PxCreateConvexMesh(params, desc, *PxGetStandaloneInsertionCallback()); +} + +/** +\brief Verifies if the convex mesh is valid. Prints an error message for each inconsistency found. + +The convex mesh descriptor must contain an already created convex mesh - the vertices, indices and polygons must be provided. + +\note This function should be used if PxConvexFlag::eDISABLE_MESH_VALIDATION is planned to be used in release builds. + +\param[in] params The cooking parameters +\param[in] desc The convex mesh descriptor to read the mesh from. + +\return true if all the validity conditions hold, false otherwise. + +\see PxCookConvexMesh() +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxValidateConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc); + +/** +\brief Compute hull polygons from given vertices and triangles. Polygons are needed for PxConvexMeshDesc rather than triangles. + +Please note that the resulting polygons may have different number of vertices. Some vertices may be removed. +The output vertices, indices and polygons must be used to construct a hull. + +The provided PxAllocatorCallback does allocate the out arrays. It is the user responsibility to deallocated those arrays. + +\param[in] params The cooking parameters +\param[in] mesh Simple triangle mesh containing vertices and triangles used to compute polygons. +\param[in] inCallback Memory allocator for out array allocations. +\param[out] nbVerts Number of vertices used by polygons. +\param[out] vertices Vertices array used by polygons. +\param[out] nbIndices Number of indices used by polygons. +\param[out] indices Indices array used by polygons. +\param[out] nbPolygons Number of created polygons. +\param[out] hullPolygons Polygons array. +\return true on success + +\see PxCookConvexMesh() PxConvexFlags PxConvexMeshDesc PxSimpleTriangleMesh +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxComputeHullPolygons(const physx::PxCookingParams& params, const physx::PxSimpleTriangleMesh& mesh, physx::PxAllocatorCallback& inCallback, physx::PxU32& nbVerts, physx::PxVec3*& vertices, + physx::PxU32& nbIndices, physx::PxU32*& indices, physx::PxU32& nbPolygons, physx::PxHullPolygon*& hullPolygons); + +// ==== Triangle meshes ==== + +/** +\brief Verifies if the triangle mesh is valid. Prints an error message for each inconsistency found. + +The following conditions are true for a valid triangle mesh: +1. There are no duplicate vertices (within specified vertexWeldTolerance. See PxCookingParams::meshWeldTolerance) +2. There are no large triangles (within specified PxTolerancesScale.) + +\param[in] params The cooking parameters +\param[in] desc The triangle mesh descriptor to read the mesh from. + +\return true if all the validity conditions hold, false otherwise. + +\see PxCookTriangleMesh() +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxValidateTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc); + +/** +\brief Cooks a triangle mesh. The results are written to the stream. + +To create a triangle mesh object it is necessary to first 'cook' the mesh data into +a form which allows the SDK to perform efficient collision detection. + +PxCookTriangleMesh() allows a mesh description to be cooked into a binary stream +suitable for loading and performing collision detection at runtime. + +\param[in] params The cooking parameters +\param[in] desc The triangle mesh descriptor to read the mesh from. +\param[in] stream User stream to output the cooked data. +\param[out] condition Result from triangle mesh cooking. +\return true on success + +\see PxCookConvexMesh() PxPhysics.createTriangleMesh() PxTriangleMeshCookingResult::Enum +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc, physx::PxOutputStream& stream, physx::PxTriangleMeshCookingResult::Enum* condition=NULL); + +/** +\brief Cooks and creates a triangle mesh without going through a stream. + +\note This method does the same as PxCookTriangleMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback() +or PxGetStandaloneInsertionCallback(). + +\param[in] params The cooking parameters +\param[in] desc The triangle mesh descriptor to read the mesh from. +\param[in] insertionCallback The insertion interface from PxPhysics. +\param[out] condition Result from triangle mesh cooking. +\return PxTriangleMesh pointer on success. + +\see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxTriangleMesh* PxCreateTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc, physx::PxInsertionCallback& insertionCallback, physx::PxTriangleMeshCookingResult::Enum* condition=NULL); + +/** +\brief Cooks and creates a triangle mesh without going through a stream. Convenience function for standalone objects. + +\note This method does the same as cookTriangleMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. +\return PxTriangleMesh pointer on success. + +\param[in] params The cooking parameters +\param[in] desc The triangle mesh descriptor to read the mesh from. + +\see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback +*/ +PX_FORCE_INLINE physx::PxTriangleMesh* PxCreateTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc) +{ + return PxCreateTriangleMesh(params, desc, *PxGetStandaloneInsertionCallback()); +} + +// ==== Tetrahedron & deformable volume meshes ==== + +/** +\brief Cooks a tetrahedron mesh. The results are written to the stream. + +To create a tetrahedron mesh object it is necessary to first 'cook' the mesh data into +a form which allows the SDK to perform efficient collision detection. + +PxCookTetrahedronMesh() allows a mesh description to be cooked into a binary stream +suitable for loading and performing collision detection at runtime. + +\param[in] params The cooking parameters +\param[in] meshDesc The tetrahedron mesh descriptor to read the mesh from. +\param[in] stream User stream to output the cooked data. +\return true on success + +\see PxCookConvexMesh() PxPhysics.createTetrahedronMesh() +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookTetrahedronMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& meshDesc, physx::PxOutputStream& stream); + +/** +\brief Cooks and creates a tetrahedron mesh without going through a stream. + +\note This method does the same as PxCookTetrahedronMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback() +or PxGetStandaloneInsertionCallback(). + +\param[in] params The cooking parameters +\param[in] meshDesc The tetrahedron mesh descriptor to read the mesh from. +\param[in] insertionCallback The insertion interface from PxPhysics. +\return PxTetrahedronMesh pointer on success. + +\see PxCookTetrahedronMesh() PxInsertionCallback +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxTetrahedronMesh* PxCreateTetrahedronMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& meshDesc, physx::PxInsertionCallback& insertionCallback); + +/** +\brief Cooks and creates a tetrahedron mesh without going through a stream. Convenience function for standalone objects. + +\note This method does the same as PxCookTetrahedronMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\param[in] params The cooking parameters +\param[in] meshDesc The tetrahedron mesh descriptor to read the mesh from. +\return PxTetrahedronMesh pointer on success. + +\see PxCookTetrahedronMesh() PxInsertionCallback +*/ +PX_FORCE_INLINE physx::PxTetrahedronMesh* PxCreateTetrahedronMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& meshDesc) +{ + return PxCreateTetrahedronMesh(params, meshDesc, *PxGetStandaloneInsertionCallback()); +} + +/** +\brief Cooks a deformable volume mesh. The results are written to the stream. + +To create a deformable volume mesh object it is necessary to first 'cook' the mesh data into +a form which allows the SDK to perform efficient collision detection and to store data +used during the FEM calculations. + +PxCookDeformableVolumeMesh() allows a mesh description to be cooked into a binary stream +suitable for loading and performing collision detection at runtime. + +\param[in] params The cooking parameters +\param[in] simulationMeshDesc The tetrahedron mesh descriptor to read the simulation mesh from. +\param[in] collisionMeshDesc The tetrahedron mesh descriptor to read the collision mesh from. +\param[in] simulationDataDesc The deformable volume data descriptor to read mapping information from. +\param[in] stream User stream to output the cooked data. +\return true on success + +\see PxCookConvexMesh() PxPhysics.createTriangleMesh() PxTriangleMeshCookingResult::Enum +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookDeformableVolumeMesh(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc, + const physx::PxDeformableVolumeSimulationDataDesc& simulationDataDesc, physx::PxOutputStream& stream); + +/** +\brief Deprecated +\see PxCookDeformableVolumeMesh +*/ +PX_DEPRECATED PX_FORCE_INLINE bool PxCookSoftBodyMesh(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc, + const physx::PxDeformableVolumeSimulationDataDesc& simulationDataDesc, physx::PxOutputStream& stream) +{ + return PxCookDeformableVolumeMesh(params, simulationMeshDesc, collisionMeshDesc, simulationDataDesc, stream); +} + +/** +\brief Cooks and creates a deformable volume mesh without going through a stream. + +\note This method does the same as PxCookDeformableVolumeMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback() +or PxGetStandaloneInsertionCallback(). + +\param[in] params The cooking parameters +\param[in] simulationMeshDesc The tetrahedron mesh descriptor to read the simulation mesh from. +\param[in] collisionMeshDesc The tetrahedron mesh descriptor to read the collision mesh from. +\param[in] simulationDataDesc The deformable volume data descriptor to read mapping information from. +\param[in] insertionCallback The insertion interface from PxPhysics. +\return PxDeformableVolumeMesh pointer on success. + +\see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxDeformableVolumeMesh* PxCreateDeformableVolumeMesh(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc, + const physx::PxDeformableVolumeSimulationDataDesc& simulationDataDesc, physx::PxInsertionCallback& insertionCallback); + +/** +\brief Deprecated +\see PxCreateDeformableVolumeMesh +*/ +PX_DEPRECATED PX_FORCE_INLINE physx::PxDeformableVolumeMesh* PxCreateSoftBodyMesh(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc, + const physx::PxDeformableVolumeSimulationDataDesc& simulationDataDesc, physx::PxInsertionCallback& insertionCallback) +{ + return PxCreateDeformableVolumeMesh(params, simulationMeshDesc, collisionMeshDesc, simulationDataDesc, insertionCallback); +} + +/** +\brief Cooks and creates a deformable volume mesh without going through a stream. Convenience function for standalone objects. + +\note This method does the same as PxCreateDeformableVolumeMesh, but the produced mesh is not stored +into a stream but is either directly inserted in PxPhysics, or created as a standalone +object. Use this method if you are unable to cook offline. + +\param[in] params The cooking parameters +\param[in] simulationMeshDesc The tetrahedron mesh descriptor to read the simulation mesh from. +\param[in] collisionMeshDesc The tetrahedron mesh descriptor to read the collision mesh from. +\param[in] simulationDataDesc The deformable volume data descriptor to read mapping information from. +\return PxDeformableVolumeMesh pointer on success. + +\see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback +*/ +PX_FORCE_INLINE physx::PxDeformableVolumeMesh* PxCreateDeformableVolumeMesh(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc, + const physx::PxDeformableVolumeSimulationDataDesc& simulationDataDesc) +{ + return PxCreateDeformableVolumeMesh(params, simulationMeshDesc, collisionMeshDesc, simulationDataDesc, *PxGetStandaloneInsertionCallback()); +} + +/** +\brief Deprecated +\see PxCreateDeformableVolumeMesh +*/ +PX_DEPRECATED PX_FORCE_INLINE physx::PxDeformableVolumeMesh* PxCreateSoftBodyMesh(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc, + const physx::PxDeformableVolumeSimulationDataDesc& simulationDataDesc) +{ + return PxCreateDeformableVolumeMesh(params, simulationMeshDesc, collisionMeshDesc, simulationDataDesc, *PxGetStandaloneInsertionCallback()); +} + +/** +\brief Computes the mapping between collision and simulation mesh + +The deformable volume deformation is computed on the simulation mesh. To deform the collision mesh accordingly +it needs to be specified how its vertices need to be placed and updated inside the deformation mesh. +This method computes that embedding information. + +\param[in] params The cooking parameters +\param[in] simulationMesh A tetrahedral mesh that defines the shape of the simulation mesh which is used to compute the body's deformation +\param[in] collisionMesh A tetrahedral mesh that defines the shape of the collision mesh which is used for collision detection +\param[in] collisionData A data container that contains acceleration structures and surface information of the collision mesh +\param[in] vertexToTet Optional indices (array of integers) that specifies the index of the tetrahedron in the simulation mesh that + contains a collision mesh vertex. If not provided, the embedding will be computed internally. If the simulation mesh is obtained from + PxTetMaker::createVoxelTetrahedronMesh, then the vertexToTet map createVoxelTetrahedronMesh returned should be used here. +\return PxCollisionMeshMappingData pointer that describes how the collision mesh is embedded into the simulation mesh + +\see PxTetMaker::createVoxelTetrahedronMesh +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxCollisionMeshMappingData* PxComputeModelsMapping(const physx::PxCookingParams& params, + physx::PxTetrahedronMeshData& simulationMesh, const physx::PxTetrahedronMeshData& collisionMesh, + const physx::PxDeformableVolumeCollisionData& collisionData, const physx::PxBoundedData* vertexToTet = NULL); + +/** +\brief Computes data to accelerate collision detection of tetrahedral meshes + +Computes data structures to speed up collision detection with tetrahedral meshes. + +\param[in] params The cooking parameters +\param[in] collisionMeshDesc Raw tetrahedral mesh descriptor which will be used for collision detection +\return PxCollisionTetrahedronMeshData pointer that describes the collision mesh +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxCollisionTetrahedronMeshData* PxComputeCollisionData(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& collisionMeshDesc); + +/** +\brief Computes data to accelerate collision detection of tetrahedral meshes + +Computes data to compute and store a deformable volume's deformation using FEM. + +\param[in] params The cooking parameters +\param[in] simulationMeshDesc Raw tetrahedral mesh descriptor which will be used for FEM simulation +\return PxSimulationTetrahedronMeshData pointer that describes the simulation mesh +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxSimulationTetrahedronMeshData* PxComputeSimulationData(const physx::PxCookingParams& params, + const physx::PxTetrahedronMeshDesc& simulationMeshDesc); + +/** +\brief Bundles all data required for deformable volume simulation + +Creates a container that provides everything to create a PxDeformableVolume + +\param[in] simulationMesh The geometry (tetrahedral mesh) to be used as simulation mesh +\param[in] simulationData Additional non-tetmesh data that contains mass information etc. for the simulation mesh +\param[in] collisionMesh The geometry (tetrahedral mesh) to be used for collision detection +\param[in] collisionData Additional non-tetmesh data that contains surface information, acceleration structures etc. for the simulation mesh +\param[in] mappingData Mapping that describes how the collision mesh's vertices are embedded into the simulation mesh +\param[in] insertionCallback The insertion interface from PxPhysics. +\return PxDeformableVolumeMesh pointer that represents a deformable volume mesh bundling all data (simulation mesh, collision mesh etc.) + +\see PxDeformableVolume createDeformableVolume() +*/ +PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxDeformableVolumeMesh* PxAssembleDeformableVolumeMesh(physx::PxTetrahedronMeshData& simulationMesh, + physx::PxDeformableVolumeSimulationData& simulationData, physx::PxTetrahedronMeshData& collisionMesh, physx::PxDeformableVolumeCollisionData& collisionData, + physx::PxCollisionMeshMappingData& mappingData, physx::PxInsertionCallback& insertionCallback); + +/** +\brief Deprecated +\see PxAssembleDeformableVolumeMesh +*/ +PX_DEPRECATED PX_FORCE_INLINE physx::PxDeformableVolumeMesh* PxAssembleSoftBodyMesh(physx::PxTetrahedronMeshData& simulationMesh, + physx::PxDeformableVolumeSimulationData& simulationData, physx::PxTetrahedronMeshData& collisionMesh, physx::PxDeformableVolumeCollisionData& collisionData, + physx::PxCollisionMeshMappingData& mappingData, physx::PxInsertionCallback& insertionCallback) +{ + return PxAssembleDeformableVolumeMesh(simulationMesh, simulationData, collisionMesh, collisionData, mappingData, insertionCallback); +} + +/** +\brief Deprecated +\see PxAssembleDeformableVolumeMesh +*/ +PX_DEPRECATED PX_FORCE_INLINE physx::PxDeformableVolumeMesh* PxAssembleSoftBodyMesh_Sim(physx::PxSimulationTetrahedronMeshData& simulationMesh, + physx::PxCollisionTetrahedronMeshData& collisionMesh, physx::PxCollisionMeshMappingData& mappingData, physx::PxInsertionCallback& insertionCallback) +{ + return PxAssembleDeformableVolumeMesh(*simulationMesh.getMesh(), *simulationMesh.getData(), + *collisionMesh.getMesh(), *collisionMesh.getData(), mappingData, insertionCallback); +} + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxCookingInternal.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxCookingInternal.h new file mode 100644 index 000000000..27c20ff71 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxCookingInternal.h @@ -0,0 +1,52 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_COOKING_INTERNAL_H +#define PX_COOKING_INTERNAL_H + +#include "cooking/PxCooking.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + struct PxTriangleMeshInternalData; + struct PxBVHInternalData; + class PxTriangleMesh; + class PxBVH; + +#if !PX_DOXYGEN +} // namespace physx +#endif + + PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxTriangleMesh* PX_CALL_CONV PxCreateTriangleMeshInternal(const physx::PxTriangleMeshInternalData& data); + + PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxBVH* PX_CALL_CONV PxCreateBVHInternal(const physx::PxBVHInternalData& data); + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxMidphaseDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxMidphaseDesc.h new file mode 100644 index 000000000..27741cfae --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxMidphaseDesc.h @@ -0,0 +1,118 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MIDPHASE_DESC_H +#define PX_MIDPHASE_DESC_H + +#include "geometry/PxTriangleMesh.h" +#include "cooking/PxBVH33MidphaseDesc.h" +#include "cooking/PxBVH34MidphaseDesc.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** + +\brief Structure describing parameters affecting midphase mesh structure. + +\see PxCookingParams, PxBVH33MidphaseDesc, PxBVH34MidphaseDesc +*/ +class PxMidphaseDesc +{ +public: + PX_FORCE_INLINE PxMidphaseDesc() { setToDefault(PxMeshMidPhase::eBVH34); } + + /** + \brief Returns type of midphase mesh structure. + \return PxMeshMidPhase::Enum + + \see PxMeshMidPhase::Enum + */ + PX_FORCE_INLINE PxMeshMidPhase::Enum getType() const { return mType; } + + /** + \brief Midphase descriptors union + + \see PxBV33MidphaseDesc, PxBV34MidphaseDesc + */ + union { + PxBVH33MidphaseDesc mBVH33Desc; + PxBVH34MidphaseDesc mBVH34Desc; + }; + + /** + \brief Initialize the midphase mesh structure descriptor + \param[in] type Midphase mesh structure descriptor + + \see PxBV33MidphaseDesc, PxBV34MidphaseDesc + */ + void setToDefault(PxMeshMidPhase::Enum type) + { + mType = type; + if(type==PxMeshMidPhase::eBVH33) + mBVH33Desc.setToDefault(); + else if(type==PxMeshMidPhase::eBVH34) + mBVH34Desc.setToDefault(); + } + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + bool isValid() const + { + if(mType==PxMeshMidPhase::eBVH33) + return mBVH33Desc.isValid(); + else if(mType==PxMeshMidPhase::eBVH34) + return mBVH34Desc.isValid(); + return false; + } + + /** + \brief Assignment operator + \return this + */ + PX_FORCE_INLINE PxMidphaseDesc& operator=(PxMeshMidPhase::Enum descType) + { + setToDefault(descType); + return *this; + } + +protected: + PxMeshMidPhase::Enum mType; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxSDFDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxSDFDesc.h new file mode 100644 index 000000000..36e0ce3da --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxSDFDesc.h @@ -0,0 +1,207 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SDF_DESC_H +#define PX_SDF_DESC_H + +#include "PxPhysXConfig.h" +#include "geometry/PxSimpleTriangleMesh.h" +#include "foundation/PxBounds3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + class PxSDFBuilder; + + /** + \brief A helper structure to define dimensions in 3D + */ + struct PxDim3 + { + PxU32 x, y, z; + }; + + /** + \brief Defines the number of bits per subgrid pixel + */ + class PxSdfBitsPerSubgridPixel + { + public: + enum Enum + { + e8_BIT_PER_PIXEL = 1, //!< 8 bit per subgrid pixel (values will be stored as normalized integers) + e16_BIT_PER_PIXEL = 2, //!< 16 bit per subgrid pixel (values will be stored as normalized integers) + e32_BIT_PER_PIXEL = 4 //!< 32 bit per subgrid pixel (values will be stored as floats in world scale units) + }; + }; + + /** + \brief A structure describing signed distance fields (SDF) for triangle meshes. SDF colliders only work when the GPU solver is + used to run the simulation. The GPU solver is enabled by setting the flag PxSceneFlag::eENABLE_GPU_DYNAMICS in the scene description. + */ + class PxSDFDesc + { + public: + + /** + \brief Pointer to first sdf array element. + */ + PxBoundedData sdf; + + /** + \brief Dimensions of sdf + */ + PxDim3 dims; + + /** + \brief The Lower bound of the original mesh + */ + PxVec3 meshLower; + + /** + \brief The spacing of each sdf voxel + */ + PxReal spacing; + + + /** + \brief The number of cells in a sparse subgrid block (full block has subgridSize^3 cells and (subgridSize+1)^3 samples). If set to zero, this indicates that only a dense background grid SDF is used without sparse blocks + */ + PxU32 subgridSize; + + /** + \brief Enumeration that defines the number of bits per subgrid pixel (either 32, 16 or 8bits) + */ + PxSdfBitsPerSubgridPixel::Enum bitsPerSubgridPixel; + + /** + \brief Number of subgrid blocks in the 3d texture. The full texture dimension will be sdfSubgrids3DTexBlockDim*(subgridSize+1). + */ + PxDim3 sdfSubgrids3DTexBlockDim; + + /** + \brief The data to create the 3d texture containg the packed subgrid blocks. Stored as PxU8 to support multiple formats (8, 16 and 32 bits per pixel) + */ + PxBoundedData sdfSubgrids; + + /** + \brief Array with start indices into the subgrid texture for every subgrid block. 10bits for z coordinate, 10bits for y and 10bits for x. Encoding is as follows: slot = (z << 20) | (y << 10) | x + */ + PxBoundedData sdfStartSlots; + + /** + \brief The minimum value over all subgrid blocks. Used if normalized textures are used which is the case for 8 and 16bit formats + */ + PxReal subgridsMinSdfValue; + + /** + \brief The maximum value over all subgrid blocks. Used if normalized textures are used which is the case for 8 and 16bit formats + */ + PxReal subgridsMaxSdfValue; + + /** + \brief The bounds of the sdf. If left unassigned (empty), the bounds of the mesh will be used + */ + PxBounds3 sdfBounds; + + /** + \brief Narrow band thickness as a fraction of the bounds diagonal length. Every subgrid block that + overlaps with the narrow band around the mesh surface will be kept providing high resolution around the mesh surface. + The valid range of this parameter is (0, 1). The higher the value, the more subgrids will get created, the more memory will be required. + */ + PxReal narrowBandThicknessRelativeToSdfBoundsDiagonal; + + /** + \brief The number of threads that are launched to compute the signed distance field + */ + PxU32 numThreadsForSdfConstruction; + + /** + \brief Optional pointer to the geometry of the mesh that is used to compute the SDF. If it is not set, the geometry of the mesh, that this descriptor is passed to during cooking, will be taken. + The mesh data must only be available during cooking. It can be released once cooking completed. + */ + PxSimpleTriangleMesh baseMesh; + + /** + \brief Optional pointer to an instance of a SDF builder. This significantly speeds up the construction of the SDF since the default SDF builder will do almost all computations directly on the GPU. + The user must release the instance of the SDF builder once cooking completed. + */ + PxSDFBuilder* sdfBuilder; + + /** + \brief Constructor + */ + PX_INLINE PxSDFDesc(); + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const; + }; + + PX_INLINE PxSDFDesc::PxSDFDesc() + { + sdf.data = NULL; + dims.x = 0; + dims.y = 0; + dims.z = 0; + spacing = 0; + meshLower = PxVec3(PxZero); + subgridSize = 0; + subgridsMinSdfValue = 0.0f; + subgridsMaxSdfValue = 0.0f; + sdfBounds = PxBounds3::empty(); + bitsPerSubgridPixel = PxSdfBitsPerSubgridPixel::e16_BIT_PER_PIXEL; + narrowBandThicknessRelativeToSdfBoundsDiagonal = 0.01f; + numThreadsForSdfConstruction = 1; + sdfBuilder = NULL; + } + + PX_INLINE bool PxSDFDesc::isValid() const + { + // Check validity of user's input(if any) + if (sdf.data) + { + if (dims.x < 1 || dims.y < 1 || dims.z < 1) + return false; + if (!meshLower.isFinite()) + return false; + if (spacing <= 0) + return false; + } + + return true; + } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxTetrahedronMeshDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxTetrahedronMeshDesc.h new file mode 100644 index 000000000..15a426025 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxTetrahedronMeshDesc.h @@ -0,0 +1,232 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TETRAHEDRON_MESH_DESC_H +#define PX_TETRAHEDRON_MESH_DESC_H + +#include "PxPhysXConfig.h" +#include "foundation/PxVec3.h" +#include "foundation/PxFlags.h" +#include "common/PxCoreUtilityTypes.h" +#include "geometry/PxSimpleTriangleMesh.h" +#include "foundation/PxArray.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + /** + \brief Descriptor class for #PxTetrahedronMesh (contains only pure geometric data). + + \see PxTetrahedronMesh PxShape + */ + class PxTetrahedronMeshDesc + { + public: + + /** + \brief Defines the tetrahedron structure of a mesh. + */ + enum PxMeshFormat + { + eTET_MESH, //!< Normal tetmesh with arbitrary tetrahedra + eHEX_MESH //!< 5 or 6 tetrahedra in a row will form a hexahedron + }; + + + /** + Optional pointer to first material index, or NULL. There are PxTetrahedronMesh::numTriangles indices in total. + Caller may add materialIndexStride bytes to the pointer to access the next triangle. + + When a tetrahedron mesh collides with another object, a material is required at the collision point. + If materialIndices is NULL, then the material of the PxShape instance is used. + Otherwise, if the point of contact is on a tetrahedron with index i, then the material index is determined as: + PxDeformableMaterialTableIndex index = *(PxDeformableMaterialTableIndex *)(((PxU8*)materialIndices) + materialIndexStride * i); + + If the contact point falls on a vertex or an edge, a tetrahedron adjacent to the vertex or edge is selected, and its index + used to look up a material. The selection is arbitrary but consistent over time. + + Default: NULL + + \see materialIndexStride + */ + PxTypedBoundedData materialIndices; + + /** + \brief Pointer to first vertex point. + */ + PxBoundedData points; + + /** + \brief Pointer to first tetrahedron. + + Caller may add tetrhedronStrideBytes bytes to the pointer to access the next tetrahedron. + + These are quadruplets of 0 based indices: + vert0 vert1 vert2 vert3 + vert0 vert1 vert2 vert3 + vert0 vert1 vert2 vert3 + ... + + where vertex is either a 32 or 16 bit unsigned integer. There are numTetrahedrons*4 indices. + + This is declared as a void pointer because it is actually either an PxU16 or a PxU32 pointer. + */ + PxBoundedData tetrahedrons; + + + /** + \brief Flags bits, combined from values of the enum ::PxMeshFlag + */ + PxMeshFlags flags; + + /** + \brief Used for simulation meshes only. Defines if this tet mesh should be simulated as a tet mesh, + or if a set of tetrahedra should be used to represent another shape, e.g. a hexahedral mesh constructed + from 5 or 6 elements. + */ + PxU16 tetsPerElement; + + /** + \brief Constructor to build an empty tetmesh description + */ + PxTetrahedronMeshDesc() + { + points.count = 0; + points.stride = 0; + points.data = NULL; + + tetrahedrons.count = 0; + tetrahedrons.stride = 0; + tetrahedrons.data = NULL; + + tetsPerElement = 1; + } + + /** + \brief Constructor to build a tetmeshdescription that links to the vertices and indices provided + */ + PxTetrahedronMeshDesc(physx::PxArray& meshVertices, physx::PxArray& meshTetIndices, + const PxTetrahedronMeshDesc::PxMeshFormat meshFormat = eTET_MESH, PxU16 numberOfTetsPerHexElement = 5) + { + points.count = meshVertices.size(); + points.stride = sizeof(float) * 3; + points.data = meshVertices.begin(); + + tetrahedrons.count = meshTetIndices.size() / 4; + tetrahedrons.stride = sizeof(int) * 4; + tetrahedrons.data = meshTetIndices.begin(); + + if (meshFormat == eTET_MESH) + tetsPerElement = 1; + else + tetsPerElement = numberOfTetsPerHexElement; + } + + PX_INLINE bool isValid() const + { + // Check geometry of the collision mesh + if (points.count < 4) //at least 1 tetrahedron's worth of points + return false; + if ((!tetrahedrons.data) && (points.count % 4)) // Non-indexed mesh => we must ensure the geometry defines an implicit number of tetrahedrons // i.e. numVertices can't be divided by 4 + return false; + if (points.count > 0xffff && flags & PxMeshFlag::e16_BIT_INDICES) + return false; + if (!points.data) + return false; + if (points.stride < sizeof(PxVec3)) //should be at least one point's worth of data + return false; + + //add more validity checks here + if (materialIndices.data && materialIndices.stride < sizeof(PxDeformableMaterialTableIndex)) + return false; + + // The tetrahedrons pointer is not mandatory + if (tetrahedrons.data) + { + // Indexed collision mesh + PxU32 limit = (flags & PxMeshFlag::e16_BIT_INDICES) ? sizeof(PxU16) * 4 : sizeof(PxU32) * 4; + if (tetrahedrons.stride < limit) + return false; + } + + //The model can only be either a tetmesh (1 tet per element), or have 5 or 6 tets per hex element, otherwise invalid. + if (tetsPerElement != 1 && tetsPerElement != 5 && tetsPerElement != 6) + return false; + + return true; + } + }; + + /** + \brief Descriptor class for #PxDeformableVolumeMesh (contains only additional data used for deformable volume simulation). + + \see PxDeformableVolumeMesh PxShape + */ + class PxDeformableVolumeSimulationDataDesc + { + public: + /** + \brief Pointer to first index of tetrahedron that contains the vertex at the same location in the vertex buffer. + if left unassigned it will be computed automatically. If a point is inside multiple tetrahedra (ambiguous case), the frist one found will be taken. + */ + PxBoundedData vertexToTet; + + /** + \brief Constructor to build an empty simulation description + */ + PxDeformableVolumeSimulationDataDesc() + { + vertexToTet.count = 0; + vertexToTet.stride = 0; + vertexToTet.data = NULL; + } + + /** + \brief Constructor to build a simulation description with a defined vertex to tetrahedron mapping + */ + PxDeformableVolumeSimulationDataDesc(physx::PxArray& vertToTet) + { + vertexToTet.count = vertToTet.size(); + vertexToTet.stride = sizeof(PxI32); + vertexToTet.data = vertToTet.begin(); + } + + PX_INLINE bool isValid() const + { + return true; + } + }; + + typedef PX_DEPRECATED PxDeformableVolumeSimulationDataDesc PxSoftBodySimulationDataDesc; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxTriangleMeshDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxTriangleMeshDesc.h new file mode 100644 index 000000000..68beb7e74 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/PxTriangleMeshDesc.h @@ -0,0 +1,131 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TRIANGLE_MESH_DESC_H +#define PX_TRIANGLE_MESH_DESC_H + +#include "PxPhysXConfig.h" +#include "geometry/PxSimpleTriangleMesh.h" +#include "PxSDFDesc.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + +/** +\brief Descriptor class for #PxTriangleMesh. + +Note that this class is derived from PxSimpleTriangleMesh which contains the members that describe the basic mesh. +The mesh data is *copied* when an PxTriangleMesh object is created from this descriptor. After the call the +user may discard the triangle data. + +\see PxTriangleMesh PxTriangleMeshGeometry PxShape +*/ +class PxTriangleMeshDesc : public PxSimpleTriangleMesh +{ +public: + + /** + Optional pointer to first material index, or NULL. There are PxSimpleTriangleMesh::numTriangles indices in total. + Caller may add materialIndexStride bytes to the pointer to access the next triangle. + + When a triangle mesh collides with another object, a material is required at the collision point. + If materialIndices is NULL, then the material of the PxShape instance is used. + Otherwise, if the point of contact is on a triangle with index i, then the material index is determined as: + PxMaterialTableIndex index = *(PxMaterialTableIndex *)(((PxU8*)materialIndices) + materialIndexStride * i); + + If the contact point falls on a vertex or an edge, a triangle adjacent to the vertex or edge is selected, and its index + used to look up a material. The selection is arbitrary but consistent over time. + + Default: NULL + + \see materialIndexStride + */ + PxTypedBoundedData materialIndices; + + /** + \brief SDF descriptor. When this descriptor is set, a signed distance field (SDF) is calculated. SDF collisions only + work when the GPU solver is used to run the simulation. The GPU solver is enabled by setting the flag PxSceneFlag::eENABLE_GPU_DYNAMICS in the scene description. + + Default: NULL + */ + PxSDFDesc* sdfDesc; + + /** + \brief Constructor sets to default. + */ + PX_INLINE PxTriangleMeshDesc(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const; +}; + + +PX_INLINE PxTriangleMeshDesc::PxTriangleMeshDesc() //constructor sets to default +{ + PxSimpleTriangleMesh::setToDefault(); + sdfDesc = NULL; +} + +PX_INLINE void PxTriangleMeshDesc::setToDefault() +{ + *this = PxTriangleMeshDesc(); +} + +PX_INLINE bool PxTriangleMeshDesc::isValid() const +{ + if(points.count < 3) //at least 1 trig's worth of points + return false; + if ((!triangles.data) && (points.count%3)) // Non-indexed mesh => we must ensure the geometry defines an implicit number of triangles // i.e. numVertices can't be divided by 3 + return false; + //add more validity checks here + if (materialIndices.data && materialIndices.stride < sizeof(PxMaterialTableIndex)) + return false; + + if (sdfDesc && !sdfDesc->isValid()) + return false; + + return PxSimpleTriangleMesh::isValid(); +} + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cooking/Pxc.h b/Jusin154_Team3D/Engine/Public/PhysX/cooking/Pxc.h new file mode 100644 index 000000000..d0866ca5c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cooking/Pxc.h @@ -0,0 +1,55 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXC_H +#define PXC_H + +#include "foundation/PxPreprocessor.h" + +// define API function declaration +#if !defined PX_PHYSX_STATIC_LIB + #if PX_WINDOWS_FAMILY + #if defined PX_PHYSX_COOKING_EXPORTS + #define PX_PHYSX_COOKING_API __declspec(dllexport) + #else + #define PX_PHYSX_COOKING_API __declspec(dllimport) + #endif + #elif PX_UNIX_FAMILY + #define PX_PHYSX_COOKING_API PX_UNIX_EXPORT + #endif +#endif + +#if !defined(PX_PHYSX_COOKING_API) + #define PX_PHYSX_COOKING_API +#endif + +#ifndef PX_C_EXPORT + #define PX_C_EXPORT extern "C" +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaContext.h b/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaContext.h new file mode 100644 index 000000000..fcceea444 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaContext.h @@ -0,0 +1,192 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_CUDA_CONTEX_H +#define PX_CUDA_CONTEX_H + +#include "foundation/PxPreprocessor.h" + +#if PX_SUPPORT_GPU_PHYSX + +#include "PxCudaTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + struct PxCudaKernelParam + { + void* data; + size_t size; + }; + + // workaround for not being able to forward declare enums in PxCudaTypes.h. + // provides different automatic casting depending on whether cuda.h was included beforehand or not. + template + struct PxCUenum + { + PxU32 value; + + PxCUenum(CUenum e) { value = PxU32(e); } + operator CUenum() const { return CUenum(value); } + }; + +#ifdef CUDA_VERSION + typedef PxCUenum PxCUjit_option; + typedef PxCUenum PxCUresult; +#else + typedef PxCUenum PxCUjit_option; + typedef PxCUenum PxCUresult; +#endif + +#define PX_CUDA_KERNEL_PARAM(X) { (void*)&X, sizeof(X) } +#define PX_CUDA_KERNEL_PARAM2(X) (void*)&X + + class PxDeviceAllocatorCallback; + /** + Cuda Context + */ + class PxCudaContext + { + protected: + virtual ~PxCudaContext() {} + + PxDeviceAllocatorCallback* mAllocatorCallback; + + public: + virtual void release() = 0; + + virtual PxCUresult memAlloc(CUdeviceptr *dptr, size_t bytesize) = 0; + + virtual PxCUresult memFree(CUdeviceptr dptr) = 0; + + virtual PxCUresult memHostAlloc(void **pp, size_t bytesize, unsigned int Flags) = 0; + + virtual PxCUresult memFreeHost(void *p) = 0; + + virtual PxCUresult memHostGetDevicePointer(CUdeviceptr *pdptr, void *p, unsigned int Flags) = 0; + + virtual PxCUresult moduleLoadDataEx(CUmodule *module, const void *image, unsigned int numOptions, PxCUjit_option *options, void **optionValues) = 0; + + virtual PxCUresult moduleGetFunction(CUfunction *hfunc, CUmodule hmod, const char *name) = 0; + + virtual PxCUresult moduleUnload(CUmodule hmod) = 0; + + virtual PxCUresult streamCreate(CUstream *phStream, unsigned int Flags) = 0; + + virtual PxCUresult streamCreateWithPriority(CUstream *phStream, unsigned int flags, int priority) = 0; + + virtual PxCUresult streamFlush(CUstream hStream) = 0; + + virtual PxCUresult streamWaitEvent(CUstream hStream, CUevent hEvent, unsigned int Flags) = 0; + + virtual PxCUresult streamWaitEvent(CUstream hStream, CUevent hEvent) = 0; + + virtual PxCUresult streamDestroy(CUstream hStream) = 0; + + virtual PxCUresult streamSynchronize(CUstream hStream) = 0; + + virtual PxCUresult eventCreate(CUevent *phEvent, unsigned int Flags) = 0; + + virtual PxCUresult eventRecord(CUevent hEvent, CUstream hStream) = 0; + + virtual PxCUresult eventQuery(CUevent hEvent) = 0; + + virtual PxCUresult eventSynchronize(CUevent hEvent) = 0; + + virtual PxCUresult eventDestroy(CUevent hEvent) = 0; + + virtual PxCUresult launchKernel( + CUfunction f, + unsigned int gridDimX, + unsigned int gridDimY, + unsigned int gridDimZ, + unsigned int blockDimX, + unsigned int blockDimY, + unsigned int blockDimZ, + unsigned int sharedMemBytes, + CUstream hStream, + PxCudaKernelParam* kernelParams, + size_t kernelParamsSizeInBytes, + void** extra, + const char* file, + int line + ) = 0; + + // PT: same as above but without copying the kernel params to a local stack before the launch + // i.e. the kernelParams data is passed directly to the kernel. + virtual PxCUresult launchKernel( + CUfunction f, + PxU32 gridDimX, PxU32 gridDimY, PxU32 gridDimZ, + PxU32 blockDimX, PxU32 blockDimY, PxU32 blockDimZ, + PxU32 sharedMemBytes, + CUstream hStream, + void** kernelParams, + void** extra, + const char* file, + int line + ) = 0; + + virtual PxCUresult memcpyDtoH(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount) = 0; + + virtual PxCUresult memcpyDtoHAsync(void* dstHost, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream) = 0; + + virtual PxCUresult memcpyHtoD(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount) = 0; + + virtual PxCUresult memcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount, CUstream hStream) = 0; + + virtual PxCUresult memcpyDtoDAsync(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream) = 0; + + virtual PxCUresult memcpyDtoD(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount) = 0; + + virtual PxCUresult memcpyPeerAsync(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount, CUstream hStream) = 0; + + virtual PxCUresult memsetD32Async(CUdeviceptr dstDevice, unsigned int ui, size_t N, CUstream hStream) = 0; + + virtual PxCUresult memsetD8Async(CUdeviceptr dstDevice, unsigned char uc, size_t N, CUstream hStream) = 0; + + virtual PxCUresult memsetD32(CUdeviceptr dstDevice, unsigned int ui, size_t N) = 0; + + virtual PxCUresult memsetD16(CUdeviceptr dstDevice, unsigned short uh, size_t N) = 0; + + virtual PxCUresult memsetD8(CUdeviceptr dstDevice, unsigned char uc, size_t N) = 0; + + virtual PxCUresult getLastError() = 0; + + PxDeviceAllocatorCallback* getAllocatorCallback() { return mAllocatorCallback; } + + virtual void setAbortMode(bool abort) = 0; + + virtual bool isInAbortMode() = 0; + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_SUPPORT_GPU_PHYSX +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaContextManager.h b/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaContextManager.h new file mode 100644 index 000000000..90d7d70f7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaContextManager.h @@ -0,0 +1,554 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_CUDA_CONTEXT_MANAGER_H +#define PX_CUDA_CONTEXT_MANAGER_H + +#include "foundation/PxPreprocessor.h" + +#if PX_SUPPORT_GPU_PHYSX + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxErrorCallback.h" +#include "foundation/PxFlags.h" + +#include "PxCudaTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxCudaContext; + +struct PxCudaInteropRegisterFlag +{ + enum Enum + { + eNONE = 0x00, + eREAD_ONLY = 0x01, + eWRITE_DISCARD = 0x02, + eSURFACE_LDST = 0x04, + eTEXTURE_GATHER = 0x08 + }; +}; + +/** +\brief An interface class that the user can implement in order for PhysX to use a user-defined device memory allocator. +*/ +class PxDeviceAllocatorCallback +{ +public: + + /** + \brief Allocated device memory. + \param[in] ptr Pointer to store the allocated address + \param[in] size The amount of memory required + \return A boolean indicates the operation succeed or fail + */ + virtual bool memAlloc(void** ptr, size_t size) = 0; + + /** + \brief Frees device memory. + \param[in] ptr The memory to free + \return A boolean indicates the operation succeed or fail + */ + virtual bool memFree(void* ptr) = 0; + +protected: + virtual ~PxDeviceAllocatorCallback() {} +}; +/** +\brief collection of set bits defined in NxCudaInteropRegisterFlag. + +\see NxCudaInteropRegisterFlag +*/ +typedef PxFlags PxCudaInteropRegisterFlags; +PX_FLAGS_OPERATORS(PxCudaInteropRegisterFlag::Enum, uint32_t) + +//! \brief Descriptor used to create a PxCudaContextManager +class PxCudaContextManagerDesc +{ +public: + /** + * \brief The CUDA context to manage + * + * If left NULL, the PxCudaContextManager will create a new context. If + * graphicsDevice is also not NULL, this new CUDA context will be bound to + * that graphics device, enabling the use of CUDA/Graphics interop features. + * + * If ctx is not NULL, the specified context must be applied to the thread + * that is allocating the PxCudaContextManager at creation time (aka, it + * cannot be popped). The PxCudaContextManager will take ownership of the + * context until the manager is released. All access to the context must be + * gated by lock acquisition. + * + * If the user provides a context for the PxCudaContextManager, the context + * _must_ have either been created on the GPU ordinal returned by + * PxGetSuggestedCudaDeviceOrdinal() or on your graphics device. + */ + CUcontext* ctx; + + /** + * \brief D3D device pointer or OpenGl context handle + * + * Only applicable when ctx is NULL, thus forcing a new context to be + * created. In that case, the created context will be bound to this + * graphics device. + */ + void* graphicsDevice; + + /** + * \brief CUDA device ordinal + * + * Only applicable when ctx is NULL, thus forcing a new context to be created based on the CUDA device ordinal. + * The first CUDA device will have an ordinal value of 0 and so on. + * If the CUDA device ordinal is -1, the device selected will be queried from the environment variable PHYSX_GPU_DEVICE. + * \note If the environment variable PHYSX_GPU_DEVICE is not found, the CUDA device ordinal will default to 0. + */ + PxI32 deviceOrdinal; + + /** + * \brief Application-specific GUID + * + * If your application employs PhysX modules that use CUDA you need to use a GUID + * so that patches for new architectures can be released for your game.You can obtain a GUID for your + * application from Nvidia. + */ + const char* appGUID; + + /** + * \brief Application-specific device memory allocator + * + * the application can implement an device memory allocator, which inherites PxDeviceAllocatorCallback, and + * pass that to the PxCudaContextManagerDesc. The SDK will use that allocator to allocate device memory instead of + * using the defaul CUDA device memory allocator. + */ + PxDeviceAllocatorCallback* deviceAllocator; + + PX_INLINE PxCudaContextManagerDesc() : + ctx (NULL), + graphicsDevice (NULL), + deviceOrdinal (-1), + appGUID (NULL), + deviceAllocator (NULL) + { + } +}; + +/** +\brief A cuda kernel index providing an index to the cuda module and the function name +*/ +struct PxKernelIndex +{ + PxU32 moduleIndex; + const char* functionName; +}; + +/** + * \brief Manages thread locks, and task scheduling for a CUDA context + * + * A PxCudaContextManager manages access to a single CUDA context, allowing it to + * be shared between multiple scenes. + * The context must be acquired from the manager before using any CUDA APIs unless stated differently. + * + * The PxCudaContextManager is based on the CUDA driver API and explicitly does not + * support the CUDA runtime API (aka, CUDART). + */ +class PxCudaContextManager +{ +public: + /** + * \brief Schedules clear operation for a device memory buffer on the specified stream + * + * The cuda context will get acquired automatically + * \deprecated The replacement is PxCudaHelpersExt::memsetAsync. + */ + template + PX_DEPRECATED void clearDeviceBufferAsync(T* deviceBuffer, PxU32 numElements, CUstream stream, PxI32 value = 0) + { + clearDeviceBufferAsyncInternal(deviceBuffer, numElements * sizeof(T), stream, value); + } + + /** + * \brief Copies a device buffer to the host + * + * The cuda context will get acquired automatically + * \deprecated The replacement is PxCudaHelpersExt::copyDToH. + */ + template + PX_DEPRECATED void copyDToH(T* hostBuffer, const T* deviceBuffer, PxU32 numElements) + { + copyDToHInternal(hostBuffer, deviceBuffer, numElements * sizeof(T)); + } + + /** + * \brief Copies a host buffer to the device + * + * The cuda context will get acquired automatically + * \deprecated The replacement is PxCudaHelpersExt::copyHtoD + */ + template + PX_DEPRECATED void copyHToD(T* deviceBuffer, const T* hostBuffer, PxU32 numElements) + { + copyHToDInternal(deviceBuffer, hostBuffer, numElements * sizeof(T)); + } + + /** + * \brief Schedules device to host copy operation on the specified stream + * + * The cuda context will get acquired automatically + * \deprecated Use PxCudaHelpersExt::copyDToHAsync instead. + */ + template + PX_DEPRECATED void copyDToHAsync(T* hostBuffer, const T* deviceBuffer, PxU32 numElements, CUstream stream) + { + copyDToHAsyncInternal(hostBuffer, deviceBuffer, numElements * sizeof(T), stream); + } + + /** + * \brief Schedules host to device copy operation on the specified stream + * + * The cuda context will get acquired automatically + * \deprecated Use PxCudaHelpersExt::copyHToDAsync instead. + */ + template + PX_DEPRECATED void copyHToDAsync(T* deviceBuffer, const T* hostBuffer, PxU32 numElements, CUstream stream) + { + copyHToDAsyncInternal(deviceBuffer, hostBuffer, numElements * sizeof(T), stream); + } + + /** + * \brief Schedules device to device copy operation on the specified stream + * + * The cuda context will get acquired automatically + * \deprecated Use PxCudaHelpersExt::copyDToDAsync instead. + */ + template + PX_DEPRECATED void copyDToDAsync(T* dstDeviceBuffer, const T* srcDeviceBuffer, PxU32 numElements, CUstream stream) + { + copyDToDAsyncInternal(dstDeviceBuffer, srcDeviceBuffer, numElements * sizeof(T), stream); + } + + /** + * \brief Schedules a memset operation on the device on the specified stream. Only supported for 1 byte or 4 byte data types. + * + * The cuda context will get acquired automatically + * \deprecated Use PxCudaHelpersExt::memsetAsync instead. + */ + template + PX_DEPRECATED void memsetAsync(T* dstDeviceBuffer, const T& value, PxU32 numElements, CUstream stream) + { + PX_COMPILE_TIME_ASSERT(sizeof(value) == sizeof(PxU32) || sizeof(value) == sizeof(PxU8)); + + if (sizeof(value) == sizeof(PxU32)) + memsetD32AsyncInternal(dstDeviceBuffer, reinterpret_cast(value), numElements, stream); + else + memsetD8AsyncInternal(dstDeviceBuffer, reinterpret_cast(value), numElements, stream); + } + + /** + * \brief Allocates a device buffer + * + * The cuda context will get acquired automatically + * \deprecated - use PxCudaHelpersExt::allocDeviceBuffer instead. + */ + template + PX_DEPRECATED void allocDeviceBuffer(T*& deviceBuffer, PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__) + { + void* ptr = allocDeviceBufferInternal(PxU64(numElements) * sizeof(T), filename, line); + deviceBuffer = reinterpret_cast(ptr); + } + + /** + * \brief Allocates a device buffer and returns the pointer to the memory + * + * The cuda context will get acquired automatically + * \deprecated - use PxCudaHelpersExt::allocDeviceBuffer instead. + */ + template + PX_DEPRECATED T* allocDeviceBuffer(PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__) + { + void* ptr = allocDeviceBufferInternal(PxU64(numElements) * sizeof(T), filename, line); + return reinterpret_cast(ptr); + } + + /** + * \brief Frees a device buffer + * + * The cuda context will get acquired automatically + * \deprecated - use PxCudaHelpersExt::freeDeviceBuffer instead. + */ + template + PX_DEPRECATED void freeDeviceBuffer(T*& deviceBuffer) + { + freeDeviceBufferInternal(deviceBuffer); + deviceBuffer = NULL; + } + + /** + * \brief Allocates a pinned host buffer + * + * A pinned host buffer can be used on the gpu after getting a mapped device pointer from the pinned host buffer pointer, see getMappedDevicePtr + * The cuda context will get acquired automatically + * \see getMappedDevicePtr + * \deprecated - use PxCudaHelpersExt::allocPinnedHostBuffer instead. + */ + template + PX_DEPRECATED void allocPinnedHostBuffer(T*& pinnedHostBuffer, PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__) + { + void* ptr = allocPinnedHostBufferInternal(PxU64(numElements) * sizeof(T), filename, line); + pinnedHostBuffer = reinterpret_cast(ptr); + } + + /** + * \brief Allocates a pinned host buffer and returns the pointer to the memory + * + * A pinned host buffer can be used on the gpu after getting a mapped device pointer from the pinned host buffer pointer, see getMappedDevicePtr + * The cuda context will get acquired automatically + * \deprecated - use PxCudaHelpersExt::allocPinnedHostBuffer instead. + * \see getMappedDevicePtr + */ + template + PX_DEPRECATED T* allocPinnedHostBuffer(PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__) + { + void* ptr = allocPinnedHostBufferInternal(PxU64(numElements) * sizeof(T), filename, line); + return reinterpret_cast(ptr); + } + + /** + * \brief Frees a pinned host buffer + * + * The cuda context will get acquired automatically + * \deprecated - use PxCudaHelpersExt::freePinnedHostBuffer instead. + */ + template + PX_DEPRECATED void freePinnedHostBuffer(T*& pinnedHostBuffer) + { + freePinnedHostBufferInternal(pinnedHostBuffer); + pinnedHostBuffer = NULL; + } + + /** + * \brief Gets a mapped pointer from a pinned host buffer that can be used in cuda kernels directly + * + * Data access performance with a mapped pinned host pointer will be slower than using a device pointer directly + * but the changes done in the kernel will be available on the host immediately. + * The cuda context will get acquired automatically + */ + virtual CUdeviceptr getMappedDevicePtr(void* pinnedHostBuffer) = 0; + + /** + * \brief Acquire the CUDA context for the current thread + * + * Acquisitions are allowed to be recursive within a single thread. + * You can acquire the context multiple times so long as you release + * it the same count. + * + * The context must be acquired before using most CUDA functions. + */ + virtual void acquireContext() = 0; + + /** + * \brief Acquire the CUDA context for the current thread + * + * Acquisitions are allowed to be recursive within a single thread. + * You can acquire the context multiple times so long as you release + * it the same count. + * + * The context must be acquired before using most CUDA functions. + * The function will return false if context aquisition fails for some reason + */ + virtual bool tryAcquireContext() = 0; + + /** + * \brief Release the CUDA context from the current thread + * + * The CUDA context should be released as soon as practically + * possible, to allow other CPU threads to work efficiently. + */ + virtual void releaseContext() = 0; + + /** + * \brief Return the CUcontext + */ + virtual CUcontext getContext() = 0; + + /** + * \brief Return the CudaContext + */ + virtual PxCudaContext* getCudaContext() = 0; + + /** + * \brief Context manager has a valid CUDA context + * + * This method should be called after creating a PxCudaContextManager, + * especially if the manager was responsible for allocating its own + * CUDA context (desc.ctx == NULL). + */ + virtual bool contextIsValid() const = 0; + + /* Query CUDA context and device properties, without acquiring context */ + + virtual bool supportsArchSM10() const = 0; //!< G80 + virtual bool supportsArchSM11() const = 0; //!< G92 + virtual bool supportsArchSM12() const = 0; //!< GT200 + virtual bool supportsArchSM13() const = 0; //!< GT260 + virtual bool supportsArchSM20() const = 0; //!< GF100 + virtual bool supportsArchSM30() const = 0; //!< GK100 + virtual bool supportsArchSM35() const = 0; //!< GK110 + virtual bool supportsArchSM50() const = 0; //!< GM100 + virtual bool supportsArchSM52() const = 0; //!< GM200 + virtual bool supportsArchSM60() const = 0; //!< GP100 + virtual bool isIntegrated() const = 0; //!< true if GPU is an integrated (MCP) part + virtual bool canMapHostMemory() const = 0; //!< true if GPU map host memory to GPU (0-copy) + virtual int getDriverVersion() const = 0; //!< returns cached value of cuGetDriverVersion() + virtual size_t getDeviceTotalMemBytes() const = 0; //!< returns cached value of device memory size + virtual int getMultiprocessorCount() const = 0; //!< returns cache value of SM unit count + virtual unsigned int getClockRate() const = 0; //!< returns cached value of SM clock frequency + virtual int getSharedMemPerBlock() const = 0; //!< returns total amount of shared memory available per block in bytes + virtual int getSharedMemPerMultiprocessor() const = 0; //!< returns total amount of shared memory available per multiprocessor in bytes + virtual unsigned int getMaxThreadsPerBlock() const = 0; //!< returns the maximum number of threads per block + virtual const char *getDeviceName() const = 0; //!< returns device name retrieved from driver + virtual CUdevice getDevice() const = 0; //!< returns device handle retrieved from driver + + virtual void setUsingConcurrentStreams(bool) = 0; //!< turn on/off using concurrent streams for GPU work + virtual bool getUsingConcurrentStreams() const = 0; //!< true if GPU work can run in concurrent streams + /* End query methods that don't require context to be acquired */ + + virtual void getDeviceMemoryInfo(size_t& free, size_t& total) const = 0; //!< get currently available and total memory + + /** + * \brief Get the cuda modules that have been loaded into this context on construction + * \return Pointer to the cuda modules + */ + virtual CUmodule* getCuModules() = 0; + + /** + * \brief Release the PxCudaContextManager + * + * If the PxCudaContextManager created the CUDA context it was + * responsible for, it also frees that context. + * + * Do not release the PxCudaContextManager if there are any scenes + * using it. Those scenes must be released first. + * + */ + virtual void release() = 0; + +protected: + + /** + * \brief protected destructor, use release() method + */ + virtual ~PxCudaContextManager() {} + + PX_DEPRECATED virtual void* allocDeviceBufferInternal(PxU64 numBytes, const char* filename = NULL, PxI32 line = -1) = 0; + PX_DEPRECATED virtual void* allocPinnedHostBufferInternal(PxU64 numBytes, const char* filename = NULL, PxI32 line = -1) = 0; + + PX_DEPRECATED virtual void freeDeviceBufferInternal(void* deviceBuffer) = 0; + PX_DEPRECATED virtual void freePinnedHostBufferInternal(void* pinnedHostBuffer) = 0; + + PX_DEPRECATED virtual void clearDeviceBufferAsyncInternal(void* deviceBuffer, PxU32 numBytes, CUstream stream, PxI32 value) = 0; + + PX_DEPRECATED virtual void copyDToHAsyncInternal(void* hostBuffer, const void* deviceBuffer, PxU32 numBytes, CUstream stream) = 0; + PX_DEPRECATED virtual void copyHToDAsyncInternal(void* deviceBuffer, const void* hostBuffer, PxU32 numBytes, CUstream stream) = 0; + PX_DEPRECATED virtual void copyDToDAsyncInternal(void* dstDeviceBuffer, const void* srcDeviceBuffer, PxU32 numBytes, CUstream stream) = 0; + + PX_DEPRECATED virtual void copyDToHInternal(void* hostBuffer, const void* deviceBuffer, PxU32 numBytes) = 0; + PX_DEPRECATED virtual void copyHToDInternal(void* deviceBuffer, const void* hostBuffer, PxU32 numBytes) = 0; + + PX_DEPRECATED virtual void memsetD8AsyncInternal(void* dstDeviceBuffer, const PxU8& value, PxU32 numBytes, CUstream stream) = 0; + PX_DEPRECATED virtual void memsetD32AsyncInternal(void* dstDeviceBuffer, const PxU32& value, PxU32 numIntegers, CUstream stream) = 0; +}; + +// These macros are deprecated. Please use the functions in extensions/PxCudaHelpersExt.h +/** + \deprecated Please use the functions in extensions/PxCudaHelpersExt.h + */ +#define PX_DEVICE_ALLOC(cudaContextManager, deviceBuffer, numElements) cudaContextManager->allocDeviceBuffer(deviceBuffer, numElements, PX_FL) + +/** + \deprecated Please use the functions in extensions/PxCudaHelpersExt.h + */ +#define PX_DEVICE_ALLOC_T(T, cudaContextManager, numElements) cudaContextManager->allocDeviceBuffer(numElements, PX_FL) + +/** + \deprecated Please use the functions in extensions/PxCudaHelpersExt.h + */ +#define PX_DEVICE_FREE(cudaContextManager, deviceBuffer) cudaContextManager->freeDeviceBuffer(deviceBuffer); + +/** + \deprecated Please use the functions in extensions/PxCudaHelpersExt.h + */ +#define PX_PINNED_HOST_ALLOC(cudaContextManager, pinnedHostBuffer, numElements) cudaContextManager->allocPinnedHostBuffer(pinnedHostBuffer, numElements, PX_FL) + +/** + \deprecated Please use the functions in extensions/PxCudaHelpersExt.h + */ +#define PX_PINNED_HOST_ALLOC_T(T, cudaContextManager, numElements) cudaContextManager->allocPinnedHostBuffer(numElements, PX_FL) + +/** + \deprecated Please use the functions in extensions/PxCudaHelpersExt.h + */ +#define PX_PINNED_HOST_FREE(cudaContextManager, pinnedHostBuffer) cudaContextManager->freePinnedHostBuffer(pinnedHostBuffer); + +/** + * \brief Convenience class for holding CUDA lock within a scope + */ +class PxScopedCudaLock +{ +public: + /** + * \brief ScopedCudaLock constructor + */ + PxScopedCudaLock(PxCudaContextManager& ctx) : mCtx(&ctx) + { + mCtx->acquireContext(); + } + + /** + * \brief ScopedCudaLock destructor + */ + ~PxScopedCudaLock() + { + mCtx->releaseContext(); + } + +protected: + + /** + * \brief CUDA context manager pointer (initialized in the constructor) + */ + PxCudaContextManager* mCtx; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_SUPPORT_GPU_PHYSX +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaTypes.h b/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaTypes.h new file mode 100644 index 000000000..73959a310 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/cudamanager/PxCudaTypes.h @@ -0,0 +1,71 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_CUDA_TYPES_H +#define PX_CUDA_TYPES_H + +//type definitions to avoid forced inclusion of cuda.h +//if cuda.h is needed anyway, please include it before PxCudaContextManager.h, PxCudaContext.h or PxCudaTypes.h + +#include "foundation/PxPreprocessor.h" + +#if PX_SUPPORT_GPU_PHYSX +#ifndef CUDA_VERSION + +#include "foundation/PxSimpleTypes.h" + +#if PX_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif + +#if PX_P64_FAMILY +typedef unsigned long long CUdeviceptr; +#else +typedef unsigned int CUdeviceptr; +#endif + +#if PX_CLANG +#pragma clang diagnostic pop +#endif + +typedef int CUdevice; + +typedef struct CUctx_st* CUcontext; +typedef struct CUmod_st* CUmodule; +typedef struct CUfunc_st* CUfunction; +typedef struct CUstream_st* CUstream; +typedef struct CUevent_st* CUevent; +typedef struct CUgraphicsResource_st* CUgraphicsResource; + +#endif + +#else +typedef struct CUstream_st* CUstream; // We declare some callbacks taking CUstream as an argument even when building with PX_SUPPORT_GPU_PHYSX = 0. +typedef struct CUevent_st* CUevent; +#endif // PX_SUPPORT_GPU_PHYSX +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxBroadPhaseExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxBroadPhaseExt.h new file mode 100644 index 000000000..82ad54a8e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxBroadPhaseExt.h @@ -0,0 +1,70 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BROAD_PHASE_EXT_H +#define PX_BROAD_PHASE_EXT_H + +#include "PxPhysXConfig.h" +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +class PxBounds3; +#endif + +class PxBroadPhaseExt +{ +public: + + /** + \brief Creates regions for PxSceneDesc, from a global box. + + This helper simply subdivides the given global box into a 2D grid of smaller boxes. Each one of those smaller boxes + is a region of interest for the broadphase. There are nbSubdiv*nbSubdiv regions in the 2D grid. The function does not + subdivide along the given up axis. + + This is the simplest setup one can use with PxBroadPhaseType::eMBP. A more sophisticated setup would try to cover + the game world with a non-uniform set of regions (i.e. not just a grid). + + \param[out] regions Regions computed from the input global box + \param[in] globalBounds World-space box covering the game world + \param[in] nbSubdiv Grid subdivision level. The function will create nbSubdiv*nbSubdiv regions. + \param[in] upAxis Up axis (0 for X, 1 for Y, 2 for Z). + \return number of regions written out to the 'regions' array + + \see PxSceneDesc PxBroadPhaseType + */ + static PxU32 createRegionsFromWorldBounds(PxBounds3* regions, const PxBounds3& globalBounds, PxU32 nbSubdiv, PxU32 upAxis=1); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCollectionExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCollectionExt.h new file mode 100644 index 000000000..e29140abb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCollectionExt.h @@ -0,0 +1,115 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_COLLECTION_EXT_H +#define PX_COLLECTION_EXT_H + +#include "PxPhysXConfig.h" +#include "common/PxCollection.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxCollection; + class PxScene; + + class PxCollectionExt + { + public: + /** + \brief Removes and releases all object from a collection. + + The Collection itself is not released. + + If the releaseExclusiveShapes flag is not set to true, release() will not be called on exclusive shapes. + + It is assumed that the application holds a reference to each of the objects in the collection, with the exception of objects that are not releasable + (PxBase::isReleasable()). In general, objects that violate this assumption need to be removed from the collection prior to calling releaseObjects. + + \note when a shape is created with PxRigidActorExt::createExclusiveShape(), the only counted reference is held by the actor. + If such a shape and its actor are present in the collection, the reference count will be decremented once when the actor is released, and once when the + shape is released, resulting in undefined behavior. Shape reference counts can be incremented with PxShape::acquireReference(). + + \param[in] collection to remove and release all object from. + \param[in] releaseExclusiveShapes if this parameter is set to false, release() will not be called on exclusive shapes. + */ + static void releaseObjects(PxCollection& collection, bool releaseExclusiveShapes = true); + + /** + \brief Removes objects of a given type from a collection, potentially adding them to another collection. + + \param[in,out] collection Collection from which objects are removed + \param[in] concreteType PxConcreteType of sdk objects that should be removed + \param[in,out] to Optional collection to which the removed objects are added + + \see PxCollection, PxConcreteType + */ + static void remove(PxCollection& collection, PxType concreteType, PxCollection* to = NULL); + + /** + \brief Collects all objects in PxPhysics that are shareable across multiple scenes. + + This function creates a new collection from all objects that are shareable across multiple + scenes. Instances of the following types are included: PxConvexMesh, PxTriangleMesh, + PxHeightField, PxShape and PxMaterial. + + This is a helper function to ease the creation of collections for serialization. + + \param[in] physics The physics SDK instance from which objects are collected. See #PxPhysics + \return Collection to which objects are added. See #PxCollection + + \see PxCollection, PxPhysics + */ + static PxCollection* createCollection(PxPhysics& physics); + + /** + \brief Collects all objects from a PxScene. + + This function creates a new collection from all objects that were added to the specified + PxScene. Instances of the following types are included: PxActor, PxAggregate, + PxArticulationReducedCoordinate and PxJoint (other PxConstraint types are not included). + + This is a helper function to ease the creation of collections for serialization. + The function PxSerialization.complete() can be used to complete the collection with required objects prior to + serialization. + + \param[in] scene The PxScene instance from which objects are collected. See #PxScene + \return Collection to which objects are added. See #PxCollection + + \see PxCollection, PxScene, PxSerialization.complete() + */ + static PxCollection* createCollection(PxScene& scene); + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConstraintExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConstraintExt.h new file mode 100644 index 000000000..7a63a062e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConstraintExt.h @@ -0,0 +1,63 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONSTRAINT_EXT_H +#define PX_CONSTRAINT_EXT_H + +#include "foundation/PxPreprocessor.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Unique identifiers for extensions classes which implement a constraint based on PxConstraint. + +\note Users which want to create their own custom constraint types should choose an ID larger or equal to eNEXT_FREE_ID +and not eINVALID_ID. + +\see PxConstraint PxSimulationEventCallback.onConstraintBreak() +*/ +struct PxConstraintExtIDs +{ + enum Enum + { + eJOINT, + eVEHICLE_JOINT, + eNEXT_FREE_ID, + eINVALID_ID = 0x7fffffff + }; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConvexCoreExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConvexCoreExt.h new file mode 100644 index 000000000..0b84e3cd7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConvexCoreExt.h @@ -0,0 +1,76 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONVEX_GEOMETRY_EXT_H +#define PX_CONVEX_GEOMETRY_EXT_H + +#include "foundation/PxMat33.h" +#include "foundation/PxTransform.h" +#include "geometry/PxConvexCoreGeometry.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxBounds3; +class PxRenderOutput; + +/** +\brief Convex geometry helpers +*/ +class PxConvexCoreExt +{ +public: + + /** + \brief Compute mass properties of the convex core geometry. + \param convex The convex geometry. + \param[out] density1Mass The mass of the geometry assuming unit density. + \param[out] inertiaTensor The inertia tensor of the geometry. + \param[out] centerOfMass The center of mass of the geometry. + */ + static void computeMassInfo(const PxConvexCoreGeometry& convex, PxReal& density1Mass, PxMat33& inertiaTensor, PxVec3& centerOfMass); + + /** + \brief Visualize the convex core geometry + \param convex The convex geometry. + \param pose The pose of the geometry in world space + \param drawCore If true, draw the core inside the full convex geometry including the margin + \param cullbox The culling box for visualization + \param out The render output object to use for visualization + */ + static void visualize(const PxConvexCoreGeometry& convex, const PxTransform& pose, bool drawCore, const PxBounds3& cullbox, PxRenderOutput& out); + +}; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConvexMeshExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConvexMeshExt.h new file mode 100644 index 000000000..907e1d9b8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxConvexMeshExt.h @@ -0,0 +1,68 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONVEX_MESH_EXT_H +#define PX_CONVEX_MESH_EXT_H + +#include "PxPhysXConfig.h" +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxConvexMeshGeometry; + + /** + \brief Computes closest polygon of the convex hull geometry for a given impact point + and impact direction. When doing sweeps against a scene, one might want to delay + the rather expensive computation of the hit face index for convexes until it is clear + the information is really needed and then use this method to get the corresponding + face index. + + \param[in] convexGeom The convex mesh geometry. + \param[in] geomPose Pose for the geometry object. + \param[in] impactPos Impact position. + \param[in] unitDir Normalized impact direction. + + \return Closest face index of the convex geometry. + + \see PxTransform PxConvexMeshGeometry + */ + PxU32 PxFindFaceIndex(const PxConvexMeshGeometry& convexGeom, + const PxTransform& geomPose, + const PxVec3& impactPos, + const PxVec3& unitDir); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCudaHelpersExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCudaHelpersExt.h new file mode 100644 index 000000000..03734be7a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCudaHelpersExt.h @@ -0,0 +1,317 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CUDA_HELPERS_EXT_H +#define PX_CUDA_HELPERS_EXT_H + + +#include "foundation/PxPreprocessor.h" + +#if PX_SUPPORT_GPU_PHYSX +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxAssert.h" +#include "foundation/PxFoundation.h" +#include "cudamanager/PxCudaContextManager.h" +#include "cudamanager/PxCudaContext.h" +#include "cudamanager/PxCudaTypes.h" + + +namespace physx +{ +namespace Ext +{ + +class PxCudaHelpersExt +{ +public: + +/** +* \brief Allocates a device buffer and returns the pointer to the memory +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context the allocation should be attributed to. +* \param[in] numElements the number of elements of type T to allocate. +* +* \return a pointer to the allocated memory. +*/ +template +static T* allocDeviceBuffer(PxCudaContextManager& cudaContextManager, PxU64 numElements) +{ + PxScopedCudaLock lock(cudaContextManager); + + CUdeviceptr ptr = 0; + PxCUresult result = cudaContextManager.getCudaContext()->memAlloc(&ptr, numElements * sizeof(T)); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "allocDeviceBuffer failed with error code %i!\n", PxI32(result)); + + return reinterpret_cast(ptr); +} + +/** +* \brief Frees a device buffer +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context the device buffer is attributed to. +* \param[in] deviceBuffer reference to a pointer pointing to the device memory buffer. +*/ +template +static void freeDeviceBuffer(PxCudaContextManager& cudaContextManager, T*& deviceBuffer) +{ + if (deviceBuffer) + { + PxScopedCudaLock lock(cudaContextManager); + PxCUresult result = cudaContextManager.getCudaContext()->memFree(reinterpret_cast(deviceBuffer)); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "freeDeviceBuffer failed with error code %i!\n", PxI32(result)); + + deviceBuffer = NULL; + } +} + +/** +* \brief Allocates a pinned host buffer and returns the pointer to the memory +* +* A pinned host buffer can be used on the gpu after getting a mapped device pointer from the pinned host buffer pointer, see getMappedDevicePtr +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context the allocation should be attributed to. +* \param[in] numElements the number of elements of type T to allocate. +* +* \return a pointer to the allocated memory. +*/ +template +static T* allocPinnedHostBuffer(PxCudaContextManager& cudaContextManager, PxU64 numElements) +{ + PxScopedCudaLock lock(cudaContextManager); + + void* ptr = NULL; + const unsigned int cuMemhostallocDevicemap = 0x02; + const unsigned int cuMemhostallocPortable = 0x01; + PxCUresult result = cudaContextManager.getCudaContext()->memHostAlloc(&ptr, numElements * sizeof(T), cuMemhostallocDevicemap | cuMemhostallocPortable); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "allocPinnedHostBuffer failed with error code %i!\n", PxI32(result)); + + return reinterpret_cast(ptr); +} + +/** +* \brief Frees a pinned host buffer +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context the pinned memory buffer is attributed to. +* \param[in] pinnedHostBuffer reference to a pointer pointing to the pinned memory buffer. +*/ +template +static void freePinnedHostBuffer(PxCudaContextManager& cudaContextManager, T*& pinnedHostBuffer) +{ + if (pinnedHostBuffer) + { + PxScopedCudaLock lock(cudaContextManager); + PxCUresult result = cudaContextManager.getCudaContext()->memFreeHost(pinnedHostBuffer); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "freePinnedHostBuffer failed with error code %i!\n", PxI32(result)); + + pinnedHostBuffer = NULL; + } +} + +/** +* \brief Copies a device buffer to the host +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context executing the operation. +* \param[in] hostBuffer pointer to the destination (pinned) host memory buffer. +* \param[in] deviceBuffer pointer to the source device buffer. +* \param[in] numElements the number of elements of type T to copy. +*/ +template +static void copyDToH(PxCudaContextManager& cudaContextManager, T* hostBuffer, const T* deviceBuffer, PxU64 numElements) +{ + if (!deviceBuffer || !hostBuffer) + return; + + PxScopedCudaLock lock(cudaContextManager); + PxU64 numBytes = numElements * sizeof(T); + + PxCUresult result = cudaContextManager.getCudaContext()->memcpyDtoH(hostBuffer, CUdeviceptr(deviceBuffer), numBytes); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "copyDToH failed with error code %i!\n", PxI32(result)); +} + +/** +* \brief Copies a host buffer to the device +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context executing the operation. +* \param[in] deviceBuffer pointer to the destination device buffer. +* \param[in] hostBuffer pointer to the source (pinned) host memory buffer. +* \param[in] numElements the number of elements of type T to copy. +*/ +template +static void copyHToD(PxCudaContextManager& cudaContextManager, T* deviceBuffer, const T* hostBuffer, PxU64 numElements) +{ + if (!deviceBuffer || !hostBuffer) + return; + + PxScopedCudaLock lock(cudaContextManager); + PxU64 numBytes = numElements * sizeof(T); + + PxCUresult result = cudaContextManager.getCudaContext()->memcpyHtoD(CUdeviceptr(deviceBuffer), hostBuffer, numBytes); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "copyHtoD failed with error code %i!\n", PxI32(result)); +} + +/** +* \brief Schedules device to host copy operation on the specified stream +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context executing the operation. +* \param[in] hostBuffer pointer to the destination (pinned) host memory buffer. +* \param[in] deviceBuffer pointer to the source device buffer. +* \param[in] numElements the number of elements of type T to copy. +* \param[in] stream the CUDA stream to perform the operation on. +*/ +template +static void copyDToHAsync(PxCudaContextManager& cudaContextManager, T* hostBuffer, const T* deviceBuffer, PxU64 numElements, CUstream stream) +{ + if (!deviceBuffer || !hostBuffer) + return; + + PxScopedCudaLock lock(cudaContextManager); + PxU64 numBytes = numElements * sizeof(T); + + PxCUresult result = cudaContextManager.getCudaContext()->memcpyDtoHAsync(hostBuffer, CUdeviceptr(deviceBuffer), numBytes, stream); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "copyDtoHAsync failed with error code %i!\n", PxI32(result)); +} + +/** +* \brief Schedules host to device copy operation on the specified stream +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context executing the operation. +* \param[in] deviceBuffer pointer to the destination device buffer. +* \param[in] hostBuffer pointer to the source (pinned) host memory buffer. +* \param[in] numElements the number of elements of type T to copy. +* \param[in] stream the CUDA stream to perform the operation on. +*/ +template +static void copyHToDAsync(PxCudaContextManager& cudaContextManager, T* deviceBuffer, const T* hostBuffer, PxU64 numElements, CUstream stream) +{ + if (!deviceBuffer || !hostBuffer) + return; + + PxScopedCudaLock lock(cudaContextManager); + PxU64 numBytes = numElements * sizeof(T); + + PxCUresult result = cudaContextManager.getCudaContext()->memcpyHtoDAsync(CUdeviceptr(deviceBuffer), hostBuffer, numBytes, stream); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "copyHtoDAsync failed with error code %i!\n", PxI32(result)); +} + +/** +* \brief Schedules device to device copy operation on the specified stream +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context executing the operation. +* \param[in] dstDeviceBuffer pointer to the destination device buffer. +* \param[in] srcDeviceBuffer pointer to the source device buffer. +* \param[in] numElements the number of elements of type T to copy. +* \param[in] stream the CUDA stream to perform the operation on. +*/ +template +static void copyDToDAsync(PxCudaContextManager& cudaContextManager, T* dstDeviceBuffer, const T* srcDeviceBuffer, PxU64 numElements, CUstream stream) +{ + if (!srcDeviceBuffer || !dstDeviceBuffer) + return; + + PxScopedCudaLock lock(cudaContextManager); + PxU64 numBytes = numElements * sizeof(T); + + PxCUresult result = cudaContextManager.getCudaContext()->memcpyDtoDAsync(CUdeviceptr(dstDeviceBuffer), CUdeviceptr(srcDeviceBuffer), numBytes, stream); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "copyDtoDAsync failed with error code %i!\n", PxI32(result)); +} + +/** +* \brief Schedules a memset operation on the device on the specified stream. Only supported for 1 bytes or 4 byte data types. +* +* The cuda context will get acquired automatically +* +* \param[in] cudaContextManager the PxCudaContextManager managing the CUDA context executing the operation. +* \param[in] dstDeviceBuffer pointer to the destination device buffer. +* \param[in] value the value to set the memory to. +* \param[in] numElements the number of elements of type T to set. +* \param[in] stream the CUDA stream to perform the operation on. +*/ +template +static void memsetAsync(PxCudaContextManager& cudaContextManager, T* dstDeviceBuffer, const T& value, PxU64 numElements, CUstream stream) +{ + PX_COMPILE_TIME_ASSERT(sizeof(T) == sizeof(PxU32) || sizeof(T) == sizeof(PxU8)); + + if (!dstDeviceBuffer) + return; + + PxScopedCudaLock lock(cudaContextManager); + PxU64 numBytes = numElements * sizeof(T); + + if (sizeof(T) == sizeof(PxU32)) + { + PxCUresult result = cudaContextManager.getCudaContext()->memsetD32Async(CUdeviceptr(dstDeviceBuffer), reinterpret_cast(value), numBytes >> 2, stream); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "memsetAsync failed with error code %i!\n", PxI32(result)); + } + else + { + PxCUresult result = cudaContextManager.getCudaContext()->memsetD8Async(CUdeviceptr(dstDeviceBuffer), reinterpret_cast(value), numBytes, stream); + if (result != 0) + PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "memsetAsync failed with error code %i!\n", PxI32(result)); + } +} +}; + +#define PX_EXT_DEVICE_MEMORY_ALLOC(T, cudaContextManager, numElements) physx::Ext::PxCudaHelpersExt::allocDeviceBuffer(cudaContextManager, numElements) +#define PX_EXT_DEVICE_MEMORY_FREE(cudaContextManager, deviceBuffer) physx::Ext::PxCudaHelpersExt::freeDeviceBuffer(cudaContextManager, deviceBuffer); + +#define PX_EXT_PINNED_MEMORY_ALLOC(T, cudaContextManager, numElements) physx::Ext::PxCudaHelpersExt::allocPinnedHostBuffer(cudaContextManager, numElements) +#define PX_EXT_PINNED_MEMORY_FREE(cudaContextManager, pinnedHostBuffer) physx::Ext::PxCudaHelpersExt::freePinnedHostBuffer(cudaContextManager, pinnedHostBuffer); + +} +} + +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCustomGeometryExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCustomGeometryExt.h new file mode 100644 index 000000000..0598c9ab4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCustomGeometryExt.h @@ -0,0 +1,221 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CUSTOM_GEOMETRY_EXT_H +#define PX_CUSTOM_GEOMETRY_EXT_H + +#include "geometry/PxCustomGeometry.h" +#include "geometry/PxGjkQuery.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxGeometry; +class PxMassProperties; +class PxGeometryHolder; +struct PxContactPoint; + +/** +\brief Pre-made custom geometry callbacks implementations. +*/ +class PxCustomGeometryExt +{ +public: + + /// \cond PRIVATE + struct BaseConvexCallbacks : PxCustomGeometry::Callbacks, PxGjkQuery::Support + { + BaseConvexCallbacks(float _margin) : margin(_margin) {} + + // override PxCustomGeometry::Callbacks + virtual PxBounds3 getLocalBounds(const PxGeometry& geometry) const; + virtual bool generateContacts(const PxGeometry& geom0, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, + const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, + PxContactBuffer& contactBuffer) const; + virtual PxU32 raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose, + PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* rayHits, PxU32 stride, PxRaycastThreadContext*) const; + virtual bool overlap(const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const; + virtual bool sweep(const PxVec3& unitDir, const PxReal maxDist, + const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, + PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext*) const; + virtual bool usePersistentContactManifold(const PxGeometry& geometry, PxReal& breakingThreshold) const; + + // override PxGjkQuery::Support + virtual PxReal getMargin() const { return margin; } + // set margin + void setMargin(float m); + + protected: + + // Shape margin + float margin; + + // Substitute geometry + virtual bool useSubstituteGeometry(PxGeometryHolder& geom, PxTransform& preTransform, const PxContactPoint& p, const PxTransform& pose0) const = 0; + }; + /// \endcond + + /** + \brief Cylinder geometry callbacks + */ + struct CylinderCallbacks : BaseConvexCallbacks + { + /** + \brief Construct cylinder geometry callbacks object + + \param[in] height The cylinder height. + \param[in] radius The cylinder radius. + \param[in] axis The cylinder axis (0 - X, 1 - Y, 2 - Z). + \param[in] margin The cylinder margin. + */ + CylinderCallbacks(float height, float radius, int axis = 0, float margin = 0); + + /// \brief Set cylinder height + /// \param[in] h The cylinder height + void setHeight(float h); + /// \brief Get cylinder height + /// \return The cylinder height + float getHeight() const { return height; } + + /// \brief Set cylinder radius + /// \param[in] r The cylinder radius. + void setRadius(float r); + /// \brief Get cylinder radius + /// \return The cylinder radius + float getRadius() const { return radius; } + + /// \brief Set cylinder axis + /// \param[in] a The cylinder axis (0 - X, 1 - Y, 2 - Z). + void setAxis(int a); + /// \brief Get cylinder axis + /// \return The cylinder axis + int getAxis() const { return axis; } + + /// \cond PRIVATE + // override PxCustomGeometry::Callbacks + DECLARE_CUSTOM_GEOMETRY_TYPE + virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const; + virtual void computeMassProperties(const PxGeometry& geometry, PxMassProperties& massProperties) const; + + // override PxGjkQuery::Support + virtual PxVec3 supportLocal(const PxVec3& dir) const; + + protected: + + // Cylinder height + float height; + // Cylinder radius + float radius; + // Cylinder axis + int axis; + + // Substitute geometry + virtual bool useSubstituteGeometry(PxGeometryHolder& geom, PxTransform& preTransform, const PxContactPoint& p, const PxTransform& pose0) const; + + // Radius at height + float getRadiusAtHeight(float height) const; + /// \endcond + }; + + /** + \brief Cone geometry callbacks + */ + struct ConeCallbacks : BaseConvexCallbacks + { + /** + \brief Construct cone geometry callbacks object + + \param[in] height The cylinder height. + \param[in] radius The cylinder radius. + \param[in] axis The cylinder axis (0 - X, 1 - Y, 2 - Z). + \param[in] margin The cylinder margin. + */ + ConeCallbacks(float height, float radius, int axis = 0, float margin = 0); + + /// \brief Set cone height + /// \param[in] h The cone height + void setHeight(float h); + /// \brief Get cone height + /// \return The cone height + float getHeight() const { return height; } + + /// \brief Set cone radius + /// \param[in] r The cone radius + void setRadius(float r); + /// \brief Get cone radius + /// \return The cone radius + float getRadius() const { return radius; } + + /// \brief Set cone axis + /// \param[in] a The cone axis + void setAxis(int a); + /// \brief Get cone axis + /// \return The cone axis + int getAxis() const { return axis; } + + /// \cond PRIVATE + // override PxCustomGeometry::Callbacks + DECLARE_CUSTOM_GEOMETRY_TYPE + virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const; + virtual void computeMassProperties(const PxGeometry& geometry, PxMassProperties& massProperties) const; + + // override PxGjkQuery::Support + virtual PxVec3 supportLocal(const PxVec3& dir) const; + + protected: + + // Cone height + float height; + // Cone radius + float radius; + // Cone axis + int axis; + + // Substitute geometry + virtual bool useSubstituteGeometry(PxGeometryHolder& geom, PxTransform& preTransform, const PxContactPoint& p, const PxTransform& pose0) const; + + // Radius at height + float getRadiusAtHeight(float height) const; + /// \endcond + }; +}; + +/// \cond PRIVATE +// OmniPVD friendly aliases +typedef PxCustomGeometryExt::BaseConvexCallbacks PxCustomGeometryExtBaseConvexCallbacks; +typedef PxCustomGeometryExt::CylinderCallbacks PxCustomGeometryExtCylinderCallbacks; +typedef PxCustomGeometryExt::ConeCallbacks PxCustomGeometryExtConeCallbacks; +/// \endcond + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCustomSceneQuerySystem.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCustomSceneQuerySystem.h new file mode 100644 index 000000000..77ef6fe80 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxCustomSceneQuerySystem.h @@ -0,0 +1,187 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_NEW_SCENE_QUERY_SYSTEM_H +#define PX_NEW_SCENE_QUERY_SYSTEM_H + +#include "PxSceneQuerySystem.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief A custom scene query system. + + This is an example of a custom scene query system. It augments the PxSceneQuerySystem API to support an arbitrary number + of "pruners", instead of the usual hardcoded two. + + It might not be possible to support the whole PxSceneQuerySystem API in this context. See the source code for details. + + \see PxSceneQuerySystem + */ + class PxCustomSceneQuerySystem : public PxSceneQuerySystem + { + public: + PxCustomSceneQuerySystem() {} + virtual ~PxCustomSceneQuerySystem() {} + + /** + \brief Adds a pruner to the system. + + The internal PhysX scene-query system uses two regular pruners (one for static shapes, one for dynamic shapes) and an optional + compound pruner. Our custom scene query system supports an arbitrary number of regular pruners. + + This can be useful to reduce the load on each pruner, in particular during updates, when internal trees are rebuilt in the + background. On the other hand this implementation simply iterates over all created pruners to perform queries, so their cost + might increase if a large number of pruners is used. + + In any case this serves as an example of how the PxSceneQuerySystem API can be used to customize scene queries. + + \param[in] primaryType Desired primary (main) type for the new pruner + \param[in] secondaryType Secondary type when primary type is PxPruningStructureType::eDYNAMIC_AABB_TREE. + \param[in] preallocated Optional number of preallocated shapes in the new pruner + + \return A pruner index + + \see PxCustomSceneQuerySystem PxSceneQueryUpdateMode PxCustomSceneQuerySystemAdapter PxSceneDesc::sceneQuerySystem + */ + virtual PxU32 addPruner(PxPruningStructureType::Enum primaryType, PxDynamicTreeSecondaryPruner::Enum secondaryType, PxU32 preallocated=0) = 0; + + /** + \brief Start custom build-steps for all pruners + + This function is used in combination with customBuildstep() and finishCustomBuildstep() to let users take control + of the pruners' build-step & commit calls - basically the pruners' update functions. These functions should be used + with the PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED update mode, otherwise the build-steps will happen + automatically in fetchResults. For N pruners it can be more efficient to use these custom build-step functions to + perform the updates in parallel: + + - call startCustomBuildstep() first (one synchronous call) + - for each pruner, call customBuildstep() (asynchronous calls from multiple threads) + - once it is done, call finishCustomBuildstep() to finish the update (synchronous call) + + The multi-threaded update is more efficient here than what it is in PxScene, because the "flushShapes()" call is + also multi-threaded (while it is not in PxScene). + + Note that users are responsible for locks here, and these calls should not overlap with other SQ calls. In particular + one should not add new objects to the SQ system or perform queries while these calls are happening. + + \return The number of pruners in the system. + + \see customBuildstep finishCustomBuildstep PxSceneQueryUpdateMode + */ + virtual PxU32 startCustomBuildstep() = 0; + + /** + \brief Perform a custom build-step for a given pruner. + + \param[in] index Pruner index (should be between 0 and the number returned by startCustomBuildstep) + + \see startCustomBuildstep finishCustomBuildstep + */ + virtual void customBuildstep(PxU32 index) = 0; + + /** + \brief Finish custom build-steps + + Call this function once after all the customBuildstep() calls are done. + + \see startCustomBuildstep customBuildstep + */ + virtual void finishCustomBuildstep() = 0; + }; + + /** + \brief An adapter class to customize the object-to-pruner mapping. + + In the regular PhysX code static shapes went to the static pruner, and dynamic shapes went to the + dynamic pruner. + + This class is a replacement for this mapping when N user-defined pruners are involved. + */ + class PxCustomSceneQuerySystemAdapter + { + public: + PxCustomSceneQuerySystemAdapter() {} + virtual ~PxCustomSceneQuerySystemAdapter() {} + + /** + \brief Gets a pruner index for an actor/shape. + + This user-defined function tells the system in which pruner a given actor/shape should go. + + \note The returned index must be valid, i.e. it must have been previously returned to users by PxCustomSceneQuerySystem::addPruner. + + \param[in] actor The actor + \param[in] shape The shape + + \return A pruner index for this actor/shape. + + \see PxRigidActor PxShape PxCustomSceneQuerySystem::addPruner + */ + virtual PxU32 getPrunerIndex(const PxRigidActor& actor, const PxShape& shape) const = 0; + + /** + \brief Pruner filtering callback. + + This will be called for each query to validate whether it should process a given pruner. + + \param[in] prunerIndex The index of currently processed pruner + \param[in] context The query context + \param[in] filterData The query's filter data + \param[in] filterCall The query's filter callback + + \return True to process the pruner, false to skip it entirely + */ + virtual bool processPruner(PxU32 prunerIndex, const PxQueryThreadContext* context, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const = 0; + }; + + /** + \brief Creates a custom scene query system. + + This is similar to PxCreateExternalSceneQuerySystem, except this function creates a PxCustomSceneQuerySystem object. + It can be plugged to PxScene the same way, via PxSceneDesc::sceneQuerySystem. + + \param[in] sceneQueryUpdateMode Desired update mode + \param[in] contextID Context ID parameter, sent to the profiler + \param[in] adapter Adapter class implementing our extended API + \param[in] usesTreeOfPruners True to keep pruners themselves in a BVH, which might increase query performance if a lot of pruners are involved + + \return A custom SQ system instance + + \see PxCustomSceneQuerySystem PxSceneQueryUpdateMode PxCustomSceneQuerySystemAdapter PxSceneDesc::sceneQuerySystem + */ + PxCustomSceneQuerySystem* PxCreateCustomSceneQuerySystem(PxSceneQueryUpdateMode::Enum sceneQueryUpdateMode, PxU64 contextID, const PxCustomSceneQuerySystemAdapter& adapter, bool usesTreeOfPruners=false); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxD6Joint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxD6Joint.h new file mode 100644 index 000000000..12e7014b5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxD6Joint.h @@ -0,0 +1,632 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_D6_JOINT_H +#define PX_D6_JOINT_H + +#include "extensions/PxJoint.h" +#include "extensions/PxJointLimit.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxD6Joint; + +/** +\brief Create a D6 joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + +\see PxD6Joint +*/ +PxD6Joint* PxD6JointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + +/** +\brief Used to specify one of the degrees of freedom of a D6 joint. + +\see PxD6Joint +*/ +struct PxD6Axis +{ + enum Enum + { + eX = 0, //!< motion along the X axis + eY = 1, //!< motion along the Y axis + eZ = 2, //!< motion along the Z axis + eTWIST = 3, //!< motion around the X axis + eSWING1 = 4, //!< motion around the Y axis + eSWING2 = 5, //!< motion around the Z axis + eCOUNT = 6 + }; +}; + + +/** +\brief Used to specify the range of motions allowed for a degree of freedom in a D6 joint. + +\see PxD6Joint +*/ +struct PxD6Motion +{ + enum Enum + { + eLOCKED, //!< The DOF is locked, it does not allow relative motion. + eLIMITED, //!< The DOF is limited, it only allows motion within a specific range. + eFREE //!< The DOF is free and has its full range of motion. + }; +}; + + +/** +\brief The configuration to use for driving to the angular component of a target pose or velocity. + +\see PxD6Joint::setAngularDriveConfig() PxD6Drive PxD6Joint::setDrive() +*/ +struct PxD6AngularDriveConfig +{ + enum Enum + { + /** + \brief The joint tries to reach the angular drive target by separately driving along each angular degree of freedom. + + Each angular degree of freedom can have its own set of drive parameters. The degrees of freedom are covered by a twist and two swing axes. + As a consequence, only the following options are available when setting the drive parameters: PxD6Drive::eSWING1, PxD6Drive::eSWING2, + PxD6Drive::eTWIST (see #PxD6Joint::setDrive()). + */ + eSWING_TWIST, + + /** + \brief The joint tries to reach the angular drive target by following a spherical linear interpolation (SLERP) based path. + + A single set of drive parameters will be used for all angular degrees of freedom and PxD6Drive::eSLERP is the only valid option to set + those parameters (see #PxD6Joint::setDrive()). + */ + eSLERP, + + /** + \deprecated + + \brief Legacy mode that uses a precedence system to either use the slerp or swing/twist angular drive model. + + \note In this config it is not possible to set separate drive parameters for the two swing axes. + + For compatibility with previous versions of PhysX, drive parameters for PxD6Drive::eTWIST, PxD6Drive::eSWING and PxD6Drive::eSLERP + can be set alltogether with ::eSLERP taking precedence (see #PxD6Joint::setDrive()). Use of PxD6Drive::eSWING1 and PxD6Drive::eSWING2 + is not allowed. + */ + eLEGACY PX_DEPRECATED + }; +}; + + +/** +\brief Used to specify which axes of a D6 joint are driven. + +Each drive is an implicit force-limited damped spring: + +force = spring * (target position - position) + damping * (targetVelocity - velocity) + +Alternatively, the spring may be configured to generate a specified acceleration instead of a force. + +A linear axis is affected by drive only if the corresponding drive flag is set. There are two possible models +for angular drive: swing/twist, which may be used to drive one or more angular degrees of freedom, or slerp, +which may only be used to drive all three angular degrees simultaneously. Please use #PxD6AngularDriveConfig +to configure the angular drive model. + +\see PxD6Joint PxD6AngularDriveConfig +*/ +struct PxD6Drive +{ + enum Enum + { + eX = 0, //!< drive along the X-axis + eY = 1, //!< drive along the Y-axis + eZ = 2, //!< drive along the Z-axis + + /** + \deprecated + + \brief rotational drive around the Y- and Z-axis + + \note Only allowed if the angular drive configuration is set to PxD6AngularDriveConfig::eLEGACY. + */ + eSWING PX_DEPRECATED = 3, + + /** + \brief rotational drive around the X-axis + + \note Only allowed if the angular drive configuration is set to PxD6AngularDriveConfig::eLEGACY or + PxD6AngularDriveConfig::eSWING_TWIST. + */ + eTWIST = 4, + + /** + \brief drive of all three angular degrees along a SLERP-path + + \note Only allowed if the angular drive configuration is set to PxD6AngularDriveConfig::eSLERP or + PxD6AngularDriveConfig::eLEGACY. + + \note If the angular drive configuration is set to PxD6AngularDriveConfig::eLEGACY, then eSLERP takes + precedence over eSWING/eTWIST + */ + eSLERP = 5, + + /** + \brief rotational drive around the Y-axis + + \note Only allowed if the angular drive configuration is set to PxD6AngularDriveConfig::eSWING_TWIST. + */ + eSWING1 = 6, + + /** + \brief rotational drive around the Z-axis + + \note Only allowed if the angular drive configuration is set to PxD6AngularDriveConfig::eSWING_TWIST. + */ + eSWING2 = 7, + + eCOUNT = 8 + }; +}; + +/** +\brief flags for configuring the drive model of a PxD6Joint + +\see PxD6JointDrive PxD6Joint +*/ +struct PxD6JointDriveFlag +{ + enum Enum + { + eACCELERATION = (1 << 0), //!< drive spring is for the acceleration at the joint (rather than the force) + + /** + \brief Add drive force/torque to the joint force/torque total. + + If this flag is raised, the force/torque value from this drive constraint will be accumulated + in the force/torque total that is reported for the underlying PxConstraint object. Note that + because the force/torque total changes, the joint break behavior will change too. + + Default: False + + \see PxConstraint::getForce() + */ + eOUTPUT_FORCE = (1 << 1) + }; +}; +typedef PxFlags PxD6JointDriveFlags; +PX_FLAGS_OPERATORS(PxD6JointDriveFlag::Enum, PxU32) + +/** +\brief parameters for configuring the drive model of a PxD6Joint + +\see PxD6Joint +*/ +class PxD6JointDrive : public PxSpring +{ +public: + PxReal forceLimit; //!< the force limit of the drive - may be an impulse or a force depending on PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES + PxD6JointDriveFlags flags; //!< the joint drive flags + + /** + \brief default constructor for PxD6JointDrive. + */ + PxD6JointDrive(): PxSpring(0,0), forceLimit(PX_MAX_F32), flags(0) {} + + /** + \brief constructor a PxD6JointDrive. + + \param[in] driveStiffness The stiffness of the drive spring. + \param[in] driveDamping The damping of the drive spring + \param[in] driveForceLimit The maximum impulse or force that can be exerted by the drive + \param[in] isAcceleration Whether the drive is an acceleration drive or a force drive + */ + PxD6JointDrive(PxReal driveStiffness, PxReal driveDamping, PxReal driveForceLimit, bool isAcceleration = false) + : PxSpring(driveStiffness, driveDamping) + , forceLimit(driveForceLimit) + , flags(isAcceleration?PxU32(PxD6JointDriveFlag::eACCELERATION) : 0) + {} + + /** + \brief returns true if the drive is valid + */ + bool isValid() const + { + return PxIsFinite(stiffness) && stiffness>=0 && + PxIsFinite(damping) && damping >=0 && + PxIsFinite(forceLimit) && forceLimit >=0; + } +}; + + +/** + \brief A D6 joint is a general constraint between two actors. + + It allows the application to individually define the linear and rotational degrees of freedom, + and also to configure a variety of limits and driven degrees of freedom. + + By default all degrees of freedom are locked. So to create a prismatic joint with free motion + along the x-axis: + + \code + ... + joint->setMotion(PxD6Axis::eX, PxD6JointMotion::eFREE); + ... + \endcode + + Or a Revolute joint with motion free allowed around the x-axis: + + \code + ... + joint->setMotion(PxD6Axis::eTWIST, PxD6JointMotion::eFREE); + ... + \endcode + + Degrees of freedom may also be set to limited instead of locked. + + There are two different kinds of linear limits available. The first kind is a single limit value + for all linear degrees of freedom, which may act as a linear, circular, or spherical limit depending + on which degrees of freedom are limited. This is similar to a distance limit. Then, the second kind + supports a pair of limit values for each linear axis, which can be used to implement a traditional + prismatic joint for example. + + If the twist degree of freedom is limited, is supports upper and lower limits. The two swing degrees + of freedom are limited with a cone limit. +\see PxD6JointCreate() PxJoint +*/ +class PxD6Joint : public PxJoint +{ +public: + + /** + \brief Set the motion type around the specified axis. + + Each axis may independently specify that the degree of freedom is locked (blocking relative movement + along or around this axis), limited by the corresponding limit, or free. + + \param[in] axis the axis around which motion is specified + \param[in] type the motion type around the specified axis + + Default: all degrees of freedom are locked + + \see getMotion() PxD6Axis PxD6Motion + */ + virtual void setMotion(PxD6Axis::Enum axis, PxD6Motion::Enum type) = 0; + + /** + \brief Get the motion type around the specified axis. + + \see setMotion() PxD6Axis PxD6Motion + + \param[in] axis the degree of freedom around which the motion type is specified + \return the motion type around the specified axis + */ + virtual PxD6Motion::Enum getMotion(PxD6Axis::Enum axis) const = 0; + + /** + \brief get the twist angle of the joint, in the range (-2*Pi, 2*Pi] + */ + virtual PxReal getTwistAngle() const = 0; + + /** + \brief get the twist angle of the joint + + \deprecated Use getTwistAngle instead. Deprecated since PhysX version 4.0 + */ + PX_DEPRECATED PX_FORCE_INLINE PxReal getTwist() const { return getTwistAngle(); } + + /** + \brief get the swing angle of the joint from the Y axis + */ + virtual PxReal getSwingYAngle() const = 0; + + /** + \brief get the swing angle of the joint from the Z axis + */ + virtual PxReal getSwingZAngle() const = 0; + + /** + \brief Set the distance limit for the joint. + + A single limit constraints all linear limited degrees of freedom, forming a linear, circular + or spherical constraint on motion depending on the number of limited degrees. This is similar + to a distance limit. + + \param[in] limit the distance limit structure + + \see getDistanceLimit() PxJointLinearLimit + */ + virtual void setDistanceLimit(const PxJointLinearLimit& limit) = 0; + + /** + \brief Get the distance limit for the joint. + + \return the distance limit structure + + \see setDistanceLimit() PxJointLinearLimit + */ + virtual PxJointLinearLimit getDistanceLimit() const = 0; + + /** + \deprecated Use setDistanceLimit instead. Deprecated since PhysX version 4.0 + */ + PX_DEPRECATED PX_FORCE_INLINE void setLinearLimit(const PxJointLinearLimit& limit) { setDistanceLimit(limit); } + + /** + \deprecated Use getDistanceLimit instead. Deprecated since PhysX version 4.0 + */ + PX_DEPRECATED PX_FORCE_INLINE PxJointLinearLimit getLinearLimit() const { return getDistanceLimit(); } + + /** + \brief Set the linear limit for a given linear axis. + + This function extends the previous setDistanceLimit call with the following features: + - there can be a different limit for each linear axis + - each limit is defined by two values, i.e. it can now be asymmetric + + This can be used to create prismatic joints similar to PxPrismaticJoint, or point-in-quad joints, + or point-in-box joints. + + \param[in] axis The limited linear axis (must be PxD6Axis::eX, PxD6Axis::eY or PxD6Axis::eZ) + \param[in] limit The linear limit pair structure + + \see getLinearLimit() + */ + virtual void setLinearLimit(PxD6Axis::Enum axis, const PxJointLinearLimitPair& limit) = 0; + + /** + \brief Get the linear limit for a given linear axis. + + \param[in] axis The limited linear axis (must be PxD6Axis::eX, PxD6Axis::eY or PxD6Axis::eZ) + + \return the linear limit pair structure from desired axis + + \see setLinearLimit() PxJointLinearLimit + */ + virtual PxJointLinearLimitPair getLinearLimit(PxD6Axis::Enum axis) const = 0; + + /** + \brief Set the twist limit for the joint. + + The twist limit controls the range of motion around the twist axis. + + The limit angle range is (-2*Pi, 2*Pi). + + \param[in] limit the twist limit structure + + \see getTwistLimit() PxJointAngularLimitPair + */ + virtual void setTwistLimit(const PxJointAngularLimitPair& limit) = 0; + + /** + \brief Get the twist limit for the joint. + + \return the twist limit structure + + \see setTwistLimit() PxJointAngularLimitPair + */ + virtual PxJointAngularLimitPair getTwistLimit() const = 0; + + /** + \brief Set the swing cone limit for the joint. + + The cone limit is used if either or both swing axes are limited. The extents are + symmetrical and measured in the frame of the parent. If only one swing degree of freedom + is limited, the corresponding value from the cone limit defines the limit range. + + \param[in] limit the cone limit structure + + \see getLimitCone() PxJointLimitCone + */ + virtual void setSwingLimit(const PxJointLimitCone& limit) = 0; + + /** + \brief Get the cone limit for the joint. + + \return the swing limit structure + + \see setLimitCone() PxJointLimitCone + */ + virtual PxJointLimitCone getSwingLimit() const = 0; + + /** + \brief Set a pyramidal swing limit for the joint. + + The pyramid limits will only be used in the following cases: + - both swing Y and Z are limited. The limit shape is then a pyramid. + - Y is limited and Z is locked, or vice versa. The limit shape is an asymmetric angular section, similar to + what is supported for the twist axis. + The remaining cases (Y limited and Z is free, or vice versa) are not supported. + + \param[in] limit the cone limit structure + + \see getLimitCone() PxJointLimitPyramid + */ + virtual void setPyramidSwingLimit(const PxJointLimitPyramid& limit) = 0; + + /** + \brief Get the pyramidal swing limit for the joint. + + \return the swing limit structure + + \see setLimitCone() PxJointLimitPyramid + */ + virtual PxJointLimitPyramid getPyramidSwingLimit() const = 0; + + /** + \brief Set the drive parameters for the specified drive type. + + \note The angular drive configuration (see #PxD6AngularDriveConfig) defines what type of + angular drives will be accepted. + + \param[in] index the type of drive being specified + \param[in] drive the drive parameters + + \see getDrive() PxD6JointDrive PxD6AngularDriveConfig + + Default The default drive spring and damping values are zero, the force limit is PX_MAX_F32, and no flags are set. + */ + virtual void setDrive(PxD6Drive::Enum index, const PxD6JointDrive& drive) = 0; + + /** + \brief Get the drive parameters for the specified drive type. + + \note The angular drive configuration (see #PxD6AngularDriveConfig) defines what type of + angular drives will be accepted. + + \param[in] index the specified drive type + + \see setDrive() PxD6JointDrive PxD6AngularDriveConfig + */ + virtual PxD6JointDrive getDrive(PxD6Drive::Enum index) const = 0; + + /** + \brief Set the drive goal pose + + The goal is relative to the constraint frame of actor[0] + + Default the identity transform + + \param[in] pose The goal drive pose if positional drive is in use. + \param[in] autowake If true and the attached actors are in a scene, this call wakes them up and increases their + wake counters to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value. + + \see setDrivePosition() + */ + virtual void setDrivePosition(const PxTransform& pose, bool autowake = true) = 0; + + /** + \brief Get the drive goal pose. + + \see getDrivePosition() + */ + virtual PxTransform getDrivePosition() const = 0; + + /** + \brief Set the target goal velocity for drive. + + The velocity is measured in the constraint frame of actor[0] + + \param[in] linear The goal velocity for linear drive + \param[in] angular The goal velocity for angular drive + \param[in] autowake If true and the attached actors are in a scene, this call wakes them up and increases their + wake counters to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value. + + \see getDriveVelocity() + */ + virtual void setDriveVelocity(const PxVec3& linear, const PxVec3& angular, bool autowake = true) = 0; + + /** + \brief Get the target goal velocity for joint drive. + + \param[in] linear The goal velocity for linear drive + \param[in] angular The goal velocity for angular drive + + \see setDriveVelocity() + */ + virtual void getDriveVelocity(PxVec3& linear, PxVec3& angular) const = 0; + + /** + \brief Returns string name of PxD6Joint, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxD6Joint"; } + +protected: + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxD6Joint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxD6Joint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxD6Joint", PxJoint); } + + //~serialization + +public: + /** + \brief Returns the GPU D6 joint index. + + \note Only use in combination with enabled GPU dynamics and enabled direct GPU API + (see #PxSceneFlag::eENABLE_GPU_DYNAMICS, #PxSceneFlag::eENABLE_DIRECT_GPU_API, + #PxBroadPhaseType::eGPU) + + \return The GPU index, or PX_INVALID_D6_JOINT_GPU_INDEX if the joint is not part of a PxScene. + + \see PxDirectGPUAPI::getD6JointData() + */ + virtual PxD6JointGPUIndex getGPUIndex() const = 0; + + /** + \brief Set the angular drive model to apply. + + \note The configuration will limit the allowed set of angular drive types (see #PxD6Drive) to use + when calling #PxD6Joint::setDrive(). + + \note Changing the angular drive model, will reset all the parameters for the angular drives to + their default values (see #PxD6Joint::setDrive() for information on the default values). + + \param[in] config The angular drive model to apply. + + \see PxD6AngularDriveConfig getAngularDriveConfig() + + Default PxD6AngularDriveConfig::eLEGACY but will soon change to PxD6AngularDriveConfig::eSWING_TWIST + */ + virtual void setAngularDriveConfig(PxD6AngularDriveConfig::Enum config) = 0; + + /** + \brief Get the angular drive model to apply. + + \return The angular drive model to apply. + + \see PxD6AngularDriveConfig setAngularDriveConfig() + */ + virtual PxD6AngularDriveConfig::Enum getAngularDriveConfig() const = 0; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxD6JointCreate.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxD6JointCreate.h new file mode 100644 index 000000000..0aa43d85f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxD6JointCreate.h @@ -0,0 +1,251 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_D6_JOINT_CREATE_H +#define PX_D6_JOINT_CREATE_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxVec3.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxPhysics; +class PxRigidActor; +class PxJoint; + +/** + \brief Helper function to create a fixed joint, using either a PxD6Joint or PxFixedJoint. + + For fixed joints it is important that the joint frames have the same orientation. This helper function uses an identity rotation for both. + It is also important that the joint frames have an equivalent position in world space. The function does not check this, so it is up to users + to ensure that this is the case. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos0 The position of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos1 The position of the joint relative to actor1 + \param[in] useD6 True to use a PxD6Joint, false to use a PxFixedJoint; + + \return The created joint. + + \see PxD6Joint PxFixedJoint +*/ +PxJoint* PxD6JointCreate_Fixed(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, bool useD6); + +/** + \brief Helper function to create a distance joint, using either a PxD6Joint or PxDistanceJoint. + + This helper function only supports a maximum distance constraint, because PxD6Joint does not support a minimum distance constraint (contrary + to PxDistanceJoint). + + The distance is computed between the joint frames' world-space positions. The joint frames' orientations are irrelevant here so the function + sets them to identity. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos0 The position of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos1 The position of the joint relative to actor1 + \param[in] maxDist The maximum allowed distance + \param[in] useD6 True to use a PxD6Joint, false to use a PxDistanceJoint; + + \return The created joint. + + \see PxD6Joint PxDistanceJoint +*/ +PxJoint* PxD6JointCreate_Distance(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, float maxDist, bool useD6); + +/** + \brief Helper function to create a prismatic joint, using either a PxD6Joint or PxPrismaticJoint. + + This function enforces that the joint frames have the same orientation, which is a local frame whose X is the desired translation axis. + This orientation is computed by the function, so users only have to define the desired translation axis (typically 1;0;0 or 0;1;0 or 0;0;1). + + The translation can be limited. Limits are enforced if minLimitmaxLimit the + limits are not enforced and the axis is free. The limit values are computed relative to the position of actor0's joint frame. + + The function creates hard limits, and uses PhysX's default contact distance parameter. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos0 The position of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos1 The position of the joint relative to actor1 + \param[in] axis The axis along which objects are allowed to move, expressed in the actors' local space + \param[in] minLimit The minimum allowed position along the axis + \param[in] maxLimit The maximum allowed position along the axis + \param[in] useD6 True to use a PxD6Joint, false to use a PxPrismaticJoint; + + \return The created joint. + + \see PxD6Joint PxPrismaticJoint +*/ +PxJoint* PxD6JointCreate_Prismatic(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, float minLimit, float maxLimit, bool useD6); + +/** + \brief Helper function to create a revolute joint, using either a PxD6Joint or PxRevoluteJoint. + + This function enforces that the joint frames have the same orientation, which is a local frame whose X is the desired rotation axis. + This orientation is computed by the function, so users only have to define the desired rotation axis (typically 1;0;0 or 0;1;0 or 0;0;1). + + The rotation can be limited. Limits are enforced if minLimitmaxLimit the + limits are not enforced and the axis is free. The limit values are computed relative to the rotation of actor0's joint frame. + + The function creates hard limits, and uses PhysX's default contact distance parameter. + + Limits are expressed in radians. Allowed range is ]-2*PI;+2*PI[ + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos0 The position of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos1 The position of the joint relative to actor1 + \param[in] axis The axis around which objects are allowed to move, expressed in the actors' local space + \param[in] minLimit The minimum allowed rotation along the axis + \param[in] maxLimit The maximum allowed rotation along the axis + \param[in] useD6 True to use a PxD6Joint, false to use a PxRevoluteJoint; + + \return The created joint. + + \see PxD6Joint PxRevoluteJoint +*/ +PxJoint* PxD6JointCreate_Revolute(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, float minLimit, float maxLimit, bool useD6); + +/** + \brief Helper function to create a spherical joint, using either a PxD6Joint or PxSphericalJoint. + + This function supports a cone limit shape, defined by a cone axis and two angular limit values. + + This function enforces that the joint frames have the same orientation, which is a local frame whose X is the desired cone axis. + This orientation is computed by the function, so users only have to define the desired cone axis (typically 1;0;0 or 0;1;0 or 0;0;1). + + The rotations can be limited. Limits are enforced if limit1>0 and limit2>0. Otherwise the motion is free. The limit values define an ellipse, + which is the cross-section of the cone limit shape. + + The function creates hard limits, and uses PhysX's default contact distance parameter. + + Limits are expressed in radians. Allowed range is ]0;PI[. Limits are symmetric around the cone axis. + + The cone axis is equivalent to the twist axis for the D6 joint. The twist motion is not limited. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos0 The position of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos1 The position of the joint relative to actor1 + \param[in] axis The cone axis, expressed in the actors' local space + \param[in] limit1 Max angular limit for the ellipse along the joint frame's second axis (first axis = cone axis) + \param[in] limit2 Max angular limit for the ellipse along the joint frame's third axis (first axis = cone axis) + \param[in] useD6 True to use a PxD6Joint, false to use a PxSphericalJoint; + + \return The created joint. + + \see PxD6Joint PxSphericalJoint +*/ +PxJoint* PxD6JointCreate_Spherical(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, float limit1, float limit2, bool useD6); + +/** + \brief Helper function to create a spherical joint, using either a PxD6Joint or PxSphericalJoint. + + This function supports a cone limit shape, defined by two pairs of angular limit values. This can be used to create an asymmetric cone. If the + angular limit values are symmetric (i.e. minLimit1=-maxLimit1 and minLimit2=-maxLimit2) then the cone axis is the X axis in actor0's space. + If the limits are not symmetric, the function rotates the cone axis accordingly so that limits remain symmetric for PhysX. If this happens, + the initial joint frames will be different for both actors. By default minLimit1/maxLimit1 are limits around the joint's Y axis, and + minLimit2/maxLimit2 are limits around the joint's Z axis. + + The function creates hard limits, and uses PhysX's default contact distance parameter. + + Limits are expressed in radians. Allowed range is ]-PI;PI[. + + The cone axis is equivalent to the twist axis for the D6 joint. The twist motion is not limited. + + The returned apiroty and apirotz values can later be added to retrieved Y and Z swing angle values (from the joint), to remap + angle values to the given input range. + + \param[out] apiroty Amount of rotation around Y used to setup actor0's joint frame + \param[out] apirotz Amount of rotation around Z used to setup actor0's joint frame + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos0 The position of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos1 The position of the joint relative to actor1 + \param[in] minLimit1 Min angular limit along the joint frame's second axis (first axis = cone axis) + \param[in] maxLimit1 Max angular limit along the joint frame's second axis (first axis = cone axis) + \param[in] minLimit2 Min angular limit along the joint frame's third axis (first axis = cone axis) + \param[in] maxLimit2 Max angular limit along the joint frame's third axis (first axis = cone axis) + \param[in] useD6 True to use a PxD6Joint, false to use a PxSphericalJoint; + + \return The created joint. + + \see PxD6Joint PxSphericalJoint +*/ +PxJoint* PxD6JointCreate_GenericCone(float& apiroty, float& apirotz, PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, float minLimit1, float maxLimit1, float minLimit2, float maxLimit2, bool useD6); + + +/** + \brief Helper function to create a D6 joint with pyramidal swing limits. + + This function supports a pyramid limit shape, defined by two pairs of angular limit values. This can be used to create an asymmetric pyramid. If the + angular limit values are symmetric (i.e. minLimit1=-maxLimit1 and minLimit2=-maxLimit2) then the pyramid axis is the X axis in actor0's space. + By default minLimit1/maxLimit1 are limits around the joint's Y axis, and minLimit2/maxLimit2 are limits around the joint's Z axis. + + The function creates hard limits, and uses PhysX's default contact distance parameter. + + Limits are expressed in radians. Allowed range is ]-PI;PI[. + + The pyramid axis is equivalent to the twist axis for the D6 joint. The twist motion is not limited. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos0 The position of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localPos1 The position of the joint relative to actor1 + \param[in] axis The pyramid axis, expressed in the actors' local space + \param[in] minLimit1 Min angular limit along the joint frame's second axis (first axis = pyramid axis) + \param[in] maxLimit1 Max angular limit along the joint frame's second axis (first axis = pyramid axis) + \param[in] minLimit2 Min angular limit along the joint frame's third axis (first axis = pyramid axis) + \param[in] maxLimit2 Max angular limit along the joint frame's third axis (first axis = pyramid axis) + + \return The created joint. + + \see PxD6Joint +*/ +PxJoint* PxD6JointCreate_Pyramid(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, + float minLimit1, float maxLimit1, float minLimit2, float maxLimit2); + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultAllocator.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultAllocator.h new file mode 100644 index 000000000..c3039c3c4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultAllocator.h @@ -0,0 +1,111 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFAULT_ALLOCATOR_H +#define PX_DEFAULT_ALLOCATOR_H + +#include "foundation/PxAllocatorCallback.h" +#include "foundation/PxAssert.h" +#include "foundation/PxMemory.h" +#include "common/PxPhysXCommonConfig.h" + +#include + +#if PX_WINDOWS_FAMILY || PX_LINUX_FAMILY || PX_SWITCH +#include +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_WINDOWS_FAMILY +// on win32 we only have 8-byte alignment guaranteed, but the CRT provides special aligned allocation fns +PX_FORCE_INLINE void* platformAlignedAlloc(size_t size) +{ + return _aligned_malloc(size, 16); +} + +PX_FORCE_INLINE void platformAlignedFree(void* ptr) +{ + _aligned_free(ptr); +} +#elif PX_LINUX_FAMILY || PX_SWITCH +PX_FORCE_INLINE void* platformAlignedAlloc(size_t size) +{ + return ::memalign(16, size); +} + +PX_FORCE_INLINE void platformAlignedFree(void* ptr) +{ + ::free(ptr); +} +#else +// on all other platforms we get 16-byte alignment by default +PX_FORCE_INLINE void* platformAlignedAlloc(size_t size) +{ + return ::malloc(size); +} + +PX_FORCE_INLINE void platformAlignedFree(void* ptr) +{ + ::free(ptr); +} +#endif + +/** +\brief default implementation of the allocator interface required by the SDK +*/ +class PxDefaultAllocator : public PxAllocatorCallback +{ +public: + virtual void* allocate(size_t size, const char*, const char*, int) + { + void* ptr = platformAlignedAlloc(size); + PX_ASSERT((size_t(ptr) & 15)==0); +#if PX_STOMP_ALLOCATED_MEMORY + if(ptr != NULL) + { + PxMemSet(ptr, PxI32(0xcd), PxU32(size)); + } +#endif + return ptr; + } + + virtual void deallocate(void* ptr) + { + platformAlignedFree(ptr); + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultCpuDispatcher.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultCpuDispatcher.h new file mode 100644 index 000000000..966fa7274 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultCpuDispatcher.h @@ -0,0 +1,119 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFAULT_CPU_DISPATCHER_H +#define PX_DEFAULT_CPU_DISPATCHER_H + +#include "common/PxPhysXCommonConfig.h" +#include "task/PxCpuDispatcher.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief A default implementation for a CPU task dispatcher. + +\see PxDefaultCpuDispatcherCreate() PxCpuDispatcher +*/ +class PxDefaultCpuDispatcher : public PxCpuDispatcher +{ +public: + /** + \brief Deletes the dispatcher. + + Do not keep a reference to the deleted instance. + + \see PxDefaultCpuDispatcherCreate() + */ + virtual void release() = 0; + + /** + \brief Enables profiling at task level. + + \note By default enabled only in profiling builds. + + \param[in] runProfiled True if tasks should be profiled. + */ + virtual void setRunProfiled(bool runProfiled) = 0; + + /** + \brief Checks if profiling is enabled at task level. + + \return True if tasks should be profiled. + */ + virtual bool getRunProfiled() const = 0; +}; + + +/** +\brief If a thread ends up waiting for work it will find itself in a spin-wait loop until work becomes available. +Three strategies are available to limit wasted cycles. +The strategies are as follows: +a) wait until a work task signals the end of the spin-wait period. +b) yield the thread by providing a hint to reschedule thread execution, thereby allowing other threads to run. +c) yield the processor by informing it that it is waiting for work and requesting it to more efficiently use compute resources. +*/ +struct PxDefaultCpuDispatcherWaitForWorkMode +{ + enum Enum + { + eWAIT_FOR_WORK, + eYIELD_THREAD, + eYIELD_PROCESSOR + }; +}; + + +/** +\brief Create default dispatcher, extensions SDK needs to be initialized first. + +\param[in] numThreads Number of worker threads the dispatcher should use. +\param[in] affinityMasks Array with affinity mask for each thread. If not defined, default masks will be used. +\param[in] mode is the strategy employed when a busy-wait is encountered. +\param[in] yieldProcessorCount specifies the number of times a OS-specific yield processor command will be executed +during each cycle of a busy-wait in the event that the specified mode is eYIELD_PROCESSOR + +\note numThreads may be zero in which case no worker thread are initialized and +simulation tasks will be executed on the thread that calls PxScene::simulate() + +\note yieldProcessorCount must be greater than zero if eYIELD_PROCESSOR is the chosen mode and equal to zero for all other modes. + +\note eYIELD_THREAD and eYIELD_PROCESSOR modes will use compute resources even if the simulation is not running. +It is left to users to keep threads inactive, if so desired, when no simulation is running. + +\see PxDefaultCpuDispatcher +*/ +PxDefaultCpuDispatcher* PxDefaultCpuDispatcherCreate(PxU32 numThreads, PxU32* affinityMasks = NULL, PxDefaultCpuDispatcherWaitForWorkMode::Enum mode = PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK, PxU32 yieldProcessorCount = 0); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultErrorCallback.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultErrorCallback.h new file mode 100644 index 000000000..10fa27c5e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultErrorCallback.h @@ -0,0 +1,61 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFAULT_ERROR_CALLBACK_H +#define PX_DEFAULT_ERROR_CALLBACK_H + +#include "foundation/PxErrorCallback.h" +#include "PxPhysXConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief default implementation of the error callback + + This class is provided in order to enable the SDK to be started with the minimum of user code. Typically an application + will use its own error callback, and log the error to file or otherwise make it visible. Warnings and error messages from + the SDK are usually indicative that changes are required in order for PhysX to function correctly, and should not be ignored. + */ + + class PxDefaultErrorCallback : public PxErrorCallback + { + public: + PxDefaultErrorCallback(); + virtual ~PxDefaultErrorCallback(); + + virtual void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) PX_OVERRIDE; + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultProfiler.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultProfiler.h new file mode 100644 index 000000000..89faab8cd --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultProfiler.h @@ -0,0 +1,182 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFAULT_PROFILER_H +#define PX_DEFAULT_PROFILER_H + +#include "foundation/PxProfiler.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + + + +/** +\brief The major and minor version of the current Default Profiler file format. +*/ +#define PX_PROFILER_VERSION_MAJOR 0 +#define PX_PROFILER_VERSION_MINOR 1 + + +/** +\brief The various profiler data types that describe what data follows in the stream. +*/ +struct PxDefaultProfilerDataType +{ + enum Enum : PxU64 + { + eTHREAD_BLOCK = 0, //!< A thread ID follows a thread tag. All data following a thread block are from this thread. + + /*! + A key, size and character string follows a name registration tag. Event names are only written once per thread. + + Ensure names are global or static so the character pointer is static and does not change. + Pointers values are used as keys to look up names. It is especially important for cross thread + zones so the zone names can be found across threads. + */ + eNAME_REGISTRATION, + + eZONE_START, //!< A PxProfilerCallback::zoneStart callback. A time tag, context and name key follows a zone start tag. + eZONE_END, //!< A PxProfilerCallback::zoneEnd callback. A time tag, context and name key follows a zone end tag. + eZONE_START_CROSS_THREAD, //!< A PxProfilerCallback::zoneStart callback with detached set to true indicating a cross thread zone. + eZONE_END_CROSS_THREAD, //!< A PxProfilerCallback::zoneEnd callback with detached set to true indicating a cross thread zone. + eVALUE_INT, //!< A PxProfilerCallback::recordData callback with an integer value. + eVALUE_FLOAT, //!< A PxProfilerCallback::recordData callback with a floating point value. + eFRAME //!< A PxProfilerCallback::recordFrame callback. Frames are simple markers that are identifable in the profiling tools. + }; +}; + +struct PxDefaultProfilerVersionInfo +{ + PxU32 major; //!< The major version of the current file format. + PxU32 minor; //!< The minor version of the current file format. +}; + +struct PxDefaultProfilerHeader +{ + PxDefaultProfilerDataType::Enum type; //!< The type of event or data that follows this header. See PxDefaultProfilerDataType. +}; + +struct PxDefaultProfilerThread +{ + PxU64 threadId; //!< The thread identifier for all of the data that follows. +}; + +struct PxDefaultProfilerName +{ + PxU64 key; //!< The key to the profiler name. Used to store the name in a map for quick look ups. It is also the pointer to the character string. + PxU32 size; //!< Byte size of the null terminated string that follows the PxDefaultProfilerName entry in the stream. Note that due to padding the size can be larger than the string size itself. + + /// @cond + PxU32 padding; + /// @endcond +}; + +struct PxDefaultProfilerEvent +{ + PxU64 time; //!< The time the event was received, in tens of nano seconds. + PxU64 contextId; //!< The context sent with the event. User controlled data to associate with the event. + PxU64 nameKey; //!< The key to look up the name at a later time so strings are not stored with every event. +}; + +struct PxDefaultProfilerValueEvent : public PxDefaultProfilerEvent +{ + union + { + PxI32 intValue; //!< Either integer or float data that is to be graphed. + PxF32 floatValue; //!< Either integer or float data that is to be graphed. + }; + + /// @cond + PxU32 padding; + /// @endcond +}; + +class PxOutputStream; + +/** + +\brief Default implementation of PxProfilerCallback to record profiling events. + +The profiling events are stored in a memory buffer which gets flushed to a user provided stream when the +buffer is full, or when flush or release is called. + +\see PxDefaultProfilerCreate() +*/ +class PxDefaultProfiler : public PxProfilerCallback +{ +public: + + /** + \brief Deletes the profiler. + + Do not keep a reference to the deleted instance. + + \see PxDefaultProfilerCreate() + */ + virtual void release() = 0; + + /** + \brief Write all of the collected profiling data to the output stream. + + This call is not thread safe, so it should only be called during a sync point or when all threads have yielded. + Calling this regularly, at appropriate times will prevent the buffers from filling up and forcing a write + to the stream at unexpected times because writes will affect performance. + */ + virtual void flush() = 0; +}; + +/** +\brief Create default profiler. + +\note The PhysXExtensions SDK needs to be initialized first before using this method (see #PxInitExtensions) + +\param[in] outputStream A PxOutputStream used to write all of the recorded +profiler events received. Writing to the stream occurs when the +buffer is full or when flush or release is called. +\param[in] numberOfBuffers The number of buffers to pre-allocate. One buffer is +used per thread, so a number larger than the anticipated number of threads is best. +If more buffers are needed, additional memory is allocated as needed, but this may +affect performance. +\param[in] bufferSize The number of bytes to allocate per thread for recording all +profiler events received on that thread. Once the buffer is full, the profiling data +is written to the stream, which will cause a slight delay. Use a larger buffer size +to prevent this, if memory permits. The minimum buffer size is 32,767 bytes, which is also +the default setting. +*/ +PxDefaultProfiler* PxDefaultProfilerCreate(PxOutputStream& outputStream, PxU32 numberOfBuffers = 16, PxU32 bufferSize = 32767); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultSimulationFilterShader.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultSimulationFilterShader.h new file mode 100644 index 000000000..118543cc0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultSimulationFilterShader.h @@ -0,0 +1,265 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFAULT_SIMULATION_FILTER_SHADER_H +#define PX_DEFAULT_SIMULATION_FILTER_SHADER_H + +#include "PxPhysXConfig.h" + +#include "PxFiltering.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxActor; + +/** +\brief 64-bit mask used for collision filtering. + +The collision filtering equation for 2 objects o0 and o1 is: + +
 (G0 op0 K0) op2 (G1 op1 K1) == b 
+ +with + +
    +
  • G0 = PxGroupsMask for object o0. See PxSetGroupsMask
  • +
  • G1 = PxGroupsMask for object o1. See PxSetGroupsMask
  • +
  • K0 = filtering constant 0. See PxSetFilterConstants
  • +
  • K1 = filtering constant 1. See PxSetFilterConstants
  • +
  • b = filtering boolean. See PxSetFilterBool
  • +
  • op0, op1, op2 = filtering operations. See PxSetFilterOps
  • +
+ +If the filtering equation is true, collision detection is enabled. + +\see PxSetFilterOps() +*/ +class PxGroupsMask +{ +public: + PX_INLINE PxGroupsMask():bits0(0),bits1(0),bits2(0),bits3(0) {} + PX_INLINE ~PxGroupsMask() {} + + PxU16 bits0, bits1, bits2, bits3; +}; + +/** +\brief Collision filtering operations. + +\see PxGroupsMask +*/ +struct PxFilterOp +{ + enum Enum + { + PX_FILTEROP_AND, + PX_FILTEROP_OR, + PX_FILTEROP_XOR, + PX_FILTEROP_NAND, + PX_FILTEROP_NOR, + PX_FILTEROP_NXOR, + PX_FILTEROP_SWAP_AND + }; +}; + +/** +\brief Implementation of a simple filter shader that emulates PhysX 2.8.x filtering + +This shader provides the following logic: +\li If one of the two filter objects is a trigger, the pair is acccepted and #PxPairFlag::eTRIGGER_DEFAULT will be used for trigger reports +\li Else, if the filter mask logic (see further below) discards the pair it will be suppressed (#PxFilterFlag::eSUPPRESS) +\li Else, the pair gets accepted and collision response gets enabled (#PxPairFlag::eCONTACT_DEFAULT) + +Filter mask logic: +Given the two #PxFilterData structures fd0 and fd1 of two collision objects, the pair passes the filter if the following +conditions are met: + + 1) Collision groups of the pair are enabled + 2) Collision filtering equation is satisfied + +Each actor can belong to a single collision group. Use PxSetGroup to set the group of an actor and PxGetGroup to retrieve the group of an actor. +A collision group is an integer value between 0 and 31 defining which group the actor belongs to. Because that value is written to an actor's +shapes internally (it is stored in the shapes' PxFilterData), this feature does not work with shared shapes, unless they all belong to actors +whose groups are similar. For example it would not work to share a shape between actors A and B, and then assign A to group 0 and B to group 1, +as they would both internally try to write different group values to the same shape. + +Once actors are assigned to groups, it is possible to define how groups collide with each-other using the PxSetGroupCollisionFlag function. +Use this function to set a simple boolean value per group pairs, defining if the corresponding groups should collide. If not, collisions between +actors of these non-colliding groups will be automatically disabled by the PxDefaultSimulationFilterShader. + +\see PxSimulationFilterShader PxGetGroupCollisionFlag PxSetGroupCollisionFlag PxGetGroup PxSetGroup +*/ +PxFilterFlags PxDefaultSimulationFilterShader( + PxFilterObjectAttributes attributes0, PxFilterData filterData0, + PxFilterObjectAttributes attributes1, PxFilterData filterData1, + PxPairFlags& pairFlags, + const void* constantBlock, PxU32 constantBlockSize); + +/** +\brief Determines if collision detection is performed between a pair of groups + +\note Collision group is an integer between 0 and 31. +\note PxGetGroupCollisionFlag(a, b) is the same as PxGetGroupCollisionFlag(b, a) + +\param[in] group1 First Group +\param[in] group2 Second Group + +\return True if the groups should collide + +\see PxSetGroupCollisionFlag +*/ +bool PxGetGroupCollisionFlag(const PxU16 group1, const PxU16 group2); + +/** +\brief Specifies if collision should be performed by a pair of groups + +\note Collision group is an integer between 0 and 31. +\note PxSetGroupCollisionFlag(a, b) is the same as PxSetGroupCollisionFlag(b, a) + +\param[in] group1 First Group +\param[in] group2 Second Group +\param[in] enable True to enable collision between the groups + +\see PxGetGroupCollisionFlag +*/ +void PxSetGroupCollisionFlag(const PxU16 group1, const PxU16 group2, const bool enable); + +/** +\brief Retrieves the value set with PxSetGroup() + +\note Collision group is an integer between 0 and 31. + +\param[in] actor The actor + +\return The collision group this actor belongs to + +\see PxSetGroup +*/ +PxU16 PxGetGroup(const PxActor& actor); + +/** +\brief Sets which collision group this actor is part of + +\note Collision group is an integer between 0 and 31. + +\param[in] actor The actor +\param[in] collisionGroup Collision group this actor belongs to + +\see PxGetGroup +*/ +void PxSetGroup(PxActor& actor, const PxU16 collisionGroup); + +/** +\brief Retrieves filtering operation. See comments for PxGroupsMask + +\param[out] op0 First filter operator. +\param[out] op1 Second filter operator. +\param[out] op2 Third filter operator. + +\see PxSetFilterOps PxSetFilterBool PxSetFilterConstants +*/ +void PxGetFilterOps(PxFilterOp::Enum& op0, PxFilterOp::Enum& op1, PxFilterOp::Enum& op2); + +/** +\brief Setups filtering operations. See comments for PxGroupsMask + +\param[in] op0 Filter op 0. +\param[in] op1 Filter op 1. +\param[in] op2 Filter op 2. + +\see PxSetFilterBool PxSetFilterConstants +*/ +void PxSetFilterOps(const PxFilterOp::Enum& op0, const PxFilterOp::Enum& op1, const PxFilterOp::Enum& op2); + +/** +\brief Retrieves filtering's boolean value. See comments for PxGroupsMask + +\return flag Boolean value for filter. + +\see PxSetFilterBool PxSetFilterConstants +*/ +bool PxGetFilterBool(); + +/** +\brief Setups filtering's boolean value. See comments for PxGroupsMask + +\param[in] enable Boolean value for filter. + +\see PxSetFilterOps PxSsetFilterConstants +*/ +void PxSetFilterBool(const bool enable); + +/** +\brief Gets filtering constant K0 and K1. See comments for PxGroupsMask + +\param[out] c0 the filtering constants, as a mask. See #PxGroupsMask. +\param[out] c1 the filtering constants, as a mask. See #PxGroupsMask. + +\see PxSetFilterOps PxSetFilterBool PxSetFilterConstants +*/ +void PxGetFilterConstants(PxGroupsMask& c0, PxGroupsMask& c1); + +/** +\brief Setups filtering's K0 and K1 value. See comments for PxGroupsMask + +\param[in] c0 The new group mask. See #PxGroupsMask. +\param[in] c1 The new group mask. See #PxGroupsMask. + +\see PxSetFilterOps PxSetFilterBool PxGetFilterConstants +*/ +void PxSetFilterConstants(const PxGroupsMask& c0, const PxGroupsMask& c1); + +/** +\brief Gets 64-bit mask used for collision filtering. See comments for PxGroupsMask + +\param[in] actor The actor + +\return The group mask for the actor. + +\see PxSetGroupsMask() +*/ +PxGroupsMask PxGetGroupsMask(const PxActor& actor); + +/** +\brief Sets 64-bit mask used for collision filtering. See comments for PxGroupsMask + +\param[in] actor The actor +\param[in] mask The group mask to set for the actor. + +\see PxGetGroupsMask() +*/ +void PxSetGroupsMask(PxActor& actor, const PxGroupsMask& mask); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultStreams.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultStreams.h new file mode 100644 index 000000000..88ee4384a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDefaultStreams.h @@ -0,0 +1,143 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFAULT_STREAMS_H +#define PX_DEFAULT_STREAMS_H + +#include +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxIO.h" +#include "foundation/PxFoundation.h" + +typedef FILE* PxFileHandle; + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief default implementation of a memory write stream + +\see PxOutputStream +*/ + +class PxDefaultMemoryOutputStream: public PxOutputStream +{ +public: + PxDefaultMemoryOutputStream(PxAllocatorCallback &allocator = *PxGetAllocatorCallback()); + virtual ~PxDefaultMemoryOutputStream(); + + virtual PxU32 write(const void* src, PxU32 count); + + virtual PxU32 getSize() const { return mSize; } + virtual PxU8* getData() const { return mData; } + +private: + PxDefaultMemoryOutputStream(const PxDefaultMemoryOutputStream&); + PxDefaultMemoryOutputStream& operator=(const PxDefaultMemoryOutputStream&); + + PxAllocatorCallback& mAllocator; + PxU8* mData; + PxU32 mSize; + PxU32 mCapacity; +}; + +/** +\brief default implementation of a memory read stream + +\see PxInputData +*/ + +class PxDefaultMemoryInputData: public PxInputData +{ +public: + PxDefaultMemoryInputData(PxU8* data, PxU32 length); + + virtual PxU32 read(void* dest, PxU32 count); + virtual PxU32 getLength() const; + virtual void seek(PxU32 pos); + virtual PxU32 tell() const; + +private: + PxU32 mSize; + const PxU8* mData; + PxU32 mPos; +}; + + + +/** +\brief default implementation of a file write stream + +\see PxOutputStream +*/ + +class PxDefaultFileOutputStream: public PxOutputStream +{ +public: + PxDefaultFileOutputStream(const char* name); + virtual ~PxDefaultFileOutputStream(); + + virtual PxU32 write(const void* src, PxU32 count); + virtual bool isValid(); +private: + PxFileHandle mFile; +}; + + +/** +\brief default implementation of a file read stream + +\see PxInputData +*/ + +class PxDefaultFileInputData: public PxInputData +{ +public: + PxDefaultFileInputData(const char* name); + virtual ~PxDefaultFileInputData(); + + virtual PxU32 read(void* dest, PxU32 count); + virtual void seek(PxU32 pos); + virtual PxU32 tell() const; + virtual PxU32 getLength() const; + + bool isValid() const; +private: + PxFileHandle mFile; + PxU32 mLength; +}; + +#if !PX_DOXYGEN +} +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableSkinningExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableSkinningExt.h new file mode 100644 index 000000000..7b2689146 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableSkinningExt.h @@ -0,0 +1,99 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_SKINNING_EXT_H +#define PX_DEFORMABLE_SKINNING_EXT_H + +#include "PxDeformableSkinning.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxCookingParams; +class PxSimpleTriangleMesh; +class PxInsertionCallback; + +/** +\brief Utility functions for deformable surface and volume skinning +*/ +class PxDeformableSkinningExt +{ +public: + + /** + \brief Initializes the interpolated vertices from guide vertices, normals, and triangles for deformable surface skinning + + This function calculates the skinning embedding information for a deformable surface mesh, + where each embedded vertex is interpolated based on the surrounding guide vertices and triangles. + + \param[out] embeddingInfo A pointer to a PxTriangleMeshEmbeddingInfo object that will store the calculated embedding information. Must be of length numEmbeddedVertices + \param[in] guideVertices A pointer to an array of guide vertices used for interpolation + \param[in] guideNormals A pointer to an array of guide normals corresponding to the guide vertices + \param[in] guideTriangles A pointer to an array of indices defining the guide triangles + \param[in] nbGuideTriangles The number of guide triangles + \param[in] embeddedVertices A pointer to an array of vertices that will be embedded and interpolated + \param[in] nbEmbeddedVertices The number of embedded vertices + + \see PxTriangleMeshEmbeddingInfo + */ + static void initializeInterpolatedVertices( + PxTriangleMeshEmbeddingInfo* embeddingInfo, + const PxVec3* guideVertices, const PxVec3* guideNormals, + const PxU32* guideTriangles, PxU32 nbGuideTriangles, const PxVec3* embeddedVertices, + PxU32 nbEmbeddedVertices); + + /** + \brief Initializes the interpolated vertices from guide vertices and tetrahedra for deformable volume skinning + + This function calculates the skinning embedding information for a deformable volume mesh, + where each embedded vertex is interpolated based on the surrounding guide vertices and tetrahedra. + + \param[out] embeddingInfo A pointer to a PxTetrahedronMeshEmbeddingInfo object that will store the calculated embedding information. Must be of length numEmbeddedVertices + \param[in] guideVertices A pointer to an array of guide vertices used for interpolation + \param[in] guideTetrahedra A pointer to an array of indices defining the guide tetrahedra + \param[in] nbGuideTetrahedra The number of guide tetrahedra + \param[in] embeddedVertices A pointer to an array of vertices that will be embedded and interpolated + \param[in] nbEmbeddedVertices The number of embedded vertices + + \see PxTetrahedronMeshEmbeddingInfo + */ + static void initializeInterpolatedVertices( + PxTetrahedronMeshEmbeddingInfo* embeddingInfo, + const PxVec3* guideVertices, + const PxU32* guideTetrahedra, PxU32 nbGuideTetrahedra, const PxVec3* embeddedVertices, + PxU32 nbEmbeddedVertices); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_SKINNING_EXT_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableSurfaceExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableSurfaceExt.h new file mode 100644 index 000000000..64f47dd17 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableSurfaceExt.h @@ -0,0 +1,177 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_SURFACE_EXT_H +#define PX_DEFORMABLE_SURFACE_EXT_H + +#include "PxDeformableSurface.h" +#include "foundation/PxVec4.h" +#include "foundation/PxTransform.h" +#include "foundation/PxUserAllocated.h" +#include "cudamanager/PxCudaContextManager.h" +#include "cudamanager/PxCudaTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Utility functions for use with PxDeformableSurface +*/ +class PxDeformableSurfaceExt +{ +public: + /** + \brief Uploads prepared deformable surface data to the GPU. + + \param[in] deformableSurface The deformable surface to perform the data upload to. + \param[in] flags Specifies which buffers the data transfer should include. + \param[in] nbVertices The number of vertices in the surface deformable mesh. + \param[in] positionsPinned A pointer to a pinned host memory buffer containing position and inverse mass for each vertex. + \param[in] velocitiesPinned A pointer to a pinned host memory buffer containing the velocity for each vertex. + \param[in] restPositionsPinned A pointer to a pinned host memory buffer containing the rest position for each vertex. + \param[in] copyStream An optional cuda stream to schedule the copy on. + + \see PxDeformableSurface + */ + static void copyToDevice(PxDeformableSurface& deformableSurface, PxDeformableSurfaceDataFlags flags, PxU32 nbVertices, + PxVec4* positionsPinned, PxVec4* velocitiesPinned, PxVec4* restPositionsPinned, + CUstream copyStream = CUstream(0)); + + /** + \brief Distributes a list of triangles masses to vertices. + + The mass for each triangle will be distributed in equal parts to the vertices of said triangle. + + \param[in] deformableSurface The deformable surface to perform the operation on. + \param[in] triangleMasses A list of floats specifying the mass of each triangle. + \param[in] positionInvMassPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex. + + \see PxDeformableSurface + */ + static void distributeTriangleMassToVertices(PxDeformableSurface& deformableSurface, const PxReal* triangleMasses, + PxVec4* positionInvMassPinned); + + /** + \brief Distributes a uniform density to the vertices of a deformable surface. + + This method distributes mass based on a specified mass per unit area. The mass for each vertex is calculated + according to the area of the triangles connected to it, and the resulting mass is assigned to the vertex. + + \param[in] deformableSurface The deformable surface to perform the operation on. + \param[in] massPerVolume The mass per unit volume (=density) to be distributed across the vertices. + \param[in] clothThickness The cloth thickness to compute the mass + \param[in] positionInvMassPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex. + + \see PxDeformableSurface + */ + static void distributeDensityToVertices(PxDeformableSurface& deformableSurface, PxReal massPerVolume, PxReal clothThickness, + PxVec4* positionInvMassPinned); + + /** + \brief Distributes a total mass uniformly to the vertices of a deformable surface. + + This method calculates the total mass to be distributed across all vertices, and assigns a proportional mass to each + vertex based on the geometry of the surface. The mass is distributed equally to ensure the total mass of the surface + matches the specified value. + + \param[in] deformableSurface The deformable surface to perform the operation on. + \param[in] totalMass The total mass to be distributed across the vertices. + \param[in] positionInvMassPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex. + + \see PxDeformableSurface + */ + static void distributeMassToVertices(PxDeformableSurface& deformableSurface, PxReal totalMass, + PxVec4* positionInvMassPinned); + + /** + \brief Allocates and initializes a pinned host memory from a PxTriangleMesh attached to a PxDeformableSurface using a PxShape. + + \note The user is responsible for deallocation and lifetime management of the positionInvMassPinned, velocityPinned + and restPositionsPinned buffers. + + This method fails if the deformable surface does not have a shape attached to it. + + \param[in] deformableSurface The deformable surface to perform the operation on. + \param[in] positions The initial positions of the surface deformable vertices. + \param[in] velocities The initial velocities of the surface deformable vertices. + \param[in] restPositions The rest positions of the surface deformable vertices. + \param[in] mass The mass of the deformable surface, will be distributed equally among vertices. + \param[in] transform The world-space transform of the deformable surface. + \param[in] cudaContextManager The PxCudaContextManager of the scene this deformable surface will be simulated in. + \param[in] positionInvMassPinned A reference to a pointer for the return value of the positionInvMassPinned buffer, will be set by this function. + \param[in] velocityPinned A reference to a pointer for the return value of the velocityPinned buffer, will be set by this function. + \param[in] restPositionPinned A reference to a pointer for the return value of the restPositionPinned buffer, will be set by this function. + + \return The number of vertices in the surface deformable mesh. + + \see PxDeformableSurface + */ + static PxU32 allocateAndInitializeHostMirror(PxDeformableSurface& deformableSurface, const PxVec3* positions, + const PxVec3* velocities, const PxVec3* restPositions, float mass, + const PxTransform& transform, PxCudaContextManager* cudaContextManager, + PxVec4*& positionInvMassPinned, PxVec4*& velocityPinned, + PxVec4*& restPositionPinned); + + /** + \brief Allocates and initializes a pinned host memory from given positions, velocities, and rest positions. + + \note The user is responsible for deallocation and lifetime management of the positionInvMassPinned, velocityPinned + and restPositionsPinned buffers. + + If the input 'restPositions' is a null pointer, positions are used in place of restPositions. + If the input 'velocities' is a null pointer, zero velocities are assigned to velocityPinned. + + \param[in] positions The positions of the surface deformable vertices, will be used to assign positionInvMassPinned buffer. + \param[in] velocities The velocities of the surface deformable vertices, will be used to assign velocityPinned buffer. + \param[in] restPositions The rest positions of the surface deformable vertices, will be used to assign restPositionPinned buffer. + \param[in] nbVertices The number of vertices in the surface deformable mesh. + \param[in] mass The mass of the deformable surface, will be distributed equally among vertices. + \param[in] transform The world-space transform of the deformable surface. + \param[in] cudaContextManager The PxCudaContextManager of the scene this deformable surface will be simulated in. + \param[in] positionInvMassPinned A reference to a pointer for the return value of the positionInvMassPinned buffer, will be set by this function. + \param[in] velocityPinned A reference to a pointer for the return value of the velocityPinned buffer, will be set by this function. + \param[in] restPositionPinned A reference to a pointer for the return value of the restPositionPinned buffer, will be set by this function. + + \return The number of vertices in the surface deformable mesh. + + \see PxDeformableSurface + */ + static PxU32 allocateAndInitializeHostMirror(const PxVec3* positions, const PxVec3* velocities, + const PxVec3* restPositions, PxU32 nbVertices, float mass, + const PxTransform& transform, PxCudaContextManager* cudaContextManager, + PxVec4*& positionInvMassPinned, PxVec4*& velocityPinned, + PxVec4*& restPositionPinned); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_SURFACE_EXT_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableVolumeExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableVolumeExt.h new file mode 100644 index 000000000..9f6c250f1 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDeformableVolumeExt.h @@ -0,0 +1,297 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DEFORMABLE_VOLUME_EXT_H +#define PX_DEFORMABLE_VOLUME_EXT_H + +#include "foundation/PxTransform.h" +#include "foundation/PxUserAllocated.h" +#include "PxDeformableVolume.h" +#include "PxDeformableVolumeFlag.h" +#include "cudamanager/PxCudaContextManager.h" +#include "cudamanager/PxCudaTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxCookingParams; +class PxSimpleTriangleMesh; +class PxInsertionCallback; +class PxDeformableVolumeMesh; + +/** +\brief Utility functions for use with PxDeformableVolume and subclasses +*/ +class PxDeformableVolumeExt +{ +public: + /** + \brief Computes the deformable volume's vertex masses from the provided density and the volume of the tetrahedra + + The buffers affected by this operation can be obtained from the deformable volume using the methods getSimPositionInvMassBufferD() and getSimVelocityBufferD() + + The inverse mass is stored in the 4th component (the first three components are x, y, z coordinates) of the simulation mesh's position buffer. + + \param[in] deformableVolume The deformable volume which will get its mass updated + \param[in] density The density to used to calculate the mass from the body's volume + \param[in] maxInvMassRatio Maximum allowed ratio defined as max(vertexMasses) / min(vertexMasses) where vertexMasses is a list of float values with a mass for every vertex in the simulation mesh + \param[in] simPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the simulation mesh. + + \see PxDeformableVolume PxDeformableVolume::getSimPositionInvMassBufferD() + */ + static void updateMass(PxDeformableVolume& deformableVolume, const PxReal density, const PxReal maxInvMassRatio, PxVec4* simPositionsPinned); + + /** + \brief Computes the deformable volume's vertex masses such that the sum of all masses is equal to the provided mass + + The buffers affected by this operation can be obtained from the deformable volume using the methods getSimPositionInvMassBufferD()) and getSimVelocityBufferD() + + The inverse mass is stored in the 4th component (the first three components are x, y, z coordinates) of the simulation mesh's position buffer. + + \param[in] deformableVolume The deformable volume which will get its mass updated + \param[in] mass The deformable volume's mass + \param[in] maxInvMassRatio Maximum allowed ratio defined as max(vertexMasses) / min(vertexMasses) where vertexMasses is a list of float values with a mass for every vertex in the simulation mesh + \param[in] simPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the simulation mesh. + + \see PxDeformableVolume PxDeformableVolume::getSimPositionInvMassBufferD() + */ + static void setMass(PxDeformableVolume& deformableVolume, const PxReal mass, const PxReal maxInvMassRatio, PxVec4* simPositionsPinned); + + /** + \brief Transforms a deformable volume + + The buffers affected by this operation can be obtained from the deformable volume using the methods getSimPositionInvMassBufferD() and getSimVelocityBufferD() + + Applies a transformation to the simulation mesh's positions an velocities. Velocities only get rotated and scaled (translation is not applicable to direction vectors). + It does not modify the body's mass. + If the method is called multiple times, the transformation will compound with the ones previously applied. + + \param[in] deformableVolume The deformable volume which is transformed + \param[in] transform The transform to apply + \param[in] scale A scaling factor + \param[in] simPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the simulation mesh. + \param[in] simVelocitiesPinned A pointer to a pinned host memory buffer containing velocities for each vertex of the simulation mesh. + \param[in] collPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the collision mesh. + \param[in] restPositionsPinned A pointer to a pinned host memory buffer containing rest positions of the collision mesh. + + \see PxDeformableVolume + */ + static void transform(PxDeformableVolume& deformableVolume, const PxTransform& transform, const PxReal scale, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned); + + /** + \brief Updates the collision mesh's vertex positions to match the simulation mesh's transformation and scale. + + The buffer affected by this operation can be obtained from the deformable volume using the method getPositionInvMassBufferD() + + \param[in] deformableVolume The deformable volume which will get its collision mesh vertices updated + \param[in] simPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the simulation mesh. + \param[in] collPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the collision mesh. + + \see PxDeformableVolume + */ + static void updateEmbeddedCollisionMesh(PxDeformableVolume& deformableVolume, PxVec4* simPositionsPinned, PxVec4* collPositionsPinned); + + /** + \brief Uploads prepared deformable volume data to the GPU. It ensures that the embedded collision mesh matches the simulation mesh's transformation and scale. + + \param[in] deformableVolume The deformable volume which will perform the data upload + \param[in] flags Specifies which buffers the data transfer should include + \param[in] simPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the simulation mesh. + \param[in] simVelocitiesPinned A pointer to a pinned host memory buffer containing velocities for each vertex of the simulation mesh. + \param[in] collPositionsPinned A pointer to a pinned host memory buffer containing positions and inverse masses for each vertex of the collision mesh. + \param[in] restPositionsPinned A pointer to a pinned host memory buffer containing rest positions of the collision mesh. + \param[in] stream A cuda stream to perform the copies. + + \see PxDeformableVolume + */ + static void copyToDevice(PxDeformableVolume& deformableVolume, PxDeformableVolumeDataFlags flags, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned, CUstream stream = CUstream(0)); + + /** + \brief Creates a full deformable volume mesh matching the shape given as input. Uses a voxel mesh for FEM simulation and a surface-matching mesh for collision detection. + + \param[in] params Cooking params instance required for mesh processing + \param[in] surfaceMesh Input triangle mesh that represents the surface of the deformable volume + \param[in] numVoxelsAlongLongestAABBAxis The number of voxels along the longest bounding box axis + \param[in] insertionCallback The insertion interface from PxPhysics + \param[in] validate If set to true the input triangle mesh will get analyzed to find possible deficiencies + \return Deformable volume mesh if cooking was successful, NULL otherwise + \see PxDeformableVolumeMesh + */ + static PxDeformableVolumeMesh* createDeformableVolumeMesh(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, PxU32 numVoxelsAlongLongestAABBAxis, PxInsertionCallback& insertionCallback, const bool validate = true); + + /** + \brief Deprecated + \see createDeformableVolumeMesh + */ + PX_DEPRECATED static PX_FORCE_INLINE PxDeformableVolumeMesh* createSoftBodyMesh(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, PxU32 numVoxelsAlongLongestAABBAxis, PxInsertionCallback& insertionCallback, const bool validate = true) + { + return createDeformableVolumeMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, insertionCallback, validate); + } + + /** + \brief Creates a full deformable volume mesh matching the shape given as input. Uses the same surface-matching mesh for collision detection and FEM simulation. + + \param[in] params Cooking params instance required for mesh processing + \param[in] surfaceMesh Input triangle mesh that represents the surface of the deformable volume + \param[in] insertionCallback The insertion interface from PxPhysics + \param[in] maxWeightRatioInTet Upper limit for the ratio of node weights that are adjacent to the same tetrahedron. The closer to one (while remaining larger than one), the more stable the simulation. + \param[in] validate If set to true the input triangle mesh will get analyzed to find possible deficiencies + \return Deformable volume mesh if cooking was successful, NULL otherwise + \see PxDeformableVolumeMesh + */ + static PxDeformableVolumeMesh* createDeformableVolumeMeshNoVoxels(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, + PxInsertionCallback& insertionCallback, PxReal maxWeightRatioInTet = 1.5f, const bool validate = true); + + /** + \brief Deprecated + \see createDeformableVolumeMeshNoVoxels + */ + PX_DEPRECATED static PX_FORCE_INLINE PxDeformableVolumeMesh* createSoftBodyMeshNoVoxels(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, + PxInsertionCallback& insertionCallback, PxReal maxWeightRatioInTet = 1.5f, const bool validate = true) + { + return createDeformableVolumeMeshNoVoxels(params, surfaceMesh, insertionCallback, maxWeightRatioInTet, validate); + } + + /** + \brief Creates a deformable volume instance from a deformable volume mesh + + \param[in] deformableVolumeMesh The deformable volume mesh + \param[in] transform The transform that defines initial position and orientation of the deformable volume + \param[in] material The material + \param[in] cudaContextManager A cuda context manager + \param[in] density The density used to compute the mass properties + \param[in] scale The scaling of the deformable volume + \return Deformable volume instance + \see PxDeformableVolumeMesh, PxDeformableVolume + */ + static PxDeformableVolume* createDeformableVolumeFromMesh(PxDeformableVolumeMesh* deformableVolumeMesh, const PxTransform& transform, + const PxDeformableVolumeMaterial& material, PxCudaContextManager& cudaContextManager, PxReal density = 100.0f, PxReal scale = 1.0f); + + /** + \brief Deprecated + \see createDeformableVolumeFromMesh + */ + PX_DEPRECATED static PX_FORCE_INLINE PxDeformableVolume* createSoftBodyFromMesh(PxDeformableVolumeMesh* deformableVolumeMesh, const PxTransform& transform, + const PxDeformableVolumeMaterial& material, PxCudaContextManager& cudaContextManager, PxReal density = 100.0f, PxU32 solverIterationCount = 30, + const PxFEMParameters& femParams = PxFEMParameters(), PxReal scale = 1.0f) + { + PxDeformableVolume* deformableVolume = createDeformableVolumeFromMesh(deformableVolumeMesh, transform, material, + cudaContextManager, density, scale); + deformableVolume->setParameter(femParams); + deformableVolume->setSolverIterationCounts(solverIterationCount); + return deformableVolume; + } + + /** + \brief Creates a deformable volume instance with a box shape + + \param[in] transform The transform that defines initial position and orientation of the deformable volume + \param[in] boxDimensions The dimensions (side lengths) of the box shape + \param[in] material The material + \param[in] cudaContextManager A cuda context manager + \param[in] maxEdgeLength The maximal length of a triangle edge. Subdivision will get applied until the edge length criteria is matched. -1 means no subdivision is applied. + \param[in] density The density used to compute the mass properties + \param[in] numVoxelsAlongLongestAABBAxis The number of voxels to use for the simulation mesh along the longest bounding box dimension + \param[in] scale The scaling of the deformable volume + \return Deformable volume instance + \see PxDeformableVolumeMesh, PxDeformableVolume + */ + static PxDeformableVolume* createDeformableVolumeBox(const PxTransform& transform, const PxVec3& boxDimensions, const PxDeformableVolumeMaterial& material, + PxCudaContextManager& cudaContextManager, PxReal maxEdgeLength = -1.0f, PxReal density = 100.0f, PxU32 numVoxelsAlongLongestAABBAxis = 10, PxReal scale = 1.0f); + + /** + \brief Deprecated + \see createDeformableVolumeBox + */ + PX_DEPRECATED static PX_FORCE_INLINE PxDeformableVolume* createSoftBodyBox(const PxTransform& transform, const PxVec3& boxDimensions, const PxDeformableVolumeMaterial& material, + PxCudaContextManager& cudaContextManager, PxReal maxEdgeLength = -1.0f, PxReal density = 100.0f, PxU32 solverIterationCount = 30, + const PxFEMParameters& femParams = PxFEMParameters(), PxU32 numVoxelsAlongLongestAABBAxis = 10, PxReal scale = 1.0f) + { + PxDeformableVolume* deformableVolume = createDeformableVolumeBox(transform, boxDimensions, material, cudaContextManager, maxEdgeLength, density, + numVoxelsAlongLongestAABBAxis, scale); + deformableVolume->setParameter(femParams); + deformableVolume->setSolverIterationCounts(solverIterationCount); + return deformableVolume; + } + + /** + \brief allocates and initializes pinned host memory buffers from an actor with shape. + + \param[in] deformableVolume A PxDeformableVolume that has a valid shape attached to it. + \param[in] cudaContextManager The PxCudaContextManager of the scene this deformable volume will be simulated in + \param[in] simPositionInvMassPinned A reference to a pointer for the return value of the simPositionInvMassPinned buffer, will be set by this function. + \param[in] simVelocityPinned A reference to a pointer for the return value of the simVelocityPinned buffer, will be set by this function. + \param[in] collPositionInvMassPinned A reference to a pointer for the return value of the collPositionInvMassPinned buffer, will be set by this function. + \param[in] restPositionPinned A reference to a pointer for the return value of the restPositionPinned buffer, will be set by this function. + + \see PxDeformableVolume + */ + static void allocateAndInitializeHostMirror(PxDeformableVolume& deformableVolume, PxCudaContextManager* cudaContextManager, PxVec4*& simPositionInvMassPinned, PxVec4*& simVelocityPinned, PxVec4*& collPositionInvMassPinned, PxVec4*& restPositionPinned); + + /** + \brief Given a set of points and a set of tetrahedra, it finds the equilibrium state of the deformable volume. Every input point is either fixed or can move freely. + + \param[in] verticesOriginal Mesh vertex positions in undeformed original state. + \param[in] verticesDeformed Mesh vertex positions in new deformed state. Only fixed vertices must have their final location, all other locations will get updated by the method. + \param[in] nbVertices The number of vertices. + \param[in] tetrahedra The tetrahedra. + \param[in] nbTetraheda The number of tetrahedra. + \param[in] vertexIsFixed Optional input that specifies which vertex is fixed and which one can move to relax the tension. If not provided, vertices from verticesOriginal which have a .w value of 0 will be considered fixed. + \param[in] numIterations The number of stress relaxation iterations to run. + */ + static void relaxDeformableVolumeMesh(const PxVec4* verticesOriginal, PxVec4* verticesDeformed, PxU32 nbVertices, + const PxU32* tetrahedra, PxU32 nbTetraheda, const bool* vertexIsFixed = NULL, PxU32 numIterations = 200); + + /** + \brief Deprecated + \see relaxDeformableVolumeMesh + */ + PX_DEPRECATED static PX_FORCE_INLINE void relaxSoftBodyMesh(const PxVec4* verticesOriginal, PxVec4* verticesDeformed, PxU32 nbVertices, const PxU32* tetrahedra, PxU32 nbTetraheda, const bool* vertexIsFixed = NULL, PxU32 numIterations = 200) + { + relaxDeformableVolumeMesh(verticesOriginal, verticesDeformed, nbVertices, tetrahedra, nbTetraheda, vertexIsFixed, numIterations); + } + + /** + \brief Converts the tet id and barycentric from the collision mesh to the tet id and barycentric of the simulation mesh. + + \param[in] deformableVolume The deformable volume to perform the operation on. + \param[in] tetId The tet id of the deformable volume's collision mesh. + \param[in] tetBarycentric The barycentric coordinates of the tetrahedron specified with tetId. + \param[out] outTetId The tet id of the deformable volume's simulation mesh. + \param[out] outTetBarycentric The barycentric coordinates of the tetrahedron specified with outTetId. + */ + static void convertCollisionToSimulationTet(PxDeformableVolume& deformableVolume, PxU32 tetId, const PxVec4& tetBarycentric, PxU32& outTetId, PxVec4& outTetBarycentric); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_DEFORMABLE_VOLUME_EXT_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDistanceJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDistanceJoint.h new file mode 100644 index 000000000..6fc6025bc --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxDistanceJoint.h @@ -0,0 +1,264 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_DISTANCE_JOINT_H +#define PX_DISTANCE_JOINT_H + +#include "extensions/PxJoint.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxDistanceJoint; + +/** +\brief Create a distance Joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + +\see PxDistanceJoint +*/ +PxDistanceJoint* PxDistanceJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + + +/** +\brief flags for configuring the drive of a PxDistanceJoint + +\see PxDistanceJoint +*/ +struct PxDistanceJointFlag +{ + enum Enum + { + eMAX_DISTANCE_ENABLED = 1<<1, + eMIN_DISTANCE_ENABLED = 1<<2, + eSPRING_ENABLED = 1<<3 + }; +}; + +typedef PxFlags PxDistanceJointFlags; +PX_FLAGS_OPERATORS(PxDistanceJointFlag::Enum, PxU16) + +/** +\brief a joint that maintains an upper or lower bound (or both) on the distance between two points on different objects + +\see PxDistanceJointCreate PxJoint +*/ +class PxDistanceJoint : public PxJoint +{ +public: + + /** + \brief Return the current distance of the joint + */ + virtual PxReal getDistance() const = 0; + + /** + \brief Set the allowed minimum distance for the joint. + + The minimum distance must be no more than the maximum distance + + Default 0.0f + Range [0, PX_MAX_F32) + + \param[in] distance the minimum distance + + \see PxDistanceJoint::minDistance, PxDistanceJointFlag::eMIN_DISTANCE_ENABLED getMinDistance() + */ + virtual void setMinDistance(PxReal distance) = 0; + + /** + \brief Get the allowed minimum distance for the joint. + + \return the allowed minimum distance + + \see PxDistanceJoint::minDistance, PxDistanceJointFlag::eMIN_DISTANCE_ENABLED setMinDistance() + */ + virtual PxReal getMinDistance() const = 0; + + /** + \brief Set the allowed maximum distance for the joint. + + The maximum distance must be no less than the minimum distance. + + Default 0.0f + Range [0, PX_MAX_F32) + + \param[in] distance the maximum distance + + \see PxDistanceJoint::maxDistance, PxDistanceJointFlag::eMAX_DISTANCE_ENABLED getMinDistance() + */ + virtual void setMaxDistance(PxReal distance) = 0; + + /** + \brief Get the allowed maximum distance for the joint. + + \return the allowed maximum distance + + \see PxDistanceJoint::maxDistance, PxDistanceJointFlag::eMAX_DISTANCE_ENABLED setMaxDistance() + */ + virtual PxReal getMaxDistance() const = 0; + + /** + \brief Set the error tolerance of the joint. + + \param[in] tolerance the distance beyond the allowed range at which the joint becomes active + + \see PxDistanceJoint::tolerance, getTolerance() + */ + virtual void setTolerance(PxReal tolerance) = 0; + + /** + \brief Get the error tolerance of the joint. + + the distance beyond the joint's [min, max] range before the joint becomes active. + + Default 0.25f * PxTolerancesScale::length + Range (0, PX_MAX_F32) + + This value should be used to ensure that if the minimum distance is zero and the + spring function is in use, the rest length of the spring is non-zero. + + \see PxDistanceJoint::tolerance, setTolerance() + */ + virtual PxReal getTolerance() const = 0; + + /** + \brief Set the strength of the joint spring. + + The spring is used if enabled, and the distance exceeds the range [min-error, max+error]. + + Default 0.0f + Range [0, PX_MAX_F32) + + \param[in] stiffness the spring strength of the joint + + \see PxDistanceJointFlag::eSPRING_ENABLED getStiffness() + */ + virtual void setStiffness(PxReal stiffness) = 0; + + /** + \brief Get the strength of the joint spring. + + \return stiffness the spring strength of the joint + + \see PxDistanceJointFlag::eSPRING_ENABLED setStiffness() + */ + virtual PxReal getStiffness() const = 0; + + /** + \brief Set the damping of the joint spring. + + The spring is used if enabled, and the distance exceeds the range [min-error, max+error]. + + Default 0.0f + Range [0, PX_MAX_F32) + + \param[in] damping the degree of damping of the joint spring of the joint + + \see PxDistanceJointFlag::eSPRING_ENABLED setDamping() + */ + virtual void setDamping(PxReal damping) = 0; + + /** + \brief Get the damping of the joint spring. + + \return the degree of damping of the joint spring of the joint + + \see PxDistanceJointFlag::eSPRING_ENABLED setDamping() + */ + virtual PxReal getDamping() const = 0; + + /** + \brief Set the flags specific to the Distance Joint. + + Default PxDistanceJointFlag::eMAX_DISTANCE_ENABLED + + \param[in] flags The joint flags. + + \see PxDistanceJointFlag setFlag() getFlags() + */ + virtual void setDistanceJointFlags(PxDistanceJointFlags flags) = 0; + + /** + \brief Set a single flag specific to a Distance Joint to true or false. + + \param[in] flag The flag to set or clear. + \param[in] value the value to which to set the flag + + \see PxDistanceJointFlag, getFlags() setFlags() + */ + virtual void setDistanceJointFlag(PxDistanceJointFlag::Enum flag, bool value) = 0; + + /** + \brief Get the flags specific to the Distance Joint. + + \return the joint flags + + \see PxDistanceJoint::flags, PxDistanceJointFlag setFlag() setFlags() + */ + virtual PxDistanceJointFlags getDistanceJointFlags() const = 0; + + /** + \brief Returns string name of PxDistanceJoint, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxDistanceJoint"; } + +protected: + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxDistanceJoint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxDistanceJoint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxDistanceJoint", PxJoint); } + + //~serialization +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxExtensionsAPI.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxExtensionsAPI.h new file mode 100644 index 000000000..99a2a2af1 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxExtensionsAPI.h @@ -0,0 +1,89 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_EXTENSIONS_API_H +#define PX_EXTENSIONS_API_H + +#include "foundation/PxErrorCallback.h" +#include "extensions/PxDefaultAllocator.h" +#include "extensions/PxConstraintExt.h" +#include "extensions/PxDistanceJoint.h" +#include "extensions/PxFixedJoint.h" +#include "extensions/PxPrismaticJoint.h" +#include "extensions/PxRevoluteJoint.h" +#include "extensions/PxSphericalJoint.h" +#include "extensions/PxD6Joint.h" +#include "extensions/PxGearJoint.h" +#include "extensions/PxRackAndPinionJoint.h" +#include "extensions/PxDefaultSimulationFilterShader.h" +#include "extensions/PxDefaultErrorCallback.h" +#include "extensions/PxDefaultStreams.h" +#include "extensions/PxRigidActorExt.h" +#include "extensions/PxRigidBodyExt.h" +#include "extensions/PxShapeExt.h" +#include "extensions/PxTriangleMeshExt.h" +#include "extensions/PxSerialization.h" +#include "extensions/PxDefaultCpuDispatcher.h" +#include "extensions/PxSmoothNormals.h" +#include "extensions/PxSimpleFactory.h" +#include "extensions/PxStringTableExt.h" +#include "extensions/PxBroadPhaseExt.h" +#include "extensions/PxMassProperties.h" +#include "extensions/PxSceneQueryExt.h" +#include "extensions/PxSceneQuerySystemExt.h" +#include "extensions/PxCustomSceneQuerySystem.h" +#include "extensions/PxConvexMeshExt.h" +#include "extensions/PxSamplingExt.h" +#include "extensions/PxTetrahedronMeshExt.h" +#include "extensions/PxCustomGeometryExt.h" +#include "extensions/PxDeformableSurfaceExt.h" + +/** \brief Initialize the PhysXExtensions library. + +This should be called before calling any functions or methods in extensions which may require allocation. +\note This function does not need to be called before creating a PxDefaultAllocator object. + +\param physics a PxPhysics object +\param pvd an PxPvd (PhysX Visual Debugger) object + +\see PxCloseExtensions PxFoundation PxPhysics +*/ +PX_C_EXPORT bool PX_CALL_CONV PxInitExtensions(physx::PxPhysics& physics, physx::PxPvd* pvd); + +/** \brief Shut down the PhysXExtensions library. + +This function should be called to cleanly shut down the PhysXExtensions library before application exit. + +\note This function is required to be called to release foundation usage. + +\see PxInitExtensions +*/ +PX_C_EXPORT void PX_CALL_CONV PxCloseExtensions(); + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxFixedJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxFixedJoint.h new file mode 100644 index 000000000..44de1b488 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxFixedJoint.h @@ -0,0 +1,96 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FIXED_JOINT_H +#define PX_FIXED_JOINT_H + +#include "extensions/PxJoint.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxFixedJoint; + +/** +\brief Create a fixed joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + +\see PxFixedJoint +*/ +PxFixedJoint* PxFixedJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + +/** + \brief A fixed joint permits no relative movement between two bodies. ie the bodies are glued together. + + \image html fixedJoint.png + + \see PxFixedJointCreate() PxJoint +*/ +class PxFixedJoint : public PxJoint +{ +public: + + /** + \brief Returns string name of PxFixedJoint, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxFixedJoint"; } + +protected: + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxFixedJoint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxFixedJoint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxFixedJoint", PxJoint); } + + //~serialization +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxGearJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxGearJoint.h new file mode 100644 index 000000000..f89230e56 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxGearJoint.h @@ -0,0 +1,125 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEAR_JOINT_H +#define PX_GEAR_JOINT_H + +#include "extensions/PxJoint.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxGearJoint; + + /** + \brief Create a gear Joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + + \see PxGearJoint + */ + PxGearJoint* PxGearJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + + /** + \brief A joint that connects two existing revolute joints and constrains their relative angular velocity with respect to each other. + + \see PxGearJointCreate PxJoint + */ + class PxGearJoint : public PxJoint + { + public: + + /** + \brief Set the hinge/revolute joints connected by the gear joint. + + The passed joints can be either PxRevoluteJoint, PxD6Joint or PxArticulationJointReducedCoordinate. + The joints must define degrees of freedom around the twist axis. + + Note that these joints are only used to compute the positional error correction term, + used to adjust potential drift between jointed actors. The gear joint can run without + calling this function, but in that case some visible overlap may develop over time between + the teeth of the gear meshes. + + \note Calling this function resets the internal positional error correction term. + + \param[in] hinge0 The first hinge joint + \param[in] hinge1 The second hinge joint + \return true if success + */ + virtual bool setHinges(const PxBase* hinge0, const PxBase* hinge1) = 0; + + /** + \brief Get the hinge/revolute joints connected by the gear joint. + + \param[out] hinge0 The first hinge joint + \param[out] hinge1 The second hinge joint + */ + virtual void getHinges(const PxBase*& hinge0, const PxBase*& hinge1) const = 0; + + /** + \brief Set the desired gear ratio. + + For two gears with n0 and n1 teeth respectively, the gear ratio is n0/n1. + + \note You may need to use a negative gear ratio if the joint frames of involved actors are not oriented in the same direction. + + \note Calling this function resets the internal positional error correction term. + + \param[in] ratio Desired ratio between the two hinges. + */ + virtual void setGearRatio(float ratio) = 0; + + /** + \brief Get the gear ratio. + + \return Current ratio + */ + virtual float getGearRatio() const = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxGearJoint"; } + + protected: + + PX_INLINE PxGearJoint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + PX_INLINE PxGearJoint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxGearJoint", PxJoint); } + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxGjkQueryExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxGjkQueryExt.h new file mode 100644 index 000000000..bdbca1bb7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxGjkQueryExt.h @@ -0,0 +1,234 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GJK_QUERY_EXT_H +#define PX_GJK_QUERY_EXT_H + +#include "geometry/PxGjkQuery.h" +#include "geometry/PxGeometry.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxSphereGeometry; +class PxCapsuleGeometry; +class PxBoxGeometry; +class PxConvexCoreGeometry; +class PxConvexMeshGeometry; +class PxContactBuffer; +class PxConvexMesh; + +/** +\brief Pre-made support mapping for built-in convex geometry types. +*/ +class PxGjkQueryExt +{ +public: + /** + \brief Pre-made support mapping for a sphere + */ + struct SphereSupport : PxGjkQuery::Support + { + PxReal radius; + + /** + \brief Default constructor + */ + SphereSupport(); + /** + \brief Constructs a SphereSupport for a sphere radius + */ + SphereSupport(PxReal radius); + /** + \brief Constructs a SphereSupport for a PxSphereGeometry + */ + SphereSupport(const PxSphereGeometry& geom); + + virtual PxReal getMargin() const PX_OVERRIDE PX_FINAL; + virtual PxVec3 supportLocal(const PxVec3& dir) const PX_OVERRIDE PX_FINAL; + }; + + /** + \brief Pre-made support mapping for a capsule + */ + struct CapsuleSupport : PxGjkQuery::Support + { + PxReal radius, halfHeight; + + /** + \brief Default constructor + */ + CapsuleSupport(); + /** + \brief Constructs a CapsuleSupport for capsule radius and halfHeight + */ + CapsuleSupport(PxReal radius, PxReal halfHeight); + /** + \brief Constructs a CapsuleSupport for a PxCapsuleGeometry + */ + CapsuleSupport(const PxCapsuleGeometry& geom); + + virtual PxReal getMargin() const PX_OVERRIDE PX_FINAL; + virtual PxVec3 supportLocal(const PxVec3& dir) const PX_OVERRIDE PX_FINAL; + }; + + /** + \brief Pre-made support mapping for a box + */ + struct BoxSupport : PxGjkQuery::Support + { + PxVec3 halfExtents; + PxReal margin; + + /** + \brief Default constructor + */ + BoxSupport(); + /** + \brief Constructs a BoxSupport for a box halfExtents with optional margin + */ + BoxSupport(const PxVec3& halfExtents, PxReal margin = 0); + /** + \brief Constructs a BoxSupport for a PxBoxGeometry + */ + BoxSupport(const PxBoxGeometry& box, PxReal margin = 0); + + virtual PxReal getMargin() const PX_OVERRIDE PX_FINAL; + virtual PxVec3 supportLocal(const PxVec3& dir) const PX_OVERRIDE PX_FINAL; + }; + + /** + \brief Pre-made support mapping for a convex core + */ + struct ConvexCoreSupport : PxGjkQuery::Support + { + PxU64 shapeData[10]; + + /** + \brief Default constructor + */ + ConvexCoreSupport(); + /** + \brief Constructs a ConvexCoreSupport for a PxConvexCoreGeometry + */ + ConvexCoreSupport(const PxConvexCoreGeometry& geom, PxReal margin = 0); + + virtual PxReal getMargin() const PX_OVERRIDE PX_FINAL; + virtual PxVec3 supportLocal(const PxVec3& dir) const PX_OVERRIDE PX_FINAL; + }; + + /** + \brief Pre-made support mapping for a convex mesh + */ + struct ConvexMeshSupport : PxGjkQuery::Support + { + const PxConvexMesh* convexMesh; + PxVec3 scale; + PxQuat scaleRotation; + PxReal margin; + + /** + \brief Default constructor + */ + ConvexMeshSupport(); + /** + \brief Constructs a BoxSupport for a PxConvexMesh + */ + ConvexMeshSupport(const PxConvexMesh& convexMesh, const PxVec3& scale = PxVec3(1), const PxQuat& scaleRotation = PxQuat(PxIdentity), PxReal margin = 0); + /** + \brief Constructs a BoxSupport for a PxConvexMeshGeometry + */ + ConvexMeshSupport(const PxConvexMeshGeometry& convexMesh, PxReal margin = 0); + + virtual PxReal getMargin() const PX_OVERRIDE PX_FINAL; + virtual PxVec3 supportLocal(const PxVec3& dir) const PX_OVERRIDE PX_FINAL; + }; + + /** + \brief Pre-made support mapping for any PhysX's convex geometry (sphere, capsule, box, convex mesh) + */ + struct ConvexGeomSupport : PxGjkQuery::Support + { + /** + \brief Default constructor + */ + ConvexGeomSupport(); + /** + \brief Constructs a BoxSupport for a PxGeometry + */ + ConvexGeomSupport(const PxGeometry& geom, PxReal margin = 0); + /** + \brief Destructor + */ + ~ConvexGeomSupport(); + + /** + \brief Returns false if ConvexGeomSupport was constructed from non-convex geometry + */ + bool isValid() const; + + virtual PxReal getMargin() const PX_OVERRIDE PX_FINAL; + virtual PxVec3 supportLocal(const PxVec3& dir) const PX_OVERRIDE PX_FINAL; + + private: + PxGeometryType::Enum mType; + union { + void* alignment; + PxU8 sphere[sizeof(SphereSupport)]; + PxU8 capsule[sizeof(CapsuleSupport)]; + PxU8 box[sizeof(BoxSupport)]; + PxU8 convexCore[sizeof(ConvexCoreSupport)]; + PxU8 convexMesh[sizeof(ConvexMeshSupport)]; + } mSupport; + }; + + /** + \brief Generates a contact point between two shapes using GJK-EPA algorithm + + \param[in] a Shape A support mapping + \param[in] b Shape B support mapping + \param[in] poseA Shape A transformation + \param[in] poseB Shape B transformation + \param[in] contactDistance The distance at which contacts begin to be generated between the shapes + \param[in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units + \param[out] contactBuffer A buffer to store the contact + + \return True if there is a contact. + */ + static bool generateContacts(const PxGjkQuery::Support& a, const PxGjkQuery::Support& b, const PxTransform& poseA, const PxTransform& poseB, + PxReal contactDistance, PxReal toleranceLength, PxContactBuffer& contactBuffer); + +}; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxJoint.h new file mode 100644 index 000000000..5533a5735 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxJoint.h @@ -0,0 +1,395 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_JOINT_H +#define PX_JOINT_H + +#include "foundation/PxTransform.h" +#include "PxRigidActor.h" +#include "PxConstraint.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxRigidActor; +class PxScene; +class PxPhysics; +class PxConstraint; + +/** +\brief an enumeration of PhysX' built-in joint types + +\see PxJoint +*/ +struct PxJointConcreteType +{ + enum Enum + { + eSPHERICAL = PxConcreteType::eFIRST_PHYSX_EXTENSION, + eREVOLUTE, + ePRISMATIC, + eFIXED, + eDISTANCE, + eD6, + eGEAR, + eRACK_AND_PINION, + eLast + }; +}; + +PX_DEFINE_TYPEINFO(PxJoint, PxConcreteType::eUNDEFINED) +PX_DEFINE_TYPEINFO(PxRackAndPinionJoint, PxJointConcreteType::eRACK_AND_PINION) +PX_DEFINE_TYPEINFO(PxGearJoint, PxJointConcreteType::eGEAR) +PX_DEFINE_TYPEINFO(PxD6Joint, PxJointConcreteType::eD6) +PX_DEFINE_TYPEINFO(PxDistanceJoint, PxJointConcreteType::eDISTANCE) +PX_DEFINE_TYPEINFO(PxFixedJoint, PxJointConcreteType::eFIXED) +PX_DEFINE_TYPEINFO(PxPrismaticJoint, PxJointConcreteType::ePRISMATIC) +PX_DEFINE_TYPEINFO(PxRevoluteJoint, PxJointConcreteType::eREVOLUTE) +PX_DEFINE_TYPEINFO(PxSphericalJoint, PxJointConcreteType::eSPHERICAL) + + +/** +\brief an enumeration for specifying one or other of the actors referenced by a joint + +\see PxJoint +*/ + +struct PxJointActorIndex +{ + enum Enum + { + eACTOR0, + eACTOR1, + COUNT + }; +}; + +/** +\brief a base interface providing common functionality for PhysX joints +*/ + +class PxJoint : public PxBase +{ +public: + + /** + \brief Set the actors for this joint. + + An actor may be NULL to indicate the world frame. At most one of the actors may be NULL. + + \param[in] actor0 the first actor. + \param[in] actor1 the second actor + + \see getActors() + */ + virtual void setActors(PxRigidActor* actor0, PxRigidActor* actor1) = 0; + + /** + \brief Get the actors for this joint. + + \param[out] actor0 the first actor. + \param[out] actor1 the second actor + + \see setActors() + */ + virtual void getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const = 0; + + /** + \brief Set the joint local pose for an actor. + + This is the relative pose which locates the joint frame relative to the actor. + + \param[in] actor 0 for the first actor, 1 for the second actor. + \param[in] localPose the local pose for the actor this joint + + \see getLocalPose() + */ + virtual void setLocalPose(PxJointActorIndex::Enum actor, const PxTransform& localPose) = 0; + + /** + \brief get the joint local pose for an actor. + + \param[in] actor 0 for the first actor, 1 for the second actor. + + return the local pose for this joint + + \see setLocalPose() + */ + virtual PxTransform getLocalPose(PxJointActorIndex::Enum actor) const = 0; + + /** + \brief get the relative pose for this joint + + This function returns the pose of the joint frame of actor1 relative to actor0 + + */ + virtual PxTransform getRelativeTransform() const = 0; + + /** + \brief get the relative linear velocity of the joint + + This function returns the linear velocity of the origin of the constraint frame of actor1, relative to the origin of the constraint + frame of actor0. The value is returned in the constraint frame of actor0 + */ + virtual PxVec3 getRelativeLinearVelocity() const = 0; + + /** + \brief get the relative angular velocity of the joint + + This function returns the angular velocity of actor1 relative to actor0. The value is returned in the constraint frame of actor0 + */ + virtual PxVec3 getRelativeAngularVelocity() const = 0; + + /** + \brief set the break force for this joint. + + if the constraint force or torque on the joint exceeds the specified values, the joint will break, + at which point it will not constrain the two actors and the flag PxConstraintFlag::eBROKEN will be set. The + force and torque are measured in the joint frame of the first actor + + \param[in] force the maximum force the joint can apply before breaking + \param[in] torque the maximum torque the joint can apply before breaking + */ + virtual void setBreakForce(PxReal force, PxReal torque) = 0; + + /** + \brief get the break force for this joint. + + \param[out] force the maximum force the joint can apply before breaking + \param[out] torque the maximum torque the joint can apply before breaking + + \see setBreakForce() + */ + virtual void getBreakForce(PxReal& force, PxReal& torque) const = 0; + + /** + \brief set the constraint flags for this joint. + + \param[in] flags the constraint flags + + \see PxConstraintFlag + */ + virtual void setConstraintFlags(PxConstraintFlags flags) = 0; + + /** + \brief set a constraint flags for this joint to a specified value. + + \param[in] flag the constraint flag + \param[in] value the value to which to set the flag + + \see PxConstraintFlag + */ + virtual void setConstraintFlag(PxConstraintFlag::Enum flag, bool value) = 0; + + /** + \brief get the constraint flags for this joint. + + \return the constraint flags + + \see PxConstraintFlag + */ + virtual PxConstraintFlags getConstraintFlags() const = 0; + + /** + \brief set the inverse mass scale for actor0. + + \param[in] invMassScale the scale to apply to the inverse mass of actor 0 for resolving this constraint + + \see getInvMassScale0 + */ + virtual void setInvMassScale0(PxReal invMassScale) = 0; + + /** + \brief get the inverse mass scale for actor0. + + \return inverse mass scale for actor0 + + \see setInvMassScale0 + */ + virtual PxReal getInvMassScale0() const = 0; + + /** + \brief set the inverse inertia scale for actor0. + + \param[in] invInertiaScale the scale to apply to the inverse inertia of actor0 for resolving this constraint + + \see getInvMassScale0 + */ + virtual void setInvInertiaScale0(PxReal invInertiaScale) = 0; + + /** + \brief get the inverse inertia scale for actor0. + + \return inverse inertia scale for actor0 + + \see setInvInertiaScale0 + */ + virtual PxReal getInvInertiaScale0() const = 0; + + /** + \brief set the inverse mass scale for actor1. + + \param[in] invMassScale the scale to apply to the inverse mass of actor 1 for resolving this constraint + + \see getInvMassScale1 + */ + virtual void setInvMassScale1(PxReal invMassScale) = 0; + + /** + \brief get the inverse mass scale for actor1. + + \return inverse mass scale for actor1 + + \see setInvMassScale1 + */ + virtual PxReal getInvMassScale1() const = 0; + + /** + \brief set the inverse inertia scale for actor1. + + \param[in] invInertiaScale the scale to apply to the inverse inertia of actor1 for resolving this constraint + + \see getInvInertiaScale1 + */ + virtual void setInvInertiaScale1(PxReal invInertiaScale) = 0; + + /** + \brief get the inverse inertia scale for actor1. + + \return inverse inertia scale for actor1 + + \see setInvInertiaScale1 + */ + virtual PxReal getInvInertiaScale1() const = 0; + + /** + \brief Retrieves the PxConstraint corresponding to this joint. + + This can be used to determine, among other things, the force applied at the joint. + + \return the constraint + */ + virtual PxConstraint* getConstraint() const = 0; + + /** + \brief Sets a name string for the object that can be retrieved with getName(). + + This is for debugging and is not used by the SDK. The string is not copied by the SDK, + only the pointer is stored. + + \param[in] name String to set the objects name to. + + \see getName() + */ + virtual void setName(const char* name) = 0; + + /** + \brief Retrieves the name string set with setName(). + + \return Name string associated with object. + + \see setName() + */ + virtual const char* getName() const = 0; + + /** + \brief Deletes the joint. + + \note This call does not wake up the connected rigid bodies. + */ + virtual void release() = 0; + + /** + \brief Retrieves the scene which this joint belongs to. + + \return Owner Scene. NULL if not part of a scene. + + \see PxScene + */ + virtual PxScene* getScene() const = 0; + + void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. + +protected: + virtual ~PxJoint() {} + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxJoint(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxJoint(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxJoint", PxBase); } + + //~serialization +}; + +class PxSpring +{ +public: + + PxReal stiffness; //!< the spring strength of the drive: that is, the force proportional to the position error + PxReal damping; //!< the damping strength of the drive: that is, the force proportional to the velocity error + + PxSpring(PxReal stiffness_, PxReal damping_): stiffness(stiffness_), damping(damping_) {} +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** \brief Helper function to setup a joint's global frame + + This replaces the following functions from previous SDK versions: + + void NxJointDesc::setGlobalAnchor(const NxVec3& wsAnchor); + void NxJointDesc::setGlobalAxis(const NxVec3& wsAxis); + + The function sets the joint's localPose using world-space input parameters. + + \param[in] wsAnchor Global frame anchor point. Range: position vector + \param[in] wsAxis Global frame axis. Range: direction vector + \param[in,out] joint Joint having its global frame set. +*/ + +PX_C_EXPORT void PX_CALL_CONV PxSetJointGlobalFrame(physx::PxJoint& joint, const physx::PxVec3* wsAnchor, const physx::PxVec3* wsAxis); + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxJointLimit.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxJointLimit.h new file mode 100644 index 000000000..bb36b6a48 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxJointLimit.h @@ -0,0 +1,483 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_JOINT_LIMIT_H +#define PX_JOINT_LIMIT_H + +#include "foundation/PxMath.h" +#include "common/PxTolerancesScale.h" +#include "extensions/PxJoint.h" +#include "PxPhysXConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Describes the parameters for a joint limit. + +Limits are enabled or disabled by setting flags or other configuration parameters joints, see the +documentation for specific joint types for details. +*/ +class PxJointLimitParameters +{ +public: + /** + \brief Controls the amount of bounce when the joint hits a limit. + + A restitution value of 1.0 causes the joint to bounce back with the velocity which it hit the limit. + A value of zero causes the joint to stop dead. + + In situations where the joint has many locked DOFs (e.g. 5) the restitution may not be applied + correctly. This is due to a limitation in the solver which causes the restitution velocity to become zero + as the solver enforces constraints on the other DOFs. + + This limitation applies to both angular and linear limits, however it is generally most apparent with limited + angular DOFs. Disabling joint projection and increasing the solver iteration count may improve this behavior + to some extent. + + Also, combining soft joint limits with joint drives driving against those limits may affect stability. + + Range: [0,1]
+ Default: 0.0 + */ + PxReal restitution; + + /** + determines the minimum impact velocity which will cause the joint to bounce + */ + PxReal bounceThreshold; + + /** + \brief if greater than zero, the limit is soft, i.e. a spring pulls the joint back to the limit + + Range: [0, PX_MAX_F32)
+ Default: 0.0 + */ + PxReal stiffness; + + /** + \brief if spring is greater than zero, this is the damping of the limit spring + + Range: [0, PX_MAX_F32)
+ Default: 0.0 + */ + PxReal damping; + + PxJointLimitParameters() : + restitution (0.0f), + bounceThreshold (0.0f), + stiffness (0.0f), + damping (0.0f) + { + } + + PxJointLimitParameters(const PxJointLimitParameters& p) : + restitution (p.restitution), + bounceThreshold (p.bounceThreshold), + stiffness (p.stiffness), + damping (p.damping) + { + } + + /** + \brief Returns true if the current settings are valid. + + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const + { + return PxIsFinite(restitution) && restitution >= 0 && restitution <= 1 && + PxIsFinite(stiffness) && stiffness >= 0 && + PxIsFinite(damping) && damping >= 0 && + PxIsFinite(bounceThreshold) && bounceThreshold >= 0; + } + + PX_INLINE bool isSoft() const + { + return damping>0 || stiffness>0; + } + +protected: + ~PxJointLimitParameters() {} +}; + + +/** +\brief Describes a one-sided linear limit. +*/ +class PxJointLinearLimit : public PxJointLimitParameters +{ +public: + /** + \brief the extent of the limit. + + Range: (0, PX_MAX_F32)
+ Default: PX_MAX_F32 + */ + PxReal value; + + /** + \brief construct a linear hard limit + + \param[in] extent The extent of the limit + + \see PxJointLimitParameters + */ + PxJointLinearLimit(PxReal extent) : value(extent) + { + } + + /** + \brief construct a linear soft limit + + \param[in] extent the extent of the limit + \param[in] spring the stiffness and damping parameters for the limit spring + + \see PxJointLimitParameters + */ + PxJointLinearLimit(PxReal extent, const PxSpring& spring) : value(extent) + { + stiffness = spring.stiffness; + damping = spring.damping; + } + + /** + \brief Returns true if the limit is valid + + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const + { + return PxJointLimitParameters::isValid() && + PxIsFinite(value) && + value > 0.0f; + } +}; + + +/** +\brief Describes a two-sided limit. +*/ +class PxJointLinearLimitPair : public PxJointLimitParameters +{ +public: + /** + \brief the range of the limit. The upper limit must be no lower than the + lower limit, and if they are equal the limited degree of freedom will be treated as locked. + + Range: See the joint on which the limit is used for details
+ Default: lower = -PX_MAX_F32/3, upper = PX_MAX_F32/3 + */ + PxReal upper, lower; + + /** + \brief Construct a linear hard limit pair. The lower distance value must be less than the upper distance value. + + \param[in] scale A PxTolerancesScale struct. Should be the same as used when creating the PxPhysics object. + \param[in] lowerLimit The lower distance of the limit + \param[in] upperLimit The upper distance of the limit + + \see PxJointLimitParameters PxTolerancesScale + */ + PxJointLinearLimitPair(const PxTolerancesScale& scale, PxReal lowerLimit = -PX_MAX_F32/3.0f, PxReal upperLimit = PX_MAX_F32/3.0f) : + upper(upperLimit), + lower(lowerLimit) + { + bounceThreshold = 2.0f*scale.length; + } + + /** + \brief construct a linear soft limit pair + + \param[in] lowerLimit The lower distance of the limit + \param[in] upperLimit The upper distance of the limit + \param[in] spring The stiffness and damping parameters of the limit spring + + \see PxJointLimitParameters + */ + PxJointLinearLimitPair(PxReal lowerLimit, PxReal upperLimit, const PxSpring& spring) : + upper(upperLimit), + lower(lowerLimit) + { + stiffness = spring.stiffness; + damping = spring.damping; + } + + /** + \brief Returns true if the limit is valid. + + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const + { + return PxJointLimitParameters::isValid() && + PxIsFinite(upper) && PxIsFinite(lower) && upper >= lower && + PxIsFinite(upper - lower); + } +}; + + +class PxJointAngularLimitPair : public PxJointLimitParameters +{ +public: + /** + \brief the range of the limit. The upper limit must be no lower than the lower limit. + + Unit: Angular: Radians + Range: See the joint on which the limit is used for details
+ Default: lower = -PI/2, upper = PI/2 + */ + PxReal upper, lower; + + /** + \brief construct an angular hard limit pair. + + The lower value must be less than the upper value. + + \param[in] lowerLimit The lower angle of the limit + \param[in] upperLimit The upper angle of the limit + + \see PxJointLimitParameters + */ + PxJointAngularLimitPair(PxReal lowerLimit, PxReal upperLimit) : + upper(upperLimit), + lower(lowerLimit) + { + bounceThreshold = 0.5f; + } + + /** + \brief construct an angular soft limit pair. + + The lower value must be less than the upper value. + + \param[in] lowerLimit The lower angle of the limit + \param[in] upperLimit The upper angle of the limit + \param[in] spring The stiffness and damping of the limit spring + + \see PxJointLimitParameters + */ + PxJointAngularLimitPair(PxReal lowerLimit, PxReal upperLimit, const PxSpring& spring) : + upper(upperLimit), + lower(lowerLimit) + { + stiffness = spring.stiffness; + damping = spring.damping; + } + + /** + \brief Returns true if the limit is valid. + + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const + { + return PxJointLimitParameters::isValid() && + PxIsFinite(upper) && PxIsFinite(lower) && upper >= lower; + } +}; + +/** +\brief Describes an elliptical conical joint limit. Note that very small or highly elliptical limit cones may +result in jitter. + +\see PxD6Joint PxSphericalJoint +*/ +class PxJointLimitCone : public PxJointLimitParameters +{ +public: + /** + \brief the maximum angle from the Y axis of the constraint frame. + + Unit: Angular: Radians + Range: Angular: (0,PI)
+ Default: PI/2 + */ + PxReal yAngle; + + /** + \brief the maximum angle from the Z-axis of the constraint frame. + + Unit: Angular: Radians + Range: Angular: (0,PI)
+ Default: PI/2 + */ + PxReal zAngle; + + /** + \brief Construct a cone hard limit. + + \param[in] yLimitAngle The limit angle from the Y-axis of the constraint frame + \param[in] zLimitAngle The limit angle from the Z-axis of the constraint frame + + \see PxJointLimitParameters + */ + PxJointLimitCone(PxReal yLimitAngle, PxReal zLimitAngle) : + yAngle(yLimitAngle), + zAngle(zLimitAngle) + { + bounceThreshold = 0.5f; + } + + /** + \brief Construct a cone soft limit. + + \param[in] yLimitAngle The limit angle from the Y-axis of the constraint frame + \param[in] zLimitAngle The limit angle from the Z-axis of the constraint frame + \param[in] spring The stiffness and damping of the limit spring + + \see PxJointLimitParameters + */ + PxJointLimitCone(PxReal yLimitAngle, PxReal zLimitAngle, const PxSpring& spring) : + yAngle(yLimitAngle), + zAngle(zLimitAngle) + { + stiffness = spring.stiffness; + damping = spring.damping; + } + + /** + \brief Returns true if the limit is valid. + + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const + { + return PxJointLimitParameters::isValid() && + PxIsFinite(yAngle) && yAngle>0 && yAngle0 && zAngleUnit: Angular: Radians + Range: Angular: (-PI,PI)
+ Default: -PI/2 + */ + PxReal yAngleMin; + + /** + \brief the maximum angle from the Y axis of the constraint frame. + + Unit: Angular: Radians + Range: Angular: (-PI,PI)
+ Default: PI/2 + */ + PxReal yAngleMax; + + /** + \brief the minimum angle from the Z-axis of the constraint frame. + + Unit: Angular: Radians + Range: Angular: (-PI,PI)
+ Default: -PI/2 + */ + PxReal zAngleMin; + + /** + \brief the maximum angle from the Z-axis of the constraint frame. + + Unit: Angular: Radians + Range: Angular: (-PI,PI)
+ Default: PI/2 + */ + PxReal zAngleMax; + + /** + \brief Construct a pyramid hard limit. + + \param[in] yLimitAngleMin The minimum limit angle from the Y-axis of the constraint frame + \param[in] yLimitAngleMax The maximum limit angle from the Y-axis of the constraint frame + \param[in] zLimitAngleMin The minimum limit angle from the Z-axis of the constraint frame + \param[in] zLimitAngleMax The maximum limit angle from the Z-axis of the constraint frame + + \see PxJointLimitParameters + */ + PxJointLimitPyramid(PxReal yLimitAngleMin, PxReal yLimitAngleMax, PxReal zLimitAngleMin, PxReal zLimitAngleMax) : + yAngleMin(yLimitAngleMin), + yAngleMax(yLimitAngleMax), + zAngleMin(zLimitAngleMin), + zAngleMax(zLimitAngleMax) + { + bounceThreshold = 0.5f; + } + + /** + \brief Construct a pyramid soft limit. + + \param[in] yLimitAngleMin The minimum limit angle from the Y-axis of the constraint frame + \param[in] yLimitAngleMax The maximum limit angle from the Y-axis of the constraint frame + \param[in] zLimitAngleMin The minimum limit angle from the Z-axis of the constraint frame + \param[in] zLimitAngleMax The maximum limit angle from the Z-axis of the constraint frame + \param[in] spring The stiffness and damping of the limit spring + + \see PxJointLimitParameters + */ + PxJointLimitPyramid(PxReal yLimitAngleMin, PxReal yLimitAngleMax, PxReal zLimitAngleMin, PxReal zLimitAngleMax, const PxSpring& spring) : + yAngleMin(yLimitAngleMin), + yAngleMax(yLimitAngleMax), + zAngleMin(zLimitAngleMin), + zAngleMax(zLimitAngleMax) + { + stiffness = spring.stiffness; + damping = spring.damping; + } + + /** + \brief Returns true if the limit is valid. + + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const + { + return PxJointLimitParameters::isValid() && + PxIsFinite(yAngleMin) && yAngleMin>-PxPi && yAngleMin-PxPi && yAngleMax-PxPi && zAngleMin-PxPi && zAngleMax=yAngleMin && zAngleMax>=zAngleMin; + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxMassProperties.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxMassProperties.h new file mode 100644 index 000000000..bd578e914 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxMassProperties.h @@ -0,0 +1,370 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MASS_PROPERTIES_H +#define PX_MASS_PROPERTIES_H + +#include "PxPhysXConfig.h" +#include "foundation/PxMath.h" +#include "foundation/PxMathUtils.h" +#include "foundation/PxVec3.h" +#include "foundation/PxMat33.h" +#include "foundation/PxQuat.h" +#include "foundation/PxTransform.h" +#include "geometry/PxGeometry.h" +#include "geometry/PxBoxGeometry.h" +#include "geometry/PxSphereGeometry.h" +#include "geometry/PxCapsuleGeometry.h" +#include "geometry/PxConvexMeshGeometry.h" +#include "geometry/PxConvexMesh.h" +#include "geometry/PxCustomGeometry.h" +#include "geometry/PxConvexCoreGeometry.h" +#include "geometry/PxTriangleMeshGeometry.h" +#include "geometry/PxTriangleMesh.h" +#include "PxConvexCoreExt.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Utility class to compute and manipulate mass and inertia tensor properties. + +In most cases #PxRigidBodyExt::updateMassAndInertia(), #PxRigidBodyExt::setMassAndUpdateInertia() should be enough to +setup the mass properties of a rigid body. This utility class targets users that need to customize the mass properties +computation. +*/ +class PxMassProperties +{ +public: + /** + \brief Default constructor. + */ + PX_FORCE_INLINE PxMassProperties() : inertiaTensor(PxIdentity), centerOfMass(0.0f), mass(1.0f) {} + + /** + \brief Construct from individual elements. + */ + PX_FORCE_INLINE PxMassProperties(const PxReal m, const PxMat33& inertiaT, const PxVec3& com) : inertiaTensor(inertiaT), centerOfMass(com), mass(m) {} + + /** + \brief Compute mass properties based on a provided geometry structure. + + This constructor assumes the geometry has a density of 1. Mass and inertia tensor scale linearly with density. + + \param[in] geometry The geometry to compute the mass properties for. Supported geometry types are: sphere, box, capsule and convex mesh. + */ + PxMassProperties(const PxGeometry& geometry) + { + switch (geometry.getType()) + { + case PxGeometryType::eSPHERE: + { + const PxSphereGeometry& s = static_cast(geometry); + mass = (4.0f / 3.0f) * PxPi * s.radius * s.radius * s.radius; + inertiaTensor = PxMat33::createDiagonal(PxVec3(2.0f / 5.0f * mass * s.radius * s.radius)); + centerOfMass = PxVec3(0.0f); + } + break; + + case PxGeometryType::eBOX: + { + const PxBoxGeometry& b = static_cast(geometry); + mass = b.halfExtents.x * b.halfExtents.y * b.halfExtents.z * 8.0f; + PxVec3 d2 = b.halfExtents.multiply(b.halfExtents); + inertiaTensor = PxMat33::createDiagonal(PxVec3(d2.y + d2.z, d2.x + d2.z, d2.x + d2.y)) * (mass * 1.0f / 3.0f); + centerOfMass = PxVec3(0.0f); + } + break; + + case PxGeometryType::eCAPSULE: + { + const PxCapsuleGeometry& c = static_cast(geometry); + PxReal r = c.radius, h = c.halfHeight; + mass = ((4.0f / 3.0f) * r + 2 * c.halfHeight) * PxPi * r * r; + + PxReal a = r*r*r * (8.0f / 15.0f) + h*r*r * (3.0f / 2.0f) + h*h*r * (4.0f / 3.0f) + h*h*h * (2.0f / 3.0f); + PxReal b = r*r*r * (8.0f / 15.0f) + h*r*r; + inertiaTensor = PxMat33::createDiagonal(PxVec3(b, a, a) * PxPi * r * r); + centerOfMass = PxVec3(0.0f); + } + break; + + case PxGeometryType::eCONVEXCORE: + { + const PxConvexCoreGeometry& g = static_cast(geometry); + PxConvexCoreExt::computeMassInfo(g, mass, inertiaTensor, centerOfMass); + } + break; + + case PxGeometryType::eCONVEXMESH: + { + const PxConvexMeshGeometry& c = static_cast(geometry); + PxVec3 unscaledCoM; + PxMat33 unscaledInertiaTensorNonCOM; // inertia tensor of convex mesh in mesh local space + PxMat33 unscaledInertiaTensorCOM; + PxReal unscaledMass; + c.convexMesh->getMassInformation(unscaledMass, unscaledInertiaTensorNonCOM, unscaledCoM); + + // inertia tensor relative to center of mass + unscaledInertiaTensorCOM[0][0] = unscaledInertiaTensorNonCOM[0][0] - unscaledMass*PxReal((unscaledCoM.y*unscaledCoM.y+unscaledCoM.z*unscaledCoM.z)); + unscaledInertiaTensorCOM[1][1] = unscaledInertiaTensorNonCOM[1][1] - unscaledMass*PxReal((unscaledCoM.z*unscaledCoM.z+unscaledCoM.x*unscaledCoM.x)); + unscaledInertiaTensorCOM[2][2] = unscaledInertiaTensorNonCOM[2][2] - unscaledMass*PxReal((unscaledCoM.x*unscaledCoM.x+unscaledCoM.y*unscaledCoM.y)); + unscaledInertiaTensorCOM[0][1] = unscaledInertiaTensorCOM[1][0] = (unscaledInertiaTensorNonCOM[0][1] + unscaledMass*PxReal(unscaledCoM.x*unscaledCoM.y)); + unscaledInertiaTensorCOM[1][2] = unscaledInertiaTensorCOM[2][1] = (unscaledInertiaTensorNonCOM[1][2] + unscaledMass*PxReal(unscaledCoM.y*unscaledCoM.z)); + unscaledInertiaTensorCOM[0][2] = unscaledInertiaTensorCOM[2][0] = (unscaledInertiaTensorNonCOM[0][2] + unscaledMass*PxReal(unscaledCoM.z*unscaledCoM.x)); + + const PxMeshScale& s = c.scale; + mass = unscaledMass * s.scale.x * s.scale.y * s.scale.z; + centerOfMass = s.transform(unscaledCoM); + inertiaTensor = scaleInertia(unscaledInertiaTensorCOM, s.rotation, s.scale); + } + break; + + case PxGeometryType::eCUSTOM: + { + *this = PxMassProperties(); + static_cast(geometry).callbacks->computeMassProperties(geometry, *this); + } + break; + + case PxGeometryType::eTRIANGLEMESH: + { + const PxTriangleMeshGeometry& g = static_cast(geometry); + + PxVec3 unscaledCoM; + PxMat33 unscaledInertiaTensorNonCOM; // inertia tensor of convex mesh in mesh local space + PxMat33 unscaledInertiaTensorCOM; + PxReal unscaledMass; + g.triangleMesh->getMassInformation(unscaledMass, unscaledInertiaTensorNonCOM, unscaledCoM); + + // inertia tensor relative to center of mass + unscaledInertiaTensorCOM[0][0] = unscaledInertiaTensorNonCOM[0][0] - unscaledMass * PxReal((unscaledCoM.y*unscaledCoM.y + unscaledCoM.z*unscaledCoM.z)); + unscaledInertiaTensorCOM[1][1] = unscaledInertiaTensorNonCOM[1][1] - unscaledMass * PxReal((unscaledCoM.z*unscaledCoM.z + unscaledCoM.x*unscaledCoM.x)); + unscaledInertiaTensorCOM[2][2] = unscaledInertiaTensorNonCOM[2][2] - unscaledMass * PxReal((unscaledCoM.x*unscaledCoM.x + unscaledCoM.y*unscaledCoM.y)); + unscaledInertiaTensorCOM[0][1] = unscaledInertiaTensorCOM[1][0] = (unscaledInertiaTensorNonCOM[0][1] + unscaledMass * PxReal(unscaledCoM.x*unscaledCoM.y)); + unscaledInertiaTensorCOM[1][2] = unscaledInertiaTensorCOM[2][1] = (unscaledInertiaTensorNonCOM[1][2] + unscaledMass * PxReal(unscaledCoM.y*unscaledCoM.z)); + unscaledInertiaTensorCOM[0][2] = unscaledInertiaTensorCOM[2][0] = (unscaledInertiaTensorNonCOM[0][2] + unscaledMass * PxReal(unscaledCoM.z*unscaledCoM.x)); + + const PxMeshScale& s = g.scale; + mass = unscaledMass * s.scale.x * s.scale.y * s.scale.z; + centerOfMass = s.transform(unscaledCoM); + inertiaTensor = scaleInertia(unscaledInertiaTensorCOM, s.rotation, s.scale); + } + break; + + default: + { + *this = PxMassProperties(); + } + } + + PX_ASSERT(inertiaTensor.column0.isFinite() && inertiaTensor.column1.isFinite() && inertiaTensor.column2.isFinite()); + PX_ASSERT(centerOfMass.isFinite()); + PX_ASSERT(PxIsFinite(mass)); + } + + /** + \brief Scale mass properties. + + \param[in] scale The linear scaling factor to apply to the mass properties. + \return The scaled mass properties. + */ + PX_FORCE_INLINE PxMassProperties operator*(const PxReal scale) const + { + PX_ASSERT(PxIsFinite(scale)); + + return PxMassProperties(mass * scale, inertiaTensor * scale, centerOfMass); + } + + /** + \brief Translate the center of mass by a given vector and adjust the inertia tensor accordingly. + + \param[in] t The translation vector for the center of mass. + */ + PX_FORCE_INLINE void translate(const PxVec3& t) + { + PX_ASSERT(t.isFinite()); + + inertiaTensor = translateInertia(inertiaTensor, mass, t); + centerOfMass += t; + + PX_ASSERT(inertiaTensor.column0.isFinite() && inertiaTensor.column1.isFinite() && inertiaTensor.column2.isFinite()); + PX_ASSERT(centerOfMass.isFinite()); + } + + /** + \brief Get the entries of the diagonalized inertia tensor and the corresponding reference rotation. + + \param[in] inertia The inertia tensor to diagonalize. + \param[out] massFrame The frame the diagonalized tensor refers to. + \return The entries of the diagonalized inertia tensor. + */ + PX_FORCE_INLINE static PxVec3 getMassSpaceInertia(const PxMat33& inertia, PxQuat& massFrame) + { + PX_ASSERT(inertia.column0.isFinite() && inertia.column1.isFinite() && inertia.column2.isFinite()); + + PxVec3 diagT = PxDiagonalize(inertia, massFrame); + PX_ASSERT(diagT.isFinite()); + PX_ASSERT(massFrame.isFinite()); + return diagT; + } + + /** + \brief Translate an inertia tensor using the parallel axis theorem + + \param[in] inertia The inertia tensor to translate. + \param[in] mass The mass of the object. + \param[in] t The relative frame to translate the inertia tensor to. + \return The translated inertia tensor. + */ + PX_FORCE_INLINE static PxMat33 translateInertia(const PxMat33& inertia, const PxReal mass, const PxVec3& t) + { + PX_ASSERT(inertia.column0.isFinite() && inertia.column1.isFinite() && inertia.column2.isFinite()); + PX_ASSERT(PxIsFinite(mass)); + PX_ASSERT(t.isFinite()); + + PxMat33 s( PxVec3(0,t.z,-t.y), + PxVec3(-t.z,0,t.x), + PxVec3(t.y,-t.x,0) ); + + PxMat33 translatedIT = s.getTranspose() * s * mass + inertia; + PX_ASSERT(translatedIT.column0.isFinite() && translatedIT.column1.isFinite() && translatedIT.column2.isFinite()); + return translatedIT; + } + + /** + \brief Rotate an inertia tensor around the center of mass + + \param[in] inertia The inertia tensor to rotate. + \param[in] q The rotation from the new to the old coordinate frame, i.e. q.rotate(v) transforms + the coordinates of vector v from the old to the new coordinate frame. + \return The rotated inertia tensor. + */ + PX_FORCE_INLINE static PxMat33 rotateInertia(const PxMat33& inertia, const PxQuat& q) + { + PX_ASSERT(inertia.column0.isFinite() && inertia.column1.isFinite() && inertia.column2.isFinite()); + PX_ASSERT(q.isUnit()); + + PxMat33 m(q); + PxMat33 rotatedIT = m * inertia * m.getTranspose(); + PX_ASSERT(rotatedIT.column0.isFinite() && rotatedIT.column1.isFinite() && rotatedIT.column2.isFinite()); + return rotatedIT; + } + + /** + \brief Non-uniform scaling of the inertia tensor + + \param[in] inertia The inertia tensor to scale. + \param[in] scaleRotation The rotation from the scaling frame to the frame that inertia is expressed in. + I.e. scaleRotation.rotate(v) transforms the coordinates of vertex v from inertia's frame to the scaling-axes frame. + \param[in] scale The scaling factor for each axis (relative to the frame specified with scaleRotation). + \return The scaled inertia tensor. + */ + static PxMat33 scaleInertia(const PxMat33& inertia, const PxQuat& scaleRotation, const PxVec3& scale) + { + PX_ASSERT(inertia.column0.isFinite() && inertia.column1.isFinite() && inertia.column2.isFinite()); + PX_ASSERT(scaleRotation.isUnit()); + PX_ASSERT(scale.isFinite()); + + PxMat33 localInertiaT = rotateInertia(inertia, scaleRotation); // rotate inertia into scaling frame + PxVec3 diagonal(localInertiaT[0][0], localInertiaT[1][1], localInertiaT[2][2]); + + PxVec3 xyz2 = PxVec3(diagonal.dot(PxVec3(0.5f))) - diagonal; // original x^2, y^2, z^2 + PxVec3 scaledxyz2 = xyz2.multiply(scale).multiply(scale); + + PxReal xx = scaledxyz2.y + scaledxyz2.z, + yy = scaledxyz2.z + scaledxyz2.x, + zz = scaledxyz2.x + scaledxyz2.y; + + PxReal xy = localInertiaT[0][1] * scale.x * scale.y, + xz = localInertiaT[0][2] * scale.x * scale.z, + yz = localInertiaT[1][2] * scale.y * scale.z; + + PxMat33 scaledInertia( PxVec3(xx, xy, xz), + PxVec3(xy, yy, yz), + PxVec3(xz, yz, zz)); + + PxMat33 scaledIT = rotateInertia(scaledInertia * (scale.x * scale.y * scale.z), scaleRotation.getConjugate()); + PX_ASSERT(scaledIT.column0.isFinite() && scaledIT.column1.isFinite() && scaledIT.column2.isFinite()); + return scaledIT; + } + + /** + \brief Sum up individual mass properties. + + \param[in] props Array of mass properties to sum up. + \param[in] transforms Reference transforms for each mass properties entry. + \param[in] count The number of mass properties to sum up. + \return The summed up mass properties. + */ + static PxMassProperties sum(const PxMassProperties* props, const PxTransform* transforms, const PxU32 count) + { + PxReal combinedMass = 0.0f; + PxVec3 combinedCoM(0.0f); + PxMat33 combinedInertiaT = PxMat33(PxZero); + + for(PxU32 i = 0; i < count; i++) + { + PX_ASSERT(props[i].inertiaTensor.column0.isFinite() && props[i].inertiaTensor.column1.isFinite() && props[i].inertiaTensor.column2.isFinite()); + PX_ASSERT(props[i].centerOfMass.isFinite()); + PX_ASSERT(PxIsFinite(props[i].mass)); + + combinedMass += props[i].mass; + const PxVec3 comTm = transforms[i].transform(props[i].centerOfMass); + combinedCoM += comTm * props[i].mass; + } + + if(combinedMass > 0.f) + combinedCoM /= combinedMass; + + for(PxU32 i = 0; i < count; i++) + { + const PxVec3 comTm = transforms[i].transform(props[i].centerOfMass); + combinedInertiaT += translateInertia(rotateInertia(props[i].inertiaTensor, transforms[i].q), props[i].mass, combinedCoM - comTm); + } + + PX_ASSERT(combinedInertiaT.column0.isFinite() && combinedInertiaT.column1.isFinite() && combinedInertiaT.column2.isFinite()); + PX_ASSERT(combinedCoM.isFinite()); + PX_ASSERT(PxIsFinite(combinedMass)); + + return PxMassProperties(combinedMass, combinedInertiaT, combinedCoM); + } + + + PxMat33 inertiaTensor; //!< The inertia tensor of the object. + PxVec3 centerOfMass; //!< The center of mass of the object. + PxReal mass; //!< The mass of the object. +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxParticleClothCooker.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxParticleClothCooker.h new file mode 100644 index 000000000..fe3eaa0be --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxParticleClothCooker.h @@ -0,0 +1,122 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_CLOTH_COOKER_H +#define PX_PARTICLE_CLOTH_COOKER_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +namespace ExtGpu +{ + +/** +\brief Holds all the information for a particle cloth constraint used in the PxParticleClothCooker. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +struct PX_DEPRECATED PxParticleClothConstraint +{ + enum + { + eTYPE_INVALID_CONSTRAINT = 0, + eTYPE_HORIZONTAL_CONSTRAINT = 1, + eTYPE_VERTICAL_CONSTRAINT = 2, + eTYPE_DIAGONAL_CONSTRAINT = 4, + eTYPE_BENDING_CONSTRAINT = 8, + eTYPE_DIAGONAL_BENDING_CONSTRAINT = 16, + eTYPE_ALL = eTYPE_HORIZONTAL_CONSTRAINT | eTYPE_VERTICAL_CONSTRAINT | eTYPE_DIAGONAL_CONSTRAINT | eTYPE_BENDING_CONSTRAINT | eTYPE_DIAGONAL_BENDING_CONSTRAINT + }; + PxU32 particleIndexA; //!< The first particle index of this constraint. + PxU32 particleIndexB; //!< The second particle index of this constraint. + PxReal length; //!< The distance between particle A and B. + PxU32 constraintType; //!< The type of constraint, see the constraint type enum. +}; + +/* +\brief Generates PxParticleClothConstraint constraints that connect the individual particles of a particle cloth. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +class PX_DEPRECATED PxParticleClothCooker +{ +public: + virtual void release() = 0; + + /** + \brief Generate the constraint list and triangle index list. + + \param[in] constraints A pointer to an array of PxParticleClothConstraint constraints. If NULL, the cooker will generate all the constraints. Otherwise, the user-provided constraints will be added. + \param[in] numConstraints The number of user-provided PxParticleClothConstraint s. + */ + virtual void cookConstraints(const PxParticleClothConstraint* constraints = NULL, const PxU32 numConstraints = 0) = 0; + + virtual PxU32* getTriangleIndices() = 0; //!< \return A pointer to the triangle indices. + virtual PxU32 getTriangleIndicesCount() = 0; //!< \return The number of triangle indices. + virtual PxParticleClothConstraint* getConstraints() = 0; //!< \return A pointer to the PxParticleClothConstraint constraints. + virtual PxU32 getConstraintCount() = 0; //!< \return The number of constraints. + virtual void calculateMeshVolume() = 0; //!< Computes the volume of a closed mesh and the contraintScale. Expects vertices in local space - 'close' to origin. + virtual PxReal getMeshVolume() = 0; //!< \return The mesh volume calculated by PxParticleClothCooker::calculateMeshVolume. + +protected: + virtual ~PxParticleClothCooker() {} +}; + +} // namespace ExtGpu + +/** +\brief Creates a PxParticleClothCooker. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +\param[in] vertexCount The number of vertices of the particle cloth. +\param[in] inVertices The vertex positions of the particle cloth. +\param[in] triangleIndexCount The number of triangles of the cloth mesh. +\param[in] inTriangleIndices The triangle indices of the cloth mesh +\param[in] constraintTypeFlags The types of constraints to generate. See PxParticleClothConstraint. +\param[in] verticalDirection The vertical direction of the cloth mesh. This is needed to generate the correct horizontal and vertical constraints to model shear stiffness. +\param[in] bendingConstraintMaxAngle The maximum angle (in radians) considered in the bending constraints. + +\return A pointer to the new PxParticleClothCooker. +*/ +PX_DEPRECATED ExtGpu::PxParticleClothCooker* PxCreateParticleClothCooker(PxU32 vertexCount, physx::PxVec4* inVertices, PxU32 triangleIndexCount, PxU32* inTriangleIndices, + PxU32 constraintTypeFlags = ExtGpu::PxParticleClothConstraint::eTYPE_ALL, + PxVec3 verticalDirection = PxVec3(0.0f, 1.0f, 0.0f), PxReal bendingConstraintMaxAngle = 20.0f*PxTwoPi/360.0f +); + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxParticleExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxParticleExt.h new file mode 100644 index 000000000..e3f335cdf --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxParticleExt.h @@ -0,0 +1,410 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLE_EXT_H +#define PX_PARTICLE_EXT_H + +#include "PxPBDParticleSystem.h" +#include "PxParticleBuffer.h" +#include "foundation/PxArray.h" +#include "foundation/PxHashMap.h" +#include "foundation/PxUserAllocated.h" +#include "PxDeformableAttachment.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +namespace ExtGpu +{ + +/** +\brief Structure to define user-defined particle state when constructing a new particle system. +*/ +struct PxParticleBufferDesc +{ + PxVec4* positions; + PxVec4* velocities; + PxU32* phases; + PxParticleVolume* volumes; + PxU32 numActiveParticles; + PxU32 maxParticles; + PxU32 numVolumes; + PxU32 maxVolumes; + + PxParticleBufferDesc() : positions(NULL), velocities(NULL), phases(NULL), volumes(NULL), numActiveParticles(0), maxParticles(0), numVolumes(0), maxVolumes(0) { } +}; + +/** +\brief Structure to define user-defined particle state when constructing a new particle system that includes diffuse particles. +*/ +struct PxParticleAndDiffuseBufferDesc : public PxParticleBufferDesc +{ + PxDiffuseParticleParams diffuseParams; + PxU32 maxDiffuseParticles; + PxU32 maxActiveDiffuseParticles; + + PxParticleAndDiffuseBufferDesc() : PxParticleBufferDesc() { } +}; + +/** +\brief Structure to define user-defined particle state when constructing a new particle system that includes shape-matched rigid bodies. +*/ +struct PxParticleRigidDesc +{ + PxParticleRigidDesc() : rigidOffsets(NULL), rigidCoefficients(NULL), rigidTranslations(NULL), rigidRotations(NULL), + rigidLocalPositions(NULL), rigidLocalNormals(NULL), maxRigids(0), numActiveRigids(0) { } + + PxU32* rigidOffsets; + PxReal* rigidCoefficients; + PxVec4* rigidTranslations; + PxQuat* rigidRotations; + PxVec4* rigidLocalPositions; + PxVec4* rigidLocalNormals; + PxU32 maxRigids; + PxU32 numActiveRigids; +}; + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** +\brief Helper class to manage PxParticleClothDesc buffers used for communicating particle based cloths to PxParticleClothBuffer. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +class PX_DEPRECATED PxParticleClothBufferHelper +{ +public: + virtual void release() = 0; + + virtual PxU32 getMaxCloths() const = 0; //!< \return The maximum number of cloths this PxParticleClothBufferHelper can hold. + virtual PxU32 getNumCloths() const = 0; //!< \return The current number of cloths in this PxParticleClothBufferHelper. + virtual PxU32 getMaxSprings() const = 0; //!< \return The maximum number of springs this PxParticleClothBufferHelper can hold. + virtual PxU32 getNumSprings() const = 0; //!< \return The current number of springs in this PxParticleClothBufferHelper. + virtual PxU32 getMaxTriangles() const = 0; //!< \return The maximum number of triangles this PxParticleClothBufferHelper can hold. + virtual PxU32 getNumTriangles() const = 0; //!< \return The current number of triangles in this PxParticleClothBufferHelper. + virtual PxU32 getMaxParticles() const = 0; //!< \return The maximum number of particles this PxParticleClothBufferHelper can hold. + virtual PxU32 getNumParticles() const = 0; //!< \return The current number of particles in this PxParticleClothBufferHelper. + + /** + \brief Adds a PxParticleCloth to this PxParticleClothBufferHelper instance. + + \param[in] particleCloth The PxParticleCloth to be added. + \param[in] triangles A pointer to the triangles + \param[in] numTriangles The number of triangles + \param[in] springs A pointer to the springs + \param[in] numSprings The number of springs + \param[in] restPositions A pointer to the particle rest positions + \param[in] numParticles The number of particles in this cloth + + \see PxParticleCloth PxParticleSpring + */ + virtual void addCloth(const PxParticleCloth& particleCloth, + const PxU32* triangles, const PxU32 numTriangles, + const PxParticleSpring* springs, const PxU32 numSprings, const PxVec4* restPositions, const PxU32 numParticles) = 0; + + /** + \brief Adds a cloth to this PxParticleClothBufferHelper instance. + + Adds a cloth to this PxParticleClothBufferHelper instance. With this method the relevant parameters for inflatable simulation + (restVolume, pressure) can be set directly. + + \param[in] blendScale This should be 1.f / (numPartitions + 1) if the springs are partitioned by the user. Otherwise this will be set during spring partitioning. + \param[in] restVolume The rest volume of the inflatable + \param[in] pressure The pressure of the inflatable. The target inflatable volume is defined as restVolume * pressure. Setting this to > 0.0 will enable inflatable simulation. + \param[in] triangles A pointer to the triangles + \param[in] numTriangles The number of triangles + \param[in] springs A pointer to the springs + \param[in] numSprings The number of springs + \param[in] restPositions A pointer to the particle rest positions + \param[in] numParticles The number of particles in this cloth + + \see PxParticleSpring + */ + virtual void addCloth(const PxReal blendScale, const PxReal restVolume, const PxReal pressure, + const PxU32* triangles, const PxU32 numTriangles, + const PxParticleSpring* springs, const PxU32 numSprings, + const PxVec4* restPositions, const PxU32 numParticles) = 0; + + /** + \brief Returns a PxParticleClothDesc for this PxParticleClothBufferHelper instance to be used for spring partitioning. + + \return the PxParticleClothDesc. + + \see PxCreateAndPopulateParticleClothBuffer, PxParticleClothPreProcessor::partitionSprings + */ + virtual PxParticleClothDesc& getParticleClothDesc() = 0; + +protected: + virtual ~PxParticleClothBufferHelper() {} +}; + + +/** +\brief Helper struct that holds information about a specific mesh in a PxParticleVolumeBufferHelper. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +struct PX_DEPRECATED PxParticleVolumeMesh +{ + PxU32 startIndex; //!< The index of the first triangle of this mesh in the triangle array of the PxParticleVolumeBufferHelper instance. + PxU32 count; //!< The number of triangles of this mesh. +}; + +/** +\brief Helper class to manage communicating PxParticleVolumes data to PxParticleBuffer. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +class PX_DEPRECATED PxParticleVolumeBufferHelper +{ +public: + virtual void release() = 0; + + virtual PxU32 getMaxVolumes() const = 0; //!< \return The maximum number of PxParticleVolume this PxParticleVolumeBufferHelper instance can hold. + virtual PxU32 getNumVolumes() const = 0; //!< \return The current number of PxParticleVolume in this PxParticleVolumeBufferHelper instance. + virtual PxU32 getMaxTriangles() const = 0; //!< \return The maximum number of triangles this PxParticleVolumeBufferHelper instance can hold. + virtual PxU32 getNumTriangles() const = 0; //!< \return The current number of triangles in this PxParticleVolumeBufferHelper instance. + + virtual PxParticleVolume* getParticleVolumes() = 0; //!< \return A pointer to the PxParticleVolume s of this PxParticleVolumeBufferHelper instance. + virtual PxParticleVolumeMesh* getParticleVolumeMeshes() = 0; //!< \return A pointer to the PxParticleVolumeMesh structs describing the PxParticleVolumes of this PxParticleVolumeBufferHelper instance. + virtual PxU32* getTriangles() = 0; //!< \return A pointer to the triangle indices in this PxParticleVolumeBufferHelper instance. + + /** + \brief Adds a PxParticleVolume with a PxParticleVolumeMesh + + \param[in] volume The PxParticleVolume to be added. + \param[in] volumeMesh A PxParticleVolumeMesh that describes the volumes to be added. startIndex is the index into the triangle list of the PxParticleVolumeBufferHelper instance. + \param[in] triangles A pointer to the triangle indices of the PxParticleVolume to be added. + \param[in] numTriangles The number of triangles of the PxParticleVolume to be added. + */ + virtual void addVolume(const PxParticleVolume& volume, const PxParticleVolumeMesh& volumeMesh, const PxU32* triangles, const PxU32 numTriangles) = 0; + + /** + \brief Adds a volume + + \param[in] particleOffset The index of the first particle of the cloth that maps to this volume in the PxParticleClothBufferHelper instance. + \param[in] numParticles The number of particles of the cloth that maps to this volume in the PxParticleClothBufferHelper instance. + \param[in] triangles A pointer to the triangle indices of this volume. + \param[in] numTriangles The number of triangles in this volume. + */ + virtual void addVolume(const PxU32 particleOffset, const PxU32 numParticles, const PxU32* triangles, const PxU32 numTriangles) = 0; + +protected: + virtual ~PxParticleVolumeBufferHelper() {} +}; + + +/** +\brief Helper class to manage PxParticleRigidDesc buffers used for communicating particle based rigids to PxPaticleSystem. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +class PX_DEPRECATED PxParticleRigidBufferHelper +{ +public: + virtual void release() = 0; + + virtual PxU32 getMaxRigids() const = 0; //!< \return The maximum number of rigids this PxParticleRigidBufferHelper instance can hold. + virtual PxU32 getNumRigids() const = 0; //!< \return The current number of rigids in this PxParticleRigidBufferHelper instance. + virtual PxU32 getMaxParticles() const = 0; //!< \return The maximum number of particles this PxParticleRigidBufferHelper instance can hold. + virtual PxU32 getNumParticles() const = 0; //!< \return The current number of particles in this PxParticleRigidBufferHelper instance. + + /** + \brief Adds a rigid. + + \param[in] translation The world-space location of the rigid. + \param[in] rotation The world-space rotation of the rigid. + \param[in] coefficient The stiffness of the rigid. + \param[in] localPositions The particle positions in local space. + \param[in] localNormals The surface normal for all the particles in local space. Each PxVec4 has the normal in the first 3 components and the SDF in the last component. + \param[in] numParticles The number of particles in this rigid. + */ + virtual void addRigid(const PxVec3& translation, const PxQuat& rotation, const PxReal coefficient, + const PxVec4* localPositions, const PxVec4* localNormals, PxU32 numParticles) = 0; + + /** + \brief Get the PxParticleRigidDesc for this buffer. + + \returns A PxParticleRigidDesc. + */ + virtual PxParticleRigidDesc& getParticleRigidDesc() = 0; + +protected: + virtual ~PxParticleRigidBufferHelper() {} +}; + +/////////////////////////////////////////////////////////////////////////////// + +/** +\brief Holds user-defined attachment data to attach particles to other bodies + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. +*/ +class PX_DEPRECATED PxParticleAttachmentBuffer : public PxUserAllocated +{ + PxArray mAttachments; + PxArray mFilters; + PxHashMap mReferencedBodies; + PxArray mNewReferencedBodies; + PxArray mDestroyedRefrencedBodies; + + PxParticleBuffer& mParticleBuffer; + + PxParticleRigidAttachment* mDeviceAttachments; + PxParticleRigidFilterPair* mDeviceFilters; + PxU32 mNumDeviceAttachments; + PxU32 mNumDeviceFilters; + + PxCudaContextManager* mCudaContextManager; + + PxParticleSystem& mParticleSystem; + + bool mDirty; + + PX_NOCOPY(PxParticleAttachmentBuffer) + +public: + + PxParticleAttachmentBuffer(PxParticleBuffer& particleBuffer, PxPBDParticleSystem& particleSystem); + + ~PxParticleAttachmentBuffer(); + + // adds attachment to attachment buffer - localPose is in actor space for attachments to all types of rigids. + void addRigidAttachment(PxRigidActor* rigidBody, const PxU32 particleID, const PxVec3& localPose, PxConeLimitedConstraint* coneLimit = NULL); + bool removeRigidAttachment(PxRigidActor* rigidBody, const PxU32 particleID); + void addRigidFilter(PxRigidActor* rigidBody, const PxU32 particleID); + bool removeRigidFilter(PxRigidActor* rigidBody, const PxU32 particleID); + + void copyToDevice(CUstream stream = 0); +}; + +/** +\brief Creates a PxParticleRigidBufferHelper. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +\param[in] maxRigids The maximum number of rigids this PxParticleRigidsBuffers instance should hold. +\param[in] maxParticles The maximum number of particles this PxParticleRigidBufferHelper instance should hold. +\param[in] cudaContextManager A pointer to a PxCudaContextManager. + +\return A pointer to the new PxParticleRigidBufferHelper. +*/ +PX_DEPRECATED PxParticleRigidBufferHelper* PxCreateParticleRigidBufferHelper(PxU32 maxRigids, PxU32 maxParticles, PxCudaContextManager* cudaContextManager); + +/** +\brief Creates a PxParticleClothBufferHelper helper. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +\param[in] maxCloths The maximum number of cloths this PxParticleClothBufferHelper should hold. +\param[in] maxTriangles The maximum number of triangles this PxParticleClothBufferHelper should hold. +\param[in] maxSprings The maximum number of springs this PxParticleClothBufferHelper should hold. +\param[in] maxParticles The maximum number of particles this PxParticleClothBufferHelper should hold. +\param[in] cudaContextManager A pointer to a PxCudaContextManager. + +\return A pointer to the PxParticleClothBufferHelper that was created. +*/ +PX_DEPRECATED PxParticleClothBufferHelper* PxCreateParticleClothBufferHelper(const PxU32 maxCloths, const PxU32 maxTriangles, const PxU32 maxSprings, const PxU32 maxParticles, PxCudaContextManager* cudaContextManager); + +/** +\brief Creates a PxParticleVolumeBufferHelper. + +\param[in] maxVolumes The maximum number of PxParticleVolume s this PxParticleVolumeBufferHelper instance should hold. +\param[in] maxTriangles The maximum number of triangles this PxParticleVolumeBufferHelper instance should hold. +\param[in] cudaContextManager A pointer to a PxCudaContextManager. + +\return A pointer to the new PxParticleVolumeBufferHelper. +*/ +PX_DEPRECATED PxParticleVolumeBufferHelper* PxCreateParticleVolumeBufferHelper(PxU32 maxVolumes, PxU32 maxTriangles, PxCudaContextManager* cudaContextManager); + +/** +\brief Creates a particle attachment buffer + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +\param[in] particleBuffer The particle buffer that contains particles that should get attached to something +\param[in] particleSystem The particle system that is used to simulate the userBuffer +\return An attachment buffer ready to use +*/ +PX_DEPRECATED PxParticleAttachmentBuffer* PxCreateParticleAttachmentBuffer(PxParticleBuffer& particleBuffer, PxParticleSystem& particleSystem); + +/** +\brief Creates and populates a particle buffer + +\param[in] desc The particle buffer descriptor +\param[in] cudaContextManager A cuda context manager +\return A fully populated particle buffer ready to use +*/ +PxParticleBuffer* PxCreateAndPopulateParticleBuffer(const ExtGpu::PxParticleBufferDesc& desc, PxCudaContextManager* cudaContextManager); + +/** +\brief Creates and populates a particle buffer that includes support for diffuse particles + +\param[in] desc The particle buffer descriptor +\param[in] cudaContextManager A cuda context manager +\return A fully populated particle buffer ready to use +*/ +PxParticleAndDiffuseBuffer* PxCreateAndPopulateParticleAndDiffuseBuffer(const ExtGpu::PxParticleAndDiffuseBufferDesc& desc, PxCudaContextManager* cudaContextManager); + +/** +\brief Creates and populates a particle cloth buffer + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +\param[in] desc The particle buffer descriptor +\param[in] clothDesc The cloth descriptor +\param[out] output A cloth output object to further configure the behavior of the cloth +\param[in] cudaContextManager A cuda context manager +\return A fully populated particle cloth buffer ready to use +*/ +PX_DEPRECATED PxParticleClothBuffer* PxCreateAndPopulateParticleClothBuffer(const ExtGpu::PxParticleBufferDesc& desc, const PxParticleClothDesc& clothDesc, + PxPartitionedParticleCloth& output, PxCudaContextManager* cudaContextManager); + +/** +\brief Creates and populates a particle rigid buffer. Particle rigids are particles that try to keep their relative positions. They are a bit commpressible similar to softbodies. + +\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated. + +\param[in] desc The particle buffer descriptor +\param[in] rigidDesc The rigid descriptor +\param[in] cudaContextManager A cuda context manager +\return A fully populated particle rigid buffer ready to use +*/ +PX_DEPRECATED PxParticleRigidBuffer* PxCreateAndPopulateParticleRigidBuffer(const ExtGpu::PxParticleBufferDesc& desc, const ExtGpu::PxParticleRigidDesc& rigidDesc, + PxCudaContextManager* cudaContextManager); + +} // namespace ExtGpu + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxPrismaticJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxPrismaticJoint.h new file mode 100644 index 000000000..0e70daecf --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxPrismaticJoint.h @@ -0,0 +1,174 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PRISMATIC_JOINT_H +#define PX_PRISMATIC_JOINT_H + +#include "extensions/PxJoint.h" +#include "extensions/PxJointLimit.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxPrismaticJoint; + +/** +\brief Create a prismatic joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + +\see PxPrismaticJoint +*/ +PxPrismaticJoint* PxPrismaticJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + + +/** +\brief Flags specific to the prismatic joint. + +\see PxPrismaticJoint +*/ +struct PxPrismaticJointFlag +{ + enum Enum + { + eLIMIT_ENABLED = 1<<1 + }; +}; + +typedef PxFlags PxPrismaticJointFlags; +PX_FLAGS_OPERATORS(PxPrismaticJointFlag::Enum, PxU16) + +/** + \brief A prismatic joint permits relative translational movement between two bodies along + an axis, but no relative rotational movement. + + The axis on each body is defined as the line containing the origin of the joint frame and + extending along the x-axis of that frame. + + \image html prismJoint.png + + \see PxPrismaticJointCreate() PxJoint +*/ +class PxPrismaticJoint : public PxJoint +{ +public: + + /** + \brief returns the displacement of the joint along its axis. + */ + virtual PxReal getPosition() const = 0; + + /** + \brief returns the velocity of the joint along its axis + */ + virtual PxReal getVelocity() const = 0; + + /** + \brief sets the joint limit parameters. + + The limit range is [-PX_MAX_F32, PX_MAX_F32], but note that the width of the limit (upper-lower) must also be + a valid float. + + \see PxJointLinearLimitPair getLimit() + */ + virtual void setLimit(const PxJointLinearLimitPair&) = 0; + + /** + \brief gets the joint limit parameters. + + \see PxJointLinearLimit getLimit() + */ + virtual PxJointLinearLimitPair getLimit() const = 0; + + /** + \brief Set the flags specific to the Prismatic Joint. + + Default PxPrismaticJointFlags(0) + + \param[in] flags The joint flags. + + \see PxPrismaticJointFlag setFlag() getFlags() + */ + virtual void setPrismaticJointFlags(PxPrismaticJointFlags flags) = 0; + + /** + \brief Set a single flag specific to a Prismatic Joint to true or false. + + \param[in] flag The flag to set or clear. + \param[in] value The value to which to set the flag + + \see PxPrismaticJointFlag, getFlags() setFlags() + */ + virtual void setPrismaticJointFlag(PxPrismaticJointFlag::Enum flag, bool value) = 0; + + /** + \brief Get the flags specific to the Prismatic Joint. + + \return the joint flags + + \see PxPrismaticJoint::flags, PxPrismaticJointFlag setFlag() setFlags() + */ + virtual PxPrismaticJointFlags getPrismaticJointFlags() const = 0; + + /** + \brief Returns string name of PxPrismaticJoint, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxPrismaticJoint"; } + +protected: + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxPrismaticJoint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxPrismaticJoint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxPrismaticJoint", PxJoint); } + + //~serialization +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRackAndPinionJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRackAndPinionJoint.h new file mode 100644 index 000000000..c572aeaab --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRackAndPinionJoint.h @@ -0,0 +1,140 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RACK_AND_PINION_JOINT_H +#define PX_RACK_AND_PINION_JOINT_H + +#include "extensions/PxJoint.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxRackAndPinionJoint; + + /** + \brief Create a rack & pinion Joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + + \see PxRackAndPinionJoint + */ + PxRackAndPinionJoint* PxRackAndPinionJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + + /** + \brief A joint that connects an existing revolute joint to an existing prismatic joint, + and constrains their relative angular/linear velocity and position with respect to each other. + + \see PxRackAndPinionJointCreate PxJoint + */ + class PxRackAndPinionJoint : public PxJoint + { + public: + + /** + \brief Set the hinge & prismatic joints connected by the rack & pinion joint. + + The passed hinge joint can be either PxRevoluteJoint, PxD6Joint or PxArticulationJointReducedCoordinate. + The passed prismatic joint can be either PxPrismaticJoint or PxD6Joint. + + Note that these joints are only used to compute the positional error correction term, + used to adjust potential drift between jointed actors. The rack & pinion joint can run without + calling this function, but in that case some visible overlap may develop over time between + the teeth of the rack & pinion meshes. + + \note Calling this function resets the internal positional error correction term. + + \param[in] hinge The hinge joint (pinion) + \param[in] prismatic The prismatic joint (rack) + \return true if success + */ + virtual bool setJoints(const PxBase* hinge, const PxBase* prismatic) = 0; + + /** + \brief Get the hinge & prismatic joints connected by the rack & pinion joint. + + \param[out] hinge The hinge joint (pinion) + \param[out] prismatic The prismatic joint (rack) + */ + virtual void getJoints(const PxBase*& hinge, const PxBase*& prismatic) const = 0; + + /** + \brief Set the desired ratio directly. + + \note You may need to use a negative gear ratio if the joint frames of involved actors are not oriented in the same direction. + + \note Calling this function resets the internal positional error correction term. + + \param[in] ratio Desired ratio between the hinge and the prismatic. + */ + virtual void setRatio(float ratio) = 0; + + /** + \brief Get the ratio. + + \return Current ratio + */ + virtual float getRatio() const = 0; + + /** + \brief Set the desired ratio indirectly. + + This is a simple helper function that computes the ratio from passed data: + + ratio = (PI*2*nbRackTeeth)/(rackLength*nbPinionTeeth) + + \note Calling this function resets the internal positional error correction term. + + \param[in] nbRackTeeth Number of teeth on the rack (cannot be zero) + \param[in] nbPinionTeeth Number of teeth on the pinion (cannot be zero) + \param[in] rackLength Length of the rack + \return true if success + */ + virtual bool setData(PxU32 nbRackTeeth, PxU32 nbPinionTeeth, float rackLength) = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxRackAndPinionJoint"; } + + protected: + + PX_INLINE PxRackAndPinionJoint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + PX_INLINE PxRackAndPinionJoint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRackAndPinionJoint", PxJoint); } + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRaycastCCD.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRaycastCCD.h new file mode 100644 index 000000000..d3dc93f27 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRaycastCCD.h @@ -0,0 +1,105 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RAYCAST_CCD_H +#define PX_RAYCAST_CCD_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxScene; + class PxShape; + class PxRigidDynamic; + class RaycastCCDManagerInternal; + + /** + \brief Raycast-CCD manager. + + Raycast-CCD is a simple and potentially cheaper alternative to the SDK's built-in continuous collision detection algorithm. + + This implementation has some limitations: + - it is only implemented for PxRigidDynamic objects (not for PxArticulationLink) + - it is only implemented for simple actors with 1 shape (not for "compounds") + + Also, since it is raycast-based, the solution is not perfect. In particular: + - small dynamic objects can still go through the static world if the ray goes through a crack between edges, or a small + hole in the world (like the keyhole from a door). + - dynamic-vs-dynamic CCD is very approximate. It only works well for fast-moving dynamic objects colliding against + slow-moving dynamic objects. + + Finally, since it is using the SDK's scene queries under the hood, it only works provided the simulation shapes also have + scene-query shapes associated with them. That is, if the objects in the scene only use PxShapeFlag::eSIMULATION_SHAPE + (and no PxShapeFlag::eSCENE_QUERY_SHAPE), then the raycast-CCD system will not work. + */ + class RaycastCCDManager + { + public: + RaycastCCDManager(PxScene* scene); + ~RaycastCCDManager(); + + /** + \brief Register dynamic object for raycast CCD. + + \param[in] actor object's actor + \param[in] shape object's shape + + \return True if success + */ + bool registerRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape); + + /** + \brief Unregister dynamic object for raycast CCD. + + \param[in] actor object's actor + \param[in] shape object's shape + + \return True if success + */ + bool unregisterRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape); + + /** + \brief Perform raycast CCD. Call this after your simulate/fetchResults calls. + + \param[in] doDynamicDynamicCCD True to enable dynamic-vs-dynamic CCD (more expensive, not always needed) + */ + void doRaycastCCD(bool doDynamicDynamicCCD); + + private: + RaycastCCDManagerInternal* mImpl; + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRemeshingExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRemeshingExt.h new file mode 100644 index 000000000..43aa588c1 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRemeshingExt.h @@ -0,0 +1,87 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_REMESHING_EXT_H +#define PX_REMESHING_EXT_H + +#include "foundation/PxVec3.h" +#include "foundation/PxArray.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Provides methods to adjust the tessellation of meshes + */ + class PxRemeshingExt + { + public: + /** + \brief Processes a triangle mesh and makes sure that no triangle edge is longer than the maximal edge length specified + + To shorten edges that are too long, additional points get inserted at their center leading to a subdivision of the input mesh. + This process is executed repeatedly until the maximum edge length criterion is satisfied + + \param[in,out] triangles The triangles of the mesh where a maximum edge length should be enforced. They will be modified in place during the process. + \param[in,out] points The vertices of the mesh where a maximum edge length should be enforced. They will be modified in place during the process. + \param[in] maxEdgeLength The maximum edge length allowed after processing the input + \param[in] maxIterations The maximum number of subdivision iterations + \param[out] triangleMap An optional map that provides the index of the original triangle for every triangle after the subdivision + \param[in] triangleCountThreshold Optional limit to the number of triangles. Not guaranteed to match exactly, the algorithm will just stop as soon as possible after reaching the limit. + + \return True if any remeshing was applied + */ + static bool limitMaxEdgeLength(PxArray& triangles, PxArray& points, PxReal maxEdgeLength, + PxU32 maxIterations = 100, PxArray* triangleMap = NULL, PxU32 triangleCountThreshold = 0xFFFFFFFF); + + /** + \brief Processes a triangle mesh and makes sure that no triangle edge is longer than the maximal edge length specified + + To shorten edges that are too long, additional points get inserted at their center leading to a subdivision of the input mesh. + This process is executed repeatedly until the maximum edge length criterion is satisfied + + \param[in,out] triangles The triangles of the mesh where a maximum edge length should be enforced. They will be modified in place during the process. + \param[in,out] points The vertices of the mesh where a maximum edge length should be enforced. They will be modified in place during the process. + \param[in] maxEdgeLength The maximum edge length allowed after processing the input + \param[in] maxIterations The maximum number of subdivision iterations + \param[out] triangleMap An optional map that provides the index of the original triangle for every triangle after the subdivision + \param[in] triangleCountThreshold Optional limit to the number of triangles. Not guaranteed to match exactly, the algorithm will just stop as soon as possible after reaching the limit. + + \return True if any remeshing was applied + */ + static bool reduceSliverTriangles(PxArray& triangles, PxArray& points, PxReal maxEdgeLength, + PxU32 maxIterations = 3, PxArray* triangleMap = NULL, PxU32 triangleCountThreshold = 0xFFFFFFFF); + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRepXSerializer.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRepXSerializer.h new file mode 100644 index 000000000..d8e740919 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRepXSerializer.h @@ -0,0 +1,152 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_REPX_SERIALIZER_H +#define PX_REPX_SERIALIZER_H + +#include "common/PxBase.h" +#include "extensions/PxRepXSimpleType.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class XmlMemoryAllocator; + class XmlWriter; + class XmlReader; + class MemoryBuffer; + + /** + \brief Serializer interface for RepX (Xml) serialization. + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + In order to serialize a class to RepX both a PxSerializer and + a PxRepXSerializer implementation are needed. + + A repx Serializer provides the ability to capture a live + object to a descriptor or static state and the ability to + write that state out to a file. Objects allocated + by the Serializer using the allocator are freed when the + collection itself is freed. + SnRepXCoreSerializers.cpp implements a set of Serializers + for the core PhysX types. + + \note Implementing a PxRepXSerializer is currently not practical without including the internal PhysXExtension header "SnRepXSerializerImpl.h". + + \see PxSerializer, PX_NEW_REPX_SERIALIZER, PxSerializationRegistry::registerRepXSerializer + */ + class PX_DEPRECATED PxRepXSerializer + { + protected: + virtual ~PxRepXSerializer(){} + public: + + /** + \brief The type this Serializer is meant to operate on. + \see PxRepXObject::typeName + */ + virtual const char* getTypeName() = 0; + + /** + \brief Convert from a RepX object to a key-value pair hierarchy + + \param[in] inLiveObject The object to convert to the passed in descriptor. + \param[in] inCollection The collection to use to find ids of references of this object. + \param[in] inWriter Interface to write data to. + \param[in] inTempBuffer used to for temporary allocations. + \param[in] inArgs The arguments used in create resources and objects. + */ + virtual void objectToFile( const PxRepXObject& inLiveObject, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& inArgs ) = 0; + + /** + \brief Convert from a descriptor to a live object. Must be an object of this Serializer type. + + \param[in] inReader The inverse of the writer, a key-value pair database. + \param[in] inAllocator An allocator to use for temporary allocations. These will be freed after instantiation completes. + \param[in] inArgs The arguments used in create resources and objects. + \param[in] inCollection The collection used to find references. + + \return The new live object. It can be an invalid object if the instantiation cannot take place. + */ + virtual PxRepXObject fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection ) = 0; + + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** +\brief Inline helper template function to create PxRepXObject from TDataType type supporting PxTypeInfo::name. +\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. +*/ +template +PX_DEPRECATED PX_INLINE physx::PxRepXObject PxCreateRepXObject(const TDataType* inType, const physx::PxSerialObjectId inId) +{ + return physx::PxRepXObject(physx::PxTypeInfo::name(), inType, inId); +} + +/** +\brief Inline helper function to create PxRepXObject from a PxBase instance. +\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. +*/ +PX_DEPRECATED PX_INLINE physx::PxRepXObject PxCreateRepXObject(const physx::PxBase* inType, const physx::PxSerialObjectId inId) +{ + PX_ASSERT(inType); + return physx::PxRepXObject(inType->getConcreteTypeName(), inType, inId); +} + +/** +\brief Inline helper template function to create PxRepXObject form TDataType type using inType pointer as a PxSerialObjectId id. +\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. +*/ +template +PX_DEPRECATED PX_INLINE physx::PxRepXObject PxCreateRepXObject(const TDataType* inType) +{ + return PxCreateRepXObject(inType, static_cast(size_t(inType))); +} + +/** +\brief Preprocessor macro for RepX serializer creation. +\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. +*/ +#define PX_NEW_REPX_SERIALIZER(T) \ + *PX_PLACEMENT_NEW(PxGetAllocatorCallback()->allocate(sizeof(T), "PxRepXSerializer", PX_FL), T)(*PxGetAllocatorCallback()) + +/** +\brief Preprocessor Macro to simplify RepX serializer delete. +\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. +*/ +#define PX_DELETE_REPX_SERIALIZER(x) \ + { PxRepXSerializer* s = x; if (s) { PxGetAllocatorCallback()->deallocate(s); } } + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRepXSimpleType.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRepXSimpleType.h new file mode 100644 index 000000000..48b77729c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRepXSimpleType.h @@ -0,0 +1,103 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_REPX_SIMPLE_TYPE_H +#define PX_REPX_SIMPLE_TYPE_H + + +#include "foundation/PxSimpleTypes.h" +#include "cooking/PxCooking.h" +#include "common/PxStringTable.h" +#include "common/PxSerialFramework.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Helper class containing the mapping of id to object, and type name. + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + */ + struct PX_DEPRECATED PxRepXObject + { + /** + \brief Identifies the extension meant to handle this object. + \see PxTypeInfo, PX_DEFINE_TYPEINFO, PxRepXSerializer + */ + const char* typeName; + + /** + \brief Pointer to the serializable this was created from + */ + const void* serializable; + + /** + \brief Id given to this object at some point + */ + PxSerialObjectId id; + PxRepXObject( const char* inTypeName = "", const void* inSerializable = NULL, const PxSerialObjectId inId = 0 ) + : typeName( inTypeName ) + , serializable( inSerializable ) + , id( inId ) + { + } + bool isValid() const { return serializable != NULL; } + }; + + /** + \brief Arguments required to instantiate a serializable object from RepX. + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + Extra arguments can be added to the object map under special ids. + + \see PxRepXSerializer::objectToFile, PxRepXSerializer::fileToObject + */ + struct PX_DEPRECATED PxRepXInstantiationArgs + { + PxPhysics& physics; + const PxCookingParams* cooker; + PxStringTable* stringTable; + PxRepXInstantiationArgs( PxPhysics& inPhysics, const PxCookingParams* inCooking = NULL , PxStringTable* inStringTable = NULL ) + : physics( inPhysics ) + , cooker( inCooking ) + , stringTable( inStringTable ) + { + } + + PxRepXInstantiationArgs& operator=(const PxRepXInstantiationArgs&); + }; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRevoluteJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRevoluteJoint.h new file mode 100644 index 000000000..dc9e9899b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRevoluteJoint.h @@ -0,0 +1,265 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_REVOLUTE_JOINT_H +#define PX_REVOLUTE_JOINT_H + +#include "extensions/PxJoint.h" +#include "extensions/PxJointLimit.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxRevoluteJoint; + +/** +\brief Create a revolute joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + +\see PxRevoluteJoint +*/ +PxRevoluteJoint* PxRevoluteJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + +/** +\brief Flags specific to the Revolute Joint. + +\see PxRevoluteJoint +*/ +struct PxRevoluteJointFlag +{ + enum Enum + { + eLIMIT_ENABLED = 1<<0, //!< enable the limit + eDRIVE_ENABLED = 1<<1, //!< enable the drive + eDRIVE_FREESPIN = 1<<2 //!< if the existing velocity is beyond the drive velocity, do not add force + }; +}; + +typedef PxFlags PxRevoluteJointFlags; +PX_FLAGS_OPERATORS(PxRevoluteJointFlag::Enum, PxU16) + +/** + +\brief A joint which behaves in a similar way to a hinge or axle. + + A hinge joint removes all but a single rotational degree of freedom from two objects. + The axis along which the two bodies may rotate is specified with a point and a direction + vector. + + The position of the hinge on each body is specified by the origin of the body's joint frame. + The axis of the hinge is specified as the direction of the x-axis in the body's joint frame. + + \image html revoluteJoint.png + + A revolute joint can be given a motor, so that it can apply a force to rotate the attached actors. + It may also be given a limit, to restrict the revolute motion to within a certain range. + + Drive and limits are activated by setting the appropriate flags on the joint. + + \see PxRevoluteJointCreate() PxJoint +*/ +class PxRevoluteJoint : public PxJoint +{ +public: + + /** + \brief return the angle of the joint, in the range (-2*Pi, 2*Pi] + */ + virtual PxReal getAngle() const = 0; + + /** + \brief return the velocity of the joint + */ + virtual PxReal getVelocity() const = 0; + + /** + \brief set the joint limit parameters. + + The limit is activated using the flag PxRevoluteJointFlag::eLIMIT_ENABLED + + The limit angle range is (-2*Pi, 2*Pi). + + \param[in] limits The joint limit parameters. + + \see PxJointAngularLimitPair getLimit() + */ + virtual void setLimit(const PxJointAngularLimitPair& limits) = 0; + + /** + \brief get the joint limit parameters. + + \return the joint limit parameters + + \see PxJointAngularLimitPair setLimit() + */ + virtual PxJointAngularLimitPair getLimit() const = 0; + + /** + \brief set the target velocity for the drive model. + + The motor will only be able to reach this velocity if the maxForce is sufficiently large. + If the joint is spinning faster than this velocity, the motor will actually try to brake + (see PxRevoluteJointFlag::eDRIVE_FREESPIN.) + + The sign of this variable determines the rotation direction, with positive values going + the same way as positive joint angles. Setting a very large target velocity may cause + undesirable results. + + \param[in] velocity the drive target velocity + \param[in] autowake Whether to wake up the joint rigids if they are asleep. + + Range: (-PX_MAX_F32, PX_MAX_F32)
+ Default: 0.0 + + \see PxRevoluteFlags::eDRIVE_FREESPIN + */ + virtual void setDriveVelocity(PxReal velocity, bool autowake = true) = 0; + + /** + \brief gets the target velocity for the drive model. + + \return the drive target velocity + + \see setDriveVelocity() + */ + virtual PxReal getDriveVelocity() const = 0; + + /** + \brief sets the maximum torque the drive can exert. + + The value set here may be used either as an impulse limit or a force limit, depending on the flag PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES + + Range: [0, PX_MAX_F32)
+ Default: PX_MAX_F32 + + \see setDriveVelocity() + */ + virtual void setDriveForceLimit(PxReal limit) = 0; + + /** + \brief gets the maximum torque the drive can exert. + + \return the torque limit + + \see setDriveVelocity() + */ + virtual PxReal getDriveForceLimit() const = 0; + + /** + \brief sets the gear ratio for the drive. + + When setting up the drive constraint, the velocity of the first actor is scaled by this value, and its response to drive torque is scaled down. + So if the drive target velocity is zero, the second actor will be driven to the velocity of the first scaled by the gear ratio + + Range: [0, PX_MAX_F32)
+ Default: 1.0 + + \param[in] ratio the drive gear ratio + + \see getDriveGearRatio() + */ + virtual void setDriveGearRatio(PxReal ratio) = 0; + + /** + \brief gets the gear ratio. + + \return the drive gear ratio + + \see setDriveGearRatio() + */ + virtual PxReal getDriveGearRatio() const = 0; + + /** + \brief sets the flags specific to the Revolute Joint. + + Default PxRevoluteJointFlags(0) + + \param[in] flags The joint flags. + + \see PxRevoluteJointFlag setFlag() getFlags() + */ + virtual void setRevoluteJointFlags(PxRevoluteJointFlags flags) = 0; + + /** + \brief sets a single flag specific to a Revolute Joint. + + \param[in] flag The flag to set or clear. + \param[in] value the value to which to set the flag + + \see PxRevoluteJointFlag, getFlags() setFlags() + */ + virtual void setRevoluteJointFlag(PxRevoluteJointFlag::Enum flag, bool value) = 0; + + /** + \brief gets the flags specific to the Revolute Joint. + + \return the joint flags + + \see PxRevoluteJoint::flags, PxRevoluteJointFlag setFlag() setFlags() + */ + virtual PxRevoluteJointFlags getRevoluteJointFlags() const = 0; + + /** + \brief Returns string name of PxRevoluteJoint, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxRevoluteJoint"; } + +protected: + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxRevoluteJoint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxRevoluteJoint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRevoluteJoint", PxJoint); } + + //~serialization +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRigidActorExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRigidActorExt.h new file mode 100644 index 000000000..df7065291 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRigidActorExt.h @@ -0,0 +1,162 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RIGID_ACTOR_EXT_H +#define PX_RIGID_ACTOR_EXT_H + +#include "PxPhysXConfig.h" +#include "PxPhysics.h" +#include "PxRigidActor.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxBVH; + +/** +\brief utility functions for use with PxRigidActor and subclasses + +\see PxRigidActor PxRigidStatic PxRigidBody PxRigidDynamic PxArticulationLink +*/ + +class PxRigidActorExt +{ +public: + + /** + \brief Creates a new shape with default properties and a list of materials and adds it to the list of shapes of this actor. + + This is equivalent to the following + + PxShape* shape(...) = PxGetPhysics().createShape(...); // reference count is 1 + actor->attachShape(shape); // increments reference count + shape->release(); // releases user reference, leaving reference count at 1 + + As a consequence, detachShape() will result in the release of the last reference, and the shape will be deleted. + + \note The default shape flags to be set are: eVISUALIZATION, eSIMULATION_SHAPE, eSCENE_QUERY_SHAPE (see #PxShapeFlag). + Triangle mesh, heightfield or plane geometry shapes configured as eSIMULATION_SHAPE are not supported for + non-kinematic PxRigidDynamic instances. + + \note Creating compounds with a very large number of shapes may adversely affect performance and stability. + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] actor the actor to which to attach the shape + \param[in] geometry the geometry of the shape + \param[in] materials a pointer to an array of material pointers + \param[in] materialCount the count of materials + \param[in] shapeFlags optional PxShapeFlags + + \return The newly created shape. + + \see PxShape PxShape::release(), PxPhysics::createShape(), PxRigidActor::attachShape() + */ + static PxShape* createExclusiveShape(PxRigidActor& actor, const PxGeometry& geometry, PxMaterial*const* materials, PxU16 materialCount, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) + { + PxShape* shape = PxGetPhysics().createShape(geometry, materials, materialCount, true, shapeFlags); + if(shape) + { + bool status = actor.attachShape(*shape); // attach can fail, if e.g. we try and attach a trimesh simulation shape to a dynamic actor + shape->release(); // if attach fails, we hold the only counted reference, and so this cleans up properly + if(!status) + shape = NULL; + } + return shape; + } + + /** + \brief Creates a new shape with default properties and a single material adds it to the list of shapes of this actor. + + This is equivalent to the following + + PxShape* shape(...) = PxGetPhysics().createShape(...); // reference count is 1 + actor->attachShape(shape); // increments reference count + shape->release(); // releases user reference, leaving reference count at 1 + + As a consequence, detachShape() will result in the release of the last reference, and the shape will be deleted. + + \note The default shape flags to be set are: eVISUALIZATION, eSIMULATION_SHAPE, eSCENE_QUERY_SHAPE (see #PxShapeFlag). + Triangle mesh, heightfield or plane geometry shapes configured as eSIMULATION_SHAPE are not supported for + non-kinematic PxRigidDynamic instances. + + \note Creating compounds with a very large number of shapes may adversely affect performance and stability. + + Sleeping: Does NOT wake the actor up automatically. + + \param[in] actor the actor to which to attach the shape + \param[in] geometry the geometry of the shape + \param[in] material the material for the shape + \param[in] shapeFlags optional PxShapeFlags + + \return The newly created shape. + + \see PxShape PxShape::release(), PxPhysics::createShape(), PxRigidActor::attachShape() + */ + static PX_FORCE_INLINE PxShape* createExclusiveShape(PxRigidActor& actor, const PxGeometry& geometry, const PxMaterial& material, + PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) + { + PxMaterial* materialPtr = const_cast(&material); + return createExclusiveShape(actor, geometry, &materialPtr, 1, shapeFlags); + } + + /** + \brief Gets a list of bounds based on shapes in rigid actor. This list can be used to cook/create + bounding volume hierarchy though PxCooking API. + + \param[in] actor The actor from which the bounds list is retrieved. + \param[out] numBounds Number of bounds in returned list. + + \see PxShape PxBVH PxCooking::createBVH PxCooking::cookBVH + */ + static PxBounds3* getRigidActorShapeLocalBoundsList(const PxRigidActor& actor, PxU32& numBounds); + + /** + \brief Convenience function to create a PxBVH object from a PxRigidActor. + + The computed PxBVH can then be used in PxScene::addActor() or PxAggregate::addActor(). + After adding the actor & BVH to the scene/aggregate, release the PxBVH object by calling PxBVH::release(). + + \param[in] physics The physics object. The function will retrieve the insertion callback from it. + \param[in] actor The actor to compute a PxBVH for. + + \return The PxBVH for this actor. + + \see PxBVH PxScene::addActor PxAggregate::addActor + */ + static PxBVH* createBVHFromActor(PxPhysics& physics, const PxRigidActor& actor); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRigidBodyExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRigidBodyExt.h new file mode 100644 index 000000000..69f688c1d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxRigidBodyExt.h @@ -0,0 +1,444 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_RIGID_BODY_EXT_H +#define PX_RIGID_BODY_EXT_H + +#include "PxPhysXConfig.h" +#include "PxRigidBody.h" +#include "PxQueryReport.h" +#include "PxQueryFiltering.h" +#include "extensions/PxMassProperties.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxScene; +struct PxQueryCache; +class PxShape; + +/** +\brief utility functions for use with PxRigidBody and subclasses + +\see PxRigidBody PxRigidDynamic PxArticulationLink +*/ + +class PxRigidBodyExt +{ +public: + /** + \brief Computation of mass properties for a rigid body actor + + To simulate a dynamic rigid actor, the SDK needs a mass and an inertia tensor. + + This method offers functionality to compute the necessary mass and inertia properties based on the shapes declared in + the PxRigidBody descriptor and some additionally specified parameters. For each shape, the shape geometry, + the shape positioning within the actor and the specified shape density are used to compute the body's mass and + inertia properties. + +
    +
  • Shapes without PxShapeFlag::eSIMULATION_SHAPE set are ignored unless includeNonSimShapes is true.
  • +
  • Shapes with plane, triangle mesh or heightfield geometry and PxShapeFlag::eSIMULATION_SHAPE set are not allowed for PxRigidBody collision.
  • +
+ + This method will set the mass, center of mass, and inertia tensor + + if no collision shapes are found, the inertia tensor is set to (1,1,1) and the mass to 1 + + if massLocalPose is non-NULL, the rigid body's center of mass parameter will be set + to the user provided value (massLocalPose) and the inertia tensor will be resolved at that point. + + \note If all shapes of the actor have the same density then the overloaded method updateMassAndInertia() with a single density parameter can be used instead. + + \param[in,out] body The rigid body. + \param[in] shapeDensities The per shape densities. There must be one entry for each shape which has the PxShapeFlag::eSIMULATION_SHAPE set (or for all shapes if includeNonSimShapes is set to true). Other shapes are ignored. The density values must be greater than 0. + \param[in] shapeDensityCount The number of provided density values. + \param[in] massLocalPose The center of mass relative to the actor frame. If set to null then (0,0,0) is assumed. + \param[in] includeNonSimShapes True if all kind of shapes (PxShapeFlag::eSCENE_QUERY_SHAPE, PxShapeFlag::eTRIGGER_SHAPE) should be taken into account. + \return Boolean. True on success else false. + + \see PxRigidBody::setMassLocalPose PxRigidBody::setMassSpaceInertiaTensor PxRigidBody::setMass + */ + static bool updateMassAndInertia(PxRigidBody& body, const PxReal* shapeDensities, PxU32 shapeDensityCount, const PxVec3* massLocalPose = NULL, bool includeNonSimShapes = false); + + /** + \brief Computation of mass properties for a rigid body actor + + See previous method for details. + + \param[in,out] body The rigid body. + \param[in] density The density of the body. Used to compute the mass of the body. The density must be greater than 0. + \param[in] massLocalPose The center of mass relative to the actor frame. If set to null then (0,0,0) is assumed. + \param[in] includeNonSimShapes True if all kind of shapes (PxShapeFlag::eSCENE_QUERY_SHAPE, PxShapeFlag::eTRIGGER_SHAPE) should be taken into account. + \return Boolean. True on success else false. + + \see PxRigidBody::setMassLocalPose PxRigidBody::setMassSpaceInertiaTensor PxRigidBody::setMass + */ + static bool updateMassAndInertia(PxRigidBody& body, PxReal density, const PxVec3* massLocalPose = NULL, bool includeNonSimShapes = false); + + /** + \brief Computation of mass properties for a rigid body actor + + This method sets the mass, inertia and center of mass of a rigid body. The mass is set to the sum of all user-supplied + shape mass values, and the inertia and center of mass are computed according to the rigid body's shapes and the per shape mass input values. + + If no collision shapes are found, the inertia tensor is set to (1,1,1) + + \note If a single mass value should be used for the actor as a whole then the overloaded method setMassAndUpdateInertia() with a single mass parameter can be used instead. + + \see updateMassAndInertia for more details. + + \param[in,out] body The rigid body for which to set the mass and centre of mass local pose properties. + \param[in] shapeMasses The per shape mass values. There must be one entry for each shape which has the PxShapeFlag::eSIMULATION_SHAPE set. Other shapes are ignored. The mass values must be greater than 0. + \param[in] shapeMassCount The number of provided mass values. + \param[in] massLocalPose The center of mass relative to the actor frame. If set to null then (0,0,0) is assumed. + \param[in] includeNonSimShapes True if all kind of shapes (PxShapeFlag::eSCENE_QUERY_SHAPE, PxShapeFlag::eTRIGGER_SHAPE) should be taken into account. + \return Boolean. True on success else false. + + \see PxRigidBody::setCMassLocalPose PxRigidBody::setMassSpaceInertiaTensor PxRigidBody::setMass + */ + static bool setMassAndUpdateInertia(PxRigidBody& body, const PxReal* shapeMasses, PxU32 shapeMassCount, const PxVec3* massLocalPose = NULL, bool includeNonSimShapes = false); + + /** + \brief Computation of mass properties for a rigid body actor + + This method sets the mass, inertia and center of mass of a rigid body. The mass is set to the user-supplied + value, and the inertia and center of mass are computed according to the rigid body's shapes and the input mass. + + If no collision shapes are found, the inertia tensor is set to (1,1,1) + + \see updateMassAndInertia for more details. + + \param[in,out] body The rigid body for which to set the mass and centre of mass local pose properties. + \param[in] mass The mass of the body. Must be greater than 0. + \param[in] massLocalPose The center of mass relative to the actor frame. If set to null then (0,0,0) is assumed. + \param[in] includeNonSimShapes True if all kind of shapes (PxShapeFlag::eSCENE_QUERY_SHAPE, PxShapeFlag::eTRIGGER_SHAPE) should be taken into account. + \return Boolean. True on success else false. + + \see PxRigidBody::setCMassLocalPose PxRigidBody::setMassSpaceInertiaTensor PxRigidBody::setMass + */ + static bool setMassAndUpdateInertia(PxRigidBody& body, PxReal mass, const PxVec3* massLocalPose = NULL, bool includeNonSimShapes = false); + + /** + \brief Compute the mass, inertia tensor and center of mass from a list of shapes. + + \param[in] shapes The shapes to compute the mass properties from. + \param[in] shapeCount The number of provided shapes. + \return The mass properties from the combined shapes. + + \see PxRigidBody::setCMassLocalPose PxRigidBody::setMassSpaceInertiaTensor PxRigidBody::setMass + */ + static PxMassProperties computeMassPropertiesFromShapes(const PxShape* const* shapes, PxU32 shapeCount); + + /** + \brief Applies a force (or impulse) defined in the global coordinate frame, acting at a particular + point in global coordinates, to the actor. + + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + \note if this call is used to apply a force or impulse to an articulation link, only the link is updated, not the entire + articulation + + ::PxForceMode determines if the force is to be conventional or impulsive. Only eFORCE and eIMPULSE are supported, as the + force required to produce a given velocity change or acceleration is underdetermined given only the desired change at a + given point. + + Sleeping: This call wakes the actor if it is sleeping and the wakeup parameter is true (default). + + \param[in] body The rigid body to apply the force to. + \param[in] force Force/impulse to add, defined in the global frame. Range: force vector + \param[in] pos Position in the global frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #PxForceMode). + \param[in] wakeup Specify if the call should wake up the actor. + + \see PxForceMode + \see addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() + */ + static void addForceAtPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode = PxForceMode::eFORCE, bool wakeup = true); + + /** + \brief Applies a force (or impulse) defined in the global coordinate frame, acting at a particular + point in local coordinates, to the actor. + + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a + total external force on an object by calling this once every frame. + + \note if this call is used to apply a force or impulse to an articulation link, only the link is updated, not the entire + articulation + + ::PxForceMode determines if the force is to be conventional or impulsive. Only eFORCE and eIMPULSE are supported, as the + force required to produce a given velocity change or acceleration is underdetermined given only the desired change at a + given point. + + Sleeping: This call wakes the actor if it is sleeping and the wakeup parameter is true (default). + + \param[in] body The rigid body to apply the force to. + \param[in] force Force/impulse to add, defined in the global frame. Range: force vector + \param[in] pos Position in the local frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #PxForceMode). + \param[in] wakeup Specify if the call should wake up the actor. + + \see PxForceMode + \see addForceAtPos() addLocalForceAtPos() addLocalForceAtLocalPos() + */ + static void addForceAtLocalPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode = PxForceMode::eFORCE, bool wakeup = true); + + /** + \brief Applies a force (or impulse) defined in the actor local coordinate frame, acting at a + particular point in global coordinates, to the actor. + + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a + total external force on an object by calling this once every frame. + + \note if this call is used to apply a force or impulse to an articulation link, only the link is updated, not the entire + articulation + + ::PxForceMode determines if the force is to be conventional or impulsive. Only eFORCE and eIMPULSE are supported, as the + force required to produce a given velocity change or acceleration is underdetermined given only the desired change at a + given point. + + Sleeping: This call wakes the actor if it is sleeping and the wakeup parameter is true (default). + + \param[in] body The rigid body to apply the force to. + \param[in] force Force/impulse to add, defined in the local frame. Range: force vector + \param[in] pos Position in the global frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #PxForceMode). + \param[in] wakeup Specify if the call should wake up the actor. + + \see PxForceMode + \see addForceAtPos() addForceAtLocalPos() addLocalForceAtLocalPos() + */ + static void addLocalForceAtPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode = PxForceMode::eFORCE, bool wakeup = true); + + /** + \brief Applies a force (or impulse) defined in the actor local coordinate frame, acting at a + particular point in local coordinates, to the actor. + + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a + total external force on an object by calling this once every frame. + + \note if this call is used to apply a force or impulse to an articulation link, only the link is updated, not the entire + articulation + + ::PxForceMode determines if the force is to be conventional or impulsive. Only eFORCE and eIMPULSE are supported, as the + force required to produce a given velocity change or acceleration is underdetermined given only the desired change at a + given point. + + Sleeping: This call wakes the actor if it is sleeping and the wakeup parameter is true (default). + + \param[in] body The rigid body to apply the force to. + \param[in] force Force/impulse to add, defined in the local frame. Range: force vector + \param[in] pos Position in the local frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #PxForceMode). + \param[in] wakeup Specify if the call should wake up the actor. + + \see PxForceMode + \see addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() + */ + static void addLocalForceAtLocalPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode = PxForceMode::eFORCE, bool wakeup = true); + + /** + \brief Computes the velocity of a point given in world coordinates if it were attached to the + specified body and moving with it. + + \param[in] body The rigid body the point is attached to. + \param[in] pos Position we wish to determine the velocity for, defined in the global frame. Range: position vector + \return The velocity of point in the global frame. + + \see getLocalPointVelocity() + */ + static PxVec3 getVelocityAtPos(const PxRigidBody& body, const PxVec3& pos); + + /** + \brief Computes the velocity of a point given in local coordinates if it were attached to the + specified body and moving with it. + + \param[in] body The rigid body the point is attached to. + \param[in] pos Position we wish to determine the velocity for, defined in the local frame. Range: position vector + \return The velocity of point in the local frame. + + \see getLocalPointVelocity() + */ + static PxVec3 getLocalVelocityAtLocalPos(const PxRigidBody& body, const PxVec3& pos); + + /** + \brief Computes the velocity of a point (offset from the origin of the body) given in world coordinates if it were attached to the + specified body and moving with it. + + \param[in] body The rigid body the point is attached to. + \param[in] pos Position (offset from the origin of the body) we wish to determine the velocity for, defined in the global frame. Range: position vector + \return The velocity of point (offset from the origin of the body) in the global frame. + + \see getLocalPointVelocity() + */ + static PxVec3 getVelocityAtOffset(const PxRigidBody& body, const PxVec3& pos); + + /** + \brief Compute the change to linear and angular velocity that would occur if an impulsive force and torque were to be applied to a specified rigid body. + + The rigid body is left unaffected unless a subsequent independent call is executed that actually applies the computed changes to velocity and angular velocity. + + \note if this call is used to determine the velocity delta for an articulation link, only the mass properties of the link are taken into account. + + \see PxRigidBody::getLinearVelocity, PxRigidBody::setLinearVelocity, PxRigidBody::getAngularVelocity, PxRigidBody::setAngularVelocity + + \param[in] body The body under consideration. + \param[in] impulsiveForce The impulsive force that would be applied to the specified rigid body. + \param[in] impulsiveTorque The impulsive torque that would be applied to the specified rigid body. + \param[out] deltaLinearVelocity The change in linear velocity that would arise if impulsiveForce was to be applied to the specified rigid body. + \param[out] deltaAngularVelocity The change in angular velocity that would arise if impulsiveTorque was to be applied to the specified rigid body. + */ + static void computeVelocityDeltaFromImpulse(const PxRigidBody& body, const PxVec3& impulsiveForce, const PxVec3& impulsiveTorque, PxVec3& deltaLinearVelocity, PxVec3& deltaAngularVelocity); + + /** + \brief Computes the linear and angular velocity change vectors for a given impulse at a world space position taking a mass and inertia scale into account + + This function is useful for extracting the respective linear and angular velocity changes from a contact or joint when the mass/inertia ratios have been adjusted. + + \note if this call is used to determine the velocity delta for an articulation link, only the mass properties of the link are taken into account. + + \param[in] body The rigid body + \param[in] globalPose The body's world space transform + \param[in] point The point in world space where the impulse is applied + \param[in] impulse The impulse vector in world space + \param[in] invMassScale The inverse mass scale + \param[in] invInertiaScale The inverse inertia scale + \param[out] deltaLinearVelocity The linear velocity change + \param[out] deltaAngularVelocity The angular velocity change + */ + static void computeVelocityDeltaFromImpulse(const PxRigidBody& body, const PxTransform& globalPose, const PxVec3& point, const PxVec3& impulse, const PxReal invMassScale, + const PxReal invInertiaScale, PxVec3& deltaLinearVelocity, PxVec3& deltaAngularVelocity); + + /** + \brief Computes the linear and angular impulse vectors for a given impulse at a world space position taking a mass and inertia scale into account + + This function is useful for extracting the respective linear and angular impulses from a contact or joint when the mass/inertia ratios have been adjusted. + + \param[in] body The rigid body + \param[in] globalPose The body's world space transform + \param[in] point The point in world space where the impulse is applied + \param[in] impulse The impulse vector in world space + \param[in] invMassScale The inverse mass scale + \param[in] invInertiaScale The inverse inertia scale + \param[out] linearImpulse The linear impulse + \param[out] angularImpulse The angular impulse + */ + static void computeLinearAngularImpulse(const PxRigidBody& body, const PxTransform& globalPose, const PxVec3& point, const PxVec3& impulse, const PxReal invMassScale, + const PxReal invInertiaScale, PxVec3& linearImpulse, PxVec3& angularImpulse); + + /** + \brief Performs a linear sweep through space with the body's geometry objects. + + \note Supported geometries are: box, sphere, capsule, convex. Other geometry types will be ignored. + \note If eTOUCH is returned from the filter callback, it will trigger an error and the hit will be discarded. + + The function sweeps all shapes attached to a given rigid body through space and reports the nearest + object in the scene which intersects any of of the shapes swept paths. + Information about the closest intersection is written to a #PxSweepHit structure. + + \param[in] body The rigid body to sweep. + \param[in] scene The scene object to process the query. + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be larger than 0. + \param[in] outputFlags Specifies which properties should be written to the hit information. + \param[out] closestHit Closest hit result. + \param[out] shapeIndex Index of the body shape that caused the closest hit. + \param[in] filterData If any word in filterData.data is non-zero then filterData.data will be used for filtering, + otherwise shape->getQueryFilterData() will be used instead. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Ray is tested against cached shape first then against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + + \return True if a blocking hit was found. + + \see PxScene PxQueryFlags PxFilterData PxSweepHit + */ + static bool linearSweepSingle( + PxRigidBody& body, PxScene& scene, const PxVec3& unitDir, const PxReal distance, + PxHitFlags outputFlags, + PxSweepHit& closestHit, PxU32& shapeIndex, + const PxQueryFilterData& filterData = PxQueryFilterData(), + PxQueryFilterCallback* filterCall = NULL, + const PxQueryCache* cache = NULL, + const PxReal inflation=0.0f); + + /** + \brief Performs a linear sweep through space with the body's geometry objects, returning all overlaps. + + \note Supported geometries are: box, sphere, capsule, convex. Other geometry types will be ignored. + + This function sweeps all shapes attached to a given rigid body through space and reports all + objects in the scene that intersect any of the shapes' swept paths until there are no more objects to report + or a blocking hit is encountered. + + \param[in] body The rigid body to sweep. + \param[in] scene The scene object to process the query. + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be larger than 0. + \param[in] outputFlags Specifies which properties should be written to the hit information. + \param[out] touchHitBuffer Raycast hit information buffer. If the buffer overflows, an arbitrary subset of touch hits + is returned (typically the query should be restarted with a larger buffer). + \param[out] touchHitShapeIndices After the query is completed, touchHitShapeIndices[i] will contain the body index that caused the hit stored in hitBuffer[i] + \param[in] touchHitBufferSize Size of both touch hit buffers in elements. + \param[out] block Closest blocking hit is returned via this reference. + \param[out] blockingShapeIndex Set to -1 if if a blocking hit was not found, otherwise set to closest blocking hit shape index. The touching hits are reported separately in hitBuffer. + \param[out] overflow Set to true if touchHitBuffer didn't have enough space for all results. Touch hits will be incomplete if overflow occurred. Possible solution is to restart the query with a larger buffer. + \param[in] filterData If any word in filterData.data is non-zero then filterData.data will be used for filtering, + otherwise shape->getQueryFilterData() will be used instead. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Ray is tested against cached shape first then against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + + \return the number of touching hits. If overflow is set to true, the results are incomplete. In case of overflow there are also no guarantees that all touching hits returned are closer than the blocking hit. + + \see PxScene PxQueryFlags PxFilterData PxSweepHit + */ + static PxU32 linearSweepMultiple( + PxRigidBody& body, PxScene& scene, const PxVec3& unitDir, const PxReal distance, + PxHitFlags outputFlags, + PxSweepHit* touchHitBuffer, PxU32* touchHitShapeIndices, PxU32 touchHitBufferSize, + PxSweepHit& block, PxI32& blockingShapeIndex, bool& overflow, + const PxQueryFilterData& filterData = PxQueryFilterData(), + PxQueryFilterCallback* filterCall = NULL, + const PxQueryCache* cache = NULL, const PxReal inflation = 0.0f); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSamplingExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSamplingExt.h new file mode 100644 index 000000000..e1b456d82 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSamplingExt.h @@ -0,0 +1,183 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SAMPLING_EXT_H +#define PX_SAMPLING_EXT_H + +#include "foundation/PxTransform.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxArray.h" +#include "geometry/PxGeometry.h" +#include "foundation/PxUserAllocated.h" +#include "geometry/PxSimpleTriangleMesh.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief utility functions to sample vertices on or inside a triangle mesh or other geometries +*/ +class PxSamplingExt +{ +public: + /** Computes samples on a triangle mesh's surface that are not closer to each other than a given distance. Optionally the mesh's interior can be filled with samples as well. + + \param[in] mesh The triangle mesh + \param[in] r The closest distance two surface samples are allowed to have + \param[out] result Equally distributed samples on and if specified inside the triangle mesh + \param[in] rVolume The average distance of samples inside the mesh. If set to zero, samples will only be placed on the mesh's surface + \param[out] triangleIds Optional output containing the index of the triangle for all samples on the mesh's surface. The array will contain less entries than output vertices if volume samples are active since volume samples are not on the surface. + \param[out] barycentricCoordinates Optional output containing the barycentric coordinates for all samples on the mesh's surface. The array will contain less entries than output vertices if volume samples are active since volume samples are not on the surface. + \param[in] axisAlignedBox A box that limits the space where samples can get created + \param[in] boxOrientation The orientation of the box that limits the space where samples can get created + \param[in] maxNumSamples If larger than zero, the sampler will stop when the sample count reaches maxNumSamples + \param[in] numSampleAttemptsAroundPoint Number of repetitions the underlying algorithm performs to find a new valid sample that matches all criteria like minimal distance to existing samples etc. + \return Returns true if the sampling was successful and false if there was a problem. Usually an internal overflow is the problem for very big meshes or very small sampling radii. + */ + static bool poissonSample(const PxSimpleTriangleMesh& mesh, PxReal r, PxArray& result, PxReal rVolume = 0.0f, PxArray* triangleIds = NULL, PxArray* barycentricCoordinates = NULL, + const PxBounds3* axisAlignedBox = NULL, const PxQuat* boxOrientation = NULL, PxU32 maxNumSamples = 0, PxU32 numSampleAttemptsAroundPoint = 30); + + /** Computes samples on a geometry's surface that are not closer to each other than a given distance. + + \param[in] geometry The geometry that defines the surface on which the samples get created + \param[in] transform The geometry's global pose + \param[in] worldBounds The geometry's bounding box + \param[in] r The closest distance two surface samples are allowed to have + \param[out] result Equally distributed samples on and if specified inside the triangle mesh + \param[in] rVolume The average distance of samples inside the mesh. If set to zero, samples will only be placed on the mesh's surface + \param[in] axisAlignedBox A box that limits the space where samples can get created + \param[in] boxOrientation The orientation of the box that limits the space where samples can get created + \param[in] maxNumSamples If larger than zero, the sampler will stop when the sample count reaches maxNumSamples + \param[in] numSampleAttemptsAroundPoint Number of repetitions the underlying algorithm performs to find a new valid sample that matches all criteria like minimal distance to existing samples etc. + \return Returns true if the sampling was successful and false if there was a problem. Usually an internal overflow is the problem for very big meshes or very small sampling radii. + */ + static bool poissonSample(const PxGeometry& geometry, const PxTransform& transform, const PxBounds3& worldBounds, PxReal r, PxArray& result, PxReal rVolume = 0.0f, + const PxBounds3* axisAlignedBox = NULL, const PxQuat* boxOrientation = NULL, PxU32 maxNumSamples = 0, PxU32 numSampleAttemptsAroundPoint = 30); +}; + +/** +\brief Sampler to generate Poisson Samples locally on a triangle mesh or a shape. For every local addition of new samples, an individual sampling density can be used. +*/ +class PxPoissonSampler : public PxUserAllocated +{ +public: + /** Sets the sampling radius + \param[in] samplingRadius The closest distance two surface samples are allowed to have. Changing the sampling radius is a bit an expensive operation. + \return Returns true if the sampling was successful and false if there was a problem. Usually an internal overflow is the problem for very big meshes or very small sampling radii. + */ + virtual bool setSamplingRadius(PxReal samplingRadius) = 0; + + /** Adds samples + \param[in] samples The samples to add. Adding samples is a bit an expensive operation. + */ + virtual void addSamples(const PxArray& samples) = 0; + + /** Adds samples + \param[in] samples The samples to remove. Removing samples is a bit an expensive operation. + \return Returns the number of removed samples. If some samples were not found, then the number of actually removed samples will be smaller than the number of samples requested to remove + */ + virtual PxU32 removeSamples(const PxArray& samples) = 0; + + /** Adds new Poisson Samples inside the sphere specified + \param[in] sphereCenter The sphere's center. Used to define the region where new samples get added. + \param[in] sphereRadius The sphere's radius. Used to define the region where new samples get added. + \param[in] createVolumeSamples If set to true, samples will also get generated inside of the mesh, not just on its surface. + */ + virtual void addSamplesInSphere(const PxVec3& sphereCenter, PxReal sphereRadius, bool createVolumeSamples = false) = 0; + + /** Adds new Poisson Samples inside the box specified + \param[in] axisAlignedBox The axis aligned bounding box. Used to define the region where new samples get added. + \param[in] boxOrientation The orientation making an oriented bounding box out of the axis aligned one. Used to define the region where new samples get added. + \param[in] createVolumeSamples If set to true, samples will also get generated inside of the mesh, not just on its surface. + */ + virtual void addSamplesInBox(const PxBounds3& axisAlignedBox, const PxQuat& boxOrientation, bool createVolumeSamples = false) = 0; + + /** Gets the Poisson Samples + \return Returns the generated Poisson Samples + */ + virtual const PxArray& getSamples() const = 0; + + virtual ~PxPoissonSampler() { } +}; + + +/** Creates a shape sampler +\param[in] geometry The shape that defines the surface on which the samples get created +\param[in] transform The shape's global pose +\param[in] worldBounds The shapes bounding box +\param[in] initialSamplingRadius The closest distance two surface samples are allowed to have +\param[in] numSampleAttemptsAroundPoint Number of repetitions the underlying algorithm performs to find a new valid sample that matches all criteria like minimal distance to existing samples etc. +\return Returns the sampler +*/ +PxPoissonSampler* PxCreateShapeSampler(const PxGeometry& geometry, const PxTransform& transform, const PxBounds3& worldBounds, PxReal initialSamplingRadius, PxI32 numSampleAttemptsAroundPoint = 30); + + +/** +\brief Sampler to generate Poisson Samples on a triangle mesh. +*/ +class PxTriangleMeshPoissonSampler : public virtual PxPoissonSampler +{ +public: + /** Gets the Poisson Samples' triangle indices + \return Returns the generated Poisson Samples' triangle indices + */ + virtual const PxArray& getSampleTriangleIds() const = 0; + + /** Gets the Poisson Samples' barycentric coordinates + \return Returns the generated Poisson Samples' barycentric coordinates + */ + virtual const PxArray& getSampleBarycentrics() const = 0; + + /** Checks whether a point is inside the triangle mesh + \return Returns true if the point is inside the triangle mesh + */ + virtual bool isPointInTriangleMesh(const PxVec3& p) = 0; + + virtual ~PxTriangleMeshPoissonSampler() { } +}; + + +/** Creates a triangle mesh sampler +\param[in] triangles The triangle indices of the mesh +\param[in] numTriangles The total number of triangles +\param[in] vertices The vertices of the mesh +\param[in] numVertices The total number of vertices +\param[in] initialSamplingRadius The closest distance two surface samples are allowed to have +\param[in] numSampleAttemptsAroundPoint Number of repetitions the underlying algorithm performs to find a new valid sample that matches all criteria like minimal distance to existing samples etc. +\return Returns the sampler +*/ +PxTriangleMeshPoissonSampler* PxCreateTriangleMeshSampler(const PxU32* triangles, PxU32 numTriangles, const PxVec3* vertices, PxU32 numVertices, PxReal initialSamplingRadius, PxI32 numSampleAttemptsAroundPoint = 30); + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSceneQueryExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSceneQueryExt.h new file mode 100644 index 000000000..442e8028e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSceneQueryExt.h @@ -0,0 +1,504 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SCENE_QUERY_EXT_H +#define PX_SCENE_QUERY_EXT_H + +#include "PxPhysXConfig.h" + +#include "PxScene.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +// These types have been deprecated (removed) in PhysX 3.4. We typedef them to the new types here for easy migration from 3.3 to 3.4. +// We will not remove these aliases for convenience. +typedef PxQueryHit PxSceneQueryHit; +typedef PxQueryFilterData PxSceneQueryFilterData; +typedef PxQueryFilterCallback PxSceneQueryFilterCallback; +typedef PxQueryCache PxSceneQueryCache; +typedef PxHitFlag PxSceneQueryFlag; +typedef PxHitFlags PxSceneQueryFlags; + +/** +\brief Utility functions for use with PxScene, related to scene queries. + +Some of these functions have been deprecated (removed) in PhysX 3.4. We re-implement them here for easy migration from 3.3 to 3.4. +We will not remove them for convenience. +*/ +class PxSceneQueryExt +{ +public: + + /** + \brief Raycast returning any blocking hit, not necessarily the closest. + + Returns whether any rigid actor is hit along the ray. + + \note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in article SceneQuery. User can ignore such objects by using one of the provided filter mechanisms. + + \param[in] scene The scene + \param[in] origin Origin of the ray. + \param[in] unitDir Normalized direction of the ray. + \param[in] distance Length of the ray. Needs to be larger than 0. + \param[out] hit Raycast hit information. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Ray is tested against cached shape first. If no hit is found the ray gets queried against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \return True if a blocking hit was found. + + \see PxSceneQueryFilterData PxSceneQueryFilterCallback PxSceneQueryCache PxSceneQueryHit + */ + static bool raycastAny( const PxScene& scene, + const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, + PxSceneQueryHit& hit, const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL, const PxSceneQueryCache* cache = NULL); + + /** + \brief Raycast returning a single result. + + Returns the first rigid actor that is hit along the ray. Data for a blocking hit will be returned as specified by the outputFlags field. Touching hits will be ignored. + + \note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in article SceneQuery. User can ignore such objects by using one of the provided filter mechanisms. + + \param[in] scene The scene + \param[in] origin Origin of the ray. + \param[in] unitDir Normalized direction of the ray. + \param[in] distance Length of the ray. Needs to be larger than 0. + \param[in] outputFlags Specifies which properties should be written to the hit information + \param[out] hit Raycast hit information. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Ray is tested against cached shape first then against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \return True if a blocking hit was found. + + \see PxSceneQueryFlags PxRaycastHit PxSceneQueryFilterData PxSceneQueryFilterCallback PxSceneQueryCache + */ + static bool raycastSingle( const PxScene& scene, + const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, + PxSceneQueryFlags outputFlags, PxRaycastHit& hit, + const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL, const PxSceneQueryCache* cache = NULL); + + /** + \brief Raycast returning multiple results. + + Find all rigid actors that get hit along the ray. Each result contains data as specified by the outputFlags field. + + \note Touching hits are not ordered. + + \note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in article SceneQuery. User can ignore such objects by using one of the provided filter mechanisms. + + \param[in] scene The scene + \param[in] origin Origin of the ray. + \param[in] unitDir Normalized direction of the ray. + \param[in] distance Length of the ray. Needs to be larger than 0. + \param[in] outputFlags Specifies which properties should be written to the hit information + \param[out] hitBuffer Raycast hit information buffer. If the buffer overflows, the blocking hit is returned as the last entry together with an arbitrary subset + of the nearer touching hits (typically the query should be restarted with a larger buffer). + \param[in] hitBufferSize Size of the hit buffer. + \param[out] blockingHit True if a blocking hit was found. If found, it is the last in the buffer, preceded by any touching hits which are closer. Otherwise the touching hits are listed. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to be touching. + \param[in] cache Cached hit shape (optional). Ray is tested against cached shape first then against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \return Number of hits in the buffer, or -1 if the buffer overflowed. + + \see PxSceneQueryFlags PxRaycastHit PxSceneQueryFilterData PxSceneQueryFilterCallback PxSceneQueryCache + */ + static PxI32 raycastMultiple( const PxScene& scene, + const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, + PxSceneQueryFlags outputFlags, + PxRaycastHit* hitBuffer, PxU32 hitBufferSize, bool& blockingHit, + const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL, const PxSceneQueryCache* cache = NULL); + + /** + \brief Sweep returning any blocking hit, not necessarily the closest. + + Returns whether any rigid actor is hit along the sweep path. + + \note If a shape from the scene is already overlapping with the query shape in its starting position, behavior is controlled by the PxSceneQueryFlag::eINITIAL_OVERLAP flag. + + \param[in] scene The scene + \param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex). + \param[in] pose Pose of the sweep object. + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be larger than 0. Will be clamped to PX_MAX_SWEEP_DISTANCE. + \param[in] queryFlags Combination of PxSceneQueryFlag defining the query behavior + \param[out] hit Sweep hit information. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Sweep is performed against cached shape first. If no hit is found the sweep gets queried against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + \return True if a blocking hit was found. + + \see PxSceneQueryFilterData PxSceneQueryFilterCallback PxSceneQueryHit PxSceneQueryCache + */ + static bool sweepAny( const PxScene& scene, + const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, + PxSceneQueryFlags queryFlags, + PxSceneQueryHit& hit, + const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL, + const PxSceneQueryCache* cache = NULL, + PxReal inflation = 0.0f); + + /** + \brief Sweep returning a single result. + + Returns the first rigid actor that is hit along the ray. Data for a blocking hit will be returned as specified by the outputFlags field. Touching hits will be ignored. + + \note If a shape from the scene is already overlapping with the query shape in its starting position, behavior is controlled by the PxSceneQueryFlag::eINITIAL_OVERLAP flag. + + \param[in] scene The scene + \param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex). + \param[in] pose Pose of the sweep object. + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be larger than 0. Will be clamped to PX_MAX_SWEEP_DISTANCE. + \param[in] outputFlags Specifies which properties should be written to the hit information. + \param[out] hit Sweep hit information. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to be blocking. + \param[in] cache Cached hit shape (optional). Sweep is performed against cached shape first then against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + \return True if a blocking hit was found. + + \see PxSceneQueryFlags PxSweepHit PxSceneQueryFilterData PxSceneQueryFilterCallback PxSceneQueryCache + */ + static bool sweepSingle(const PxScene& scene, + const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, + PxSceneQueryFlags outputFlags, + PxSweepHit& hit, + const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL, + const PxSceneQueryCache* cache = NULL, + PxReal inflation=0.0f); + + /** + \brief Sweep returning multiple results. + + Find all rigid actors that get hit along the sweep. Each result contains data as specified by the outputFlags field. + + \note Touching hits are not ordered. + + \note If a shape from the scene is already overlapping with the query shape in its starting position, behavior is controlled by the PxSceneQueryFlag::eINITIAL_OVERLAP flag. + + \param[in] scene The scene + \param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex). + \param[in] pose Pose of the sweep object. + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be larger than 0. Will be clamped to PX_MAX_SWEEP_DISTANCE. + \param[in] outputFlags Specifies which properties should be written to the hit information. + \param[out] hitBuffer Sweep hit information buffer. If the buffer overflows, the blocking hit is returned as the last entry together with an arbitrary subset + of the nearer touching hits (typically the query should be restarted with a larger buffer). + \param[in] hitBufferSize Size of the hit buffer. + \param[out] blockingHit True if a blocking hit was found. If found, it is the last in the buffer, preceded by any touching hits which are closer. Otherwise the touching hits are listed. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to be touching. + \param[in] cache Cached hit shape (optional). Sweep is performed against cached shape first then against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + \return Number of hits in the buffer, or -1 if the buffer overflowed. + + \see PxSceneQueryFlags PxSweepHit PxSceneQueryFilterData PxSceneQueryFilterCallback PxSceneQueryCache + */ + static PxI32 sweepMultiple( const PxScene& scene, + const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, + PxSceneQueryFlags outputFlags, PxSweepHit* hitBuffer, PxU32 hitBufferSize, bool& blockingHit, + const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL, const PxSceneQueryCache* cache = NULL, + PxReal inflation = 0.0f); + + /** + \brief Test overlap between a geometry and objects in the scene. + + \note Filtering: Overlap tests do not distinguish between touching and blocking hit types. Both get written to the hit buffer. + + \note PxHitFlag::eMESH_MULTIPLE and PxHitFlag::eMESH_BOTH_SIDES have no effect in this case + + \param[in] scene The scene + \param[in] geometry Geometry of object to check for overlap (supported types are: box, sphere, capsule, convex). + \param[in] pose Pose of the object. + \param[out] hitBuffer Buffer to store the overlapping objects to. If the buffer overflows, an arbitrary subset of overlapping objects is stored (typically the query should be restarted with a larger buffer). + \param[in] hitBufferSize Size of the hit buffer. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to overlap. + \return Number of hits in the buffer, or -1 if the buffer overflowed. + + \see PxSceneQueryFlags PxSceneQueryFilterData PxSceneQueryFilterCallback + */ + static PxI32 overlapMultiple( const PxScene& scene, + const PxGeometry& geometry, const PxTransform& pose, + PxOverlapHit* hitBuffer, PxU32 hitBufferSize, + const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL); + + /** + \brief Test returning, for a given geometry, any overlapping object in the scene. + + \note Filtering: Overlap tests do not distinguish between touching and blocking hit types. Both trigger a hit. + + \note PxHitFlag::eMESH_MULTIPLE and PxHitFlag::eMESH_BOTH_SIDES have no effect in this case + + \param[in] scene The scene + \param[in] geometry Geometry of object to check for overlap (supported types are: box, sphere, capsule, convex). + \param[in] pose Pose of the object. + \param[out] hit Pointer to store the overlapping object to. + \param[in] filterData Filtering data and simple logic. + \param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxHitFlag flags are set. If NULL, all hits are assumed to overlap. + \return True if an overlap was found. + + \see PxSceneQueryFlags PxSceneQueryFilterData PxSceneQueryFilterCallback + */ + static bool overlapAny( const PxScene& scene, + const PxGeometry& geometry, const PxTransform& pose, + PxOverlapHit& hit, + const PxSceneQueryFilterData& filterData = PxSceneQueryFilterData(), + PxSceneQueryFilterCallback* filterCall = NULL); +}; + +struct PxBatchQueryStatus +{ + enum Enum + { + /** + \brief This is the initial state before a query starts. + */ + ePENDING = 0, + + /** + \brief The query is finished; results have been written into the result and hit buffers. + */ + eSUCCESS, + + /** + \brief The query results were incomplete due to touch hit buffer overflow. Blocking hit is still correct. + */ + eOVERFLOW + }; + + static PX_FORCE_INLINE Enum getStatus(const PxRaycastBuffer& r) + { + return (0xffffffff == r.nbTouches) ? ePENDING : (0xffffffff == r.maxNbTouches ? eOVERFLOW : eSUCCESS); + } + static PX_FORCE_INLINE Enum getStatus(const PxSweepBuffer& r) + { + return (0xffffffff == r.nbTouches) ? ePENDING : (0xffffffff == r.maxNbTouches ? eOVERFLOW : eSUCCESS); + } + static PX_FORCE_INLINE Enum getStatus(const PxOverlapBuffer& r) + { + return (0xffffffff == r.nbTouches) ? ePENDING : (0xffffffff == r.maxNbTouches ? eOVERFLOW : eSUCCESS); + } +}; + +class PxBatchQueryExt +{ +public: + + virtual void release() = 0; + + /** + \brief Performs a raycast against objects in the scene. + + \note Touching hits are not ordered. + \note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in article SceneQuery. User can ignore such objects by using one of the provided filter mechanisms. + + \param[in] origin Origin of the ray. + \param[in] unitDir Normalized direction of the ray. + \param[in] distance Length of the ray. Needs to be larger than 0. + \param[in] maxNbTouches Maximum number of hits to record in the touch buffer for this query. Default=0 reports a single blocking hit. If maxTouchHits is set to 0 all hits are treated as blocking by default. + \param[in] hitFlags Specifies which properties per hit should be computed and returned in hit array and blocking hit. + \param[in] filterData Filtering data passed to the filter shader. See #PxQueryFilterData #PxQueryFilterCallback + \param[in] cache Cached hit shape (optional). Query is tested against cached shape first. If no hit is found the ray gets queried against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + + \note This query call writes to a list associated with the query object and is NOT thread safe (for performance reasons there is no lock + and overlapping writes from different threads may result in undefined behavior). + + \return Returns a PxRaycastBuffer pointer that will store the result of the query after execute() is completed. + This will point either to an element of the buffer allocated on construction or to a user buffer passed to the constructor. + \see PxCreateBatchQueryExt + + \see PxQueryFilterData PxQueryFilterCallback PxRaycastHit PxScene::raycast + */ + virtual PxRaycastBuffer* raycast( + const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, + const PxU16 maxNbTouches = 0, + PxHitFlags hitFlags = PxHitFlags(PxHitFlag::eDEFAULT), + const PxQueryFilterData& filterData = PxQueryFilterData(), + const PxQueryCache* cache = NULL) = 0; + + /** + \brief Performs a sweep test against objects in the scene. + + \note Touching hits are not ordered. + \note If a shape from the scene is already overlapping with the query shape in its starting position, + the hit is returned unless eASSUME_NO_INITIAL_OVERLAP was specified. + + \param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex). + \param[in] pose Pose of the sweep object. + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be larger than 0. Will be clamped to PX_MAX_SWEEP_DISTANCE. + \param[in] maxNbTouches Maximum number of hits to record in the touch buffer for this query. Default=0 reports a single blocking hit. If maxTouchHits is set to 0 all hits are treated as blocking by default. + \param[in] hitFlags Specifies which properties per hit should be computed and returned in hit array and blocking hit. + \param[in] filterData Filtering data and simple logic. See #PxQueryFilterData #PxQueryFilterCallback + \param[in] cache Cached hit shape (optional). Query is tested against cached shape first. If no hit is found the ray gets queried against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + Note: ePRECISE_SWEEP doesn't support inflation. Therefore the sweep will be performed with zero inflation. + + \note This query call writes to a list associated with the query object and is NOT thread safe (for performance reasons there is no lock + and overlapping writes from different threads may result in undefined behavior). + + \return Returns a PxSweepBuffer pointer that will store the result of the query after execute() is completed. + This will point either to an element of the buffer allocated on construction or to a user buffer passed to the constructor. + \see PxCreateBatchQueryExt + + \see PxHitFlags PxQueryFilterData PxBatchQueryPreFilterShader PxBatchQueryPostFilterShader PxSweepHit + */ + virtual PxSweepBuffer* sweep( + const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, + const PxU16 maxNbTouches = 0, + PxHitFlags hitFlags = PxHitFlags(PxHitFlag::eDEFAULT), + const PxQueryFilterData& filterData = PxQueryFilterData(), + const PxQueryCache* cache = NULL, + const PxReal inflation = 0.0f) = 0; + + + /** + \brief Performs an overlap test of a given geometry against objects in the scene. + + \note Filtering: returning eBLOCK from user filter for overlap queries will cause a warning (see #PxQueryHitType). + + \param[in] geometry Geometry of object to check for overlap (supported types are: box, sphere, capsule, convex). + \param[in] pose Pose of the object. + \param[in] maxNbTouches Maximum number of hits to record in the touch buffer for this query. Default=0 reports a single blocking hit. If maxTouchHits is set to 0 all hits are treated as blocking by default. + \param[in] filterData Filtering data and simple logic. See #PxQueryFilterData #PxQueryFilterCallback + \param[in] cache Cached hit shape (optional). Query is tested against cached shape first. If no hit is found the ray gets queried against the scene. + Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit. + Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking. + + \note eBLOCK should not be returned from user filters for overlap(). Doing so will result in undefined behavior, and a warning will be issued. + \note If the PxQueryFlag::eNO_BLOCK flag is set, the eBLOCK will instead be automatically converted to an eTOUCH and the warning suppressed. + \note This query call writes to a list associated with the query object and is NOT thread safe (for performance reasons there is no lock + and overlapping writes from different threads may result in undefined behavior). + + \return Returns a PxOverlapBuffer pointer that will store the result of the query after execute() is completed. + This will point either to an element of the buffer allocated on construction or to a user buffer passed to the constructor. + \see PxCreateBatchQueryExt + + \see PxQueryFilterData PxQueryFilterCallback + */ + virtual PxOverlapBuffer* overlap( + const PxGeometry& geometry, const PxTransform& pose, + PxU16 maxNbTouches = 0, + const PxQueryFilterData& filterData = PxQueryFilterData(), + const PxQueryCache* cache = NULL) = 0; + + virtual void execute() = 0; + +protected: + + virtual ~PxBatchQueryExt() {} +}; + +/** +\brief Create a PxBatchQueryExt without the need for pre-allocated result or touch buffers. + +\param[in] scene Queries will be performed against objects in the specified PxScene +\param[in] queryFilterCallback Filtering for all queries is performed using queryFilterCallback. A null pointer results in all shapes being considered. + +\param[in] maxNbRaycasts A result buffer will be allocated that is large enough to accommodate maxNbRaycasts calls to PxBatchQueryExt::raycast() +\param[in] maxNbRaycastTouches A touch buffer will be allocated that is large enough to accommodate maxNbRaycastTouches touches for all raycasts in the batch. + +\param[in] maxNbSweeps A result buffer will be allocated that is large enough to accommodate maxNbSweeps calls to PxBatchQueryExt::sweep() +\param[in] maxNbSweepTouches A touch buffer will be allocated that is large enough to accommodate maxNbSweepTouches touches for all sweeps in the batch. + +\param[in] maxNbOverlaps A result buffer will be allocated that is large enough to accommodate maxNbOverlaps calls to PxBatchQueryExt::overlap() +\param[in] maxNbOverlapTouches A touch buffer will be allocated that is large enough to accommodate maxNbOverlapTouches touches for all overlaps in the batch. + +\return Returns a PxBatchQueryExt instance. A NULL pointer will be returned if the subsequent allocations fail or if any of the arguments are illegal. +In the event that a NULL pointer is returned a corresponding error will be issued to the error stream. +*/ +PxBatchQueryExt* PxCreateBatchQueryExt( + const PxScene& scene, PxQueryFilterCallback* queryFilterCallback, + const PxU32 maxNbRaycasts, const PxU32 maxNbRaycastTouches, + const PxU32 maxNbSweeps, const PxU32 maxNbSweepTouches, + const PxU32 maxNbOverlaps, const PxU32 maxNbOverlapTouches); + + +/** +\brief Create a PxBatchQueryExt with user-supplied result and touch buffers. + +\param[in] scene Queries will be performed against objects in the specified PxScene +\param[in] queryFilterCallback Filtering for all queries is performed using queryFilterCallback. A null pointer results in all shapes being considered. + +\param[in] raycastBuffers This is the array that will be used to store the results of each raycast in a batch. +\param[in] maxNbRaycasts This is the length of the raycastBuffers array. +\param[in] raycastTouches This is the array that will be used to store the touches generated by all raycasts in a batch. +\param[in] maxNbRaycastTouches This is the length of the raycastTouches array. + +\param[in] sweepBuffers This is the array that will be used to store the results of each sweep in a batch. +\param[in] maxNbSweeps This is the length of the sweepBuffers array. +\param[in] sweepTouches This is the array that will be used to store the touches generated by all sweeps in a batch. +\param[in] maxNbSweepTouches This is the length of the sweepTouches array. + +\param[in] overlapBuffers This is the array that will be used to store the results of each overlap in a batch. +\param[in] maxNbOverlaps This is the length of the overlapBuffers array. +\param[in] overlapTouches This is the array that will be used to store the touches generated by all overlaps in a batch. +\param[in] maxNbOverlapTouches This is the length of the overlapTouches array. + +\return Returns a PxBatchQueryExt instance. A NULL pointer will be returned if the subsequent allocations fail or if any of the arguments are illegal. +In the event that a NULL pointer is returned a corresponding error will be issued to the error stream. +*/ +PxBatchQueryExt* PxCreateBatchQueryExt( + const PxScene& scene, PxQueryFilterCallback* queryFilterCallback, + PxRaycastBuffer* raycastBuffers, const PxU32 maxNbRaycasts, PxRaycastHit* raycastTouches, const PxU32 maxNbRaycastTouches, + PxSweepBuffer* sweepBuffers, const PxU32 maxNbSweeps, PxSweepHit* sweepTouches, const PxU32 maxNbSweepTouches, + PxOverlapBuffer* overlapBuffers, const PxU32 maxNbOverlaps, PxOverlapHit* overlapTouches, const PxU32 maxNbOverlapTouches); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSceneQuerySystemExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSceneQuerySystemExt.h new file mode 100644 index 000000000..53aa6fc50 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSceneQuerySystemExt.h @@ -0,0 +1,63 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SCENE_QUERY_SYSTEM_EXT_H +#define PX_SCENE_QUERY_SYSTEM_EXT_H + +#include "PxSceneQuerySystem.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Creates an external scene query system. + + An external SQ system is the part of a PxScene that deals with scene queries (SQ). This is usually taken care of + by an internal implementation inside PxScene, but it is also possible to re-route all SQ calls to an external + implementation, potentially opening the door to some customizations in behavior and features for advanced users. + + The following external SQ system is an example of how an implementation would look like. It re-uses much of the + same code as the internal version, but it could be re-implemented in a completely different way to match users' + specific needs. + + \param[in] desc Scene query descriptor + \param[in] contextID Context ID parameter, sent to the profiler + + \return An external SQ system instance + + \see PxSceneQuerySystem PxSceneQueryDesc + */ + PxSceneQuerySystem* PxCreateExternalSceneQuerySystem(const PxSceneQueryDesc& desc, PxU64 contextID); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSerialization.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSerialization.h new file mode 100644 index 000000000..03d0c2b70 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSerialization.h @@ -0,0 +1,251 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SERIALIZATION_H +#define PX_SERIALIZATION_H + +#include "PxPhysXConfig.h" +#include "common/PxBase.h" +#include "cooking/PxCooking.h" +#include "foundation/PxIO.h" +#include "common/PxTolerancesScale.h" +#include "common/PxTypeInfo.h" +#include "common/PxStringTable.h" + +/** +PX_BINARY_SERIAL_VERSION is used to version the PhysX binary data and meta data. The global unique identifier of the PhysX SDK needs to match +the one in the data and meta data, otherwise they are considered incompatible. A 32 character wide GUID can be generated with https://www.guidgenerator.com/ for example. +*/ +#define PX_BINARY_SERIAL_VERSION "49FB7605F83144B6825C2673CF3840C9" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Utility functions for serialization + +\see PxCollection, PxSerializationRegistry +*/ +class PxSerialization +{ +public: + /** + \brief Additional PxScene and PxPhysics options stored in XML serialized data. + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + The PxXmlMiscParameter parameter can be serialized and deserialized along with PxCollection instances (XML only). + This is for application use only and has no impact on how objects are serialized or deserialized. + + \see PxSerialization::createCollectionFromXml, PxSerialization::serializeCollectionToXml + */ + struct PX_DEPRECATED PxXmlMiscParameter + { + /** + \brief Up vector for the scene reference coordinate system. + */ + PxVec3 upVector; + + /** + \brief Tolerances scale to be used for the scene. + */ + PxTolerancesScale scale; + + PxXmlMiscParameter() : upVector(0) {} + PxXmlMiscParameter(PxVec3& inUpVector, PxTolerancesScale inScale) : upVector(inUpVector), scale(inScale) {} + }; + + /** + \brief Returns whether the collection is serializable with the externalReferences collection. + + Some definitions to explain whether a collection can be serialized or not: + + For definitions of requires and complete see #PxSerialization::complete + + A serializable object is subordinate if it cannot be serialized on its own + The following objects are subordinate: + - articulation links + - articulation joints + - joints + + A collection C can be serialized with external references collection D iff + - C is complete relative to D (no dangling references) + - Every object in D required by an object in C has a valid ID (no unnamed references) + - Every subordinate object in C is required by another object in C (no orphans) + + \param[in] collection Collection to be checked + \param[in] sr PxSerializationRegistry instance with information about registered classes. + \param[in] externalReferences the external References collection + \return Whether the collection is serializable + \see PxSerialization::complete, PxSerialization::serializeCollectionToBinary, PxSerialization::serializeCollectionToXml, PxSerializationRegistry + */ + static bool isSerializable(PxCollection& collection, PxSerializationRegistry& sr, const PxCollection* externalReferences = NULL); + + /** + \brief Adds to a collection all objects such that it can be successfully serialized. + + A collection C is complete relative to an other collection D if every object required by C is either in C or D. + This function adds objects to a collection, such that it becomes complete with respect to the exceptFor collection. + Completeness is needed for serialization. See #PxSerialization::serializeCollectionToBinary, + #PxSerialization::serializeCollectionToXml. + + Sdk objects require other sdk object according to the following rules: + - joints require their actors and constraint + - rigid actors require their shapes + - shapes require their material(s) and mesh (triangle mesh, convex mesh or height field), if any + - articulations require their links and joints + - aggregates require their actors + + If followJoints is specified another rule is added: + - actors require their joints + + Specifying followJoints will make whole jointed actor chains being added to the collection. Following chains + is interrupted whenever a object in exceptFor is encountered. + + \param[in,out] collection Collection which is completed + \param[in] sr PxSerializationRegistry instance with information about registered classes. + \param[in] exceptFor Optional exemption collection + \param[in] followJoints Specifies whether joints should be added for jointed actors + \see PxCollection, PxSerialization::serializeCollectionToBinary, PxSerialization::serializeCollectionToXml, PxSerializationRegistry + */ + static void complete(PxCollection& collection, PxSerializationRegistry& sr, const PxCollection* exceptFor = NULL, bool followJoints = false); + + /** + \brief Creates PxSerialObjectId values for unnamed objects in a collection. + + Creates PxSerialObjectId names for unnamed objects in a collection starting at a base value and incrementing, + skipping values that are already assigned to objects in the collection. + + \param[in,out] collection Collection for which names are created + \param[in] base Start address for PxSerialObjectId names + \see PxCollection + */ + static void createSerialObjectIds(PxCollection& collection, const PxSerialObjectId base); + + /** + \brief Creates a PxCollection from XML data. + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + \param inputData The input data containing the XML collection. + \param params Cooking parameters used for sdk object instantiation. + \param sr PxSerializationRegistry instance with information about registered classes. + \param externalRefs PxCollection used to resolve external references. + \param stringTable PxStringTable instance used for storing object names. + \param outArgs Optional parameters of physics and scene deserialized from XML. See #PxSerialization::PxXmlMiscParameter + \return a pointer to a PxCollection if successful or NULL if it failed. + + \see PxCollection, PxSerializationRegistry, PxInputData, PxStringTable, PxCooking, PxSerialization::PxXmlMiscParameter + */ + PX_DEPRECATED static PxCollection* createCollectionFromXml(PxInputData& inputData, const PxCookingParams& params, PxSerializationRegistry& sr, const PxCollection* externalRefs = NULL, PxStringTable* stringTable = NULL, PxXmlMiscParameter* outArgs = NULL); + + /** + \brief Deserializes a PxCollection from memory. + + Creates a collection from memory. If the collection has external dependencies another collection + can be provided to resolve these. + + The memory block provided has to be 128 bytes aligned and contain a contiguous serialized collection as written + by PxSerialization::serializeCollectionToBinary. The contained binary data needs to be compatible with the current binary format version + which is defined by "PX_PHYSICS_VERSION_MAJOR.PX_PHYSICS_VERSION_MINOR.PX_PHYSICS_VERSION_BUGFIX-PX_BINARY_SERIAL_VERSION". + For a list of compatible sdk releases refer to the documentation of PX_BINARY_SERIAL_VERSION. + + \param[in] memBlock Pointer to memory block containing the serialized collection + \param[in] sr PxSerializationRegistry instance with information about registered classes. + \param[in] externalRefs Collection to resolve external dependencies + + \see PxCollection, PxSerialization::complete, PxSerialization::serializeCollectionToBinary, PxSerializationRegistry, PX_BINARY_SERIAL_VERSION + */ + static PxCollection* createCollectionFromBinary(void* memBlock, PxSerializationRegistry& sr, const PxCollection* externalRefs = NULL); + + /** + \brief Serializes a physics collection to an XML output stream. + + \deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics. + + The collection to be serialized needs to be complete \see PxSerialization.complete. + Optionally the XML may contain meshes in binary cooked format for fast loading. It does this when providing a valid non-null PxCooking pointer. + + \note Serialization of objects in a scene that is simultaneously being simulated is not supported and leads to undefined behavior. + + \param outputStream Stream to save collection to. + \param collection PxCollection instance which is serialized. The collection needs to be complete with respect to the externalRefs collection. + \param sr PxSerializationRegistry instance with information about registered classes. + \param params Optional pointer to cooking params. If provided, cooked mesh data is cached for fast loading. + \param externalRefs Collection containing external references. + \param inArgs Optional parameters of physics and scene serialized to XML along with the collection. See #PxSerialization::PxXmlMiscParameter + \return true if the collection is successfully serialized. + + \see PxCollection, PxOutputStream, PxSerializationRegistry, PxCooking, PxSerialization::PxXmlMiscParameter + */ + PX_DEPRECATED static bool serializeCollectionToXml(PxOutputStream& outputStream, PxCollection& collection, PxSerializationRegistry& sr, const PxCookingParams* params = NULL, const PxCollection* externalRefs = NULL, PxXmlMiscParameter* inArgs = NULL); + + /** + \brief Serializes a collection to a binary stream. + + Serializes a collection to a stream. In order to resolve external dependencies the externalReferences collection has to be provided. + Optionally names of objects that where set for example with #PxActor::setName are serialized along with the objects. + + The collection can be successfully serialized if isSerializable(collection) returns true. See #isSerializable. + + The implementation of the output stream needs to fulfill the requirements on the memory block input taken by + PxSerialization::createCollectionFromBinary. + + \note Serialization of objects in a scene that is simultaneously being simulated is not supported and leads to undefined behavior. + + \param[out] outputStream into which the collection is serialized + \param[in] collection Collection to be serialized + \param[in] sr PxSerializationRegistry instance with information about registered classes. + \param[in] externalRefs Collection used to resolve external dependencies + \param[in] exportNames Specifies whether object names are serialized + \return Whether serialization was successful + + \see PxCollection, PxOutputStream, PxSerialization::complete, PxSerialization::createCollectionFromBinary, PxSerializationRegistry + */ + static bool serializeCollectionToBinary(PxOutputStream& outputStream, PxCollection& collection, PxSerializationRegistry& sr, const PxCollection* externalRefs = NULL, bool exportNames = false ); + + /** + \brief Creates an application managed registry for serialization. + + \param[in] physics Physics SDK to generate create serialization registry + + \return PxSerializationRegistry instance. + + \see PxSerializationRegistry + */ + static PxSerializationRegistry* createSerializationRegistry(PxPhysics& physics); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxShapeExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxShapeExt.h new file mode 100644 index 000000000..f6de3bd91 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxShapeExt.h @@ -0,0 +1,155 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SHAPE_EXT_H +#define PX_SHAPE_EXT_H + +#include "PxPhysXConfig.h" + +#include "PxShape.h" +#include "PxRigidActor.h" +#include "geometry/PxGeometryQuery.h" +#include "PxQueryReport.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief utility functions for use with PxShape + +\see PxShape +*/ + +class PxShapeExt +{ +public: + /** + \brief Retrieves the world space pose of the shape. + + \param[in] shape The shape for which to get the global pose. + \param[in] actor The actor to which the shape is attached + + \return Global pose of shape. + */ + static PX_INLINE PxTransform getGlobalPose(const PxShape& shape, const PxRigidActor& actor) + { + // PT:: tag: scalar transform*transform + return actor.getGlobalPose() * shape.getLocalPose(); + } + + /** + \brief Raycast test against the shape. + + \param[in] shape the shape + \param[in] actor the actor to which the shape is attached + \param[in] rayOrigin The origin of the ray to test the geometry object against + \param[in] rayDir The direction of the ray to test the geometry object against + \param[in] maxDist Maximum ray length + \param[in] hitFlags Specify which properties per hit should be computed and written to result hit array. Combination of #PxHitFlag flags + \param[in] maxHits max number of returned hits = size of 'rayHits' buffer + \param[out] rayHits Raycast hits information + \return Number of hits between the ray and the shape + + \see PxRaycastHit PxTransform + */ + static PX_INLINE PxU32 raycast(const PxShape& shape, const PxRigidActor& actor, + const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, + PxU32 maxHits, PxRaycastHit* rayHits) + { + return PxGeometryQuery::raycast( + rayOrigin, rayDir, shape.getGeometry(), getGlobalPose(shape, actor), maxDist, hitFlags, maxHits, rayHits); + } + + /** + \brief Test overlap between the shape and a geometry object + + \param[in] shape the shape + \param[in] actor the actor to which the shape is attached + \param[in] otherGeom The other geometry object to test overlap with + \param[in] otherGeomPose Pose of the other geometry object + \return True if the shape overlaps the geometry object + + \see PxGeometry PxTransform + */ + static PX_INLINE bool overlap(const PxShape& shape, const PxRigidActor& actor, + const PxGeometry& otherGeom, const PxTransform& otherGeomPose) + { + return PxGeometryQuery::overlap(shape.getGeometry(), getGlobalPose(shape, actor), otherGeom, otherGeomPose); + } + + /** + \brief Sweep a geometry object against the shape. + + Currently only box, sphere, capsule and convex mesh shapes are supported, i.e. the swept geometry object must be one of those types. + + \param[in] shape the shape + \param[in] actor the actor to which the shape is attached + \param[in] unitDir Normalized direction along which the geometry object should be swept. + \param[in] distance Sweep distance. Needs to be larger than 0. + \param[in] otherGeom The geometry object to sweep against the shape + \param[in] otherGeomPose Pose of the geometry object + \param[out] sweepHit The sweep hit information. Only valid if this method returns true. + \param[in] hitFlags Specify which properties per hit should be computed and written to result hit array. Combination of #PxHitFlag flags + \return True if the swept geometry object hits the shape + + \see PxGeometry PxTransform PxSweepHit + */ + static PX_INLINE bool sweep(const PxShape& shape, const PxRigidActor& actor, + const PxVec3& unitDir, const PxReal distance, const PxGeometry& otherGeom, const PxTransform& otherGeomPose, + PxSweepHit& sweepHit, PxHitFlags hitFlags) + { + return PxGeometryQuery::sweep(unitDir, distance, otherGeom, otherGeomPose, shape.getGeometry(), getGlobalPose(shape, actor), sweepHit, hitFlags); + } + + /** + \brief Retrieves the axis aligned bounding box enclosing the shape. + + \return The shape's bounding box. + + \param[in] shape the shape + \param[in] actor the actor to which the shape is attached + \param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value. + + \see PxBounds3 + */ + static PX_INLINE PxBounds3 getWorldBounds(const PxShape& shape, const PxRigidActor& actor, float inflation=1.01f) + { + PxBounds3 bounds; + PxGeometryQuery::computeGeomBounds(bounds, shape.getGeometry(), getGlobalPose(shape, actor), 0.0f, inflation); + return bounds; + } + +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSimpleFactory.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSimpleFactory.h new file mode 100644 index 000000000..113ad1b74 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSimpleFactory.h @@ -0,0 +1,293 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SIMPLE_FACTORY_H +#define PX_SIMPLE_FACTORY_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxTransform.h" +#include "foundation/PxPlane.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxPhysics; + class PxMaterial; + class PxRigidActor; + class PxRigidDynamic; + class PxRigidStatic; + class PxGeometry; + class PxShape; + +/** \brief simple method to create a PxRigidDynamic actor with a single PxShape. + + \param[in] sdk the PxPhysics object + \param[in] transform the global pose of the new object + \param[in] geometry the geometry of the new object's shape, which must be a sphere, capsule, box or convex + \param[in] material the material for the new object's shape + \param[in] density the density of the new object. Must be greater than zero. + \param[in] shapeOffset an optional offset for the new shape, defaults to identity + + \return a new dynamic actor with the PxRigidBodyFlag, or NULL if it could + not be constructed + + \see PxRigidDynamic PxShapeFlag +*/ +PxRigidDynamic* PxCreateDynamic(PxPhysics& sdk, + const PxTransform& transform, + const PxGeometry& geometry, + PxMaterial& material, + PxReal density, + const PxTransform& shapeOffset = PxTransform(PxIdentity)); + +/** \brief simple method to create a PxRigidDynamic actor with a single PxShape. + + \param[in] sdk the PxPhysics object + \param[in] transform the transform of the new object + \param[in] shape the shape of the new object + \param[in] density the density of the new object. Must be greater than zero. + + \return a new dynamic actor with the PxRigidBodyFlag, or NULL if it could + not be constructed + + \see PxRigidDynamic PxShapeFlag +*/ +PxRigidDynamic* PxCreateDynamic(PxPhysics& sdk, + const PxTransform& transform, + PxShape& shape, + PxReal density); + +/** \brief simple method to create a kinematic PxRigidDynamic actor with a single PxShape. + + \param[in] sdk the PxPhysics object + \param[in] transform the global pose of the new object + \param[in] geometry the geometry of the new object's shape + \param[in] material the material for the new object's shape + \param[in] density the density of the new object. Must be greater than zero if the object is to participate in simulation. + \param[in] shapeOffset an optional offset for the new shape, defaults to identity + + \note unlike PxCreateDynamic, the geometry is not restricted to box, capsule, sphere or convex. However, + kinematics of other geometry types may not participate in simulation collision and may be used only for + triggers or scene queries of moving objects under animation control. In this case the density parameter + will be ignored and the created shape will be set up as a scene query only shape (see #PxShapeFlag::eSCENE_QUERY_SHAPE) + + \return a new dynamic actor with the PxRigidBodyFlag::eKINEMATIC set, or NULL if it could + not be constructed + + \see PxRigidDynamic PxShapeFlag +*/ +PxRigidDynamic* PxCreateKinematic(PxPhysics& sdk, + const PxTransform& transform, + const PxGeometry& geometry, + PxMaterial& material, + PxReal density, + const PxTransform& shapeOffset = PxTransform(PxIdentity)); + +/** \brief simple method to create a kinematic PxRigidDynamic actor with a single PxShape. + + \param[in] sdk the PxPhysics object + \param[in] transform the global pose of the new object + \param[in] density the density of the new object. Must be greater than zero if the object is to participate in simulation. + \param[in] shape the shape of the new object + + \note unlike PxCreateDynamic, the geometry is not restricted to box, capsule, sphere or convex. However, + kinematics of other geometry types may not participate in simulation collision and may be used only for + triggers or scene queries of moving objects under animation control. In this case the density parameter + will be ignored and the created shape will be set up as a scene query only shape (see #PxShapeFlag::eSCENE_QUERY_SHAPE) + + \return a new dynamic actor with the PxRigidBodyFlag::eKINEMATIC set, or NULL if it could + not be constructed + + \see PxRigidDynamic PxShapeFlag +*/ +PxRigidDynamic* PxCreateKinematic(PxPhysics& sdk, + const PxTransform& transform, + PxShape& shape, + PxReal density); + +/** \brief simple method to create a PxRigidStatic actor with a single PxShape. + + \param[in] sdk the PxPhysics object + \param[in] transform the global pose of the new object + \param[in] geometry the geometry of the new object's shape + \param[in] material the material for the new object's shape + \param[in] shapeOffset an optional offset for the new shape, defaults to identity + + \return a new static actor, or NULL if it could not be constructed + + \see PxRigidStatic +*/ +PxRigidStatic* PxCreateStatic(PxPhysics& sdk, + const PxTransform& transform, + const PxGeometry& geometry, + PxMaterial& material, + const PxTransform& shapeOffset = PxTransform(PxIdentity)); + +/** \brief simple method to create a PxRigidStatic actor with a single PxShape. + + \param[in] sdk the PxPhysics object + \param[in] transform the global pose of the new object + \param[in] shape the new object's shape + + \return a new static actor, or NULL if it could not be constructed + + \see PxRigidStatic +*/ +PxRigidStatic* PxCreateStatic(PxPhysics& sdk, + const PxTransform& transform, + PxShape& shape); + +/** +\brief create a shape by copying attributes from another shape + +The function clones a PxShape. The following properties are copied: +- geometry +- flags +- materials +- actor-local pose +- contact offset +- rest offset +- simulation filter data +- query filter data +- torsional patch radius +- minimum torsional patch radius + +The following are not copied and retain their default values: +- name +- user data + +\param[in] physicsSDK - the physics SDK used to allocate the shape +\param[in] shape the shape from which to take the attributes. +\param[in] isExclusive whether the new shape should be an exclusive or shared shape. + +\return the newly-created rigid static +*/ +PxShape* PxCloneShape(PxPhysics& physicsSDK, + const PxShape& shape, + bool isExclusive); + +/** +\brief create a static body by copying attributes from another rigid actor + +The function clones a PxRigidDynamic or PxRigidStatic as a PxRigidStatic. A uniform scale is applied. The following properties are copied: +- shapes +- actor flags +- owner client and client behavior bits +- dominance group + +The following are not copied and retain their default values: +- name +- joints or observers +- aggregate or scene membership +- user data + +\note Transforms are not copied with bit-exact accuracy. + +\param[in] physicsSDK - the physics SDK used to allocate the rigid static +\param[in] actor the rigid actor from which to take the attributes. +\param[in] transform the transform of the new static. + +\return the newly-created rigid static +*/ +PxRigidStatic* PxCloneStatic(PxPhysics& physicsSDK, + const PxTransform& transform, + const PxRigidActor& actor); + +/** +\brief create a dynamic body by copying attributes from an existing body + +The following properties are copied: +- shapes +- actor flags, rigidDynamic flags and rigidDynamic lock flags +- mass, moment of inertia, and center of mass frame +- linear and angular velocity +- linear and angular damping +- maximum linear velocity +- maximum angular velocity +- position and velocity solver iterations +- maximum depenetration velocity +- sleep threshold +- contact report threshold +- dominance group +- owner client and client behavior bits +- name pointer +- kinematic target + +The following are not copied and retain their default values: +- name +- joints or observers +- aggregate or scene membership +- sleep timer +- user data + +\note Transforms are not copied with bit-exact accuracy. + +\param[in] physicsSDK PxPhysics - the physics SDK used to allocate the rigid static +\param[in] body the rigid dynamic to clone. +\param[in] transform the transform of the new dynamic + +\return the newly-created rigid static +*/ +PxRigidDynamic* PxCloneDynamic(PxPhysics& physicsSDK, + const PxTransform& transform, + const PxRigidDynamic& body); + +/** \brief create a plane actor. The plane equation is n.x + d = 0 + + \param[in] sdk the PxPhysics object + \param[in] plane a plane of the form n.x + d = 0 + \param[in] material the material for the new object's shape + + \return a new static actor, or NULL if it could not be constructed + + \see PxRigidStatic +*/ +PxRigidStatic* PxCreatePlane(PxPhysics& sdk, + const PxPlane& plane, + PxMaterial& material); + +/** +\brief scale a rigid actor by a uniform scale + +The geometry and relative positions of the actor are multiplied by the given scale value. If the actor is a rigid body or an +articulation link and the scaleMassProps value is true, the mass properties are scaled assuming the density is constant: the +center of mass is linearly scaled, the mass is multiplied by the cube of the scale, and the inertia tensor by the fifth power of the scale. + +\param[in] actor a rigid actor +\param[in] scale the scale by which to multiply the actor. Must be >0. +\param[in] scaleMassProps whether to scale the mass properties +*/ +void PxScaleRigidActor(PxRigidActor& actor, PxReal scale, bool scaleMassProps = true); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSmoothNormals.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSmoothNormals.h new file mode 100644 index 000000000..11a8e6466 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSmoothNormals.h @@ -0,0 +1,56 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SMOOTH_NORMALS_H +#define PX_SMOOTH_NORMALS_H + +#include "foundation/PxVec3.h" +#include "common/PxPhysXCommonConfig.h" + +/** +\brief Builds smooth vertex normals over a mesh. + +- "smooth" because smoothing groups are not supported here +- takes angles into account for correct cube normals computation + +To use 32bit indices pass a pointer in dFaces and set wFaces to zero. Alternatively pass a pointer to +wFaces and set dFaces to zero. + +\param[in] nbTris Number of triangles +\param[in] nbVerts Number of vertices +\param[in] verts Array of vertices +\param[in] dFaces Array of dword triangle indices, or null +\param[in] wFaces Array of word triangle indices, or null +\param[out] normals Array of computed normals (assumes nbVerts vectors) +\param[in] flip Flips the normals or not +\return True on success. +*/ +PX_C_EXPORT bool PX_CALL_CONV PxBuildSmoothNormals(physx::PxU32 nbTris, physx::PxU32 nbVerts, const physx::PxVec3* verts, + const physx::PxU32* dFaces, const physx::PxU16* wFaces, physx::PxVec3* normals, bool flip); + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSoftBodyExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSoftBodyExt.h new file mode 100644 index 000000000..514a20d96 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSoftBodyExt.h @@ -0,0 +1,49 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SOFT_BODY_EXT_H +#define PX_SOFT_BODY_EXT_H + +#include "PxDeformableVolumeExt.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Deprecated +\see PxDeformableVolumeExt +*/ +typedef PX_DEPRECATED PxDeformableVolumeExt PxSoftBodyExt; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSphericalJoint.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSphericalJoint.h new file mode 100644 index 000000000..66762c933 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxSphericalJoint.h @@ -0,0 +1,180 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SPHERICAL_JOINT_H +#define PX_SPHERICAL_JOINT_H + +#include "extensions/PxJoint.h" +#include "extensions/PxJointLimit.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxSphericalJoint; + +/** +\brief Create a spherical joint. + + \param[in] physics The physics SDK + \param[in] actor0 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame0 The position and orientation of the joint relative to actor0 + \param[in] actor1 An actor to which the joint is attached. NULL may be used to attach the joint to a specific point in the world frame + \param[in] localFrame1 The position and orientation of the joint relative to actor1 + +\see PxSphericalJoint +*/ +PxSphericalJoint* PxSphericalJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); + + +/** +\brief Flags specific to the spherical joint. + +\see PxSphericalJoint +*/ +struct PxSphericalJointFlag +{ + enum Enum + { + eLIMIT_ENABLED = 1<<1 //!< the cone limit for the spherical joint is enabled + }; +}; +typedef PxFlags PxSphericalJointFlags; +PX_FLAGS_OPERATORS(PxSphericalJointFlag::Enum, PxU16) + +/** +\brief A joint which behaves in a similar way to a ball and socket. + + A spherical joint removes all linear degrees of freedom from two objects. + + The position of the joint on each actor is specified by the origin of the body's joint frame. + + A spherical joint may have a cone limit, to restrict the motion to within a certain range. + + Dirve and limits are activated by setting the appropriate flags on the joint. + + \see PxRevoluteJointCreate() PxJoint +*/ +class PxSphericalJoint : public PxJoint +{ +public: + + /** + \brief Set the limit cone. + + If enabled, the limit cone will constrain the angular movement of the joint to lie + within an elliptical cone. + + \return the limit cone + + \see PxJointLimitCone setLimit() + */ + virtual PxJointLimitCone getLimitCone() const = 0; + + /** + \brief Get the limit cone. + + \param[in] limit the limit cone + + \see PxJointLimitCone getLimit() + */ + virtual void setLimitCone(const PxJointLimitCone& limit) = 0; + + /** + \brief get the swing angle of the joint from the Y axis + */ + virtual PxReal getSwingYAngle() const = 0; + + /** + \brief get the swing angle of the joint from the Z axis + */ + virtual PxReal getSwingZAngle() const = 0; + + /** + \brief Set the flags specific to the Spherical Joint. + + Default PxSphericalJointFlags(0) + + \param[in] flags The joint flags. + + \see PxSphericalJointFlag setFlag() getFlags() + */ + virtual void setSphericalJointFlags(PxSphericalJointFlags flags) = 0; + + /** + \brief Set a single flag specific to a Spherical Joint to true or false. + + \param[in] flag The flag to set or clear. + \param[in] value the value to which to set the flag + + \see PxSphericalJointFlag, getFlags() setFlags() + */ + virtual void setSphericalJointFlag(PxSphericalJointFlag::Enum flag, bool value) = 0; + + /** + \brief Get the flags specific to the Spherical Joint. + + \return the joint flags + + \see PxSphericalJoint::flags, PxSphericalJointFlag setFlag() setFlags() + */ + virtual PxSphericalJointFlags getSphericalJointFlags() const = 0; + + /** + \brief Returns string name of PxSphericalJoint, used for serialization + */ + virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxSphericalJoint"; } + +protected: + + //serialization + + /** + \brief Constructor + */ + PX_INLINE PxSphericalJoint(PxType concreteType, PxBaseFlags baseFlags) : PxJoint(concreteType, baseFlags) {} + + /** + \brief Deserialization constructor + */ + PX_INLINE PxSphericalJoint(PxBaseFlags baseFlags) : PxJoint(baseFlags) {} + + /** + \brief Returns whether a given type name matches with the type of this instance + */ + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxSphericalJoint", PxJoint); } + + //~serialization +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxStringTableExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxStringTableExt.h new file mode 100644 index 000000000..924b05881 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxStringTableExt.h @@ -0,0 +1,56 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_STRING_TABLE_EXT_H +#define PX_STRING_TABLE_EXT_H + +#include "foundation/PxAllocatorCallback.h" +#include "common/PxStringTable.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief a factory class for creating PxStringTable with a specific allocator. + +\see PxStringTable +*/ + +class PxStringTableExt +{ +public: + static PxStringTable& createStringTable( physx::PxAllocatorCallback& inAllocator ); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetMakerExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetMakerExt.h new file mode 100644 index 000000000..958be6ff0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetMakerExt.h @@ -0,0 +1,221 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TETMAKER_EXT_H +#define PX_TETMAKER_EXT_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec3.h" +#include "common/PxCoreUtilityTypes.h" +#include "foundation/PxArray.h" +#include "PxTriangleMeshAnalysisResult.h" +#include "PxTetrahedronMeshAnalysisResult.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxTriangleMesh; +class PxTetrahedronMeshDesc; +class PxDeformableVolumeSimulationDataDesc; +struct PxTetMakerData; +class PxSimpleTriangleMesh; + +/** +\brief Provides functionality to create a tetrahedral mesh from a triangle mesh. +*/ +class PxTetMaker +{ +public: + + /** + \brief Create conforming tetrahedron mesh using TetMaker + + \param[in] triangleMesh The description of the triangle mesh including vertices and indices + \param[out] outVertices The vertices to store the conforming tetrahedral mesh + \param[out] outTetIndices The indices to store the conforming tetrahedral mesh + \param[in] validate If set to true the input triangle mesh will get analyzed to find possible deficiencies + \param[in] volumeThreshold Tetrahedra with a volume smaller than the specified threshold will be removed from the mesh + \return True if success + */ + static bool createConformingTetrahedronMesh(const PxSimpleTriangleMesh& triangleMesh, physx::PxArray& outVertices, physx::PxArray& outTetIndices, + const bool validate = true, PxReal volumeThreshold = 0.0f); + + /** + \brief Create voxel-based tetrahedron mesh using TetMaker + + \param[in] tetMesh The description of the tetrahedral mesh including vertices and indices + \param[in] numVoxelsAlongLongestBoundingBoxAxis The number of voxels along the longest bounding box axis + \param[out] outVertices The vertices to store the voxel-based tetrahedral mesh + \param[out] outTetIndices The indices to store the voxel-based tetrahedral mesh + \param[out] inputPointToOutputTetIndex Buffer with the size of nbTetVerts that contains the tetrahedron index containing the input point with the same index + \param[in] anchorNodeIndices Some input vertices may not be referenced by any tetrahedron. They can be mapped to another input vertex that is used by a tetrahedron to support embedding of additional points. + \param[in] numTetsPerVoxel The number of tetrahedra used to fill a voxel. Only a value of 5 or 6 is supported. 5 is recommended because it mostly avoids mesh anisotropy. + \return True if success + */ + static bool createVoxelTetrahedronMesh(const PxTetrahedronMeshDesc& tetMesh, const PxU32 numVoxelsAlongLongestBoundingBoxAxis, + physx::PxArray& outVertices, physx::PxArray& outTetIndices, PxI32* inputPointToOutputTetIndex = NULL, const PxU32* anchorNodeIndices = NULL, PxU32 numTetsPerVoxel = 5); + + /** + \brief Create voxel-based tetrahedron mesh using TetMaker + + \param[in] tetMesh The description of the tetrahedral mesh including vertices and indices + \param[in] voxelEdgeLength The edge length of a voxel.Can be adjusted slightly such that a multiple of it matches the input points' bounding box size + \param[out] outVertices The vertices to store the voxel-based tetrahedral mesh + \param[out] outTetIndices The indices to store the voxel-based tetrahedral mesh + \param[out] inputPointToOutputTetIndex Buffer with the size of nbTetVerts that contains the tetrahedron index containing the input point with the same index + \param[in] anchorNodeIndices Some input vertices may not be referenced by any tetrahedron. They can be mapped to another input vertex that is used by a tetrahedron to support embedding of additional points. + \param[in] numTetsPerVoxel The number of tetrahedra used to fill a voxel. Only a value of 5 or 6 is supported. 5 is recommended because it mostly avoids mesh anisotropy. + \return True if success + */ + static bool createVoxelTetrahedronMeshFromEdgeLength(const PxTetrahedronMeshDesc& tetMesh, const PxReal voxelEdgeLength, + physx::PxArray& outVertices, physx::PxArray& outTetIndices, PxI32* inputPointToOutputTetIndex = NULL, const PxU32* anchorNodeIndices = NULL, PxU32 numTetsPerVoxel = 5); + + /** + \brief Analyzes the triangle mesh to get a report about deficiencies. Some deficiencies can be handled by the tetmesher, others cannot. + + \param[in] triangleMesh The description of the triangle mesh including vertices and indices + \param[in] minVolumeThreshold Minimum volume the mesh must have such that no volume warning is generated + \param[in] minTriangleAngleRadians Minimum angle allowed for triangles such that no angle warning is generated + \return Flags that describe the triangle mesh's deficiencies + */ + static PxTriangleMeshAnalysisResults validateTriangleMesh(const PxSimpleTriangleMesh& triangleMesh, const PxReal minVolumeThreshold = 1e-6f, const PxReal minTriangleAngleRadians = 10.0f*3.1415926535898f / 180.0f); + + /** + \brief Analyzes the tetrahedron mesh to get a report about deficiencies. Some deficiencies can be handled by the deformable volume cooker, others cannot. + + \param[in] points The mesh's points + \param[in] tetrahedra The mesh's tetrahedra (index buffer) + \param[in] minTetVolumeThreshold Minimum volume every tetrahedron in the mesh must have such that no volume warning is generated + \return Flags that describe the tetrahedron mesh's deficiencies + */ + static PxTetrahedronMeshAnalysisResults validateTetrahedronMesh(const PxBoundedData& points, const PxBoundedData& tetrahedra, const PxReal minTetVolumeThreshold = 1e-8f); + + /** + \brief Simplifies (decimates) a triangle mesh using quadric simplification. + + \param[in] inputVertices The vertices of the input triangle mesh + \param[in] inputIndices The indices of the input triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[in] targetTriangleCount Desired number of triangles in the output mesh + \param[in] maximalEdgeLength Edges below this length will not be collapsed. A value of zero means there is no limit. + \param[out] outputVertices The vertices of the output (decimated) triangle mesh + \param[out] outputIndices The indices of the output (decimated) triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[out] vertexMap Optional parameter which returns the mapping from input to output vertices. Note that multiple input vertices are typically collapsed into the same output vertex. + \param[in] edgeLengthCostWeight Factor to scale influence of edge length when prioritizing edge collapses. Has no effect if set to zero. + \param[in] flatnessDetectionThreshold Threshold used to detect edges in flat regions and to improve the placement of the collapsed point. If set to a large value it will have no effect. + \param[in] projectSimplifiedPointsOnInputMeshSurface If set to true, the simplified points will lie exactly on the original surface. + \param[out] outputVertexToInputTriangle Optional indices providing the triangle index per resulting vertex. Only available when projectSimplifiedPointsOnInputMeshSurface is set to true + \param[in] removeDisconnectedPatches Enables the optional removal of disconnected triangles in the mesh. Only the largest connected set/patch will be kept + */ + static void simplifyTriangleMesh(const PxArray& inputVertices, const PxArray&inputIndices, int targetTriangleCount, PxF32 maximalEdgeLength, + PxArray& outputVertices, PxArray& outputIndices, + PxArray *vertexMap = NULL, PxReal edgeLengthCostWeight = 0.1f, PxReal flatnessDetectionThreshold = 0.01f, + bool projectSimplifiedPointsOnInputMeshSurface = false, PxArray* outputVertexToInputTriangle = NULL, bool removeDisconnectedPatches = false); + + /** + \brief Creates a new mesh from a given mesh. The input mesh is first voxelized. The new surface is created from the voxel surface and subsequent projection to the original mesh. + + \param[in] inputVertices The vertices of the input triangle mesh + \param[in] inputIndices The indices of the input triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[in] gridResolution Size of the voxel grid (number of voxels along the longest dimension) + \param[out] outputVertices The vertices of the output (decimated) triangle mesh + \param[out] outputIndices The indices of the output (decimated) triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[out] vertexMap Optional parameter which returns a mapping from input to output vertices. Since the meshes are independent, the mapping returns an output vertex that is topologically close to the input vertex. + */ + static void remeshTriangleMesh(const PxArray& inputVertices, const PxArray&inputIndices, PxU32 gridResolution, + PxArray& outputVertices, PxArray& outputIndices, PxArray *vertexMap = NULL); + + /** + \brief Creates a new mesh from a given mesh. The input mesh is first voxelized. The new surface is created from the voxel surface and subsequent projection to the original mesh. + + \param[in] inputVertices The vertices of the input triangle mesh + \param[in] nbVertices The number of vertices of the input triangle mesh + \param[in] inputIndices The indices of the input triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[in] nbIndices The number of indices of the input triangle mesh (equal to three times the number of triangles) + \param[in] gridResolution Size of the voxel grid (number of voxels along the longest dimension) + \param[out] outputVertices The vertices of the output (decimated) triangle mesh + \param[out] outputIndices The indices of the output (decimated) triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[out] vertexMap Optional parameter which returns a mapping from input to output vertices. Since the meshes are independent, the mapping returns an output vertex that is topologically close to the input vertex. + */ + static void remeshTriangleMesh(const PxVec3* inputVertices, PxU32 nbVertices, const PxU32* inputIndices, PxU32 nbIndices, PxU32 gridResolution, + PxArray& outputVertices, PxArray& outputIndices, PxArray *vertexMap = NULL); + + /** + \brief Creates a tetrahedral mesh using an octree. + + \param[in] inputVertices The vertices of the input triangle mesh + \param[in] inputIndices The indices of the input triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[in] useTreeNodes Using the nodes of the octree as tetrahedral vertices + \param[out] outputVertices The vertices of the output tetrahedral mesh + \param[out] outputIndices The indices of the output tetrahedral mesh of the form (id0, id1, id2, id3), (id0, id1, id2, id3), .. + \param[in] volumeThreshold Tetrahedra with a volume smaller than the specified threshold will be removed from the mesh + */ + static void createTreeBasedTetrahedralMesh(const PxArray& inputVertices, const PxArray&inputIndices, + bool useTreeNodes, PxArray& outputVertices, PxArray& outputIndices, PxReal volumeThreshold = 0.0f); + + /** + \brief Creates a tetrahedral mesh by relaxing a voxel mesh around the input mesh + + \param[in] inputVertices The vertices of the input triangle mesh + \param[in] inputIndices The indices of the input triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[out] outputVertices The vertices of the output tetrahedral mesh + \param[out] outputIndices The indices of the output tetrahedral mesh of the form (id0, id1, id2, id3), (id0, id1, id2, id3), .. + \param[in] resolution The grid spacing is computed as the diagonal of the bounding box of the input mesh divided by the resolution. + \param[in] numRelaxationIterations Number of iterations to pull the tetrahedral mesh towards the input mesh + \param[in] relMinTetVolume Constrains the volumes of the tetrahedra to stay abobe relMinTetvolume times the tetrahedron's rest volume. + */ + static void createRelaxedVoxelTetrahedralMesh(const PxArray& inputVertices, const PxArray&inputIndices, + PxArray& outputVertices, PxArray& outputIndices, + PxI32 resolution, PxI32 numRelaxationIterations = 5, PxF32 relMinTetVolume = 0.05f); + + /** + \brief Creates a tetrahedral mesh by relaxing a voxel mesh around the input mesh + + \param[in] triangles The indices of the input triangle mesh of the form (id0, id1, id2), (id0, id1, id2), .. + \param[in] numTriangles The number of triangles + \param[out] islandIndexPerTriangle Every triangle gets an island index assigned. Triangles with the same island index belong to the same patch of connected triangles. + */ + static void detectTriangleIslands(const PxI32* triangles, PxU32 numTriangles, PxArray& islandIndexPerTriangle); + + /** + \brief Creates a tetrahedral mesh by relaxing a voxel mesh around the input mesh + + \param[in] islandIndexPerTriangle An island marker per triangles. All triangles with the same marker belong to an island. Can becomputed using the method detectTriangleIslands. + \param[in] numTriangles The number of triangles + \return The marker value of the island that contains the most triangles + */ + static PxU32 findLargestIslandId(const PxU32* islandIndexPerTriangle, PxU32 numTriangles); +}; + +#if !PX_DOXYGEN +} +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetrahedronMeshAnalysisResult.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetrahedronMeshAnalysisResult.h new file mode 100644 index 000000000..4e4f7cc26 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetrahedronMeshAnalysisResult.h @@ -0,0 +1,61 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_TETRAHEDRON_MESH_ANALYSIS_RESULT_H +#define PX_TETRAHEDRON_MESH_ANALYSIS_RESULT_H + + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief These flags indicate what kind of deficiencies a tetrahedron mesh has and describe if the mesh is considered ok, problematic or invalid for deformable volume cooking + */ + class PxTetrahedronMeshAnalysisResult + { + public: + enum Enum + { + eVALID = 0, + eDEGENERATE_TETRAHEDRON = (1 << 0), //!< At least one tetrahedron has zero or negative volume. This can happen when the input triangle mesh contains triangles that are very elongated, e. g. one edge is a lot shorther than the other two. + + eMESH_IS_PROBLEMATIC = (1 << 1), //!< flag is set if the mesh is categorized as problematic + eMESH_IS_INVALID = (1 << 2) //!< flag is set if the mesh is categorized as invalid + }; + }; + typedef PxFlags PxTetrahedronMeshAnalysisResults; + PX_FLAGS_OPERATORS(PxTetrahedronMeshAnalysisResult::Enum, PxU32) + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetrahedronMeshExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetrahedronMeshExt.h new file mode 100644 index 000000000..f9b3b0c97 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTetrahedronMeshExt.h @@ -0,0 +1,108 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TETRAHEDRON_MESH_EXT_H +#define PX_TETRAHEDRON_MESH_EXT_H + +#include "foundation/PxVec3.h" +#include "foundation/PxVec4.h" +#include "foundation/PxArray.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + class PxTetrahedronMesh; + + /** + \brief utility functions for use with PxTetrahedronMesh and subclasses + */ + class PxTetrahedronMeshExt + { + public: + /** Returns the index of the tetrahedron that contains a point + + \param[in] mesh The tetmesh + \param[in] point The point to find the enclosing tetrahedron for + \param[in] bary The barycentric coordinates of the point inside the enclosing tetrahedron + \param[in] tolerance Tolerance value used classify points as inside if they lie exactly a tetrahedron's surface + \return The index of the tetrahedron containing the point, -1 if not tetrahedron contains the opoint + */ + static PxI32 findTetrahedronContainingPoint(const PxTetrahedronMesh* mesh, const PxVec3& point, PxVec4& bary, PxReal tolerance = 1e-6f); + + /** Returns the index of the tetrahedron closest to a point + + \param[in] mesh The tetmesh + \param[in] point The point to find the closest tetrahedron for + \param[out] bary The barycentric coordinates of the point in the tetrahedron + \return The index of the tetrahedron closest to the point + */ + static PxI32 findTetrahedronClosestToPoint(const PxTetrahedronMesh* mesh, const PxVec3& point, PxVec4& bary); + + /** Associates points with closest tetrahedra from input tetrahedral mesh. If the tetmesh does not have any tetrahedra + or points, a warning will be generated and the result arrays will be empty, even if there are query points passed into the method. + + \param[in] tetMeshVertices The tetrahedral mesh vertices + \param[in] tetMeshIndices The tetraheral mesh indices + \param[in] pointsToEmbed The points for which the embedding should be created + \param[in] barycentricCoordinates The output barycentric coordinates for each input point relative to its closest tetrahedron + \param[in] tetLinks The output indices of the closest tetrahedron for each input point + */ + static void createPointsToTetrahedronMap(const PxArray& tetMeshVertices, const PxArray& tetMeshIndices, const PxArray& pointsToEmbed, PxArray& barycentricCoordinates, PxArray& tetLinks); + + /** Extracts the surface triangles of a tetmesh + + The extracted triangle's vertex indices point to the vertex buffer of the tetmesh. + + \param[in] tetrahedra The tetrahedra indices + \param[in] numTetrahedra The number of tetrahedra + \param[in] sixteenBitIndices If set to true, the tetrahedra indices are read as 16bit integers, otherwise 32bit integers are used + \param[in] surfaceTriangles The resulting surface triangles + \param[in] surfaceTriangleToTet Optional array to get the index of a tetrahedron that is adjacent to the surface triangle with the corresponding index + \param[in] flipTriangleOrientation Reverses the orientation of the ouput triangles + */ + static void extractTetMeshSurface(const void* tetrahedra, PxU32 numTetrahedra, bool sixteenBitIndices, PxArray& surfaceTriangles, PxArray* surfaceTriangleToTet = NULL, bool flipTriangleOrientation = false); + + /** Extracts the surface triangles of a tetmesh + + The extracted triangle's vertex indices point to the vertex buffer of the tetmesh. + + \param[in] mesh The mesh from which the surface shall be computed + \param[in] surfaceTriangles The resulting surface triangles + \param[in] surfaceTriangleToTet Optional array to get the index of a tetrahedron that is adjacent to the surface triangle with the corresponding index + \param[in] flipTriangleOrientation Reverses the orientation of the ouput triangles + */ + static void extractTetMeshSurface(const PxTetrahedronMesh* mesh, PxArray& surfaceTriangles, PxArray* surfaceTriangleToTet = NULL, bool flipTriangleOrientation = false); + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTriangleMeshAnalysisResult.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTriangleMeshAnalysisResult.h new file mode 100644 index 000000000..1a635ef42 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTriangleMeshAnalysisResult.h @@ -0,0 +1,70 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_TRIANGLE_MESH_ANALYSIS_RESULT_H +#define PX_TRIANGLE_MESH_ANALYSIS_RESULT_H + + +#include "PxPhysXConfig.h" +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief These flags indicate what kind of deficiencies a triangle mesh has and describe if the mesh is considered ok, problematic or invalid for tetmeshing + */ + class PxTriangleMeshAnalysisResult + { + public: + enum Enum + { + eVALID = 0, + eZERO_VOLUME = (1 << 0), //!< invalid: Flat mesh without meaningful amount of volume - cannot be meshed since a tetmesh is volumetric + eOPEN_BOUNDARIES = (1 << 1), //!< problematic: Open boundary means that the mesh is not watertight and that there are holes. The mesher can fill holes but the surface might have an unexpected shape where the hole was. + eSELF_INTERSECTIONS = (1 << 2), //!< problematic: The surface of the resulting mesh won't match exactly at locations of self-intersections. The tetmesh might be connected at self-intersections even if the input triangle mesh is not + eINCONSISTENT_TRIANGLE_ORIENTATION = (1 << 3), //!< invalid: It is not possible to distinguish what is inside and outside of the mesh. If there are no self-intersections and not edges shared by more than two triangles, a call to makeTriOrientationConsistent can fix this. Without fixing it, the output from the tetmesher will be incorrect + eCONTAINS_ACUTE_ANGLED_TRIANGLES = (1 << 4), //!< problematic: An ideal mesh for a volume deformable has triangles with similar angles and evenly distributed vertices. Acute angles can be handled but might lead to a poor quality tetmesh. + eEDGE_SHARED_BY_MORE_THAN_TWO_TRIANGLES = (1 << 5), //!< problematic: Border case of a self-intersecting mesh. The tetmesh might not match the surace exactly near such edges. + eCONTAINS_DUPLICATE_POINTS = (1 << 6), //!< ok: Duplicate points can be handled by the mesher without problems. The resulting tetmesh will only make use of first unique point that is found, duplicate points will get mapped to that unique point in the tetmesh. Therefore the tetmesh can contain points that are not accessed by a tet. + eCONTAINS_INVALID_POINTS = (1 << 7), //!< invalid: Points contain NAN, infinity or similar values that will lead to an invalid mesh + eREQUIRES_32BIT_INDEX_BUFFER = (1 << 8), //!< invalid: Mesh contains more indices than a 16bit index buffer can address + eTRIANGLE_INDEX_OUT_OF_RANGE = (1 << 9), //!< invalid: A mesh triangle index is negative or lager than the size of the vertex buffer + + eMESH_IS_PROBLEMATIC = (1 << 10), //!< flag is set if the mesh is categorized as problematic + eMESH_IS_INVALID = (1 << 11) //!< flag is set if the mesh is categorized as invalid + }; + }; + typedef PxFlags PxTriangleMeshAnalysisResults; + PX_FLAGS_OPERATORS(PxTriangleMeshAnalysisResult::Enum, PxU32) + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTriangleMeshExt.h b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTriangleMeshExt.h new file mode 100644 index 000000000..f62057c0a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/extensions/PxTriangleMeshExt.h @@ -0,0 +1,194 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TRIANGLE_MESH_EXT_H +#define PX_TRIANGLE_MESH_EXT_H + +#include "PxPhysXConfig.h" +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxArray.h" +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxGeometry; +class PxTriangleMesh; +class PxTriangleMeshGeometry; +class PxHeightFieldGeometry; + + /** + \brief Utility class to find mesh triangles touched by a specified geometry object. + + This class is a helper calling PxMeshQuery::findOverlapTriangleMesh or PxMeshQuery::findOverlapHeightField under the hood, + while taking care of necessary memory management issues. + + PxMeshQuery::findOverlapTriangleMesh and PxMeshQuery::findOverlapHeightField are the "raw" functions operating on user-provided fixed-size + buffers. These functions abort with an error code in case of buffer overflow. PxMeshOverlapUtil is a convenient helper function checking + this error code, and resizing buffers appropriately, until the desired call succeeds. + + Returned triangle indices are stored within the class, and can be used with PxMeshQuery::getTriangle() to retrieve the triangle properties. + */ + class PxMeshOverlapUtil + { + public: + PxMeshOverlapUtil(); + ~PxMeshOverlapUtil(); + /** + \brief Find the mesh triangles which touch the specified geometry object. + + \param[in] geom The geometry object to test for mesh triangle overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry + \param[in] geomPose Pose of the geometry object + \param[in] meshGeom The triangle mesh geometry to check overlap against + \param[in] meshPose Pose of the triangle mesh + \return Number of overlaps found. Triangle indices can then be accessed through the #getResults() function. + + \see PxGeometry PxTransform PxTriangleMeshGeometry PxMeshQuery::findOverlapTriangleMesh + */ + PxU32 findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose); + + /** + \brief Find the height field triangles which touch the specified geometry object. + + \param[in] geom The geometry object to test for height field overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry. The sphere and capsule queries are currently conservative estimates. + \param[in] geomPose Pose of the geometry object + \param[in] hfGeom The height field geometry to check overlap against + \param[in] hfPose Pose of the height field + \return Number of overlaps found. Triangle indices can then be accessed through the #getResults() function. + + \see PxGeometry PxTransform PxHeightFieldGeometry PxMeshQuery::findOverlapHeightField + */ + PxU32 findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose); + + /** + \brief Retrieves array of triangle indices after a findOverlap call. + \return Indices of touched triangles + */ + PX_FORCE_INLINE const PxU32* getResults() const { return mResultsMemory; } + + /** + \brief Retrieves number of triangle indices after a findOverlap call. + \return Number of touched triangles + */ + PX_FORCE_INLINE PxU32 getNbResults() const { return mNbResults; } + + private: + PxU32* mResultsMemory; + PxU32 mResults[256]; + PxU32 mNbResults; + PxU32 mMaxNbResults; + }; + + /** + \brief Computes an approximate minimum translational distance (MTD) between a geometry object and a mesh. + + This iterative function computes an approximate vector that can be used to depenetrate a geom object + from a triangle mesh. Returned depenetration vector should be applied to 'geom', to get out of the mesh. + + The function works best when the amount of overlap between the geom object and the mesh is small. If the + geom object's center goes inside the mesh, backface culling usually kicks in, no overlap is detected, + and the function does not compute an MTD vector. + + The function early exits if no overlap is detected after a depenetration attempt. This means that if + maxIter = N, the code will attempt at most N iterations but it might exit earlier if depenetration has + been successful. Usually N = 4 gives good results. + + \param[out] direction Computed MTD unit direction + \param[out] depth Penetration depth. Always positive or zero. + \param[in] geom The geometry object + \param[in] geomPose Pose for the geometry object + \param[in] meshGeom The mesh geometry + \param[in] meshPose Pose for the mesh + \param[in] maxIter Max number of iterations before returning. + \param[out] usedIter Number of depenetrations attempts performed during the call. Will not be returned if the pointer is NULL. + + \return True if the MTD has successfully been computed, i.e. if objects do overlap. + + \see PxGeometry PxTransform PxTriangleMeshGeometry + */ + bool PxComputeTriangleMeshPenetration(PxVec3& direction, + PxReal& depth, + const PxGeometry& geom, + const PxTransform& geomPose, + const PxTriangleMeshGeometry& meshGeom, + const PxTransform& meshPose, + PxU32 maxIter, + PxU32* usedIter = NULL); + + /** + \brief Computes an approximate minimum translational distance (MTD) between a geometry object and a heightfield. + + This iterative function computes an approximate vector that can be used to depenetrate a geom object + from a heightfield. Returned depenetration vector should be applied to 'geom', to get out of the heightfield. + + The function works best when the amount of overlap between the geom object and the mesh is small. If the + geom object's center goes inside the heightfield, backface culling usually kicks in, no overlap is detected, + and the function does not compute an MTD vector. + + The function early exits if no overlap is detected after a depenetration attempt. This means that if + maxIter = N, the code will attempt at most N iterations but it might exit earlier if depenetration has + been successful. Usually N = 4 gives good results. + + \param[out] direction Computed MTD unit direction + \param[out] depth Penetration depth. Always positive or zero. + \param[in] geom The geometry object + \param[in] geomPose Pose for the geometry object + \param[in] heightFieldGeom The heightfield geometry + \param[in] heightFieldPose Pose for the heightfield + \param[in] maxIter Max number of iterations before returning. + \param[out] usedIter Number of depenetrations attempts performed during the call. Will not be returned if the pointer is NULL. + + \return True if the MTD has successfully been computed, i.e. if objects do overlap. + + \see PxGeometry PxTransform PxHeightFieldGeometry + */ + bool PxComputeHeightFieldPenetration(PxVec3& direction, + PxReal& depth, + const PxGeometry& geom, + const PxTransform& geomPose, + const PxHeightFieldGeometry& heightFieldGeom, + const PxTransform& heightFieldPose, + PxU32 maxIter, + PxU32* usedIter = NULL); + + /** + \brief Extracts an isosurface from the SDF of a mesh if it the SDF is available. + + \param[in] triangleMesh The triangle mesh + \param[out] isosurfaceVertices The vertices of the extracted isosurface + \param[out] isosurfaceTriangleIndices The triangles of the extracted isosurface + */ + bool PxExtractIsosurfaceFromSDF(const PxTriangleMesh& triangleMesh, PxArray& isosurfaceVertices, PxArray& isosurfaceTriangleIndices); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/filebuf/PxFileBuf.h b/Jusin154_Team3D/Engine/Public/PhysX/filebuf/PxFileBuf.h new file mode 100644 index 000000000..a9ede6e0c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/filebuf/PxFileBuf.h @@ -0,0 +1,335 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef PSFILEBUFFER_PXFILEBUF_H +#define PSFILEBUFFER_PXFILEBUF_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxAllocator.h" + + +#if !PX_DOXYGEN +namespace physx +{ + +namespace general_PxIOStream2 +{ +#endif + +PX_PUSH_PACK_DEFAULT + +/** +\brief Callback class for data serialization. + +The user needs to supply an PxFileBuf implementation to a number of methods to allow the SDK to read or write +chunks of binary data. This allows flexibility for the source/destination of the data. For example the PxFileBuf +could store data in a file, memory buffer or custom file format. + +\note It is the users responsibility to ensure that the data is written to the appropriate offset. + +*/ +class PxFileBuf +{ +public: + + enum EndianMode + { + ENDIAN_NONE = 0, // do no conversion for endian mode + ENDIAN_BIG = 1, // always read/write data as natively big endian (Power PC, etc.) + ENDIAN_LITTLE = 2 // always read/write data as natively little endian (Intel, etc.) Default Behavior! + }; + + PxFileBuf(EndianMode mode=ENDIAN_LITTLE) + { + setEndianMode(mode); + } + + virtual ~PxFileBuf() + { + + } + + /** + \brief Declares a constant to seek to the end of the stream. + * + * Does not support streams longer than 32 bits + */ + static const uint32_t STREAM_SEEK_END=0xFFFFFFFF; + + enum OpenMode + { + OPEN_FILE_NOT_FOUND, + OPEN_READ_ONLY, // open file buffer stream for read only access + OPEN_WRITE_ONLY, // open file buffer stream for write only access + OPEN_READ_WRITE_NEW, // open a new file for both read/write access + OPEN_READ_WRITE_EXISTING // open an existing file for both read/write access + }; + + virtual OpenMode getOpenMode() const = 0; + + bool isOpen() const + { + return getOpenMode()!=OPEN_FILE_NOT_FOUND; + } + + enum SeekType + { + SEEKABLE_NO = 0, + SEEKABLE_READ = 0x1, + SEEKABLE_WRITE = 0x2, + SEEKABLE_READWRITE = 0x3 + }; + + virtual SeekType isSeekable() const = 0; + + void setEndianMode(EndianMode e) + { + mEndianMode = e; + if ( (e==ENDIAN_BIG && !isBigEndian() ) || + (e==ENDIAN_LITTLE && isBigEndian() ) ) + { + mEndianSwap = true; + } + else + { + mEndianSwap = false; + } + } + + EndianMode getEndianMode() const + { + return mEndianMode; + } + + virtual uint32_t getFileLength() const = 0; + + /** + \brief Seeks the stream to a particular location for reading + * + * If the location passed exceeds the length of the stream, then it will seek to the end. + * Returns the location it ended up at (useful if you seek to the end) to get the file position + */ + virtual uint32_t seekRead(uint32_t loc) = 0; + + /** + \brief Seeks the stream to a particular location for writing + * + * If the location passed exceeds the length of the stream, then it will seek to the end. + * Returns the location it ended up at (useful if you seek to the end) to get the file position + */ + virtual uint32_t seekWrite(uint32_t loc) = 0; + + /** + \brief Reads from the stream into a buffer. + + \param[out] mem The buffer to read the stream into. + \param[in] len The number of bytes to stream into the buffer + + \return Returns the actual number of bytes read. If not equal to the length requested, then reached end of stream. + */ + virtual uint32_t read(void *mem,uint32_t len) = 0; + + + /** + \brief Reads from the stream into a buffer but does not advance the read location. + + \param[out] mem The buffer to read the stream into. + \param[in] len The number of bytes to stream into the buffer + + \return Returns the actual number of bytes read. If not equal to the length requested, then reached end of stream. + */ + virtual uint32_t peek(void *mem,uint32_t len) = 0; + + /** + \brief Writes a buffer of memory to the stream + + \param[in] mem The address of a buffer of memory to send to the stream. + \param[in] len The number of bytes to send to the stream. + + \return Returns the actual number of bytes sent to the stream. If not equal to the length specific, then the stream is full or unable to write for some reason. + */ + virtual uint32_t write(const void *mem,uint32_t len) = 0; + + /** + \brief Reports the current stream location read aqccess. + + \return Returns the current stream read location. + */ + virtual uint32_t tellRead() const = 0; + + /** + \brief Reports the current stream location for write access. + + \return Returns the current stream write location. + */ + virtual uint32_t tellWrite() const = 0; + + /** + \brief Causes any temporarily cached data to be flushed to the stream. + */ + virtual void flush() = 0; + + /** + \brief Close the stream. + */ + virtual void close() {} + + void release() + { + PX_DELETE_THIS; + } + + static PX_INLINE bool isBigEndian() + { + int32_t i = 1; + return *(reinterpret_cast(&i))==0; + } + + PX_INLINE void swap2Bytes(void* _data) const + { + char *data = static_cast(_data); + char one_byte; + one_byte = data[0]; data[0] = data[1]; data[1] = one_byte; + } + + PX_INLINE void swap4Bytes(void* _data) const + { + char *data = static_cast(_data); + char one_byte; + one_byte = data[0]; data[0] = data[3]; data[3] = one_byte; + one_byte = data[1]; data[1] = data[2]; data[2] = one_byte; + } + + PX_INLINE void swap8Bytes(void *_data) const + { + char *data = static_cast(_data); + char one_byte; + one_byte = data[0]; data[0] = data[7]; data[7] = one_byte; + one_byte = data[1]; data[1] = data[6]; data[6] = one_byte; + one_byte = data[2]; data[2] = data[5]; data[5] = one_byte; + one_byte = data[3]; data[3] = data[4]; data[4] = one_byte; + } + + + PX_INLINE void storeDword(uint32_t v) + { + if ( mEndianSwap ) + swap4Bytes(&v); + + write(&v,sizeof(v)); + } + + PX_INLINE void storeFloat(float v) + { + if ( mEndianSwap ) + swap4Bytes(&v); + write(&v,sizeof(v)); + } + + PX_INLINE void storeDouble(double v) + { + if ( mEndianSwap ) + swap8Bytes(&v); + write(&v,sizeof(v)); + } + + PX_INLINE void storeByte(uint8_t b) + { + write(&b,sizeof(b)); + } + + PX_INLINE void storeWord(uint16_t w) + { + if ( mEndianSwap ) + swap2Bytes(&w); + write(&w,sizeof(w)); + } + + uint8_t readByte() + { + uint8_t v=0; + read(&v,sizeof(v)); + return v; + } + + uint16_t readWord() + { + uint16_t v=0; + read(&v,sizeof(v)); + if ( mEndianSwap ) + swap2Bytes(&v); + return v; + } + + uint32_t readDword() + { + uint32_t v=0; + read(&v,sizeof(v)); + if ( mEndianSwap ) + swap4Bytes(&v); + return v; + } + + float readFloat() + { + float v=0; + read(&v,sizeof(v)); + if ( mEndianSwap ) + swap4Bytes(&v); + return v; + } + + double readDouble() + { + double v=0; + read(&v,sizeof(v)); + if ( mEndianSwap ) + swap8Bytes(&v); + return v; + } + +private: + bool mEndianSwap; // whether or not the endian should be swapped on the current platform + EndianMode mEndianMode; // the current endian mode behavior for the stream +}; + +PX_POP_PACK + +#if !PX_DOXYGEN +} // end of namespace + +using namespace general_PxIOStream2; + +namespace general_PxIOStream = general_PxIOStream2; + +} // end of namespace +#endif + + +#endif // PSFILEBUFFER_PXFILEBUF_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAlignedMalloc.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAlignedMalloc.h new file mode 100644 index 000000000..001ebeda6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAlignedMalloc.h @@ -0,0 +1,94 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ALIGNED_MALLOC_H +#define PX_ALIGNED_MALLOC_H + +#include "PxUserAllocated.h" + +/*! +Allocate aligned memory. +Alignment must be a power of 2! +-- should be templated by a base allocator +*/ + +#if !PX_DOXYGEN +namespace physx +{ +#endif + /** + Allocator, which is used to access the global PxAllocatorCallback instance + (used for dynamic data types template instantiation), which can align memory + */ + + // SCS: AlignedMalloc with 3 params not found, seems not used on PC either + // disabled for now to avoid GCC error + + template + class PxAlignedAllocator : public BaseAllocator + { + public: + PxAlignedAllocator(const BaseAllocator& base = BaseAllocator()) : BaseAllocator(base) + { + } + + void* allocate(size_t size, const char* file, int line, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + + size_t pad = N - 1 + sizeof(size_t); // store offset for delete. + uint8_t* base = reinterpret_cast(BaseAllocator::allocate(size + pad, file, line)); + if (!base) + return NULL; + + uint8_t* ptr = reinterpret_cast(size_t(base + pad) & ~(size_t(N) - 1)); // aligned pointer, ensuring N + // is a size_t + // wide mask + reinterpret_cast(ptr)[-1] = size_t(ptr - base); // store offset + + return ptr; + } + + void deallocate(void* ptr, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + + if (ptr == NULL) + return; + + uint8_t* base = reinterpret_cast(ptr) - reinterpret_cast(ptr)[-1]; + BaseAllocator::deallocate(base); + } + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAlloca.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAlloca.h new file mode 100644 index 000000000..44d7f8172 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAlloca.h @@ -0,0 +1,90 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ALLOCA_H +#define PX_ALLOCA_H + +#include "foundation/PxTempAllocator.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +template +class PxScopedPointer : private Alloc +{ + public: + ~PxScopedPointer() + { + if(mOwned) + Alloc::deallocate(mPointer); + } + + operator T*() const + { + return mPointer; + } + + T* mPointer; + bool mOwned; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + + // Don't use inline for alloca !!! +#if PX_WINDOWS_FAMILY + #include + #define PxAlloca(x) _alloca(x) +#elif PX_LINUX + #include + #define PxAlloca(x) alloca(x) +#elif PX_APPLE_FAMILY + #include + #define PxAlloca(x) alloca(x) +#elif PX_SWITCH + #include + #define PxAlloca(x) alloca(x) +#endif + +#define PxAllocaAligned(x, alignment) ((size_t(PxAlloca(x + alignment)) + (alignment - 1)) & ~size_t(alignment - 1)) + +/*! Stack allocation for \c count instances of \c type. Falling back to temp allocator if using more than 4kB. */ +#define PX_ALLOCA(var, type, count) \ + physx::PxScopedPointer var; \ + { \ + const uint32_t size = sizeof(type) * (count); \ + var.mOwned = size > 4096; \ + if(var.mOwned) \ + var.mPointer = reinterpret_cast(physx::PxTempAllocator().allocate(size, PX_FL)); \ + else \ + var.mPointer = reinterpret_cast(PxAlloca(size)); \ + } +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAllocator.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAllocator.h new file mode 100644 index 000000000..3c7eb5551 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAllocator.h @@ -0,0 +1,257 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ALLOCATOR_H +#define PX_ALLOCATOR_H + +#include "foundation/PxAllocatorCallback.h" +#include "foundation/PxAssert.h" +#include "foundation/PxFoundation.h" +#include "foundation/PxIO.h" +#include + +#if PX_VC + #pragma warning(push) + #pragma warning(disable : 4577) +#endif + +#if PX_WINDOWS_FAMILY +#if(_MSC_VER >= 1923) + #include +#else + #include +#endif +#endif + +#if(PX_APPLE_FAMILY) + #include +#endif + +#include + +#if PX_VC + #pragma warning(pop) +#endif + +// PT: the rules are simple: +// - PX_ALLOC/PX_ALLOCATE/PX_FREE is similar to malloc/free. Use that for POD/anything that doesn't need ctor/dtor. +// - PX_NEW/PX_DELETE is similar to new/delete. Use that for anything that needs a ctor/dtor. +// - Everything goes through the user allocator. +// - Inherit from PxUserAllocated to PX_NEW something. Do it even on small classes, it's free. +// - You cannot PX_NEW a POD. Use PX_ALLOC. + +#define PX_ALLOC(n, name) physx::PxAllocator().allocate(n, PX_FL) + +// PT: use this one to reduce the amount of visible reinterpret_cast +#define PX_ALLOCATE(type, count, name) reinterpret_cast(PX_ALLOC(count*sizeof(type), name)) + +#define PX_FREE(x) \ + if(x) \ + { \ + physx::PxAllocator().deallocate(x); \ + x = NULL; \ + } + +#define PX_FREE_THIS physx::PxAllocator().deallocate(this) + +// PT: placement new is only needed when you control where the object is created (i.e. you already have an address for it before creating the object). +// So there are basically 2 legitimate placement new usages in PhysX: +// - binary deserialization +// - arrays/pools +// If you end up writing "PX_PLACEMENT_NEW(PX_ALLOC(sizeof(X), "X")", consider deriving X from PxUserAllocated and using PX_NEW instead. +#define PX_PLACEMENT_NEW(p, T) new (p) T +#define PX_NEW(T) new (physx::PxReflectionAllocator(), PX_FL) T +#define PX_DELETE_THIS delete this +#define PX_DELETE(x) if(x) { delete x; x = NULL; } +#define PX_DELETE_ARRAY(x) if(x) { delete []x; x = NULL; } +#define PX_RELEASE(x) if(x) { x->release(); x = NULL; } + +#if !PX_DOXYGEN +namespace physx +{ +#endif + /** + \brief Allocator used to access the global PxAllocatorCallback instance without providing additional information. + */ + class PxAllocator + { + public: + PX_FORCE_INLINE PxAllocator(const char* = NULL){} + + static PX_FORCE_INLINE void* allocate(size_t size, const char* file, int line, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + return size ? PxGetBroadcastAllocator()->allocate(size, "", file, line) : NULL; + } + + static PX_FORCE_INLINE void deallocate(void* ptr, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + if(ptr) + PxGetBroadcastAllocator()->deallocate(ptr); + } + }; + + /** + * \brief Bootstrap allocator using malloc/free. + * Don't use unless your objects get allocated before foundation is initialized. + */ + class PxRawAllocator + { + public: + PxRawAllocator(const char* = 0) {} + + static PX_FORCE_INLINE void* allocate(size_t size, const char*, int, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + // malloc returns valid pointer for size==0, no need to check + return ::malloc(size); + } + + static PX_FORCE_INLINE void deallocate(void* ptr, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + // free(0) is guaranteed to have no side effect, no need to check + ::free(ptr); + } + }; + + /** + \brief Virtual allocator callback used to provide run-time defined allocators to foundation types like Array or Bitmap. + This is used by VirtualAllocator + */ + class PxVirtualAllocatorCallback + { + public: + PxVirtualAllocatorCallback() {} + virtual ~PxVirtualAllocatorCallback() {} + + virtual void* allocate(size_t size, int group, const char* file, int line) = 0; + virtual void deallocate(void* ptr) = 0; + }; + + /** + \brief Virtual allocator to be used by foundation types to provide run-time defined allocators. + Due to the fact that Array extends its allocator, rather than contains a reference/pointer to it, the VirtualAllocator must + be a concrete type containing a pointer to a virtual callback. The callback may not be available at instantiation time, + therefore methods are provided to set the callback later. + */ + class PxVirtualAllocator + { + public: + PxVirtualAllocator(PxVirtualAllocatorCallback* callback = NULL, int group = 0) : mCallback(callback), mGroup(group) {} + + PX_FORCE_INLINE void* allocate(size_t size, const char* file, int line, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + PX_ASSERT(mCallback); + if (size) + return mCallback->allocate(size, mGroup, file, line); + return NULL; + } + + PX_FORCE_INLINE void deallocate(void* ptr, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + PX_ASSERT(mCallback); + if (ptr) + mCallback->deallocate(ptr); + } + + PX_FORCE_INLINE void setCallback(PxVirtualAllocatorCallback* callback) + { + mCallback = callback; + } + + PX_FORCE_INLINE PxVirtualAllocatorCallback* getCallback() + { + return mCallback; + } + + private: + PxVirtualAllocatorCallback* mCallback; + const int mGroup; + PxVirtualAllocator& operator=(const PxVirtualAllocator&); + }; + + /** + \brief Allocator used to access the global PxAllocatorCallback instance using a static name derived from T. + */ + template + class PxReflectionAllocator + { + static const char* getName(bool reportAllocationNames) + { + if(!reportAllocationNames) + return ""; +#if PX_GCC_FAMILY + return __PRETTY_FUNCTION__; +#else + // name() calls malloc(), raw_name() wouldn't + return typeid(T).name(); +#endif + } + + public: + PxReflectionAllocator(const PxEMPTY) {} + PxReflectionAllocator(const char* = 0) {} + + inline PxReflectionAllocator(const PxReflectionAllocator&) {} + + static PX_FORCE_INLINE void* allocate(size_t size, const char* filename, int line, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + if(!size) + return NULL; + + bool reportAllocationNames; + PxAllocatorCallback* cb = PxGetBroadcastAllocator(&reportAllocationNames); + + return cb->allocate(size, getName(reportAllocationNames), filename, line); + } + + static PX_FORCE_INLINE void deallocate(void* ptr, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + if(ptr) + PxGetBroadcastAllocator()->deallocate(ptr); + } + }; + + template + struct PxAllocatorTraits + { + typedef PxReflectionAllocator Type; + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAllocatorCallback.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAllocatorCallback.h new file mode 100644 index 000000000..9c6f37a24 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAllocatorCallback.h @@ -0,0 +1,90 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ALLOCATOR_CALLBACK_H +#define PX_ALLOCATOR_CALLBACK_H + + +#include "foundation/PxFoundationConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Abstract base class for an application defined memory allocator that can be used by the Nv library. + +\note The SDK state should not be modified from within any allocation/free function. + +Threading: All methods of this class should be thread safe as it can be called from the user thread +or the physics processing thread(s). +*/ + +class PxAllocatorCallback +{ + public: + + virtual ~PxAllocatorCallback() + { + } + + /** + \brief Allocates size bytes of memory, which must be 16-byte aligned. + + This method should never return NULL. If you run out of memory, then + you should terminate the app or take some other appropriate action. + + Threading: This function should be thread safe as it can be called in the context of the user thread + and physics processing thread(s). + + \param size Number of bytes to allocate. + \param typeName Name of the datatype that is being allocated + \param filename The source file which allocated the memory + \param line The source line which allocated the memory + \return The allocated block of memory. + */ + virtual void* allocate(size_t size, const char* typeName, const char* filename, int line) = 0; + + /** + \brief Frees memory previously allocated by allocate(). + + Threading: This function should be thread safe as it can be called in the context of the user thread + and physics processing thread(s). + + \param ptr Memory to free. + */ + virtual void deallocate(void* ptr) = 0; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAoS.h new file mode 100644 index 000000000..a42f63e55 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAoS.h @@ -0,0 +1,41 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_AOS_H +#define PX_AOS_H + + +#if PX_WINDOWS && !PX_NEON +#include "windows/PxWindowsAoS.h" +#elif(PX_UNIX_FAMILY || PX_SWITCH) +#include "unix/PxUnixAoS.h" +#else +#error "Platform not supported!" +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxArray.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxArray.h new file mode 100644 index 000000000..39b6c37f0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxArray.h @@ -0,0 +1,724 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ARRAY_H +#define PX_ARRAY_H + +#include "foundation/PxAssert.h" +#include "foundation/PxMathIntrinsics.h" +#include "foundation/PxAllocator.h" +#include "foundation/PxBasicTemplates.h" +#include "foundation/PxMemory.h" +#include "foundation/PxIO.h" + +namespace physx +{ + +/*! +An array is a sequential container. + +Implementation note +* entries between 0 and size are valid objects +* we use inheritance to build this because the array is included inline in a lot + of objects and we want the allocator to take no space if it's not stateful, which + aggregation doesn't allow. Also, we want the metadata at the front for the inline + case where the allocator contains some inline storage space +*/ +template ::Type> +class PxArray : protected Alloc +{ + public: + typedef T* Iterator; + typedef const T* ConstIterator; + + explicit PxArray(const PxEMPTY v) : Alloc(v) + { + if(mData) + mCapacity |= PX_SIGN_BITMASK; + } + + /*! + Default array constructor. Initialize an empty array + */ + PX_INLINE explicit PxArray(const Alloc& alloc = Alloc()) : Alloc(alloc), mData(0), mSize(0), mCapacity(0) + { + } + + /*! + Initialize array with given capacity + */ + PX_INLINE explicit PxArray(uint32_t size, const T& a = T(), const Alloc& alloc = Alloc()) + : Alloc(alloc), mData(0), mSize(0), mCapacity(0) + { + resize(size, a); + } + + /*! + Copy-constructor. Copy all entries from other array + */ + template + PX_INLINE explicit PxArray(const PxArray& other, const Alloc& alloc = Alloc()) + : Alloc(alloc) + { + copy(other); + } + + // This is necessary else the basic default copy constructor is used in the case of both arrays being of the same + // template instance + // The C++ standard clearly states that a template constructor is never a copy constructor [2]. In other words, + // the presence of a template constructor does not suppress the implicit declaration of the copy constructor. + // Also never make a copy constructor explicit, or copy-initialization* will no longer work. This is because + // 'binding an rvalue to a const reference requires an accessible copy constructor' (http://gcc.gnu.org/bugs/) + // *http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-assignment-initializ + PX_INLINE PxArray(const PxArray& other, const Alloc& alloc = Alloc()) : Alloc(alloc) + { + copy(other); + } + + /*! + Initialize array with given length + */ + PX_INLINE explicit PxArray(const T* first, const T* last, const Alloc& alloc = Alloc()) + : Alloc(alloc), mSize(last < first ? 0 : uint32_t(last - first)), mCapacity(mSize) + { + mData = allocate(mSize); + copy(mData, mData + mSize, first); + } + + /*! + Destructor + */ + PX_INLINE ~PxArray() + { + destroy(mData, mData + mSize); + + if(capacity() && !isInUserMemory()) + deallocate(mData); + } + + /*! + Assignment operator. Copy content (deep-copy) + */ + template + PX_INLINE PxArray& operator=(const PxArray& rhs) + { + if(&rhs == this) + return *this; + + clear(); + reserve(rhs.mSize); + copy(mData, mData + rhs.mSize, rhs.mData); + + mSize = rhs.mSize; + return *this; + } + + PX_INLINE PxArray& operator=(const PxArray& t) // Needs to be declared, see comment at copy-constructor + { + return operator=(t); + } + + /*! + Array indexing operator. + \param i + The index of the element that will be returned. + \return + The element i in the array. + */ + PX_FORCE_INLINE const T& operator[](uint32_t i) const + { + PX_ASSERT(i < mSize); + return mData[i]; + } + + /*! + Array indexing operator. + \param i + The index of the element that will be returned. + \return + The element i in the array. + */ + PX_FORCE_INLINE T& operator[](uint32_t i) + { + PX_ASSERT(i < mSize); + return mData[i]; + } + + /*! + Returns a pointer to the initial element of the array. + \return + a pointer to the initial element of the array. + */ + PX_FORCE_INLINE ConstIterator begin() const + { + return mData; + } + + PX_FORCE_INLINE Iterator begin() + { + return mData; + } + + /*! + Returns an iterator beyond the last element of the array. Do not dereference. + \return + a pointer to the element beyond the last element of the array. + */ + + PX_FORCE_INLINE ConstIterator end() const + { + return mData + mSize; + } + + PX_FORCE_INLINE Iterator end() + { + return mData + mSize; + } + + /*! + Returns a reference to the first element of the array. Undefined if the array is empty. + \return a reference to the first element of the array + */ + + PX_FORCE_INLINE const T& front() const + { + PX_ASSERT(mSize); + return mData[0]; + } + + PX_FORCE_INLINE T& front() + { + PX_ASSERT(mSize); + return mData[0]; + } + + /*! + Returns a reference to the last element of the array. Undefined if the array is empty + \return a reference to the last element of the array + */ + + PX_FORCE_INLINE const T& back() const + { + PX_ASSERT(mSize); + return mData[mSize - 1]; + } + + PX_FORCE_INLINE T& back() + { + PX_ASSERT(mSize); + return mData[mSize - 1]; + } + + /*! + Returns the number of entries in the array. This can, and probably will, + differ from the array capacity. + \return + The number of of entries in the array. + */ + PX_FORCE_INLINE uint32_t size() const + { + return mSize; + } + + /*! + Clears the array. + */ + PX_INLINE void clear() + { + destroy(mData, mData + mSize); + mSize = 0; + } + + /*! + Returns whether the array is empty (i.e. whether its size is 0). + \return + true if the array is empty + */ + PX_FORCE_INLINE bool empty() const + { + return mSize == 0; + } + + /*! + Finds the first occurrence of an element in the array. + \param a + The element to find. + */ + + PX_INLINE Iterator find(const T& a) + { + uint32_t index; + for(index = 0; index < mSize && mData[index] != a; index++) + ; + return mData + index; + } + + PX_INLINE ConstIterator find(const T& a) const + { + uint32_t index; + for(index = 0; index < mSize && mData[index] != a; index++) + ; + return mData + index; + } + + ///////////////////////////////////////////////////////////////////////// + /*! + Adds one element to the end of the array. Operation is O(1). + \param a + The element that will be added to this array. + */ + ///////////////////////////////////////////////////////////////////////// + + PX_FORCE_INLINE T& pushBack(const T& a) + { + if(capacity() <= mSize) + return growAndPushBack(a); + + PX_PLACEMENT_NEW(reinterpret_cast(mData + mSize), T)(a); + + return mData[mSize++]; + } + + ///////////////////////////////////////////////////////////////////////// + /*! + Returns the element at the end of the array. Only legal if the array is non-empty. + */ + ///////////////////////////////////////////////////////////////////////// + PX_INLINE T popBack() + { + PX_ASSERT(mSize); + T t = mData[mSize - 1]; + + mData[--mSize].~T(); + + return t; + } + + ///////////////////////////////////////////////////////////////////////// + /*! + Construct one element at the end of the array. Operation is O(1). + */ + ///////////////////////////////////////////////////////////////////////// + PX_INLINE T& insert() + { + if(capacity() <= mSize) + grow(capacityIncrement()); + + T* ptr = mData + mSize++; + PX_PLACEMENT_NEW(ptr, T); // not 'T()' because PODs should not get default-initialized. + return *ptr; + } + + ///////////////////////////////////////////////////////////////////////// + /*! + Subtracts the element on position i from the array and replace it with + the last element. + Operation is O(1) + \param i + The position of the element that will be subtracted from this array. + */ + ///////////////////////////////////////////////////////////////////////// + PX_INLINE void replaceWithLast(uint32_t i) + { + PX_ASSERT(i < mSize); + mData[i] = mData[--mSize]; + + mData[mSize].~T(); + } + + PX_INLINE void replaceWithLast(Iterator i) + { + replaceWithLast(static_cast(i - mData)); + } + + ///////////////////////////////////////////////////////////////////////// + /*! + Replaces the first occurrence of the element a with the last element + Operation is O(n) + \param a + The position of the element that will be subtracted from this array. + \return true if the element has been removed. + */ + ///////////////////////////////////////////////////////////////////////// + + PX_INLINE bool findAndReplaceWithLast(const T& a) + { + uint32_t index = 0; + while(index < mSize && mData[index] != a) + ++index; + if(index == mSize) + return false; + replaceWithLast(index); + return true; + } + + ///////////////////////////////////////////////////////////////////////// + /*! + Subtracts the element on position i from the array. Shift the entire + array one step. + Operation is O(n) + \param i + The position of the element that will be subtracted from this array. + */ + ///////////////////////////////////////////////////////////////////////// + PX_INLINE void remove(uint32_t i) + { + PX_ASSERT(i < mSize); + + T* it = mData + i; + it->~T(); + while (++i < mSize) + { + PX_PLACEMENT_NEW(it, T(mData[i])); + ++it; + it->~T(); + } + --mSize; + } + + ///////////////////////////////////////////////////////////////////////// + /*! + Removes a range from the array. Shifts the array so order is maintained. + Operation is O(n) + \param begin + The starting position of the element that will be subtracted from this array. + \param count + The number of elments that will be subtracted from this array. + */ + ///////////////////////////////////////////////////////////////////////// + PX_INLINE void removeRange(uint32_t begin, uint32_t count) + { + PX_ASSERT(begin < mSize); + PX_ASSERT((begin + count) <= mSize); + + for(uint32_t i = 0; i < count; i++) + mData[begin + i].~T(); // call the destructor on the ones being removed first. + + T* dest = &mData[begin]; // location we are copying the tail end objects to + T* src = &mData[begin + count]; // start of tail objects + uint32_t move_count = mSize - (begin + count); // compute remainder that needs to be copied down + + for(uint32_t i = 0; i < move_count; i++) + { + PX_PLACEMENT_NEW(dest, T(*src)); // copy the old one to the new location + src->~T(); // call the destructor on the old location + dest++; + src++; + } + mSize -= count; + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Resize array + */ + ////////////////////////////////////////////////////////////////////////// + PX_NOINLINE void resize(const uint32_t size, const T& a = T()); + + PX_NOINLINE void resizeUninitialized(const uint32_t size); + + ////////////////////////////////////////////////////////////////////////// + /*! + Resize array such that only as much memory is allocated to hold the + existing elements + */ + ////////////////////////////////////////////////////////////////////////// + PX_INLINE void shrink() + { + recreate(mSize); + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Deletes all array elements and frees memory. + */ + ////////////////////////////////////////////////////////////////////////// + PX_INLINE void reset() + { + resize(0); + shrink(); + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Resets or clears the array depending on occupancy. + */ + ////////////////////////////////////////////////////////////////////////// + PX_INLINE void resetOrClear() + { + const PxU32 c = capacity(); + const PxU32 s = size(); + if(s>=c/2) + clear(); + else + reset(); + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Ensure that the array has at least size capacity. + */ + ////////////////////////////////////////////////////////////////////////// + PX_INLINE void reserve(const uint32_t capacity) + { + if(capacity > this->capacity()) + grow(capacity); + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Query the capacity(allocated mem) for the array. + */ + ////////////////////////////////////////////////////////////////////////// + PX_FORCE_INLINE uint32_t capacity() const + { + return mCapacity & ~PX_SIGN_BITMASK; + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Unsafe function to force the size of the array + */ + ////////////////////////////////////////////////////////////////////////// + PX_FORCE_INLINE void forceSize_Unsafe(uint32_t size) + { + PX_ASSERT(size <= mCapacity); + mSize = size; + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Swap contents of an array without allocating temporary storage + */ + ////////////////////////////////////////////////////////////////////////// + PX_INLINE void swap(PxArray& other) + { + PxSwap(mData, other.mData); + PxSwap(mSize, other.mSize); + PxSwap(mCapacity, other.mCapacity); + } + + ////////////////////////////////////////////////////////////////////////// + /*! + Assign a range of values to this vector (resizes to length of range) + */ + ////////////////////////////////////////////////////////////////////////// + PX_INLINE void assign(const T* first, const T* last) + { + resizeUninitialized(uint32_t(last - first)); + copy(begin(), end(), first); + } + + // We need one bit to mark arrays that have been deserialized from a user-provided memory block. + // For alignment & memory saving purpose we store that bit in the rarely used capacity member. + PX_FORCE_INLINE uint32_t isInUserMemory() const + { + return mCapacity & PX_SIGN_BITMASK; + } + + /// return reference to allocator + PX_INLINE Alloc& getAllocator() + { + return *this; + } + + protected: + // constructor for where we don't own the memory + PxArray(T* memory, uint32_t size, uint32_t capacity, const Alloc& alloc = Alloc()) + : Alloc(alloc), mData(memory), mSize(size), mCapacity(capacity | PX_SIGN_BITMASK) + { + } + + template + PX_NOINLINE void copy(const PxArray& other); + + PX_INLINE T* allocate(uint32_t size, uint32_t* cookie=NULL) + { + // always call Alloc::allocate to respect cookie logic even if size is 0 + T* p = reinterpret_cast(Alloc::allocate(sizeof(T) * size, PX_FL, cookie)); + if(size > 0 && p) + { + PxMarkSerializedMemory(p, sizeof(T) * size); + } + return p; + } + + PX_INLINE void deallocate(void* mem, uint32_t* cookie=NULL) + { + Alloc::deallocate(mem, cookie); + } + + static PX_INLINE void create(T* first, T* last, const T& a) + { + for(; first < last; ++first) + ::PX_PLACEMENT_NEW(first, T(a)); + } + + static PX_INLINE void copy(T* first, T* last, const T* src) + { + if(last <= first) + return; + + for(; first < last; ++first, ++src) + ::PX_PLACEMENT_NEW(first, T(*src)); + } + + static PX_INLINE void destroy(T* first, T* last) + { + for(; first < last; ++first) + first->~T(); + } + + /*! + Called when pushBack() needs to grow the array. + \param a The element that will be added to this array. + */ + PX_NOINLINE T& growAndPushBack(const T& a); + + /*! + Resizes the available memory for the array. + + \param capacity + The number of entries that the set should be able to hold. + */ + PX_INLINE void grow(uint32_t capacity) + { + PX_ASSERT(this->capacity() < capacity); + recreate(capacity); + } + + /*! + Creates a new memory block, copies all entries to the new block and destroys old entries. + + \param capacity + The number of entries that the set should be able to hold. + */ + PX_NOINLINE void recreate(uint32_t capacity); + + // The idea here is to prevent accidental bugs with pushBack or insert. Unfortunately + // it interacts badly with InlineArrays with smaller inline allocations. + // TODO(dsequeira): policy template arg, this is exactly what they're for. + PX_INLINE uint32_t capacityIncrement() const + { + const uint32_t capacity = this->capacity(); + return capacity == 0 ? 1 : capacity * 2; + } + + T* mData; + uint32_t mSize; + uint32_t mCapacity; +}; + +template +PX_NOINLINE void PxArray::resize(const uint32_t size, const T& a) +{ + reserve(size); + create(mData + mSize, mData + size, a); + destroy(mData + size, mData + mSize); + mSize = size; +} + +template +template +PX_NOINLINE void PxArray::copy(const PxArray& other) +{ + if(!other.empty()) + { + mData = allocate(mSize = mCapacity = other.size()); + copy(mData, mData + mSize, other.begin()); + } + else + { + mData = NULL; + mSize = 0; + mCapacity = 0; + } + + // mData = allocate(other.mSize); + // mSize = other.mSize; + // mCapacity = other.mSize; + // copy(mData, mData + mSize, other.mData); +} + +template +PX_NOINLINE void PxArray::resizeUninitialized(const uint32_t size) +{ + reserve(size); + mSize = size; +} + +template +PX_NOINLINE T& PxArray::growAndPushBack(const T& a) +{ + const uint32_t capacity = capacityIncrement(); + + uint32_t cookie = 0; + T* newData = allocate(capacity, &cookie); + PX_ASSERT((!capacity) || (newData && (newData != mData))); + copy(newData, newData + mSize, mData); + + // inserting element before destroying old array + // avoids referencing destroyed object when duplicating array element. + PX_PLACEMENT_NEW(reinterpret_cast(newData + mSize), T)(a); + + destroy(mData, mData + mSize); + if(!isInUserMemory()) + deallocate(mData, &cookie); + + mData = newData; + mCapacity = capacity; + + return mData[mSize++]; +} + +template +PX_NOINLINE void PxArray::recreate(uint32_t capacity) +{ + uint32_t cookie = 0; + T* newData = allocate(capacity, &cookie); + PX_ASSERT((!capacity) || (newData && (newData != mData))); + + copy(newData, newData + mSize, mData); + destroy(mData, mData + mSize); + if(!isInUserMemory()) + deallocate(mData, &cookie); + + mData = newData; + mCapacity = capacity; +} + +template +PX_INLINE void swap(PxArray& x, PxArray& y) +{ + x.swap(y); +} + +} // namespace physx + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAssert.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAssert.h new file mode 100644 index 000000000..465ce491d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAssert.h @@ -0,0 +1,85 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ASSERT_H +#define PX_ASSERT_H + +#include +#include "foundation/PxFoundationConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** + * \brief Built-in assert function + */ +PX_FOUNDATION_API void PxAssert(const char* exp, const char* file, int line, bool& ignore); + +#if !PX_ENABLE_ASSERTS + #define PX_ASSERT(exp) ((void)0) + #define PX_ALWAYS_ASSERT_MESSAGE(exp) ((void)0) + #define PX_ASSERT_WITH_MESSAGE(condition, message) ((void)0) +#else +#if PX_VC + #define PX_CODE_ANALYSIS_ASSUME(exp) \ + __analysis_assume(!!(exp)) // This macro will be used to get rid of analysis warning messages if a PX_ASSERT is used + // to "guard" illegal mem access, for example. +#else + #define PX_CODE_ANALYSIS_ASSUME(exp) +#endif + #define PX_ASSERT(exp) \ + { \ + static bool _ignore = false; \ + ((void)((!!(exp)) || (!_ignore && (physx::PxAssert(#exp, PX_FL, _ignore), false)))); \ + PX_CODE_ANALYSIS_ASSUME(exp); \ + } + #define PX_ALWAYS_ASSERT_MESSAGE(exp) \ + { \ + static bool _ignore = false; \ + if(!_ignore) \ + physx::PxAssert(exp, PX_FL, _ignore); \ + } + #define PX_ASSERT_WITH_MESSAGE(exp, message) \ + { \ + static bool _ignore = false; \ + ((void)((!!(exp)) || (!_ignore && (physx::PxAssert(message, PX_FL, _ignore), false)))); \ + PX_CODE_ANALYSIS_ASSUME(exp); \ + } +#endif // !PX_ENABLE_ASSERTS + +#define PX_ALWAYS_ASSERT() PX_ASSERT(0) + +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAtomic.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAtomic.h new file mode 100644 index 000000000..6254ffb94 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxAtomic.h @@ -0,0 +1,79 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ATOMIC_H +#define PX_ATOMIC_H + +#include "foundation/PxFoundationConfig.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +/* set *dest equal to val. Return the old value of *dest */ +PX_FOUNDATION_API PxI32 PxAtomicExchange(volatile PxI32* dest, PxI32 val); +PX_FOUNDATION_API PxI64 PxAtomicExchange(volatile PxI64* dest, PxI64 val); + +/* if *dest == comp, replace with exch. Return original value of *dest */ +PX_FOUNDATION_API PxI32 PxAtomicCompareExchange(volatile PxI32* dest, PxI32 exch, PxI32 comp); +PX_FOUNDATION_API PxI64 PxAtomicCompareExchange(volatile PxI64* dest, PxI64 exch, PxI64 comp); + +/* if *dest == comp, replace with exch. Return original value of *dest */ +PX_FOUNDATION_API void* PxAtomicCompareExchangePointer(volatile void** dest, void* exch, void* comp); + +/* increment the specified location. Return the incremented value */ +PX_FOUNDATION_API PxI32 PxAtomicIncrement(volatile PxI32* val); +PX_FOUNDATION_API PxI64 PxAtomicIncrement(volatile PxI64* val); + +/* decrement the specified location. Return the decremented value */ +PX_FOUNDATION_API PxI32 PxAtomicDecrement(volatile PxI32* val); +PX_FOUNDATION_API PxI64 PxAtomicDecrement(volatile PxI64* val); + +/* add delta to *val. Return the new value */ +PX_FOUNDATION_API PxI32 PxAtomicAdd(volatile PxI32* val, PxI32 delta); +PX_FOUNDATION_API PxI64 PxAtomicAdd(volatile PxI64* val, PxI64 delta); + +/* compute the maximum of dest and val. Return the new value */ +PX_FOUNDATION_API PxI32 PxAtomicMax(volatile PxI32* val, PxI32 val2); +PX_FOUNDATION_API PxI64 PxAtomicMax(volatile PxI64* val, PxI64 val2); + +/* or mask to *val. Return the new value */ +PX_FOUNDATION_API PxI32 PxAtomicOr(volatile PxI32* val, PxI32 mask); +PX_FOUNDATION_API PxI64 PxAtomicOr(volatile PxI64* val, PxI64 mask); + +/* and mask to *val. Return the new value */ +PX_FOUNDATION_API PxI32 PxAtomicAnd(volatile PxI32* val, PxI32 mask); +PX_FOUNDATION_API PxI64 PxAtomicAnd(volatile PxI64* val, PxI64 mask); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBasicTemplates.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBasicTemplates.h new file mode 100644 index 000000000..c8a895d2f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBasicTemplates.h @@ -0,0 +1,145 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BASIC_TEMPLATES_H +#define PX_BASIC_TEMPLATES_H + +#include "foundation/PxPreprocessor.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + template + struct PxEqual + { + bool operator()(const A& a, const A& b) const + { + return a == b; + } + }; + + template + struct PxLess + { + bool operator()(const A& a, const A& b) const + { + return a < b; + } + }; + + template + struct PxGreater + { + bool operator()(const A& a, const A& b) const + { + return a > b; + } + }; + + template + class PxPair + { + public: + F first; + S second; + PX_CUDA_CALLABLE PX_INLINE PxPair() : first(F()), second(S()) + { + } + PX_CUDA_CALLABLE PX_INLINE PxPair(const F& f, const S& s) : first(f), second(s) + { + } + PX_CUDA_CALLABLE PX_INLINE PxPair(const PxPair& p) : first(p.first), second(p.second) + { + } + PX_CUDA_CALLABLE PX_INLINE PxPair& operator=(const PxPair& p) + { + first = p.first; + second = p.second; + return *this; + } + PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxPair& p) const + { + return first == p.first && second == p.second; + } + PX_CUDA_CALLABLE PX_INLINE bool operator<(const PxPair& p) const + { + if (first < p.first) + return true; + else + return !(p.first < first) && (second < p.second); + } + }; + + template + struct PxLogTwo + { + static const unsigned int value = PxLogTwo<(A >> 1)>::value + 1; + }; + template <> + struct PxLogTwo<1> + { + static const unsigned int value = 0; + }; + + template + struct PxUnConst + { + typedef T Type; + }; + template + struct PxUnConst + { + typedef T Type; + }; + + template + T PxPointerOffset(void* p, ptrdiff_t offset) + { + return reinterpret_cast(reinterpret_cast(p) + offset); + } + template + T PxPointerOffset(const void* p, ptrdiff_t offset) + { + return reinterpret_cast(reinterpret_cast(p) + offset); + } + + template + PX_CUDA_CALLABLE PX_INLINE void PxSwap(T& x, T& y) + { + const T tmp = x; + x = y; + y = tmp; + } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitAndData.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitAndData.h new file mode 100644 index 000000000..a7cea4fbb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitAndData.h @@ -0,0 +1,84 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BIT_AND_DATA_H +#define PX_BIT_AND_DATA_H + +#include "foundation/PxIO.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +template +class PxBitAndDataT +{ + public: + PX_FORCE_INLINE PxBitAndDataT(const PxEMPTY) + { + } + PX_FORCE_INLINE PxBitAndDataT() : mData(0) + { + } + PX_FORCE_INLINE PxBitAndDataT(storageType data, bool bit = false) + { + mData = bit ? storageType(data | bitMask) : data; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE operator storageType() const + { + return storageType(mData & ~bitMask); + } + PX_CUDA_CALLABLE PX_FORCE_INLINE void setBit() + { + mData |= bitMask; + } + PX_CUDA_CALLABLE PX_FORCE_INLINE void clearBit() + { + mData &= ~bitMask; + } + PX_CUDA_CALLABLE PX_FORCE_INLINE storageType isBitSet() const + { + return storageType(mData & bitMask); + } + + protected: + storageType mData; +}; +typedef PxBitAndDataT PxBitAndByte; +typedef PxBitAndDataT PxBitAndWord; +typedef PxBitAndDataT PxBitAndDword; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitMap.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitMap.h new file mode 100644 index 000000000..d504cc14f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitMap.h @@ -0,0 +1,531 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BITMAP_H +#define PX_BITMAP_H + +#include "foundation/PxAssert.h" +#include "foundation/PxMath.h" +#include "foundation/PxMemory.h" +#include "foundation/PxAllocator.h" +#include "foundation/PxUserAllocated.h" +#include "foundation/PxIntrinsics.h" +#include "foundation/PxBitUtils.h" +#include "foundation/PxConstructor.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + /*! + Allocation helper with cookie parameter that can be overloaded for pinned memory support + */ + template + PX_INLINE void* PxBitMapAlloc(AllocT& a, PxU32 bytes, const char* file, int line, uint32_t* /*cookie*/) + { + return a.allocate(bytes, file, line); + } + + /*! + Deallocation helper with cookie parameter that can be overloaded for pinned memory support + */ + template + PX_INLINE void PxBitMapDealloc(AllocT& a, void* ptr, uint32_t* /*cookie*/) + { + a.deallocate(ptr); + } + + /*! + Hold a bitmap with operations to set,reset or test given bit. + + We inhibit copy to prevent unintentional copies. If a copy is desired copy() should be used or + alternatively a copy constructor implemented. + */ + template + class PxBitMapBase : public PxUserAllocated + { + PX_NOCOPY(PxBitMapBase) + + public: + + // PX_SERIALIZATION + /* todo: explicit */ PxBitMapBase(const PxEMPTY) + { + if(mMap) + mWordCount |= PX_SIGN_BITMASK; + } + //~PX_SERIALIZATION + + PX_INLINE PxBitMapBase(const PxAllocator& allocator) : mMap(0), mWordCount(0), mAllocator(allocator) {} + + PX_INLINE PxBitMapBase() : mMap(0), mWordCount(0) {} + + PX_INLINE ~PxBitMapBase() + { + release(); + } + + PX_INLINE void release() + { + if(mMap && !isInUserMemory()) + PxBitMapDealloc(mAllocator, mMap, NULL); + mMap = NULL; + } + + PX_FORCE_INLINE PxAllocator& getAllocator() { return mAllocator; } + + PX_INLINE void growAndSet(PxU32 index) + { + extend(index + 1); + mMap[index >> 5] |= 1 << (index & 31); + } + + PX_INLINE void growAndReset(PxU32 index) + { + extend(index + 1); + mMap[index >> 5] &= ~(1 << (index & 31)); + } + + PX_INLINE PxIntBool boundedTest(PxU32 index) const + { + return PxIntBool(index >> 5 >= getWordCount() ? PxIntFalse : (mMap[index >> 5] & (1 << (index & 31)))); + } + + PX_INLINE void boundedReset(PxU32 index) + { + if((index >> 5) < getWordCount()) + mMap[index >> 5] &= ~(1 << (index & 31)); + } + + // Special optimized versions, when you _know_ your index is in range + PX_INLINE void set(PxU32 index) + { + PX_ASSERT(index> 5] |= 1 << (index & 31); + } + + PX_INLINE void reset(PxU32 index) + { + PX_ASSERT(index> 5] &= ~(1 << (index & 31)); + } + + PX_INLINE PxIntBool test(PxU32 index) const + { + PX_ASSERT(index> 5] & (1 << (index & 31))); + } + + // nibble == 4 bits + PX_INLINE PxU32 getNibbleFast(PxU32 nibIndex) const + { + const PxU32 bitIndex = nibIndex << 2; + PX_ASSERT(bitIndex < getWordCount() * 32); + return (mMap[bitIndex >> 5] >> (bitIndex & 31)) & 0xf; + } + + PX_INLINE void andNibbleFast(PxU32 nibIndex, PxU32 mask) + { + //TODO: there has to be a faster way... + const PxU32 bitIndex = nibIndex << 2; + const PxU32 shift = (bitIndex & 31); + const PxU32 nibMask = (0xfu << shift); + + PX_ASSERT(bitIndex < getWordCount() * 32); + + mMap[bitIndex >> 5] &= ((mask << shift) | ~nibMask); + } + + PX_INLINE void orNibbleFast(PxU32 nibIndex, PxU32 mask) + { + PX_ASSERT(!(mask & ~0xfu)); //check extra bits are not set + + const PxU32 bitIndex = nibIndex << 2; + const PxU32 shift = bitIndex & 31; + + PX_ASSERT(bitIndex < getWordCount() * 32); + + mMap[bitIndex >> 5] |= (mask << shift); + } + + void clear() + { + PxMemSet(mMap, 0, getWordCount() * sizeof(PxU32)); + } + + void resizeAndClear(PxU32 newBitCount) + { + extendUninitialized(newBitCount); + PxMemSet(mMap, 0, getWordCount() * sizeof(PxU32)); + } + + void setEmpty() + { + mMap = NULL; + mWordCount = 0; + } + + void setWords(PxU32* map, PxU32 wordCount) + { + mMap = map; + mWordCount = wordCount | PX_SIGN_BITMASK; + } + + // !!! only sets /last/ bit to value + void resize(PxU32 newBitCount, bool value = false) + { + PX_ASSERT(!value); // only new class supports this + PX_UNUSED(value); + extend(newBitCount); + } + + PX_FORCE_INLINE PxU32 size() const { return getWordCount() * 32; } + + void copy(const PxBitMapBase& a) + { + extendUninitialized(a.getWordCount() << 5); + PxMemCopy(mMap, a.mMap, a.getWordCount() * sizeof(PxU32)); + if(getWordCount() > a.getWordCount()) + PxMemSet(mMap + a.getWordCount(), 0, (getWordCount() - a.getWordCount()) * sizeof(PxU32)); + } + + PX_INLINE PxU32 count() const + { + // NOTE: we can probably do this faster, since the last steps in PxBitCount can be defered to + // the end of the seq. + 64/128bits at a time + native bit counting instructions(360 is fast non micro code). + PxU32 count = 0; + const PxU32 wordCount = getWordCount(); + for(PxU32 i = 0; i 0;) + { + if(mMap[i]) + return (i << 5) + PxHighestSetBit(mMap[i]); + } + return PxU32(0); + } + + bool hasAnyBitSet() const + { + const PxU32 wordCount = getWordCount(); + for(PxU32 i = 0; i + PX_INLINE void combineInPlace(const PxBitMapBase<_>& b) + { + combine1(b.mMap, b.getWordCount()); + } + + template + PX_INLINE void combine(const PxBitMapBase<_1>& a, const PxBitMapBase<_2>& b) + { + combine2(a.mMap, a.getWordCount(), b.mMap, b.getWordCount()); + } + + PX_FORCE_INLINE const PxU32* getWords() const { return mMap; } + PX_FORCE_INLINE PxU32* getWords() { return mMap; } + + // PX_SERIALIZATION + PX_FORCE_INLINE PxU32 getWordCount() const { return mWordCount & ~PX_SIGN_BITMASK; } + + // We need one bit to mark arrays that have been deserialized from a user-provided memory block. + PX_FORCE_INLINE PxU32 isInUserMemory() const { return mWordCount & PX_SIGN_BITMASK; } + //~PX_SERIALIZATION + + /*! + Iterate over indices in a bitmap + + This iterator is good because it finds the set bit without looping over the cached bits upto 31 times. + However it does require a variable shift. + */ + class Iterator + { + public: + static const PxU32 DONE = 0xffffffff; + + PX_INLINE Iterator(const PxBitMapBase &map) : mBitMap(map) + { + reset(); + } + + PX_INLINE Iterator& operator=(const Iterator& other) + { + PX_ASSERT(&mBitMap == &other.mBitMap); + mBlock = other.mBlock; + mIndex = other.mIndex; + return *this; + } + + PX_INLINE PxU32 getNext() + { + if(mBlock) + { + PxU32 block = mBlock; + PxU32 index = mIndex; + + const PxU32 bitIndex = index << 5 | PxLowestSetBit(block); + block &= block - 1; + PxU32 wordCount = mBitMap.getWordCount(); + while(!block && ++index < wordCount) + block = mBitMap.mMap[index]; + + mBlock = block; + mIndex = index; + + return bitIndex; + } + return DONE; + } + + PX_INLINE void reset() + { + PxU32 index = 0; + PxU32 block = 0; + + PxU32 wordCount = mBitMap.getWordCount(); + while(index < wordCount && ((block = mBitMap.mMap[index]) == 0)) + ++index; + + mBlock = block; + mIndex = index; + } + private: + PxU32 mBlock, mIndex; + const PxBitMapBase& mBitMap; + }; + + // DS: faster but less general: hasBits() must be true or getNext() is illegal so it is the calling code's responsibility to ensure that getNext() is not called illegally. + class PxLoopIterator + { + PX_NOCOPY(PxLoopIterator) + + public: + PX_FORCE_INLINE PxLoopIterator(const PxBitMapBase &map) : mMap(map.getWords()), mBlock(0), mIndex(-1), mWordCount(PxI32(map.getWordCount())) {} + + PX_FORCE_INLINE bool hasBits() + { + PX_ASSERT(mIndex> 5; + if (newWordCount > getWordCount()) + { + uint32_t cookie = 0; + void* newMap = PxBitMapAlloc(mAllocator, newWordCount * sizeof(PxU32), PX_FL, &cookie); + if (mMap) + { + PxMemCopy(newMap, mMap, getWordCount() * sizeof(PxU32)); + if (!isInUserMemory()) + PxBitMapDealloc(mAllocator, mMap, &cookie); + } + mMap = reinterpret_cast(newMap); + PxMemSet(mMap + getWordCount(), 0, (newWordCount - getWordCount()) * sizeof(PxU32)); + // also resets the isInUserMemory bit + mWordCount = newWordCount; + } + } + + void extendUninitialized(PxU32 size) + { + PxU32 newWordCount = (size + 31) >> 5; + if (newWordCount > getWordCount()) + { + if (mMap && !isInUserMemory()) + PxBitMapDealloc(mAllocator, mMap, NULL); + // also resets the isInUserMemory bit + mWordCount = newWordCount; + void* newMap = PxBitMapAlloc(mAllocator, mWordCount * sizeof(PxU32), PX_FL, NULL); + mMap = reinterpret_cast(newMap); + } + } + + template + void combine1(const PxU32* words, PxU32 length) + { + extend(length << 5); + PxU32 combineLength = PxMin(getWordCount(), length); + for (PxU32 i = 0; i + void combine2(const PxU32* words1, PxU32 length1, + const PxU32* words2, PxU32 length2) + { + extendUninitialized(PxMax(length1, length2) << 5); + + PxU32 commonSize = PxMin(length1, length2); + + for (PxU32 i = 0; i PxBitMap; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitUtils.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitUtils.h new file mode 100644 index 000000000..4f5ea1192 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBitUtils.h @@ -0,0 +1,128 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BIT_UTILS_H +#define PX_BIT_UTILS_H + +#include "foundation/PxMathIntrinsics.h" +#include "foundation/PxAssert.h" +#include "foundation/PxIntrinsics.h" +#include "foundation/PxMathIntrinsics.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +PX_INLINE uint32_t PxBitCount(uint32_t v) +{ + // from http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel + uint32_t const w = v - ((v >> 1) & 0x55555555); + uint32_t const x = (w & 0x33333333) + ((w >> 2) & 0x33333333); + return (((x + (x >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; +} + +PX_INLINE bool PxIsPowerOfTwo(uint32_t x) +{ + return x != 0 && (x & (x - 1)) == 0; +} + +// "Next Largest Power of 2 +// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm +// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with +// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next +// largest power of 2. For a 32-bit value:" +PX_INLINE uint32_t PxNextPowerOfTwo(uint32_t x) +{ + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return x + 1; +} + +/*! +Return the index of the highest set bit. Not valid for zero arg. +*/ + +PX_INLINE uint32_t PxLowestSetBit(uint32_t x) +{ + PX_ASSERT(x); + return PxLowestSetBitUnsafe(x); +} + +/*! +Return the index of the highest set bit. Not valid for zero arg. +*/ + +PX_INLINE uint32_t PxLowestSetBit(uint64_t x) +{ + PX_ASSERT(x); + return PxLowestSetBitUnsafe(x); +} + +/*! +Return the index of the highest set bit. Not valid for zero arg. +*/ + +PX_INLINE uint32_t PxHighestSetBit(uint32_t x) +{ + PX_ASSERT(x); + return PxHighestSetBitUnsafe(x); +} + +/*! +Return the index of the highest set bit. Not valid for zero arg. +*/ +PX_INLINE uint32_t PxHighestSetBit(uint64_t x) +{ + PX_ASSERT(x); + return PxHighestSetBitUnsafe(x); +} + +// Helper function to approximate log2 of an integer value +// assumes that the input is actually power of two. +PX_INLINE uint32_t PxILog2(uint32_t num) +{ + for(uint32_t i = 0; i < 32; i++) + { + num >>= 1; + if(num == 0) + return i; + } + + PX_ASSERT(0); + return uint32_t(-1); +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBounds3.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBounds3.h new file mode 100644 index 000000000..8ccd58173 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBounds3.h @@ -0,0 +1,496 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BOUNDS3_H +#define PX_BOUNDS3_H + +#include "foundation/PxTransform.h" +#include "foundation/PxMat33.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +// maximum extents defined such that floating point exceptions are avoided for standard use cases +#define PX_MAX_BOUNDS_EXTENTS (PX_MAX_REAL * 0.25f) + +/** +\brief Class representing 3D range or axis aligned bounding box. + +Stored as minimum and maximum extent corners. Alternate representation +would be center and dimensions. +May be empty or nonempty. For nonempty bounds, minimum <= maximum has to hold for all axes. +Empty bounds have to be represented as minimum = PX_MAX_BOUNDS_EXTENTS and maximum = -PX_MAX_BOUNDS_EXTENTS for all +axes. +All other representations are invalid and the behavior is undefined. +*/ +class PxBounds3 +{ + public: + /** + \brief Default constructor, not performing any initialization for performance reason. + \remark Use empty() function below to construct empty bounds. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3() + { + } + + /** + \brief Construct from two bounding points + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3(const PxVec3& minimum, const PxVec3& maximum); + + PX_CUDA_CALLABLE PX_FORCE_INLINE void operator=(const PxBounds3& other) + { + minimum = other.minimum; + maximum = other.maximum; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3(const PxBounds3& other) + { + minimum = other.minimum; + maximum = other.maximum; + } + + /** + \brief Return empty bounds. + */ + static PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 empty(); + + /** + \brief returns the AABB containing v0 and v1. + \param v0 first point included in the AABB. + \param v1 second point included in the AABB. + */ + static PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 boundsOfPoints(const PxVec3& v0, const PxVec3& v1); + + /** + \brief returns the AABB from center and extents vectors. + \param center Center vector + \param extent Extents vector + */ + static PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 centerExtents(const PxVec3& center, const PxVec3& extent); + + /** + \brief Construct from center, extent, and (not necessarily orthogonal) basis + */ + static PX_CUDA_CALLABLE PX_INLINE PxBounds3 basisExtent(const PxVec3& center, const PxMat33& basis, const PxVec3& extent); + + /** + \brief Construct from pose and extent + */ + static PX_CUDA_CALLABLE PX_INLINE PxBounds3 poseExtent(const PxTransform& pose, const PxVec3& extent); + + /** + \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB). + + This version is safe to call for empty bounds. + + \param[in] matrix Transform to apply, can contain scaling as well + \param[in] bounds The bounds to transform. + */ + static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformSafe(const PxMat33& matrix, const PxBounds3& bounds); + + /** + \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB). + + Calling this method for empty bounds leads to undefined behavior. Use #transformSafe() instead. + + \param[in] matrix Transform to apply, can contain scaling as well + \param[in] bounds The bounds to transform. + */ + static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformFast(const PxMat33& matrix, const PxBounds3& bounds); + + /** + \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB). + + This version is safe to call for empty bounds. + + \param[in] transform Transform to apply, can contain scaling as well + \param[in] bounds The bounds to transform. + */ + static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformSafe(const PxTransform& transform, const PxBounds3& bounds); + + /** + \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB). + + Calling this method for empty bounds leads to undefined behavior. Use #transformSafe() instead. + + \param[in] transform Transform to apply, can contain scaling as well + \param[in] bounds The bounds to transform. + */ + static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformFast(const PxTransform& transform, const PxBounds3& bounds); + + /** + \brief Sets empty to true + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void setEmpty(); + + /** + \brief Sets the bounds to maximum size [-PX_MAX_BOUNDS_EXTENTS, PX_MAX_BOUNDS_EXTENTS]. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void setMaximal(); + + /** + \brief expands the volume to include v + \param v Point to expand to. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void include(const PxVec3& v); + + /** + \brief expands the volume to include b. + \param b Bounds to perform union with. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void include(const PxBounds3& b); + + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isEmpty() const; + + /** + \brief indicates whether the intersection of this and b is empty or not. + \param b Bounds to test for intersection. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool intersects(const PxBounds3& b) const; + + /** + \brief computes the 1D-intersection between two AABBs, on a given axis. + \param a the other AABB + \param axis the axis (0, 1, 2) + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool intersects1D(const PxBounds3& a, uint32_t axis) const; + + /** + \brief indicates if these bounds contain v. + \param v Point to test against bounds. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool contains(const PxVec3& v) const; + + /** + \brief checks a box is inside another box. + \param box the other AABB + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isInside(const PxBounds3& box) const; + + /** + \brief returns the center of this axis aligned box. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getCenter() const; + + /** + \brief get component of the box's center along a given axis + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE float getCenter(uint32_t axis) const; + + /** + \brief get component of the box's extents along a given axis + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE float getExtents(uint32_t axis) const; + + /** + \brief returns the dimensions (width/height/depth) of this axis aligned box. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getDimensions() const; + + /** + \brief returns the extents, which are half of the width/height/depth. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getExtents() const; + + /** + \brief scales the AABB. + + This version is safe to call for empty bounds. + + \param scale Factor to scale AABB by. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void scaleSafe(float scale); + + /** + \brief scales the AABB. + + Calling this method for empty bounds leads to undefined behavior. Use #scaleSafe() instead. + + \param scale Factor to scale AABB by. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void scaleFast(float scale); + + /** + fattens the AABB in all 3 dimensions by the given distance. + + This version is safe to call for empty bounds. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void fattenSafe(float distance); + + /** + fattens the AABB in all 3 dimensions by the given distance. + + Calling this method for empty bounds leads to undefined behavior. Use #fattenSafe() instead. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE void fattenFast(float distance); + + /** + checks that the AABB values are not NaN + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite() const; + + /** + checks that the AABB values describe a valid configuration. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isValid() const; + + /** + Finds the closest point in the box to the point p. If p is contained, this will be p, otherwise it + will be the closest point on the surface of the box. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 closestPoint(const PxVec3& p) const; + + PxVec3 minimum, maximum; +}; + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3::PxBounds3(const PxVec3& minimum_, const PxVec3& maximum_) +: minimum(minimum_), maximum(maximum_) +{ +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 PxBounds3::empty() +{ + return PxBounds3(PxVec3(PX_MAX_BOUNDS_EXTENTS), PxVec3(-PX_MAX_BOUNDS_EXTENTS)); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isFinite() const +{ + return minimum.isFinite() && maximum.isFinite(); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 PxBounds3::boundsOfPoints(const PxVec3& v0, const PxVec3& v1) +{ + return PxBounds3(v0.minimum(v1), v0.maximum(v1)); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 PxBounds3::centerExtents(const PxVec3& center, const PxVec3& extent) +{ + return PxBounds3(center - extent, center + extent); +} + +PX_CUDA_CALLABLE PX_INLINE PxBounds3 +PxBounds3::basisExtent(const PxVec3& center, const PxMat33& basis, const PxVec3& extent) +{ + // extended basis vectors + const PxVec3 c0 = basis.column0 * extent.x; + const PxVec3 c1 = basis.column1 * extent.y; + const PxVec3 c2 = basis.column2 * extent.z; + + // find combination of base vectors that produces max. distance for each component = sum of abs() + const PxVec3 w( PxAbs(c0.x) + PxAbs(c1.x) + PxAbs(c2.x), + PxAbs(c0.y) + PxAbs(c1.y) + PxAbs(c2.y), + PxAbs(c0.z) + PxAbs(c1.z) + PxAbs(c2.z)); + + return PxBounds3(center - w, center + w); +} + +PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::poseExtent(const PxTransform& pose, const PxVec3& extent) +{ + return basisExtent(pose.p, PxMat33(pose.q), extent); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::setEmpty() +{ + minimum = PxVec3(PX_MAX_BOUNDS_EXTENTS); + maximum = PxVec3(-PX_MAX_BOUNDS_EXTENTS); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::setMaximal() +{ + minimum = PxVec3(-PX_MAX_BOUNDS_EXTENTS); + maximum = PxVec3(PX_MAX_BOUNDS_EXTENTS); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::include(const PxVec3& v) +{ + PX_ASSERT(isValid()); + minimum = minimum.minimum(v); + maximum = maximum.maximum(v); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::include(const PxBounds3& b) +{ + PX_ASSERT(isValid()); + minimum = minimum.minimum(b.minimum); + maximum = maximum.maximum(b.maximum); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isEmpty() const +{ + PX_ASSERT(isValid()); + return minimum.x > maximum.x; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::intersects(const PxBounds3& b) const +{ + PX_ASSERT(isValid() && b.isValid()); + return !(b.minimum.x > maximum.x || minimum.x > b.maximum.x || b.minimum.y > maximum.y || minimum.y > b.maximum.y || + b.minimum.z > maximum.z || minimum.z > b.maximum.z); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::intersects1D(const PxBounds3& a, uint32_t axis) const +{ + PX_ASSERT(isValid() && a.isValid()); + return maximum[axis] >= a.minimum[axis] && a.maximum[axis] >= minimum[axis]; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::contains(const PxVec3& v) const +{ + PX_ASSERT(isValid()); + + return !(v.x < minimum.x || v.x > maximum.x || v.y < minimum.y || v.y > maximum.y || v.z < minimum.z || + v.z > maximum.z); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isInside(const PxBounds3& box) const +{ + PX_ASSERT(isValid() && box.isValid()); + if(box.minimum.x > minimum.x) + return false; + if(box.minimum.y > minimum.y) + return false; + if(box.minimum.z > minimum.z) + return false; + if(box.maximum.x < maximum.x) + return false; + if(box.maximum.y < maximum.y) + return false; + if(box.maximum.z < maximum.z) + return false; + return true; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxBounds3::getCenter() const +{ + PX_ASSERT(isValid()); + return (minimum + maximum) * 0.5f; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxBounds3::getCenter(uint32_t axis) const +{ + PX_ASSERT(isValid()); + return (minimum[axis] + maximum[axis]) * 0.5f; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxBounds3::getExtents(uint32_t axis) const +{ + PX_ASSERT(isValid()); + return (maximum[axis] - minimum[axis]) * 0.5f; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxBounds3::getDimensions() const +{ + PX_ASSERT(isValid()); + return maximum - minimum; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxBounds3::getExtents() const +{ + PX_ASSERT(isValid()); + return getDimensions() * 0.5f; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::scaleSafe(float scale) +{ + PX_ASSERT(isValid()); + if(!isEmpty()) + scaleFast(scale); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::scaleFast(float scale) +{ + PX_ASSERT(isValid()); + *this = centerExtents(getCenter(), getExtents() * scale); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::fattenSafe(float distance) +{ + PX_ASSERT(isValid()); + if(!isEmpty()) + fattenFast(distance); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::fattenFast(float distance) +{ + PX_ASSERT(isValid()); + minimum.x -= distance; + minimum.y -= distance; + minimum.z -= distance; + + maximum.x += distance; + maximum.y += distance; + maximum.z += distance; +} + +PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformSafe(const PxMat33& matrix, const PxBounds3& bounds) +{ + PX_ASSERT(bounds.isValid()); + return !bounds.isEmpty() ? transformFast(matrix, bounds) : bounds; +} + +PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformFast(const PxMat33& matrix, const PxBounds3& bounds) +{ + PX_ASSERT(bounds.isValid()); + return PxBounds3::basisExtent(matrix * bounds.getCenter(), matrix, bounds.getExtents()); +} + +PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformSafe(const PxTransform& transform, const PxBounds3& bounds) +{ + PX_ASSERT(bounds.isValid()); + return !bounds.isEmpty() ? transformFast(transform, bounds) : bounds; +} + +PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformFast(const PxTransform& transform, const PxBounds3& bounds) +{ + PX_ASSERT(bounds.isValid()); + return PxBounds3::basisExtent(transform.transform(bounds.getCenter()), PxMat33(transform.q), bounds.getExtents()); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isValid() const +{ + return (isFinite() && (((minimum.x <= maximum.x) && (minimum.y <= maximum.y) && (minimum.z <= maximum.z)) || + ((minimum.x == PX_MAX_BOUNDS_EXTENTS) && (minimum.y == PX_MAX_BOUNDS_EXTENTS) && + (minimum.z == PX_MAX_BOUNDS_EXTENTS) && (maximum.x == -PX_MAX_BOUNDS_EXTENTS) && + (maximum.y == -PX_MAX_BOUNDS_EXTENTS) && (maximum.z == -PX_MAX_BOUNDS_EXTENTS)))); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxBounds3::closestPoint(const PxVec3& p) const +{ + return minimum.maximum(maximum.minimum(p)); +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBroadcast.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBroadcast.h new file mode 100644 index 000000000..989dd9fd5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxBroadcast.h @@ -0,0 +1,276 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BROADCAST_H +#define PX_BROADCAST_H + +#include "foundation/PxInlineArray.h" +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxErrorCallback.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Abstract listener class that listens to allocation and deallocation events from the + foundation memory system. + +Threading: All methods of this class should be thread safe as it can be called from the user thread +or the physics processing thread(s). +*/ +class PxAllocationListener +{ + public: + /** + \brief callback when memory is allocated. + \param size Size of the allocation in bytes. + \param typeName Type this data is being allocated for. + \param filename File the allocation came from. + \param line the allocation came from. + \param allocatedMemory memory that will be returned from the allocation. + */ + virtual void onAllocation(size_t size, const char* typeName, const char* filename, int line, + void* allocatedMemory) = 0; + + /** + \brief callback when memory is deallocated. + \param allocatedMemory memory just before allocation. + */ + virtual void onDeallocation(void* allocatedMemory) = 0; + + protected: + virtual ~PxAllocationListener() + { + } +}; + +/** +\brief Broadcast class implementation, registering listeners. + +Threading: All methods of this class should be thread safe as it can be called from the user thread +or the physics processing thread(s). There is not internal locking +*/ +template +class PxBroadcast : public Base +{ + public: + static const uint32_t MAX_NB_LISTENERS = 16; + + /** + \brief The default constructor. + */ + PxBroadcast() + { + } + + /** + \brief Register new listener. + + \note It is NOT SAFE to register and deregister listeners while allocations may be taking place. + moreover, there is no thread safety to registration/deregistration. + + \param listener Listener to register. + */ + void registerListener(Listener& listener) + { + if(mListeners.size() < MAX_NB_LISTENERS) + mListeners.pushBack(&listener); + } + + /** + \brief Deregister an existing listener. + + \note It is NOT SAFE to register and deregister listeners while allocations may be taking place. + moreover, there is no thread safety to registration/deregistration. + + \param listener Listener to deregister. + */ + void deregisterListener(Listener& listener) + { + mListeners.findAndReplaceWithLast(&listener); + } + + /** + \brief Get number of registered listeners. + + \return Number of listeners. + */ + uint32_t getNbListeners() const + { + return mListeners.size(); + } + + /** + \brief Get an existing listener from given index. + + \param index Index of the listener. + \return Listener on given index. + */ + Listener& getListener(uint32_t index) + { + PX_ASSERT(index <= mListeners.size()); + return *mListeners[index]; + } + + protected: + virtual ~PxBroadcast() + { + } + + physx::PxInlineArray mListeners; +}; + +/** +\brief Abstract base class for an application defined memory allocator that allows an external listener +to audit the memory allocations. +*/ +class PxBroadcastingAllocator : public PxBroadcast +{ + PX_NOCOPY(PxBroadcastingAllocator) + + public: + /** + \brief The default constructor. + */ + PxBroadcastingAllocator(PxAllocatorCallback& allocator, PxErrorCallback& error) : mAllocator(allocator), mError(error) + { + mListeners.clear(); + } + + /** + \brief The default constructor. + */ + virtual ~PxBroadcastingAllocator() + { + mListeners.clear(); + } + + /** + \brief Allocates size bytes of memory, which must be 16-byte aligned. + + This method should never return NULL. If you run out of memory, then + you should terminate the app or take some other appropriate action. + + Threading: This function should be thread safe as it can be called in the context of the user thread + and physics processing thread(s). + + \param size Number of bytes to allocate. + \param typeName Name of the datatype that is being allocated + \param filename The source file which allocated the memory + \param line The source line which allocated the memory + \return The allocated block of memory. + */ + void* allocate(size_t size, const char* typeName, const char* filename, int line) + { + void* mem = mAllocator.allocate(size, typeName, filename, line); + + if(!mem) + { + mError.reportError(PxErrorCode::eABORT, "User allocator returned NULL.", filename, line); + return NULL; + } + + if((size_t(mem) & 15)) + { + mError.reportError(PxErrorCode::eABORT, "Allocations must be 16-byte aligned.", filename, line); + return NULL; + } + + for(uint32_t i = 0; i < mListeners.size(); i++) + mListeners[i]->onAllocation(size, typeName, filename, line, mem); + + return mem; + } + + /** + \brief Frees memory previously allocated by allocate(). + + Threading: This function should be thread safe as it can be called in the context of the user thread + and physics processing thread(s). + + \param ptr Memory to free. + */ + void deallocate(void* ptr) + { + for(uint32_t i = 0; i < mListeners.size(); i++) + { + mListeners[i]->onDeallocation(ptr); + } + mAllocator.deallocate(ptr); + } + + private: + PxAllocatorCallback& mAllocator; + PxErrorCallback& mError; +}; + +/** +\brief Abstract base class for an application defined error callback that allows an external listener +to report errors. +*/ +class PxBroadcastingErrorCallback : public PxBroadcast +{ + PX_NOCOPY(PxBroadcastingErrorCallback) + public: + /** + \brief The default constructor. + */ + PxBroadcastingErrorCallback(PxErrorCallback& errorCallback) + { + registerListener(errorCallback); + } + + /** + \brief The default destructor. + */ + virtual ~PxBroadcastingErrorCallback() + { + mListeners.clear(); + } + + /** + \brief Reports an error code. + \param code Error code, see #PxErrorCode + \param message Message to display. + \param file File error occured in. + \param line Line number error occured on. + */ + void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) + { + for(uint32_t i = 0; i < mListeners.size(); i++) + mListeners[i]->reportError(code, message, file, line); + } +}; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxConstructor.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxConstructor.h new file mode 100644 index 000000000..7855ac9b5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxConstructor.h @@ -0,0 +1,55 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONSTRUCTOR_H +#define PX_CONSTRUCTOR_H + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + +/** enum for zero constructor tag for vectors and matrices */ +enum PxZERO +{ + PxZero +}; + +/** enum for identity constructor flag for quaternions, transforms, and matrices */ +enum PxIDENTITY +{ + PxIdentity +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif //PX_CONSTRUCTOR_H + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxErrorCallback.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxErrorCallback.h new file mode 100644 index 000000000..5fb24742e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxErrorCallback.h @@ -0,0 +1,69 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ERROR_CALLBACK_H +#define PX_ERROR_CALLBACK_H + + +#include "foundation/PxErrors.h" +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief User defined interface class. Used by the library to emit debug information. + +\note The SDK state should not be modified from within any error reporting functions. + +Threading: The SDK sequences its calls to the output stream using a mutex, so the class need not +be implemented in a thread-safe manner if the SDK is the only client. +*/ +class PxErrorCallback +{ + public: + virtual ~PxErrorCallback() + { + } + + /** + \brief Reports an error code. + \param code Error code, see #PxErrorCode + \param message Message to display. + \param file File error occured in. + \param line Line number error occured on. + */ + virtual void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) = 0; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxErrors.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxErrors.h new file mode 100644 index 000000000..eabd24334 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxErrors.h @@ -0,0 +1,128 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_ERRORS_H +#define PX_ERRORS_H + +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Error codes + +These error codes are passed to #PxErrorCallback + +\see PxErrorCallback +*/ +struct PxErrorCode +{ + enum Enum + { + eNO_ERROR = 0, + + //! \brief An informational message. + eDEBUG_INFO = 1, + + //! \brief a warning message for the user to help with debugging + eDEBUG_WARNING = 2, + + //! \brief method called with invalid parameter(s) + eINVALID_PARAMETER = 4, + + //! \brief method was called at a time when an operation is not possible + eINVALID_OPERATION = 8, + + //! \brief method failed to allocate some memory + eOUT_OF_MEMORY = 16, + + /** \brief The library failed for some reason. + Possibly you have passed invalid values like NaNs, which are not checked for. + */ + eINTERNAL_ERROR = 32, + + //! \brief An unrecoverable error, execution should be halted and log output flushed + eABORT = 64, + + //! \brief The SDK has determined that an operation may result in poor performance. + ePERF_WARNING = 128, + + //! \brief A bit mask for including all errors + eMASK_ALL = -1 + }; +}; + +#if PX_CHECKED + #define PX_CHECK_MSG(exp, msg) (!!(exp) || (PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, msg), 0) ) + #define PX_CHECK_AND_RETURN(exp, msg) { if(!(exp)) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, msg); return; } } + #define PX_CHECK_AND_RETURN_NULL(exp, msg) { if(!(exp)) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, msg); return 0; } } + #define PX_CHECK_AND_RETURN_VAL(exp, msg, r) { if(!(exp)) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, msg); return r; } } +#else + #define PX_CHECK_MSG(exp, msg) + #define PX_CHECK_AND_RETURN(exp, msg) + #define PX_CHECK_AND_RETURN_NULL(exp, msg) + #define PX_CHECK_AND_RETURN_VAL(exp, msg, r) +#endif + +// shortcut macros: +// usage: PxGetFoundation().error(PX_WARN, "static friction %f is is lower than dynamic friction %d", sfr, dfr); +#define PX_WARN ::physx::PxErrorCode::eDEBUG_WARNING, PX_FL +#define PX_INFO ::physx::PxErrorCode::eDEBUG_INFO, PX_FL + +#if PX_DEBUG || PX_CHECKED + #define PX_WARN_ONCE(string) \ + { \ + static PxU32 timestamp = 0; \ + const PxU32 ts = PxGetWarnOnceTimeStamp(); \ + if(timestamp != ts) \ + { \ + timestamp = ts; \ + PxGetFoundation().error(PX_WARN, string); \ + } \ + } + #define PX_WARN_ONCE_IF(condition, string) \ + { \ + if(condition) \ + { \ + PX_WARN_ONCE(string) \ + } \ + } +#else + #define PX_WARN_ONCE(string) ((void)0) + #define PX_WARN_ONCE_IF(condition, string) ((void)0) +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFPU.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFPU.h new file mode 100644 index 000000000..4529adac7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFPU.h @@ -0,0 +1,100 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FPU_H +#define PX_FPU_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxIntrinsics.h" +#include "foundation/PxAssert.h" +#include "foundation/PxFoundationConfig.h" + +#define PX_IR(x) ((PxU32&)(x)) // integer representation of a floating-point value. +#define PX_SIR(x) ((PxI32&)(x)) // signed integer representation of a floating-point value. +#define PX_FR(x) ((PxReal&)(x)) // floating-point representation of a integer value. + +#define PX_FPU_GUARD PxFPUGuard scopedFpGuard; +#define PX_SIMD_GUARD PxSIMDGuard scopedFpGuard; +#define PX_SIMD_GUARD_CNDT(x) PxSIMDGuard scopedFpGuard(x); + +#if !PX_DOXYGEN +namespace physx +{ +#endif +// sets the default SDK state for scalar and SIMD units +class PX_FOUNDATION_API PxFPUGuard +{ + public: + PxFPUGuard(); // set fpu control word for PhysX + ~PxFPUGuard(); // restore fpu control word + private: + PxU32 mControlWords[8]; +}; + +// sets default SDK state for simd unit only, lighter weight than FPUGuard +class PxSIMDGuard +{ + public: + PX_INLINE PxSIMDGuard(bool enable = true); // set simd control word for PhysX + PX_INLINE ~PxSIMDGuard(); // restore simd control word + private: +#if !(PX_LINUX || PX_OSX) || (!PX_EMSCRIPTEN && PX_INTEL_FAMILY) + PxU32 mControlWord; + bool mEnabled; +#endif +}; + +/** +\brief Enables floating point exceptions for the scalar and SIMD unit +*/ +PX_FOUNDATION_API void PxEnableFPExceptions(); + +/** +\brief Disables floating point exceptions for the scalar and SIMD unit +*/ +PX_FOUNDATION_API void PxDisableFPExceptions(); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#if PX_WINDOWS_FAMILY +#include "foundation/windows/PxWindowsFPU.h" +#elif (PX_LINUX && PX_SSE2) || PX_OSX +#include "foundation/unix/PxUnixFPU.h" +#else +PX_INLINE physx::PxSIMDGuard::PxSIMDGuard(bool) +{ +} +PX_INLINE physx::PxSIMDGuard::~PxSIMDGuard() +{ +} +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFlags.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFlags.h new file mode 100644 index 000000000..22527f7b8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFlags.h @@ -0,0 +1,381 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FLAGS_H +#define PX_FLAGS_H + + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxPreprocessor.h" +#include "foundation/PxIO.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +/** +\brief Container for bitfield flag variables associated with a specific enum type. + +This allows for type safe manipulation for bitfields. + +

Example

+ // enum that defines each bit... + struct MyEnum + { + enum Enum + { + eMAN = 1, + eBEAR = 2, + ePIG = 4, + }; + }; + + // implements some convenient global operators. + PX_FLAGS_OPERATORS(MyEnum::Enum, PxU8); + + PxFlags myFlags; + myFlags |= MyEnum::eMAN; + myFlags |= MyEnum::eBEAR | MyEnum::ePIG; + if(myFlags & MyEnum::eBEAR) + { + doSomething(); + } +*/ + +template +class PxFlags +{ + public: + typedef storagetype InternalType; + + PX_CUDA_CALLABLE PX_INLINE explicit PxFlags(const PxEMPTY) + { + } + PX_CUDA_CALLABLE PX_INLINE PxFlags(); + PX_CUDA_CALLABLE PX_INLINE PxFlags(enumtype e); + PX_CUDA_CALLABLE PX_INLINE PxFlags(const PxFlags& f); + PX_CUDA_CALLABLE PX_INLINE explicit PxFlags(storagetype b); + + PX_CUDA_CALLABLE PX_INLINE bool operator==(enumtype e) const; + PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxFlags& f) const; + PX_CUDA_CALLABLE PX_INLINE bool operator==(bool b) const; + PX_CUDA_CALLABLE PX_INLINE bool operator!=(enumtype e) const; + PX_CUDA_CALLABLE PX_INLINE bool operator!=(const PxFlags& f) const; + + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator=(const PxFlags& f); + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator=(enumtype e); + + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator|=(enumtype e); + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator|=(const PxFlags& f); + PX_CUDA_CALLABLE PX_INLINE PxFlags operator|(enumtype e) const; + PX_CUDA_CALLABLE PX_INLINE PxFlags operator|(const PxFlags& f) const; + + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator&=(enumtype e); + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator&=(const PxFlags& f); + PX_CUDA_CALLABLE PX_INLINE PxFlags operator&(enumtype e) const; + PX_CUDA_CALLABLE PX_INLINE PxFlags operator&(const PxFlags& f) const; + + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator^=(enumtype e); + PX_CUDA_CALLABLE PX_INLINE PxFlags& operator^=(const PxFlags& f); + PX_CUDA_CALLABLE PX_INLINE PxFlags operator^(enumtype e) const; + PX_CUDA_CALLABLE PX_INLINE PxFlags operator^(const PxFlags& f) const; + + PX_CUDA_CALLABLE PX_INLINE PxFlags operator~() const; + + PX_CUDA_CALLABLE PX_INLINE operator bool() const; + PX_CUDA_CALLABLE PX_INLINE operator PxU8() const; + PX_CUDA_CALLABLE PX_INLINE operator PxU16() const; + PX_CUDA_CALLABLE PX_INLINE operator PxU32() const; + + PX_CUDA_CALLABLE PX_INLINE void clear(enumtype e); + PX_CUDA_CALLABLE PX_INLINE void raise(enumtype e); + PX_CUDA_CALLABLE PX_INLINE bool isSet(enumtype e) const; + PX_CUDA_CALLABLE PX_INLINE PxFlags& setAll(enumtype e); + + public: + friend PX_INLINE PxFlags operator&(enumtype a, PxFlags& b) + { + PxFlags out; + out.mBits = a & b.mBits; + return out; + } + + private: + storagetype mBits; +}; + +#if !PX_DOXYGEN + +#define PX_FLAGS_OPERATORS(enumtype, storagetype) \ + PX_CUDA_CALLABLE PX_INLINE PxFlags operator|(enumtype a, enumtype b) \ + { \ + PxFlags r(a); \ + r |= b; \ + return r; \ + } \ + PX_CUDA_CALLABLE PX_INLINE PxFlags operator&(enumtype a, enumtype b) \ + { \ + PxFlags r(a); \ + r &= b; \ + return r; \ + } \ + PX_CUDA_CALLABLE PX_INLINE PxFlags operator~(enumtype a) \ + { \ + return ~PxFlags(a); \ + } + +#define PX_FLAGS_TYPEDEF(x, y) \ + typedef PxFlags x##s; \ + PX_FLAGS_OPERATORS(x::Enum, y) + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::PxFlags() +{ + mBits = 0; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::PxFlags(enumtype e) +{ + mBits = static_cast(e); +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::PxFlags(const PxFlags& f) +{ + mBits = f.mBits; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::PxFlags(storagetype b) +{ + mBits = b; +} + +template +PX_CUDA_CALLABLE PX_INLINE bool PxFlags::operator==(enumtype e) const +{ + return mBits == static_cast(e); +} + +template +PX_CUDA_CALLABLE PX_INLINE bool PxFlags::operator==(const PxFlags& f) const +{ + return mBits == f.mBits; +} + +template +PX_CUDA_CALLABLE PX_INLINE bool PxFlags::operator==(bool b) const +{ + return bool(*this) == b; +} + +template +PX_CUDA_CALLABLE PX_INLINE bool PxFlags::operator!=(enumtype e) const +{ + return mBits != static_cast(e); +} + +template +PX_CUDA_CALLABLE PX_INLINE bool PxFlags::operator!=(const PxFlags& f) const +{ + return mBits != f.mBits; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags::operator=(enumtype e) +{ + mBits = static_cast(e); + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags::operator=(const PxFlags& f) +{ + mBits = f.mBits; + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags::operator|=(enumtype e) +{ + mBits |= static_cast(e); + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags:: +operator|=(const PxFlags& f) +{ + mBits |= f.mBits; + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags PxFlags::operator|(enumtype e) const +{ + PxFlags out(*this); + out |= e; + return out; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags PxFlags:: +operator|(const PxFlags& f) const +{ + PxFlags out(*this); + out |= f; + return out; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags::operator&=(enumtype e) +{ + mBits &= static_cast(e); + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags:: +operator&=(const PxFlags& f) +{ + mBits &= f.mBits; + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags PxFlags::operator&(enumtype e) const +{ + PxFlags out = *this; + out.mBits &= static_cast(e); + return out; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags PxFlags:: +operator&(const PxFlags& f) const +{ + PxFlags out = *this; + out.mBits &= f.mBits; + return out; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags::operator^=(enumtype e) +{ + mBits ^= static_cast(e); + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags:: +operator^=(const PxFlags& f) +{ + mBits ^= f.mBits; + return *this; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags PxFlags::operator^(enumtype e) const +{ + PxFlags out = *this; + out.mBits ^= static_cast(e); + return out; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags PxFlags:: +operator^(const PxFlags& f) const +{ + PxFlags out = *this; + out.mBits ^= f.mBits; + return out; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags PxFlags::operator~() const +{ + PxFlags out; + out.mBits = storagetype(~mBits); + return out; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::operator bool() const +{ + return mBits ? true : false; +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::operator PxU8() const +{ + return static_cast(mBits); +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::operator PxU16() const +{ + return static_cast(mBits); +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags::operator PxU32() const +{ + return static_cast(mBits); +} + +template +PX_CUDA_CALLABLE PX_INLINE void PxFlags::clear(enumtype e) +{ + mBits &= ~static_cast(e); +} + +template +PX_CUDA_CALLABLE PX_INLINE void PxFlags::raise(enumtype e) +{ + mBits |= static_cast(e); +} + +template +PX_CUDA_CALLABLE PX_INLINE bool PxFlags::isSet(enumtype e) const +{ + return (mBits & static_cast(e)) == static_cast(e); +} + +template +PX_CUDA_CALLABLE PX_INLINE PxFlags& PxFlags::setAll(enumtype e) +{ + mBits = static_cast(e); + return *this; +} + +} // namespace physx +#endif //!PX_DOXYGEN + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFoundation.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFoundation.h new file mode 100644 index 000000000..39fa32d96 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFoundation.h @@ -0,0 +1,233 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FOUNDATION_H +#define PX_FOUNDATION_H + + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxErrors.h" +#include "foundation/PxFoundationConfig.h" + +#include + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxAllocationListener; +class PxErrorCallback; +class PxAllocatorCallback; + +/** +\brief Foundation SDK singleton class. + +You need to have an instance of this class to instance the higher level SDKs. +*/ +class PX_FOUNDATION_API PxFoundation +{ + public: + /** + \brief Destroys the instance it is called on. + + The operation will fail, if there are still modules referencing the foundation object. Release all dependent modules + prior to calling this method. + + \see PxCreateFoundation() + */ + virtual void release() = 0; + + /** + retrieves error callback + */ + virtual PxErrorCallback& getErrorCallback() = 0; + + /** + Sets mask of errors to report. + */ + virtual void setErrorLevel(PxErrorCode::Enum mask = PxErrorCode::eMASK_ALL) = 0; + + /** + Retrieves mask of errors to be reported. + */ + virtual PxErrorCode::Enum getErrorLevel() const = 0; + + /** + Retrieves the allocator this object was created with. + */ + virtual PxAllocatorCallback& getAllocatorCallback() = 0; + + /** + Retrieves if allocation names are being passed to allocator callback. + */ + virtual bool getReportAllocationNames() const = 0; + + /** + Set if allocation names are being passed to allocator callback. + \details Enabled by default in debug and checked build, disabled by default in profile and release build. + */ + virtual void setReportAllocationNames(bool value) = 0; + + virtual void registerAllocationListener(PxAllocationListener& listener) = 0; + + virtual void deregisterAllocationListener(PxAllocationListener& listener) = 0; + + virtual void registerErrorCallback(PxErrorCallback& callback) = 0; + + virtual void deregisterErrorCallback(PxErrorCallback& callback) = 0; + + virtual bool error(PxErrorCode::Enum c, const char* file, int line, const char* messageFmt, ...) = 0; + + virtual bool error(PxErrorCode::Enum, const char* file, int line, const char* messageFmt, va_list) = 0; + + protected: + virtual ~PxFoundation() + { + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +// PT: use this to make generated code shorter (e.g. from 52 to 24 bytes of assembly (10 to 4 instructions)) +// We must use a macro here to let __FILE__ expand to the proper filename (it doesn't work with an inlined function). +#define PX_IMPLEMENT_OUTPUT_ERROR \ +template \ +static PX_NOINLINE bool outputError(int line, const char* message) \ +{ \ + return PxGetFoundation().error(PxErrorCode::Enum(errorCode), __FILE__, line, message); \ +} + +/** +\brief Creates an instance of the foundation class + +The foundation class is needed to initialize higher level SDKs. There may be only one instance per process. +Calling this method after an instance has been created already will result in an error message and NULL will be +returned. + +\param version Version number we are expecting (should be #PX_PHYSICS_VERSION) +\param allocator User supplied interface for allocating memory(see #PxAllocatorCallback) +\param errorCallback User supplied interface for reporting errors and displaying messages(see #PxErrorCallback) +\return Foundation instance on success, NULL if operation failed + +\see PxFoundation +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxFoundation* PX_CALL_CONV PxCreateFoundation(physx::PxU32 version, physx::PxAllocatorCallback& allocator, physx::PxErrorCallback& errorCallback); + + +PX_C_EXPORT PX_FOUNDATION_API void PX_CALL_CONV PxSetFoundationInstance(physx::PxFoundation& foundation); + + +/** +\brief Retrieves the Foundation SDK after it has been created. + +\note The behavior of this method is undefined if the foundation instance has not been created already. + +\see PxCreateFoundation(), PxIsFoundationValid() +*/ +#if PX_CLANG +#if PX_LINUX +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreturn-type-c-linkage" +#endif // PX_LINUX +#endif // PX_CLANG +PX_C_EXPORT PX_FOUNDATION_API physx::PxFoundation& PX_CALL_CONV PxGetFoundation(); +#if PX_CLANG +#if PX_LINUX +#pragma clang diagnostic pop +#endif // PX_LINUX +#endif // PX_CLANG + +/** +\brief Similar to PxGetFoundation() except it handles the case if the foundation was not created already. +\return Pointer to the foundation if an instance is currently available, otherwise null. + +\see PxCreateFoundation(), PxGetFoundation() +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxFoundation* PX_CALL_CONV PxIsFoundationValid(); + +#if !PX_DOXYGEN +namespace physx +{ +#endif +class PxProfilerCallback; +class PxAllocatorCallback; +class PxErrorCallback; +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** +\brief Get the callback that will be used for all profiling. +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxProfilerCallback* PX_CALL_CONV PxGetProfilerCallback(); + +/** +\brief Set the callback that will be used for all profiling. +*/ +PX_C_EXPORT PX_FOUNDATION_API void PX_CALL_CONV PxSetProfilerCallback(physx::PxProfilerCallback* profiler); + +/** +\brief Get the allocator callback +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxAllocatorCallback* PX_CALL_CONV PxGetAllocatorCallback(); + +/** +\brief Get the broadcasting allocator callback +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxAllocatorCallback* PX_CALL_CONV PxGetBroadcastAllocator(bool* reportAllocationNames = NULL); + +/** +\brief Get the error callback +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxErrorCallback* PX_CALL_CONV PxGetErrorCallback(); + +/** +\brief Get the broadcasting error callback +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxErrorCallback* PX_CALL_CONV PxGetBroadcastError(); + +/** +\brief Get the warn once timestamp +*/ +PX_C_EXPORT PX_FOUNDATION_API physx::PxU32 PX_CALL_CONV PxGetWarnOnceTimeStamp(); + +/** +\brief Decrement the ref count of PxFoundation +*/ +PX_C_EXPORT PX_FOUNDATION_API void PX_CALL_CONV PxDecFoundationRefCount(); + +/** +\brief Increment the ref count of PxFoundation +*/ +PX_C_EXPORT PX_FOUNDATION_API void PX_CALL_CONV PxIncFoundationRefCount(); + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFoundationConfig.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFoundationConfig.h new file mode 100644 index 000000000..89237c992 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxFoundationConfig.h @@ -0,0 +1,52 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_FOUNDATION_CONFIG_H +#define PX_FOUNDATION_CONFIG_H + +#include "foundation/PxPreprocessor.h" + + +#if defined PX_PHYSX_STATIC_LIB + #define PX_FOUNDATION_API +#else + #if PX_WINDOWS_FAMILY && !PX_CUDA_COMPILER + #if defined PX_PHYSX_FOUNDATION_EXPORTS + #define PX_FOUNDATION_API __declspec(dllexport) + #else + #define PX_FOUNDATION_API __declspec(dllimport) + #endif + #elif PX_UNIX_FAMILY + #define PX_FOUNDATION_API PX_UNIX_EXPORT + #else + #define PX_FOUNDATION_API + #endif +#endif + + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHash.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHash.h new file mode 100644 index 000000000..9db92366b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHash.h @@ -0,0 +1,163 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HASH_H +#define PX_HASH_H + +#include "foundation/PxBasicTemplates.h" +#include "foundation/PxString.h" + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4302) +#endif + +#if PX_LINUX +#include "foundation/PxSimpleTypes.h" +#endif + +/*! +Central definition of hash functions +*/ + +#if !PX_DOXYGEN +namespace physx +{ +#endif +// Hash functions + +// Thomas Wang's 32 bit mix +// http://www.cris.com/~Ttwang/tech/inthash.htm +PX_FORCE_INLINE uint32_t PxComputeHash(const uint32_t key) +{ + uint32_t k = key; + k += ~(k << 15); + k ^= (k >> 10); + k += (k << 3); + k ^= (k >> 6); + k += ~(k << 11); + k ^= (k >> 16); + return uint32_t(k); +} + +PX_FORCE_INLINE uint32_t PxComputeHash(const int32_t key) +{ + return PxComputeHash(uint32_t(key)); +} + +// Thomas Wang's 64 bit mix +// http://www.cris.com/~Ttwang/tech/inthash.htm +PX_FORCE_INLINE uint32_t PxComputeHash(const uint64_t key) +{ + uint64_t k = key; + k += ~(k << 32); + k ^= (k >> 22); + k += ~(k << 13); + k ^= (k >> 8); + k += (k << 3); + k ^= (k >> 15); + k += ~(k << 27); + k ^= (k >> 31); + return uint32_t(UINT32_MAX & k); +} + +#if PX_APPLE_FAMILY +// hash for size_t, to make gcc happy +PX_INLINE uint32_t PxComputeHash(const size_t key) +{ +#if PX_P64_FAMILY + return PxComputeHash(uint64_t(key)); +#else + return PxComputeHash(uint32_t(key)); +#endif +} +#endif + +// Hash function for pointers +PX_INLINE uint32_t PxComputeHash(const void* ptr) +{ +#if PX_P64_FAMILY + return PxComputeHash(uint64_t(ptr)); +#else + return PxComputeHash(uint32_t(UINT32_MAX & size_t(ptr))); +#endif +} + +// Hash function for pairs +template +PX_INLINE uint32_t PxComputeHash(const PxPair& p) +{ + uint32_t seed = 0x876543; + uint32_t m = 1000007; + return PxComputeHash(p.second) ^ (m * (PxComputeHash(p.first) ^ (m * seed))); +} + +// hash object for hash map template parameter +template +struct PxHash +{ + uint32_t operator()(const Key& k) const + { + return PxComputeHash(k); + } + bool equal(const Key& k0, const Key& k1) const + { + return k0 == k1; + } +}; + +// specialization for strings +template <> +struct PxHash +{ + public: + uint32_t operator()(const char* _string) const + { + // "DJB" string hash + const uint8_t* string = reinterpret_cast(_string); + uint32_t h = 5381; + for(const uint8_t* ptr = string; *ptr; ptr++) + h = ((h << 5) + h) ^ uint32_t(*ptr); + return h; + } + bool equal(const char* string0, const char* string1) const + { + return !Pxstrcmp(string0, string1); + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#if PX_VC +#pragma warning(pop) +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashInternals.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashInternals.h new file mode 100644 index 000000000..d31a9153a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashInternals.h @@ -0,0 +1,791 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HASH_INTERNALS_H +#define PX_HASH_INTERNALS_H + +#include "foundation/PxAllocator.h" +#include "foundation/PxBitUtils.h" +#include "foundation/PxMathIntrinsics.h" +#include "foundation/PxBasicTemplates.h" +#include "foundation/PxHash.h" + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4127) // conditional expression is constant +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +template +class PxHashBase : private PxAllocator +{ + void init(uint32_t initialTableSize, float loadFactor) + { + mBuffer = NULL; + mEntries = NULL; + mEntriesNext = NULL; + mHash = NULL; + mEntriesCapacity = 0; + mHashSize = 0; + mLoadFactor = loadFactor; + mFreeList = uint32_t(EOL); + mTimestamp = 0; + mEntriesCount = 0; + + if(initialTableSize) + reserveInternal(initialTableSize); + } + + public: + typedef Entry EntryType; + + PxHashBase(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : PxAllocator("hashBase") + { + init(initialTableSize, loadFactor); + } + + PxHashBase(uint32_t initialTableSize, float loadFactor, const PxAllocator& alloc) : PxAllocator(alloc) + { + init(initialTableSize, loadFactor); + } + + PxHashBase(const PxAllocator& alloc) : PxAllocator(alloc) + { + init(64, 0.75f); + } + + ~PxHashBase() + { + destroy(); // No need to clear() + + if(mBuffer) + PxAllocator::deallocate(mBuffer); + } + + static const uint32_t EOL = 0xffffffff; + + PX_INLINE Entry* create(const Key& k, bool& exists) + { + uint32_t h = 0; + if(mHashSize) + { + h = hash(k); + uint32_t index = mHash[h]; + while(index != EOL && !HashFn().equal(GetKey()(mEntries[index]), k)) + index = mEntriesNext[index]; + exists = index != EOL; + if(exists) + return mEntries + index; + } + else + exists = false; + + if(freeListEmpty()) + { + grow(); + h = hash(k); + } + + uint32_t entryIndex = freeListGetNext(); + + mEntriesNext[entryIndex] = mHash[h]; + mHash[h] = entryIndex; + + mEntriesCount++; + mTimestamp++; + + return mEntries + entryIndex; + } + + PX_INLINE const Entry* find(const Key& k) const + { + if(!mEntriesCount) + return NULL; + + const uint32_t h = hash(k); + uint32_t index = mHash[h]; + while(index != EOL && !HashFn().equal(GetKey()(mEntries[index]), k)) + index = mEntriesNext[index]; + return index != EOL ? mEntries + index : NULL; + } + + PX_INLINE bool erase(const Key& k, Entry& e) + { + if(!mEntriesCount) + return false; + + const uint32_t h = hash(k); + uint32_t* ptr = mHash + h; + while(*ptr != EOL && !HashFn().equal(GetKey()(mEntries[*ptr]), k)) + ptr = mEntriesNext + *ptr; + + if(*ptr == EOL) + return false; + + PX_PLACEMENT_NEW(&e, Entry)(mEntries[*ptr]); + + return eraseInternal(ptr); + } + + PX_INLINE bool erase(const Key& k) + { + if(!mEntriesCount) + return false; + + const uint32_t h = hash(k); + uint32_t* ptr = mHash + h; + while(*ptr != EOL && !HashFn().equal(GetKey()(mEntries[*ptr]), k)) + ptr = mEntriesNext + *ptr; + + if(*ptr == EOL) + return false; + + return eraseInternal(ptr); + } + + PX_INLINE uint32_t size() const + { + return mEntriesCount; + } + + PX_INLINE uint32_t capacity() const + { + return mHashSize; + } + + void clear() + { + if(!mHashSize || mEntriesCount == 0) + return; + + destroy(); + + intrinsics::memSet(mHash, EOL, mHashSize * sizeof(uint32_t)); + + const uint32_t sizeMinus1 = mEntriesCapacity - 1; + for(uint32_t i = 0; i < sizeMinus1; i++) + { + PxPrefetchLine(mEntriesNext + i, 128); + mEntriesNext[i] = i + 1; + } + mEntriesNext[mEntriesCapacity - 1] = uint32_t(EOL); + mFreeList = 0; + mEntriesCount = 0; + } + + void reserve(uint32_t size) + { + if(size > mHashSize) + reserveInternal(size); + } + + PX_INLINE const Entry* getEntries() const + { + return mEntries; + } + + PX_INLINE Entry* insertUnique(const Key& k) + { + PX_ASSERT(find(k) == NULL); + uint32_t h = hash(k); + + uint32_t entryIndex = freeListGetNext(); + + mEntriesNext[entryIndex] = mHash[h]; + mHash[h] = entryIndex; + + mEntriesCount++; + mTimestamp++; + + return mEntries + entryIndex; + } + + private: + void destroy() + { + for(uint32_t i = 0; i < mHashSize; i++) + { + for(uint32_t j = mHash[i]; j != EOL; j = mEntriesNext[j]) + mEntries[j].~Entry(); + } + } + + template + PX_NOINLINE void copy(const PxHashBase& other); + + // free list management - if we're coalescing, then we use mFreeList to hold + // the top of the free list and it should always be equal to size(). Otherwise, + // we build a free list in the next() pointers. + + PX_INLINE void freeListAdd(uint32_t index) + { + if(compacting) + { + mFreeList--; + PX_ASSERT(mFreeList == mEntriesCount); + } + else + { + mEntriesNext[index] = mFreeList; + mFreeList = index; + } + } + + PX_INLINE void freeListAdd(uint32_t start, uint32_t end) + { + if(!compacting) + { + for(uint32_t i = start; i < end - 1; i++) // add the new entries to the free list + mEntriesNext[i] = i + 1; + + // link in old free list + mEntriesNext[end - 1] = mFreeList; + PX_ASSERT(mFreeList != end - 1); + mFreeList = start; + } + else if(mFreeList == EOL) // don't reset the free ptr for the compacting hash unless it's empty + mFreeList = start; + } + + PX_INLINE uint32_t freeListGetNext() + { + PX_ASSERT(!freeListEmpty()); + if(compacting) + { + PX_ASSERT(mFreeList == mEntriesCount); + return mFreeList++; + } + else + { + uint32_t entryIndex = mFreeList; + mFreeList = mEntriesNext[mFreeList]; + return entryIndex; + } + } + + PX_INLINE bool freeListEmpty() const + { + if(compacting) + return mEntriesCount == mEntriesCapacity; + else + return mFreeList == EOL; + } + + PX_INLINE void replaceWithLast(uint32_t index) + { + PX_PLACEMENT_NEW(mEntries + index, Entry)(mEntries[mEntriesCount]); + mEntries[mEntriesCount].~Entry(); + mEntriesNext[index] = mEntriesNext[mEntriesCount]; + + uint32_t h = hash(GetKey()(mEntries[index])); + uint32_t* ptr; + for(ptr = mHash + h; *ptr != mEntriesCount; ptr = mEntriesNext + *ptr) + PX_ASSERT(*ptr != EOL); + *ptr = index; + } + + PX_INLINE uint32_t hash(const Key& k, uint32_t hashSize) const + { + return HashFn()(k) & (hashSize - 1); + } + + PX_INLINE uint32_t hash(const Key& k) const + { + return hash(k, mHashSize); + } + + PX_INLINE bool eraseInternal(uint32_t* ptr) + { + const uint32_t index = *ptr; + + *ptr = mEntriesNext[index]; + + mEntries[index].~Entry(); + + mEntriesCount--; + mTimestamp++; + + if (compacting && index != mEntriesCount) + replaceWithLast(index); + + freeListAdd(index); + return true; + } + + PX_NOINLINE void reserveInternal(uint32_t size) + { + if(!PxIsPowerOfTwo(size)) + size = PxNextPowerOfTwo(size); + + PX_ASSERT(!(size & (size - 1))); + + // decide whether iteration can be done on the entries directly + bool resizeCompact = compacting || freeListEmpty(); + + // define new table sizes + uint32_t oldEntriesCapacity = mEntriesCapacity; + uint32_t newEntriesCapacity = uint32_t(float(size) * mLoadFactor); + uint32_t newHashSize = size; + + // allocate new common buffer and setup pointers to new tables + uint8_t* newBuffer; + uint32_t* newHash; + uint32_t* newEntriesNext; + Entry* newEntries; + { + const uint64_t newEntriesNextBytesOffset = newHashSize * sizeof(uint32_t); + uint64_t newEntriesByteOffset = newEntriesNextBytesOffset + newEntriesCapacity * sizeof(uint32_t); + newEntriesByteOffset += (16 - (newEntriesByteOffset & 15)) & 15; + const uint64_t newBufferByteSize = newEntriesByteOffset + newEntriesCapacity * sizeof(Entry); + + newBuffer = reinterpret_cast(PxAllocator::allocate(newBufferByteSize, PX_FL)); + PX_ASSERT(newBuffer); + + newHash = reinterpret_cast(newBuffer); + newEntriesNext = reinterpret_cast(newBuffer + newEntriesNextBytesOffset); + newEntries = reinterpret_cast(newBuffer + newEntriesByteOffset); + } + + // initialize new hash table + intrinsics::memSet(newHash, int32_t(EOL), newHashSize * sizeof(uint32_t)); + + // iterate over old entries, re-hash and create new entries + if(resizeCompact) + { + // check that old free list is empty - we don't need to copy the next entries + PX_ASSERT(compacting || mFreeList == EOL); + + for(uint32_t index = 0; index < mEntriesCount; ++index) + { + uint32_t h = hash(GetKey()(mEntries[index]), newHashSize); + newEntriesNext[index] = newHash[h]; + newHash[h] = index; + + PX_PLACEMENT_NEW(newEntries + index, Entry)(mEntries[index]); + mEntries[index].~Entry(); + } + } + else + { + // copy old free list, only required for non compact resizing + intrinsics::memCopy(newEntriesNext, mEntriesNext, mEntriesCapacity * sizeof(uint32_t)); + + for(uint32_t bucket = 0; bucket < mHashSize; bucket++) + { + uint32_t index = mHash[bucket]; + while(index != EOL) + { + uint32_t h = hash(GetKey()(mEntries[index]), newHashSize); + newEntriesNext[index] = newHash[h]; + PX_ASSERT(index != newHash[h]); + + newHash[h] = index; + + PX_PLACEMENT_NEW(newEntries + index, Entry)(mEntries[index]); + mEntries[index].~Entry(); + + index = mEntriesNext[index]; + } + } + } + + // swap buffer and pointers + PxAllocator::deallocate(mBuffer); + mBuffer = newBuffer; + mHash = newHash; + mHashSize = newHashSize; + mEntriesNext = newEntriesNext; + mEntries = newEntries; + mEntriesCapacity = newEntriesCapacity; + + freeListAdd(oldEntriesCapacity, newEntriesCapacity); + } + + void grow() + { + PX_ASSERT((mFreeList == EOL) || (compacting && (mEntriesCount == mEntriesCapacity))); + + uint32_t size = mHashSize == 0 ? 16 : mHashSize * 2; + reserve(size); + } + + uint8_t* mBuffer; + Entry* mEntries; + uint32_t* mEntriesNext; // same size as mEntries + uint32_t* mHash; + uint32_t mEntriesCapacity; + uint32_t mHashSize; + float mLoadFactor; + uint32_t mFreeList; + uint32_t mTimestamp; + uint32_t mEntriesCount; // number of entries + + public: + class Iter + { + public: + PX_INLINE Iter(PxHashBase& b) : mBucket(0), mEntry(uint32_t(b.EOL)), mTimestamp(b.mTimestamp), mBase(b) + { + if(mBase.mEntriesCapacity > 0) + { + mEntry = mBase.mHash[0]; + skip(); + } + } + + PX_INLINE void check() const + { + PX_ASSERT(mTimestamp == mBase.mTimestamp); + } + PX_INLINE const Entry& operator*() const + { + check(); + return mBase.mEntries[mEntry]; + } + PX_INLINE Entry& operator*() + { + check(); + return mBase.mEntries[mEntry]; + } + PX_INLINE const Entry* operator->() const + { + check(); + return mBase.mEntries + mEntry; + } + PX_INLINE Entry* operator->() + { + check(); + return mBase.mEntries + mEntry; + } + PX_INLINE Iter operator++() + { + check(); + advance(); + return *this; + } + PX_INLINE Iter operator++(int) + { + check(); + Iter i = *this; + advance(); + return i; + } + PX_INLINE bool done() const + { + check(); + return mEntry == mBase.EOL; + } + + private: + PX_INLINE void advance() + { + mEntry = mBase.mEntriesNext[mEntry]; + skip(); + } + PX_INLINE void skip() + { + while(mEntry == mBase.EOL) + { + if(++mBucket == mBase.mHashSize) + break; + mEntry = mBase.mHash[mBucket]; + } + } + + Iter& operator=(const Iter&); + + uint32_t mBucket; + uint32_t mEntry; + uint32_t mTimestamp; + PxHashBase& mBase; + }; + + /*! + Iterate over entries in a hash base and allow entry erase while iterating + */ + class PxEraseIterator + { + public: + PX_INLINE PxEraseIterator(PxHashBase& b): mBase(b) + { + reset(); + } + + PX_INLINE Entry* eraseCurrentGetNext(bool eraseCurrent) + { + if(eraseCurrent && mCurrentEntryIndexPtr) + { + mBase.eraseInternal(mCurrentEntryIndexPtr); + // if next was valid return the same ptr, if next was EOL search new hash entry + if(*mCurrentEntryIndexPtr != mBase.EOL) + return mBase.mEntries + *mCurrentEntryIndexPtr; + else + return traverseHashEntries(); + } + + // traverse mHash to find next entry + if(mCurrentEntryIndexPtr == NULL) + return traverseHashEntries(); + + const uint32_t index = *mCurrentEntryIndexPtr; + if(mBase.mEntriesNext[index] == mBase.EOL) + { + return traverseHashEntries(); + } + else + { + mCurrentEntryIndexPtr = mBase.mEntriesNext + index; + return mBase.mEntries + *mCurrentEntryIndexPtr; + } + } + + PX_INLINE void reset() + { + mCurrentHashIndex = 0; + mCurrentEntryIndexPtr = NULL; + } + + private: + PX_INLINE Entry* traverseHashEntries() + { + mCurrentEntryIndexPtr = NULL; + while (mCurrentEntryIndexPtr == NULL && mCurrentHashIndex < mBase.mHashSize) + { + if (mBase.mHash[mCurrentHashIndex] != mBase.EOL) + { + mCurrentEntryIndexPtr = mBase.mHash + mCurrentHashIndex; + mCurrentHashIndex++; + return mBase.mEntries + *mCurrentEntryIndexPtr; + } + else + { + mCurrentHashIndex++; + } + } + return NULL; + } + + PxEraseIterator& operator=(const PxEraseIterator&); + private: + uint32_t* mCurrentEntryIndexPtr; + uint32_t mCurrentHashIndex; + PxHashBase& mBase; + }; +}; + +template +template +PX_NOINLINE void +PxHashBase::copy(const PxHashBase& other) +{ + reserve(other.mEntriesCount); + + for(uint32_t i = 0; i < other.mEntriesCount; i++) + { + for(uint32_t j = other.mHash[i]; j != EOL; j = other.mEntriesNext[j]) + { + const Entry& otherEntry = other.mEntries[j]; + + bool exists; + Entry* newEntry = create(GK()(otherEntry), exists); + PX_ASSERT(!exists); + + PX_PLACEMENT_NEW(newEntry, Entry)(otherEntry); + } + } +} + +template ::Type, bool Coalesced = false> +class PxHashSetBase +{ + PX_NOCOPY(PxHashSetBase) + public: + struct GetKey + { + PX_INLINE const Key& operator()(const Key& e) + { + return e; + } + }; + + typedef PxHashBase BaseMap; + typedef typename BaseMap::Iter Iterator; + + PxHashSetBase(uint32_t initialTableSize, float loadFactor, const PxAllocator& alloc) + : mBase(initialTableSize, loadFactor, alloc) + { + } + + PxHashSetBase(const PxAllocator& alloc) : mBase(64, 0.75f, alloc) + { + } + + PxHashSetBase(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : mBase(initialTableSize, loadFactor) + { + } + + bool insert(const Key& k) + { + bool exists; + Key* e = mBase.create(k, exists); + if(!exists) + PX_PLACEMENT_NEW(e, Key)(k); + return !exists; + } + + PX_INLINE bool contains(const Key& k) const + { + return mBase.find(k) != 0; + } + PX_INLINE bool erase(const Key& k) + { + return mBase.erase(k); + } + PX_INLINE uint32_t size() const + { + return mBase.size(); + } + PX_INLINE uint32_t capacity() const + { + return mBase.capacity(); + } + PX_INLINE void reserve(uint32_t size) + { + mBase.reserve(size); + } + PX_INLINE void clear() + { + mBase.clear(); + } + + protected: + BaseMap mBase; +}; + +template >::Type> +class PxHashMapBase +{ + PX_NOCOPY(PxHashMapBase) + public: + typedef PxPair Entry; + + struct GetKey + { + PX_INLINE const Key& operator()(const Entry& e) + { + return e.first; + } + }; + + typedef PxHashBase BaseMap; + typedef typename BaseMap::Iter Iterator; + typedef typename BaseMap::PxEraseIterator EraseIterator; + + PxHashMapBase(uint32_t initialTableSize, float loadFactor, const PxAllocator& alloc) + : mBase(initialTableSize, loadFactor, alloc) + { + } + + PxHashMapBase(const PxAllocator& alloc) : mBase(64, 0.75f, alloc) + { + } + + PxHashMapBase(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : mBase(initialTableSize, loadFactor) + { + } + + bool insert(const Key /*&*/ k, const Value /*&*/ v) + { + bool exists; + Entry* e = mBase.create(k, exists); + if(!exists) + PX_PLACEMENT_NEW(e, Entry)(k, v); + return !exists; + } + + Value& operator[](const Key& k) + { + bool exists; + Entry* e = mBase.create(k, exists); + if(!exists) + PX_PLACEMENT_NEW(e, Entry)(k, Value()); + + return e->second; + } + + PX_INLINE const Entry* find(const Key& k) const + { + return mBase.find(k); + } + PX_INLINE bool erase(const Key& k) + { + return mBase.erase(k); + } + PX_INLINE bool erase(const Key& k, Entry& e) + { + return mBase.erase(k, e); + } + PX_INLINE uint32_t size() const + { + return mBase.size(); + } + PX_INLINE uint32_t capacity() const + { + return mBase.capacity(); + } + PX_INLINE Iterator getIterator() + { + return Iterator(mBase); + } + PX_INLINE EraseIterator getEraseIterator() + { + return EraseIterator(mBase); + } + PX_INLINE void reserve(uint32_t size) + { + mBase.reserve(size); + } + PX_INLINE void clear() + { + mBase.clear(); + } + + protected: + BaseMap mBase; +}; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#if PX_VC +#pragma warning(pop) +#endif +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashMap.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashMap.h new file mode 100644 index 000000000..476700711 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashMap.h @@ -0,0 +1,119 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HASHMAP_H +#define PX_HASHMAP_H + +#include "foundation/PxHashInternals.h" + +// TODO: make this doxy-format +// +// This header defines two hash maps. Hash maps +// * support custom initial table sizes (rounded up internally to power-of-2) +// * support custom static allocator objects +// * auto-resize, based on a load factor (i.e. a 64-entry .75 load factor hash will resize +// when the 49th element is inserted) +// * are based on open hashing +// * have O(1) contains, erase +// +// Maps have STL-like copying semantics, and properly initialize and destruct copies of objects +// +// There are two forms of map: coalesced and uncoalesced. Coalesced maps keep the entries in the +// initial segment of an array, so are fast to iterate over; however deletion is approximately +// twice as expensive. +// +// HashMap: +// bool insert(const Key& k, const Value& v) O(1) amortized (exponential resize policy) +// Value & operator[](const Key& k) O(1) for existing objects, else O(1) amortized +// const Entry * find(const Key& k); O(1) +// bool erase(const T& k); O(1) +// uint32_t size(); constant +// void reserve(uint32_t size); O(MAX(currentOccupancy,size)) +// void clear(); O(currentOccupancy) (with zero constant for objects +// without +// destructors) +// Iterator getIterator(); +// +// operator[] creates an entry if one does not exist, initializing with the default constructor. +// CoalescedHashMap does not support getIterator, but instead supports +// const Key *getEntries(); +// +// Use of iterators: +// +// for(HashMap::Iterator iter = test.getIterator(); !iter.done(); ++iter) +// myFunction(iter->first, iter->second); + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +template , class Allocator = PxAllocator> +class PxHashMap : public physx::PxHashMapBase +{ + public: + typedef physx::PxHashMapBase HashMapBase; + typedef typename HashMapBase::Iterator Iterator; + + PxHashMap(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : HashMapBase(initialTableSize, loadFactor) + { + } + PxHashMap(uint32_t initialTableSize, float loadFactor, const Allocator& alloc) + : HashMapBase(initialTableSize, loadFactor, alloc) + { + } + PxHashMap(const Allocator& alloc) : HashMapBase(64, 0.75f, alloc) + { + } + Iterator getIterator() + { + return Iterator(HashMapBase::mBase); + } +}; + +template , class Allocator = PxAllocator> +class PxCoalescedHashMap : public physx::PxHashMapBase +{ + public: + typedef physx::PxHashMapBase HashMapBase; + + PxCoalescedHashMap(uint32_t initialTableSize = 64, float loadFactor = 0.75f) + : HashMapBase(initialTableSize, loadFactor) + { + } + const PxPair* getEntries() const + { + return HashMapBase::mBase.getEntries(); + } +}; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashSet.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashSet.h new file mode 100644 index 000000000..fa4c650a9 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxHashSet.h @@ -0,0 +1,128 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HASHSET_H +#define PX_HASHSET_H + +#include "foundation/PxHashInternals.h" + +// TODO: make this doxy-format + +// This header defines two hash sets. Hash sets +// * support custom initial table sizes (rounded up internally to power-of-2) +// * support custom static allocator objects +// * auto-resize, based on a load factor (i.e. a 64-entry .75 load factor hash will resize +// when the 49th element is inserted) +// * are based on open hashing +// +// Sets have STL-like copying semantics, and properly initialize and destruct copies of objects +// +// There are two forms of set: coalesced and uncoalesced. Coalesced sets keep the entries in the +// initial segment of an array, so are fast to iterate over; however deletion is approximately +// twice as expensive. +// +// HashSet: +// bool insert(const T& k) amortized O(1) (exponential resize policy) +// bool contains(const T& k) const; O(1) +// bool erase(const T& k); O(1) +// uint32_t size() const; constant +// void reserve(uint32_t size); O(MAX(size, currentOccupancy)) +// void clear(); O(currentOccupancy) (with zero constant for objects without +// destructors) +// Iterator getIterator(); +// +// Use of iterators: +// +// for(HashSet::Iterator iter = test.getIterator(); !iter.done(); ++iter) +// myFunction(*iter); +// +// CoalescedHashSet does not support getIterator, but instead supports +// const Key *getEntries(); +// +// insertion into a set already containing the element fails returning false, as does +// erasure of an element not in the set +// + +#if !PX_DOXYGEN +namespace physx +{ +#endif +template , class Allocator = PxAllocator> +class PxHashSet : public physx::PxHashSetBase +{ + public: + typedef physx::PxHashSetBase HashSetBase; + typedef typename HashSetBase::Iterator Iterator; + + PxHashSet(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : HashSetBase(initialTableSize, loadFactor) + { + } + PxHashSet(uint32_t initialTableSize, float loadFactor, const Allocator& alloc) + : HashSetBase(initialTableSize, loadFactor, alloc) + { + } + PxHashSet(const Allocator& alloc) : HashSetBase(64, 0.75f, alloc) + { + } + Iterator getIterator() + { + return Iterator(HashSetBase::mBase); + } +}; + +template , class Allocator = PxAllocator> +class PxCoalescedHashSet : public physx::PxHashSetBase +{ + public: + typedef typename physx::PxHashSetBase HashSetBase; + + PxCoalescedHashSet(uint32_t initialTableSize = 64, float loadFactor = 0.75f) + : HashSetBase(initialTableSize, loadFactor) + { + } + + PxCoalescedHashSet(uint32_t initialTableSize, float loadFactor, const Allocator& alloc) + : HashSetBase(initialTableSize, loadFactor, alloc) + { + } + PxCoalescedHashSet(const Allocator& alloc) : HashSetBase(64, 0.75f, alloc) + { + } + + const Key* getEntries() const + { + return HashSetBase::mBase.getEntries(); + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxIO.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxIO.h new file mode 100644 index 000000000..177d4776e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxIO.h @@ -0,0 +1,140 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_IO_H +#define PX_IO_H + + +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** enum for empty constructor tag*/ +enum PxEMPTY +{ + PxEmpty +}; + +/** +\brief Input stream class for I/O. + +The user needs to supply a PxInputStream implementation to a number of methods to allow the SDK to read data. +*/ + +class PxInputStream +{ + public: + /** + \brief read from the stream. The number of bytes read may be less than the number requested. + + \param[in] dest the destination address to which the data will be read + \param[in] count the number of bytes requested + + \return the number of bytes read from the stream. + */ + + virtual uint32_t read(void* dest, uint32_t count) = 0; + + virtual ~PxInputStream() + { + } +}; + +/** +\brief Input data class for I/O which provides random read access. + +The user needs to supply a PxInputData implementation to a number of methods to allow the SDK to read data. +*/ + +class PxInputData : public PxInputStream +{ + public: + /** + \brief return the length of the input data + + \return size in bytes of the input data + */ + + virtual uint32_t getLength() const = 0; + + /** + \brief seek to the given offset from the start of the data. + + \param[in] offset the offset to seek to. If greater than the length of the data, this call is equivalent to + seek(length); + */ + + virtual void seek(uint32_t offset) = 0; + + /** + \brief return the current offset from the start of the data + + \return the offset to seek to. + */ + + virtual uint32_t tell() const = 0; + + virtual ~PxInputData() + { + } +}; + +/** +\brief Output stream class for I/O. + +The user needs to supply a PxOutputStream implementation to a number of methods to allow the SDK to write data. +*/ + +class PxOutputStream +{ + public: + /** + \brief write to the stream. The number of bytes written may be less than the number sent. + + \param[in] src the destination address from which the data will be written + \param[in] count the number of bytes to be written + + \return the number of bytes written to the stream by this call. + */ + + virtual uint32_t write(const void* src, uint32_t count) = 0; + + virtual ~PxOutputStream() + { + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineAllocator.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineAllocator.h new file mode 100644 index 000000000..3084e00e0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineAllocator.h @@ -0,0 +1,94 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_INLINE_ALLOCATOR_H +#define PX_INLINE_ALLOCATOR_H + +#include "foundation/PxUserAllocated.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +// this is used by the array class to allocate some space for a small number +// of objects along with the metadata +template +class PxInlineAllocator : private BaseAllocator +{ + public: + PxInlineAllocator(const PxEMPTY v) : BaseAllocator(v) + { + } + + PxInlineAllocator(const BaseAllocator& alloc = BaseAllocator()) : BaseAllocator(alloc), mBufferUsed(false) + { + } + + PxInlineAllocator(const PxInlineAllocator& aloc) : BaseAllocator(aloc), mBufferUsed(false) + { + } + + void* allocate(PxU32 size, const char* filename, PxI32 line, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + if(!mBufferUsed && size <= N) + { + mBufferUsed = true; + return mBuffer; + } + return BaseAllocator::allocate(size, filename, line); + } + + void deallocate(void* ptr, uint32_t* cookie=NULL) + { + PX_UNUSED(cookie); + if(ptr == mBuffer) + mBufferUsed = false; + else + BaseAllocator::deallocate(ptr); + } + + PX_FORCE_INLINE PxU8* getInlineBuffer() + { + return mBuffer; + } + PX_FORCE_INLINE bool isBufferUsed() const + { + return mBufferUsed; + } + + protected: + PxU8 mBuffer[N]; + bool mBufferUsed; +}; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineAoS.h new file mode 100644 index 000000000..5d7c0ceb2 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineAoS.h @@ -0,0 +1,45 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_INLINE_AOS_H +#define PX_INLINE_AOS_H + +#include "foundation/PxPreprocessor.h" + +#if PX_WINDOWS +#include "windows/PxWindowsTrigConstants.h" +#include "windows/PxWindowsInlineAoS.h" +#elif(PX_UNIX_FAMILY || PX_SWITCH) +#include "unix/PxUnixTrigConstants.h" +#include "unix/PxUnixInlineAoS.h" +#else +#error "Platform not supported!" +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineArray.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineArray.h new file mode 100644 index 000000000..88314fbb7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxInlineArray.h @@ -0,0 +1,69 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_INLINE_ARRAY_H +#define PX_INLINE_ARRAY_H + +#include "foundation/PxArray.h" +#include "foundation/PxInlineAllocator.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +// array that pre-allocates for N elements +template ::Type> +class PxInlineArray : public PxArray > +{ + typedef PxInlineAllocator Allocator; + + public: + PxInlineArray(const PxEMPTY v) : PxArray(v) + { + if(isInlined()) + this->mData = reinterpret_cast(PxArray::getInlineBuffer()); + } + + PX_INLINE bool isInlined() const + { + return Allocator::isBufferUsed(); + } + + PX_INLINE explicit PxInlineArray(const Alloc& alloc = Alloc()) : PxArray(alloc) + { + this->mData = this->allocate(N); + this->mCapacity = N; + } +}; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxIntrinsics.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxIntrinsics.h new file mode 100644 index 000000000..a60eca75b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxIntrinsics.h @@ -0,0 +1,44 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_INTRINSICS_H +#define PX_INTRINSICS_H + +#include "foundation/PxPreprocessor.h" +#if PX_WINDOWS_FAMILY +#include "windows/PxWindowsIntrinsics.h" +#elif(PX_LINUX || PX_APPLE_FAMILY) +#include "unix/PxUnixIntrinsics.h" +#elif PX_SWITCH +#include "switch/PxSwitchIntrinsics.h" +#else +#error "Platform not supported!" +#endif + + +#endif // #ifndef PX_INTRINSICS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat33.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat33.h new file mode 100644 index 000000000..4aac4f918 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat33.h @@ -0,0 +1,508 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MAT33_H +#define PX_MAT33_H + +#include "foundation/PxVec3.h" +#include "foundation/PxQuat.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +/*! +\brief 3x3 matrix class + +Some clarifications, as there have been much confusion about matrix formats etc in the past. + +Short: +- Matrix have base vectors in columns (vectors are column matrices, 3x1 matrices). +- Matrix is physically stored in column major format +- Matrices are concaternated from left + +Long: +Given three base vectors a, b and c the matrix is stored as + +|a.x b.x c.x| +|a.y b.y c.y| +|a.z b.z c.z| + +Vectors are treated as columns, so the vector v is + +|x| +|y| +|z| + +And matrices are applied _before_ the vector (pre-multiplication) +v' = M*v + +|x'| |a.x b.x c.x| |x| |a.x*x + b.x*y + c.x*z| +|y'| = |a.y b.y c.y| * |y| = |a.y*x + b.y*y + c.y*z| +|z'| |a.z b.z c.z| |z| |a.z*x + b.z*y + c.z*z| + + +Physical storage and indexing: +To be compatible with popular 3d rendering APIs (read D3d and OpenGL) +the physical indexing is + +|0 3 6| +|1 4 7| +|2 5 8| + +index = column*3 + row + +which in C++ translates to M[column][row] + +The mathematical indexing is M_row,column and this is what is used for _-notation +so _12 is 1st row, second column and operator(row, column)! +*/ + +template +class PxMat33T +{ + public: + //! Default constructor + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33T() + { + } + + //! identity constructor + PX_CUDA_CALLABLE PX_INLINE PxMat33T(PxIDENTITY) : + column0(Type(1.0), Type(0.0), Type(0.0)), + column1(Type(0.0), Type(1.0), Type(0.0)), + column2(Type(0.0), Type(0.0), Type(1.0)) + { + } + + //! zero constructor + PX_CUDA_CALLABLE PX_INLINE PxMat33T(PxZERO) : + column0(Type(0.0)), + column1(Type(0.0)), + column2(Type(0.0)) + { + } + + //! Construct from three base vectors + PX_CUDA_CALLABLE PxMat33T(const PxVec3T& col0, const PxVec3T& col1, const PxVec3T& col2) : + column0(col0), + column1(col1), + column2(col2) + { + } + + //! constructor from a scalar, which generates a multiple of the identity matrix + explicit PX_CUDA_CALLABLE PX_INLINE PxMat33T(Type r) : + column0(r, Type(0.0), Type(0.0)), + column1(Type(0.0), r, Type(0.0)), + column2(Type(0.0), Type(0.0), r) + { + } + + //! Construct from Type[9] + explicit PX_CUDA_CALLABLE PX_INLINE PxMat33T(Type values[]) : + column0(values[0], values[1], values[2]), + column1(values[3], values[4], values[5]), + column2(values[6], values[7], values[8]) + { + } + + //! Construct from a quaternion + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33T(const PxQuatT& q) + { + // PT: TODO: PX-566 + const Type x = q.x; + const Type y = q.y; + const Type z = q.z; + const Type w = q.w; + + const Type x2 = x + x; + const Type y2 = y + y; + const Type z2 = z + z; + + const Type xx = x2 * x; + const Type yy = y2 * y; + const Type zz = z2 * z; + + const Type xy = x2 * y; + const Type xz = x2 * z; + const Type xw = x2 * w; + + const Type yz = y2 * z; + const Type yw = y2 * w; + const Type zw = z2 * w; + + column0 = PxVec3T(Type(1.0) - yy - zz, xy + zw, xz - yw); + column1 = PxVec3T(xy - zw, Type(1.0) - xx - zz, yz + xw); + column2 = PxVec3T(xz + yw, yz - xw, Type(1.0) - xx - yy); + } + + //! Copy constructor + PX_CUDA_CALLABLE PX_INLINE PxMat33T(const PxMat33T& other) : + column0(other.column0), + column1(other.column1), + column2(other.column2) + { + } + + //! Assignment operator + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33T& operator=(const PxMat33T& other) + { + column0 = other.column0; + column1 = other.column1; + column2 = other.column2; + return *this; + } + + //! Construct from diagonal, off-diagonals are zero. + PX_CUDA_CALLABLE PX_INLINE static const PxMat33T createDiagonal(const PxVec3T& d) + { + return PxMat33T(PxVec3T(d.x, Type(0.0), Type(0.0)), + PxVec3T(Type(0.0), d.y, Type(0.0)), + PxVec3T(Type(0.0), Type(0.0), d.z)); + } + + //! Computes the outer product of two vectors + PX_CUDA_CALLABLE PX_INLINE static const PxMat33T outer(const PxVec3T& a, const PxVec3T& b) + { + return PxMat33T(a * b.x, a * b.y, a * b.z); + } + + /** + \brief returns true if the two matrices are exactly equal + */ + PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxMat33T& m) const + { + return column0 == m.column0 && column1 == m.column1 && column2 == m.column2; + } + + //! Get transposed matrix + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxMat33T getTranspose() const + { + const PxVec3T v0(column0.x, column1.x, column2.x); + const PxVec3T v1(column0.y, column1.y, column2.y); + const PxVec3T v2(column0.z, column1.z, column2.z); + + return PxMat33T(v0, v1, v2); + } + + //! Get the real inverse + PX_CUDA_CALLABLE PX_INLINE const PxMat33T getInverse() const + { + const Type det = getDeterminant(); + PxMat33T inverse; + + if(det != Type(0.0)) + { + const Type invDet = Type(1.0) / det; + + inverse.column0.x = invDet * (column1.y * column2.z - column2.y * column1.z); + inverse.column0.y = invDet * -(column0.y * column2.z - column2.y * column0.z); + inverse.column0.z = invDet * (column0.y * column1.z - column0.z * column1.y); + + inverse.column1.x = invDet * -(column1.x * column2.z - column1.z * column2.x); + inverse.column1.y = invDet * (column0.x * column2.z - column0.z * column2.x); + inverse.column1.z = invDet * -(column0.x * column1.z - column0.z * column1.x); + + inverse.column2.x = invDet * (column1.x * column2.y - column1.y * column2.x); + inverse.column2.y = invDet * -(column0.x * column2.y - column0.y * column2.x); + inverse.column2.z = invDet * (column0.x * column1.y - column1.x * column0.y); + + return inverse; + } + else + { + return PxMat33T(PxIdentity); + } + } + + //! Get determinant + PX_CUDA_CALLABLE PX_INLINE Type getDeterminant() const + { + return column0.dot(column1.cross(column2)); + } + + //! Unary minus + PX_CUDA_CALLABLE PX_INLINE const PxMat33T operator-() const + { + return PxMat33T(-column0, -column1, -column2); + } + + //! Add + PX_CUDA_CALLABLE PX_INLINE const PxMat33T operator+(const PxMat33T& other) const + { + return PxMat33T(column0 + other.column0, column1 + other.column1, column2 + other.column2); + } + + //! Subtract + PX_CUDA_CALLABLE PX_INLINE const PxMat33T operator-(const PxMat33T& other) const + { + return PxMat33T(column0 - other.column0, column1 - other.column1, column2 - other.column2); + } + + //! Scalar multiplication + PX_CUDA_CALLABLE PX_INLINE const PxMat33T operator*(Type scalar) const + { + return PxMat33T(column0 * scalar, column1 * scalar, column2 * scalar); + } + + template + PX_CUDA_CALLABLE PX_INLINE friend PxMat33T operator*(Type2, const PxMat33T&); + + //! Matrix vector multiplication (returns 'this->transform(vec)') + PX_CUDA_CALLABLE PX_INLINE const PxVec3T operator*(const PxVec3T& vec) const + { + return transform(vec); + } + + // a = b operators + + //! Matrix multiplication + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxMat33T operator*(const PxMat33T& other) const + { + // Rows from this columns from other + // column0 = transform(other.column0) etc + return PxMat33T(transform(other.column0), + transform(other.column1), + transform(other.column2)); + } + + //! Equals-add + PX_CUDA_CALLABLE PX_INLINE PxMat33T& operator+=(const PxMat33T& other) + { + column0 += other.column0; + column1 += other.column1; + column2 += other.column2; + return *this; + } + + //! Equals-sub + PX_CUDA_CALLABLE PX_INLINE PxMat33T& operator-=(const PxMat33T& other) + { + column0 -= other.column0; + column1 -= other.column1; + column2 -= other.column2; + return *this; + } + + //! Equals scalar multiplication + PX_CUDA_CALLABLE PX_INLINE PxMat33T& operator*=(Type scalar) + { + column0 *= scalar; + column1 *= scalar; + column2 *= scalar; + return *this; + } + + //! Equals matrix multiplication + PX_CUDA_CALLABLE PX_INLINE PxMat33T& operator*=(const PxMat33T& other) + { + *this = *this * other; + return *this; + } + + //! Element access, mathematical way! + PX_CUDA_CALLABLE PX_FORCE_INLINE Type operator()(PxU32 row, PxU32 col) const + { + return (*this)[col][row]; + } + + //! Element access, mathematical way! + PX_CUDA_CALLABLE PX_FORCE_INLINE Type& operator()(PxU32 row, PxU32 col) + { + return (*this)[col][row]; + } + + // Transform etc + + //! Transform vector by matrix, equal to v' = M*v + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3T transform(const PxVec3T& other) const + { + return column0 * other.x + column1 * other.y + column2 * other.z; + } + + //! Transform vector by matrix transpose, v' = M^t*v + PX_CUDA_CALLABLE PX_INLINE const PxVec3T transformTranspose(const PxVec3T& other) const + { + return PxVec3T(column0.dot(other), column1.dot(other), column2.dot(other)); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE const Type* front() const + { + return &column0.x; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T& operator[](PxU32 num) + { + return (&column0)[num]; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3T& operator[](PxU32 num) const + { + return (&column0)[num]; + } + + // Data, see above for format! + + PxVec3T column0, column1, column2; // the three base vectors +}; + +template +PX_CUDA_CALLABLE PX_INLINE PxMat33T operator*(Type scalar, const PxMat33T& m) +{ + return PxMat33T(scalar * m.column0, scalar * m.column1, scalar * m.column2); +} + +// implementation from PxQuat.h +template +PX_CUDA_CALLABLE PX_INLINE PxQuatT::PxQuatT(const PxMat33T& m) +{ + if(m.column2.z < Type(0)) + { + if(m.column0.x > m.column1.y) + { + const Type t = Type(1.0) + m.column0.x - m.column1.y - m.column2.z; + *this = PxQuatT(t, m.column0.y + m.column1.x, m.column2.x + m.column0.z, m.column1.z - m.column2.y) * (Type(0.5) / PxSqrt(t)); + } + else + { + const Type t = Type(1.0) - m.column0.x + m.column1.y - m.column2.z; + *this = PxQuatT(m.column0.y + m.column1.x, t, m.column1.z + m.column2.y, m.column2.x - m.column0.z) * (Type(0.5) / PxSqrt(t)); + } + } + else + { + if(m.column0.x < -m.column1.y) + { + const Type t = Type(1.0) - m.column0.x - m.column1.y + m.column2.z; + *this = PxQuatT(m.column2.x + m.column0.z, m.column1.z + m.column2.y, t, m.column0.y - m.column1.x) * (Type(0.5) / PxSqrt(t)); + } + else + { + const Type t = Type(1.0) + m.column0.x + m.column1.y + m.column2.z; + *this = PxQuatT(m.column1.z - m.column2.y, m.column2.x - m.column0.z, m.column0.y - m.column1.x, t) * (Type(0.5) / PxSqrt(t)); + } + } +} + +typedef PxMat33T PxMat33; +typedef PxMat33T PxMat33d; + + /** + \brief Sets a rotation matrix around the X axis. + \param m [out] output rotation matrix + \param angle [in] desired angle + */ + PX_INLINE void PxSetRotX(PxMat33& m, PxReal angle) + { + m = PxMat33(PxIdentity); + + PxReal sin, cos; + PxSinCos(angle, sin, cos); + + m[1][1] = m[2][2] = cos; + m[1][2] = sin; + m[2][1] = -sin; + } + + /** + \brief Sets a rotation matrix around the Y axis. + \param m [out] output rotation matrix + \param angle [in] desired angle + */ + PX_INLINE void PxSetRotY(PxMat33& m, PxReal angle) + { + m = PxMat33(PxIdentity); + + PxReal sin, cos; + PxSinCos(angle, sin, cos); + + m[0][0] = m[2][2] = cos; + m[0][2] = -sin; + m[2][0] = sin; + } + + /** + \brief Sets a rotation matrix around the Z axis. + \param m [out] output rotation matrix + \param angle [in] desired angle + */ + PX_INLINE void PxSetRotZ(PxMat33& m, PxReal angle) + { + m = PxMat33(PxIdentity); + + PxReal sin, cos; + PxSinCos(angle, sin, cos); + + m[0][0] = m[1][1] = cos; + m[0][1] = sin; + m[1][0] = -sin; + } + + /** + \brief Returns a rotation quaternion around the X axis. + \param angle [in] desired angle + \return Quaternion that rotates around the desired axis + */ + PX_INLINE PxQuat PxGetRotXQuat(float angle) + { + PxMat33 m; + PxSetRotX(m, angle); + return PxQuat(m); + } + + /** + \brief Returns a rotation quaternion around the Y axis. + \param angle [in] desired angle + \return Quaternion that rotates around the desired axis + */ + PX_INLINE PxQuat PxGetRotYQuat(float angle) + { + PxMat33 m; + PxSetRotY(m, angle); + return PxQuat(m); + } + + /** + \brief Returns a rotation quaternion around the Z axis. + \param angle [in] desired angle + \return Quaternion that rotates around the desired axis + */ + PX_INLINE PxQuat PxGetRotZQuat(float angle) + { + PxMat33 m; + PxSetRotZ(m, angle); + return PxQuat(m); + } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat34.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat34.h new file mode 100644 index 000000000..3b8f0cecb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat34.h @@ -0,0 +1,273 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MAT34_H +#define PX_MAT34_H + +#include "foundation/PxTransform.h" +#include "foundation/PxMat33.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +/*! +Basic mathematical 3x4 matrix, implemented as a 3x3 rotation matrix and a translation + +See PxMat33 for the format of the rotation matrix. +*/ + +template +class PxMat34T +{ + public: + //! Default constructor + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T() + { + } + + //! Construct from four base vectors + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T(const PxVec3T& b0, const PxVec3T& b1, const PxVec3T& b2, const PxVec3T& b3) + : m(b0, b1, b2), p(b3) + { + } + + //! Construct from Type[12] + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T(Type values[]) : + m(values), p(values[9], values[10], values[11]) + { + } + + //! Construct from a 3x3 matrix + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T(const PxMat33T& other) + : m(other), p(PxZero) + { + } + + //! Construct from a 3x3 matrix and a translation vector + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T(const PxMat33T& other, const PxVec3T& t) + : m(other), p(t) + { + } + + //! Construct from a PxTransformT + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T(const PxTransformT& other) + : m(other.q), p(other.p) + { + } + + //! Copy constructor + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T(const PxMat34T& other) : m(other.m), p(other.p) + { + } + + //! Assignment operator + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxMat34T& operator=(const PxMat34T& other) + { + m = other.m; + p = other.p; + return *this; + } + + //! Set to identity matrix + PX_CUDA_CALLABLE PX_FORCE_INLINE void setIdentity() + { + m = PxMat33T(PxIdentity); + p = PxVec3T(0); + } + + // Simpler operators + //! Equality operator + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator==(const PxMat34T& other) const + { + return m == other.m && p == other.p; + } + + //! Inequality operator + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator!=(const PxMat34T& other) const + { + return !operator==(other); + } + + //! Unary minus + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T operator-() const + { + return PxMat34T(-m, -p); + } + + //! Add + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T operator+(const PxMat34T& other) const + { + return PxMat34T(m + other.m, p + other.p); + } + + //! Subtract + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T operator-(const PxMat34T& other) const + { + return PxMat34T(m - other.m, p - other.p); + } + + //! Scalar multiplication + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T operator*(Type scalar) const + { + return PxMat34T(m*scalar, p*scalar); + } + + //! Matrix multiplication + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T operator*(const PxMat34T& other) const + { + //Rows from this columns from other + //base0 = rotate(other.m.column0) etc + return PxMat34T(m*other.m, m*other.p + p); + } + + //! Matrix multiplication, extend the second matrix + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T operator*(const PxMat33T& other) const + { + //Rows from this columns from other + //base0 = transform(other.m.column0) etc + return PxMat34T(m*other, p); + } + + template + friend PxMat34T operator*(const PxMat33T& a, const PxMat34T& b); + + // a = b operators + + //! Equals-add + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T& operator+=(const PxMat34T& other) + { + m += other.m; + p += other.p; + return *this; + } + + //! Equals-sub + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T& operator-=(const PxMat34T& other) + { + m -= other.m; + p -= other.p; + return *this; + } + + //! Equals scalar multiplication + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T& operator*=(Type scalar) + { + m *= scalar; + p *= scalar; + return *this; + } + + //! Element access, mathematical way! + PX_CUDA_CALLABLE PX_FORCE_INLINE Type operator()(PxU32 row, PxU32 col) const + { + return (*this)[col][row]; + } + + //! Element access, mathematical way! + PX_CUDA_CALLABLE PX_FORCE_INLINE Type& operator()(PxU32 row, PxU32 col) + { + return (*this)[col][row]; + } + + // Transform etc + + //! Transform vector by matrix, equal to v' = M*v + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T rotate(const PxVec3T& other) const + { + return m*other; + } + + //! Transform vector by transpose of matrix, equal to v' = M^t*v + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T rotateTranspose(const PxVec3T& other) const + { + return m.transformTranspose(other); + } + + //! Transform point by matrix + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T transform(const PxVec3T& other) const + { + return m*other + p; + } + + //! Transform point by transposed matrix + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T transformTranspose(const PxVec3T& other) const + { + return m.transformTranspose(other - p); + } + + //! Transform point by transposed matrix + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T transformTranspose(const PxMat34T& other) const + { + return PxMat34T(m.transformTranspose(other.m.column0), + m.transformTranspose(other.m.column1), + m.transformTranspose(other.m.column2), + m.transformTranspose(other.p - p)); + } + + //! Invert matrix treating it as a rotation+translation matrix only + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat34T getInverseRT() const + { + return PxMat34T(m.getTranspose(), m.transformTranspose(-p)); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T& operator[](PxU32 num) { return (&m.column0)[num]; } + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3T& operator[](PxU32 num) const { return (&m.column0)[num]; } + + //Data, see above for format! + + PxMat33T m; + PxVec3T p; +}; + +//! Multiply a*b, a is extended +template +PX_INLINE PxMat34T operator*(const PxMat33T& a, const PxMat34T& b) +{ + return PxMat34T(a * b.m, a * b.p); +} + +typedef PxMat34T PxMat34; +typedef PxMat34T PxMat34d; + +//! A padded version of PxMat34, to safely load its data using SIMD +class PxMat34Padded : public PxMat34 +{ + public: + PX_FORCE_INLINE PxMat34Padded(const PxMat34& src) : PxMat34(src) {} + PX_FORCE_INLINE PxMat34Padded() {} + PX_FORCE_INLINE ~PxMat34Padded() {} + PxU32 padding; +}; +PX_COMPILE_TIME_ASSERT(0==(sizeof(PxMat34Padded)==16)); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat44.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat44.h new file mode 100644 index 000000000..85161d421 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMat44.h @@ -0,0 +1,387 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MAT44_H +#define PX_MAT44_H + +#include "foundation/PxQuat.h" +#include "foundation/PxVec4.h" +#include "foundation/PxMat33.h" +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/*! +\brief 4x4 matrix class + +This class is layout-compatible with D3D and OpenGL matrices. More notes on layout are given in the PxMat33 + +\see PxMat33 PxTransform +*/ + +template +class PxMat44T +{ + public: + //! Default constructor + PX_CUDA_CALLABLE PX_INLINE PxMat44T() + { + } + + //! identity constructor + PX_CUDA_CALLABLE PX_INLINE PxMat44T(PxIDENTITY) : + column0(Type(1.0), Type(0.0), Type(0.0), Type(0.0)), + column1(Type(0.0), Type(1.0), Type(0.0), Type(0.0)), + column2(Type(0.0), Type(0.0), Type(1.0), Type(0.0)), + column3(Type(0.0), Type(0.0), Type(0.0), Type(1.0)) + { + } + + //! zero constructor + PX_CUDA_CALLABLE PX_INLINE PxMat44T(PxZERO) : column0(PxZero), column1(PxZero), column2(PxZero), column3(PxZero) + { + } + + //! Construct from four 4-vectors + PX_CUDA_CALLABLE PxMat44T(const PxVec4T& col0, const PxVec4T& col1, const PxVec4T& col2, const PxVec4T& col3) : + column0(col0), + column1(col1), + column2(col2), + column3(col3) + { + } + + //! constructor that generates a multiple of the identity matrix + explicit PX_CUDA_CALLABLE PX_INLINE PxMat44T(Type r) : + column0(r, Type(0.0), Type(0.0), Type(0.0)), + column1(Type(0.0), r, Type(0.0), Type(0.0)), + column2(Type(0.0), Type(0.0), r, Type(0.0)), + column3(Type(0.0), Type(0.0), Type(0.0), r) + { + } + + //! Construct from three base vectors and a translation + PX_CUDA_CALLABLE PxMat44T(const PxVec3T& col0, const PxVec3T& col1, const PxVec3T& col2, const PxVec3T& col3) : + column0(col0, Type(0.0)), + column1(col1, Type(0.0)), + column2(col2, Type(0.0)), + column3(col3, Type(1.0)) + { + } + + //! Construct from Type[16] + explicit PX_CUDA_CALLABLE PX_INLINE PxMat44T(Type values[]) : + column0(values[0], values[1], values[2], values[3]), + column1(values[4], values[5], values[6], values[7]), + column2(values[8], values[9], values[10], values[11]), + column3(values[12], values[13], values[14], values[15]) + { + } + + //! Construct from a quaternion + explicit PX_CUDA_CALLABLE PX_INLINE PxMat44T(const PxQuatT& q) + { + // PT: TODO: PX-566 + const Type x = q.x; + const Type y = q.y; + const Type z = q.z; + const Type w = q.w; + + const Type x2 = x + x; + const Type y2 = y + y; + const Type z2 = z + z; + + const Type xx = x2 * x; + const Type yy = y2 * y; + const Type zz = z2 * z; + + const Type xy = x2 * y; + const Type xz = x2 * z; + const Type xw = x2 * w; + + const Type yz = y2 * z; + const Type yw = y2 * w; + const Type zw = z2 * w; + + column0 = PxVec4T(Type(1.0) - yy - zz, xy + zw, xz - yw, Type(0.0)); + column1 = PxVec4T(xy - zw, Type(1.0) - xx - zz, yz + xw, Type(0.0)); + column2 = PxVec4T(xz + yw, yz - xw, Type(1.0) - xx - yy, Type(0.0)); + column3 = PxVec4T(Type(0.0), Type(0.0), Type(0.0), Type(1.0)); + } + + //! Construct from a diagonal vector + explicit PX_CUDA_CALLABLE PX_INLINE PxMat44T(const PxVec4T& diagonal) : + column0(diagonal.x, Type(0.0), Type(0.0), Type(0.0)), + column1(Type(0.0), diagonal.y, Type(0.0), Type(0.0)), + column2(Type(0.0), Type(0.0), diagonal.z, Type(0.0)), + column3(Type(0.0), Type(0.0), Type(0.0), diagonal.w) + { + } + + //! Construct from Mat33 and a translation + PX_CUDA_CALLABLE PxMat44T(const PxMat33T& axes, const PxVec3T& position) : + column0(axes.column0, Type(0.0)), + column1(axes.column1, Type(0.0)), + column2(axes.column2, Type(0.0)), + column3(position, Type(1.0)) + { + } + + PX_CUDA_CALLABLE PxMat44T(const PxTransform& t) + { + *this = PxMat44T(PxMat33T(t.q), t.p); + } + + /** + \brief returns true if the two matrices are exactly equal + */ + PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxMat44T& m) const + { + return column0 == m.column0 && column1 == m.column1 && column2 == m.column2 && column3 == m.column3; + } + + //! Copy constructor + PX_CUDA_CALLABLE PX_INLINE PxMat44T(const PxMat44T& other) : + column0(other.column0), + column1(other.column1), + column2(other.column2), + column3(other.column3) + { + } + + //! Assignment operator + PX_CUDA_CALLABLE PX_INLINE PxMat44T& operator=(const PxMat44T& other) + { + column0 = other.column0; + column1 = other.column1; + column2 = other.column2; + column3 = other.column3; + return *this; + } + + //! Get transposed matrix + PX_CUDA_CALLABLE PX_INLINE const PxMat44T getTranspose() const + { + return PxMat44T( + PxVec4T(column0.x, column1.x, column2.x, column3.x), PxVec4T(column0.y, column1.y, column2.y, column3.y), + PxVec4T(column0.z, column1.z, column2.z, column3.z), PxVec4T(column0.w, column1.w, column2.w, column3.w)); + } + + //! Unary minus + PX_CUDA_CALLABLE PX_INLINE const PxMat44T operator-() const + { + return PxMat44T(-column0, -column1, -column2, -column3); + } + + //! Add + PX_CUDA_CALLABLE PX_INLINE const PxMat44T operator+(const PxMat44T& other) const + { + return PxMat44T(column0 + other.column0, column1 + other.column1, column2 + other.column2, column3 + other.column3); + } + + //! Subtract + PX_CUDA_CALLABLE PX_INLINE const PxMat44T operator-(const PxMat44T& other) const + { + return PxMat44T(column0 - other.column0, column1 - other.column1, column2 - other.column2, column3 - other.column3); + } + + //! Scalar multiplication + PX_CUDA_CALLABLE PX_INLINE const PxMat44T operator*(Type scalar) const + { + return PxMat44T(column0 * scalar, column1 * scalar, column2 * scalar, column3 * scalar); + } + + template + friend PxMat44T operator*(Type2, const PxMat44T&); + + //! Matrix multiplication + PX_CUDA_CALLABLE PX_INLINE const PxMat44T operator*(const PxMat44T& other) const + { + // Rows from this columns from other + // column0 = transform(other.column0) etc + return PxMat44T(transform(other.column0), transform(other.column1), transform(other.column2), transform(other.column3)); + } + + // a = b operators + + //! Equals-add + PX_CUDA_CALLABLE PX_INLINE PxMat44T& operator+=(const PxMat44T& other) + { + column0 += other.column0; + column1 += other.column1; + column2 += other.column2; + column3 += other.column3; + return *this; + } + + //! Equals-sub + PX_CUDA_CALLABLE PX_INLINE PxMat44T& operator-=(const PxMat44T& other) + { + column0 -= other.column0; + column1 -= other.column1; + column2 -= other.column2; + column3 -= other.column3; + return *this; + } + + //! Equals scalar multiplication + PX_CUDA_CALLABLE PX_INLINE PxMat44T& operator*=(Type scalar) + { + column0 *= scalar; + column1 *= scalar; + column2 *= scalar; + column3 *= scalar; + return *this; + } + + //! Equals matrix multiplication + PX_CUDA_CALLABLE PX_INLINE PxMat44T& operator*=(const PxMat44T& other) + { + *this = *this * other; + return *this; + } + + //! Element access, mathematical way! + PX_CUDA_CALLABLE PX_FORCE_INLINE Type operator()(PxU32 row, PxU32 col) const + { + return (*this)[col][row]; + } + + //! Element access, mathematical way! + PX_CUDA_CALLABLE PX_FORCE_INLINE Type& operator()(PxU32 row, PxU32 col) + { + return (*this)[col][row]; + } + + //! Transform vector by matrix, equal to v' = M*v + PX_CUDA_CALLABLE PX_INLINE const PxVec4T transform(const PxVec4T& other) const + { + return column0 * other.x + column1 * other.y + column2 * other.z + column3 * other.w; + } + + //! Transform vector by matrix, equal to v' = M*v + PX_CUDA_CALLABLE PX_INLINE const PxVec3T transform(const PxVec3T& other) const + { + return transform(PxVec4T(other, Type(1.0))).getXYZ(); + } + + //! Rotate vector by matrix, equal to v' = M*v + PX_CUDA_CALLABLE PX_INLINE const PxVec4T rotate(const PxVec4T& other) const + { + return column0 * other.x + column1 * other.y + column2 * other.z; // + column3*0; + } + + //! Rotate vector by matrix, equal to v' = M*v + PX_CUDA_CALLABLE PX_INLINE const PxVec3T rotate(const PxVec3T& other) const + { + return rotate(PxVec4T(other, Type(1.0))).getXYZ(); + } + + PX_CUDA_CALLABLE PX_INLINE const PxVec3T getBasis(PxU32 num) const + { + PX_ASSERT(num < 3); + return (&column0)[num].getXYZ(); + } + + PX_CUDA_CALLABLE PX_INLINE const PxVec3T getPosition() const + { + return column3.getXYZ(); + } + + PX_CUDA_CALLABLE PX_INLINE void setPosition(const PxVec3T& position) + { + column3.x = position.x; + column3.y = position.y; + column3.z = position.z; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE const Type* front() const + { + return &column0.x; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4T& operator[](PxU32 num) + { + return (&column0)[num]; + } + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec4T& operator[](PxU32 num) const + { + return (&column0)[num]; + } + + PX_CUDA_CALLABLE PX_INLINE void scale(const PxVec4T& p) + { + column0 *= p.x; + column1 *= p.y; + column2 *= p.z; + column3 *= p.w; + } + + PX_CUDA_CALLABLE PX_INLINE const PxMat44T inverseRT() const + { + const PxVec3T r0(column0.x, column1.x, column2.x); + const PxVec3T r1(column0.y, column1.y, column2.y); + const PxVec3T r2(column0.z, column1.z, column2.z); + + return PxMat44T(r0, r1, r2, -(r0 * column3.x + r1 * column3.y + r2 * column3.z)); + } + + PX_CUDA_CALLABLE PX_INLINE bool isFinite() const + { + return column0.isFinite() && column1.isFinite() && column2.isFinite() && column3.isFinite(); + } + + // Data, see above for format! + + PxVec4T column0, column1, column2, column3; // the four base vectors +}; + +// implementation from PxTransform.h +template +PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT::PxTransformT(const PxMat44T& m) +{ + const PxVec3T column0(m.column0.x, m.column0.y, m.column0.z); + const PxVec3T column1(m.column1.x, m.column1.y, m.column1.z); + const PxVec3T column2(m.column2.x, m.column2.y, m.column2.z); + + q = PxQuatT(PxMat33T(column0, column1, column2)); + p = PxVec3T(m.column3.x, m.column3.y, m.column3.z); +} + +typedef PxMat44T PxMat44; +typedef PxMat44T PxMat44d; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMath.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMath.h new file mode 100644 index 000000000..b2866f485 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMath.h @@ -0,0 +1,380 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MATH_H +#define PX_MATH_H + + +#include "foundation/PxPreprocessor.h" + + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4985) // 'symbol name': attributes not present on previous declaration +#endif +#include +#if PX_VC +#pragma warning(pop) +#endif + +#if (PX_LINUX_FAMILY && !PX_ARM_FAMILY) +// Force linking against nothing newer than glibc v2.17 to remain compatible with platforms with older glibc versions +__asm__(".symver expf,expf@GLIBC_2.2.5"); +__asm__(".symver powf,powf@GLIBC_2.2.5"); +#endif + +#include +#include "foundation/PxMathIntrinsics.h" +#include "foundation/PxAssert.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +// constants +static constexpr float PxPi = float(3.141592653589793); +static constexpr float PxHalfPi = float(1.57079632679489661923); +static constexpr float PxTwoPi = float(6.28318530717958647692); +static constexpr float PxInvPi = float(0.31830988618379067154); +static constexpr float PxInvTwoPi = float(0.15915494309189533577); +static constexpr float PxPiDivTwo = float(1.57079632679489661923); +static constexpr float PxPiDivFour = float(0.78539816339744830962); +static constexpr float PxSqrt2 = float(1.4142135623730951); +static constexpr float PxInvSqrt2 = float(0.7071067811865476); + +/** +\brief The return value is the greater of the two specified values. +*/ +template +PX_CUDA_CALLABLE PX_FORCE_INLINE T PxMax(T a, T b) +{ + return a < b ? b : a; +} + +//! overload for float to use fsel on xbox +template <> +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxMax(float a, float b) +{ + return intrinsics::selectMax(a, b); +} + +/** +\brief The return value is the lesser of the two specified values. +*/ +template +PX_CUDA_CALLABLE PX_FORCE_INLINE T PxMin(T a, T b) +{ + return a < b ? a : b; +} + +template <> +//! overload for float to use fsel on xbox +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxMin(float a, float b) +{ + return intrinsics::selectMin(a, b); +} + +/* +Many of these are just implemented as PX_CUDA_CALLABLE PX_FORCE_INLINE calls to the C lib right now, +but later we could replace some of them with some approximations or more +clever stuff. +*/ + +/** +\brief abs returns the absolute value of its argument. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAbs(float a) +{ + return intrinsics::abs(a); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxEquals(float a, float b, float eps) +{ + return (PxAbs(a - b) < eps); +} + +/** +\brief abs returns the absolute value of its argument. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAbs(double a) +{ + return ::fabs(a); +} + +/** +\brief abs returns the absolute value of its argument. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE int32_t PxAbs(int32_t a) +{ + return ::abs(a); +} + +/** +\brief Clamps v to the range [hi,lo] +*/ +template +PX_CUDA_CALLABLE PX_FORCE_INLINE T PxClamp(T v, T lo, T hi) +{ + PX_ASSERT(lo <= hi); + return PxMin(hi, PxMax(lo, v)); +} + +//! \brief Square root. +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxSqrt(float a) +{ + return intrinsics::sqrt(a); +} + +//! \brief Square root. +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxSqrt(double a) +{ + return ::sqrt(a); +} + +//! \brief reciprocal square root. +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxRecipSqrt(float a) +{ + return intrinsics::recipSqrt(a); +} + +//! \brief reciprocal square root. +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxRecipSqrt(double a) +{ + return 1 / ::sqrt(a); +} + +//! \brief square of the argument +PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 PxSqr(const PxF32 a) +{ + return a * a; +} + +//! trigonometry -- all angles are in radians. + +//! \brief Sine of an angle ( Unit: Radians ) +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxSin(float a) +{ + return intrinsics::sin(a); +} + +//! \brief Sine of an angle ( Unit: Radians ) +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxSin(double a) +{ + return ::sin(a); +} + +//! \brief Cosine of an angle (Unit: Radians) +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxCos(float a) +{ + return intrinsics::cos(a); +} + +//! \brief Cosine of an angle (Unit: Radians) +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxCos(double a) +{ + return ::cos(a); +} + +//! \brief compute sine and cosine at the same time +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxSinCos(const PxF32 a, PxF32& sin, PxF32& cos) +{ +#if PX_CUDA_COMPILER && __CUDA_ARCH__ >= 350 + __sincosf(a, &sin, &cos); +#else + sin = PxSin(a); + cos = PxCos(a); +#endif +} + +//! \brief compute sine and cosine at the same time +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxSinCos(const double a, double& sin, double& cos) +{ + sin = PxSin(a); + cos = PxCos(a); +} + +/** +\brief Tangent of an angle. +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxTan(float a) +{ + return ::tanf(a); +} + +/** +\brief Tangent of an angle. +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxTan(double a) +{ + return ::tan(a); +} + +/** +\brief Arcsine. +Returns angle between -PI/2 and PI/2 in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAsin(float f) +{ + return ::asinf(PxClamp(f, -1.0f, 1.0f)); +} + +/** +\brief Arcsine. +Returns angle between -PI/2 and PI/2 in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAsin(double f) +{ + return ::asin(PxClamp(f, -1.0, 1.0)); +} + +/** +\brief Arccosine. +Returns angle between 0 and PI in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAcos(float f) +{ + return ::acosf(PxClamp(f, -1.0f, 1.0f)); +} + +/** +\brief Arccosine. +Returns angle between 0 and PI in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAcos(double f) +{ + return ::acos(PxClamp(f, -1.0, 1.0)); +} + +/** +\brief ArcTangent. +Returns angle between -PI/2 and PI/2 in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAtan(float a) +{ + return ::atanf(a); +} + +/** +\brief ArcTangent. +Returns angle between -PI/2 and PI/2 in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAtan(double a) +{ + return ::atan(a); +} + +/** +\brief Arctangent of (x/y) with correct sign. +Returns angle between -PI and PI in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAtan2(float x, float y) +{ + return ::atan2f(x, y); +} + +/** +\brief Arctangent of (x/y) with correct sign. +Returns angle between -PI and PI in radians +Unit: Radians +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAtan2(double x, double y) +{ + return ::atan2(x, y); +} + +/** +\brief Converts degrees to radians. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 PxDegToRad(const PxF32 a) +{ + return 0.01745329251994329547f * a; +} + +//! \brief returns true if the passed number is a finite floating point number as opposed to INF, NAN, etc. +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxIsFinite(float f) +{ + return intrinsics::isFinite(f); +} + +//! \brief returns true if the passed number is a finite floating point number as opposed to INF, NAN, etc. +PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxIsFinite(double f) +{ + return intrinsics::isFinite(f); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxFloor(float a) +{ + return ::floorf(a); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxExp(float a) +{ + return ::expf(a); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxCeil(float a) +{ + return ::ceilf(a); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxSign(float a) +{ + return physx::intrinsics::sign(a); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxSign2(float a, float eps = FLT_EPSILON) +{ + return (a < -eps) ? -1.0f : (a > eps) ? 1.0f : 0.0f; +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxPow(float x, float y) +{ + return ::powf(x, y); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float PxLog(float x) +{ + return ::logf(x); +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMathIntrinsics.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMathIntrinsics.h new file mode 100644 index 000000000..b17555a1e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMathIntrinsics.h @@ -0,0 +1,54 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MATH_INTRINSICS_H +#define PX_MATH_INTRINSICS_H + +#include +#include "foundation/PxPreprocessor.h" +#include "foundation/PxSimpleTypes.h" + +#if PX_WINDOWS_FAMILY +#include "foundation/windows/PxWindowsMathIntrinsics.h" +#elif(PX_LINUX || PX_APPLE_FAMILY) +#include "foundation/unix/PxUnixMathIntrinsics.h" +#elif PX_SWITCH +#include "foundation/switch/PxSwitchMathIntrinsics.h" +#else +#error "Platform not supported!" +#endif + +/** +Platform specific defines +*/ +#if PX_WINDOWS_FAMILY +#pragma intrinsic(abs) +#pragma intrinsic(labs) +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMathUtils.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMathUtils.h new file mode 100644 index 000000000..3871d7563 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMathUtils.h @@ -0,0 +1,785 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MATH_UTILS_H +#define PX_MATH_UTILS_H + + +#include "foundation/PxFoundationConfig.h" +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" +#include "foundation/PxAssert.h" +#include "foundation/PxPlane.h" +#include "foundation/PxMat33.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief finds the shortest rotation between two vectors. + +\param[in] from the vector to start from +\param[in] target the vector to rotate to +\return a rotation about an axis normal to the two vectors which takes one to the other via the shortest path +*/ +PX_FOUNDATION_API PxQuat PxShortestRotation(const PxVec3& from, const PxVec3& target); + +/* \brief diagonalizes a 3x3 symmetric matrix y + +The returned matrix satisfies M = R * D * R', where R is the rotation matrix for the output quaternion, R' its +transpose, and D the diagonal matrix + +If the matrix is not symmetric, the result is undefined. + +\param[in] m the matrix to diagonalize +\param[out] axes a quaternion rotation which diagonalizes the matrix +\return the vector diagonal of the diagonalized matrix. +*/ +PX_FOUNDATION_API PxVec3 PxDiagonalize(const PxMat33& m, PxQuat& axes); + +/** \brief creates a transform from the endpoints of a segment, suitable for an actor transform for a PxCapsuleGeometry + +\param[in] p0 one end of major axis of the capsule +\param[in] p1 the other end of the axis of the capsule +\param[out] halfHeight the halfHeight of the capsule. This parameter is optional. +\return A PxTransform which will transform the vector (1,0,0) to the capsule axis shrunk by the halfHeight +*/ +PX_FOUNDATION_API PxTransform PxTransformFromSegment(const PxVec3& p0, const PxVec3& p1, PxReal* halfHeight = NULL); + +/** \brief creates a transform from a plane equation, suitable for an actor transform for a PxPlaneGeometry + +\param[in] plane the desired plane equation +\return a PxTransform which will transform the plane PxPlane(1,0,0,0) to the specified plane +*/ +PX_FOUNDATION_API PxTransform PxTransformFromPlaneEquation(const PxPlane& plane); + +/** \brief creates a plane equation from a transform, such as the actor transform for a PxPlaneGeometry + +\param[in] pose the transform +\return the plane +*/ +PX_INLINE PxPlane PxPlaneEquationFromTransform(const PxTransform& pose) +{ + return PxPlane(1.0f, 0.0f, 0.0f, 0.0f).transform(pose); +} + +/** +\brief Spherical linear interpolation of two quaternions. +\param[in] t is the interpolation parameter in range (0, 1) +\param[in] left is the start of the interpolation +\param[in] right is the end of the interpolation +\return Returns left when t=0, right when t=1 and a linear interpolation of left and right when 0 < t < 1. +Returns angle between -PI and PI in radians +*/ +PX_CUDA_CALLABLE PX_INLINE PxQuat PxSlerp(const PxReal t, const PxQuat& left, const PxQuat& right) +{ + const PxReal quatEpsilon = (PxReal(1.0e-8f)); + + PxReal cosine = left.dot(right); + PxReal sign = PxReal(1); + if (cosine < 0) + { + cosine = -cosine; + sign = PxReal(-1); + } + + PxReal sine = PxReal(1) - cosine * cosine; + + if (sine >= quatEpsilon * quatEpsilon) + { + sine = PxSqrt(sine); + const PxReal angle = PxAtan2(sine, cosine); + const PxReal i_sin_angle = PxReal(1) / sine; + + const PxReal leftw = PxSin(angle * (PxReal(1) - t)) * i_sin_angle; + const PxReal rightw = PxSin(angle * t) * i_sin_angle * sign; + + return left * leftw + right * rightw; + } + + return left; +} + +/** +\brief integrate transform. +\param[in] curTrans The current transform +\param[in] linvel Linear velocity +\param[in] angvel Angular velocity +\param[in] timeStep The time-step for integration +\param[out] result The integrated transform +*/ +PX_FOUNDATION_API void PxIntegrateTransform(const PxTransform& curTrans, const PxVec3& linvel, const PxVec3& angvel, + PxReal timeStep, PxTransform& result); + +//! \brief Compute the exponent of a PxVec3 +PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat PxExp(const PxVec3& v) +{ + const PxReal m = v.magnitudeSquared(); + return m < 1e-24f ? PxQuat(PxIdentity) : PxQuat(PxSqrt(m), v * PxRecipSqrt(m)); +} + +/** +\brief computes a oriented bounding box around the scaled basis. +\param basis Input = skewed basis, Output = (normalized) orthogonal basis. +\return Bounding box extent. +*/ +PX_FOUNDATION_API PxVec3 PxOptimizeBoundingBox(PxMat33& basis); + +/** +\brief return Returns the log of a PxQuat +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxLog(const PxQuat& q) +{ + const PxReal s = q.getImaginaryPart().magnitude(); + if (s < 1e-12f) + return PxVec3(0.0f); + // force the half-angle to have magnitude <= pi/2 + PxReal halfAngle = q.w < 0 ? PxAtan2(-s, -q.w) : PxAtan2(s, q.w); + PX_ASSERT(halfAngle >= -PxPi / 2 && halfAngle <= PxPi / 2); + + return q.getImaginaryPart().getNormalized() * 2.f * halfAngle; +} + +/** +\brief return Returns 0 if v.x is largest element of v, 1 if v.y is largest element, 2 if v.z is largest element. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 PxLargestAxis(const PxVec3& v) +{ + PxU32 m = PxU32(v.y > v.x ? 1 : 0); + return v.z > v[m] ? 2 : m; +} + +/** +\brief Compute tan(theta/2) given sin(theta) and cos(theta) as inputs. +\param[in] sin has value sin(theta) +\param[in] cos has value cos(theta) +\return Returns tan(theta/2) +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal PxTanHalf(PxReal sin, PxReal cos) +{ + // PT: avoids divide by zero for singularity. We return sqrt(FLT_MAX) instead of FLT_MAX + // to make sure the calling code doesn't generate INF values when manipulating the returned value + // (some joints multiply it by 4, etc). + if (cos == -1.0f) + return sin < 0.0f ? -sqrtf(FLT_MAX) : sqrtf(FLT_MAX); + + // PT: half-angle formula: tan(a/2) = sin(a)/(1+cos(a)) + return sin / (1.0f + cos); +} + +/** +\brief Compute the closest point on an 2d ellipse to a given 2d point. +\param[in] point is a 2d point in the y-z plane represented by (point.y, point.z) +\param[in] radii are the radii of the ellipse (radii.y and radii.z) in the y-z plane. +\return Returns the 2d position on the surface of the ellipse that is closest to point. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxEllipseClamp(const PxVec3& point, const PxVec3& radii) +{ + // lagrange multiplier method with Newton/Halley hybrid root-finder. + // see http://www.geometrictools.com/Documentation/DistancePointToEllipse2.pdf + // for proof of Newton step robustness and initial estimate. + // Halley converges much faster but sometimes overshoots - when that happens we take + // a newton step instead + + // converges in 1-2 iterations where D&C works well, and it's good with 4 iterations + // with any ellipse that isn't completely crazy + + const PxU32 MAX_ITERATIONS = 20; + const PxReal convergenceThreshold = 1e-4f; + + // iteration requires first quadrant but we recover generality later + + PxVec3 q(0, PxAbs(point.y), PxAbs(point.z)); + const PxReal tinyEps = 1e-6f; // very close to minor axis is numerically problematic but trivial + if (radii.y >= radii.z) + { + if (q.z < tinyEps) + return PxVec3(0, point.y > 0 ? radii.y : -radii.y, 0); + } + else + { + if (q.y < tinyEps) + return PxVec3(0, 0, point.z > 0 ? radii.z : -radii.z); + } + + PxVec3 denom, e2 = radii.multiply(radii), eq = radii.multiply(q); + + // we can use any initial guess which is > maximum(-e.y^2,-e.z^2) and for which f(t) is > 0. + // this guess works well near the axes, but is weak along the diagonals. + + PxReal t = PxMax(eq.y - e2.y, eq.z - e2.z); + + for (PxU32 i = 0; i < MAX_ITERATIONS; i++) + { + denom = PxVec3(0, 1 / (t + e2.y), 1 / (t + e2.z)); + PxVec3 denom2 = eq.multiply(denom); + + PxVec3 fv = denom2.multiply(denom2); + PxReal f = fv.y + fv.z - 1; + + // although in exact arithmetic we are guaranteed f>0, we can get here + // on the first iteration via catastrophic cancellation if the point is + // very close to the origin. In that case we just behave as if f=0 + + if (f < convergenceThreshold) + return e2.multiply(point).multiply(denom); + + PxReal df = fv.dot(denom) * -2.0f; + t = t - f / df; + } + + // we didn't converge, so clamp what we have + PxVec3 r = e2.multiply(point).multiply(denom); + return r * PxRecipSqrt(PxSqr(r.y / radii.y) + PxSqr(r.z / radii.z)); +} + +/** +\brief Compute from an input quaternion q a pair of quaternions (swing, twist) such that +q = swing * twist +with the caveats that swing.x = twist.y = twist.z = 0. +\param[in] q is the quaternion to be decomposed into swing and twist quaternions. +\param[out] swing is the swing component of the quaternion decomposition. +\param[out] twist is the twist component of the quaternion decomposition. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxSeparateSwingTwist(const PxQuat& q, PxQuat& swing, PxQuat& twist) +{ + twist = q.x != 0.0f ? PxQuat(q.x, 0, 0, q.w).getNormalized() : PxQuat(PxIdentity); + swing = q * twist.getConjugate(); +} + +/** +\brief Compute the angle between two non-unit vectors +\param[in] v0 is one of the non-unit vectors +\param[in] v1 is the other of the two non-unit vectors +\return Returns the angle (in radians) between the two vector v0 and v1. +*/ +PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 PxComputeAngle(const PxVec3& v0, const PxVec3& v1) +{ + const PxF32 cos = v0.dot(v1); // |v0|*|v1|*Cos(Angle) + const PxF32 sin = (v0.cross(v1)).magnitude(); // |v0|*|v1|*Sin(Angle) + return PxAtan2(sin, cos); +} + +/** +\brief Compute two normalized vectors (right and up) that are perpendicular to an input normalized vector (dir). +\param[in] dir is a normalized vector that is used to compute the perpendicular vectors. +\param[out] right is the first of the two vectors perpendicular to dir +\param[out] up is the second of the two vectors perpendicular to dir +*/ +PX_CUDA_CALLABLE PX_INLINE void PxComputeBasisVectors(const PxVec3& dir, PxVec3& right, PxVec3& up) +{ + // Derive two remaining vectors + if (PxAbs(dir.y) <= 0.9999f) + { + right = PxVec3(dir.z, 0.0f, -dir.x); + right.normalize(); + + // PT: normalize not needed for 'up' because dir & right are unit vectors, + // and by construction the angle between them is 90 degrees (i.e. sin(angle)=1) + up = PxVec3(dir.y * right.z, dir.z * right.x - dir.x * right.z, -dir.y * right.x); + } + else + { + right = PxVec3(1.0f, 0.0f, 0.0f); + + up = PxVec3(0.0f, dir.z, -dir.y); + up.normalize(); + } +} + +/** +\brief Compute three normalized vectors (dir, right and up) that are parallel to (dir) and perpendicular to (right, up) the +normalized direction vector (p1 - p0)/||p1 - p0||. +\param[in] p0 is used to compute the normalized vector dir = (p1 - p0)/||p1 - p0||. +\param[in] p1 is used to compute the normalized vector dir = (p1 - p0)/||p1 - p0||. +\param[out] dir is the normalized vector (p1 - p0)/||p1 - p0||. +\param[out] right is the first of the two normalized vectors perpendicular to dir +\param[out] up is the second of the two normalized vectors perpendicular to dir +*/ +PX_INLINE void PxComputeBasisVectors(const PxVec3& p0, const PxVec3& p1, PxVec3& dir, PxVec3& right, PxVec3& up) +{ + // Compute the new direction vector + dir = p1 - p0; + dir.normalize(); + + // Derive two remaining vectors + PxComputeBasisVectors(dir, right, up); +} + + +/** +\brief Compute (i+1)%3 +*/ +PX_INLINE PxU32 PxGetNextIndex3(PxU32 i) +{ + return (i + 1 + (i >> 1)) & 3; +} + +/** +\brief Computes the barycentric coordinates for a point inside a tetrahedron. + +This function calculates the barycentric coordinates of a point p with respect to a tetrahedron defined by vertices a, b, c, and d. + +\param[in] a Vertex A of the tetrahedron +\param[in] b Vertex B of the tetrahedron +\param[in] c Vertex C of the tetrahedron +\param[in] d Vertex D of the tetrahedron +\param[in] p The point for which to compute the barycentric coordinates +\param[out] bary The resulting barycentric coordinates as a PxVec4 +*/ +PX_INLINE PX_CUDA_CALLABLE void PxComputeBarycentric(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxVec3& p, PxVec4& bary) +{ + const PxVec3 ba = b - a; + const PxVec3 ca = c - a; + const PxVec3 da = d - a; + const PxVec3 pa = p - a; + + const PxReal detBcd = ba.dot(ca.cross(da)); + const PxReal detPcd = pa.dot(ca.cross(da)); + + bary.y = detPcd / detBcd; + + const PxReal detBpd = ba.dot(pa.cross(da)); + bary.z = detBpd / detBcd; + + const PxReal detBcp = ba.dot(ca.cross(pa)); + + bary.w = detBcp / detBcd; + bary.x = 1 - bary.y - bary.z - bary.w; +} + +/** +\brief Computes the barycentric coordinates for a point inside a triangle. + +This function calculates the barycentric coordinates of a point p with respect to a triangle defined by vertices a, b, and c. + +\param[in] a Vertex A of the triangle +\param[in] b Vertex B of the triangle +\param[in] c Vertex C of the triangle +\param[in] p The point for which to compute the barycentric coordinates +\param[out] bary The resulting barycentric coordinates as a PxVec4 +*/ +PX_INLINE PX_CUDA_CALLABLE void PxComputeBarycentric(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& p, PxVec4& bary) +{ + const PxVec3 v0 = b - a; + const PxVec3 v1 = c - a; + const PxVec3 v2 = p - a; + + const float d00 = v0.dot(v0); + const float d01 = v0.dot(v1); + const float d11 = v1.dot(v1); + const float d20 = v2.dot(v0); + const float d21 = v2.dot(v1); + + const float denom = d00 * d11 - d01 * d01; + const float v = (d11 * d20 - d01 * d21) / denom; + const float w = (d00 * d21 - d01 * d20) / denom; + const float u = 1.f - v - w; + + bary.x = u; bary.y = v; bary.z = w; + bary.w = 0.f; +} + +/** +\brief Computes the barycentric coordinates for a point inside a triangle (deprecated). + +This function is deprecated. Use PxComputeBarycentric instead. + +\param[in] a Vertex A of the triangle +\param[in] b Vertex B of the triangle +\param[in] c Vertex C of the triangle +\param[in] p The point for which to compute the barycentric coordinates +\param[out] bary The resulting barycentric coordinates as a PxVec4 + +\see PxComputeBarycentric +*/ +PX_INLINE PX_CUDA_CALLABLE PX_DEPRECATED void computeBarycentric(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& p, PxVec4& bary) +{ + PxComputeBarycentric(a, b, c, p, bary); +} + +/** +\brief Computes the barycentric coordinates for a point inside a tetrahedron (deprecated). + +This function is deprecated. Use PxComputeBarycentric instead. + +\param[in] a Vertex A of the tetrahedron +\param[in] b Vertex B of the tetrahedron +\param[in] c Vertex C of the tetrahedron +\param[in] d Vertex D of the tetrahedron +\param[in] p The point for which to compute the barycentric coordinates +\param[out] bary The resulting barycentric coordinates as a PxVec4 + +\see PxComputeBarycentric +*/ +PX_INLINE PX_CUDA_CALLABLE PX_DEPRECATED void computeBarycentric(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxVec3& p, PxVec4& bary) +{ + PxComputeBarycentric(a, b, c, d, p, bary); +} + + +/** +\brief Performs linear interpolation between two values. + +\param[in] a The start value +\param[in] b The end value +\param[in] t The interpolation parameter in the range [0, 1] +\return The interpolated value +*/ +PX_INLINE PX_CUDA_CALLABLE static float PxLerp(float a, float b, float t) +{ + return a + t * (b - a); +} + +/** +\brief Performs bilinear interpolation. + +\param[in] f00 The value at (0, 0) +\param[in] f10 The value at (1, 0) +\param[in] f01 The value at (0, 1) +\param[in] f11 The value at (1, 1) +\param[in] tx The interpolation parameter along the x-axis +\param[in] ty The interpolation parameter along the y-axis +\return The interpolated value + +\see PxLerp +*/ +PX_INLINE PX_CUDA_CALLABLE static PxReal PxBiLerp( + const PxReal f00, + const PxReal f10, + const PxReal f01, + const PxReal f11, + const PxReal tx, const PxReal ty) +{ + return PxLerp( + PxLerp(f00, f10, tx), + PxLerp(f01, f11, tx), + ty); +} + +/** +\brief Performs trilinear interpolation. + +\param[in] f000 The value at (0, 0, 0) +\param[in] f100 The value at (1, 0, 0) +\param[in] f010 The value at (0, 1, 0) +\param[in] f110 The value at (1, 1, 0) +\param[in] f001 The value at (0, 0, 1) +\param[in] f101 The value at (1, 0, 1) +\param[in] f011 The value at (0, 1, 1) +\param[in] f111 The value at (1, 1, 1) +\param[in] tx The interpolation parameter along the x-axis +\param[in] ty The interpolation parameter along the y-axis +\param[in] tz The interpolation parameter along the z-axis +\return The interpolated value + +\see PxLerp PxBiLerp +*/ +PX_INLINE PX_CUDA_CALLABLE static PxReal PxTriLerp( + const PxReal f000, + const PxReal f100, + const PxReal f010, + const PxReal f110, + const PxReal f001, + const PxReal f101, + const PxReal f011, + const PxReal f111, + const PxReal tx, + const PxReal ty, + const PxReal tz) +{ + return PxLerp( + PxBiLerp(f000, f100, f010, f110, tx, ty), + PxBiLerp(f001, f101, f011, f111, tx, ty), + tz); +} + +/** +\brief Computes the 1D index for a 3D grid point. + +\param[in] i The x-coordinate index +\param[in] j The y-coordinate index +\param[in] k The z-coordinate index +\param[in] nbX The number of grid points along the x-axis +\param[in] nbY The number of grid points along the y-axis +\return The 1D index corresponding to the 3D grid point +*/ +PX_INLINE PX_CUDA_CALLABLE static PxU32 PxSDFIdx(PxU32 i, PxU32 j, PxU32 k, PxU32 nbX, PxU32 nbY) +{ + return i + j * nbX + k * nbX*nbY; +} + +/** +\brief Samples the signed distance field (SDF) at a given local position. + +This function samples the SDF at a given local position within the defined box bounds and calculates the interpolated distance value. It handles grid clamping and ensures that the sampled value is within the tolerance limit. + +\param[in] sdf A pointer to the SDF data +\param[in] localPos The local position to sample the SDF +\param[in] sdfBoxLower The lower bound of the SDF box +\param[in] sdfBoxHigher The upper bound of the SDF box +\param[in] sdfDx The spacing between grid points in the SDF +\param[in] invSdfDx The inverse of the grid spacing +\param[in] dimX The number of grid points along the x-axis +\param[in] dimY The number of grid points along the y-axis +\param[in] dimZ The number of grid points along the z-axis +\param[in] tolerance The tolerance for clamping the grid points +\return The sampled SDF value + +\see PxTriLerp PxSDFIdx +*/ +PX_INLINE PX_CUDA_CALLABLE static PxReal PxSDFSample(const PxReal* PX_RESTRICT sdf, const PxVec3& localPos, const PxVec3& sdfBoxLower, + const PxVec3& sdfBoxHigher, const PxReal sdfDx, const PxReal invSdfDx, const PxU32 dimX, const PxU32 dimY, const PxU32 dimZ, PxReal tolerance) +{ + PxVec3 clampedGridPt = localPos.maximum(sdfBoxLower).minimum(sdfBoxHigher); + + const PxVec3 diff = (localPos - clampedGridPt); + + if (diff.magnitudeSquared() > tolerance*tolerance) + return PX_MAX_F32; + + PxVec3 f = (clampedGridPt - sdfBoxLower) * invSdfDx; + + PxU32 i = PxU32(f.x); + PxU32 j = PxU32(f.y); + PxU32 k = PxU32(f.z); + + f -= PxVec3(PxReal(i), PxReal(j), PxReal(k)); + + if (i >= (dimX - 1)) + { + i = dimX - 2; + clampedGridPt.x -= f.x * sdfDx; + f.x = 1.f; + } + if (j >= (dimY - 1)) + { + j = dimY - 2; + clampedGridPt.y -= f.y * sdfDx; + f.y = 1.f; + } + if (k >= (dimZ - 1)) + { + k = dimZ - 2; + clampedGridPt.z -= f.z * sdfDx; + f.z = 1.f; + } + + const PxReal s000 = sdf[PxSDFIdx(i, j, k, dimX, dimY)]; + const PxReal s100 = sdf[PxSDFIdx(i + 1, j, k, dimX, dimY)]; + const PxReal s010 = sdf[PxSDFIdx(i, j + 1, k, dimX, dimY)]; + const PxReal s110 = sdf[PxSDFIdx(i + 1, j + 1, k, dimX, dimY)]; + const PxReal s001 = sdf[PxSDFIdx(i, j, k + 1, dimX, dimY)]; + const PxReal s101 = sdf[PxSDFIdx(i + 1, j, k + 1, dimX, dimY)]; + const PxReal s011 = sdf[PxSDFIdx(i, j + 1, k + 1, dimX, dimY)]; + const PxReal s111 = sdf[PxSDFIdx(i + 1, j + 1, k + 1, dimX, dimY)]; + + PxReal dist = PxTriLerp( + s000, + s100, + s010, + s110, + s001, + s101, + s011, + s111, + f.x, f.y, f.z); + + dist += diff.magnitude(); + + return dist; +} + +#if !PX_DOXYGEN // remove due to failing references + +PX_DEPRECATED struct Interpolation +{ + /** + \brief Performs linear interpolation between two values. + + \param[in] a The start value + \param[in] b The end value + \param[in] t The interpolation parameter in the range [0, 1] + \return The interpolated value + + \deprecated Please use corresponding freestanding function outside of Interpolation scope. + */ + PX_DEPRECATED PX_INLINE PX_CUDA_CALLABLE static float PxLerp(float a, float b, float t) + { + return ::physx::PxLerp(a, b, t); + } + + /** + \brief Performs bilinear interpolation. + + \param[in] f00 The value at (0, 0) + \param[in] f10 The value at (1, 0) + \param[in] f01 The value at (0, 1) + \param[in] f11 The value at (1, 1) + \param[in] tx The interpolation parameter along the x-axis + \param[in] ty The interpolation parameter along the y-axis + \return The interpolated value + + \deprecated Please use corresponding freestanding function outside of Interpolation scope. + */ + PX_DEPRECATED PX_INLINE PX_CUDA_CALLABLE static PxReal PxBiLerp( + const PxReal f00, + const PxReal f10, + const PxReal f01, + const PxReal f11, + const PxReal tx, const PxReal ty) + { + return ::physx::PxBiLerp(f00, f10, f01, f11, tx, ty); + } + + /** + \brief Performs trilinear interpolation. + + \param[in] f000 The value at (0, 0, 0) + \param[in] f100 The value at (1, 0, 0) + \param[in] f010 The value at (0, 1, 0) + \param[in] f110 The value at (1, 1, 0) + \param[in] f001 The value at (0, 0, 1) + \param[in] f101 The value at (1, 0, 1) + \param[in] f011 The value at (0, 1, 1) + \param[in] f111 The value at (1, 1, 1) + \param[in] tx The interpolation parameter along the x-axis + \param[in] ty The interpolation parameter along the y-axis + \param[in] tz The interpolation parameter along the z-axis + \return The interpolated value + + \deprecated Please use corresponding freestanding function outside of Interpolation scope. + */ + PX_DEPRECATED PX_INLINE PX_CUDA_CALLABLE static PxReal PxTriLerp( + const PxReal f000, + const PxReal f100, + const PxReal f010, + const PxReal f110, + const PxReal f001, + const PxReal f101, + const PxReal f011, + const PxReal f111, + const PxReal tx, + const PxReal ty, + const PxReal tz) + { + return ::physx::PxTriLerp(f000, f100, f010, f110, f001, f101, f011, f111, tx, ty, tz); + } + + /** + \brief Computes the 1D index for a 3D grid point. + + \param[in] i The x-coordinate index + \param[in] j The y-coordinate index + \param[in] k The z-coordinate index + \param[in] nbX The number of grid points along the x-axis + \param[in] nbY The number of grid points along the y-axis + \return The 1D index corresponding to the 3D grid point + + \deprecated Please use corresponding freestanding function outside of Interpolation scope. + */ + PX_DEPRECATED PX_INLINE PX_CUDA_CALLABLE static PxU32 PxSDFIdx(PxU32 i, PxU32 j, PxU32 k, PxU32 nbX, PxU32 nbY) + { + return ::physx::PxSDFIdx(i, j, k, nbX, nbY); + } + + /** + \brief Samples the signed distance field (SDF) at a given local position. + + This function samples the SDF at a given local position within the defined box bounds and calculates the interpolated distance value. It handles grid clamping and ensures that the sampled value is within the tolerance limit. + + \param[in] sdf A pointer to the SDF data + \param[in] localPos The local position to sample the SDF + \param[in] sdfBoxLower The lower bound of the SDF box + \param[in] sdfBoxHigher The upper bound of the SDF box + \param[in] sdfDx The spacing between grid points in the SDF + \param[in] invSdfDx The inverse of the grid spacing + \param[in] dimX The number of grid points along the x-axis + \param[in] dimY The number of grid points along the y-axis + \param[in] dimZ The number of grid points along the z-axis + \param[in] tolerance The tolerance for clamping the grid points + \return The sampled SDF value + + \deprecated Please use corresponding freestanding function outside of Interpolation scope. + */ + PX_DEPRECATED PX_INLINE PX_CUDA_CALLABLE static PxReal PxSDFSampleImpl(const PxReal* PX_RESTRICT sdf, const PxVec3& localPos, const PxVec3& sdfBoxLower, + const PxVec3& sdfBoxHigher, const PxReal sdfDx, const PxReal invSdfDx, const PxU32 dimX, const PxU32 dimY, const PxU32 dimZ, PxReal tolerance) + { + return ::physx::PxSDFSample(sdf, localPos, sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance); + } +}; +#endif // !PX_DOXYGEN // remove due to failing references + +/** +\brief Samples the signed distance field (SDF) at a given local position with gradient computation (deprecated). + +\param[in] sdf A pointer to the SDF data +\param[in] localPos The local position to sample the SDF +\param[in] sdfBoxLower The lower bound of the SDF box +\param[in] sdfBoxHigher The upper bound of the SDF box +\param[in] sdfDx The spacing between grid points in the SDF +\param[in] invSdfDx The inverse of the grid spacing +\param[in] dimX The number of grid points along the x-axis +\param[in] dimY The number of grid points along the y-axis +\param[in] dimZ The number of grid points along the z-axis +\param[out] gradient The resulting gradient vector +\param[in] tolerance The tolerance for clamping the grid points (default is PX_MAX_F32) +\return The sampled SDF value +\deprecated Please use PxSDFSample. +*/ +PX_DEPRECATED PX_INLINE PX_CUDA_CALLABLE PxReal PxSdfSample(const PxReal* PX_RESTRICT sdf, const PxVec3& localPos, const PxVec3& sdfBoxLower, + const PxVec3& sdfBoxHigher, const PxReal sdfDx, const PxReal invSdfDx, const PxU32 dimX, const PxU32 dimY, const PxU32 dimZ, PxVec3& gradient, PxReal tolerance = PX_MAX_F32) +{ + PxReal dist = PxSDFSample(sdf, localPos, sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance); + + if (dist < tolerance) + { + + PxVec3 grad; + grad.x = PxSDFSample(sdf, localPos + PxVec3(sdfDx, 0.f, 0.f), sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance) - + PxSDFSample(sdf, localPos - PxVec3(sdfDx, 0.f, 0.f), sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance); + grad.y = PxSDFSample(sdf, localPos + PxVec3(0.f, sdfDx, 0.f), sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance) - + PxSDFSample(sdf, localPos - PxVec3(0.f, sdfDx, 0.f), sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance); + grad.z = PxSDFSample(sdf, localPos + PxVec3(0.f, 0.f, sdfDx), sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance) - + PxSDFSample(sdf, localPos - PxVec3(0.f, 0.f, sdfDx), sdfBoxLower, sdfBoxHigher, sdfDx, invSdfDx, dimX, dimY, dimZ, tolerance); + + gradient = grad; + + } + + return dist; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMemory.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMemory.h new file mode 100644 index 000000000..9f4f9b6ab --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMemory.h @@ -0,0 +1,126 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MEMORY_H +#define PX_MEMORY_H + + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxMathIntrinsics.h" +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Sets the bytes of the provided buffer to zero. + + \param dest [out] Pointer to block of memory to set zero. + \param count [in] Number of bytes to set to zero. + + \return Pointer to memory block (same as input) + */ + PX_FORCE_INLINE void* PxMemZero(void* dest, PxU32 count) + { + // This is to avoid undefined behavior + return (count != 0) ? physx::intrinsics::memZero(dest, count) : NULL; + } + + /** + \brief Sets the bytes of the provided buffer to the specified value. + + \param dest [out] Pointer to block of memory to set to the specified value. + \param c [in] Value to set the bytes of the block of memory to. + \param count [in] Number of bytes to set to the specified value. + + \return Pointer to memory block (same as input) + */ + PX_FORCE_INLINE void* PxMemSet(void* dest, PxI32 c, PxU32 count) + { + // This is to avoid undefined behavior + return (count != 0) ? physx::intrinsics::memSet(dest, c, count) : NULL; + } + + /** + \brief Copies the bytes of one memory block to another. The memory blocks must not overlap. + + \note Use #PxMemMove if memory blocks overlap. + + \param dest [out] Pointer to block of memory to copy to. + \param src [in] Pointer to block of memory to copy from. + \param count [in] Number of bytes to copy. + + \return Pointer to destination memory block + */ + PX_FORCE_INLINE void* PxMemCopy(void* dest, const void* src, PxU32 count) + { + // This is to avoid undefined behavior + return (count != 0) ? physx::intrinsics::memCopy(dest, src, count) : NULL; + } + + /** + \brief Copies the bytes of one memory block to another. The memory blocks can overlap. + + \note Use #PxMemCopy if memory blocks do not overlap. + + \param dest [out] Pointer to block of memory to copy to. + \param src [in] Pointer to block of memory to copy from. + \param count [in] Number of bytes to copy. + + \return Pointer to destination memory block + */ + PX_FORCE_INLINE void* PxMemMove(void* dest, const void* src, PxU32 count) + { + return physx::intrinsics::memMove(dest, src, count); + } + + /** + Mark a specified amount of memory with 0xcd pattern. This is used to check that the meta data + definition for serialized classes is complete in checked builds. + + \param ptr [out] Pointer to block of memory to initialize. + \param byteSize [in] Number of bytes to initialize. + */ + PX_INLINE void PxMarkSerializedMemory(void* ptr, PxU32 byteSize) + { +#if PX_CHECKED + PxMemSet(ptr, 0xcd, byteSize); +#else + PX_UNUSED(ptr); + PX_UNUSED(byteSize); +#endif + } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMutex.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMutex.h new file mode 100644 index 000000000..ec2eca096 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxMutex.h @@ -0,0 +1,183 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MUTEX_H +#define PX_MUTEX_H + +#include "foundation/PxAllocator.h" + +/* + * This inclusion is a best known fix for gcc 4.4.1 error: + * Creating object file for apex/src/PsAllocator.cpp ... + * In file included from apex/include/PsFoundation.h:30, + * from apex/src/PsAllocator.cpp:26: + * apex/include/PsMutex.h: In constructor 'physx::PxMutexT::MutexT(const Alloc&)': + * apex/include/PsMutex.h:92: error: no matching function for call to 'operator new(unsigned int, + * physx::PxMutexImpl*&)' + * :0: note: candidates are: void* operator new(unsigned int) + */ +#include + +#if !PX_DOXYGEN +namespace physx +{ +#endif +class PX_FOUNDATION_API PxMutexImpl +{ + public: + /** + The constructor for Mutex creates a mutex. It is initially unlocked. + */ + PxMutexImpl(); + + /** + The destructor for Mutex deletes the mutex. + */ + ~PxMutexImpl(); + + /** + Acquire (lock) the mutex. If the mutex is already locked + by another thread, this method blocks until the mutex is + unlocked. + */ + void lock(); + + /** + Acquire (lock) the mutex. If the mutex is already locked + by another thread, this method returns false without blocking. + */ + bool trylock(); + + /** + Release (unlock) the mutex. + */ + void unlock(); + + /** + Size of this class. + */ + static uint32_t getSize(); +}; + +template > +class PxMutexT : protected Alloc +{ + PX_NOCOPY(PxMutexT) + public: + class ScopedLock + { + PxMutexT& mMutex; + PX_NOCOPY(ScopedLock) + public: + PX_INLINE ScopedLock(PxMutexT& mutex) : mMutex(mutex) + { + mMutex.lock(); + } + PX_INLINE ~ScopedLock() + { + mMutex.unlock(); + } + }; + + /** + The constructor for Mutex creates a mutex. It is initially unlocked. + */ + PxMutexT(const Alloc& alloc = Alloc()) : Alloc(alloc) + { + mImpl = reinterpret_cast(Alloc::allocate(PxMutexImpl::getSize(), PX_FL)); + PX_PLACEMENT_NEW(mImpl, PxMutexImpl)(); + } + + /** + The destructor for Mutex deletes the mutex. + */ + ~PxMutexT() + { + mImpl->~PxMutexImpl(); + Alloc::deallocate(mImpl); + } + + /** + Acquire (lock) the mutex. If the mutex is already locked + by another thread, this method blocks until the mutex is + unlocked. + */ + PX_FORCE_INLINE void lock() const + { + mImpl->lock(); + } + + /** + Acquire (lock) the mutex. If the mutex is already locked + by another thread, this method returns false without blocking, + returns true if lock is successfully acquired + */ + PX_FORCE_INLINE bool trylock() const + { + return mImpl->trylock(); + } + + /** + Release (unlock) the mutex, the calling thread must have + previously called lock() or method will error + */ + PX_FORCE_INLINE void unlock() const + { + mImpl->unlock(); + } + + private: + PxMutexImpl* mImpl; +}; + +class PX_FOUNDATION_API PxReadWriteLock +{ + PX_NOCOPY(PxReadWriteLock) + public: + PxReadWriteLock(); + ~PxReadWriteLock(); + + // "takeLock" can only be false if the thread already holds the mutex, e.g. if it already acquired the write lock + void lockReader(bool takeLock); + void lockWriter(); + + void unlockReader(); + void unlockWriter(); + + private: + class ReadWriteLockImpl* mImpl; +}; + +typedef PxMutexT<> PxMutex; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPhysicsVersion.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPhysicsVersion.h new file mode 100644 index 000000000..48d87973d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPhysicsVersion.h @@ -0,0 +1,59 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSICS_VERSION_H +#define PX_PHYSICS_VERSION_H + +/* +VersionNumbers: The combination of these +numbers uniquely identifies the API, and should +be incremented when the SDK API changes. This may +include changes to file formats. + +This header is included in the main SDK header files +so that the entire SDK and everything that builds on it +is completely rebuilt when this file changes. Thus, +this file is not to include a frequently changing +build number. See BuildNumber.h for that. + +Each of these three values should stay below 255 because +sometimes they are stored in a byte. +*/ + +#define PX_PHYSICS_VERSION_MAJOR 5 +#define PX_PHYSICS_VERSION_MINOR 6 +#define PX_PHYSICS_VERSION_BUGFIX 1 + +/** +The constant PX_PHYSICS_VERSION is used when creating certain PhysX module objects. +This is to ensure that the application is using the same header version as the library was built with. +*/ +#define PX_PHYSICS_VERSION ((PX_PHYSICS_VERSION_MAJOR<<24) + (PX_PHYSICS_VERSION_MINOR<<16) + (PX_PHYSICS_VERSION_BUGFIX<<8) + 0) + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPinnedArray.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPinnedArray.h new file mode 100644 index 000000000..4b95a16c1 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPinnedArray.h @@ -0,0 +1,147 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PINNED_ARRAY_H +#define PX_PINNED_ARRAY_H + +#include "foundation/PxArray.h" +#include "foundation/PxAllocator.h" +#include "foundation/PxBounds3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + // PT: the default pinned-memory arrays are defined as PxPinnedArray = PxArray. + // The PxVirtualAllocator ultimately uses cuMemHostAlloc via PxgCudaHostMemoryAllocatorCallback / PxgPinnedMemoryAllocate. + // We use the CU_MEMHOSTALLOC_DEVICEMAP flag there so cuMemHostGetDevicePointer() can later be used on returned ptr. + // + // The new pinned-memory arrays are defined as PxPinnedArraySafe = PxArray >. This uses a new + // allocator that allocates either from cuMemHostAlloc, *or* fallbacks to regular allocs when we run out of pinned memory. + // The issue is that in the second case cuMemHostGetDevicePointer() will fail, so we cannot use this everywhere. + // + // I think this exposes issues in PxArray itself, for example in the swap function (we don't swap the allocator data there, + // so when using a PxVirtualAllocator with PxArray the PxVirtualAllocator members are not swapped). + + // PT: this class uses the fact that PxArray inherits from the allocator to add new members to the array class. In particular + // PxPinnedAllocator::mPinned describes where PxArray::mData has been allocated. The class is mostly designed to be used in + // conjunction with PxArray, not as a standalone allocator. + template + class PxPinnedAllocator + { + public: + PxPinnedAllocator(PxVirtualAllocatorCallback* callback = NULL, int group = 0) : mCallback(callback), mGroup(group), mPinned(0) {} + + PX_INLINE void* allocate(size_t size, const char* file, int line, uint32_t* cookie=NULL) + { + PX_ASSERT(mCallback); + // PT: returns *previous* pinned value. It will be passed back to the deallocate function. + if(cookie) + *cookie = mPinned; + + if(!size) + { + mPinned = 0xffffffff; + return NULL; + } + + // PT: first, try with the pinned-memory allocator + void* ptr = mCallback->allocate(size, mGroup, file, line); + if(ptr) + { + mPinned = 1; + return ptr; + } + + // PT: if it fails, fallback to regular allocator + mPinned = 0; + return PxReflectionAllocator::allocate(size, file, line); + } + + PX_INLINE void deallocate(void* ptr, uint32_t* cookie=NULL) + { + PX_ASSERT(mCallback); + if(ptr) + { + // PT: by default use the internal value, except if we're given an explicit cookie + const uint32_t pinned = cookie ? *cookie : mPinned; + if(pinned==1) + mCallback->deallocate(ptr); + else + PxReflectionAllocator::deallocate(ptr); + } + } + + PX_FORCE_INLINE void setCallback(PxVirtualAllocatorCallback* callback) + { + mCallback = callback; + } + + PX_FORCE_INLINE PxVirtualAllocatorCallback* getCallback() + { + return mCallback; + } + + private: + PxVirtualAllocatorCallback* mCallback; + const int mGroup; + uint32_t mPinned; + PxPinnedAllocator& operator=(const PxPinnedAllocator&); + }; + + struct PxsCachedTransform; + + // PT: default versions: + template + using PxPinnedArray = PxArray; + + typedef PxArray PxCachedTransformArrayPinned; + typedef PxArray PxBoundsArrayPinned; + typedef PxArray PxFloatArrayPinned; + typedef PxArray PxInt32ArrayPinned; + typedef PxArray PxInt16ArrayPinned; + typedef PxArray PxInt8ArrayPinned; + + // PT: new versions + template + using PxPinnedArraySafe = PxArray >; + + typedef PxArray > PxCachedTransformArrayPinnedSafe; + typedef PxArray > PxBoundsArrayPinnedSafe; + typedef PxArray > PxFloatArrayPinnedSafe; + typedef PxArray > PxInt32ArrayPinnedSafe; + typedef PxArray > PxInt16ArrayPinnedSafe; + typedef PxArray > PxInt8ArrayPinnedSafe; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPinnedBitMap.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPinnedBitMap.h new file mode 100644 index 000000000..bce12e5ab --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPinnedBitMap.h @@ -0,0 +1,67 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PINNED_BITMAP_H +#define PX_PINNED_BITMAP_H + +#include "foundation/PxBitMap.h" +#include "foundation/PxPinnedArray.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/*! +Overloaded allocation helper for pinned memory support +*/ +PX_INLINE void* PxBitMapAlloc(PxPinnedAllocator& a, PxU32 bytes, const char* file, int line, uint32_t* cookie) +{ + return a.allocate(bytes, file, line, cookie); +} + +/*! +Overloaded de-allocation helper for pinned memory support +*/ +PX_INLINE void PxBitMapDealloc(PxPinnedAllocator& a, void* ptr, uint32_t* cookie) +{ + a.deallocate(ptr, cookie); +} + +/*! +As opposed to PxPinnedArray, PxBitMapPinned has non-pinned allocation fallback, +same as PxPinnedArraySafe. +*/ +typedef PxBitMapBase< PxPinnedAllocator > PxBitMapPinned; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // PX_PINNED_BITMAP_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPlane.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPlane.h new file mode 100644 index 000000000..06f1cf74d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPlane.h @@ -0,0 +1,158 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PLANE_H +#define PX_PLANE_H + + +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Representation of a plane. + + Plane equation used: n.dot(v) + d = 0 +*/ +class PxPlane +{ + public: + /** + \brief Constructor + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane() + { + } + + /** + \brief Constructor from a normal and a distance + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(float nx, float ny, float nz, float distance) : n(nx, ny, nz), d(distance) + { + } + + /** + \brief Constructor from a normal and a distance + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(const PxVec3& normal, float distance) : n(normal), d(distance) + { + } + + /** + \brief Constructor from a point on the plane and a normal + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(const PxVec3& point, const PxVec3& normal) + : n(normal), d(-point.dot(n)) // p satisfies normal.dot(p) + d = 0 + { + } + + /** + \brief Constructor from three points + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2) + { + n = (p1 - p0).cross(p2 - p0).getNormalized(); + d = -p0.dot(n); + } + + /** + \brief returns true if the two planes are exactly equal + */ + PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxPlane& p) const + { + return n == p.n && d == p.d; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE float distance(const PxVec3& p) const + { + return p.dot(n) + d; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE bool contains(const PxVec3& p) const + { + return PxAbs(distance(p)) < (1.0e-7f); + } + + /** + \brief projects p into the plane + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 project(const PxVec3& p) const + { + return p - n * distance(p); + } + + /** + \brief find an arbitrary point in the plane + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 pointInPlane() const + { + return -n * d; + } + + /** + \brief equivalent plane with unit normal + */ + + PX_CUDA_CALLABLE PX_FORCE_INLINE void normalize() + { + float denom = 1.0f / n.magnitude(); + n *= denom; + d *= denom; + } + + /** + \brief transform plane + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane transform(const PxTransform& pose) const + { + const PxVec3 transformedNormal = pose.rotate(n); + return PxPlane(transformedNormal, d - pose.p.dot(transformedNormal)); + } + + /** + \brief inverse-transform plane + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane inverseTransform(const PxTransform& pose) const + { + const PxVec3 transformedNormal = pose.rotateInv(n); + return PxPlane(transformedNormal, d + pose.p.dot(n)); + } + + PxVec3 n; //!< The normal to the plane + float d; //!< The distance from the origin +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPool.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPool.h new file mode 100644 index 000000000..27107f071 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPool.h @@ -0,0 +1,265 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_POOL_H +#define PX_POOL_H + +#include "foundation/PxArray.h" +#include "foundation/PxSort.h" +#include "foundation/PxBasicTemplates.h" +#include "foundation/PxInlineArray.h" +#include "foundation/PxMemory.h" + +namespace physx +{ + +/*! +Simple allocation pool +*/ +template ::Type> +class PxPoolBase : public PxUserAllocated, public Alloc +{ + PX_NOCOPY(PxPoolBase) + protected: + PxPoolBase(const Alloc& alloc, uint32_t elementsPerSlab, uint32_t slabSize) + : Alloc(alloc), mSlabs(alloc), mElementsPerSlab(elementsPerSlab), mUsed(0), mSlabSize(slabSize), mFreeElement(0) + { + mSlabs.reserve(64); + PX_COMPILE_TIME_ASSERT(sizeof(T) >= sizeof(size_t)); + } + + public: + ~PxPoolBase() + { + if(mUsed) + disposeElements(); + + for(void** slabIt = mSlabs.begin(), *slabEnd = mSlabs.end(); slabIt != slabEnd; ++slabIt) + Alloc::deallocate(*slabIt); + } + + // Allocate space for single object + PX_INLINE T* allocate() + { + if(mFreeElement == 0) + allocateSlab(); + T* p = reinterpret_cast(mFreeElement); + mFreeElement = mFreeElement->mNext; + mUsed++; + + PxMarkSerializedMemory(p, sizeof(T)); + return p; + } + + // Put space for a single element back in the lists + PX_INLINE void deallocate(T* p) + { + if(p) + { + PX_ASSERT(mUsed); + mUsed--; + push(reinterpret_cast(p)); + } + } + + PX_INLINE T* construct() + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T()) : NULL; + } + + template + PX_INLINE T* construct(A1& a) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a)) : NULL; + } + + template + PX_INLINE T* construct(A1& a, A2& b) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b)) : NULL; + } + + template + PX_INLINE T* construct(A1& a, A2& b, A3& c) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c)) : NULL; + } + + template + PX_INLINE T* construct(A1* a, A2& b, A3& c) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c)) : NULL; + } + + template + PX_INLINE T* construct(A1& a, A2& b, A3& c, A4& d) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c, d)) : NULL; + } + + template + PX_INLINE T* construct(A1& a, A2& b, A3& c, A4& d, A5& e) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c, d, e)) : NULL; + } + + template + PX_INLINE T* construct(A1& a, A2& b, A3& c, A4& d, A5& e, A6& f) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c, d, e, f)) : NULL; + } + + template + PX_INLINE T* construct(const A1& a, A2& b, const A3& c, A4& d, A5& e, A6& f) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c, d, e, f)) : NULL; + } + + template + PX_INLINE T* construct(A1& a, A2& b, A3& c, A4& d, A5& e, A6& f, A7& g) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c, d, e, f, g)) : NULL; + } + + template + PX_INLINE T* construct(A1& a, A2& b, A3& c, A4& d, A5& e, A6& f, A7& g, A8& h) + { + T* t = allocate(); + return t ? PX_PLACEMENT_NEW(t, T(a, b, c, d, e, f, g, h)) : NULL; + } + + PX_INLINE void destroy(T* const p) + { + if(p) + { + p->~T(); + deallocate(p); + } + } + + protected: + struct FreeList + { + FreeList* mNext; + }; + + // All the allocated slabs, sorted by pointer + PxArray mSlabs; + + const uint32_t mElementsPerSlab; + uint32_t mUsed; + const uint32_t mSlabSize; + + FreeList* mFreeElement; // Head of free-list + + // Helper function to get bitmap of allocated elements + + void push(FreeList* p) + { + p->mNext = mFreeElement; + mFreeElement = p; + } + + // Allocate a slab and segregate it into the freelist + void allocateSlab() + { + T* slab = reinterpret_cast(Alloc::allocate(mSlabSize, PX_FL)); + + mSlabs.pushBack(slab); + + // Build a chain of nodes for the freelist + T* it = slab + mElementsPerSlab; + while(--it >= slab) + push(reinterpret_cast(it)); + } + + /* + Cleanup method. Go through all active slabs and call destructor for live objects, + then free their memory + */ + void disposeElements() + { + PxArray freeNodes(*this); + while(mFreeElement) + { + freeNodes.pushBack(mFreeElement); + mFreeElement = mFreeElement->mNext; + } + Alloc& alloc(*this); + PxSort(freeNodes.begin(), freeNodes.size(), PxLess(), alloc); + PxSort(mSlabs.begin(), mSlabs.size(), PxLess(), alloc); + + typename PxArray::Iterator slabIt = mSlabs.begin(), slabEnd = mSlabs.end(); + for(typename PxArray::Iterator freeIt = freeNodes.begin(); slabIt != slabEnd; ++slabIt) + { + for(T* tIt = reinterpret_cast(*slabIt), *tEnd = tIt + mElementsPerSlab; tIt != tEnd; ++tIt) + { + if(freeIt != freeNodes.end() && *freeIt == tIt) + ++freeIt; + else + tIt->~T(); + } + } + } +}; + +// original pool implementation +template ::Type> +class PxPool : public PxPoolBase +{ + public: + PxPool(const Alloc& alloc = Alloc(), uint32_t elementsPerSlab = 32) + : PxPoolBase(alloc, elementsPerSlab, elementsPerSlab * sizeof(T)) + { + } +}; + +// allows specification of the slab size instead of the occupancy +template ::Type> +class PxPool2 : public PxPoolBase +{ + public: + PxPool2(const Alloc& alloc = Alloc()) : PxPoolBase(alloc, slabSize / sizeof(T), slabSize) + { + PX_COMPILE_TIME_ASSERT(slabSize > sizeof(T)); + } +}; + +} // namespace physx + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPreprocessor.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPreprocessor.h new file mode 100644 index 000000000..4ae2456a8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxPreprocessor.h @@ -0,0 +1,536 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PREPROCESSOR_H +#define PX_PREPROCESSOR_H + +#include + + +#define PX_STRINGIZE_HELPER(X) #X +#define PX_STRINGIZE(X) PX_STRINGIZE_HELPER(X) + +#define PX_CONCAT_HELPER(X, Y) X##Y +#define PX_CONCAT(X, Y) PX_CONCAT_HELPER(X, Y) + +/* +The following preprocessor identifiers specify compiler, OS, and architecture. +All definitions have a value of 1 or 0, use '#if' instead of '#ifdef'. +*/ + +/** +Compiler defines, see http://sourceforge.net/p/predef/wiki/Compilers/ +*/ +#if defined(_MSC_VER) +#if _MSC_VER >= 1920 + #define PX_VC 16 +#elif _MSC_VER >= 1910 + #define PX_VC 15 +#elif _MSC_VER >= 1900 + #define PX_VC 14 +#elif _MSC_VER >= 1800 + #define PX_VC 12 +#elif _MSC_VER >= 1700 + #define PX_VC 11 +#elif _MSC_VER >= 1600 + #define PX_VC 10 +#elif _MSC_VER >= 1500 + #define PX_VC 9 +#else + #error "Unknown VC version" +#endif +#elif defined(__clang__) +#define PX_CLANG 1 + #if defined (__clang_major__) + #define PX_CLANG_MAJOR __clang_major__ + #elif defined (_clang_major) + #define PX_CLANG_MAJOR _clang_major + #else + #define PX_CLANG_MAJOR 0 + #endif +#elif defined(__GNUC__) // note: __clang__ implies __GNUC__ + #define PX_GCC 1 +#else + #error "Unknown compiler" +#endif + +// not treated as its own compiler because clang, for example, can, in theory, compile CUDA code too +#if defined(__CUDACC__) + #define PX_CUDA_COMPILER 1 +#else + #define PX_CUDA_COMPILER 0 +#endif + +/** +Operating system defines, see http://sourceforge.net/p/predef/wiki/OperatingSystems/ +*/ +#if defined(_WIN64) + #define PX_WIN64 1 +#elif defined(_WIN32) // note: _M_PPC implies _WIN32 + #define PX_WIN32 1 +#elif defined(__linux__) || defined (__EMSCRIPTEN__) + #define PX_LINUX 1 +#elif defined(__APPLE__) + #define PX_OSX 1 +#elif defined(__NX__) + #define PX_SWITCH 1 +#else + #error "Unknown operating system" +#endif + +/** +Architecture defines, see http://sourceforge.net/p/predef/wiki/Architectures/ +*/ +#if defined(__x86_64__) || defined(_M_X64) + #define PX_X64 1 +#elif defined(__i386__) || defined(_M_IX86) || defined (__EMSCRIPTEN__) + #define PX_X86 1 +#elif defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64) + #define PX_A64 1 +#elif defined(__arm__) || defined(_M_ARM) + #define PX_ARM 1 +#elif defined(__ppc__) || defined(_M_PPC) || defined(__CELLOS_LV2__) + #define PX_PPC 1 +#else + #error "Unknown architecture" +#endif + +/** +SIMD defines +*/ +#if !defined(PX_SIMD_DISABLED) + #if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) || (defined (__EMSCRIPTEN__) && defined(__SSE2__)) + #define PX_SSE2 1 + #endif + #if defined(_M_ARM) || defined(__ARM_NEON__) || defined(__ARM_NEON) + #define PX_NEON 1 + #endif + #if defined(_M_PPC) || defined(__CELLOS_LV2__) + #define PX_VMX 1 + #endif +#endif + +/** +define anything not defined on this platform to 0 +*/ +#ifndef PX_VC + #define PX_VC 0 +#endif +#ifndef PX_CLANG + #define PX_CLANG 0 +#endif +#ifndef PX_GCC + #define PX_GCC 0 +#endif +#ifndef PX_WIN64 + #define PX_WIN64 0 +#endif +#ifndef PX_WIN32 + #define PX_WIN32 0 +#endif +#ifndef PX_LINUX + #define PX_LINUX 0 +#endif +#ifndef PX_OSX + #define PX_OSX 0 +#endif +#ifndef PX_SWITCH + #define PX_SWITCH 0 +#endif +#ifndef PX_X64 + #define PX_X64 0 +#endif +#ifndef PX_X86 + #define PX_X86 0 +#endif +#ifndef PX_A64 + #define PX_A64 0 +#endif +#ifndef PX_ARM + #define PX_ARM 0 +#endif +#ifndef PX_PPC + #define PX_PPC 0 +#endif +#ifndef PX_SSE2 + #define PX_SSE2 0 +#endif +#ifndef PX_NEON + #define PX_NEON 0 +#endif +#ifndef PX_VMX + #define PX_VMX 0 +#endif + +/* +define anything not defined through the command line to 0 +*/ +#ifndef PX_DEBUG + #define PX_DEBUG 0 +#endif +#ifndef PX_CHECKED + #define PX_CHECKED 0 +#endif +#ifndef PX_PROFILE + #define PX_PROFILE 0 +#endif +#ifndef PX_DEBUG_CRT + #define PX_DEBUG_CRT 0 +#endif +#ifndef PX_NVTX + #define PX_NVTX 0 +#endif +#ifndef PX_DOXYGEN + #define PX_DOXYGEN 0 +#endif + +/** +family shortcuts +*/ +// compiler +#define PX_GCC_FAMILY (PX_CLANG || PX_GCC) +// os +#define PX_WINDOWS_FAMILY (PX_WIN32 || PX_WIN64) +#define PX_LINUX_FAMILY PX_LINUX +#define PX_APPLE_FAMILY PX_OSX // equivalent to #if __APPLE__ +#define PX_UNIX_FAMILY (PX_LINUX_FAMILY || PX_APPLE_FAMILY) // shortcut for unix/posix platforms +#if defined(__EMSCRIPTEN__) + #define PX_EMSCRIPTEN 1 +#else + #define PX_EMSCRIPTEN 0 +#endif +// architecture +#define PX_INTEL_FAMILY (PX_X64 || PX_X86) +#define PX_ARM_FAMILY (PX_ARM || PX_A64) +#define PX_P64_FAMILY (PX_X64 || PX_A64) // shortcut for 64-bit architectures + +/** +C++ standard library defines +*/ +#if defined(_LIBCPP_VERSION) || PX_WIN64 || PX_WIN32 || PX_EMSCRIPTEN + #define PX_LIBCPP 1 +#else + #define PX_LIBCPP 0 +#endif + +// legacy define for PhysX +#define PX_WINDOWS (PX_WINDOWS_FAMILY && !PX_ARM_FAMILY) + +/** +Assert macro +*/ +#ifndef PX_ENABLE_ASSERTS + #if PX_DEBUG && !PX_CUDA_COMPILER + #define PX_ENABLE_ASSERTS 1 + #else + #define PX_ENABLE_ASSERTS 0 + #endif +#endif + +/** +DLL export macros +*/ +#ifndef PX_C_EXPORT + #if PX_WINDOWS_FAMILY || PX_LINUX + #define PX_C_EXPORT extern "C" + #else + #define PX_C_EXPORT + #endif +#endif + +#if PX_UNIX_FAMILY&& __GNUC__ >= 4 + #define PX_UNIX_EXPORT __attribute__((visibility("default"))) +#else + #define PX_UNIX_EXPORT +#endif + +#if PX_WINDOWS_FAMILY + #define PX_DLL_EXPORT __declspec(dllexport) + #define PX_DLL_IMPORT __declspec(dllimport) +#else + #define PX_DLL_EXPORT PX_UNIX_EXPORT + #define PX_DLL_IMPORT +#endif + +/** +Calling convention +*/ +#ifndef PX_CALL_CONV + #if PX_WINDOWS_FAMILY + #define PX_CALL_CONV __cdecl + #else + #define PX_CALL_CONV + #endif +#endif + +/** +Pack macros - disabled on SPU because they are not supported +*/ +#if PX_VC + #define PX_PUSH_PACK_DEFAULT __pragma(pack(push, 8)) + #define PX_POP_PACK __pragma(pack(pop)) +#elif PX_GCC_FAMILY + #define PX_PUSH_PACK_DEFAULT _Pragma("pack(push, 8)") + #define PX_POP_PACK _Pragma("pack(pop)") +#else + #define PX_PUSH_PACK_DEFAULT + #define PX_POP_PACK +#endif + +/** +Inline macro +*/ +#define PX_INLINE inline +#if PX_WINDOWS_FAMILY + #pragma inline_depth(255) +#endif + +/** +Force inline macro +*/ +#if PX_VC + #define PX_FORCE_INLINE __forceinline +#elif PX_CUDA_COMPILER + #define PX_FORCE_INLINE __forceinline__ +#elif PX_GCC_FAMILY + #define PX_FORCE_INLINE inline __attribute__((always_inline)) +#else + #define PX_FORCE_INLINE inline +#endif + +/** +Noinline macro +*/ +#if PX_WINDOWS_FAMILY + #define PX_NOINLINE __declspec(noinline) +#elif PX_GCC_FAMILY + #define PX_NOINLINE __attribute__((noinline)) +#else + #define PX_NOINLINE +#endif + +/** +Restrict macro +*/ +#if PX_CUDA_COMPILER + #define PX_RESTRICT __restrict__ +#else + #define PX_RESTRICT __restrict +#endif + +/** +Noalias macro +*/ +#if PX_WINDOWS_FAMILY + #define PX_NOALIAS __declspec(noalias) +#else + #define PX_NOALIAS +#endif + +/** +Override macro +*/ +#define PX_OVERRIDE override + +/** +Final macro + */ +#define PX_FINAL final + +/** +Unused attribute macro. Only on GCC for now. + */ +#if PX_GCC_FAMILY + #define PX_UNUSED_ATTRIBUTE __attribute__((unused)) +#else + #define PX_UNUSED_ATTRIBUTE +#endif + +/** +Alignment macros + +PX_ALIGN_PREFIX and PX_ALIGN_SUFFIX can be used for type alignment instead of aligning individual variables as follows: +PX_ALIGN_PREFIX(16) +struct A { +... +} PX_ALIGN_SUFFIX(16); +This declaration style is parsed correctly by Visual Assist. +*/ +#ifndef PX_ALIGN + #if PX_WINDOWS_FAMILY + #define PX_ALIGN(alignment, decl) __declspec(align(alignment)) decl + #define PX_ALIGN_PREFIX(alignment) __declspec(align(alignment)) + #define PX_ALIGN_SUFFIX(alignment) + #elif PX_GCC_FAMILY + #define PX_ALIGN(alignment, decl) decl __attribute__((aligned(alignment))) + #define PX_ALIGN_PREFIX(alignment) + #define PX_ALIGN_SUFFIX(alignment) __attribute__((aligned(alignment))) + #elif PX_CUDA_COMPILER + #define PX_ALIGN(alignment, decl) __align__(alignment) decl + #define PX_ALIGN_PREFIX(alignment) + #define PX_ALIGN_SUFFIX(alignment) __align__(alignment)) + #else + #define PX_ALIGN(alignment, decl) + #define PX_ALIGN_PREFIX(alignment) + #define PX_ALIGN_SUFFIX(alignment) + #endif +#endif + +/** +Deprecated macro +- To deprecate a function: Place PX_DEPRECATED at the start of the function header (leftmost word). +- To deprecate a 'typedef', a 'struct' or a 'class': Place PX_DEPRECATED directly after the keywords ('typedef', +'struct', 'class'). + +Use these macro definitions to create warnings for deprecated functions +\#define PX_DEPRECATED __declspec(deprecated) // Microsoft +\#define PX_DEPRECATED __attribute__((deprecated())) // GCC +*/ +#define PX_DEPRECATED + +/** +General defines +*/ + + +#if PX_LINUX && PX_CLANG && !PX_CUDA_COMPILER +#define PX_COMPILE_TIME_ASSERT(exp) \ +_Pragma(" clang diagnostic push") \ +_Pragma(" clang diagnostic ignored \"-Wc++98-compat\"") \ +static_assert(exp, "") \ +_Pragma(" clang diagnostic pop") +#else +#define PX_COMPILE_TIME_ASSERT(exp) static_assert(exp, "") +#endif + +#if PX_GCC_FAMILY + #define PX_OFFSET_OF(X, Y) __builtin_offsetof(X, Y) +#else + #define PX_OFFSET_OF(X, Y) offsetof(X, Y) +#endif + +#define PX_OFFSETOF_BASE 0x100 // casting the null ptr takes a special-case code path, which we don't want +#define PX_OFFSET_OF_RT(Class, Member) (reinterpret_cast(&reinterpret_cast(PX_OFFSETOF_BASE)->Member) - size_t(PX_OFFSETOF_BASE)) + + +#if PX_WINDOWS_FAMILY + // check that exactly one of NDEBUG and _DEBUG is defined + #if !defined(NDEBUG) ^ defined(_DEBUG) + #error Exactly one of NDEBUG and _DEBUG needs to be defined! + #endif +#endif + +// make sure PX_CHECKED is defined in all _DEBUG configurations as well +#if !PX_CHECKED && PX_DEBUG + #error PX_CHECKED must be defined when PX_DEBUG is defined +#endif + +#if PX_CUDA_COMPILER + #define PX_CUDA_CALLABLE __host__ __device__ +#else + #define PX_CUDA_CALLABLE +#endif + +// avoid unreferenced parameter warning +// preferred solution: omit the parameter's name from the declaration +template +PX_CUDA_CALLABLE PX_INLINE void PX_UNUSED(T const&) +{ +} + +// Ensure that the application hasn't tweaked the pack value to less than 8, which would break +// matching between the API headers and the binaries +// This assert works on win32/win64, but may need further specialization on other platforms. +// Some GCC compilers need the compiler flag -malign-double to be set. +// Apparently the apple-clang-llvm compiler doesn't support malign-double. +#if PX_APPLE_FAMILY || (PX_CLANG && !PX_ARM) + struct PxPackValidation + { + char _; + long a; + }; +#elif PX_CLANG && PX_ARM + struct PxPackValidation + { + char _; + double a; + }; +#else + struct PxPackValidation + { + char _; + long long a; + }; +#endif +// clang (as of version 3.9) cannot align doubles on 8 byte boundary when compiling for Intel 32 bit target +#if !PX_APPLE_FAMILY && !PX_EMSCRIPTEN && !(PX_CLANG && PX_X86) + PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxPackValidation, a) == 8); +#endif + +// use in a cpp file to suppress LNK4221 +#if PX_VC + #define PX_DUMMY_SYMBOL \ + namespace \ + { \ + char PxDummySymbol; \ + } +#else + #define PX_DUMMY_SYMBOL +#endif + +#if PX_GCC_FAMILY + #define PX_WEAK_SYMBOL __attribute__((weak)) // this is to support SIMD constant merging in template specialization +#else + #define PX_WEAK_SYMBOL +#endif + +// Macro for avoiding default assignment and copy, because doing this by inheritance can increase class size on some +// platforms. +#define PX_NOCOPY(Class) \ +protected: \ + Class(const Class&); \ + Class& operator=(const Class&); + +//#define DISABLE_CUDA_PHYSX +#ifndef DISABLE_CUDA_PHYSX + //CUDA is currently supported on x86_64 windows and linux, and ARM_64 linux + #define PX_SUPPORT_GPU_PHYSX ((PX_X64 && (PX_WINDOWS_FAMILY || PX_LINUX)) || (PX_A64 && PX_LINUX)) +#else + #define PX_SUPPORT_GPU_PHYSX 0 +#endif + +#ifndef PX_SUPPORT_EXTERN_TEMPLATE + #define PX_SUPPORT_EXTERN_TEMPLATE (PX_VC != 11) +#else + #define PX_SUPPORT_EXTERN_TEMPLATE 0 +#endif + +#define PX_FL __FILE__, __LINE__ + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxProfiler.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxProfiler.h new file mode 100644 index 000000000..01570f1b4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxProfiler.h @@ -0,0 +1,143 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_PROFILER_H +#define PX_PROFILER_H + +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief The pure virtual callback interface for general purpose instrumentation and profiling of GameWorks modules as +well as applications +*/ +class PxProfilerCallback +{ +protected: + virtual ~PxProfilerCallback() {} + +public: + /************************************************************************************************************************** + Instrumented profiling events + ***************************************************************************************************************************/ + + /** + \brief Mark the beginning of a nested profile block + \param[in] eventName Event name. Must be a persistent const char* that is the same pointer passed to zoneEnd such that the pointer can be used to pair the calls. + \param[in] detached True for cross thread events + \param[in] contextId the context id of this zone. Zones with the same id belong to the same group. 0 is used for no specific group. + \return Returns implementation-specific profiler data for this event + */ + virtual void* zoneStart(const char* eventName, bool detached, uint64_t contextId) = 0; + + /** + \brief Mark the end of a nested profile block + \param[in] profilerData The data returned by the corresponding zoneStart call (or NULL if not available) + \param[in] eventName Event name. Must be a persistent const char* that is the same pointer passed to zoneStart such that the pointer can be used to pair the calls. + \param[in] detached True for cross thread events. Should match the value passed to zoneStart. + \param[in] contextId The context of this zone. Should match the value passed to zoneStart. + + \note eventName plus contextId can be used to uniquely match up start and end of a zone. + */ + virtual void zoneEnd(void* profilerData, const char* eventName, bool detached, uint64_t contextId) = 0; + + /** + \brief Record integer data to be displayed in the profiler. + \param[in] value The integer data point to be recorded. + \param[in] valueName The name of the data being recorded. Must be a persistent const char * + \param[in] contextId The context of this data. + */ + virtual void recordData(int32_t value, const char* valueName, uint64_t contextId) + { + PX_UNUSED(value); + PX_UNUSED(valueName); + PX_UNUSED(contextId); + } + + /** + \brief Record float data to be displayed in the profiler. + \param[in] value The floating point data to be recorded. + \param[in] valueName The name of the data being recorded. Must be a persistent const char * + \param[in] contextId The context of this data. + */ + virtual void recordData(float value, const char* valueName, uint64_t contextId) + { + PX_UNUSED(value); + PX_UNUSED(valueName); + PX_UNUSED(contextId); + } + + /** + \brief Record a frame marker to be displayed in the profiler. + + Markers that have identical names will be displayed in the profiler + along with the time between each of the markers. A frame counter will display the frame marker count. + \param[in] name The name of the frame. Must be a persistent const char * + \param[in] contextId The context of the frame. + */ + virtual void recordFrame(const char* name, uint64_t contextId) + { + PX_UNUSED(name); + PX_UNUSED(contextId); + } +}; + +class PxProfileScoped +{ + public: + PX_FORCE_INLINE PxProfileScoped(PxProfilerCallback* callback, const char* eventName, bool detached, uint64_t contextId) : mCallback(callback), mProfilerData(NULL) + { + if(mCallback) + { + mEventName = eventName; + mContextId = contextId; + mDetached = detached; + mProfilerData = mCallback->zoneStart(eventName, detached, contextId); + } + } + + PX_FORCE_INLINE ~PxProfileScoped() + { + if(mCallback) + mCallback->zoneEnd(mProfilerData, mEventName, mDetached, mContextId); + } + PxProfilerCallback* mCallback; + const char* mEventName; + void* mProfilerData; + uint64_t mContextId; + bool mDetached; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxQuat.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxQuat.h new file mode 100644 index 000000000..0b7dfbc44 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxQuat.h @@ -0,0 +1,428 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_QUAT_H +#define PX_QUAT_H + + +#include "foundation/PxVec3.h" +#if !PX_DOXYGEN +namespace physx +{ +#endif + +template class PxMat33T; + +/** +\brief This is a quaternion class. For more information on quaternion mathematics +consult a mathematics source on complex numbers. +*/ + +template +class PxQuatT +{ + public: + + /** + \brief Default constructor, does not do any initialization. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT() + { + } + + //! identity constructor + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT(PxIDENTITY) : x(Type(0.0)), y(Type(0.0)), z(Type(0.0)), w(Type(1.0)) + { + } + + /** + \brief Constructor from a scalar: sets the real part w to the scalar value, and the imaginary parts (x,y,z) to zero + */ + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT(Type r) : x(Type(0.0)), y(Type(0.0)), z(Type(0.0)), w(r) + { + } + + /** + \brief Constructor. Take note of the order of the elements! + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT(Type nx, Type ny, Type nz, Type nw) : x(nx), y(ny), z(nz), w(nw) + { + } + + /** + \brief Creates from angle-axis representation. + + Axis must be normalized! + + Angle is in radians! + + Unit: Radians + */ + PX_CUDA_CALLABLE PX_INLINE PxQuatT(Type angleRadians, const PxVec3T& unitAxis) + { + PX_ASSERT(PxAbs(Type(1.0) - unitAxis.magnitude()) < Type(1e-3)); + const Type a = angleRadians * Type(0.5); + + Type s; + PxSinCos(a, s, w); + x = unitAxis.x * s; + y = unitAxis.y * s; + z = unitAxis.z * s; + } + + /** + \brief Copy ctor. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT(const PxQuatT& v) : x(v.x), y(v.y), z(v.z), w(v.w) + { + } + + /** + \brief Creates from orientation matrix. + + \param[in] m Rotation matrix to extract quaternion from. + */ + PX_CUDA_CALLABLE PX_INLINE explicit PxQuatT(const PxMat33T& m); /* defined in PxMat33.h */ + + /** + \brief returns true if quat is identity + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isIdentity() const + { + return x==Type(0.0) && y==Type(0.0) && z==Type(0.0) && w==Type(1.0); + } + + /** + \brief returns true if all elements are finite (not NAN or INF, etc.) + */ + PX_CUDA_CALLABLE bool isFinite() const + { + return PxIsFinite(x) && PxIsFinite(y) && PxIsFinite(z) && PxIsFinite(w); + } + + /** + \brief returns true if finite and magnitude is close to unit + */ + PX_CUDA_CALLABLE bool isUnit() const + { + const Type unitTolerance = Type(1e-3); + return isFinite() && PxAbs(magnitude() - Type(1.0)) < unitTolerance; + } + + /** + \brief returns true if finite and magnitude is reasonably close to unit to allow for some accumulation of error vs + isValid + */ + PX_CUDA_CALLABLE bool isSane() const + { + const Type unitTolerance = Type(1e-2); + return isFinite() && PxAbs(magnitude() - Type(1.0)) < unitTolerance; + } + + /** + \brief returns true if the two quaternions are exactly equal + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator==(const PxQuatT& q) const + { + return x == q.x && y == q.y && z == q.z && w == q.w; + } + + /** + \brief converts this quaternion to angle-axis representation + */ + PX_CUDA_CALLABLE PX_INLINE void toRadiansAndUnitAxis(Type& angle, PxVec3T& axis) const + { + const Type quatEpsilon = Type(1.0e-8); + const Type s2 = x * x + y * y + z * z; + if(s2 < quatEpsilon * quatEpsilon) // can't extract a sensible axis + { + angle = Type(0.0); + axis = PxVec3T(Type(1.0), Type(0.0), Type(0.0)); + } + else + { + const Type s = PxRecipSqrt(s2); + axis = PxVec3T(x, y, z) * s; + angle = PxAbs(w) < quatEpsilon ? Type(PxPi) : PxAtan2(s2 * s, w) * Type(2.0); + } + } + + /** + \brief Gets the angle between this quat and the identity quaternion. + + Unit: Radians + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type getAngle() const + { + return PxAcos(w) * Type(2.0); + } + + /** + \brief Gets the angle between this quat and the argument + + Unit: Radians + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type getAngle(const PxQuatT& q) const + { + return PxAcos(dot(q)) * Type(2.0); + } + + /** + \brief This is the squared 4D vector length, should be 1 for unit quaternions. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type magnitudeSquared() const + { + return x * x + y * y + z * z + w * w; + } + + /** + \brief returns the scalar product of this and other. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type dot(const PxQuatT& v) const + { + return x * v.x + y * v.y + z * v.z + w * v.w; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT getNormalized() const + { + const Type s = Type(1.0) / magnitude(); + return PxQuatT(x * s, y * s, z * s, w * s); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE Type magnitude() const + { + return PxSqrt(magnitudeSquared()); + } + + // modifiers: + /** + \brief maps to the closest unit quaternion. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type normalize() // convert this PxQuatT to a unit quaternion + { + const Type mag = magnitude(); + if(mag != Type(0.0)) + { + const Type imag = Type(1.0) / mag; + + x *= imag; + y *= imag; + z *= imag; + w *= imag; + } + return mag; + } + + /* + \brief returns the conjugate. + + \note for unit quaternions, this is the inverse. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT getConjugate() const + { + return PxQuatT(-x, -y, -z, w); + } + + /* + \brief returns imaginary part. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getImaginaryPart() const + { + return PxVec3T(x, y, z); + } + + /** brief computes rotation of x-axis */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getBasisVector0() const + { + const Type x2 = x * Type(2.0); + const Type w2 = w * Type(2.0); + return PxVec3T((w * w2) - Type(1.0) + x * x2, (z * w2) + y * x2, (-y * w2) + z * x2); + } + + /** brief computes rotation of y-axis */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getBasisVector1() const + { + const Type y2 = y * Type(2.0); + const Type w2 = w * Type(2.0); + return PxVec3T((-z * w2) + x * y2, (w * w2) - Type(1.0) + y * y2, (x * w2) + z * y2); + } + + /** brief computes rotation of z-axis */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getBasisVector2() const + { + const Type z2 = z * Type(2.0); + const Type w2 = w * Type(2.0); + return PxVec3T((y * w2) + x * z2, (-x * w2) + y * z2, (w * w2) - Type(1.0) + z * z2); + } + + /** + rotates passed vec by this (assumed unitary) + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3T rotate(const PxVec3T& v) const + { + const Type vx = Type(2.0) * v.x; + const Type vy = Type(2.0) * v.y; + const Type vz = Type(2.0) * v.z; + const Type w2 = w * w - Type(0.5); + const Type dot2 = (x * vx + y * vy + z * vz); + return PxVec3T((vx * w2 + (y * vz - z * vy) * w + x * dot2), (vy * w2 + (z * vx - x * vz) * w + y * dot2), + (vz * w2 + (x * vy - y * vx) * w + z * dot2)); + } + + /** \brief computes inverse rotation of x-axis */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getInvBasisVector0() const + { + const Type x2 = x * Type(2.0); + const Type w2 = w * Type(2.0); + return PxVec3T((w * w2) - Type(1.0) + x * x2, (-z * w2) + y * x2, (y * w2) + z * x2); + } + + /** \brief computes the inverse rotation of the y-axis */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getInvBasisVector1() const + { + const Type y2 = y * Type(2.0); + const Type w2 = w * Type(2.0); + return PxVec3T((z * w2) + x * y2, (w * w2) - Type(1.0) + y * y2, (-x * w2) + z * y2); + } + + /** \brief computes the inverse rotation of the z-axis */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getInvBasisVector2() const + { + const Type z2 = z * Type(2.0); + const Type w2 = w * Type(2.0); + return PxVec3T((-y * w2) + x * z2, (x * w2) + y * z2, (w * w2) - Type(1.0) + z * z2); + } + + /** + inverse rotates passed vec by this (assumed unitary) + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3T rotateInv(const PxVec3T& v) const + { + const Type vx = Type(2.0) * v.x; + const Type vy = Type(2.0) * v.y; + const Type vz = Type(2.0) * v.z; + const Type w2 = w * w - Type(0.5); + const Type dot2 = (x * vx + y * vy + z * vz); + return PxVec3T((vx * w2 - (y * vz - z * vy) * w + x * dot2), (vy * w2 - (z * vx - x * vz) * w + y * dot2), + (vz * w2 - (x * vy - y * vx) * w + z * dot2)); + } + + /** + \brief Assignment operator + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT& operator=(const PxQuatT& p) + { + x = p.x; + y = p.y; + z = p.z; + w = p.w; + return *this; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT& operator*=(const PxQuatT& q) + { + const Type tx = w * q.x + q.w * x + y * q.z - q.y * z; + const Type ty = w * q.y + q.w * y + z * q.x - q.z * x; + const Type tz = w * q.z + q.w * z + x * q.y - q.x * y; + + w = w * q.w - q.x * x - y * q.y - q.z * z; + x = tx; + y = ty; + z = tz; + return *this; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT& operator+=(const PxQuatT& q) + { + x += q.x; + y += q.y; + z += q.z; + w += q.w; + return *this; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT& operator-=(const PxQuatT& q) + { + x -= q.x; + y -= q.y; + z -= q.z; + w -= q.w; + return *this; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT& operator*=(const Type s) + { + x *= s; + y *= s; + z *= s; + w *= s; + return *this; + } + + /** quaternion multiplication */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT operator*(const PxQuatT& q) const + { + return PxQuatT(w * q.x + q.w * x + y * q.z - q.y * z, w * q.y + q.w * y + z * q.x - q.z * x, + w * q.z + q.w * z + x * q.y - q.x * y, w * q.w - x * q.x - y * q.y - z * q.z); + } + + /** quaternion addition */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT operator+(const PxQuatT& q) const + { + return PxQuatT(x + q.x, y + q.y, z + q.z, w + q.w); + } + + /** quaternion subtraction */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT operator-() const + { + return PxQuatT(-x, -y, -z, -w); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT operator-(const PxQuatT& q) const + { + return PxQuatT(x - q.x, y - q.y, z - q.z, w - q.w); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuatT operator*(Type r) const + { + return PxQuatT(x * r, y * r, z * r, w * r); + } + + /** the quaternion elements */ + Type x, y, z, w; +}; + +typedef PxQuatT PxQuat; +typedef PxQuatT PxQuatd; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSIMDHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSIMDHelpers.h new file mode 100644 index 000000000..8d29cc2ff --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSIMDHelpers.h @@ -0,0 +1,134 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SIMD_HELPERS_H +#define PX_SIMD_HELPERS_H + +#include "foundation/PxMat33.h" +#include "foundation/PxVecMath.h" +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + //! A padded version of PxMat33, to safely load its data using SIMD + class PxMat33Padded : public PxMat33 + { + public: + explicit PX_FORCE_INLINE PxMat33Padded(const PxQuat& q) + { + using namespace aos; + const QuatV qV = V4LoadU(&q.x); + Vec3V column0V, column1V, column2V; + QuatGetMat33V(qV, column0V, column1V, column2V); +#if defined(PX_SIMD_DISABLED) || (PX_LINUX && (PX_ARM || PX_A64)) + V3StoreU(column0V, column0); + V3StoreU(column1V, column1); + V3StoreU(column2V, column2); +#else + V4StoreU(column0V, &column0.x); + V4StoreU(column1V, &column1.x); + V4StoreU(column2V, &column2.x); +#endif + } + PX_FORCE_INLINE ~PxMat33Padded() {} + PX_FORCE_INLINE void operator=(const PxMat33& other) + { + column0 = other.column0; + column1 = other.column1; + column2 = other.column2; + } + PxU32 padding; + }; + +#if !PX_DOXYGEN +namespace aos +{ +#endif + + PX_FORCE_INLINE void transformKernelVec4( const FloatVArg wa, const Vec4VArg va, const Vec4VArg pa, + const FloatVArg wb, const Vec4VArg vb, const Vec4VArg pb, + FloatV& wo, Vec4V& vo, Vec4V& po) + { + wo = FSub(FMul(wa, wb), V4Dot3(va, vb)); + vo = V4ScaleAdd(va, wb, V4ScaleAdd(vb, wa, V4Cross(va, vb))); + + const Vec4V t1 = V4Scale(pb, FScaleAdd(wa, wa, FLoad(-0.5f))); + const Vec4V t2 = V4ScaleAdd(V4Cross(va, pb), wa, t1); + const Vec4V t3 = V4ScaleAdd(va, V4Dot3(va, pb), t2); + + po = V4ScaleAdd(t3, FLoad(2.0f), pa); + } + + // PT: out = a * b + template + PX_FORCE_INLINE void transformMultiply(PxTransform& out, const PxTransform& a, const PxTransform& b) + { + PX_ASSERT(!alignedInput || (size_t(&a)&15) == 0); + PX_ASSERT(!alignedInput || (size_t(&b)&15) == 0); + + const Vec4V aPos = alignedInput ? V4LoadA(&a.p.x) : V4LoadU(&a.p.x); + const Vec4V aRot = alignedInput ? V4LoadA(&a.q.x) : V4LoadU(&a.q.x); + + const Vec4V bPos = alignedInput ? V4LoadA(&b.p.x) : V4LoadU(&b.p.x); + const Vec4V bRot = alignedInput ? V4LoadA(&b.q.x) : V4LoadU(&b.q.x); + + Vec4V v, p; + FloatV w; + transformKernelVec4(V4GetW(aRot), aRot, aPos, V4GetW(bRot), bRot, bPos, w, v, p); + + if(alignedOutput) + { + PX_ASSERT((size_t(&out)&15) == 0); + V4StoreA(p, &out.p.x); + V4StoreA(V4SetW(v,w), &out.q.x); + } + else + { + V4StoreU(p, &out.p.x); + V4StoreU(V4SetW(v,w), &out.q.x); + } + } + + // PT: out = a * b + PX_FORCE_INLINE void transformMultiply(PxTransform32& out, const PxTransform32& a, const PxTransform32& b) + { + transformMultiply(out, a, b); + } + +#if !PX_DOXYGEN +} // namespace aos +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSList.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSList.h new file mode 100644 index 000000000..a8a5894ff --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSList.h @@ -0,0 +1,132 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SLIST_H +#define PX_SLIST_H + +#include "foundation/PxAssert.h" +#include "foundation/PxAlignedMalloc.h" + +#if PX_P64_FAMILY + #define PX_SLIST_ALIGNMENT 16 +#else + #define PX_SLIST_ALIGNMENT 8 +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +#if PX_VC + #pragma warning(push) + #pragma warning(disable : 4324) // Padding was added at the end of a structure because of a __declspec(align) value. +#endif + +PX_ALIGN_PREFIX(PX_SLIST_ALIGNMENT) +class PxSListEntry +{ + friend struct PxSListImpl; + + public: + PxSListEntry() : mNext(NULL) + { + PX_ASSERT((size_t(this) & (PX_SLIST_ALIGNMENT - 1)) == 0); + } + + // Only use on elements returned by SList::flush() + // because the operation is not atomic. + PxSListEntry* next() + { + return mNext; + } + + private: + PxSListEntry* mNext; +}PX_ALIGN_SUFFIX(PX_SLIST_ALIGNMENT); + +#if PX_VC + #pragma warning(pop) +#endif + +// template-less implementation +struct PX_FOUNDATION_API PxSListImpl +{ + PxSListImpl(); + ~PxSListImpl(); + void push(PxSListEntry* entry); + PxSListEntry* pop(); + PxSListEntry* flush(); + static uint32_t getSize(); +}; + +template > +class PxSListT : protected Alloc +{ + public: + PxSListT(const Alloc& alloc = Alloc()) : Alloc(alloc) + { + mImpl = reinterpret_cast(Alloc::allocate(PxSListImpl::getSize(), PX_FL)); + PX_ASSERT((size_t(mImpl) & (PX_SLIST_ALIGNMENT - 1)) == 0); + PX_PLACEMENT_NEW(mImpl, PxSListImpl)(); + } + ~PxSListT() + { + mImpl->~PxSListImpl(); + Alloc::deallocate(mImpl); + } + + // pushes a new element to the list + void push(PxSListEntry& entry) + { + mImpl->push(&entry); + } + + // pops an element from the list + PxSListEntry* pop() + { + return mImpl->pop(); + } + + // removes all items from list, returns pointer to first element + PxSListEntry* flush() + { + return mImpl->flush(); + } + + private: + PxSListImpl* mImpl; +}; + +typedef PxSListT<> PxSList; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSimpleTypes.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSimpleTypes.h new file mode 100644 index 000000000..d9c87f962 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSimpleTypes.h @@ -0,0 +1,120 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SIMPLE_TYPES_H +#define PX_SIMPLE_TYPES_H + + +// Platform specific types: +// Design note: Its OK to use int for general loop variables and temps. + +#include "foundation/PxPreprocessor.h" +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4668) // suppressing warning generated by Microsoft Visual Studio when including this standard +// header +#endif + +#include +#if PX_VC +#pragma warning(pop) +#endif + +#if PX_VC // we could use inttypes.h starting with VC12 +#define PX_PRIu64 "I64u" +#else +#include +#define PX_PRIu64 PRIu64 +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +typedef int64_t PxI64; +typedef uint64_t PxU64; +typedef int32_t PxI32; +typedef uint32_t PxU32; +typedef int16_t PxI16; +typedef uint16_t PxU16; +typedef int8_t PxI8; +typedef uint8_t PxU8; +typedef float PxF32; +typedef double PxF64; +typedef float PxReal; +// Int-as-bool type - has some uses for efficiency and with SIMD +typedef PxI32 PxIntBool; +static const PxIntBool PxIntFalse = 0; +static const PxIntBool PxIntTrue = 1; + +// types for direct-GPU API +typedef PxU32 PxArticulationGPUIndex; +typedef PxU32 PxRigidDynamicGPUIndex; +typedef PxU32 PxShapeGPUIndex; + +typedef PxU32 PxConstraintGPUIndex; +#define PX_INVALID_CONSTRAINT_GPU_INDEX 0xffffFFFF + +typedef PxConstraintGPUIndex PxD6JointGPUIndex; +#define PX_INVALID_D6_JOINT_GPU_INDEX PX_INVALID_CONSTRAINT_GPU_INDEX + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#define PX_SIGN_BITMASK 0x80000000 + +// Type ranges + +#define PX_MAX_F32 3.4028234663852885981170418348452e+38F +// maximum possible float value +#define PX_MAX_F64 DBL_MAX // maximum possible double value + +#define PX_EPS_F32 FLT_EPSILON // maximum relative error of float rounding +#define PX_EPS_F64 DBL_EPSILON // maximum relative error of double rounding + +#define PX_MAX_REAL PX_MAX_F32 +#define PX_EPS_REAL PX_EPS_F32 +#define PX_NORMALIZATION_EPSILON float(1e-20f) + +// Legacy type ranges used by PhysX +#define PX_MAX_I8 INT8_MAX +#define PX_MIN_I8 INT8_MIN +#define PX_MAX_U8 UINT8_MAX +#define PX_MIN_U8 UINT8_MIN +#define PX_MAX_I16 INT16_MAX +#define PX_MIN_I16 INT16_MIN +#define PX_MAX_U16 UINT16_MAX +#define PX_MIN_U16 UINT16_MIN +#define PX_MAX_I32 INT32_MAX +#define PX_MIN_I32 INT32_MIN +#define PX_MAX_U32 UINT32_MAX +#define PX_MIN_U32 UINT32_MIN + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSocket.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSocket.h new file mode 100644 index 000000000..251879267 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSocket.h @@ -0,0 +1,187 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SOCKET_H +#define PX_SOCKET_H + +#include "foundation/PxUserAllocated.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +/** +Socket abstraction API +*/ + +class PX_FOUNDATION_API PxSocket : public PxUserAllocated +{ + public: + static const uint32_t DEFAULT_BUFFER_SIZE; + + PxSocket(bool inEnableBuffering = true, bool blocking = true); + + virtual ~PxSocket(); + + /*! + Opens a network socket for input and/or output + + \param host + Name of the host to connect to. This can be an IP, URL, etc + + \param port + The port to connect to on the remote host + + \param timeout + Timeout in ms until the connection must be established. + + \return + True if the connection was successful, false otherwise + */ + bool connect(const char* host, uint16_t port, uint32_t timeout = 1000); + + /*! + Opens a network socket for input and/or output as a server. Put the connection in listening mode + + \param port + The port on which the socket listens + */ + bool listen(uint16_t port); + + /*! + Accept a connection on a socket that is in listening mode + + \note + This method only supports a single connection client. Additional clients + that connect to the listening port will overwrite the existing socket handle. + + \param block + whether or not the call should block + + \return whether a connection was established + */ + bool accept(bool block); + + /*! + Disconnects an open socket + */ + void disconnect(); + + /*! + Returns whether the socket is currently open (connected) or not. + + \return + True if the socket is connected, false otherwise + */ + bool isConnected() const; + + /*! + Returns the name of the connected host. This is the same as the string + that was supplied to the connect call. + + \return + The name of the connected host + */ + const char* getHost() const; + + /*! + Returns the port of the connected host. This is the same as the port + that was supplied to the connect call. + + \return + The port of the connected host + */ + uint16_t getPort() const; + + /*! + Flushes the output stream. Until the stream is flushed, there is no + guarantee that the written data has actually reached the destination + storage. Flush forces all buffered data to be sent to the output. + + \note flush always blocks. If the socket is in non-blocking mode, this will result + the thread spinning. + + \return + True if the flush was successful, false otherwise + */ + bool flush(); + + /*! + Writes data to the output stream. + + \param data + Pointer to a block of data to write to the stream + + \param length + Amount of data to write, in bytes + + \return + Number of bytes actually written. This could be lower than length if the socket is non-blocking. + */ + + uint32_t write(const uint8_t* data, uint32_t length); + + /*! + Reads data from the output stream. + + \param data + Pointer to a buffer where the read data will be stored. + + \param length + Amount of data to read, in bytes. + + \return + Number of bytes actually read. This could be lower than length if the stream end is + encountered or the socket is non-blocking. + */ + uint32_t read(uint8_t* data, uint32_t length); + + /*! + Sets blocking mode of the socket. + Socket must be connected, otherwise calling this method won't take any effect. + */ + void setBlocking(bool blocking); + + /*! + Returns whether read/write/flush calls to the socket are blocking. + + \return + True if the socket is blocking. + */ + bool isBlocking() const; + + private: + class SocketImpl* mImpl; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSort.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSort.h new file mode 100644 index 000000000..f89256833 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSort.h @@ -0,0 +1,127 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SORT_H +#define PX_SORT_H + + +#include "foundation/PxSortInternals.h" +#include "foundation/PxAlloca.h" + +#define PX_SORT_PARANOIA PX_DEBUG + +/** +\brief Sorts an array of objects in ascending order, assuming +that the predicate implements the < operator: + +\see PxLess, PxGreater +*/ + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4706) // disable the warning that we did an assignment within a conditional expression, as +// this was intentional. +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +template +void PxSort(T* elements, uint32_t count, const Predicate& compare, const PxAllocator& inAllocator, + const uint32_t initialStackSize = 32) +{ + static const uint32_t SMALL_SORT_CUTOFF = 5; // must be >= 3 since we need 3 for median + + PX_ALLOCA(stackMem, int32_t, initialStackSize); + PxStack stack(stackMem, initialStackSize, inAllocator); + + int32_t first = 0, last = int32_t(count - 1); + if(last > first) + { + for(;;) + { + while(last > first) + { + PX_ASSERT(first >= 0 && last < int32_t(count)); + if(uint32_t(last - first) < SMALL_SORT_CUTOFF) + { + PxSmallSort(elements, first, last, compare); + break; + } + else + { + const int32_t partIndex = PxPartition(elements, first, last, compare); + + // push smaller sublist to minimize stack usage + if((partIndex - first) < (last - partIndex)) + { + stack.push(first, partIndex - 1); + first = partIndex + 1; + } + else + { + stack.push(partIndex + 1, last); + last = partIndex - 1; + } + } + } + + if(stack.empty()) + break; + + stack.pop(first, last); + } + } +#if PX_SORT_PARANOIA + for(uint32_t i = 1; i < count; i++) + PX_ASSERT(!compare(elements[i], elements[i - 1])); +#endif +} + +template +void PxSort(T* elements, uint32_t count, const Predicate& compare) +{ + PxSort(elements, count, compare, typename PxAllocatorTraits::Type()); +} + +template +void PxSort(T* elements, uint32_t count) +{ + PxSort(elements, count, PxLess(), typename PxAllocatorTraits::Type()); +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#if PX_VC +#pragma warning(pop) +#endif +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSortInternals.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSortInternals.h new file mode 100644 index 000000000..4b37e5cf6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSortInternals.h @@ -0,0 +1,182 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SORT_INTERNALS_H +#define PX_SORT_INTERNALS_H + + +#include "foundation/PxAssert.h" +#include "foundation/PxMathIntrinsics.h" +#include "foundation/PxBasicTemplates.h" +#include "foundation/PxUserAllocated.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +template +PX_INLINE void PxMedian3(T* elements, int32_t first, int32_t last, Predicate& compare) +{ + /* + This creates sentinels because we know there is an element at the start minimum(or equal) + than the pivot and an element at the end greater(or equal) than the pivot. Plus the + median of 3 reduces the chance of degenerate behavour. + */ + + int32_t mid = (first + last) / 2; + + if(compare(elements[mid], elements[first])) + PxSwap(elements[first], elements[mid]); + + if(compare(elements[last], elements[first])) + PxSwap(elements[first], elements[last]); + + if(compare(elements[last], elements[mid])) + PxSwap(elements[mid], elements[last]); + + // keep the pivot at last-1 + PxSwap(elements[mid], elements[last - 1]); +} + +template +PX_INLINE int32_t PxPartition(T* elements, int32_t first, int32_t last, Predicate& compare) +{ + PxMedian3(elements, first, last, compare); + + /* + WARNING: using the line: + + T partValue = elements[last-1]; + + and changing the scan loops to: + + while(comparator.greater(partValue, elements[++i])); + while(comparator.greater(elements[--j], partValue); + + triggers a compiler optimizer bug on xenon where it stores a double to the stack for partValue + then loads it as a single...:-( + */ + + int32_t i = first; // we know first is less than pivot(but i gets pre incremented) + int32_t j = last - 1; // pivot is in last-1 (but j gets pre decremented) + + for(;;) + { + while(compare(elements[++i], elements[last - 1])) + ; + while(compare(elements[last - 1], elements[--j])) + ; + + if(i >= j) + break; + + PX_ASSERT(i <= last && j >= first); + PxSwap(elements[i], elements[j]); + } + // put the pivot in place + + PX_ASSERT(i <= last && first <= (last - 1)); + PxSwap(elements[i], elements[last - 1]); + + return i; +} + +template +PX_INLINE void PxSmallSort(T* elements, int32_t first, int32_t last, Predicate& compare) +{ + // selection sort - could reduce to fsel on 360 with floats. + + for(int32_t i = first; i < last; i++) + { + int32_t m = i; + for(int32_t j = i + 1; j <= last; j++) + if(compare(elements[j], elements[m])) + m = j; + + if(m != i) + PxSwap(elements[m], elements[i]); + } +} + +template +class PxStack +{ + PxAllocator mAllocator; + uint32_t mSize, mCapacity; + int32_t* mMemory; + bool mRealloc; + + public: + PxStack(int32_t* memory, uint32_t capacity, const PxAllocator& inAllocator) + : mAllocator(inAllocator), mSize(0), mCapacity(capacity), mMemory(memory), mRealloc(false) + { + } + ~PxStack() + { + if(mRealloc) + mAllocator.deallocate(mMemory); + } + + void grow() + { + mCapacity *= 2; + int32_t* newMem = + reinterpret_cast(mAllocator.allocate(sizeof(int32_t) * mCapacity, PX_FL)); + intrinsics::memCopy(newMem, mMemory, mSize * sizeof(int32_t)); + if(mRealloc) + mAllocator.deallocate(mMemory); + mRealloc = true; + mMemory = newMem; + } + + PX_INLINE void push(int32_t start, int32_t end) + { + if(mSize >= mCapacity - 1) + grow(); + mMemory[mSize++] = start; + mMemory[mSize++] = end; + } + + PX_INLINE void pop(int32_t& start, int32_t& end) + { + PX_ASSERT(!empty()); + end = mMemory[--mSize]; + start = mMemory[--mSize]; + } + + PX_INLINE bool empty() + { + return mSize == 0; + } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxStrideIterator.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxStrideIterator.h new file mode 100644 index 000000000..933e338f6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxStrideIterator.h @@ -0,0 +1,348 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_STRIDE_ITERATOR_H +#define PX_STRIDE_ITERATOR_H + +#include "foundation/PxAssert.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Iterator class for iterating over arrays of data that may be interleaved with other data. + +This class is used for iterating over arrays of elements that may have a larger element to element +offset, called the stride, than the size of the element itself (non-contiguous). + +The template parameter T denotes the type of the element accessed. The stride itself +is stored as a member field so multiple instances of a PxStrideIterator class can have +different strides. This is useful for cases were the stride depends on runtime configuration. + +The stride iterator can be used for index based access, e.g.: +\code + PxStrideIterator strideArray(...); + for (unsigned i = 0; i < 10; ++i) + { + PxVec3& vec = strideArray[i]; + ... + } +\endcode +or iteration by increment, e.g.: +\code + PxStrideIterator strideBegin(...); + PxStrideIterator strideEnd(strideBegin + 10); + for (PxStrideIterator it = strideBegin; it < strideEnd; ++it) + { + PxVec3& vec = *it; + ... + } +\endcode + +Two special cases: +- A stride of sizeof(T) represents a regular c array of type T. +- A stride of 0 can be used to describe re-occurrence of the same element multiple times. + +*/ +template +class PxStrideIterator +{ + +#if !PX_DOXYGEN + template + struct StripConst + { + typedef X Type; + }; + + template + struct StripConst + { + typedef X Type; + }; +#endif + + public: + /** + \brief Constructor. + + Optionally takes a pointer to an element and a stride. + + \param[in] ptr pointer to element, defaults to NULL. + \param[in] stride stride for accessing consecutive elements, defaults to the size of one element. + */ + explicit PX_INLINE PxStrideIterator(T* ptr = NULL, PxU32 stride = sizeof(T)) : mPtr(ptr), mStride(stride) + { + PX_ASSERT(mStride == 0 || sizeof(T) <= mStride); + } + + /** + \brief Copy constructor. + + \param[in] strideIterator PxStrideIterator to be copied. + */ + PX_INLINE PxStrideIterator(const PxStrideIterator::Type>& strideIterator) + : mPtr(strideIterator.ptr()), mStride(strideIterator.stride()) + { + PX_ASSERT(mStride == 0 || sizeof(T) <= mStride); + } + + /** + \brief Get pointer to element. + */ + PX_INLINE T* ptr() const + { + return mPtr; + } + + /** + \brief Get stride. + */ + PX_INLINE PxU32 stride() const + { + return mStride; + } + + /** + \brief Indirection operator. + */ + PX_INLINE T& operator*() const + { + return *mPtr; + } + + /** + \brief Dereferencing operator. + */ + PX_INLINE T* operator->() const + { + return mPtr; + } + + /** + \brief Indexing operator. + */ + PX_INLINE T& operator[](unsigned int i) const + { + return *byteAdd(mPtr, i * stride()); + } + + /** + \brief Pre-increment operator. + */ + PX_INLINE PxStrideIterator& operator++() + { + mPtr = byteAdd(mPtr, stride()); + return *this; + } + + /** + \brief Post-increment operator. + */ + PX_INLINE PxStrideIterator operator++(int) + { + PxStrideIterator tmp = *this; + mPtr = byteAdd(mPtr, stride()); + return tmp; + } + + /** + \brief Pre-decrement operator. + */ + PX_INLINE PxStrideIterator& operator--() + { + mPtr = byteSub(mPtr, stride()); + return *this; + } + + /** + \brief Post-decrement operator. + */ + PX_INLINE PxStrideIterator operator--(int) + { + PxStrideIterator tmp = *this; + mPtr = byteSub(mPtr, stride()); + return tmp; + } + + /** + \brief Addition operator. + */ + PX_INLINE PxStrideIterator operator+(unsigned int i) const + { + return PxStrideIterator(byteAdd(mPtr, i * stride()), stride()); + } + + /** + \brief Subtraction operator. + */ + PX_INLINE PxStrideIterator operator-(unsigned int i) const + { + return PxStrideIterator(byteSub(mPtr, i * stride()), stride()); + } + + /** + \brief Addition compound assignment operator. + */ + PX_INLINE PxStrideIterator& operator+=(unsigned int i) + { + mPtr = byteAdd(mPtr, i * stride()); + return *this; + } + + /** + \brief Subtraction compound assignment operator. + */ + PX_INLINE PxStrideIterator& operator-=(unsigned int i) + { + mPtr = byteSub(mPtr, i * stride()); + return *this; + } + + /** + \brief Iterator difference. + */ + PX_INLINE int operator-(const PxStrideIterator& other) const + { + PX_ASSERT(isCompatible(other)); + int byteDiff = static_cast(reinterpret_cast(mPtr) - reinterpret_cast(other.mPtr)); + return byteDiff / static_cast(stride()); + } + + /** + \brief Equality operator. + */ + PX_INLINE bool operator==(const PxStrideIterator& other) const + { + PX_ASSERT(isCompatible(other)); + return mPtr == other.mPtr; + } + + /** + \brief Inequality operator. + */ + PX_INLINE bool operator!=(const PxStrideIterator& other) const + { + PX_ASSERT(isCompatible(other)); + return mPtr != other.mPtr; + } + + /** + \brief Less than operator. + */ + PX_INLINE bool operator<(const PxStrideIterator& other) const + { + PX_ASSERT(isCompatible(other)); + return mPtr < other.mPtr; + } + + /** + \brief Greater than operator. + */ + PX_INLINE bool operator>(const PxStrideIterator& other) const + { + PX_ASSERT(isCompatible(other)); + return mPtr > other.mPtr; + } + + /** + \brief Less or equal than operator. + */ + PX_INLINE bool operator<=(const PxStrideIterator& other) const + { + PX_ASSERT(isCompatible(other)); + return mPtr <= other.mPtr; + } + + /** + \brief Greater or equal than operator. + */ + PX_INLINE bool operator>=(const PxStrideIterator& other) const + { + PX_ASSERT(isCompatible(other)); + return mPtr >= other.mPtr; + } + + private: + PX_INLINE static T* byteAdd(T* ptr, PxU32 bytes) + { + return const_cast(reinterpret_cast(reinterpret_cast(ptr) + bytes)); + } + + PX_INLINE static T* byteSub(T* ptr, PxU32 bytes) + { + return const_cast(reinterpret_cast(reinterpret_cast(ptr) - bytes)); + } + + PX_INLINE bool isCompatible(const PxStrideIterator& other) const + { + int byteDiff = static_cast(reinterpret_cast(mPtr) - reinterpret_cast(other.mPtr)); + return (stride() == other.stride()) && (abs(byteDiff) % stride() == 0); + } + + T* mPtr; + PxU32 mStride; +}; + +/** +\brief Addition operator. +*/ +template +PX_INLINE PxStrideIterator operator+(int i, PxStrideIterator it) +{ + it += i; + return it; +} + +/** +\brief Stride iterator factory function which infers the iterator type. +*/ +template +PX_INLINE PxStrideIterator PxMakeIterator(T* ptr, PxU32 stride = sizeof(T)) +{ + return PxStrideIterator(ptr, stride); +} + +/** +\brief Stride iterator factory function which infers the iterator type. +*/ +template +PX_INLINE PxStrideIterator PxMakeIterator(const T* ptr, PxU32 stride = sizeof(T)) +{ + return PxStrideIterator(ptr, stride); +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxString.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxString.h new file mode 100644 index 000000000..916bf3a2b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxString.h @@ -0,0 +1,79 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_STRING_H +#define PX_STRING_H + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxFoundationConfig.h" +#include + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +// the following functions have C99 semantics. Note that C99 requires for snprintf and vsnprintf: +// * the resulting string is always NULL-terminated regardless of truncation. +// * in the case of truncation the return value is the number of characters that would have been created. + +PX_FOUNDATION_API int32_t Pxsscanf(const char* buffer, const char* format, ...); +PX_FOUNDATION_API int32_t Pxstrcmp(const char* str1, const char* str2); +PX_FOUNDATION_API int32_t Pxstrncmp(const char* str1, const char* str2, size_t count); +PX_FOUNDATION_API int32_t Pxsnprintf(char* dst, size_t dstSize, const char* format, ...); +PX_FOUNDATION_API int32_t Pxvsnprintf(char* dst, size_t dstSize, const char* src, va_list arg); + +// strlcat and strlcpy have BSD semantics: +// * dstSize is always the size of the destination buffer +// * the resulting string is always NULL-terminated regardless of truncation +// * in the case of truncation the return value is the length of the string that would have been created + +PX_FOUNDATION_API size_t Pxstrlcat(char* dst, size_t dstSize, const char* src); +PX_FOUNDATION_API size_t Pxstrlcpy(char* dst, size_t dstSize, const char* src); + +// case-insensitive string comparison +PX_FOUNDATION_API int32_t Pxstricmp(const char* str1, const char* str2); +PX_FOUNDATION_API int32_t Pxstrnicmp(const char* str1, const char* str2, size_t count); + +// in-place string case conversion +PX_FOUNDATION_API void Pxstrlwr(char* str); +PX_FOUNDATION_API void Pxstrupr(char* str); + + +/** +\brief Prints the string literally (does not consume % specifier), trying to make sure it's visible to the app +programmer +*/ +PX_FOUNDATION_API void PxPrintString(const char*); + +#if !PX_DOXYGEN +} // namespace physx +#endif +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSync.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSync.h new file mode 100644 index 000000000..4c7fe9fc5 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxSync.h @@ -0,0 +1,139 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SYNC_H +#define PX_SYNC_H + +#include "foundation/PxAllocator.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +/*! +Implementation notes: +* - Calling set() on an already signaled Sync does not change its state. +* - Calling reset() on an already reset Sync does not change its state. +* - Calling set() on a reset Sync wakes all waiting threads (potential for thread contention). +* - Calling wait() on an already signaled Sync will return true immediately. +* - NOTE: be careful when pulsing an event with set() followed by reset(), because a +* thread that is not waiting on the event will miss the signal. +*/ +class PX_FOUNDATION_API PxSyncImpl +{ + public: + static const uint32_t waitForever = 0xffffffff; + + PxSyncImpl(); + + ~PxSyncImpl(); + + /** Wait on the object for at most the given number of ms. Returns + * true if the object is signaled. Sync::waitForever will block forever + * or until the object is signaled. + */ + + bool wait(uint32_t milliseconds = waitForever); + + /** Signal the synchronization object, waking all threads waiting on it */ + + void set(); + + /** Reset the synchronization object */ + + void reset(); + + /** + Size of this class. + */ + static uint32_t getSize(); +}; + +/*! +Implementation notes: +* - Calling set() on an already signaled Sync does not change its state. +* - Calling reset() on an already reset Sync does not change its state. +* - Calling set() on a reset Sync wakes all waiting threads (potential for thread contention). +* - Calling wait() on an already signaled Sync will return true immediately. +* - NOTE: be careful when pulsing an event with set() followed by reset(), because a +* thread that is not waiting on the event will miss the signal. +*/ +template > +class PxSyncT : protected Alloc +{ + public: + static const uint32_t waitForever = PxSyncImpl::waitForever; + + PxSyncT(const Alloc& alloc = Alloc()) : Alloc(alloc) + { + mImpl = reinterpret_cast(Alloc::allocate(PxSyncImpl::getSize(), PX_FL)); + PX_PLACEMENT_NEW(mImpl, PxSyncImpl)(); + } + + ~PxSyncT() + { + mImpl->~PxSyncImpl(); + Alloc::deallocate(mImpl); + } + + /** Wait on the object for at most the given number of ms. Returns + * true if the object is signaled. Sync::waitForever will block forever + * or until the object is signaled. + */ + + bool wait(uint32_t milliseconds = PxSyncImpl::waitForever) + { + return mImpl->wait(milliseconds); + } + + /** Signal the synchronization object, waking all threads waiting on it */ + + void set() + { + mImpl->set(); + } + + /** Reset the synchronization object */ + + void reset() + { + mImpl->reset(); + } + + private: + class PxSyncImpl* mImpl; +}; + +typedef PxSyncT<> PxSync; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTempAllocator.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTempAllocator.h new file mode 100644 index 000000000..1744191f8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTempAllocator.h @@ -0,0 +1,54 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TEMP_ALLOCATOR_H +#define PX_TEMP_ALLOCATOR_H + +#include "foundation/PxAllocator.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxTempAllocator +{ + public: + PX_FORCE_INLINE PxTempAllocator(const char* = 0) + { + } + PX_FOUNDATION_API void* allocate(size_t size, const char* file, PxI32 line); + PX_FOUNDATION_API void deallocate(void* ptr); +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxThread.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxThread.h new file mode 100644 index 000000000..eaca9fce6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxThread.h @@ -0,0 +1,369 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_THREAD_H +#define PX_THREAD_H + +#include "foundation/PxUserAllocated.h" + +// todo: these need to go somewhere else +// PT: looks like this is still used on some platforms + +#if PX_WINDOWS_FAMILY +#define PxSpinLockPause() __asm pause +#elif PX_LINUX || PX_APPLE_FAMILY || PX_SWITCH +#define PxSpinLockPause() asm("nop") +#else +#error "Platform not supported!" +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxThreadPriority +{ + enum Enum + { + eHIGH = 0, //!< High priority + eABOVE_NORMAL = 1, //!< Above Normal priority + eNORMAL = 2, //!< Normal/default priority + eBELOW_NORMAL = 3, //!< Below Normal priority + eLOW = 4, //!< Low priority. + eFORCE_DWORD = 0xffFFffFF + }; +}; + +class PxRunnable +{ + public: + PxRunnable() {} + virtual ~PxRunnable() {} + virtual void execute() {} +}; + +class PX_FOUNDATION_API PxThreadImpl +{ + public: + typedef size_t Id; // space for a pointer or an integer + typedef void* (*ExecuteFn)(void*); + + static PxU32 getDefaultStackSize(); + static Id getId(); + + /** + Construct (but do not start) the thread object. The OS thread object will not be created + until start() is called. Executes in the context + of the spawning thread. + */ + + PxThreadImpl(); + + /** + Construct and start the the thread, passing the given arg to the given fn. (pthread style) + */ + + PxThreadImpl(ExecuteFn fn, void* arg, const char* name); + + /** + Deallocate all resources associated with the thread. Should be called in the + context of the spawning thread. + */ + + ~PxThreadImpl(); + + /** + Create the OS thread and start it running. Called in the context of the spawning thread. + If an affinity mask has previously been set then it will be applied after the + thread has been created. + */ + + void start(PxU32 stackSize, PxRunnable* r); + + /** + Violently kill the current thread. Blunt instrument, not recommended since + it can leave all kinds of things unreleased (stack, memory, mutexes...) Should + be called in the context of the spawning thread. + */ + + void kill(); + + /** + Stop the thread. Signals the spawned thread that it should stop, so the + thread should check regularly + */ + + void signalQuit(); + + /** + Wait for a thread to stop. Should be called in the context of the spawning + thread. Returns false if the thread has not been started. + */ + + bool waitForQuit(); + + /** + check whether the thread is signalled to quit. Called in the context of the + spawned thread. + */ + + bool quitIsSignalled(); + + /** + Cleanly shut down this thread. Called in the context of the spawned thread. + */ + void quit(); + + /** + Change the affinity mask for this thread. The mask is a platform + specific value. + + On Windows, Linux, and Switch platforms, each set mask bit represents + the index of a logical processor that the OS may schedule thread execution on. + Bits outside the range of valid logical processors may be ignored or cause + the function to return an error. + + On Apple platforms, this function has no effect. + + If the thread has not yet been started then the mask is stored + and applied when the thread is started. + + If the thread has already been started then this method returns the + previous affinity mask on success, otherwise it returns zero. + */ + PxU32 setAffinityMask(PxU32 mask); + + static PxThreadPriority::Enum getPriority(Id threadId); + + /** Set thread priority. */ + void setPriority(PxThreadPriority::Enum prio); + + /** set the thread's name */ + void setName(const char* name); + + /** Put the current thread to sleep for the given number of milliseconds */ + static void sleep(PxU32 ms); + + /** Yield the current thread's slot on the CPU */ + static void yield(); + + /** Inform the processor that we're in a busy wait to give it a chance to do something clever. + yield() yields the thread, while yieldProcessor() aims to yield the processor */ + static void yieldProcessor(); + + /** Return the number of physical cores (does not include hyper-threaded cores), returns 0 on failure */ + static PxU32 getNbPhysicalCores(); + + /** + Size of this class. + */ + static PxU32 getSize(); +}; + +/** +Thread abstraction API +*/ +template > +class PxThreadT : protected Alloc, public PxUserAllocated, public PxRunnable +{ + public: + typedef PxThreadImpl::Id Id; // space for a pointer or an integer + + /** + Construct (but do not start) the thread object. Executes in the context + of the spawning thread + */ + PxThreadT(const Alloc& alloc = Alloc()) : Alloc(alloc) + { + mImpl = reinterpret_cast(Alloc::allocate(PxThreadImpl::getSize(), PX_FL)); + PX_PLACEMENT_NEW(mImpl, PxThreadImpl)(); + } + + /** + Construct and start the the thread, passing the given arg to the given fn. (pthread style) + */ + PxThreadT(PxThreadImpl::ExecuteFn fn, void* arg, const char* name, const Alloc& alloc = Alloc()) : Alloc(alloc) + { + mImpl = reinterpret_cast(Alloc::allocate(PxThreadImpl::getSize(), PX_FL)); + PX_PLACEMENT_NEW(mImpl, PxThreadImpl)(fn, arg, name); + } + + /** + Deallocate all resources associated with the thread. Should be called in the + context of the spawning thread. + */ + virtual ~PxThreadT() + { + mImpl->~PxThreadImpl(); + Alloc::deallocate(mImpl); + } + + /** + start the thread running. Called in the context of the spawning thread. + */ + + void start(PxU32 stackSize = PxThreadImpl::getDefaultStackSize()) + { + mImpl->start(stackSize, this); + } + + /** + Violently kill the current thread. Blunt instrument, not recommended since + it can leave all kinds of things unreleased (stack, memory, mutexes...) Should + be called in the context of the spawning thread. + */ + + void kill() + { + mImpl->kill(); + } + + /** + The virtual execute() method is the user defined function that will + run in the new thread. Called in the context of the spawned thread. + */ + + virtual void execute() + { + } + + /** + stop the thread. Signals the spawned thread that it should stop, so the + thread should check regularly + */ + + void signalQuit() + { + mImpl->signalQuit(); + } + + /** + Wait for a thread to stop. Should be called in the context of the spawning + thread. Returns false if the thread has not been started. + */ + + bool waitForQuit() + { + return mImpl->waitForQuit(); + } + + /** + check whether the thread is signalled to quit. Called in the context of the + spawned thread. + */ + + bool quitIsSignalled() + { + return mImpl->quitIsSignalled(); + } + + /** + Cleanly shut down this thread. Called in the context of the spawned thread. + */ + void quit() + { + mImpl->quit(); + } + + PxU32 setAffinityMask(PxU32 mask) + { + return mImpl->setAffinityMask(mask); + } + + static PxThreadPriority::Enum getPriority(PxThreadImpl::Id threadId) + { + return PxThreadImpl::getPriority(threadId); + } + + /** Set thread priority. */ + void setPriority(PxThreadPriority::Enum prio) + { + mImpl->setPriority(prio); + } + + /** set the thread's name */ + void setName(const char* name) + { + mImpl->setName(name); + } + + /** Put the current thread to sleep for the given number of milliseconds */ + static void sleep(PxU32 ms) + { + PxThreadImpl::sleep(ms); + } + + /** Yield the current thread's slot on the CPU */ + static void yield() + { + PxThreadImpl::yield(); + } + + /** Inform the processor that we're in a busy wait to give it a chance to do something clever + yield() yields the thread, while yieldProcessor() aims to yield the processor */ + static void yieldProcesor() + { + PxThreadImpl::yieldProcessor(); + } + + static PxU32 getDefaultStackSize() + { + return PxThreadImpl::getDefaultStackSize(); + } + + static PxThreadImpl::Id getId() + { + return PxThreadImpl::getId(); + } + + static PxU32 getNbPhysicalCores() + { + return PxThreadImpl::getNbPhysicalCores(); + } + + private: + class PxThreadImpl* mImpl; +}; + +typedef PxThreadT<> PxThread; + +PX_FOUNDATION_API PxU32 PxTlsAlloc(); +PX_FOUNDATION_API void PxTlsFree(PxU32 index); +PX_FOUNDATION_API void* PxTlsGet(PxU32 index); +PX_FOUNDATION_API size_t PxTlsGetValue(PxU32 index); +PX_FOUNDATION_API PxU32 PxTlsSet(PxU32 index, void* value); +PX_FOUNDATION_API PxU32 PxTlsSetValue(PxU32 index, size_t value); + + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTime.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTime.h new file mode 100644 index 000000000..7a94a4e7d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTime.h @@ -0,0 +1,97 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TIME_H +#define PX_TIME_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxFoundationConfig.h" + +#if PX_LINUX +#include +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxCounterFrequencyToTensOfNanos +{ + PxU64 mNumerator; + PxU64 mDenominator; + PxCounterFrequencyToTensOfNanos(PxU64 inNum, PxU64 inDenom) : mNumerator(inNum), mDenominator(inDenom) + { + } + + // quite slow. + PxU64 toTensOfNanos(PxU64 inCounter) const + { + return (inCounter * mNumerator) / mDenominator; + } +}; + +class PX_FOUNDATION_API PxTime +{ + public: + typedef PxF64 Second; + static const PxU64 sNumTensOfNanoSecondsInASecond = 100000000; + // This is supposedly guaranteed to not change after system boot + // regardless of processors, speedstep, etc. + static const PxCounterFrequencyToTensOfNanos& getBootCounterFrequency(); + + static PxCounterFrequencyToTensOfNanos getCounterFrequency(); + + static PxU64 getCurrentCounterValue(); + + // SLOW!! + // Thar be a 64 bit divide in thar! + static PxU64 getCurrentTimeInTensOfNanoSeconds() + { + PxU64 ticks = getCurrentCounterValue(); + return getBootCounterFrequency().toTensOfNanos(ticks); + } + + PxTime(); + Second getElapsedSeconds(); + Second peekElapsedSeconds(); + Second getLastTime() const; + + private: +#if PX_LINUX || PX_APPLE_FAMILY + Second mLastTime; +#else + PxI64 mTickCount; +#endif +}; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTransform.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTransform.h new file mode 100644 index 000000000..3abc05ed3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxTransform.h @@ -0,0 +1,261 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TRANSFORM_H +#define PX_TRANSFORM_H + +#include "foundation/PxQuat.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + +template class PxMat44T; + +/*! +\brief class representing a rigid euclidean transform as a quaternion and a vector +*/ + +template +class PxTransformT +{ + public: + PxQuatT q; + PxVec3T p; + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT() + { + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransformT(PxIDENTITY) : q(PxIdentity), p(PxZero) + { + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransformT(const PxVec3T& position) : q(PxIdentity), p(position) + { + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransformT(const PxQuatT& orientation) : q(orientation), p(Type(0)) + { + PX_ASSERT(orientation.isSane()); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT(Type x, Type y, Type z, PxQuatT aQ = PxQuatT(PxIdentity)) : q(aQ), p(x, y, z) + { + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT(const PxVec3T& p0, const PxQuatT& q0) : q(q0), p(p0) + { + PX_ASSERT(q0.isSane()); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransformT(const PxMat44T& m); // defined in PxMat44.h + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT(const PxTransformT& other) + { + p = other.p; + q = other.q; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE void operator=(const PxTransformT& other) + { + p = other.p; + q = other.q; + } + + /** + \brief returns true if the two transforms are exactly equal + */ + PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxTransformT& t) const + { + return p == t.p && q == t.q; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT operator*(const PxTransformT& x) const + { + PX_ASSERT(x.isSane()); + return transform(x); + } + + //! Equals matrix multiplication + PX_CUDA_CALLABLE PX_INLINE PxTransformT& operator*=(const PxTransformT& other) + { + *this = *this * other; + return *this; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT getInverse() const + { + PX_ASSERT(isFinite()); + return PxTransformT(q.rotateInv(-p), q.getConjugate()); + } + + /** + \brief return a normalized transform (i.e. one in which the quaternion has unit magnitude) + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT getNormalized() const + { + return PxTransformT(p, q.getNormalized()); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T transform(const PxVec3T& input) const + { + PX_ASSERT(isFinite()); + return q.rotate(input) + p; + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T transformInv(const PxVec3T& input) const + { + PX_ASSERT(isFinite()); + return q.rotateInv(input - p); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T rotate(const PxVec3T& input) const + { + PX_ASSERT(isFinite()); + return q.rotate(input); + } + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T rotateInv(const PxVec3T& input) const + { + PX_ASSERT(isFinite()); + return q.rotateInv(input); + } + + //! Transform transform to parent (returns compound transform: first src, then *this) + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT transform(const PxTransformT& src) const + { + PX_ASSERT(src.isSane()); + PX_ASSERT(isSane()); + // src = [srct, srcr] -> [r*srct + t, r*srcr] + return PxTransformT(q.rotate(src.p) + p, q * src.q); + } + + //! Transform transform from parent (returns compound transform: first src, then this->inverse) + PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransformT transformInv(const PxTransformT& src) const + { + PX_ASSERT(src.isSane()); + PX_ASSERT(isFinite()); + // src = [srct, srcr] -> [r^-1*(srct-t), r^-1*srcr] + const PxQuatT qinv = q.getConjugate(); + return PxTransformT(qinv.rotate(src.p - p), qinv * src.q); + } + + /** + \brief returns true if finite and q is a unit quaternion + */ + PX_CUDA_CALLABLE bool isValid() const + { + return p.isFinite() && q.isFinite() && q.isUnit(); + } + + /** + \brief returns true if finite and quat magnitude is reasonably close to unit to allow for some accumulation of error + vs isValid + */ + PX_CUDA_CALLABLE bool isSane() const + { + return isFinite() && q.isSane(); + } + + /** + \brief returns true if all elems are finite (not NAN or INF, etc.) + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite() const + { + return p.isFinite() && q.isFinite(); + } +}; + +typedef PxTransformT PxTransform; +typedef PxTransformT PxTransformd; + +/*! +\brief A generic padded & aligned transform class. + +This can be used for safe faster loads & stores, and faster address computations +(the default PxTransformT often generating imuls for this otherwise). Padding bytes +can be reused to store useful data if needed. +*/ +struct PX_ALIGN_PREFIX(16) PxTransformPadded : PxTransform +{ + PX_FORCE_INLINE PxTransformPadded() + { + } + + PX_FORCE_INLINE PxTransformPadded(const PxTransformPadded& other) : PxTransform(other) + { + } + + PX_FORCE_INLINE explicit PxTransformPadded(const PxTransform& other) : PxTransform(other) + { + } + + PX_FORCE_INLINE explicit PxTransformPadded(PxIDENTITY) : PxTransform(PxIdentity) + { + } + + PX_FORCE_INLINE explicit PxTransformPadded(const PxVec3& position) : PxTransform(position) + { + } + + PX_FORCE_INLINE explicit PxTransformPadded(const PxQuat& orientation) : PxTransform(orientation) + { + } + + PX_FORCE_INLINE PxTransformPadded(const PxVec3& p0, const PxQuat& q0) : PxTransform(p0, q0) + { + } + + PX_FORCE_INLINE void operator=(const PxTransformPadded& other) + { + p = other.p; + q = other.q; + } + + PX_FORCE_INLINE void operator=(const PxTransform& other) + { + p = other.p; + q = other.q; + } + + PxU32 padding; +} +PX_ALIGN_SUFFIX(16); +PX_COMPILE_TIME_ASSERT(sizeof(PxTransformPadded)==32); + +typedef PxTransformPadded PxTransform32; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUnionCast.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUnionCast.h new file mode 100644 index 000000000..50d041fd1 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUnionCast.h @@ -0,0 +1,69 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_UNION_CAST_H +#define PX_UNION_CAST_H + +#include "foundation/PxPreprocessor.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +// Needed for clang 7 +#if PX_CLANG && PX_CLANG_MAJOR >= 7 + #define USE_VOLATILE_UNION volatile +#else + #define USE_VOLATILE_UNION +#endif + +template +PX_FORCE_INLINE A PxUnionCast(B b) +{ + union AB + { + AB(B bb) : _b(bb) + { + } + B _b; + A _a; + } USE_VOLATILE_UNION u(b); + return u._a; +} + +#undef USE_VOLATILE_UNION + +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUserAllocated.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUserAllocated.h new file mode 100644 index 000000000..41e416b9f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUserAllocated.h @@ -0,0 +1,116 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_USER_ALLOCATED_H +#define PX_USER_ALLOCATED_H + +#include "PxAllocator.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + /** + Provides new and delete using a UserAllocator. + Guarantees that 'delete x;' uses the UserAllocator too. + */ + class PxUserAllocated + { + public: + // PX_SERIALIZATION + PX_INLINE void* operator new(size_t, void* address) + { + return address; + } + + //~PX_SERIALIZATION + // Matching operator delete to the above operator new. Don't ask me + // how this makes any sense - Nuernberger. + PX_INLINE void operator delete(void*, void*) + { + } + + template + PX_INLINE void* operator new(size_t size, Alloc alloc, const char* fileName, int line) + { + return alloc.allocate(size, fileName, line); + } + + template + PX_INLINE void* operator new(size_t size, size_t /*align*/, Alloc alloc, const char* fileName, int line) + { + // align is not respected, we have 16bit aligned allocator + return alloc.allocate(size, fileName, line); + } + + template + PX_INLINE void* operator new [](size_t size, Alloc alloc, const char* fileName, int line) + { + return alloc.allocate(size, fileName, line); + } + + template + PX_INLINE void* operator new [](size_t size, size_t /*align*/, Alloc alloc, const char* fileName, int line) + { + // align is not respected, we have 16bit aligned allocator + return alloc.allocate(size, fileName, line); + } + + // placement delete + template + PX_INLINE void operator delete(void* ptr, Alloc alloc, const char* fileName, int line) + { + PX_UNUSED(fileName); + PX_UNUSED(line); + alloc.deallocate(ptr); + } + + template + PX_INLINE void operator delete [](void* ptr, Alloc alloc, const char* fileName, int line) + { + PX_UNUSED(fileName); + PX_UNUSED(line); + alloc.deallocate(ptr); + } + + PX_INLINE void operator delete(void* ptr) + { + PxAllocator().deallocate(ptr); + } + + PX_INLINE void operator delete [](void* ptr) + { + PxAllocator().deallocate(ptr); + } + }; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUtilities.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUtilities.h new file mode 100644 index 000000000..5d3d7f1e8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxUtilities.h @@ -0,0 +1,151 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_UTILITIES_H +#define PX_UTILITIES_H + +#include "foundation/PxVec3.h" +#include "foundation/PxAssert.h" +#include "foundation/PxIntrinsics.h" +#include "foundation/PxBasicTemplates.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +PX_INLINE char PxLittleEndian() +{ + int i = 1; + return *(reinterpret_cast(&i)); +} + +// PT: checked casts +PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 PxTo32(PxU64 value) +{ + PX_ASSERT(value <= 0xffffffff); + return PxU32(value); +} +PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 PxToU32(PxI32 value) +{ + PX_ASSERT(value >= 0); + return PxU32(value); +} +PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 PxTo16(PxU32 value) +{ + PX_ASSERT(value <= 0xffff); + return PxU16(value); +} +PX_CUDA_CALLABLE PX_FORCE_INLINE PxU8 PxTo8(PxU16 value) +{ + PX_ASSERT(value <= 0xff); + return PxU8(value); +} +PX_CUDA_CALLABLE PX_FORCE_INLINE PxU8 PxTo8(PxU32 value) +{ + PX_ASSERT(value <= 0xff); + return PxU8(value); +} +PX_CUDA_CALLABLE PX_FORCE_INLINE PxU8 PxTo8(PxI32 value) +{ + PX_ASSERT(value <= 0xff); + PX_ASSERT(value >= 0); + return PxU8(value); +} +PX_CUDA_CALLABLE PX_FORCE_INLINE PxI8 PxToI8(PxU32 value) +{ + PX_ASSERT(value <= 0x7f); + return PxI8(value); +} + +//! \cond +/*! +Get number of elements in array +*/ +template +char (&PxArraySizeHelper(T (&array)[N]))[N]; +#define PX_ARRAY_SIZE(_array) (sizeof(physx::PxArraySizeHelper(_array))) +//! \endcond + +/*! +Sort two elements using operator< + +On return x will be the smaller of the two +*/ +template +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxOrder(T& x, T& y) +{ + if(y < x) + PxSwap(x, y); +} + +// most architectures can do predication on real comparisons, and on VMX, it matters + +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxOrder(PxReal& x, PxReal& y) +{ + PxReal newX = PxMin(x, y); + PxReal newY = PxMax(x, y); + x = newX; + y = newY; +} + +/*! +Sort two elements using operator< and also keep order +of any extra data +*/ +template +PX_CUDA_CALLABLE PX_FORCE_INLINE void PxOrder(T& x, T& y, E1& xe1, E1& ye1) +{ + if(y < x) + { + swap(x, y); + swap(xe1, ye1); + } +} + +#if PX_GCC_FAMILY && !PX_EMSCRIPTEN +__attribute__((noreturn)) +#endif + PX_INLINE void PxDebugBreak() +{ +#if PX_WINDOWS + __debugbreak(); +#elif PX_LINUX + __builtin_trap(); +#elif PX_GCC_FAMILY + __builtin_trap(); +#else + PX_ASSERT(false); +#endif +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec2.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec2.h new file mode 100644 index 000000000..e7185fb79 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec2.h @@ -0,0 +1,347 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC2_H +#define PX_VEC2_H + + +#include "foundation/PxMath.h" +#include "foundation/PxConstructor.h" + + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief 2 Element vector class. + +This is a 2-dimensional vector class with public data members. +*/ +template +class PxVec2T +{ + public: + /** + \brief default constructor leaves data uninitialized. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T() + { + } + + /** + \brief zero constructor. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T(PxZERO) : x(Type(0.0)), y(Type(0.0)) + { + } + + /** + \brief Assigns scalar parameter to all elements. + + Useful to initialize to zero or one. + + \param[in] a Value to assign to elements. + */ + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T(Type a) : x(a), y(a) + { + } + + /** + \brief Initializes from 2 scalar parameters. + + \param[in] nx Value to initialize X component. + \param[in] ny Value to initialize Y component. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T(Type nx, Type ny) : x(nx), y(ny) + { + } + + /** + \brief Copy ctor. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T(const PxVec2T& v) : x(v.x), y(v.y) + { + } + + // Operators + + /** + \brief Assignment operator + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T& operator=(const PxVec2T& p) + { + x = p.x; + y = p.y; + return *this; + } + + /** + \brief element access + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type& operator[](unsigned int index) + { + PX_ASSERT(index <= 1); + return reinterpret_cast(this)[index]; + } + + /** + \brief element access + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const Type& operator[](unsigned int index) const + { + PX_ASSERT(index <= 1); + return reinterpret_cast(this)[index]; + } + + /** + \brief returns true if the two vectors are exactly equal. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator==(const PxVec2T& v) const + { + return x == v.x && y == v.y; + } + + /** + \brief returns true if the two vectors are not exactly equal. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator!=(const PxVec2T& v) const + { + return x != v.x || y != v.y; + } + + /** + \brief tests for exact zero vector + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isZero() const + { + return x == Type(0.0) && y == Type(0.0); + } + + /** + \brief returns true if all 2 elems of the vector are finite (not NAN or INF, etc.) + */ + PX_CUDA_CALLABLE PX_INLINE bool isFinite() const + { + return PxIsFinite(x) && PxIsFinite(y); + } + + /** + \brief is normalized - used by API parameter validation + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isNormalized() const + { + const Type unitTolerance = Type(1e-4); + return isFinite() && PxAbs(magnitude() - Type(1.0)) < unitTolerance; + } + + /** + \brief returns the squared magnitude + + Avoids calling PxSqrt()! + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type magnitudeSquared() const + { + return x * x + y * y; + } + + /** + \brief returns the magnitude + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type magnitude() const + { + return PxSqrt(magnitudeSquared()); + } + + /** + \brief negation + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T operator-() const + { + return PxVec2T(-x, -y); + } + + /** + \brief vector addition + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T operator+(const PxVec2T& v) const + { + return PxVec2T(x + v.x, y + v.y); + } + + /** + \brief vector difference + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T operator-(const PxVec2T& v) const + { + return PxVec2T(x - v.x, y - v.y); + } + + /** + \brief scalar post-multiplication + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T operator*(Type f) const + { + return PxVec2T(x * f, y * f); + } + + /** + \brief scalar division + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T operator/(Type f) const + { + f = Type(1.0) / f; + return PxVec2T(x * f, y * f); + } + + /** + \brief vector addition + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T& operator+=(const PxVec2T& v) + { + x += v.x; + y += v.y; + return *this; + } + + /** + \brief vector difference + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T& operator-=(const PxVec2T& v) + { + x -= v.x; + y -= v.y; + return *this; + } + + /** + \brief scalar multiplication + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T& operator*=(Type f) + { + x *= f; + y *= f; + return *this; + } + + /** + \brief scalar division + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T& operator/=(Type f) + { + f = Type(1.0) / f; + x *= f; + y *= f; + return *this; + } + + /** + \brief returns the scalar product of this and other. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type dot(const PxVec2T& v) const + { + return x * v.x + y * v.y; + } + + /** returns a unit vector */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T getNormalized() const + { + const Type m = magnitudeSquared(); + return m > Type(0.0) ? *this * PxRecipSqrt(m) : PxVec2T(Type(0)); + } + + /** + \brief normalizes the vector in place + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type normalize() + { + const Type m = magnitude(); + if(m > Type(0.0)) + *this /= m; + return m; + } + + /** + \brief a[i] * b[i], for all i. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T multiply(const PxVec2T& a) const + { + return PxVec2T(x * a.x, y * a.y); + } + + /** + \brief element-wise minimum + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T minimum(const PxVec2T& v) const + { + return PxVec2T(PxMin(x, v.x), PxMin(y, v.y)); + } + + /** + \brief returns MIN(x, y); + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type minElement() const + { + return PxMin(x, y); + } + + /** + \brief element-wise maximum + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2T maximum(const PxVec2T& v) const + { + return PxVec2T(PxMax(x, v.x), PxMax(y, v.y)); + } + + /** + \brief returns MAX(x, y); + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type maxElement() const + { + return PxMax(x, y); + } + + Type x, y; +}; + +template +PX_CUDA_CALLABLE static PX_FORCE_INLINE PxVec2T operator*(Type f, const PxVec2T& v) +{ + return PxVec2T(f * v.x, f * v.y); +} + +typedef PxVec2T PxVec2; +typedef PxVec2T PxVec2d; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec3.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec3.h new file mode 100644 index 000000000..ef2abad35 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec3.h @@ -0,0 +1,420 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC3_H +#define PX_VEC3_H + + +#include "foundation/PxMath.h" +#include "foundation/PxConstructor.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief 3 Element vector class. + +This is a 3-dimensional vector class with public data members. +*/ +template +class PxVec3T +{ + public: + + /** + \brief default constructor leaves data uninitialized. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T() + { + } + + /** + \brief zero constructor. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T(PxZERO) : x(Type(0.0)), y(Type(0.0)), z(Type(0.0)) + { + } + + /** + \brief Assigns scalar parameter to all elements. + + Useful to initialize to zero or one. + + \param[in] a Value to assign to elements. + */ + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T(Type a) : x(a), y(a), z(a) + { + } + + /** + \brief Initializes from 3 scalar parameters. + + \param[in] nx Value to initialize X component. + \param[in] ny Value to initialize Y component. + \param[in] nz Value to initialize Z component. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T(Type nx, Type ny, Type nz) : x(nx), y(ny), z(nz) + { + } + + /** + \brief Copy ctor. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T(const PxVec3T& v) : x(v.x), y(v.y), z(v.z) + { + } + + // Operators + + /** + \brief Assignment operator + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T& operator=(const PxVec3T& p) + { + x = p.x; + y = p.y; + z = p.z; + return *this; + } + + /** + \brief element access + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type& operator[](unsigned int index) + { + PX_ASSERT(index <= 2); + return reinterpret_cast(this)[index]; + } + + /** + \brief element access + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE const Type& operator[](unsigned int index) const + { + PX_ASSERT(index <= 2); + return reinterpret_cast(this)[index]; + } + + /** + \brief returns true if the two vectors are exactly equal. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator==(const PxVec3T& v) const + { + return x == v.x && y == v.y && z == v.z; + } + + /** + \brief returns true if the two vectors are not exactly equal. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator!=(const PxVec3T& v) const + { + return x != v.x || y != v.y || z != v.z; + } + + /** + \brief tests for exact zero vector + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isZero() const + { + return x == Type(0.0) && y == Type(0.0) && z == Type(0.0); + } + + /** + \brief returns true if all 3 elems of the vector are finite (not NAN or INF, etc.) + */ + PX_CUDA_CALLABLE PX_INLINE bool isFinite() const + { + return PxIsFinite(x) && PxIsFinite(y) && PxIsFinite(z); + } + + /** + \brief is normalized - used by API parameter validation + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isNormalized() const + { + const float unitTolerance = Type(1e-4); // PT: do we need a different epsilon for float & double? + return isFinite() && PxAbs(magnitude() - Type(1.0)) < unitTolerance; + } + + /** + \brief returns the squared magnitude + + Avoids calling PxSqrt()! + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type magnitudeSquared() const + { + return x * x + y * y + z * z; + } + + /** + \brief returns the magnitude + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type magnitude() const + { + return PxSqrt(magnitudeSquared()); + } + + /** + \brief negation + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T operator-() const + { + return PxVec3T(-x, -y, -z); + } + + /** + \brief vector addition + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T operator+(const PxVec3T& v) const + { + return PxVec3T(x + v.x, y + v.y, z + v.z); + } + + /** + \brief vector difference + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T operator-(const PxVec3T& v) const + { + return PxVec3T(x - v.x, y - v.y, z - v.z); + } + + /** + \brief scalar post-multiplication + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T operator*(Type f) const + { + return PxVec3T(x * f, y * f, z * f); + } + + /** + \brief scalar division + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T operator/(Type f) const + { + f = Type(1.0) / f; + return PxVec3T(x * f, y * f, z * f); + } + + /** + \brief vector addition + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T& operator+=(const PxVec3T& v) + { + x += v.x; + y += v.y; + z += v.z; + return *this; + } + + /** + \brief vector difference + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T& operator-=(const PxVec3T& v) + { + x -= v.x; + y -= v.y; + z -= v.z; + return *this; + } + + /** + \brief scalar multiplication + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T& operator*=(Type f) + { + x *= f; + y *= f; + z *= f; + return *this; + } + /** + \brief scalar division + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T& operator/=(Type f) + { + f = Type(1.0) / f; + x *= f; + y *= f; + z *= f; + return *this; + } + + /** + \brief returns the scalar product of this and other. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type dot(const PxVec3T& v) const + { + return x * v.x + y * v.y + z * v.z; + } + + /** + \brief cross product + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T cross(const PxVec3T& v) const + { + return PxVec3T(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); + } + + /** returns a unit vector */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T getNormalized() const + { + const Type m = magnitudeSquared(); + return m > Type(0.0) ? *this * PxRecipSqrt(m) : PxVec3T(Type(0)); + } + + /** + \brief normalizes the vector in place + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type normalize() + { + const Type m = magnitude(); + if(m > Type(0.0)) + *this /= m; + return m; + } + + /** + \brief normalizes the vector in place. Does nothing if vector magnitude is under PX_NORMALIZATION_EPSILON. + Returns vector magnitude if >= PX_NORMALIZATION_EPSILON and 0.0f otherwise. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type normalizeSafe() + { + const Type mag = magnitude(); + if(mag < PX_NORMALIZATION_EPSILON) // PT: do we need a different epsilon for float & double? + return Type(0.0); + *this *= Type(1.0) / mag; + return mag; + } + + /** + \brief normalizes the vector in place. Asserts if vector magnitude is under PX_NORMALIZATION_EPSILON. + returns vector magnitude. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type normalizeFast() + { + const Type mag = magnitude(); + PX_ASSERT(mag >= PX_NORMALIZATION_EPSILON); // PT: do we need a different epsilon for float & double? + *this *= Type(1.0) / mag; + return mag; + } + + /** + \brief a[i] * b[i], for all i. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T multiply(const PxVec3T& a) const + { + return PxVec3T(x * a.x, y * a.y, z * a.z); + } + + /** + \brief element-wise minimum + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T minimum(const PxVec3T& v) const + { + return PxVec3T(PxMin(x, v.x), PxMin(y, v.y), PxMin(z, v.z)); + } + + /** + \brief returns MIN(x, y, z); + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type minElement() const + { + return PxMin(x, PxMin(y, z)); + } + + /** + \brief element-wise maximum + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T maximum(const PxVec3T& v) const + { + return PxVec3T(PxMax(x, v.x), PxMax(y, v.y), PxMax(z, v.z)); + } + + /** + \brief returns MAX(x, y, z); + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE Type maxElement() const + { + return PxMax(x, PxMax(y, z)); + } + + /** + \brief returns absolute values of components; + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3T abs() const + { + return PxVec3T(PxAbs(x), PxAbs(y), PxAbs(z)); + } + + Type x, y, z; +}; + +template +PX_CUDA_CALLABLE static PX_FORCE_INLINE PxVec3T operator*(Type f, const PxVec3T& v) +{ + return PxVec3T(f * v.x, f * v.y, f * v.z); +} + +typedef PxVec3T PxVec3; +typedef PxVec3T PxVec3d; + +//! A padded version of PxVec3, to safely load its data using SIMD +class PxVec3Padded : public PxVec3 +{ + public: + PX_FORCE_INLINE PxVec3Padded() {} + PX_FORCE_INLINE ~PxVec3Padded() {} + PX_FORCE_INLINE PxVec3Padded(const PxVec3& p) : PxVec3(p) {} + PX_FORCE_INLINE PxVec3Padded(float f) : PxVec3(f) {} + + /** + \brief Assignment operator. + To fix this: + error: definition of implicit copy assignment operator for 'PxVec3Padded' is deprecated because it has a user-declared destructor [-Werror,-Wdeprecated] + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3Padded& operator=(const PxVec3Padded& p) + { + x = p.x; + y = p.y; + z = p.z; + return *this; + } + + PxU32 padding; +}; +PX_COMPILE_TIME_ASSERT(sizeof(PxVec3Padded) == 16); + +typedef PxVec3Padded PxVec3p; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec4.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec4.h new file mode 100644 index 000000000..4c26a735b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVec4.h @@ -0,0 +1,364 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC4_H +#define PX_VEC4_H + +#include "foundation/PxMath.h" +#include "foundation/PxVec3.h" + +/** +\brief 4 Element vector class. + +This is a 4-dimensional vector class with public data members. +*/ +#if !PX_DOXYGEN +namespace physx +{ +#endif + +template +class PxVec4T +{ + public: + /** + \brief default constructor leaves data uninitialized. + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T() + { + } + + /** + \brief zero constructor. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4T(PxZERO) : x(Type(0.0)), y(Type(0.0)), z(Type(0.0)), w(Type(0.0)) + { + } + + /** + \brief Assigns scalar parameter to all elements. + + Useful to initialize to zero or one. + + \param[in] a Value to assign to elements. + */ + explicit PX_CUDA_CALLABLE PX_INLINE PxVec4T(Type a) : x(a), y(a), z(a), w(a) + { + } + + /** + \brief Initializes from 3 scalar parameters. + + \param[in] nx Value to initialize X component. + \param[in] ny Value to initialize Y component. + \param[in] nz Value to initialize Z component. + \param[in] nw Value to initialize W component. + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T(Type nx, Type ny, Type nz, Type nw) : x(nx), y(ny), z(nz), w(nw) + { + } + + /** + \brief Initializes from 3 scalar parameters. + + \param[in] v Value to initialize the X, Y, and Z components. + \param[in] nw Value to initialize W component. + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T(const PxVec3T& v, Type nw) : x(v.x), y(v.y), z(v.z), w(nw) + { + } + + /** + \brief Initializes from an array of scalar parameters. + + \param[in] v Value to initialize with. + */ + explicit PX_CUDA_CALLABLE PX_INLINE PxVec4T(const Type v[]) : x(v[0]), y(v[1]), z(v[2]), w(v[3]) + { + } + + /** + \brief Copy ctor. + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T(const PxVec4T& v) : x(v.x), y(v.y), z(v.z), w(v.w) + { + } + + // Operators + + /** + \brief Assignment operator + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T& operator=(const PxVec4T& p) + { + x = p.x; + y = p.y; + z = p.z; + w = p.w; + return *this; + } + + /** + \brief element access + */ + PX_CUDA_CALLABLE PX_INLINE Type& operator[](unsigned int index) + { + PX_ASSERT(index <= 3); + return reinterpret_cast(this)[index]; + } + + /** + \brief element access + */ + PX_CUDA_CALLABLE PX_INLINE const Type& operator[](unsigned int index) const + { + PX_ASSERT(index <= 3); + return reinterpret_cast(this)[index]; + } + + /** + \brief returns true if the two vectors are exactly equal. + */ + PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxVec4T& v) const + { + return x == v.x && y == v.y && z == v.z && w == v.w; + } + + /** + \brief returns true if the two vectors are not exactly equal. + */ + PX_CUDA_CALLABLE PX_INLINE bool operator!=(const PxVec4T& v) const + { + return x != v.x || y != v.y || z != v.z || w != v.w; + } + + /** + \brief tests for exact zero vector + */ + PX_CUDA_CALLABLE PX_INLINE bool isZero() const + { + return x == Type(0) && y == Type(0) && z == Type(0) && w == Type(0); + } + + /** + \brief returns true if all 3 elems of the vector are finite (not NAN or INF, etc.) + */ + PX_CUDA_CALLABLE PX_INLINE bool isFinite() const + { + return PxIsFinite(x) && PxIsFinite(y) && PxIsFinite(z) && PxIsFinite(w); + } + + /** + \brief is normalized - used by API parameter validation + */ + PX_CUDA_CALLABLE PX_INLINE bool isNormalized() const + { + const Type unitTolerance = Type(1e-4); + return isFinite() && PxAbs(magnitude() - Type(1.0)) < unitTolerance; + } + + /** + \brief returns the squared magnitude + + Avoids calling PxSqrt()! + */ + PX_CUDA_CALLABLE PX_INLINE Type magnitudeSquared() const + { + return x * x + y * y + z * z + w * w; + } + + /** + \brief returns the magnitude + */ + PX_CUDA_CALLABLE PX_INLINE Type magnitude() const + { + return PxSqrt(magnitudeSquared()); + } + + /** + \brief negation + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T operator-() const + { + return PxVec4T(-x, -y, -z, -w); + } + + /** + \brief vector addition + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T operator+(const PxVec4T& v) const + { + return PxVec4T(x + v.x, y + v.y, z + v.z, w + v.w); + } + + /** + \brief vector difference + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T operator-(const PxVec4T& v) const + { + return PxVec4T(x - v.x, y - v.y, z - v.z, w - v.w); + } + + /** + \brief scalar post-multiplication + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T operator*(Type f) const + { + return PxVec4T(x * f, y * f, z * f, w * f); + } + + /** + \brief scalar division + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T operator/(Type f) const + { + f = Type(1.0) / f; + return PxVec4T(x * f, y * f, z * f, w * f); + } + + /** + \brief vector addition + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T& operator+=(const PxVec4T& v) + { + x += v.x; + y += v.y; + z += v.z; + w += v.w; + return *this; + } + + /** + \brief vector difference + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T& operator-=(const PxVec4T& v) + { + x -= v.x; + y -= v.y; + z -= v.z; + w -= v.w; + return *this; + } + + /** + \brief scalar multiplication + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T& operator*=(Type f) + { + x *= f; + y *= f; + z *= f; + w *= f; + return *this; + } + /** + \brief scalar division + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T& operator/=(Type f) + { + f = Type(1.0) / f; + x *= f; + y *= f; + z *= f; + w *= f; + return *this; + } + + /** + \brief returns the scalar product of this and other. + */ + PX_CUDA_CALLABLE PX_INLINE Type dot(const PxVec4T& v) const + { + return x * v.x + y * v.y + z * v.z + w * v.w; + } + + /** returns a unit vector */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T getNormalized() const + { + const Type m = magnitudeSquared(); + return m > Type(0.0) ? *this * PxRecipSqrt(m) : PxVec4T(Type(0)); + } + + /** + \brief normalizes the vector in place + */ + PX_CUDA_CALLABLE PX_INLINE Type normalize() + { + const Type m = magnitude(); + if(m > Type(0.0)) + *this /= m; + return m; + } + + /** + \brief a[i] * b[i], for all i. + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T multiply(const PxVec4T& a) const + { + return PxVec4T(x * a.x, y * a.y, z * a.z, w * a.w); + } + + /** + \brief element-wise minimum + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T minimum(const PxVec4T& v) const + { + return PxVec4T(PxMin(x, v.x), PxMin(y, v.y), PxMin(z, v.z), PxMin(w, v.w)); + } + + /** + \brief element-wise maximum + */ + PX_CUDA_CALLABLE PX_INLINE PxVec4T maximum(const PxVec4T& v) const + { + return PxVec4T(PxMax(x, v.x), PxMax(y, v.y), PxMax(z, v.z), PxMax(w, v.w)); + } + + PX_CUDA_CALLABLE PX_INLINE PxVec3T getXYZ() const + { + return PxVec3T(x, y, z); + } + + Type x, y, z, w; +}; + +template +PX_CUDA_CALLABLE static PX_INLINE PxVec4T operator*(Type f, const PxVec4T& v) +{ + return PxVec4T(f * v.x, f * v.y, f * v.z, f * v.w); +} + +typedef PxVec4T PxVec4; +typedef PxVec4T PxVec4d; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMath.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMath.h new file mode 100644 index 000000000..183cb91b9 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMath.h @@ -0,0 +1,1355 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC_MATH_H +#define PX_VEC_MATH_H + +#include "foundation/PxIntrinsics.h" +#include "foundation/PxVec3.h" +#include "foundation/PxVec4.h" +#include "foundation/PxMat33.h" +#include "foundation/PxUnionCast.h" + +// We can opt to use the scalar version of vectorised functions. +// This can catch type safety issues and might even work out more optimal on pc. +// It will also be useful for benchmarking and testing. +// NEVER submit with vector intrinsics deactivated without good reason. +// AM: deactivating SIMD for debug win64 just so autobuild will also exercise +// non-SIMD path, until a dedicated non-SIMD platform sich as Arm comes online. +// TODO: dima: reference all platforms with SIMD support here, +// all unknown/experimental cases should better default to NO SIMD. + +// enable/disable SIMD +#if !defined(PX_SIMD_DISABLED) +#if PX_INTEL_FAMILY && (!defined(__EMSCRIPTEN__) || defined(__SSE2__)) + #define COMPILE_VECTOR_INTRINSICS 1 +#elif PX_SWITCH + #define COMPILE_VECTOR_INTRINSICS 1 +#else + #define COMPILE_VECTOR_INTRINSICS 0 +#endif +#else + #define COMPILE_VECTOR_INTRINSICS 0 +#endif + +#if COMPILE_VECTOR_INTRINSICS && PX_INTEL_FAMILY && PX_UNIX_FAMILY +// only SSE2 compatible platforms should reach this +#if PX_EMSCRIPTEN + #include +#endif + #include +#endif + +#if COMPILE_VECTOR_INTRINSICS + #include "PxAoS.h" +#else + #include "PxVecMathAoSScalar.h" +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +namespace aos +{ + +// Basic AoS types are +// FloatV - 16-byte aligned representation of float. +// Vec3V - 16-byte aligned representation of PxVec3 stored as (x y z 0). +// Vec4V - 16-byte aligned representation of vector of 4 floats stored as (x y z w). +// BoolV - 16-byte aligned representation of vector of 4 bools stored as (x y z w). +// VecU32V - 16-byte aligned representation of 4 unsigned ints stored as (x y z w). +// VecI32V - 16-byte aligned representation of 4 signed ints stored as (x y z w). +// Mat33V - 16-byte aligned representation of any 3x3 matrix. +// Mat34V - 16-byte aligned representation of transformation matrix (rotation in col1,col2,col3 and translation in +// col4). +// Mat44V - 16-byte aligned representation of any 4x4 matrix. + +////////////////////////////////////////// +// Construct a simd type from a scalar type +////////////////////////////////////////// + +// FloatV +//(f,f,f,f) +PX_FORCE_INLINE FloatV FLoad(const PxF32 f); + +// Vec3V +//(f,f,f,0) +PX_FORCE_INLINE Vec3V V3Load(const PxF32 f); +//(f.x,f.y,f.z,0) +PX_FORCE_INLINE Vec3V V3LoadU(const PxVec3& f); +//(f.x,f.y,f.z,0), f must be 16-byte aligned +PX_FORCE_INLINE Vec3V V3LoadA(const PxVec3& f); +//(f.x,f.y,f.z,w_undefined), f must be 16-byte aligned +PX_FORCE_INLINE Vec3V V3LoadUnsafeA(const PxVec3& f); +//(f.x,f.y,f.z,0) +PX_FORCE_INLINE Vec3V V3LoadU(const PxF32* f); +//(f.x,f.y,f.z,0), f must be 16-byte aligned +PX_FORCE_INLINE Vec3V V3LoadA(const PxF32* f); + +// Vec4V +//(f,f,f,f) +PX_FORCE_INLINE Vec4V V4Load(const PxF32 f); +//(f[0],f[1],f[2],f[3]) +PX_FORCE_INLINE Vec4V V4LoadU(const PxF32* const f); +//(f[0],f[1],f[2],f[3]), f must be 16-byte aligned +PX_FORCE_INLINE Vec4V V4LoadA(const PxF32* const f); +//(x,y,z,w) +PX_FORCE_INLINE Vec4V V4LoadXYZW(const PxF32& x, const PxF32& y, const PxF32& z, const PxF32& w); + +// BoolV +//(f,f,f,f) +PX_FORCE_INLINE BoolV BLoad(const bool f); +//(f[0],f[1],f[2],f[3]) +PX_FORCE_INLINE BoolV BLoad(const bool* const f); + +// VecU32V +//(f,f,f,f) +PX_FORCE_INLINE VecU32V U4Load(const PxU32 f); +//(f[0],f[1],f[2],f[3]) +PX_FORCE_INLINE VecU32V U4LoadU(const PxU32* f); +//(f[0],f[1],f[2],f[3]), f must be 16-byte aligned +PX_FORCE_INLINE VecU32V U4LoadA(const PxU32* f); +//((U32)x, (U32)y, (U32)z, (U32)w) +PX_FORCE_INLINE VecU32V U4LoadXYZW(PxU32 x, PxU32 y, PxU32 z, PxU32 w); + +// VecI32V +//(i,i,i,i) +PX_FORCE_INLINE VecI32V I4Load(const PxI32 i); +//(i,i,i,i) +PX_FORCE_INLINE VecI32V I4LoadU(const PxI32* i); +//(i,i,i,i) +PX_FORCE_INLINE VecI32V I4LoadA(const PxI32* i); + +// QuatV +//(x = v[0], y=v[1], z=v[2], w=v3[3]) and array don't need to aligned +PX_FORCE_INLINE QuatV QuatVLoadU(const PxF32* v); +//(x = v[0], y=v[1], z=v[2], w=v3[3]) and array need to aligned, fast load +PX_FORCE_INLINE QuatV QuatVLoadA(const PxF32* v); +//(x, y, z, w) +PX_FORCE_INLINE QuatV QuatVLoadXYZW(const PxF32 x, const PxF32 y, const PxF32 z, const PxF32 w); + +// not added to public api +Vec4V Vec4V_From_PxVec3_WUndefined(const PxVec3& v); + +/////////////////////////////////////////////////// +// Construct a simd type from a different simd type +/////////////////////////////////////////////////// + +// Vec3V +//(v.x,v.y,v.z,0) +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V(Vec4V v); +//(v.x,v.y,v.z,undefined) - be very careful with w!=0 because many functions require w==0 for correct operation eg V3Dot, V3Length, V3Cross etc etc. +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V_WUndefined(const Vec4V v); + +// Vec4V +//(f.x,f.y,f.z,f.w) +PX_FORCE_INLINE Vec4V Vec4V_From_Vec3V(Vec3V f); +//((PxF32)f.x, (PxF32)f.y, (PxF32)f.z, (PxF32)f.w) +PX_FORCE_INLINE Vec4V Vec4V_From_VecU32V(VecU32V a); +//((PxF32)f.x, (PxF32)f.y, (PxF32)f.z, (PxF32)f.w) +PX_FORCE_INLINE Vec4V Vec4V_From_VecI32V(VecI32V a); +//(*(reinterpret_cast(&f.x), (reinterpret_cast(&f.y), (reinterpret_cast(&f.z), +//(reinterpret_cast(&f.w)) +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecU32V(VecU32V a); +//(*(reinterpret_cast(&f.x), (reinterpret_cast(&f.y), (reinterpret_cast(&f.z), +//(reinterpret_cast(&f.w)) +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecI32V(VecI32V a); + +// VecU32V +//(*(reinterpret_cast(&f.x), (reinterpret_cast(&f.y), (reinterpret_cast(&f.z), +//(reinterpret_cast(&f.w)) +PX_FORCE_INLINE VecU32V VecU32V_ReinterpretFrom_Vec4V(Vec4V a); +//(b[0], b[1], b[2], b[3]) +PX_FORCE_INLINE VecU32V VecU32V_From_BoolV(const BoolVArg b); + +// VecI32V +//(*(reinterpret_cast(&f.x), (reinterpret_cast(&f.y), (reinterpret_cast(&f.z), +//(reinterpret_cast(&f.w)) +PX_FORCE_INLINE VecI32V VecI32V_ReinterpretFrom_Vec4V(Vec4V a); +//((I32)a.x, (I32)a.y, (I32)a.z, (I32)a.w) +PX_FORCE_INLINE VecI32V VecI32V_From_Vec4V(Vec4V a); +//((I32)b.x, (I32)b.y, (I32)b.z, (I32)b.w) +PX_FORCE_INLINE VecI32V VecI32V_From_BoolV(const BoolVArg b); + +/////////////////////////////////////////////////// +// Convert from a simd type back to a scalar type +/////////////////////////////////////////////////// + +// FloatV +// a.x +PX_FORCE_INLINE void FStore(const FloatV a, PxF32* PX_RESTRICT f); + +// Vec3V +//(a.x,a.y,a.z) +PX_FORCE_INLINE void V3StoreA(const Vec3V a, PxVec3& f); +//(a.x,a.y,a.z) +PX_FORCE_INLINE void V3StoreU(const Vec3V a, PxVec3& f); + +// Vec4V +PX_FORCE_INLINE void V4StoreA(const Vec4V a, PxF32* f); +PX_FORCE_INLINE void V4StoreU(const Vec4V a, PxF32* f); + +// BoolV +PX_FORCE_INLINE void BStoreA(const BoolV b, PxU32* f); + +// VecU32V +PX_FORCE_INLINE void U4StoreA(const VecU32V uv, PxU32* u); + +// VecI32V +PX_FORCE_INLINE void I4StoreA(const VecI32V iv, PxI32* i); + +////////////////////////////////////////////////////////////////// +// Test that simd types have elements in the floating point range +////////////////////////////////////////////////////////////////// + +// check for each component is valid ie in floating point range +PX_FORCE_INLINE bool isFiniteFloatV(const FloatV a); +// check for each component is valid ie in floating point range +PX_FORCE_INLINE bool isFiniteVec3V(const Vec3V a); +// check for each component is valid ie in floating point range +PX_FORCE_INLINE bool isFiniteVec4V(const Vec4V a); + +// Check that w-component is zero. +PX_FORCE_INLINE bool isValidVec3V(const Vec3V a); + +////////////////////////////////////////////////////////////////// +// Tests that all elements of two 16-byte types are completely equivalent. +// Use these tests for unit testing and asserts only. +////////////////////////////////////////////////////////////////// + +namespace vecMathTests +{ +PX_FORCE_INLINE Vec3V getInvalidVec3V(); +PX_FORCE_INLINE bool allElementsEqualFloatV(const FloatV a, const FloatV b); +PX_FORCE_INLINE bool allElementsEqualVec3V(const Vec3V a, const Vec3V b); +PX_FORCE_INLINE bool allElementsEqualVec4V(const Vec4V a, const Vec4V b); +PX_FORCE_INLINE bool allElementsEqualBoolV(const BoolV a, const BoolV b); +PX_FORCE_INLINE bool allElementsEqualVecU32V(const VecU32V a, const VecU32V b); +PX_FORCE_INLINE bool allElementsEqualVecI32V(const VecI32V a, const VecI32V b); + +PX_FORCE_INLINE bool allElementsEqualMat33V(const Mat33V& a, const Mat33V& b) +{ + return (allElementsEqualVec3V(a.col0, b.col0) && allElementsEqualVec3V(a.col1, b.col1) && + allElementsEqualVec3V(a.col2, b.col2)); +} +PX_FORCE_INLINE bool allElementsEqualMat34V(const Mat34V& a, const Mat34V& b) +{ + return (allElementsEqualVec3V(a.col0, b.col0) && allElementsEqualVec3V(a.col1, b.col1) && + allElementsEqualVec3V(a.col2, b.col2) && allElementsEqualVec3V(a.col3, b.col3)); +} +PX_FORCE_INLINE bool allElementsEqualMat44V(const Mat44V& a, const Mat44V& b) +{ + return (allElementsEqualVec4V(a.col0, b.col0) && allElementsEqualVec4V(a.col1, b.col1) && + allElementsEqualVec4V(a.col2, b.col2) && allElementsEqualVec4V(a.col3, b.col3)); +} + +PX_FORCE_INLINE bool allElementsNearEqualFloatV(const FloatV a, const FloatV b); +PX_FORCE_INLINE bool allElementsNearEqualVec3V(const Vec3V a, const Vec3V b); +PX_FORCE_INLINE bool allElementsNearEqualVec4V(const Vec4V a, const Vec4V b); +PX_FORCE_INLINE bool allElementsNearEqualMat33V(const Mat33V& a, const Mat33V& b) +{ + return (allElementsNearEqualVec3V(a.col0, b.col0) && allElementsNearEqualVec3V(a.col1, b.col1) && + allElementsNearEqualVec3V(a.col2, b.col2)); +} +PX_FORCE_INLINE bool allElementsNearEqualMat34V(const Mat34V& a, const Mat34V& b) +{ + return (allElementsNearEqualVec3V(a.col0, b.col0) && allElementsNearEqualVec3V(a.col1, b.col1) && + allElementsNearEqualVec3V(a.col2, b.col2) && allElementsNearEqualVec3V(a.col3, b.col3)); +} +PX_FORCE_INLINE bool allElementsNearEqualMat44V(const Mat44V& a, const Mat44V& b) +{ + return (allElementsNearEqualVec4V(a.col0, b.col0) && allElementsNearEqualVec4V(a.col1, b.col1) && + allElementsNearEqualVec4V(a.col2, b.col2) && allElementsNearEqualVec4V(a.col3, b.col3)); +} +} + +////////////////////////////////////////////////////////////////// +// Math operations on FloatV +////////////////////////////////////////////////////////////////// + +//(0,0,0,0) +PX_FORCE_INLINE FloatV FZero(); +//(1,1,1,1) +PX_FORCE_INLINE FloatV FOne(); +//(0.5,0.5,0.5,0.5) +PX_FORCE_INLINE FloatV FHalf(); +//(PX_EPS_REAL,PX_EPS_REAL,PX_EPS_REAL,PX_EPS_REAL) +PX_FORCE_INLINE FloatV FEps(); +//! \cond +//(PX_MAX_REAL, PX_MAX_REAL, PX_MAX_REAL PX_MAX_REAL) +PX_FORCE_INLINE FloatV FMax(); +//! \endcond +//(-PX_MAX_REAL, -PX_MAX_REAL, -PX_MAX_REAL -PX_MAX_REAL) +PX_FORCE_INLINE FloatV FNegMax(); +//(1e-6f, 1e-6f, 1e-6f, 1e-6f) +PX_FORCE_INLINE FloatV FEps6(); +//((PxF32*)&1, (PxF32*)&1, (PxF32*)&1, (PxF32*)&1) + +//-f (per component) +PX_FORCE_INLINE FloatV FNeg(const FloatV f); +// a+b (per component) +PX_FORCE_INLINE FloatV FAdd(const FloatV a, const FloatV b); +// a-b (per component) +PX_FORCE_INLINE FloatV FSub(const FloatV a, const FloatV b); +// a*b (per component) +PX_FORCE_INLINE FloatV FMul(const FloatV a, const FloatV b); +// a/b (per component) +PX_FORCE_INLINE FloatV FDiv(const FloatV a, const FloatV b); +// a/b (per component) +PX_FORCE_INLINE FloatV FDivFast(const FloatV a, const FloatV b); +// 1.0f/a +PX_FORCE_INLINE FloatV FRecip(const FloatV a); +// 1.0f/a +PX_FORCE_INLINE FloatV FRecipFast(const FloatV a); +// 1.0f/sqrt(a) +PX_FORCE_INLINE FloatV FRsqrt(const FloatV a); +// 1.0f/sqrt(a) +PX_FORCE_INLINE FloatV FRsqrtFast(const FloatV a); +// sqrt(a) +PX_FORCE_INLINE FloatV FSqrt(const FloatV a); +// a*b+c +PX_FORCE_INLINE FloatV FScaleAdd(const FloatV a, const FloatV b, const FloatV c); +// c-a*b +PX_FORCE_INLINE FloatV FNegScaleSub(const FloatV a, const FloatV b, const FloatV c); +// fabs(a) +PX_FORCE_INLINE FloatV FAbs(const FloatV a); +// c ? a : b (per component) +PX_FORCE_INLINE FloatV FSel(const BoolV c, const FloatV a, const FloatV b); +// a>b (per component) +PX_FORCE_INLINE BoolV FIsGrtr(const FloatV a, const FloatV b); +// a>=b (per component) +PX_FORCE_INLINE BoolV FIsGrtrOrEq(const FloatV a, const FloatV b); +// a==b (per component) +PX_FORCE_INLINE BoolV FIsEq(const FloatV a, const FloatV b); +// Max(a,b) (per component) +PX_FORCE_INLINE FloatV FMax(const FloatV a, const FloatV b); +// Min(a,b) (per component) +PX_FORCE_INLINE FloatV FMin(const FloatV a, const FloatV b); +// Clamp(a,b) (per component) +PX_FORCE_INLINE FloatV FClamp(const FloatV a, const FloatV minV, const FloatV maxV); + +// a.x>b.x +PX_FORCE_INLINE PxU32 FAllGrtr(const FloatV a, const FloatV b); +// a.x>=b.x +PX_FORCE_INLINE PxU32 FAllGrtrOrEq(const FloatV a, const FloatV b); +// a.x==b.x +PX_FORCE_INLINE PxU32 FAllEq(const FloatV a, const FloatV b); +// amax +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV min, const FloatV max); +// a>=min && a<=max +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV min, const FloatV max); +// a<-bounds || a>bounds +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV bounds); +// a>=-bounds && a<=bounds +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV bounds); + +// round float a to the near int +PX_FORCE_INLINE FloatV FRound(const FloatV a); +// calculate the sin of float a +PX_FORCE_INLINE FloatV FSin(const FloatV a); +// calculate the cos of float b +PX_FORCE_INLINE FloatV FCos(const FloatV a); + +////////////////////////////////////////////////////////////////// +// Math operations on Vec3V +////////////////////////////////////////////////////////////////// + +//(f,f,f,f) +PX_FORCE_INLINE Vec3V V3Splat(const FloatV f); + +//(x,y,z) +PX_FORCE_INLINE Vec3V V3Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z); + +//(1,0,0,0) +PX_FORCE_INLINE Vec3V V3UnitX(); +//(0,1,0,0) +PX_FORCE_INLINE Vec3V V3UnitY(); +//(0,0,1,0) +PX_FORCE_INLINE Vec3V V3UnitZ(); + +//(f.x,f.x,f.x,f.x) +PX_FORCE_INLINE FloatV V3GetX(const Vec3V f); +//(f.y,f.y,f.y,f.y) +PX_FORCE_INLINE FloatV V3GetY(const Vec3V f); +//(f.z,f.z,f.z,f.z) +PX_FORCE_INLINE FloatV V3GetZ(const Vec3V f); + +//(f,v.y,v.z,v.w) +PX_FORCE_INLINE Vec3V V3SetX(const Vec3V v, const FloatV f); +//(v.x,f,v.z,v.w) +PX_FORCE_INLINE Vec3V V3SetY(const Vec3V v, const FloatV f); +//(v.x,v.y,f,v.w) +PX_FORCE_INLINE Vec3V V3SetZ(const Vec3V v, const FloatV f); + +// v.x=f +PX_FORCE_INLINE void V3WriteX(Vec3V& v, const PxF32 f); +// v.y=f +PX_FORCE_INLINE void V3WriteY(Vec3V& v, const PxF32 f); +// v.z=f +PX_FORCE_INLINE void V3WriteZ(Vec3V& v, const PxF32 f); +// v.x=f.x, v.y=f.y, v.z=f.z +PX_FORCE_INLINE void V3WriteXYZ(Vec3V& v, const PxVec3& f); +// return v.x +PX_FORCE_INLINE PxF32 V3ReadX(const Vec3V& v); +// return v.y +PX_FORCE_INLINE PxF32 V3ReadY(const Vec3V& v); +// return v.y +PX_FORCE_INLINE PxF32 V3ReadZ(const Vec3V& v); +// return (v.x,v.y,v.z) +PX_FORCE_INLINE const PxVec3& V3ReadXYZ(const Vec3V& v); + +//(a.x, b.x, c.x) +PX_FORCE_INLINE Vec3V V3ColX(const Vec3V a, const Vec3V b, const Vec3V c); +//(a.y, b.y, c.y) +PX_FORCE_INLINE Vec3V V3ColY(const Vec3V a, const Vec3V b, const Vec3V c); +//(a.z, b.z, c.z) +PX_FORCE_INLINE Vec3V V3ColZ(const Vec3V a, const Vec3V b, const Vec3V c); + +//(0,0,0,0) +PX_FORCE_INLINE Vec3V V3Zero(); +//(1,1,1,1) +PX_FORCE_INLINE Vec3V V3One(); +//(PX_EPS_REAL,PX_EPS_REAL,PX_EPS_REAL,PX_EPS_REAL) +PX_FORCE_INLINE Vec3V V3Eps(); +//-c (per component) +PX_FORCE_INLINE Vec3V V3Neg(const Vec3V c); +// a+b (per component) +PX_FORCE_INLINE Vec3V V3Add(const Vec3V a, const Vec3V b); +// a-b (per component) +PX_FORCE_INLINE Vec3V V3Sub(const Vec3V a, const Vec3V b); +// a*b (per component) +PX_FORCE_INLINE Vec3V V3Scale(const Vec3V a, const FloatV b); +// a*b (per component) +PX_FORCE_INLINE Vec3V V3Mul(const Vec3V a, const Vec3V b); +// a/b (per component) +PX_FORCE_INLINE Vec3V V3ScaleInv(const Vec3V a, const FloatV b); +// a/b (per component) +PX_FORCE_INLINE Vec3V V3Div(const Vec3V a, const Vec3V b); +// a/b (per component) +PX_FORCE_INLINE Vec3V V3ScaleInvFast(const Vec3V a, const FloatV b); +// a/b (per component) +PX_FORCE_INLINE Vec3V V3DivFast(const Vec3V a, const Vec3V b); +// 1.0f/a +PX_FORCE_INLINE Vec3V V3Recip(const Vec3V a); +// 1.0f/a +PX_FORCE_INLINE Vec3V V3RecipFast(const Vec3V a); +// 1.0f/sqrt(a) +PX_FORCE_INLINE Vec3V V3Rsqrt(const Vec3V a); +// 1.0f/sqrt(a) +PX_FORCE_INLINE Vec3V V3RsqrtFast(const Vec3V a); +// a*b+c +PX_FORCE_INLINE Vec3V V3ScaleAdd(const Vec3V a, const FloatV b, const Vec3V c); +// c-a*b +PX_FORCE_INLINE Vec3V V3NegScaleSub(const Vec3V a, const FloatV b, const Vec3V c); +// a*b+c +PX_FORCE_INLINE Vec3V V3MulAdd(const Vec3V a, const Vec3V b, const Vec3V c); +// c-a*b +PX_FORCE_INLINE Vec3V V3NegMulSub(const Vec3V a, const Vec3V b, const Vec3V c); +// fabs(a) +PX_FORCE_INLINE Vec3V V3Abs(const Vec3V a); + +// a.b +// Note: a.w and b.w must have value zero +PX_FORCE_INLINE FloatV V3Dot(const Vec3V a, const Vec3V b); +// aXb +// Note: a.w and b.w must have value zero +PX_FORCE_INLINE Vec3V V3Cross(const Vec3V a, const Vec3V b); +// |a.a|^1/2 +// Note: a.w must have value zero +PX_FORCE_INLINE FloatV V3Length(const Vec3V a); +// a.a +// Note: a.w must have value zero +PX_FORCE_INLINE FloatV V3LengthSq(const Vec3V a); +// a*|a.a|^-1/2 +// Note: a.w must have value zero +PX_FORCE_INLINE Vec3V V3Normalize(const Vec3V a); +// a.a>0 ? a*|a.a|^-1/2 : (0,0,0,0) +// Note: a.w must have value zero +PX_FORCE_INLINE FloatV V3Length(const Vec3V a); +// a.a>0 ? a*|a.a|^-1/2 : unsafeReturnValue +// Note: a.w must have value zero +PX_FORCE_INLINE Vec3V V3NormalizeSafe(const Vec3V a, const Vec3V unsafeReturnValue); +// a.x + a.y + a.z +// Note: a.w must have value zero +PX_FORCE_INLINE FloatV V3SumElems(const Vec3V a); + +// c ? a : b (per component) +PX_FORCE_INLINE Vec3V V3Sel(const BoolV c, const Vec3V a, const Vec3V b); +// a>b (per component) +PX_FORCE_INLINE BoolV V3IsGrtr(const Vec3V a, const Vec3V b); +// a>=b (per component) +PX_FORCE_INLINE BoolV V3IsGrtrOrEq(const Vec3V a, const Vec3V b); +// a==b (per component) +PX_FORCE_INLINE BoolV V3IsEq(const Vec3V a, const Vec3V b); +// Max(a,b) (per component) +PX_FORCE_INLINE Vec3V V3Max(const Vec3V a, const Vec3V b); +// Min(a,b) (per component) +PX_FORCE_INLINE Vec3V V3Min(const Vec3V a, const Vec3V b); + +// Extract the maximum value from a +// Note: a.w must have value zero +PX_FORCE_INLINE FloatV V3ExtractMax(const Vec3V a); + +// Extract the minimum value from a +// Note: a.w must have value zero +PX_FORCE_INLINE FloatV V3ExtractMin(const Vec3V a); + +// Clamp(a,b) (per component) +PX_FORCE_INLINE Vec3V V3Clamp(const Vec3V a, const Vec3V minV, const Vec3V maxV); + +// Extract the sign for each component +PX_FORCE_INLINE Vec3V V3Sign(const Vec3V a); + +// Test all components. +// (a.x>b.x && a.y>b.y && a.z>b.z) +// Note: a.w and b.w must have value zero +PX_FORCE_INLINE PxU32 V3AllGrtr(const Vec3V a, const Vec3V b); +// (a.x>=b.x && a.y>=b.y && a.z>=b.z) +// Note: a.w and b.w must have value zero +PX_FORCE_INLINE PxU32 V3AllGrtrOrEq(const Vec3V a, const Vec3V b); +// (a.x==b.x && a.y==b.y && a.z==b.z) +// Note: a.w and b.w must have value zero +PX_FORCE_INLINE PxU32 V3AllEq(const Vec3V a, const Vec3V b); +// a.xmax.x || a.y>max.y || a.z>max.z +// Note: a.w and min.w and max.w must have value zero +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V min, const Vec3V max); +// a.x>=min.x && a.y>=min.y && a.z>=min.z && a.x<=max.x && a.y<=max.y && a.z<=max.z +// Note: a.w and min.w and max.w must have value zero +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V min, const Vec3V max); +// a.x<-bounds.x || a.y<=-bounds.y || a.zbounds.x || a.y>bounds.y || a.z>bounds.z +// Note: a.w and bounds.w must have value zero +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V bounds); +// a.x>=-bounds.x && a.y>=-bounds.y && a.z>=-bounds.z && a.x<=bounds.x && a.y<=bounds.y && a.z<=bounds.z +// Note: a.w and bounds.w must have value zero +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V bounds); + +//(floor(a.x + 0.5f), floor(a.y + 0.5f), floor(a.z + 0.5f)) +PX_FORCE_INLINE Vec3V V3Round(const Vec3V a); + +//(sinf(a.x), sinf(a.y), sinf(a.z)) +PX_FORCE_INLINE Vec3V V3Sin(const Vec3V a); +//(cosf(a.x), cosf(a.y), cosf(a.z)) +PX_FORCE_INLINE Vec3V V3Cos(const Vec3V a); + +//(a.y,a.z,a.z) +PX_FORCE_INLINE Vec3V V3PermYZZ(const Vec3V a); +//(a.x,a.y,a.x) +PX_FORCE_INLINE Vec3V V3PermXYX(const Vec3V a); +//(a.y,a.z,a.x) +PX_FORCE_INLINE Vec3V V3PermYZX(const Vec3V a); +//(a.z, a.x, a.y) +PX_FORCE_INLINE Vec3V V3PermZXY(const Vec3V a); +//(a.z,a.z,a.y) +PX_FORCE_INLINE Vec3V V3PermZZY(const Vec3V a); +//(a.y,a.x,a.x) +PX_FORCE_INLINE Vec3V V3PermYXX(const Vec3V a); +//(0, v1.z, v0.y) +PX_FORCE_INLINE Vec3V V3Perm_Zero_1Z_0Y(const Vec3V v0, const Vec3V v1); +//(v0.z, 0, v1.x) +PX_FORCE_INLINE Vec3V V3Perm_0Z_Zero_1X(const Vec3V v0, const Vec3V v1); +//(v1.y, v0.x, 0) +PX_FORCE_INLINE Vec3V V3Perm_1Y_0X_Zero(const Vec3V v0, const Vec3V v1); + +// Transpose 3 Vec3Vs inplace. Sets the w component to zero +// [ x0, y0, z0, w0] [ x1, y1, z1, w1] [ x2, y2, z2, w2] -> [x0 x1 x2 0] [y0 y1 y2 0] [z0 z1 z2 0] +PX_FORCE_INLINE void V3Transpose(Vec3V& col0, Vec3V& col1, Vec3V& col2); + +////////////////////////////////////////////////////////////////// +// Math operations on Vec4V +////////////////////////////////////////////////////////////////// + +//(f,f,f,f) +PX_FORCE_INLINE Vec4V V4Splat(const FloatV f); + +//(f[0],f[1],f[2],f[3]) +PX_FORCE_INLINE Vec4V V4Merge(const FloatV* const f); +//(x,y,z,w) +PX_FORCE_INLINE Vec4V V4Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z, const FloatVArg w); +//(x.w, y.w, z.w, w.w) +PX_FORCE_INLINE Vec4V V4MergeW(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w); +//(x.z, y.z, z.z, w.z) +PX_FORCE_INLINE Vec4V V4MergeZ(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w); +//(x.y, y.y, z.y, w.y) +PX_FORCE_INLINE Vec4V V4MergeY(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w); +//(x.x, y.x, z.x, w.x) +PX_FORCE_INLINE Vec4V V4MergeX(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w); + +//(a.x, b.x, a.y, b.y) +PX_FORCE_INLINE Vec4V V4UnpackXY(const Vec4VArg a, const Vec4VArg b); +//(a.z, b.z, a.w, b.w) +PX_FORCE_INLINE Vec4V V4UnpackZW(const Vec4VArg a, const Vec4VArg b); + +//(1,0,0,0) +PX_FORCE_INLINE Vec4V V4UnitW(); +//(0,1,0,0) +PX_FORCE_INLINE Vec4V V4UnitY(); +//(0,0,1,0) +PX_FORCE_INLINE Vec4V V4UnitZ(); +//(0,0,0,1) +PX_FORCE_INLINE Vec4V V4UnitW(); + +//(f.x,f.x,f.x,f.x) +PX_FORCE_INLINE FloatV V4GetX(const Vec4V f); +//(f.y,f.y,f.y,f.y) +PX_FORCE_INLINE FloatV V4GetY(const Vec4V f); +//(f.z,f.z,f.z,f.z) +PX_FORCE_INLINE FloatV V4GetZ(const Vec4V f); +//(f.w,f.w,f.w,f.w) +PX_FORCE_INLINE FloatV V4GetW(const Vec4V f); + +//(f,v.y,v.z,v.w) +PX_FORCE_INLINE Vec4V V4SetX(const Vec4V v, const FloatV f); +//(v.x,f,v.z,v.w) +PX_FORCE_INLINE Vec4V V4SetY(const Vec4V v, const FloatV f); +//(v.x,v.y,f,v.w) +PX_FORCE_INLINE Vec4V V4SetZ(const Vec4V v, const FloatV f); +//(v.x,v.y,v.z,f) +PX_FORCE_INLINE Vec4V V4SetW(const Vec4V v, const FloatV f); + +//(v.x,v.y,v.z,0) +PX_FORCE_INLINE Vec4V V4ClearW(const Vec4V v); + +//(a[elementIndex], a[elementIndex], a[elementIndex], a[elementIndex]) +template +PX_FORCE_INLINE Vec4V V4SplatElement(Vec4V a); + +// v.x=f +PX_FORCE_INLINE void V4WriteX(Vec4V& v, const PxF32 f); +// v.y=f +PX_FORCE_INLINE void V4WriteY(Vec4V& v, const PxF32 f); +// v.z=f +PX_FORCE_INLINE void V4WriteZ(Vec4V& v, const PxF32 f); +// v.w=f +PX_FORCE_INLINE void V4WriteW(Vec4V& v, const PxF32 f); +// v.x=f.x, v.y=f.y, v.z=f.z +PX_FORCE_INLINE void V4WriteXYZ(Vec4V& v, const PxVec3& f); +// return v.x +PX_FORCE_INLINE PxF32 V4ReadX(const Vec4V& v); +// return v.y +PX_FORCE_INLINE PxF32 V4ReadY(const Vec4V& v); +// return v.z +PX_FORCE_INLINE PxF32 V4ReadZ(const Vec4V& v); +// return v.w +PX_FORCE_INLINE PxF32 V4ReadW(const Vec4V& v); +// return (v.x,v.y,v.z) +PX_FORCE_INLINE const PxVec3& V4ReadXYZ(const Vec4V& v); + +//(0,0,0,0) +PX_FORCE_INLINE Vec4V V4Zero(); +//(1,1,1,1) +PX_FORCE_INLINE Vec4V V4One(); +//(PX_EPS_REAL,PX_EPS_REAL,PX_EPS_REAL,PX_EPS_REAL) +PX_FORCE_INLINE Vec4V V4Eps(); + +//-c (per component) +PX_FORCE_INLINE Vec4V V4Neg(const Vec4V c); +// a+b (per component) +PX_FORCE_INLINE Vec4V V4Add(const Vec4V a, const Vec4V b); +// a-b (per component) +PX_FORCE_INLINE Vec4V V4Sub(const Vec4V a, const Vec4V b); +// a*b (per component) +PX_FORCE_INLINE Vec4V V4Scale(const Vec4V a, const FloatV b); +// a*b (per component) +PX_FORCE_INLINE Vec4V V4Mul(const Vec4V a, const Vec4V b); +// a/b (per component) +PX_FORCE_INLINE Vec4V V4ScaleInv(const Vec4V a, const FloatV b); +// a/b (per component) +PX_FORCE_INLINE Vec4V V4Div(const Vec4V a, const Vec4V b); +// a/b (per component) +PX_FORCE_INLINE Vec4V V4ScaleInvFast(const Vec4V a, const FloatV b); +// a/b (per component) +PX_FORCE_INLINE Vec4V V4DivFast(const Vec4V a, const Vec4V b); +// 1.0f/a +PX_FORCE_INLINE Vec4V V4Recip(const Vec4V a); +// 1.0f/a +PX_FORCE_INLINE Vec4V V4RecipFast(const Vec4V a); +// 1.0f/sqrt(a) +PX_FORCE_INLINE Vec4V V4Rsqrt(const Vec4V a); +// 1.0f/sqrt(a) +PX_FORCE_INLINE Vec4V V4RsqrtFast(const Vec4V a); +// a*b+c +PX_FORCE_INLINE Vec4V V4ScaleAdd(const Vec4V a, const FloatV b, const Vec4V c); +// c-a*b +PX_FORCE_INLINE Vec4V V4NegScaleSub(const Vec4V a, const FloatV b, const Vec4V c); +// a*b+c +PX_FORCE_INLINE Vec4V V4MulAdd(const Vec4V a, const Vec4V b, const Vec4V c); +// c-a*b +PX_FORCE_INLINE Vec4V V4NegMulSub(const Vec4V a, const Vec4V b, const Vec4V c); + +// fabs(a) +PX_FORCE_INLINE Vec4V V4Abs(const Vec4V a); +// bitwise a & ~b +PX_FORCE_INLINE Vec4V V4Andc(const Vec4V a, const VecU32V b); + +// a.b (W is taken into account) +PX_FORCE_INLINE FloatV V4Dot(const Vec4V a, const Vec4V b); +// a.b (same computation as V3Dot. W is ignored in input) +PX_FORCE_INLINE FloatV V4Dot3(const Vec4V a, const Vec4V b); +// aXb (same computation as V3Cross. W is ignored in input and undefined in output) +PX_FORCE_INLINE Vec4V V4Cross(const Vec4V a, const Vec4V b); + +//|a.a|^1/2 +PX_FORCE_INLINE FloatV V4Length(const Vec4V a); +// a.a +PX_FORCE_INLINE FloatV V4LengthSq(const Vec4V a); + +// a*|a.a|^-1/2 +PX_FORCE_INLINE Vec4V V4Normalize(const Vec4V a); +// a.a>0 ? a*|a.a|^-1/2 : unsafeReturnValue +PX_FORCE_INLINE Vec4V V4NormalizeSafe(const Vec4V a, const Vec4V unsafeReturnValue); +// a*|a.a|^-1/2 +PX_FORCE_INLINE Vec4V V4NormalizeFast(const Vec4V a); + +// c ? a : b (per component) +PX_FORCE_INLINE Vec4V V4Sel(const BoolV c, const Vec4V a, const Vec4V b); +// a>b (per component) +PX_FORCE_INLINE BoolV V4IsGrtr(const Vec4V a, const Vec4V b); +// a>=b (per component) +PX_FORCE_INLINE BoolV V4IsGrtrOrEq(const Vec4V a, const Vec4V b); +// a==b (per component) +PX_FORCE_INLINE BoolV V4IsEq(const Vec4V a, const Vec4V b); +// Max(a,b) (per component) +PX_FORCE_INLINE Vec4V V4Max(const Vec4V a, const Vec4V b); +// Min(a,b) (per component) +PX_FORCE_INLINE Vec4V V4Min(const Vec4V a, const Vec4V b); +// Get the maximum component from a +PX_FORCE_INLINE FloatV V4ExtractMax(const Vec4V a); +// Get the minimum component from a +PX_FORCE_INLINE FloatV V4ExtractMin(const Vec4V a); + +// Clamp(a,b) (per component) +PX_FORCE_INLINE Vec4V V4Clamp(const Vec4V a, const Vec4V minV, const Vec4V maxV); + +// return 1 if all components of a are greater than all components of b. +PX_FORCE_INLINE PxU32 V4AllGrtr(const Vec4V a, const Vec4V b); +// return 1 if all components of a are greater than or equal to all components of b +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq(const Vec4V a, const Vec4V b); +// return 1 if XYZ components of a are greater than or equal to XYZ components of b. W is ignored. +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq3(const Vec4V a, const Vec4V b); +// return 1 if all components of a are equal to all components of b +PX_FORCE_INLINE PxU32 V4AllEq(const Vec4V a, const Vec4V b); +// return 1 if any XYZ component of a is greater than the corresponding component of b. W is ignored. +PX_FORCE_INLINE PxU32 V4AnyGrtr3(const Vec4V a, const Vec4V b); + +// round(a)(per component) +PX_FORCE_INLINE Vec4V V4Round(const Vec4V a); +// sin(a) (per component) +PX_FORCE_INLINE Vec4V V4Sin(const Vec4V a); +// cos(a) (per component) +PX_FORCE_INLINE Vec4V V4Cos(const Vec4V a); + +// Permute v into a new vec4v with YXWZ format +PX_FORCE_INLINE Vec4V V4PermYXWZ(const Vec4V v); +// Permute v into a new vec4v with XZXZ format +PX_FORCE_INLINE Vec4V V4PermXZXZ(const Vec4V v); +// Permute v into a new vec4v with YWYW format +PX_FORCE_INLINE Vec4V V4PermYWYW(const Vec4V v); +// Permute v into a new vec4v with YZXW format +PX_FORCE_INLINE Vec4V V4PermYZXW(const Vec4V v); +// Permute v into a new vec4v with ZWXY format - equivalent to a swap of the two 64bit parts of the vector +PX_FORCE_INLINE Vec4V V4PermZWXY(const Vec4V a); + +// Permute v into a new vec4v with format {a[x], a[y], a[z], a[w]} +// V4Perm<1,3,1,3> is equal to V4PermYWYW +// V4Perm<0,2,0,2> is equal to V4PermXZXZ +// V3Perm<1,0,3,2> is equal to V4PermYXWZ +template +PX_FORCE_INLINE Vec4V V4Perm(const Vec4V a); + +// Transpose 4 Vec4Vs inplace. +// [ x0, y0, z0, w0] [ x1, y1, z1, w1] [ x2, y2, z2, w2] [ x3, y3, z3, w3] -> +// [ x0, x1, x2, x3] [ y0, y1, y2, y3] [ z0, z1, z2, z3] [ w0, w1, w2, w3] +PX_FORCE_INLINE void V3Transpose(Vec3V& col0, Vec3V& col1, Vec3V& col2); + +// q = cos(a/2) + u*sin(a/2) +PX_FORCE_INLINE QuatV QuatV_From_RotationAxisAngle(const Vec3V u, const FloatV a); +// convert q to a unit quaternion +PX_FORCE_INLINE QuatV QuatNormalize(const QuatV q); +//|q.q|^1/2 +PX_FORCE_INLINE FloatV QuatLength(const QuatV q); +// q.q +PX_FORCE_INLINE FloatV QuatLengthSq(const QuatV q); +// a.b +PX_FORCE_INLINE FloatV QuatDot(const QuatV a, const QuatV b); +//(-q.x, -q.y, -q.z, q.w) +PX_FORCE_INLINE QuatV QuatConjugate(const QuatV q); +//(q.x, q.y, q.z) +PX_FORCE_INLINE Vec3V QuatGetImaginaryPart(const QuatV q); +// convert quaternion to matrix 33 +PX_FORCE_INLINE Mat33V QuatGetMat33V(const QuatVArg q); +// convert quaternion to matrix 33 +PX_FORCE_INLINE void QuatGetMat33V(const QuatVArg q, Vec3V& column0, Vec3V& column1, Vec3V& column2); +// convert matrix 33 to quaternion +PX_FORCE_INLINE QuatV Mat33GetQuatV(const Mat33V& a); +// brief computes rotation of x-axis +PX_FORCE_INLINE Vec3V QuatGetBasisVector0(const QuatV q); +// brief computes rotation of y-axis +PX_FORCE_INLINE Vec3V QuatGetBasisVector1(const QuatV q); +// brief computes rotation of z-axis +PX_FORCE_INLINE Vec3V QuatGetBasisVector2(const QuatV q); +// calculate the rotation vector from q and v +PX_FORCE_INLINE Vec3V QuatRotate(const QuatV q, const Vec3V v); +// calculate the rotation vector from the conjugate quaternion and v +PX_FORCE_INLINE Vec3V QuatRotateInv(const QuatV q, const Vec3V v); +// quaternion multiplication +PX_FORCE_INLINE QuatV QuatMul(const QuatV a, const QuatV b); +// quaternion add +PX_FORCE_INLINE QuatV QuatAdd(const QuatV a, const QuatV b); +// (-q.x, -q.y, -q.z, -q.w) +PX_FORCE_INLINE QuatV QuatNeg(const QuatV q); +// (a.x - b.x, a.y-b.y, a.z-b.z, a.w-b.w ) +PX_FORCE_INLINE QuatV QuatSub(const QuatV a, const QuatV b); +// (a.x*b, a.y*b, a.z*b, a.w*b) +PX_FORCE_INLINE QuatV QuatScale(const QuatV a, const FloatV b); +// (x = v[0], y = v[1], z = v[2], w =v[3]) +PX_FORCE_INLINE QuatV QuatMerge(const FloatV* const v); +// (x = v[0], y = v[1], z = v[2], w =v[3]) +PX_FORCE_INLINE QuatV QuatMerge(const FloatVArg x, const FloatVArg y, const FloatVArg z, const FloatVArg w); +// (x = 0.f, y = 0.f, z = 0.f, w = 1.f) +PX_FORCE_INLINE QuatV QuatIdentity(); +// check for each component is valid +PX_FORCE_INLINE bool isFiniteQuatV(const QuatV q); +// check for each component is valid +PX_FORCE_INLINE bool isValidQuatV(const QuatV q); +// check for each component is valid +PX_FORCE_INLINE bool isSaneQuatV(const QuatV q); + +// Math operations on 16-byte aligned booleans. +// x=false y=false z=false w=false +PX_FORCE_INLINE BoolV BFFFF(); +// x=false y=false z=false w=true +PX_FORCE_INLINE BoolV BFFFT(); +// x=false y=false z=true w=false +PX_FORCE_INLINE BoolV BFFTF(); +// x=false y=false z=true w=true +PX_FORCE_INLINE BoolV BFFTT(); +// x=false y=true z=false w=false +PX_FORCE_INLINE BoolV BFTFF(); +// x=false y=true z=false w=true +PX_FORCE_INLINE BoolV BFTFT(); +// x=false y=true z=true w=false +PX_FORCE_INLINE BoolV BFTTF(); +// x=false y=true z=true w=true +PX_FORCE_INLINE BoolV BFTTT(); +// x=true y=false z=false w=false +PX_FORCE_INLINE BoolV BTFFF(); +// x=true y=false z=false w=true +PX_FORCE_INLINE BoolV BTFFT(); +// x=true y=false z=true w=false +PX_FORCE_INLINE BoolV BTFTF(); +// x=true y=false z=true w=true +PX_FORCE_INLINE BoolV BTFTT(); +// x=true y=true z=false w=false +PX_FORCE_INLINE BoolV BTTFF(); +// x=true y=true z=false w=true +PX_FORCE_INLINE BoolV BTTFT(); +// x=true y=true z=true w=false +PX_FORCE_INLINE BoolV BTTTF(); +// x=true y=true z=true w=true +PX_FORCE_INLINE BoolV BTTTT(); + +// x=false y=false z=false w=true +PX_FORCE_INLINE BoolV BWMask(); +// x=true y=false z=false w=false +PX_FORCE_INLINE BoolV BXMask(); +// x=false y=true z=false w=false +PX_FORCE_INLINE BoolV BYMask(); +// x=false y=false z=true w=false +PX_FORCE_INLINE BoolV BZMask(); + +// get x component +PX_FORCE_INLINE BoolV BGetX(const BoolV f); +// get y component +PX_FORCE_INLINE BoolV BGetY(const BoolV f); +// get z component +PX_FORCE_INLINE BoolV BGetZ(const BoolV f); +// get w component +PX_FORCE_INLINE BoolV BGetW(const BoolV f); + +// Use elementIndex to splat xxxx or yyyy or zzzz or wwww +template +PX_FORCE_INLINE BoolV BSplatElement(Vec4V a); + +// component-wise && (AND) +PX_FORCE_INLINE BoolV BAnd(const BoolV a, const BoolV b); +// component-wise || (OR) +PX_FORCE_INLINE BoolV BOr(const BoolV a, const BoolV b); +// component-wise not +PX_FORCE_INLINE BoolV BNot(const BoolV a); + +// if all four components are true, return true, otherwise return false +PX_FORCE_INLINE BoolV BAllTrue4(const BoolV a); + +// if any four components is true, return true, otherwise return false +PX_FORCE_INLINE BoolV BAnyTrue4(const BoolV a); + +// if all three(0, 1, 2) components are true, return true, otherwise return false +PX_FORCE_INLINE BoolV BAllTrue3(const BoolV a); + +// if any three (0, 1, 2) components is true, return true, otherwise return false +PX_FORCE_INLINE BoolV BAnyTrue3(const BoolV a); + +// Return 1 if all components equal, zero otherwise. +PX_FORCE_INLINE PxU32 BAllEq(const BoolV a, const BoolV b); + +// Specialized/faster BAllEq function for b==TTTT +PX_FORCE_INLINE PxU32 BAllEqTTTT(const BoolV a); +// Specialized/faster BAllEq function for b==FFFF +PX_FORCE_INLINE PxU32 BAllEqFFFF(const BoolV a); + +/// Get BoolV as bits set in an PxU32. A bit in the output is set if the element is 'true' in the input. +/// There is a bit for each element in a, with element 0s value held in bit0, element 1 in bit 1s and so forth. +/// If nothing is true in the input it will return 0, and if all are true if will return 0xf. +/// NOTE! That performance of the function varies considerably by platform, thus it is recommended to use +/// where your algorithm really needs a BoolV in an integer variable. +PX_FORCE_INLINE PxU32 BGetBitMask(const BoolV a); + +// VecI32V stuff + +PX_FORCE_INLINE VecI32V VecI32V_Zero(); + +PX_FORCE_INLINE VecI32V VecI32V_One(); + +PX_FORCE_INLINE VecI32V VecI32V_Two(); + +PX_FORCE_INLINE VecI32V VecI32V_MinusOne(); + +// Compute a shift parameter for VecI32V_LeftShift and VecI32V_RightShift +// Each element of shift must be identical ie the vector must have form {count, count, count, count} with count>=0 +PX_FORCE_INLINE VecShiftV VecI32V_PrepareShift(const VecI32VArg shift); + +// Shift each element of a leftwards by the same amount +// Compute shift with VecI32V_PrepareShift +//{a.x<>shift[0], a.y>>shift[0], a.z>>shift[0], a.w>>shift[0]} +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const VecShiftVArg shift); + +PX_FORCE_INLINE VecI32V VecI32V_Add(const VecI32VArg a, const VecI32VArg b); + +PX_FORCE_INLINE VecI32V VecI32V_Or(const VecI32VArg a, const VecI32VArg b); + +PX_FORCE_INLINE VecI32V VecI32V_GetX(const VecI32VArg a); + +PX_FORCE_INLINE VecI32V VecI32V_GetY(const VecI32VArg a); + +PX_FORCE_INLINE VecI32V VecI32V_GetZ(const VecI32VArg a); + +PX_FORCE_INLINE VecI32V VecI32V_GetW(const VecI32VArg a); + +PX_FORCE_INLINE VecI32V VecI32V_Sub(const VecI32VArg a, const VecI32VArg b); + +PX_FORCE_INLINE BoolV VecI32V_IsGrtr(const VecI32VArg a, const VecI32VArg b); + +PX_FORCE_INLINE BoolV VecI32V_IsEq(const VecI32VArg a, const VecI32VArg b); + +PX_FORCE_INLINE VecI32V V4I32Sel(const BoolV c, const VecI32V a, const VecI32V b); + +// VecU32V stuff + +PX_FORCE_INLINE VecU32V U4Zero(); + +PX_FORCE_INLINE VecU32V U4One(); + +PX_FORCE_INLINE VecU32V U4Two(); + +PX_FORCE_INLINE BoolV V4IsEqU32(const VecU32V a, const VecU32V b); + +PX_FORCE_INLINE VecU32V V4U32Sel(const BoolV c, const VecU32V a, const VecU32V b); + +PX_FORCE_INLINE VecU32V V4U32or(VecU32V a, VecU32V b); + +PX_FORCE_INLINE VecU32V V4U32xor(VecU32V a, VecU32V b); + +PX_FORCE_INLINE VecU32V V4U32and(VecU32V a, VecU32V b); + +PX_FORCE_INLINE VecU32V V4U32Andc(VecU32V a, VecU32V b); + +// VecU32 - why does this not return a bool? +PX_FORCE_INLINE VecU32V V4IsGrtrV32u(const Vec4V a, const Vec4V b); + +// Math operations on 16-byte aligned Mat33s (represents any 3x3 matrix) +PX_FORCE_INLINE Mat33V M33Load(const PxMat33& m) +{ + return Mat33V(Vec3V_From_Vec4V(V4LoadU(&m.column0.x)), + Vec3V_From_Vec4V(V4LoadU(&m.column1.x)), V3LoadU(m.column2)); +} +// a*b +PX_FORCE_INLINE Vec3V M33MulV3(const Mat33V& a, const Vec3V b); +// A*x + b +PX_FORCE_INLINE Vec3V M33MulV3AddV3(const Mat33V& A, const Vec3V b, const Vec3V c); +// transpose(a) * b +PX_FORCE_INLINE Vec3V M33TrnspsMulV3(const Mat33V& a, const Vec3V b); +// a*b +PX_FORCE_INLINE Mat33V M33MulM33(const Mat33V& a, const Mat33V& b); +// a+b +PX_FORCE_INLINE Mat33V M33Add(const Mat33V& a, const Mat33V& b); +// a+b +PX_FORCE_INLINE Mat33V M33Sub(const Mat33V& a, const Mat33V& b); +//-a +PX_FORCE_INLINE Mat33V M33Neg(const Mat33V& a); +// absolute value of the matrix +PX_FORCE_INLINE Mat33V M33Abs(const Mat33V& a); +// inverse mat +PX_FORCE_INLINE Mat33V M33Inverse(const Mat33V& a); +// transpose(a) +PX_FORCE_INLINE Mat33V M33Trnsps(const Mat33V& a); +// create an identity matrix +PX_FORCE_INLINE Mat33V M33Identity(); + +// create a vec3 to store the diagonal element of the M33 +PX_FORCE_INLINE Mat33V M33Diagonal(const Vec3VArg); + +// Not implemented +// return 1 if all components of a are equal to all components of b +// PX_FORCE_INLINE PxU32 V4U32AllEq(const VecU32V a, const VecU32V b); +// v.w=f +// PX_FORCE_INLINE void V3WriteW(Vec3V& v, const PxF32 f); +// PX_FORCE_INLINE PxF32 V3ReadW(const Vec3V& v); + +// Not used +// PX_FORCE_INLINE Vec4V V4LoadAligned(Vec4V* addr); +// PX_FORCE_INLINE Vec4V V4LoadUnaligned(Vec4V* addr); +// floor(a)(per component) +// PX_FORCE_INLINE Vec4V V4Floor(Vec4V a); +// ceil(a) (per component) +// PX_FORCE_INLINE Vec4V V4Ceil(Vec4V a); +// PX_FORCE_INLINE VecU32V V4ConvertToU32VSaturate(const Vec4V a, PxU32 power); + +// Math operations on 16-byte aligned Mat34s (represents transformation matrix - rotation and translation). +// namespace _Mat34V +//{ +// //a*b +// PX_FORCE_INLINE Vec3V multiplyV(const Mat34V& a, const Vec3V b); +// //a_rotation * b +// PX_FORCE_INLINE Vec3V multiply3X3V(const Mat34V& a, const Vec3V b); +// //transpose(a_rotation)*b +// PX_FORCE_INLINE Vec3V multiplyTranspose3X3V(const Mat34V& a, const Vec3V b); +// //a*b +// PX_FORCE_INLINE Mat34V multiplyV(const Mat34V& a, const Mat34V& b); +// //a_rotation*b +// PX_FORCE_INLINE Mat33V multiply3X3V(const Mat34V& a, const Mat33V& b); +// //a_rotation*b_rotation +// PX_FORCE_INLINE Mat33V multiply3X3V(const Mat34V& a, const Mat34V& b); +// //a+b +// PX_FORCE_INLINE Mat34V addV(const Mat34V& a, const Mat34V& b); +// //a^-1 +// PX_FORCE_INLINE Mat34V getInverseV(const Mat34V& a); +// //transpose(a_rotation) +// PX_FORCE_INLINE Mat33V getTranspose3X3(const Mat34V& a); +//}; //namespace _Mat34V + +// a*b +//#define M34MulV3(a,b) (M34MulV3(a,b)) +////a_rotation * b +//#define M34Mul33V3(a,b) (M34Mul33V3(a,b)) +////transpose(a_rotation)*b +//#define M34TrnspsMul33V3(a,b) (M34TrnspsMul33V3(a,b)) +////a*b +//#define M34MulM34(a,b) (_Mat34V::multiplyV(a,b)) +// a_rotation*b +//#define M34MulM33(a,b) (M34MulM33(a,b)) +// a_rotation*b_rotation +//#define M34Mul33MM34(a,b) (M34MulM33(a,b)) +// a+b +//#define M34Add(a,b) (M34Add(a,b)) +////a^-1 +//#define M34Inverse(a,b) (M34Inverse(a)) +// transpose(a_rotation) +//#define M34Trnsps33(a) (M33Trnsps3X3(a)) + +// Math operations on 16-byte aligned Mat44s (represents any 4x4 matrix) +// namespace _Mat44V +//{ +// //a*b +// PX_FORCE_INLINE Vec4V multiplyV(const Mat44V& a, const Vec4V b); +// //transpose(a)*b +// PX_FORCE_INLINE Vec4V multiplyTransposeV(const Mat44V& a, const Vec4V b); +// //a*b +// PX_FORCE_INLINE Mat44V multiplyV(const Mat44V& a, const Mat44V& b); +// //a+b +// PX_FORCE_INLINE Mat44V addV(const Mat44V& a, const Mat44V& b); +// //a&-1 +// PX_FORCE_INLINE Mat44V getInverseV(const Mat44V& a); +// //transpose(a) +// PX_FORCE_INLINE Mat44V getTransposeV(const Mat44V& a); +//}; //namespace _Mat44V + +// namespace _VecU32V +//{ +// // pack 8 U32s to 8 U16s with saturation +// PX_FORCE_INLINE VecU16V pack2U32VToU16VSaturate(VecU32V a, VecU32V b); +// PX_FORCE_INLINE VecU32V orV(VecU32V a, VecU32V b); +// PX_FORCE_INLINE VecU32V andV(VecU32V a, VecU32V b); +// PX_FORCE_INLINE VecU32V andcV(VecU32V a, VecU32V b); +// // conversion from integer to float +// PX_FORCE_INLINE Vec4V convertToVec4V(VecU32V a); +// // splat a[elementIndex] into all fields of a +// template +// PX_FORCE_INLINE VecU32V splatElement(VecU32V a); +// PX_FORCE_INLINE void storeAligned(VecU32V a, VecU32V* address); +//}; + +// namespace _VecI32V +//{ +// template PX_FORCE_INLINE VecI32V splatI32(); +//}; +// +// namespace _VecU16V +//{ +// PX_FORCE_INLINE VecU16V orV(VecU16V a, VecU16V b); +// PX_FORCE_INLINE VecU16V andV(VecU16V a, VecU16V b); +// PX_FORCE_INLINE VecU16V andcV(VecU16V a, VecU16V b); +// PX_FORCE_INLINE void storeAligned(VecU16V val, VecU16V *address); +// PX_FORCE_INLINE VecU16V loadAligned(VecU16V* addr); +// PX_FORCE_INLINE VecU16V loadUnaligned(VecU16V* addr); +// PX_FORCE_INLINE VecU16V compareGt(VecU16V a, VecU16V b); +// template +// PX_FORCE_INLINE VecU16V splatElement(VecU16V a); +// PX_FORCE_INLINE VecU16V subtractModulo(VecU16V a, VecU16V b); +// PX_FORCE_INLINE VecU16V addModulo(VecU16V a, VecU16V b); +// PX_FORCE_INLINE VecU32V getLo16(VecU16V a); // [0,2,4,6] 16-bit values to [0,1,2,3] 32-bit vector +// PX_FORCE_INLINE VecU32V getHi16(VecU16V a); // [1,3,5,7] 16-bit values to [0,1,2,3] 32-bit vector +//}; +// +// namespace _VecI16V +//{ +// template PX_FORCE_INLINE VecI16V splatImmediate(); +//}; +// +// namespace _VecU8V +//{ +//}; + +// a*b +//#define M44MulV4(a,b) (M44MulV4(a,b)) +////transpose(a)*b +//#define M44TrnspsMulV4(a,b) (M44TrnspsMulV4(a,b)) +////a*b +//#define M44MulM44(a,b) (M44MulM44(a,b)) +////a+b +//#define M44Add(a,b) (M44Add(a,b)) +////a&-1 +//#define M44Inverse(a) (M44Inverse(a)) +////transpose(a) +//#define M44Trnsps(a) (M44Trnsps(a)) + +// dsequeira: these used to be assert'd out in SIMD builds, but they're necessary if +// we want to be able to write some scalar functions which run using SIMD data structures + +PX_FORCE_INLINE void V3WriteX(Vec3V& v, const PxF32 f) +{ + reinterpret_cast(v).x = f; +} + +PX_FORCE_INLINE void V3WriteY(Vec3V& v, const PxF32 f) +{ + reinterpret_cast(v).y = f; +} + +PX_FORCE_INLINE void V3WriteZ(Vec3V& v, const PxF32 f) +{ + reinterpret_cast(v).z = f; +} + +PX_FORCE_INLINE void V3WriteXYZ(Vec3V& v, const PxVec3& f) +{ + reinterpret_cast(v) = f; +} + +PX_FORCE_INLINE PxF32 V3ReadX(const Vec3V& v) +{ + return reinterpret_cast(v).x; +} + +PX_FORCE_INLINE PxF32 V3ReadY(const Vec3V& v) +{ + return reinterpret_cast(v).y; +} + +PX_FORCE_INLINE PxF32 V3ReadZ(const Vec3V& v) +{ + return reinterpret_cast(v).z; +} + +PX_FORCE_INLINE const PxVec3& V3ReadXYZ(const Vec3V& v) +{ + return reinterpret_cast(v); +} + +PX_FORCE_INLINE void V4WriteX(Vec4V& v, const PxF32 f) +{ + reinterpret_cast(v).x = f; +} + +PX_FORCE_INLINE void V4WriteY(Vec4V& v, const PxF32 f) +{ + reinterpret_cast(v).y = f; +} + +PX_FORCE_INLINE void V4WriteZ(Vec4V& v, const PxF32 f) +{ + reinterpret_cast(v).z = f; +} + +PX_FORCE_INLINE void V4WriteW(Vec4V& v, const PxF32 f) +{ + reinterpret_cast(v).w = f; +} + +PX_FORCE_INLINE void V4WriteXYZ(Vec4V& v, const PxVec3& f) +{ + reinterpret_cast(v) = f; +} + +PX_FORCE_INLINE PxF32 V4ReadX(const Vec4V& v) +{ + return reinterpret_cast(v).x; +} + +PX_FORCE_INLINE PxF32 V4ReadY(const Vec4V& v) +{ + return reinterpret_cast(v).y; +} + +PX_FORCE_INLINE PxF32 V4ReadZ(const Vec4V& v) +{ + return reinterpret_cast(v).z; +} + +PX_FORCE_INLINE PxF32 V4ReadW(const Vec4V& v) +{ + return reinterpret_cast(v).w; +} + +PX_FORCE_INLINE const PxVec3& V4ReadXYZ(const Vec4V& v) +{ + return reinterpret_cast(v); +} + +// this macro transposes 4 Vec4V into 3 Vec4V (assuming that the W component can be ignored +//inA: 1 2 3 4 +//inB: 5 6 7 8 +//inC: 9 10 11 12 +//inD: 13 14 15 16 +//outA: 1 5 9 13 +//outB: 2 6 10 14 +//outC: 3 7 11 15 +#define PX_TRANSPOSE_44_34(inA, inB, inC, inD, outA, outB, outC) \ +outA = V4UnpackXY(inA, inC); \ +inA = V4UnpackZW(inA, inC); \ +inC = V4UnpackXY(inB, inD); \ +inB = V4UnpackZW(inB, inD); \ +outB = V4UnpackZW(outA, inC); \ +outA = V4UnpackXY(outA, inC); \ +outC = V4UnpackXY(inA, inB); + +// this macro transposes 3 Vec4V into 4 Vec4V (with W components as garbage!) +//inA: 1 2 3 4 +//inB: 5 6 7 8 +//inC: 9 10 11 12 +//outA: 1 5 9 undefined +//outB: 2 6 10 undefined +//outC: 3 7 11 undefined +//outD: 4 8 12 undefined +#define PX_TRANSPOSE_34_44(inA, inB, inC, outA, outB, outC, outD) \ + outA = V4UnpackXY(inA, inC); \ + inA = V4UnpackZW(inA, inC); \ + outC = V4UnpackXY(inB, inB); \ + inC = V4UnpackZW(inB, inB); \ + outB = V4UnpackZW(outA, outC); \ + outA = V4UnpackXY(outA, outC); \ + outC = V4UnpackXY(inA, inC); \ + outD = V4UnpackZW(inA, inC); + +//inA: 1 2 3 4 +//inB: 5 6 7 8 +//inC: 9 10 11 12 +//inD: 13 14 15 16 +//outA: 1 5 9 13 +//outB: 2 6 10 14 +//outC: 3 7 11 15 +//outD: 4 8 12 16 +#define PX_TRANSPOSE_44(inA, inB, inC, inD, outA, outB, outC, outD) \ + outA = V4UnpackXY(inA, inC); \ + inA = V4UnpackZW(inA, inC); \ + inC = V4UnpackXY(inB, inD); \ + inB = V4UnpackZW(inB, inD); \ + outB = V4UnpackZW(outA, inC); \ + outA = V4UnpackXY(outA, inC); \ + outC = V4UnpackXY(inA, inB); \ + outD = V4UnpackZW(inA, inB); + +// This function returns a Vec4V, where each element is the dot product of one pair of Vec3Vs. On PC, each element in +// the result should be identical to the results if V3Dot was performed +// for each pair of Vec3V. +// However, on other platforms, the result might diverge by some small margin due to differences in FP rounding, e.g. if +// _mm_dp_ps was used or some other approximate dot product or fused madd operations +// were used. +// Where there does not exist a hw-accelerated dot-product operation, this approach should be the fastest way to compute +// the dot product of 4 vectors. +PX_FORCE_INLINE Vec4V V3Dot4(const Vec3VArg a0, const Vec3VArg b0, const Vec3VArg a1, const Vec3VArg b1, + const Vec3VArg a2, const Vec3VArg b2, const Vec3VArg a3, const Vec3VArg b3) +{ + Vec4V a0b0 = Vec4V_From_Vec3V(V3Mul(a0, b0)); + Vec4V a1b1 = Vec4V_From_Vec3V(V3Mul(a1, b1)); + Vec4V a2b2 = Vec4V_From_Vec3V(V3Mul(a2, b2)); + Vec4V a3b3 = Vec4V_From_Vec3V(V3Mul(a3, b3)); + + Vec4V aTrnsps, bTrnsps, cTrnsps; + + PX_TRANSPOSE_44_34(a0b0, a1b1, a2b2, a3b3, aTrnsps, bTrnsps, cTrnsps); + + return V4Add(V4Add(aTrnsps, bTrnsps), cTrnsps); +} + +//(f.x,f.y,f.z,0) - Alternative/faster V3LoadU implementation when it is safe to read "W", i.e. the 32bits after the PxVec3. +PX_FORCE_INLINE Vec3V V3LoadU_SafeReadW(const PxVec3& f) +{ + return Vec3V_From_Vec4V(V4LoadU(&f.x)); +} + +} // namespace aos +#if !PX_DOXYGEN +} // namespace physx +#endif + +// Now for the cross-platform implementations of the 16-byte aligned maths functions (win32/360/ppu/spu etc). +#if COMPILE_VECTOR_INTRINSICS +#include "PxInlineAoS.h" +#else // #if COMPILE_VECTOR_INTRINSICS +#include "PxVecMathAoSScalarInline.h" +#endif // #if !COMPILE_VECTOR_INTRINSICS +#include "PxVecQuat.h" + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathAoSScalar.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathAoSScalar.h new file mode 100644 index 000000000..d2b96b1ae --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathAoSScalar.h @@ -0,0 +1,251 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC_MATH_AOS_SCALAR_H +#define PX_VEC_MATH_AOS_SCALAR_H + +#if COMPILE_VECTOR_INTRINSICS +#error Scalar version should not be included when using vector intrinsics. +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +namespace aos +{ + +struct VecI16V; +struct VecU16V; +struct VecI32V; +struct VecU32V; +struct Vec4V; +typedef Vec4V QuatV; + +PX_ALIGN_PREFIX(16) +struct FloatV +{ + PxF32 x; + PxF32 pad[3]; + FloatV() + { + } + FloatV(const PxF32 _x) : x(_x) + { + } +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Vec4V +{ + PxF32 x, y, z, w; + Vec4V() + { + } + Vec4V(const PxF32 _x, const PxF32 _y, const PxF32 _z, const PxF32 _w) : x(_x), y(_y), z(_z), w(_w) + { + } +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Vec3V +{ + PxF32 x, y, z; + PxF32 pad; + Vec3V() + { + } + Vec3V(const PxF32 _x, const PxF32 _y, const PxF32 _z) : x(_x), y(_y), z(_z), pad(0.0f) + { + } +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct BoolV +{ + PxU32 ux, uy, uz, uw; + BoolV() + { + } + BoolV(const PxU32 _x, const PxU32 _y, const PxU32 _z, const PxU32 _w) : ux(_x), uy(_y), uz(_z), uw(_w) + { + } +} PX_ALIGN_SUFFIX(16); + +struct Mat33V +{ + Mat33V() + { + } + Mat33V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec3V col0; + Vec3V col1; + Vec3V col2; +}; + +struct Mat34V +{ + Mat34V() + { + } + Mat34V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2, const Vec3V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec3V col0; + Vec3V col1; + Vec3V col2; + Vec3V col3; +}; + +struct Mat43V +{ + Mat43V() + { + } + Mat43V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec4V col0; + Vec4V col1; + Vec4V col2; +}; + +struct Mat44V +{ + Mat44V() + { + } + Mat44V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2, const Vec4V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec4V col0; + Vec4V col1; + Vec4V col2; + Vec4V col3; +}; + +PX_ALIGN_PREFIX(16) +struct VecU32V +{ + PxU32 u32[4]; + PX_FORCE_INLINE VecU32V() + { + } + PX_FORCE_INLINE VecU32V(PxU32 a, PxU32 b, PxU32 c, PxU32 d) + { + u32[0] = a; + u32[1] = b; + u32[2] = c; + u32[3] = d; + } +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct VecI32V +{ + PxI32 i32[4]; + PX_FORCE_INLINE VecI32V() + { + } + PX_FORCE_INLINE VecI32V(PxI32 a, PxI32 b, PxI32 c, PxI32 d) + { + i32[0] = a; + i32[1] = b; + i32[2] = c; + i32[3] = d; + } +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct VecI16V +{ + PxI16 i16[8]; + PX_FORCE_INLINE VecI16V() + { + } + PX_FORCE_INLINE VecI16V(PxI16 a, PxI16 b, PxI16 c, PxI16 d, PxI16 e, PxI16 f, PxI16 g, PxI16 h) + { + i16[0] = a; + i16[1] = b; + i16[2] = c; + i16[3] = d; + i16[4] = e; + i16[5] = f; + i16[6] = g; + i16[7] = h; + } +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct VecU16V +{ + union + { + PxU16 u16[8]; + PxI16 i16[8]; + }; + PX_FORCE_INLINE VecU16V() + { + } + PX_FORCE_INLINE VecU16V(PxU16 a, PxU16 b, PxU16 c, PxU16 d, PxU16 e, PxU16 f, PxU16 g, PxU16 h) + { + u16[0] = a; + u16[1] = b; + u16[2] = c; + u16[3] = d; + u16[4] = e; + u16[5] = f; + u16[6] = g; + u16[7] = h; + } +} PX_ALIGN_SUFFIX(16); + +#define FloatVArg FloatV & +#define Vec3VArg Vec3V & +#define Vec4VArg Vec4V & +#define BoolVArg BoolV & +#define VecU32VArg VecU32V & +#define VecI32VArg VecI32V & +#define VecU16VArg VecU16V & +#define VecI16VArg VecI16V & +#define QuatVArg QuatV & + +#define VecCrossV Vec3V + +typedef VecI32V VecShiftV; +#define VecShiftVArg VecShiftV & + +} // namespace aos +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathAoSScalarInline.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathAoSScalarInline.h new file mode 100644 index 000000000..d5290294e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathAoSScalarInline.h @@ -0,0 +1,2301 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC_MATH_AOS_SCALAR_INLINE_H +#define PX_VEC_MATH_AOS_SCALAR_INLINE_H + +#if COMPILE_VECTOR_INTRINSICS +#error Scalar version should not be included when using vector intrinsics. +#endif + +#if PX_GCC_FAMILY +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +namespace aos +{ + +#define BOOL_TO_U32(b) PxU32(- PxI32(b)) +#define TRUE_TO_U32 PxU32(-1) +#define FALSE_TO_U32 PxU32(0) + +#define BOOL_TO_U16(b) PxU16(- PxI32(b)) + +#define PX_VECMATH_ASSERT_ENABLED 0 + +#if PX_VECMATH_ASSERT_ENABLED +#define VECMATHAOS_ASSERT(x) { PX_ASSERT(x); } +#else +#define VECMATHAOS_ASSERT(x) +#endif + +///////////////////////////////////////////////////////////////////// +////INTERNAL USE ONLY AND TESTS +///////////////////////////////////////////////////////////////////// + +namespace internalScalarSimd +{ +PX_FORCE_INLINE PxF32 FStore(const FloatV a) +{ + return a.x; +} + +PX_FORCE_INLINE bool hasZeroElementInFloatV(const FloatV a) +{ + return (0 == a.x); +} + +PX_FORCE_INLINE bool hasZeroElementInVec3V(const Vec3V a) +{ + return (0 == a.x || 0 == a.y || 0 == a.z); +} + +PX_FORCE_INLINE bool hasZeroElementInVec4V(const Vec4V a) +{ + return (0 == a.x || 0 == a.y || 0 == a.z || 0 == a.w); +} +} + +namespace vecMathTests +{ +// PT: this function returns an invalid Vec3V (W!=0.0f) just for unit-testing 'isValidVec3V' +PX_FORCE_INLINE Vec3V getInvalidVec3V() +{ + Vec3V tmp; + tmp.x = tmp.y = tmp.z = 0.0f; + tmp.pad = 1.0f; + return tmp; +} + +PX_FORCE_INLINE bool allElementsEqualFloatV(const FloatV a, const FloatV b) +{ + return (a.x == b.x); +} + +PX_FORCE_INLINE bool allElementsEqualVec3V(const Vec3V a, const Vec3V b) +{ + return (a.x == b.x && a.y == b.y && a.z == b.z); +} + +PX_FORCE_INLINE bool allElementsEqualVec4V(const Vec4V a, const Vec4V b) +{ + return (a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w); +} + +PX_FORCE_INLINE bool allElementsEqualBoolV(const BoolV a, const BoolV b) +{ + return (a.ux == b.ux && a.uy == b.uy && a.uz == b.uz && a.uw == b.uw); +} + +PX_FORCE_INLINE bool allElementsEqualVecU32V(const VecU32V a, const VecU32V b) +{ + return (a.u32[0] == b.u32[0] && a.u32[1] == b.u32[1] && a.u32[2] == b.u32[2] && a.u32[3] == b.u32[3]); +} + +PX_FORCE_INLINE bool allElementsEqualVecI32V(const VecI32V a, const VecI32V b) +{ + return (a.i32[0] == b.i32[0] && a.i32[1] == b.i32[1] && a.i32[2] == b.i32[2] && a.i32[3] == b.i32[3]); +} + +#define VECMATH_AOS_EPSILON (1e-3f) + +PX_FORCE_INLINE bool allElementsNearEqualFloatV(const FloatV a, const FloatV b) +{ + const PxF32 cx = a.x - b.x; + return (cx > -VECMATH_AOS_EPSILON && cx < VECMATH_AOS_EPSILON); +} + +PX_FORCE_INLINE bool allElementsNearEqualVec3V(const Vec3V a, const Vec3V b) +{ + const PxF32 cx = a.x - b.x; + const PxF32 cy = a.y - b.y; + const PxF32 cz = a.z - b.z; + return (cx > -VECMATH_AOS_EPSILON && cx < VECMATH_AOS_EPSILON && cy > -VECMATH_AOS_EPSILON && + cy < VECMATH_AOS_EPSILON && cz > -VECMATH_AOS_EPSILON && cz < VECMATH_AOS_EPSILON); +} + +PX_FORCE_INLINE bool allElementsNearEqualVec4V(const Vec4V a, const Vec4V b) +{ + const PxF32 cx = a.x - b.x; + const PxF32 cy = a.y - b.y; + const PxF32 cz = a.z - b.z; + const PxF32 cw = a.w - b.w; + return (cx > -VECMATH_AOS_EPSILON && cx < VECMATH_AOS_EPSILON && cy > -VECMATH_AOS_EPSILON && + cy < VECMATH_AOS_EPSILON && cz > -VECMATH_AOS_EPSILON && cz < VECMATH_AOS_EPSILON && + cw > -VECMATH_AOS_EPSILON && cw < VECMATH_AOS_EPSILON); +} +} + +/////////////////////////////////////////////////////// + +PX_FORCE_INLINE bool isValidVec3V(const Vec3V a) +{ + return a.pad == 0.f; +} + +PX_FORCE_INLINE bool isFiniteFloatV(const FloatV a) +{ + return PxIsFinite(a.x); +} + +PX_FORCE_INLINE bool isFiniteVec3V(const Vec3V a) +{ + return PxIsFinite(a.x) && PxIsFinite(a.y) && PxIsFinite(a.z); +} + +PX_FORCE_INLINE bool isFiniteVec4V(const Vec4V a) +{ + return PxIsFinite(a.x) && PxIsFinite(a.y) && PxIsFinite(a.z) && PxIsFinite(a.w); +} + +///////////////////////////////////////////////////////////////////// +////VECTORISED FUNCTION IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE FloatV FLoad(const PxF32 f) +{ + return FloatV(f); +} + +PX_FORCE_INLINE Vec3V V3Load(const PxF32 f) +{ + return Vec3V(f, f, f); +} + +PX_FORCE_INLINE Vec4V V4Load(const PxF32 f) +{ + return Vec4V(f, f, f, f); +} + +PX_FORCE_INLINE BoolV BLoad(const bool f) +{ +#if PX_ARM + // SD: Android ARM builds fail if this is done with a cast. + // Might also fail because of something else but the select + // operator here seems to fix everything that failed in release builds. + return f ? BTTTT() : BFFFF(); +#else + return BoolV(BOOL_TO_U32(f), BOOL_TO_U32(f), BOOL_TO_U32(f), BOOL_TO_U32(f)); +#endif +} + +PX_FORCE_INLINE Vec3V V3LoadA(const PxVec3& f) +{ + return Vec3V(f.x, f.y, f.z); +} + +PX_FORCE_INLINE Vec3V V3LoadU(const PxVec3& f) +{ + return Vec3V(f.x, f.y, f.z); +} + +PX_FORCE_INLINE Vec3V V3LoadUnsafeA(const PxVec3& f) +{ + return Vec3V(f.x, f.y, f.z); +} + +PX_FORCE_INLINE Vec3V V3LoadA(const PxF32* const f) +{ + return Vec3V(f[0], f[1], f[2]); +} + +PX_FORCE_INLINE Vec3V V3LoadU(const PxF32* const f) +{ + return Vec3V(f[0], f[1], f[2]); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V(Vec4V f) +{ + return Vec3V(f.x, f.y, f.z); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V_WUndefined(const Vec4V v) +{ + return Vec3V(v.x, v.y, v.z); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_Vec3V(Vec3V f) +{ + return Vec4V(f.x, f.y, f.z, 0.0f); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_FloatV(FloatV f) +{ + return Vec4V(f.x, f.x, f.x, f.x); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_FloatV(FloatV f) +{ + return Vec3V(f.x, f.x, f.x); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_FloatV_WUndefined(FloatV f) +{ + return Vec3V(f.x, f.x, f.x); +} + +PX_FORCE_INLINE Vec4V V4LoadA(const PxF32* const f) +{ + return Vec4V(f[0], f[1], f[2], f[3]); +} + +PX_FORCE_INLINE void V4StoreA(const Vec4V a, PxF32* f) +{ + *reinterpret_cast(f) = a; +} + +PX_FORCE_INLINE void V4StoreU(const Vec4V a, PxF32* f) +{ + *reinterpret_cast(f) = *reinterpret_cast(&a.x); +} + +PX_FORCE_INLINE void BStoreA(const BoolV a, PxU32* f) +{ + *reinterpret_cast(f) = a; +} + +PX_FORCE_INLINE void U4StoreA(const VecU32V uv, PxU32* u) +{ + *reinterpret_cast(u) = uv; +} + +PX_FORCE_INLINE void I4StoreA(const VecI32V iv, PxI32* i) +{ + *reinterpret_cast(i) = iv; +} + +PX_FORCE_INLINE Vec4V V4LoadU(const PxF32* const f) +{ + return Vec4V(f[0], f[1], f[2], f[3]); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_PxVec3_WUndefined(const PxVec3& f) +{ + return Vec4V(f[0], f[1], f[2], 0.0f); +} + +PX_FORCE_INLINE BoolV BLoad(const bool* const f) +{ + return BoolV(BOOL_TO_U32(f[0]), BOOL_TO_U32(f[1]), BOOL_TO_U32(f[2]), BOOL_TO_U32(f[3])); +} + +PX_FORCE_INLINE void FStore(const FloatV a, PxF32* PX_RESTRICT f) +{ + *f = a.x; +} + +PX_FORCE_INLINE void V3StoreA(const Vec3V a, PxVec3& f) +{ + f = PxVec3(a.x, a.y, a.z); +} + +PX_FORCE_INLINE void V3StoreU(const Vec3V a, PxVec3& f) +{ + f = PxVec3(a.x, a.y, a.z); +} + +PX_FORCE_INLINE void Store_From_BoolV(const BoolV b, PxU32* b2) +{ + *b2 = b.ux; +} + +////////////////////////// +// FLOATV +////////////////////////// + +PX_FORCE_INLINE FloatV FZero() +{ + return FLoad(0.0f); +} + +PX_FORCE_INLINE FloatV FOne() +{ + return FLoad(1.0f); +} + +PX_FORCE_INLINE FloatV FHalf() +{ + return FLoad(0.5f); +} + +PX_FORCE_INLINE FloatV FEps() +{ + return FLoad(PX_EPS_REAL); +} + +PX_FORCE_INLINE FloatV FEps6() +{ + return FLoad(1e-6f); +} + +//! \cond +PX_FORCE_INLINE FloatV FMax() +{ + return FLoad(PX_MAX_REAL); +} +//! \endcond + +PX_FORCE_INLINE FloatV FNegMax() +{ + return FLoad(-PX_MAX_REAL); +} + +PX_FORCE_INLINE FloatV FNeg(const FloatV f) +{ + return FloatV(-f.x); +} + +PX_FORCE_INLINE FloatV FAdd(const FloatV a, const FloatV b) +{ + return FloatV(a.x + b.x); +} + +PX_FORCE_INLINE FloatV FSub(const FloatV a, const FloatV b) +{ + return FloatV(a.x - b.x); +} + +PX_FORCE_INLINE FloatV FMul(const FloatV a, const FloatV b) +{ + return FloatV(a.x * b.x); +} + +PX_FORCE_INLINE FloatV FDiv(const FloatV a, const FloatV b) +{ + VECMATHAOS_ASSERT(b.x != 0.0f); + return FloatV(a.x / b.x); +} + +PX_FORCE_INLINE FloatV FDivFast(const FloatV a, const FloatV b) +{ + VECMATHAOS_ASSERT(b.x != 0.0f); + return FloatV(a.x / b.x); +} + +PX_FORCE_INLINE FloatV FRecip(const FloatV a) +{ + VECMATHAOS_ASSERT(a.x != 0.0f); + return 1.0f / a.x; +} + +PX_FORCE_INLINE FloatV FRecipFast(const FloatV a) +{ + VECMATHAOS_ASSERT(a.x != 0.0f); + return 1.0f / a.x; +} + +PX_FORCE_INLINE FloatV FRsqrt(const FloatV a) +{ + VECMATHAOS_ASSERT(a.x != 0.0f); + return PxRecipSqrt(a.x); +} + +PX_FORCE_INLINE FloatV FSqrt(const FloatV a) +{ + return PxSqrt(a.x); +} + +PX_FORCE_INLINE FloatV FRsqrtFast(const FloatV a) +{ + VECMATHAOS_ASSERT(a.x != 0.0f); + return PxRecipSqrt(a.x); +} + +PX_FORCE_INLINE FloatV FScaleAdd(const FloatV a, const FloatV b, const FloatV c) +{ + return FAdd(FMul(a, b), c); +} + +PX_FORCE_INLINE FloatV FNegScaleSub(const FloatV a, const FloatV b, const FloatV c) +{ + return FSub(c, FMul(a, b)); +} + +PX_FORCE_INLINE FloatV FAbs(const FloatV a) +{ + return FloatV(PxAbs(a.x)); +} + +PX_FORCE_INLINE FloatV FSel(const BoolV c, const FloatV a, const FloatV b) +{ + return FloatV(c.ux ? a.x : b.x); +} + +PX_FORCE_INLINE BoolV FIsGrtr(const FloatV a, const FloatV b) +{ + return BLoad(a.x > b.x); +} + +PX_FORCE_INLINE BoolV FIsGrtrOrEq(const FloatV a, const FloatV b) +{ + return BLoad(a.x >= b.x); +} + +PX_FORCE_INLINE BoolV FIsEq(const FloatV a, const FloatV b) +{ + return BLoad(a.x == b.x); +} + +PX_FORCE_INLINE FloatV FMax(const FloatV a, const FloatV b) +{ + return (a.x > b.x ? FloatV(a.x) : FloatV(b.x)); +} + +PX_FORCE_INLINE FloatV FMin(const FloatV a, const FloatV b) +{ + return (a.x > b.x ? FloatV(b.x) : FloatV(a.x)); +} + +PX_FORCE_INLINE FloatV FClamp(const FloatV a, const FloatV minV, const FloatV maxV) +{ + return FMax(FMin(a, maxV), minV); +} + +PX_FORCE_INLINE PxU32 FAllGrtr(const FloatV a, const FloatV b) +{ + return BOOL_TO_U32(a.x > b.x); +} + +PX_FORCE_INLINE PxU32 FAllGrtrOrEq(const FloatV a, const FloatV b) +{ + return BOOL_TO_U32(a.x >= b.x); +} +PX_FORCE_INLINE PxU32 FAllEq(const FloatV a, const FloatV b) +{ + return BOOL_TO_U32(a.x == b.x); +} + +PX_FORCE_INLINE FloatV FRound(const FloatV a) +{ + return floorf(a.x + 0.5f); +} + +PX_FORCE_INLINE FloatV FSin(const FloatV a) +{ + return sinf(a.x); +} + +PX_FORCE_INLINE FloatV FCos(const FloatV a) +{ + return cosf(a.x); +} + +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV min, const FloatV max) +{ + return BOOL_TO_U32(a.x > max.x || a.x < min.x); +} + +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV min, const FloatV max) +{ + return BOOL_TO_U32(a.x >= min.x && a.x <= max.x); +} + +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV bounds) +{ + return FOutOfBounds(a, FNeg(bounds), bounds); +} + +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV bounds) +{ + return FInBounds(a, FNeg(bounds), bounds); +} + +///////////////////// +// VEC3V +///////////////////// + +PX_FORCE_INLINE Vec3V V3Splat(const FloatV f) +{ + return Vec3V(f.x, f.x, f.x); +} + +PX_FORCE_INLINE Vec3V V3Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z) +{ + return Vec3V(x.x, y.x, z.x); +} + +PX_FORCE_INLINE Vec3V V3UnitX() +{ + return Vec3V(1.0f, 0.0f, 0.0f); +} + +PX_FORCE_INLINE Vec3V V3UnitY() +{ + return Vec3V(0.0f, 1.0f, 0.0f); +} + +PX_FORCE_INLINE Vec3V V3UnitZ() +{ + return Vec3V(0.0f, 0.0f, 1.0f); +} + +PX_FORCE_INLINE FloatV V3GetX(const Vec3V f) +{ + return FloatV(f.x); +} + +PX_FORCE_INLINE FloatV V3GetY(const Vec3V f) +{ + return FloatV(f.y); +} + +PX_FORCE_INLINE FloatV V3GetZ(const Vec3V f) +{ + return FloatV(f.z); +} + +PX_FORCE_INLINE Vec3V V3SetX(const Vec3V v, const FloatV f) +{ + return Vec3V(f.x, v.y, v.z); +} + +PX_FORCE_INLINE Vec3V V3SetY(const Vec3V v, const FloatV f) +{ + return Vec3V(v.x, f.x, v.z); +} + +PX_FORCE_INLINE Vec3V V3SetZ(const Vec3V v, const FloatV f) +{ + return Vec3V(v.x, v.y, f.x); +} + +PX_FORCE_INLINE Vec3V V3ColX(const Vec3V a, const Vec3V b, const Vec3V c) +{ + return Vec3V(a.x, b.x, c.x); +} + +PX_FORCE_INLINE Vec3V V3ColY(const Vec3V a, const Vec3V b, const Vec3V c) +{ + return Vec3V(a.y, b.y, c.y); +} + +PX_FORCE_INLINE Vec3V V3ColZ(const Vec3V a, const Vec3V b, const Vec3V c) +{ + return Vec3V(a.z, b.z, c.z); +} + +PX_FORCE_INLINE Vec3V V3Zero() +{ + return V3Load(0.0f); +} + +PX_FORCE_INLINE Vec3V V3One() +{ + return V3Load(1.0f); +} + +PX_FORCE_INLINE Vec3V V3Eps() +{ + return V3Load(PX_EPS_REAL); +} + +PX_FORCE_INLINE Vec3V V3Neg(const Vec3V c) +{ + return Vec3V(-c.x, -c.y, -c.z); +} + +PX_FORCE_INLINE Vec3V V3Add(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.x + b.x, a.y + b.y, a.z + b.z); +} + +PX_FORCE_INLINE Vec3V V3Sub(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.x - b.x, a.y - b.y, a.z - b.z); +} + +PX_FORCE_INLINE Vec3V V3Scale(const Vec3V a, const FloatV b) +{ + return Vec3V(a.x * b.x, a.y * b.x, a.z * b.x); +} + +PX_FORCE_INLINE Vec3V V3Mul(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.x * b.x, a.y * b.y, a.z * b.z); +} + +PX_FORCE_INLINE Vec3V V3ScaleInv(const Vec3V a, const FloatV b) +{ + const PxF32 bInv = 1.0f / b.x; + return Vec3V(a.x * bInv, a.y * bInv, a.z * bInv); +} + +PX_FORCE_INLINE Vec3V V3Div(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.x / b.x, a.y / b.y, a.z / b.z); +} + +PX_FORCE_INLINE Vec3V V3ScaleInvFast(const Vec3V a, const FloatV b) +{ + const PxF32 bInv = 1.0f / b.x; + return Vec3V(a.x * bInv, a.y * bInv, a.z * bInv); +} + +PX_FORCE_INLINE Vec3V V3DivFast(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.x / b.x, a.y / b.y, a.z / b.z); +} + +PX_FORCE_INLINE Vec3V V3Recip(const Vec3V a) +{ + return Vec3V(1.0f / a.x, 1.0f / a.y, 1.0f / a.z); +} + +PX_FORCE_INLINE Vec3V V3RecipFast(const Vec3V a) +{ + return Vec3V(1.0f / a.x, 1.0f / a.y, 1.0f / a.z); +} + +PX_FORCE_INLINE Vec3V V3Rsqrt(const Vec3V a) +{ + return Vec3V(PxRecipSqrt(a.x), PxRecipSqrt(a.y), PxRecipSqrt(a.z)); +} + +PX_FORCE_INLINE Vec3V V3RsqrtFast(const Vec3V a) +{ + return Vec3V(PxRecipSqrt(a.x), PxRecipSqrt(a.y), PxRecipSqrt(a.z)); +} + +PX_FORCE_INLINE Vec3V V3ScaleAdd(const Vec3V a, const FloatV b, const Vec3V c) +{ + return V3Add(V3Scale(a, b), c); +} + +PX_FORCE_INLINE Vec3V V3NegScaleSub(const Vec3V a, const FloatV b, const Vec3V c) +{ + return V3Sub(c, V3Scale(a, b)); +} + +PX_FORCE_INLINE Vec3V V3MulAdd(const Vec3V a, const Vec3V b, const Vec3V c) +{ + return V3Add(V3Mul(a, b), c); +} + +PX_FORCE_INLINE Vec3V V3NegMulSub(const Vec3V a, const Vec3V b, const Vec3V c) +{ + return V3Sub(c, V3Mul(a, b)); +} + +PX_FORCE_INLINE FloatV V3Dot(const Vec3V a, const Vec3V b) +{ + return FloatV(a.x * b.x + a.y * b.y + a.z * b.z); +} + +PX_FORCE_INLINE VecCrossV V3PrepareCross(const Vec3VArg normal) +{ + return normal; +} + +PX_FORCE_INLINE Vec3V V3Cross(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); +} + +PX_FORCE_INLINE FloatV V3Length(const Vec3V a) +{ + return FloatV(PxSqrt(a.x * a.x + a.y * a.y + a.z * a.z)); +} + +PX_FORCE_INLINE FloatV V3LengthSq(const Vec3V a) +{ + return FloatV(a.x * a.x + a.y * a.y + a.z * a.z); +} + +PX_FORCE_INLINE Vec3V V3Normalize(const Vec3V a) +{ + VECMATHAOS_ASSERT(a.x != 0 || a.y != 0 || a.z != 0); + const PxF32 lengthInv = 1.0f / PxSqrt(a.x * a.x + a.y * a.y + a.z * a.z); + return Vec3V(a.x * lengthInv, a.y * lengthInv, a.z * lengthInv); +} + +PX_FORCE_INLINE Vec3V V3NormalizeSafe(const Vec3V a, const Vec3V unsafeReturnValue) +{ + const PxF32 length = PxSqrt(a.x * a.x + a.y * a.y + a.z * a.z); + if(PX_EPS_REAL >= length) + { + return unsafeReturnValue; + } + else + { + const PxF32 lengthInv = 1.0f / length; + return Vec3V(a.x * lengthInv, a.y * lengthInv, a.z * lengthInv); + } +} + +PX_FORCE_INLINE Vec3V V3NormalizeFast(const Vec3V a) +{ + VECMATHAOS_ASSERT(a.x != 0 || a.y != 0 || a.z != 0); + const PxF32 lengthInv = 1.0f / PxSqrt(a.x * a.x + a.y * a.y + a.z * a.z); + return Vec3V(a.x * lengthInv, a.y * lengthInv, a.z * lengthInv); +} + +PX_FORCE_INLINE Vec3V V3Sel(const BoolV c, const Vec3V a, const Vec3V b) +{ + return Vec3V(c.ux ? a.x : b.x, c.uy ? a.y : b.y, c.uz ? a.z : b.z); +} + +PX_FORCE_INLINE BoolV V3IsGrtr(const Vec3V a, const Vec3V b) +{ + return BoolV(BOOL_TO_U32(a.x > b.x), BOOL_TO_U32(a.y > b.y), BOOL_TO_U32(a.z > b.z), FALSE_TO_U32); +} + +PX_FORCE_INLINE BoolV V3IsGrtrOrEq(const Vec3V a, const Vec3V b) +{ + return BoolV(BOOL_TO_U32(a.x >= b.x), BOOL_TO_U32(a.y >= b.y), BOOL_TO_U32(a.z >= b.z), TRUE_TO_U32); +} + +PX_FORCE_INLINE BoolV V3IsEq(const Vec3V a, const Vec3V b) +{ + return BoolV(BOOL_TO_U32(a.x == b.x), BOOL_TO_U32(a.y == b.y), BOOL_TO_U32(a.z == b.z), TRUE_TO_U32); +} + +PX_FORCE_INLINE Vec3V V3Max(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y, a.z > b.z ? a.z : b.z); +} + +PX_FORCE_INLINE Vec3V V3Min(const Vec3V a, const Vec3V b) +{ + return Vec3V(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y, a.z < b.z ? a.z : b.z); +} + +PX_FORCE_INLINE FloatV V3ExtractMax(const Vec3V a) +{ + const PxF32 t0 = (a.x >= a.y) ? a.x : a.y; + return t0 >= a.z ? t0 : a.z; +} + +PX_FORCE_INLINE FloatV V3ExtractMin(const Vec3V a) +{ + const PxF32 t0 = (a.x <= a.y) ? a.x : a.y; + return t0 <= a.z ? t0 : a.z; +} + +// return (a >= 0.0f) ? 1.0f : -1.0f; +PX_FORCE_INLINE Vec3V V3Sign(const Vec3V a) +{ + return Vec3V((a.x >= 0.f ? 1.f : -1.f), (a.y >= 0.f ? 1.f : -1.f), (a.z >= 0.f ? 1.f : -1.f)); +} + +PX_FORCE_INLINE Vec3V V3Clamp(const Vec3V a, const Vec3V minV, const Vec3V maxV) +{ + return V3Max(V3Min(a, maxV), minV); +} + +PX_FORCE_INLINE Vec3V V3Abs(const Vec3V a) +{ + return V3Max(a, V3Neg(a)); +} + +PX_FORCE_INLINE PxU32 V3AllGrtr(const Vec3V a, const Vec3V b) +{ + return BOOL_TO_U32((a.x > b.x) & (a.y > b.y) & (a.z > b.z)); +} + +PX_FORCE_INLINE PxU32 V3AllGrtrOrEq(const Vec3V a, const Vec3V b) +{ + return BOOL_TO_U32((a.x >= b.x) & (a.y >= b.y) & (a.z >= b.z)); +} + +PX_FORCE_INLINE PxU32 V3AllEq(const Vec3V a, const Vec3V b) +{ + return BOOL_TO_U32((a.x == b.x) & (a.y == b.y) & (a.z == b.z)); +} + +PX_FORCE_INLINE Vec3V V3Round(const Vec3V a) +{ + return Vec3V(floorf(a.x + 0.5f), floorf(a.y + 0.5f), floorf(a.z + 0.5f)); +} + +PX_FORCE_INLINE Vec3V V3Sin(const Vec3V a) +{ + return Vec3V(sinf(a.x), sinf(a.y), sinf(a.z)); +} + +PX_FORCE_INLINE Vec3V V3Cos(const Vec3V a) +{ + return Vec3V(cosf(a.x), cosf(a.y), cosf(a.z)); +} + +PX_FORCE_INLINE Vec3V V3PermYZZ(const Vec3V a) +{ + return Vec3V(a.y, a.z, a.z); +} + +PX_FORCE_INLINE Vec3V V3PermXYX(const Vec3V a) +{ + return Vec3V(a.x, a.y, a.x); +} + +PX_FORCE_INLINE Vec3V V3PermYZX(const Vec3V a) +{ + return Vec3V(a.y, a.z, a.x); +} + +PX_FORCE_INLINE Vec3V V3PermZXY(const Vec3V a) +{ + return Vec3V(a.z, a.x, a.y); +} + +PX_FORCE_INLINE Vec3V V3PermZZY(const Vec3V a) +{ + return Vec3V(a.z, a.z, a.y); +} + +PX_FORCE_INLINE Vec3V V3PermYXX(const Vec3V a) +{ + return Vec3V(a.y, a.x, a.x); +} + +PX_FORCE_INLINE Vec3V V3Perm_Zero_1Z_0Y(const Vec3V v0, const Vec3V v1) +{ + return Vec3V(0.0f, v1.z, v0.y); +} + +PX_FORCE_INLINE Vec3V V3Perm_0Z_Zero_1X(const Vec3V v0, const Vec3V v1) +{ + return Vec3V(v0.z, 0.0f, v1.x); +} + +PX_FORCE_INLINE Vec3V V3Perm_1Y_0X_Zero(const Vec3V v0, const Vec3V v1) +{ + return Vec3V(v1.y, v0.x, 0.0f); +} + +PX_FORCE_INLINE FloatV V3SumElems(const Vec3V a) +{ + return FloatV(a.x + a.y + a.z); +} + +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V min, const Vec3V max) +{ + return BOOL_TO_U32(a.x > max.x || a.y > max.y || a.z > max.z || a.x < min.x || a.y < min.y || a.z < min.z); +} + +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V min, const Vec3V max) +{ + return BOOL_TO_U32(a.x <= max.x && a.y <= max.y && a.z <= max.z && a.x >= min.x && a.y >= min.y && a.z >= min.z); +} + +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V bounds) +{ + return V3OutOfBounds(a, V3Neg(bounds), bounds); +} + +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V bounds) +{ + return V3InBounds(a, V3Neg(bounds), bounds); +} + +PX_FORCE_INLINE void V3Transpose(Vec3V& col0, Vec3V& col1, Vec3V& col2) +{ + const PxF32 t01 = col0.y, t02 = col0.z, t12 = col1.z; + col0.y = col1.x; + col0.z = col2.x; + col1.z = col2.y; + col1.x = t01; + col2.x = t02; + col2.y = t12; +} + +///////////////////////// +// VEC4V +///////////////////////// + +PX_FORCE_INLINE Vec4V V4Splat(const FloatV f) +{ + return Vec4V(f.x, f.x, f.x, f.x); +} + +PX_FORCE_INLINE Vec4V V4Merge(const FloatV* const floatVArray) +{ + return Vec4V(floatVArray[0].x, floatVArray[1].x, floatVArray[2].x, floatVArray[3].x); +} + +PX_FORCE_INLINE Vec4V V4Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z, const FloatVArg w) +{ + return Vec4V(x.x, y.x, z.x, w.x); +} + +PX_FORCE_INLINE Vec4V V4MergeW(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + return Vec4V(x.w, y.w, z.w, w.w); +} + +PX_FORCE_INLINE Vec4V V4MergeZ(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + return Vec4V(x.z, y.z, z.z, w.z); +} + +PX_FORCE_INLINE Vec4V V4MergeY(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + return Vec4V(x.y, y.y, z.y, w.y); +} + +PX_FORCE_INLINE Vec4V V4MergeX(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + return Vec4V(x.x, y.x, z.x, w.x); +} + +PX_FORCE_INLINE Vec4V V4UnpackXY(const Vec4VArg a, const Vec4VArg b) +{ + return Vec4V(a.x, b.x, a.y, b.y); +} + +PX_FORCE_INLINE Vec4V V4UnpackZW(const Vec4VArg a, const Vec4VArg b) +{ + return Vec4V(a.z, b.z, a.w, b.w); +} + +PX_FORCE_INLINE Vec4V V4UnitX() +{ + return Vec4V(1.0f, 0.0f, 0.0f, 0.0f); +} + +PX_FORCE_INLINE Vec4V V4UnitY() +{ + return Vec4V(0.0f, 1.0f, 0.0f, 0.0f); +} + +PX_FORCE_INLINE Vec4V V4UnitZ() +{ + return Vec4V(0.0f, 0.0f, 1.0f, 0.0f); +} + +PX_FORCE_INLINE Vec4V V4UnitW() +{ + return Vec4V(0.0f, 0.0f, 0.0f, 1.0f); +} + +PX_FORCE_INLINE FloatV V4GetX(const Vec4V f) +{ + return FloatV(f.x); +} + +PX_FORCE_INLINE FloatV V4GetY(const Vec4V f) +{ + return FloatV(f.y); +} + +PX_FORCE_INLINE FloatV V4GetZ(const Vec4V f) +{ + return FloatV(f.z); +} + +PX_FORCE_INLINE FloatV V4GetW(const Vec4V f) +{ + return FloatV(f.w); +} + +PX_FORCE_INLINE Vec4V V4SetX(const Vec4V v, const FloatV f) +{ + return Vec4V(f.x, v.y, v.z, v.w); +} + +PX_FORCE_INLINE Vec4V V4SetY(const Vec4V v, const FloatV f) +{ + return Vec4V(v.x, f.x, v.z, v.w); +} + +PX_FORCE_INLINE Vec4V V4SetZ(const Vec4V v, const FloatV f) +{ + return Vec4V(v.x, v.y, f.x, v.w); +} + +PX_FORCE_INLINE Vec4V V4SetW(const Vec4V v, const FloatV f) +{ + return Vec4V(v.x, v.y, v.z, f.x); +} + +PX_FORCE_INLINE Vec4V V4SetW(const Vec3V v, const FloatV f) +{ + return Vec4V(v.x, v.y, v.z, f.x); +} + +PX_FORCE_INLINE Vec4V V4ClearW(const Vec4V v) +{ + return Vec4V(v.x, v.y, v.z, 0.0f); +} + +PX_FORCE_INLINE Vec4V V4PermYXWZ(const Vec4V v) +{ + return Vec4V(v.y, v.x, v.w, v.z); +} + +PX_FORCE_INLINE Vec4V V4PermXZXZ(const Vec4V v) +{ + return Vec4V(v.x, v.z, v.x, v.z); +} + +PX_FORCE_INLINE Vec4V V4PermYWYW(const Vec4V v) +{ + return Vec4V(v.y, v.w, v.y, v.w); +} + +PX_FORCE_INLINE Vec4V V4PermYZXW(const Vec4V v) +{ + return Vec4V(v.y, v.z, v.x, v.w); +} + +PX_FORCE_INLINE Vec4V V4PermZWXY(const Vec4V v) +{ + return Vec4V(v.z, v.w, v.x, v.y); +} + +template +PX_FORCE_INLINE Vec4V V4Perm(const Vec4V v) +{ + const PxF32 f[4] = { v.x, v.y, v.z, v.w }; + return Vec4V(f[_x], f[_y], f[_z], f[_w]); +} + +PX_FORCE_INLINE Vec4V V4Zero() +{ + return V4Load(0.0f); +} + +PX_FORCE_INLINE Vec4V V4One() +{ + return V4Load(1.0f); +} + +PX_FORCE_INLINE Vec4V V4Eps() +{ + return V4Load(PX_EPS_REAL); +} + +PX_FORCE_INLINE Vec4V V4Neg(const Vec4V c) +{ + return Vec4V(-c.x, -c.y, -c.z, -c.w); +} + +PX_FORCE_INLINE Vec4V V4Add(const Vec4V a, const Vec4V b) +{ + return Vec4V(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); +} + +PX_FORCE_INLINE Vec4V V4Sub(const Vec4V a, const Vec4V b) +{ + return Vec4V(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); +} + +PX_FORCE_INLINE Vec4V V4Scale(const Vec4V a, const FloatV b) +{ + return Vec4V(a.x * b.x, a.y * b.x, a.z * b.x, a.w * b.x); +} + +PX_FORCE_INLINE Vec4V V4Mul(const Vec4V a, const Vec4V b) +{ + return Vec4V(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); +} + +PX_FORCE_INLINE Vec4V V4ScaleInv(const Vec4V a, const FloatV b) +{ + const PxF32 bInv = 1.0f / b.x; + return Vec4V(a.x * bInv, a.y * bInv, a.z * bInv, a.w * bInv); +} + +PX_FORCE_INLINE Vec4V V4Div(const Vec4V a, const Vec4V b) +{ + VECMATHAOS_ASSERT(b.x != 0 && b.y != 0 && b.z != 0 && b.w != 0); + return Vec4V(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); +} + +PX_FORCE_INLINE Vec4V V4ScaleInvFast(const Vec4V a, const FloatV b) +{ + const PxF32 bInv = 1.0f / b.x; + return Vec4V(a.x * bInv, a.y * bInv, a.z * bInv, a.w * bInv); +} + +PX_FORCE_INLINE Vec4V V4DivFast(const Vec4V a, const Vec4V b) +{ + return Vec4V(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); +} + +PX_FORCE_INLINE Vec4V V4Recip(const Vec4V a) +{ + return Vec4V(1.0f / a.x, 1.0f / a.y, 1.0f / a.z, 1.0f / a.w); +} + +PX_FORCE_INLINE Vec4V V4RecipFast(const Vec4V a) +{ + return Vec4V(1.0f / a.x, 1.0f / a.y, 1.0f / a.z, 1.0f / a.w); +} + +PX_FORCE_INLINE Vec4V V4Rsqrt(const Vec4V a) +{ + return Vec4V(PxRecipSqrt(a.x), PxRecipSqrt(a.y), PxRecipSqrt(a.z), PxRecipSqrt(a.w)); +} + +PX_FORCE_INLINE Vec4V V4RsqrtFast(const Vec4V a) +{ + return Vec4V(PxRecipSqrt(a.x), PxRecipSqrt(a.y), PxRecipSqrt(a.z), PxRecipSqrt(a.w)); +} + +PX_FORCE_INLINE Vec4V V4Sqrt(const Vec4V a) +{ + return Vec4V(PxSqrt(a.x), PxSqrt(a.y), PxSqrt(a.z), PxSqrt(a.w)); +} + +PX_FORCE_INLINE Vec4V V4ScaleAdd(const Vec4V a, const FloatV b, const Vec4V c) +{ + return V4Add(V4Scale(a, b), c); +} + +PX_FORCE_INLINE Vec4V V4NegScaleSub(const Vec4V a, const FloatV b, const Vec4V c) +{ + return V4Sub(c, V4Scale(a, b)); +} + +PX_FORCE_INLINE Vec4V V4MulAdd(const Vec4V a, const Vec4V b, const Vec4V c) +{ + return V4Add(V4Mul(a, b), c); +} + +PX_FORCE_INLINE Vec4V V4NegMulSub(const Vec4V a, const Vec4V b, const Vec4V c) +{ + return V4Sub(c, V4Mul(a, b)); +} + +PX_FORCE_INLINE FloatV V4SumElements(const Vec4V a) +{ + return FloatV(a.x + a.y + a.z + a.w); +} + +PX_FORCE_INLINE FloatV V4Dot(const Vec4V a, const Vec4V b) +{ + return FloatV(a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w); +} + +PX_FORCE_INLINE FloatV V4Dot3(const Vec4V a, const Vec4V b) +{ + return FloatV(a.x * b.x + a.y * b.y + a.z * b.z); +} + +PX_FORCE_INLINE Vec4V V4Cross(const Vec4V a, const Vec4V b) +{ + return Vec4V(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x, 0.0f); +} + +PX_FORCE_INLINE FloatV V4Length(const Vec4V a) +{ + return FloatV(PxSqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w)); +} + +PX_FORCE_INLINE FloatV V4LengthSq(const Vec4V a) +{ + return V4Dot(a, a); +} + +PX_FORCE_INLINE Vec4V V4Normalize(const Vec4V a) +{ + VECMATHAOS_ASSERT(0 != a.x || 0 != a.y || 0 != a.z || 0 != a.w); + const FloatV length = FloatV(V4Length(a)); + return V4ScaleInv(a, length); +} + +PX_FORCE_INLINE Vec4V V4NormalizeSafe(const Vec4V a, const Vec4V unsafeReturnValue) +{ + const FloatV length = FloatV(V4Length(a)); + if(PX_EPS_REAL >= length.x) + { + return unsafeReturnValue; + } + else + { + return V4ScaleInv(a, length); + } +} +PX_FORCE_INLINE Vec4V V4NormalizeFast(const Vec4V a) +{ + VECMATHAOS_ASSERT(0 != a.x || 0 != a.y || 0 != a.z || 0 != a.w); + const FloatV length = FloatV(V4Length(a)); + return V4ScaleInv(a, length); +} + +PX_FORCE_INLINE Vec4V V4Sel(const BoolV c, const Vec4V a, const Vec4V b) +{ + return Vec4V(c.ux ? a.x : b.x, c.uy ? a.y : b.y, c.uz ? a.z : b.z, c.uw ? a.w : b.w); +} + +PX_FORCE_INLINE BoolV V4IsGrtr(const Vec4V a, const Vec4V b) +{ + return BoolV(BOOL_TO_U32(a.x > b.x), BOOL_TO_U32(a.y > b.y), BOOL_TO_U32(a.z > b.z), BOOL_TO_U32(a.w > b.w)); +} + +PX_FORCE_INLINE BoolV V4IsGrtrOrEq(const Vec4V a, const Vec4V b) +{ + return BoolV(BOOL_TO_U32(a.x >= b.x), BOOL_TO_U32(a.y >= b.y), BOOL_TO_U32(a.z >= b.z), BOOL_TO_U32(a.w >= b.w)); +} + +PX_FORCE_INLINE BoolV V4IsEq(const Vec4V a, const Vec4V b) +{ + return BoolV(BOOL_TO_U32(a.x == b.x), BOOL_TO_U32(a.y == b.y), BOOL_TO_U32(a.z == b.z), BOOL_TO_U32(a.w == b.w)); +} + +PX_FORCE_INLINE Vec4V V4Max(const Vec4V a, const Vec4V b) +{ + return Vec4V(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y, a.z > b.z ? a.z : b.z, a.w > b.w ? a.w : b.w); +} + +PX_FORCE_INLINE Vec4V V4Min(const Vec4V a, const Vec4V b) +{ + return Vec4V(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y, a.z < b.z ? a.z : b.z, a.w < b.w ? a.w : b.w); +} + +PX_FORCE_INLINE FloatV V4ExtractMax(const Vec4V a) +{ + const PxF32 t0 = (a.x >= a.y) ? a.x : a.y; + const PxF32 t1 = (a.z >= a.w) ? a.x : a.w; + return t0 >= t1 ? t0 : t1; +} + +PX_FORCE_INLINE FloatV V4ExtractMin(const Vec4V a) +{ + const PxF32 t0 = (a.x <= a.y) ? a.x : a.y; + const PxF32 t1 = (a.z <= a.w) ? a.x : a.w; + return t0 <= t1 ? t0 : t1; +} + +PX_FORCE_INLINE Vec4V V4Clamp(const Vec4V a, const Vec4V minV, const Vec4V maxV) +{ + return V4Max(V4Min(a, maxV), minV); +} + +PX_FORCE_INLINE Vec4V V4Round(const Vec4V a) +{ + return Vec4V(floorf(a.x + 0.5f), floorf(a.y + 0.5f), floorf(a.z + 0.5f), floorf(a.w + 0.5f)); +} + +PX_FORCE_INLINE Vec4V V4Sin(const Vec4V a) +{ + return Vec4V(sinf(a.x), sinf(a.y), sinf(a.z), sinf(a.w)); +} + +PX_FORCE_INLINE Vec4V V4Cos(const Vec4V a) +{ + return Vec4V(cosf(a.x), cosf(a.y), cosf(a.z), cosf(a.w)); +} + +PX_FORCE_INLINE PxU32 V4AllGrtr(const Vec4V a, const Vec4V b) +{ + return BOOL_TO_U32((a.x > b.x) & (a.y > b.y) & (a.z > b.z) & (a.w > b.w)); +} + +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq(const Vec4V a, const Vec4V b) +{ + return BOOL_TO_U32((a.x >= b.x) & (a.y >= b.y) & (a.z >= b.z) & (a.w >= b.w)); +} + +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq3(const Vec4V a, const Vec4V b) +{ + return BOOL_TO_U32((a.x >= b.x) & (a.y >= b.y) & (a.z >= b.z)); +} + +PX_FORCE_INLINE PxU32 V4AllEq(const Vec4V a, const Vec4V b) +{ + return BOOL_TO_U32((a.x == b.x) & (a.y == b.y) & (a.z == b.z) & (a.w == b.w)); +} + +PX_FORCE_INLINE PxU32 V4AnyGrtr3(const Vec4V a, const Vec4V b) +{ + return BOOL_TO_U32((a.x > b.x) | (a.y > b.y) | (a.z > b.z)); +} + +PX_FORCE_INLINE void V4Transpose(Vec4V& col0, Vec4V& col1, Vec4V& col2, Vec4V& col3) +{ + const PxF32 t01 = col0.y, t02 = col0.z, t03 = col0.w; + const PxF32 t12 = col1.z, t13 = col1.w; + const PxF32 t23 = col2.w; + col0.y = col1.x; + col0.z = col2.x; + col0.w = col3.x; + col1.z = col2.y; + col1.w = col3.y; + col2.w = col3.z; + col1.x = t01; + col2.x = t02; + col3.x = t03; + col2.y = t12; + col3.y = t13; + col3.z = t23; +} + +PX_FORCE_INLINE BoolV BFFFF() +{ + return BoolV(FALSE_TO_U32, FALSE_TO_U32, FALSE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BFFFT() +{ + return BoolV(FALSE_TO_U32, FALSE_TO_U32, FALSE_TO_U32, TRUE_TO_U32); +} +PX_FORCE_INLINE BoolV BFFTF() +{ + return BoolV(FALSE_TO_U32, FALSE_TO_U32, TRUE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BFFTT() +{ + return BoolV(FALSE_TO_U32, FALSE_TO_U32, TRUE_TO_U32, TRUE_TO_U32); +} +PX_FORCE_INLINE BoolV BFTFF() +{ + return BoolV(FALSE_TO_U32, TRUE_TO_U32, FALSE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BFTFT() +{ + return BoolV(FALSE_TO_U32, TRUE_TO_U32, FALSE_TO_U32, TRUE_TO_U32); +} +PX_FORCE_INLINE BoolV BFTTF() +{ + return BoolV(FALSE_TO_U32, TRUE_TO_U32, TRUE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BFTTT() +{ + return BoolV(FALSE_TO_U32, TRUE_TO_U32, TRUE_TO_U32, TRUE_TO_U32); +} +PX_FORCE_INLINE BoolV BTFFF() +{ + return BoolV(TRUE_TO_U32, FALSE_TO_U32, FALSE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BTFFT() +{ + return BoolV(TRUE_TO_U32, FALSE_TO_U32, FALSE_TO_U32, TRUE_TO_U32); +} +PX_FORCE_INLINE BoolV BTFTF() +{ + return BoolV(TRUE_TO_U32, FALSE_TO_U32, TRUE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BTFTT() +{ + return BoolV(TRUE_TO_U32, FALSE_TO_U32, TRUE_TO_U32, TRUE_TO_U32); +} +PX_FORCE_INLINE BoolV BTTFF() +{ + return BoolV(TRUE_TO_U32, TRUE_TO_U32, FALSE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BTTFT() +{ + return BoolV(TRUE_TO_U32, TRUE_TO_U32, FALSE_TO_U32, TRUE_TO_U32); +} +PX_FORCE_INLINE BoolV BTTTF() +{ + return BoolV(TRUE_TO_U32, TRUE_TO_U32, TRUE_TO_U32, FALSE_TO_U32); +} +PX_FORCE_INLINE BoolV BTTTT() +{ + return BoolV(TRUE_TO_U32, TRUE_TO_U32, TRUE_TO_U32, TRUE_TO_U32); +} + +PX_FORCE_INLINE BoolV BXMask() +{ + return BTFFF(); +} +PX_FORCE_INLINE BoolV BYMask() +{ + return BFTFF(); +} +PX_FORCE_INLINE BoolV BZMask() +{ + return BFFTF(); +} +PX_FORCE_INLINE BoolV BWMask() +{ + return BFFFT(); +} + +PX_FORCE_INLINE BoolV BGetX(const BoolV a) +{ + return BoolV(a.ux, a.ux, a.ux, a.ux); +} + +PX_FORCE_INLINE BoolV BGetY(const BoolV a) +{ + return BoolV(a.uy, a.uy, a.uy, a.uy); +} + +PX_FORCE_INLINE BoolV BGetZ(const BoolV a) +{ + return BoolV(a.uz, a.uz, a.uz, a.uz); +} + +PX_FORCE_INLINE BoolV BGetW(const BoolV a) +{ + return BoolV(a.uw, a.uw, a.uw, a.uw); +} + +PX_FORCE_INLINE BoolV BSetX(const BoolV v, const BoolV f) +{ + return BoolV(f.ux, v.uy, v.uz, v.uw); +} + +PX_FORCE_INLINE BoolV BSetY(const BoolV v, const BoolV f) +{ + return BoolV(v.ux, f.uy, v.uz, v.uw); +} + +PX_FORCE_INLINE BoolV BSetZ(const BoolV v, const BoolV f) +{ + return BoolV(v.ux, v.uy, f.uz, v.uw); +} + +PX_FORCE_INLINE BoolV BSetW(const BoolV v, const BoolV f) +{ + return BoolV(v.ux, v.uy, v.uz, f.uw); +} + +template +BoolV BSplatElement(BoolV a) +{ + PxU32* b = reinterpret_cast(&a); + return BoolV(b[index], b[index], b[index], b[index]); +} + +PX_FORCE_INLINE BoolV BAnd(const BoolV a, const BoolV b) +{ + return BoolV(BOOL_TO_U32(a.ux && b.ux), BOOL_TO_U32(a.uy && b.uy), BOOL_TO_U32(a.uz && b.uz), BOOL_TO_U32(a.uw && b.uw)); +} + +PX_FORCE_INLINE BoolV BAndNot(const BoolV a, const BoolV b) +{ + return BoolV(a.ux & ~b.ux, a.uy & ~b.uy, a.uz & ~b.uz, a.uw & ~b.uw); +} + +PX_FORCE_INLINE BoolV BNot(const BoolV a) +{ + return BoolV(~a.ux, ~a.uy, ~a.uz, ~a.uw); +} + +PX_FORCE_INLINE BoolV BOr(const BoolV a, const BoolV b) +{ + return BoolV(BOOL_TO_U32(a.ux || b.ux), BOOL_TO_U32(a.uy || b.uy), BOOL_TO_U32(a.uz || b.uz), BOOL_TO_U32(a.uw || b.uw)); +} + +PX_FORCE_INLINE PxU32 BAllEq(const BoolV a, const BoolV b) +{ + return (a.ux == b.ux && a.uy == b.uy && a.uz == b.uz && a.uw == b.uw ? 1 : 0); +} + +PX_FORCE_INLINE PxU32 BAllEqTTTT(const BoolV a) +{ + return BAllEq(a, BTTTT()); +} + +PX_FORCE_INLINE PxU32 BAllEqFFFF(const BoolV a) +{ + return BAllEq(a, BFFFF()); +} + +PX_FORCE_INLINE BoolV BAllTrue4(const BoolV a) +{ + return (a.ux & a.uy & a.uz & a.uw) ? BTTTT() : BFFFF(); +} + +PX_FORCE_INLINE BoolV BAnyTrue4(const BoolV a) +{ + return (a.ux | a.uy | a.uz | a.uw) ? BTTTT() : BFFFF(); +} + +PX_FORCE_INLINE BoolV BAllTrue3(const BoolV a) +{ + return (a.ux & a.uy & a.uz) ? BTTTT() : BFFFF(); +} + +PX_FORCE_INLINE BoolV BAnyTrue3(const BoolV a) +{ + return (a.ux | a.uy | a.uz) ? BTTTT() : BFFFF(); +} + +PX_FORCE_INLINE PxU32 BGetBitMask(const BoolV a) +{ + return (a.ux & 1) | (a.uy & 2) | (a.uz & 4) | (a.uw & 8); +} + +////////////////////////////////// +// MAT33V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M33MulV3(const Mat33V& a, const Vec3V b) +{ + return Vec3V(a.col0.x * b.x + a.col1.x * b.y + a.col2.x * b.z, a.col0.y * b.x + a.col1.y * b.y + a.col2.y * b.z, + a.col0.z * b.x + a.col1.z * b.y + a.col2.z * b.z); +} + +PX_FORCE_INLINE Vec3V M33TrnspsMulV3(const Mat33V& a, const Vec3V b) +{ + return Vec3V(a.col0.x * b.x + a.col0.y * b.y + a.col0.z * b.z, a.col1.x * b.x + a.col1.y * b.y + a.col1.z * b.z, + a.col2.x * b.x + a.col2.y * b.y + a.col2.z * b.z); +} + +PX_FORCE_INLINE Vec3V M33MulV3AddV3(const Mat33V& A, const Vec3V b, const Vec3V c) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + Vec3V result = V3ScaleAdd(A.col0, x, c); + result = V3ScaleAdd(A.col1, y, result); + return V3ScaleAdd(A.col2, z, result); +} + +PX_FORCE_INLINE Mat33V M33MulM33(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(M33MulV3(a, b.col0), M33MulV3(a, b.col1), M33MulV3(a, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Add(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(V3Add(a.col0, b.col0), V3Add(a.col1, b.col1), V3Add(a.col2, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Scale(const Mat33V& a, const FloatV& b) +{ + return Mat33V(V3Scale(a.col0, b), V3Scale(a.col1, b), V3Scale(a.col2, b)); +} + +PX_FORCE_INLINE Mat33V M33Sub(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(V3Sub(a.col0, b.col0), V3Sub(a.col1, b.col1), V3Sub(a.col2, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Neg(const Mat33V& a) +{ + return Mat33V(V3Neg(a.col0), V3Neg(a.col1), V3Neg(a.col2)); +} + +PX_FORCE_INLINE Mat33V M33Abs(const Mat33V& a) +{ + return Mat33V(V3Abs(a.col0), V3Abs(a.col1), V3Abs(a.col2)); +} + +PX_FORCE_INLINE Mat33V M33Diagonal(const Vec3VArg d) +{ + const Vec3V x = V3Mul(V3UnitX(), d); + const Vec3V y = V3Mul(V3UnitY(), d); + const Vec3V z = V3Mul(V3UnitZ(), d); + return Mat33V(x, y, z); +} + +PX_FORCE_INLINE Mat33V M33Inverse(const Mat33V& a) +{ + const PxF32 det = a.col0.x * (a.col1.y * a.col2.z - a.col1.z * a.col2.y) - + a.col1.x * (a.col0.y * a.col2.z - a.col2.y * a.col0.z) + + a.col2.x * (a.col0.y * a.col1.z - a.col1.y * a.col0.z); + + const PxF32 invDet = 1.0f / det; + + Mat33V ret; + ret.col0.x = invDet * (a.col1.y * a.col2.z - a.col2.y * a.col1.z); + ret.col0.y = invDet * (a.col2.y * a.col0.z - a.col0.y * a.col2.z); + ret.col0.z = invDet * (a.col0.y * a.col1.z - a.col1.y * a.col0.z); + + ret.col1.x = invDet * (a.col2.x * a.col1.z - a.col1.x * a.col2.z); + ret.col1.y = invDet * (a.col0.x * a.col2.z - a.col2.x * a.col0.z); + ret.col1.z = invDet * (a.col1.x * a.col0.z - a.col0.x * a.col1.z); + + ret.col2.x = invDet * (a.col1.x * a.col2.y - a.col2.x * a.col1.y); + ret.col2.y = invDet * (a.col2.x * a.col0.y - a.col0.x * a.col2.y); + ret.col2.z = invDet * (a.col0.x * a.col1.y - a.col1.x * a.col0.y); + + return ret; +} + +PX_FORCE_INLINE Mat33V Mat33V_From_PxMat33(const PxMat33& m) +{ + return Mat33V(V3LoadU(m.column0), V3LoadU(m.column1), V3LoadU(m.column2)); +} + +PX_FORCE_INLINE void PxMat33_From_Mat33V(const Mat33V& m, PxMat33& out) +{ + PX_ASSERT((size_t(&out) & 15) == 0); + V3StoreU(m.col0, out.column0); + V3StoreU(m.col1, out.column1); + V3StoreU(m.col2, out.column2); +} + +PX_FORCE_INLINE Mat33V M33Trnsps(const Mat33V& a) +{ + return Mat33V(Vec3V(a.col0.x, a.col1.x, a.col2.x), Vec3V(a.col0.y, a.col1.y, a.col2.y), + Vec3V(a.col0.z, a.col1.z, a.col2.z)); +} + +PX_FORCE_INLINE Mat33V M33Identity() +{ + return Mat33V(V3UnitX(), V3UnitY(), V3UnitZ()); +} + +////////////////////////////////// +// MAT34V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M34MulV3(const Mat34V& a, const Vec3V b) +{ + return Vec3V(a.col0.x * b.x + a.col1.x * b.y + a.col2.x * b.z + a.col3.x, + a.col0.y * b.x + a.col1.y * b.y + a.col2.y * b.z + a.col3.y, + a.col0.z * b.x + a.col1.z * b.y + a.col2.z * b.z + a.col3.z); +} + +PX_FORCE_INLINE Vec3V M34Mul33V3(const Mat34V& a, const Vec3V b) +{ + return Vec3V(a.col0.x * b.x + a.col1.x * b.y + a.col2.x * b.z, a.col0.y * b.x + a.col1.y * b.y + a.col2.y * b.z, + a.col0.z * b.x + a.col1.z * b.y + a.col2.z * b.z); +} + +PX_FORCE_INLINE Vec3V M34TrnspsMul33V3(const Mat34V& a, const Vec3V b) +{ + return Vec3V(a.col0.x * b.x + a.col0.y * b.y + a.col0.z * b.z, a.col1.x * b.x + a.col1.y * b.y + a.col1.z * b.z, + a.col2.x * b.x + a.col2.y * b.y + a.col2.z * b.z); +} + +PX_FORCE_INLINE Mat34V M34MulM34(const Mat34V& a, const Mat34V& b) +{ + return Mat34V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2), M34MulV3(a, b.col3)); +} + +PX_FORCE_INLINE Mat33V M34MulM33(const Mat34V& a, const Mat33V& b) +{ + return Mat33V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2)); +} + +PX_FORCE_INLINE Mat33V M34Mul33V3(const Mat34V& a, const Mat33V& b) +{ + return Mat33V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2)); +} + +PX_FORCE_INLINE Mat33V M34Mul33MM34(const Mat34V& a, const Mat34V& b) +{ + return Mat33V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2)); +} + +PX_FORCE_INLINE Mat34V M34Add(const Mat34V& a, const Mat34V& b) +{ + return Mat34V(V3Add(a.col0, b.col0), V3Add(a.col1, b.col1), V3Add(a.col2, b.col2), V3Add(a.col3, b.col3)); +} + +PX_FORCE_INLINE Mat33V M34Trnsps33(const Mat34V& a) +{ + return Mat33V(Vec3V(a.col0.x, a.col1.x, a.col2.x), Vec3V(a.col0.y, a.col1.y, a.col2.y), + Vec3V(a.col0.z, a.col1.z, a.col2.z)); +} + +////////////////////////////////// +// MAT44V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V M44MulV4(const Mat44V& a, const Vec4V b) +{ + return Vec4V(a.col0.x * b.x + a.col1.x * b.y + a.col2.x * b.z + a.col3.x * b.w, + a.col0.y * b.x + a.col1.y * b.y + a.col2.y * b.z + a.col3.y * b.w, + a.col0.z * b.x + a.col1.z * b.y + a.col2.z * b.z + a.col3.z * b.w, + a.col0.w * b.x + a.col1.w * b.y + a.col2.w * b.z + a.col3.w * b.w); +} + +PX_FORCE_INLINE Vec4V M44TrnspsMulV4(const Mat44V& a, const Vec4V b) +{ + return Vec4V(a.col0.x * b.x + a.col0.y * b.y + a.col0.z * b.z + a.col0.w * b.w, + a.col1.x * b.x + a.col1.y * b.y + a.col1.z * b.z + a.col1.w * b.w, + a.col2.x * b.x + a.col2.y * b.y + a.col2.z * b.z + a.col2.w * b.w, + a.col3.x * b.x + a.col3.y * b.y + a.col3.z * b.z + a.col3.w * b.w); +} + +PX_FORCE_INLINE Mat44V M44MulM44(const Mat44V& a, const Mat44V& b) +{ + return Mat44V(M44MulV4(a, b.col0), M44MulV4(a, b.col1), M44MulV4(a, b.col2), M44MulV4(a, b.col3)); +} + +PX_FORCE_INLINE Mat44V M44Add(const Mat44V& a, const Mat44V& b) +{ + return Mat44V(V4Add(a.col0, b.col0), V4Add(a.col1, b.col1), V4Add(a.col2, b.col2), V4Add(a.col3, b.col3)); +} + +PX_FORCE_INLINE Mat44V M44Inverse(const Mat44V& a) +{ + PxF32 tmp[12]; + PxF32 dst[16]; + PxF32 det; + + const PxF32 src[16] = { a.col0.x, a.col0.y, a.col0.z, a.col0.w, a.col1.x, a.col1.y, a.col1.z, a.col1.w, + a.col2.x, a.col2.y, a.col2.z, a.col2.w, a.col3.x, a.col3.y, a.col3.z, a.col3.w }; + + tmp[0] = src[10] * src[15]; + tmp[1] = src[11] * src[14]; + tmp[2] = src[9] * src[15]; + tmp[3] = src[11] * src[13]; + tmp[4] = src[9] * src[14]; + tmp[5] = src[10] * src[13]; + tmp[6] = src[8] * src[15]; + tmp[7] = src[11] * src[12]; + tmp[8] = src[8] * src[14]; + tmp[9] = src[10] * src[12]; + tmp[10] = src[8] * src[13]; + tmp[11] = src[9] * src[12]; + + dst[0] = tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7]; + dst[0] -= tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7]; + dst[1] = tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7]; + dst[1] -= tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7]; + dst[2] = tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7]; + dst[2] -= tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7]; + dst[3] = tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6]; + dst[3] -= tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6]; + dst[4] = tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3]; + dst[4] -= tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3]; + dst[5] = tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3]; + dst[5] -= tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3]; + dst[6] = tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3]; + dst[6] -= tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3]; + dst[7] = tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2]; + dst[7] -= tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2]; + + tmp[0] = src[2] * src[7]; + tmp[1] = src[3] * src[6]; + tmp[2] = src[1] * src[7]; + tmp[3] = src[3] * src[5]; + tmp[4] = src[1] * src[6]; + tmp[5] = src[2] * src[5]; + tmp[6] = src[0] * src[7]; + tmp[7] = src[3] * src[4]; + tmp[8] = src[0] * src[6]; + tmp[9] = src[2] * src[4]; + tmp[10] = src[0] * src[5]; + tmp[11] = src[1] * src[4]; + + dst[8] = tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15]; + dst[8] -= tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15]; + dst[9] = tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15]; + dst[9] -= tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15]; + dst[10] = tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15]; + dst[10] -= tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15]; + dst[11] = tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14]; + dst[11] -= tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14]; + dst[12] = tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9]; + dst[12] -= tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10]; + dst[13] = tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10]; + dst[13] -= tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8]; + dst[14] = tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8]; + dst[14] -= tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9]; + dst[15] = tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9]; + dst[15] -= tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8]; + + det = src[0] * dst[0] + src[1] * dst[1] + src[2] * dst[2] + src[3] * dst[3]; + + det = 1.0f / det; + for(PxU32 j = 0; j < 16; j++) + { + dst[j] *= det; + } + + return Mat44V(Vec4V(dst[0], dst[4], dst[8], dst[12]), Vec4V(dst[1], dst[5], dst[9], dst[13]), + Vec4V(dst[2], dst[6], dst[10], dst[14]), Vec4V(dst[3], dst[7], dst[11], dst[15])); +} + +PX_FORCE_INLINE Mat44V M44Trnsps(const Mat44V& a) +{ + return Mat44V(Vec4V(a.col0.x, a.col1.x, a.col2.x, a.col3.x), Vec4V(a.col0.y, a.col1.y, a.col2.y, a.col3.y), + Vec4V(a.col0.z, a.col1.z, a.col2.z, a.col3.z), Vec4V(a.col0.w, a.col1.w, a.col2.w, a.col3.w)); +} + +PX_FORCE_INLINE Vec4V V4LoadXYZW(const PxF32& x, const PxF32& y, const PxF32& z, const PxF32& w) +{ + return Vec4V(x, y, z, w); +} + +/* +PX_FORCE_INLINE VecU16V V4U32PK(VecU32V a, VecU32V b) +{ + return VecU16V( + PxU16(PxClamp((a).u32[0], 0, 0xFFFF)), + PxU16(PxClamp((a).u32[1], 0, 0xFFFF)), + PxU16(PxClamp((a).u32[2], 0, 0xFFFF)), + PxU16(PxClamp((a).u32[3], 0, 0xFFFF)), + PxU16(PxClamp((b).u32[0], 0, 0xFFFF)), + PxU16(PxClamp((b).u32[1], 0, 0xFFFF)), + PxU16(PxClamp((b).u32[2], 0, 0xFFFF)), + PxU16(PxClamp((b).u32[3], 0, 0xFFFF))); +} +*/ + +PX_FORCE_INLINE VecU32V V4U32Sel(const BoolV c, const VecU32V a, const VecU32V b) +{ + return VecU32V(c.ux ? a.u32[0] : b.u32[0], c.uy ? a.u32[1] : b.u32[1], c.uz ? a.u32[2] : b.u32[2], + c.uw ? a.u32[3] : b.u32[3]); +} + +PX_FORCE_INLINE VecU32V V4U32or(VecU32V a, VecU32V b) +{ + return VecU32V((a).u32[0] | (b).u32[0], (a).u32[1] | (b).u32[1], (a).u32[2] | (b).u32[2], (a).u32[3] | (b).u32[3]); +} + +PX_FORCE_INLINE VecU32V V4U32xor(VecU32V a, VecU32V b) +{ + return VecU32V((a).u32[0] ^ (b).u32[0], (a).u32[1] ^ (b).u32[1], (a).u32[2] ^ (b).u32[2], (a).u32[3] ^ (b).u32[3]); +} + +PX_FORCE_INLINE VecU32V V4U32and(VecU32V a, VecU32V b) +{ + return VecU32V((a).u32[0] & (b).u32[0], (a).u32[1] & (b).u32[1], (a).u32[2] & (b).u32[2], (a).u32[3] & (b).u32[3]); +} + +PX_FORCE_INLINE VecU32V V4U32Andc(VecU32V a, VecU32V b) +{ + return VecU32V((a).u32[0] & ~(b).u32[0], (a).u32[1] & ~(b).u32[1], (a).u32[2] & ~(b).u32[2], + (a).u32[3] & ~(b).u32[3]); +} + +/* +PX_FORCE_INLINE VecU16V V4U16Or(VecU16V a, VecU16V b) +{ + return VecU16V( + (a).u16[0]|(b).u16[0], (a).u16[1]|(b).u16[1], (a).u16[2]|(b).u16[2], (a).u16[3]|(b).u16[3], + (a).u16[4]|(b).u16[4], (a).u16[5]|(b).u16[5], (a).u16[6]|(b).u16[6], (a).u16[7]|(b).u16[7]); +} +*/ + +/* +PX_FORCE_INLINE VecU16V V4U16And(VecU16V a, VecU16V b) +{ + return VecU16V( + (a).u16[0]&(b).u16[0], (a).u16[1]&(b).u16[1], (a).u16[2]&(b).u16[2], (a).u16[3]&(b).u16[3], + (a).u16[4]&(b).u16[4], (a).u16[5]&(b).u16[5], (a).u16[6]&(b).u16[6], (a).u16[7]&(b).u16[7]); +} +*/ + +/* +PX_FORCE_INLINE VecU16V V4U16Andc(VecU16V a, VecU16V b) +{ + return VecU16V( + (a).u16[0]&~(b).u16[0], (a).u16[1]&~(b).u16[1], (a).u16[2]&~(b).u16[2], (a).u16[3]&~(b).u16[3], + (a).u16[4]&~(b).u16[4], (a).u16[5]&~(b).u16[5], (a).u16[6]&~(b).u16[6], (a).u16[7]&~(b).u16[7]); +} +*/ + +/* +template PX_FORCE_INLINE VecI32V V4ISplat() +{ + return VecI32V(a, a, a, a); +} + +template PX_FORCE_INLINE VecU32V V4USplat() +{ + return VecU32V(a, a, a, a); +} +*/ + +/* +PX_FORCE_INLINE void V4U16StoreAligned(VecU16V val, VecU16V* address) +{ + *address = val; +} +*/ + +PX_FORCE_INLINE void V4U32StoreAligned(VecU32V val, VecU32V* address) +{ + *address = val; +} + +PX_FORCE_INLINE Vec4V V4Andc(const Vec4V a, const VecU32V b) +{ + VecU32V r = V4U32Andc(*reinterpret_cast(&a), b); + return (*reinterpret_cast(&r)); +} + +PX_FORCE_INLINE VecU32V V4IsGrtrV32u(const Vec4V a, const Vec4V b) +{ + return VecU32V(a.x > b.x ? 0xFFFFffff : 0, a.y > b.y ? 0xFFFFffff : 0, a.z > b.z ? 0xFFFFffff : 0, + a.w > b.w ? 0xFFFFffff : 0); +} + +PX_FORCE_INLINE VecU16V V4U16LoadAligned(const VecU16V* addr) +{ + return *addr; +} + +PX_FORCE_INLINE VecU16V V4U16LoadUnaligned(const VecU16V* addr) +{ + return *addr; +} + +PX_FORCE_INLINE VecU16V V4U16CompareGt(VecU16V a, VecU16V b) +{ + return VecU16V + ( + BOOL_TO_U16(a.u16[0] > b.u16[0]), BOOL_TO_U16(a.u16[1] > b.u16[1]), BOOL_TO_U16(a.u16[2] > b.u16[2]), BOOL_TO_U16(a.u16[3] > b.u16[3]), + BOOL_TO_U16(a.u16[4] > b.u16[4]), BOOL_TO_U16(a.u16[5] > b.u16[5]), BOOL_TO_U16(a.u16[6] > b.u16[6]), BOOL_TO_U16(a.u16[7] > b.u16[7]) + ); +} + +PX_FORCE_INLINE VecU16V V4I16CompareGt(VecU16V a, VecU16V b) +{ + return VecU16V + ( + BOOL_TO_U16(a.i16[0] > b.i16[0]), BOOL_TO_U16(a.i16[1] > b.i16[1]), BOOL_TO_U16(a.i16[2] > b.i16[2]), BOOL_TO_U16(a.i16[3] > b.i16[3]), + BOOL_TO_U16(a.i16[4] > b.i16[4]), BOOL_TO_U16(a.i16[5] > b.i16[5]), BOOL_TO_U16(a.i16[6] > b.i16[6]), BOOL_TO_U16(a.i16[7] > b.i16[7]) + ); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_VecU32V(VecU32V a) +{ + return Vec4V(PxF32((a).u32[0]), PxF32((a).u32[1]), PxF32((a).u32[2]), PxF32((a).u32[3])); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_VecI32V(VecI32V a) +{ + return Vec4V(PxF32((a).i32[0]), PxF32((a).i32[1]), PxF32((a).i32[2]), PxF32((a).i32[3])); +} + +PX_FORCE_INLINE VecI32V VecI32V_From_Vec4V(Vec4V a) +{ + float* data = reinterpret_cast(&a); + return VecI32V(PxI32(data[0]), PxI32(data[1]), PxI32(data[2]), PxI32(data[3])); +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecU32V(VecU32V a) +{ + Vec4V b = *reinterpret_cast(&a); + return b; +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecI32V(VecI32V a) +{ + Vec4V b = *reinterpret_cast(&a); + return b; +} + +PX_FORCE_INLINE VecU32V VecU32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + VecU32V b = *reinterpret_cast(&a); + return b; +} + +PX_FORCE_INLINE VecI32V VecI32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + VecI32V b = *reinterpret_cast(&a); + return b; +} + +template +PX_FORCE_INLINE VecU32V V4U32SplatElement(VecU32V a) +{ + return VecU32V((a).u32[index], (a).u32[index], (a).u32[index], (a).u32[index]); +} + +template +PX_FORCE_INLINE VecU32V V4U32SplatElement(BoolV a) +{ + const PxU32 u = (&a.ux)[index]; + return VecU32V(u, u, u, u); +} + +template +PX_FORCE_INLINE Vec4V V4SplatElement(Vec4V a) +{ + float* data = reinterpret_cast(&a); + return Vec4V(data[index], data[index], data[index], data[index]); +} + +PX_FORCE_INLINE VecU32V U4LoadXYZW(PxU32 x, PxU32 y, PxU32 z, PxU32 w) +{ + return VecU32V(x, y, z, w); +} + +PX_FORCE_INLINE Vec4V V4Abs(const Vec4V a) +{ + return V4Max(a, V4Neg(a)); +} + +PX_FORCE_INLINE BoolV V4IsEqU32(const VecU32V a, const VecU32V b) +{ + return BoolV(BOOL_TO_U32(a.u32[0] == b.u32[0]), BOOL_TO_U32(a.u32[1] == b.u32[1]), BOOL_TO_U32(a.u32[2] == b.u32[2]), BOOL_TO_U32(a.u32[3] == b.u32[3])); +} + +PX_FORCE_INLINE VecU32V U4Load(const PxU32 i) +{ + return VecU32V(i, i, i, i); +} + +PX_FORCE_INLINE VecU32V U4LoadU(const PxU32* i) +{ + return VecU32V(i[0], i[1], i[2], i[3]); +} + +PX_FORCE_INLINE VecU32V U4LoadA(const PxU32* i) +{ + return VecU32V(i[0], i[1], i[2], i[3]); +} + +PX_FORCE_INLINE VecI32V I4LoadXYZW(const PxI32& x, const PxI32& y, const PxI32& z, const PxI32& w) +{ + return VecI32V(x, y, z, w); +} + +PX_FORCE_INLINE VecI32V I4Load(const PxI32 i) +{ + return VecI32V(i, i, i, i); +} + +PX_FORCE_INLINE VecI32V I4LoadU(const PxI32* i) +{ + return VecI32V(i[0], i[1], i[2], i[3]); +} + +PX_FORCE_INLINE VecI32V I4LoadA(const PxI32* i) +{ + return VecI32V(i[0], i[1], i[2], i[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_Add(const VecI32VArg a, const VecI32VArg b) +{ + return VecI32V(a.i32[0] + b.i32[0], a.i32[1] + b.i32[1], a.i32[2] + b.i32[2], a.i32[3] + b.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_Sub(const VecI32VArg a, const VecI32VArg b) +{ + return VecI32V(a.i32[0] - b.i32[0], a.i32[1] - b.i32[1], a.i32[2] - b.i32[2], a.i32[3] - b.i32[3]); +} + +PX_FORCE_INLINE BoolV VecI32V_IsGrtr(const VecI32VArg a, const VecI32VArg b) +{ + return BoolV(BOOL_TO_U32(a.i32[0] > b.i32[0]), BOOL_TO_U32(a.i32[1] > b.i32[1]), BOOL_TO_U32(a.i32[2] > b.i32[2]), BOOL_TO_U32(a.i32[3] > b.i32[3])); +} + +PX_FORCE_INLINE BoolV VecI32V_IsEq(const VecI32VArg a, const VecI32VArg b) +{ + return BoolV(BOOL_TO_U32(a.i32[0] == b.i32[0]), BOOL_TO_U32(a.i32[1] == b.i32[1]), BOOL_TO_U32(a.i32[2] == b.i32[2]), BOOL_TO_U32(a.i32[3] == b.i32[3])); +} + +PX_FORCE_INLINE VecI32V V4I32Sel(const BoolV c, const VecI32V a, const VecI32V b) +{ + return VecI32V(c.ux ? a.i32[0] : b.i32[0], c.uy ? a.i32[1] : b.i32[1], c.uz ? a.i32[2] : b.i32[2], + c.uw ? a.i32[3] : b.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_Zero() +{ + return VecI32V(0, 0, 0, 0); +} + +PX_FORCE_INLINE VecI32V VecI32V_One() +{ + return VecI32V(1, 1, 1, 1); +} + +PX_FORCE_INLINE VecI32V VecI32V_Two() +{ + return VecI32V(2, 2, 2, 2); +} + +PX_FORCE_INLINE VecI32V VecI32V_MinusOne() +{ + return VecI32V(-1, -1, -1, -1); +} + +PX_FORCE_INLINE VecU32V U4Zero() +{ + return VecU32V(0, 0, 0, 0); +} + +PX_FORCE_INLINE VecU32V U4One() +{ + return VecU32V(1, 1, 1, 1); +} + +PX_FORCE_INLINE VecU32V U4Two() +{ + return VecU32V(2, 2, 2, 2); +} + +PX_FORCE_INLINE VecShiftV VecI32V_PrepareShift(const VecI32VArg shift) +{ + return shift; +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const VecShiftVArg count) +{ + return VecI32V(a.i32[0] << count.i32[0], a.i32[1] << count.i32[1], a.i32[2] << count.i32[2], a.i32[3] + << count.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const VecShiftVArg count) +{ + return VecI32V(a.i32[0] >> count.i32[0], a.i32[1] >> count.i32[1], a.i32[2] >> count.i32[2], + a.i32[3] >> count.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const PxU32 count) +{ + return VecI32V(a.i32[0] << count, a.i32[1] << count, a.i32[2] << count, a.i32[3] << count); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const PxU32 count) +{ + return VecI32V(a.i32[0] >> count, a.i32[1] >> count, a.i32[2] >> count, a.i32[3] >> count); +} + +PX_FORCE_INLINE VecI32V VecI32V_And(const VecI32VArg a, const VecI32VArg b) +{ + return VecI32V(a.i32[0] & b.i32[0], a.i32[1] & b.i32[1], a.i32[2] & b.i32[2], a.i32[3] & b.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_Or(const VecI32VArg a, const VecI32VArg b) +{ + return VecI32V(a.i32[0] | b.i32[0], a.i32[1] | b.i32[1], a.i32[2] | b.i32[2], a.i32[3] | b.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetX(const VecI32VArg a) +{ + return VecI32V(a.i32[0], a.i32[0], a.i32[0], a.i32[0]); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetY(const VecI32VArg a) +{ + return VecI32V(a.i32[1], a.i32[1], a.i32[1], a.i32[1]); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetZ(const VecI32VArg a) +{ + return VecI32V(a.i32[2], a.i32[2], a.i32[2], a.i32[2]); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetW(const VecI32VArg a) +{ + return VecI32V(a.i32[3], a.i32[3], a.i32[3], a.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_Sel(const BoolV c, const VecI32VArg a, const VecI32VArg b) +{ + return VecI32V(c.ux ? a.i32[0] : b.i32[0], c.uy ? a.i32[1] : b.i32[1], c.uz ? a.i32[2] : b.i32[2], + c.uw ? a.i32[3] : b.i32[3]); +} + +PX_FORCE_INLINE VecI32V VecI32V_Merge(const VecI32VArg a, const VecI32VArg b, const VecI32VArg c, const VecI32VArg d) +{ + return VecI32V(a.i32[0], b.i32[0], c.i32[0], d.i32[0]); +} + +PX_FORCE_INLINE void PxI32_From_VecI32V(const VecI32VArg a, PxI32* i) +{ + *i = a.i32[0]; +} + +PX_FORCE_INLINE VecI32V VecI32V_From_BoolV(const BoolVArg b) +{ + return VecI32V(PxI32(b.ux), PxI32(b.uy), PxI32(b.uz), PxI32(b.uw)); +} + +PX_FORCE_INLINE VecU32V VecU32V_From_BoolV(const BoolVArg b) +{ + return VecU32V(b.ux, b.uy, b.uz, b.uw); +} + +PX_FORCE_INLINE void QuatGetMat33V(const QuatVArg q, Vec3V& column0, Vec3V& column1, Vec3V& column2) +{ + const FloatV one = FOne(); + const FloatV x = V4GetX(q); + const FloatV y = V4GetY(q); + const FloatV z = V4GetZ(q); + const FloatV w = V4GetW(q); + + const FloatV x2 = FAdd(x, x); + const FloatV y2 = FAdd(y, y); + const FloatV z2 = FAdd(z, z); + + const FloatV xx = FMul(x2, x); + const FloatV yy = FMul(y2, y); + const FloatV zz = FMul(z2, z); + + const FloatV xy = FMul(x2, y); + const FloatV xz = FMul(x2, z); + const FloatV xw = FMul(x2, w); + + const FloatV yz = FMul(y2, z); + const FloatV yw = FMul(y2, w); + const FloatV zw = FMul(z2, w); + + const FloatV v = FSub(one, xx); + + column0 = V3Merge(FSub(FSub(one, yy), zz), FAdd(xy, zw), FSub(xz, yw)); + column1 = V3Merge(FSub(xy, zw), FSub(v, zz), FAdd(yz, xw)); + column2 = V3Merge(FAdd(xz, yw), FSub(yz, xw), FSub(v, yy)); +} + + +// not used + +/* +PX_FORCE_INLINE Vec4V V4LoadAligned(Vec4V* addr) +{ + return *addr; +} +*/ + +/* +PX_FORCE_INLINE Vec4V V4LoadUnaligned(Vec4V* addr) +{ + return *addr; +} +*/ + +/* +PX_FORCE_INLINE Vec4V V4Ceil(const Vec4V a) +{ + return Vec4V(PxCeil(a.x), PxCeil(a.y), PxCeil(a.z), PxCeil(a.w)); +} + +PX_FORCE_INLINE Vec4V V4Floor(const Vec4V a) +{ + return Vec4V(PxFloor(a.x), PxFloor(a.y), PxFloor(a.z), PxFloor(a.w)); +} +*/ + +/* +PX_FORCE_INLINE VecU32V V4ConvertToU32VSaturate(const Vec4V a, PxU32 power) +{ + PX_ASSERT(power == 0 && "Non-zero power not supported in convertToU32VSaturate"); + PX_UNUSED(power); // prevent warning in release builds + PxF32 ffffFFFFasFloat = PxF32(0xFFFF0000); + return VecU32V( + PxU32(PxClamp((a).x, 0.0f, ffffFFFFasFloat)), + PxU32(PxClamp((a).y, 0.0f, ffffFFFFasFloat)), + PxU32(PxClamp((a).z, 0.0f, ffffFFFFasFloat)), + PxU32(PxClamp((a).w, 0.0f, ffffFFFFasFloat))); +} +*/ + +} // namespace aos +#if !PX_DOXYGEN +} // namespace physx +#endif + +#if PX_GCC_FAMILY +#pragma GCC diagnostic pop +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathSSE.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathSSE.h new file mode 100644 index 000000000..358e7e363 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecMathSSE.h @@ -0,0 +1,2716 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC_MATH_SSE_H +#define PX_VEC_MATH_SSE_H + +// PT: this file contains the SSE code common to the Windows & Unix versions + +#if !COMPILE_VECTOR_INTRINSICS + #error Vector intrinsics should not be included when using scalar implementation. +#endif + +#ifdef __SSE4_2__ + #include "smmintrin.h" +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +namespace aos +{ + +namespace +{ + const PX_ALIGN(16, PxF32) minus1w[4] = { 0.0f, 0.0f, 0.0f, -1.0f }; +} + +PX_FORCE_INLINE void QuatGetMat33V(const QuatVArg q, Vec3V& column0, Vec3V& column1, Vec3V& column2) +{ + const __m128 q2 = V4Add(q, q); + const __m128 qw2 = V4MulAdd(q2, V4GetW(q), _mm_load_ps(minus1w)); // (2wx, 2wy, 2wz, 2ww-1) + const __m128 nw2 = Vec3V_From_Vec4V(V4Neg(qw2)); // (-2wx, -2wy, -2wz, 0) + const __m128 v = Vec3V_From_Vec4V(q); + + const __m128 a0 = _mm_shuffle_ps(qw2, nw2, _MM_SHUFFLE(3, 1, 2, 3)); // (2ww-1, 2wz, -2wy, 0) + column0 = V4MulAdd(v, V4GetX(q2), a0); + + const __m128 a1 = _mm_shuffle_ps(qw2, nw2, _MM_SHUFFLE(3, 2, 0, 3)); // (2ww-1, 2wx, -2wz, 0) + column1 = V4MulAdd(v, V4GetY(q2), _mm_shuffle_ps(a1, a1, _MM_SHUFFLE(3, 1, 0, 2))); + + const __m128 a2 = _mm_shuffle_ps(qw2, nw2, _MM_SHUFFLE(3, 0, 1, 3)); // (2ww-1, 2wy, -2wx, 0) + column2 = V4MulAdd(v, V4GetZ(q2), _mm_shuffle_ps(a2, a2, _MM_SHUFFLE(3, 0, 2, 1))); +} + +////////////////////////////////////////////////////////////////////// +//Test that Vec3V and FloatV are legal +////////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE bool isValidVec3V(const Vec3V a) +{ + //using _mm_comieq_ss to do the comparison doesn't work for NaN. + PX_ALIGN(16, PxF32 f[4]); + V4StoreA(a, f); + return f[3] == 0.0f; +} + +PX_FORCE_INLINE bool isFiniteLength(const Vec3V a) +{ + return !FAllEq(V4LengthSq(a), FZero()); +} + +PX_FORCE_INLINE bool isAligned16(const void* a) +{ + return (0 == (size_t(a) & 0x0f)); +} + +//ASSERT_FINITELENGTH is deactivated because there is a lot of code that calls a simd normalisation function with zero length but then ignores the result. + +#if PX_DEBUG + #define ASSERT_ISVALIDVEC3V(a) PX_ASSERT(isValidVec3V(a)) + #define ASSERT_ISVALIDFLOATV(a) PX_ASSERT(isValidFloatV(a)) + #define ASSERT_ISALIGNED16(a) PX_ASSERT(isAligned16(reinterpret_cast(a))) + #define ASSERT_ISFINITELENGTH(a) //PX_ASSERT(isFiniteLength(a)) +#else + #define ASSERT_ISVALIDVEC3V(a) + #define ASSERT_ISVALIDFLOATV(a) + #define ASSERT_ISALIGNED16(a) + #define ASSERT_ISFINITELENGTH(a) +#endif + +namespace internalSimd +{ +PX_FORCE_INLINE __m128 m128_I2F(__m128i n) +{ + return _mm_castsi128_ps(n); +} + +PX_FORCE_INLINE __m128i m128_F2I(__m128 n) +{ + return _mm_castps_si128(n); +} + +PX_FORCE_INLINE PxU32 BAllTrue4_R(const BoolV a) +{ + const PxI32 moveMask = _mm_movemask_ps(a); + return PxU32(moveMask == 0xf); +} + +PX_FORCE_INLINE PxU32 BAllTrue3_R(const BoolV a) +{ + const PxI32 moveMask = _mm_movemask_ps(a); + return PxU32((moveMask & 0x7) == 0x7); +} + +PX_FORCE_INLINE PxU32 BAnyTrue4_R(const BoolV a) +{ + const PxI32 moveMask = _mm_movemask_ps(a); + return PxU32(moveMask != 0x0); +} + +PX_FORCE_INLINE PxU32 BAnyTrue3_R(const BoolV a) +{ + const PxI32 moveMask = _mm_movemask_ps(a); + return PxU32((moveMask & 0x7) != 0x0); +} + +PX_FORCE_INLINE PxU32 FiniteTestEq(const Vec4V a, const Vec4V b) +{ + // This is a bit of a bodge. + //_mm_comieq_ss returns 1 if either value is nan so we need to re-cast a and b with true encoded as a non-nan + // number. + // There must be a better way of doing this in sse. + const BoolV one = FOne(); + const BoolV zero = FZero(); + const BoolV a1 = V4Sel(a, one, zero); + const BoolV b1 = V4Sel(b, one, zero); + return (PxU32( + _mm_comieq_ss(a1, b1) && + _mm_comieq_ss(_mm_shuffle_ps(a1, a1, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b1, b1, _MM_SHUFFLE(1, 1, 1, 1))) && + _mm_comieq_ss(_mm_shuffle_ps(a1, a1, _MM_SHUFFLE(2, 2, 2, 2)), _mm_shuffle_ps(b1, b1, _MM_SHUFFLE(2, 2, 2, 2))) && + _mm_comieq_ss(_mm_shuffle_ps(a1, a1, _MM_SHUFFLE(3, 3, 3, 3)), _mm_shuffle_ps(b1, b1, _MM_SHUFFLE(3, 3, 3, 3))))); +} + +PX_FORCE_INLINE bool hasZeroElementInFloatV(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return _mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)), FZero()) ? true : false; +} + +PX_FORCE_INLINE bool hasZeroElementInVec3V(const Vec3V a) +{ + return (_mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)), FZero()) || + _mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)), FZero()) || + _mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)), FZero())); +} + +PX_FORCE_INLINE bool hasZeroElementInVec4V(const Vec4V a) +{ + return (_mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)), FZero()) || + _mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)), FZero()) || + _mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)), FZero()) || + _mm_comieq_ss(_mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 3, 3, 3)), FZero())); +} + +} //internalSimd + +namespace vecMathTests +{ +// PT: this function returns an invalid Vec3V (W!=0.0f) just for unit-testing 'isValidVec3V' +PX_FORCE_INLINE Vec3V getInvalidVec3V() +{ + const float f = 1.0f; + return _mm_load1_ps(&f); +} + +PX_FORCE_INLINE bool allElementsEqualFloatV(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_comieq_ss(a, b) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualVec3V(const Vec3V a, const Vec3V b) +{ + return V3AllEq(a, b) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualVec4V(const Vec4V a, const Vec4V b) +{ + return V4AllEq(a, b) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualVecU32V(const VecU32V a, const VecU32V b) +{ + return internalSimd::BAllTrue4_R(V4IsEqU32(a, b)) != 0; +} + +} //vecMathTests + +///////////////////////////////////////////////////////////////////// +////VECTORISED FUNCTION IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE BoolV BLoad(const bool f) +{ + const PxU32 i = PxU32(-PxI32(f)); + return _mm_load1_ps(reinterpret_cast(&i)); +} + +PX_FORCE_INLINE FloatV FLoad(const PxF32 f) +{ + return _mm_load1_ps(&f); +} + +PX_FORCE_INLINE Vec3V V3Load(const PxF32 f) +{ + return _mm_set_ps(0.0f, f, f, f); +} + +PX_FORCE_INLINE Vec4V V4Load(const PxF32 f) +{ + return _mm_load1_ps(&f); +} + +PX_FORCE_INLINE Vec3V V3LoadU(const PxVec3& f) +{ + return _mm_set_ps(0.0f, f.z, f.y, f.x); +} + +PX_FORCE_INLINE Vec3V V3LoadU(const PxF32* const i) +{ + return _mm_set_ps(0.0f, i[2], i[1], i[0]); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V(Vec4V v) +{ + return V4ClearW(v); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V_WUndefined(const Vec4V v) +{ + return v; +} + +PX_FORCE_INLINE Vec4V Vec4V_From_PxVec3_WUndefined(const PxVec3& f) +{ + return _mm_set_ps(0.0f, f.z, f.y, f.x); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_FloatV(FloatV f) +{ + return f; +} + +PX_FORCE_INLINE Vec4V Vec4V_From_Vec3V(Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + return f; // ok if it is implemented as the same type. +} + +PX_FORCE_INLINE Vec3V Vec3V_From_FloatV(FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return Vec3V_From_Vec4V(Vec4V_From_FloatV(f)); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_FloatV_WUndefined(FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return Vec3V_From_Vec4V_WUndefined(Vec4V_From_FloatV(f)); +} + +PX_FORCE_INLINE Vec4V V4LoadA(const PxF32* const f) +{ + ASSERT_ISALIGNED16(f); + return _mm_load_ps(f); +} + +PX_FORCE_INLINE Vec4V V4LoadU(const PxF32* const f) +{ + return _mm_loadu_ps(f); +} + +PX_FORCE_INLINE void V4StoreA(const Vec4V a, PxF32* f) +{ + ASSERT_ISALIGNED16(f); + _mm_store_ps(f, a); +} + +PX_FORCE_INLINE void V4StoreU(const Vec4V a, PxF32* f) +{ + _mm_storeu_ps(f, a); +} + +PX_FORCE_INLINE void BStoreA(const BoolV a, PxU32* f) +{ + ASSERT_ISALIGNED16(f); + _mm_store_ps(reinterpret_cast(f), a); +} + +PX_FORCE_INLINE void U4StoreA(const VecU32V uv, PxU32* u) +{ + ASSERT_ISALIGNED16(u); + _mm_store_ps(reinterpret_cast(u), uv); +} + +PX_FORCE_INLINE void FStore(const FloatV a, PxF32* PX_RESTRICT f) +{ + ASSERT_ISVALIDFLOATV(a); + _mm_store_ss(f, a); +} + +PX_FORCE_INLINE void Store_From_BoolV(const BoolV b, PxU32* b2) +{ + _mm_store_ss(reinterpret_cast(b2), b); +} + +////////////////////////////////// +// FLOATV +////////////////////////////////// + +PX_FORCE_INLINE FloatV FZero() +{ + return _mm_setzero_ps(); +} + +PX_FORCE_INLINE FloatV FOne() +{ + return FLoad(1.0f); +} + +PX_FORCE_INLINE FloatV FHalf() +{ + return FLoad(0.5f); +} + +PX_FORCE_INLINE FloatV FEps() +{ + return FLoad(PX_EPS_REAL); +} + +PX_FORCE_INLINE FloatV FEps6() +{ + return FLoad(1e-6f); +} + +PX_FORCE_INLINE FloatV FMax() +{ + return FLoad(PX_MAX_REAL); +} + +PX_FORCE_INLINE FloatV FNegMax() +{ + return FLoad(-PX_MAX_REAL); +} + +PX_FORCE_INLINE FloatV IZero() +{ + const PxU32 zero = 0; + return _mm_load1_ps(reinterpret_cast(&zero)); +} + +PX_FORCE_INLINE FloatV IOne() +{ + const PxU32 one = 1; + return _mm_load1_ps(reinterpret_cast(&one)); +} + +PX_FORCE_INLINE FloatV ITwo() +{ + const PxU32 two = 2; + return _mm_load1_ps(reinterpret_cast(&two)); +} + +PX_FORCE_INLINE FloatV IThree() +{ + const PxU32 three = 3; + return _mm_load1_ps(reinterpret_cast(&three)); +} + +PX_FORCE_INLINE FloatV IFour() +{ + const PxU32 four = 4; + return _mm_load1_ps(reinterpret_cast(&four)); +} + +PX_FORCE_INLINE FloatV FNeg(const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return _mm_sub_ps(_mm_setzero_ps(), f); +} + +PX_FORCE_INLINE FloatV FAdd(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_add_ps(a, b); +} + +PX_FORCE_INLINE FloatV FSub(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_sub_ps(a, b); +} + +PX_FORCE_INLINE FloatV FMul(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_mul_ps(a, b); +} + +PX_FORCE_INLINE FloatV FDiv(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_div_ps(a, b); +} + +PX_FORCE_INLINE FloatV FDivFast(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_mul_ps(a, _mm_rcp_ps(b)); +} + +PX_FORCE_INLINE FloatV FRecip(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return _mm_div_ps(FOne(), a); +} + +PX_FORCE_INLINE FloatV FRecipFast(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return _mm_rcp_ps(a); +} + +PX_FORCE_INLINE FloatV FRsqrt(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return _mm_div_ps(FOne(), _mm_sqrt_ps(a)); +} + +PX_FORCE_INLINE FloatV FSqrt(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return _mm_sqrt_ps(a); +} + +PX_FORCE_INLINE FloatV FRsqrtFast(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return _mm_rsqrt_ps(a); +} + +PX_FORCE_INLINE FloatV FScaleAdd(const FloatV a, const FloatV b, const FloatV c) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDFLOATV(c); + return FAdd(FMul(a, b), c); +} + +PX_FORCE_INLINE FloatV FNegScaleSub(const FloatV a, const FloatV b, const FloatV c) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDFLOATV(c); + return FSub(c, FMul(a, b)); +} + +PX_FORCE_INLINE FloatV FSel(const BoolV c, const FloatV a, const FloatV b) +{ + PX_ASSERT(vecMathTests::allElementsEqualBoolV(c, BTTTT()) || + vecMathTests::allElementsEqualBoolV(c, BFFFF())); + ASSERT_ISVALIDFLOATV(_mm_or_ps(_mm_andnot_ps(c, b), _mm_and_ps(c, a))); + return _mm_or_ps(_mm_andnot_ps(c, b), _mm_and_ps(c, a)); +} + +PX_FORCE_INLINE BoolV FIsGrtr(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_cmpgt_ps(a, b); +} + +PX_FORCE_INLINE BoolV FIsGrtrOrEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_cmpge_ps(a, b); +} + +PX_FORCE_INLINE BoolV FIsEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_cmpeq_ps(a, b); +} + +PX_FORCE_INLINE FloatV FMax(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_max_ps(a, b); +} + +PX_FORCE_INLINE FloatV FMin(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_min_ps(a, b); +} + +PX_FORCE_INLINE FloatV FClamp(const FloatV a, const FloatV minV, const FloatV maxV) +{ + ASSERT_ISVALIDFLOATV(minV); + ASSERT_ISVALIDFLOATV(maxV); + return _mm_max_ps(_mm_min_ps(a, maxV), minV); +} + +PX_FORCE_INLINE PxU32 FAllGrtr(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return PxU32(_mm_comigt_ss(a, b)); +} + +PX_FORCE_INLINE PxU32 FAllGrtrOrEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return PxU32(_mm_comige_ss(a, b)); +} + +PX_FORCE_INLINE PxU32 FAllEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return PxU32(_mm_comieq_ss(a, b)); +} + +PX_FORCE_INLINE FloatV FRound(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); +#ifdef __SSE4_2__ + return _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); +#else + // return _mm_round_ps(a, 0x0); + const FloatV half = FLoad(0.5f); + const __m128 signBit = _mm_cvtepi32_ps(_mm_srli_epi32(_mm_cvtps_epi32(a), 31)); + const FloatV aRound = FSub(FAdd(a, half), signBit); + __m128i tmp = _mm_cvttps_epi32(aRound); + return _mm_cvtepi32_ps(tmp); +#endif +} + +PX_FORCE_INLINE FloatV FSin(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const FloatV recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const FloatV twoPi = V4LoadA(g_PXTwoPi.f); + const FloatV tmp = FMul(a, recipTwoPi); + const FloatV b = FRound(tmp); + const FloatV V1 = FNegScaleSub(twoPi, b, a); + + // sin(V) ~= V - V^3 / 3! + V^5 / 5! - V^7 / 7! + V^9 / 9! - V^11 / 11! + V^13 / 13! - + // V^15 / 15! + V^17 / 17! - V^19 / 19! + V^21 / 21! - V^23 / 23! (for -PI <= V < PI) + const FloatV V2 = FMul(V1, V1); + const FloatV V3 = FMul(V2, V1); + const FloatV V5 = FMul(V3, V2); + const FloatV V7 = FMul(V5, V2); + const FloatV V9 = FMul(V7, V2); + const FloatV V11 = FMul(V9, V2); + const FloatV V13 = FMul(V11, V2); + const FloatV V15 = FMul(V13, V2); + const FloatV V17 = FMul(V15, V2); + const FloatV V19 = FMul(V17, V2); + const FloatV V21 = FMul(V19, V2); + const FloatV V23 = FMul(V21, V2); + + const Vec4V sinCoefficients0 = V4LoadA(g_PXSinCoefficients0.f); + const Vec4V sinCoefficients1 = V4LoadA(g_PXSinCoefficients1.f); + const Vec4V sinCoefficients2 = V4LoadA(g_PXSinCoefficients2.f); + + const FloatV S1 = V4GetY(sinCoefficients0); + const FloatV S2 = V4GetZ(sinCoefficients0); + const FloatV S3 = V4GetW(sinCoefficients0); + const FloatV S4 = V4GetX(sinCoefficients1); + const FloatV S5 = V4GetY(sinCoefficients1); + const FloatV S6 = V4GetZ(sinCoefficients1); + const FloatV S7 = V4GetW(sinCoefficients1); + const FloatV S8 = V4GetX(sinCoefficients2); + const FloatV S9 = V4GetY(sinCoefficients2); + const FloatV S10 = V4GetZ(sinCoefficients2); + const FloatV S11 = V4GetW(sinCoefficients2); + + FloatV Result; + Result = FScaleAdd(S1, V3, V1); + Result = FScaleAdd(S2, V5, Result); + Result = FScaleAdd(S3, V7, Result); + Result = FScaleAdd(S4, V9, Result); + Result = FScaleAdd(S5, V11, Result); + Result = FScaleAdd(S6, V13, Result); + Result = FScaleAdd(S7, V15, Result); + Result = FScaleAdd(S8, V17, Result); + Result = FScaleAdd(S9, V19, Result); + Result = FScaleAdd(S10, V21, Result); + Result = FScaleAdd(S11, V23, Result); + + return Result; +} + +PX_FORCE_INLINE FloatV FCos(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const FloatV recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const FloatV twoPi = V4LoadA(g_PXTwoPi.f); + const FloatV tmp = FMul(a, recipTwoPi); + const FloatV b = FRound(tmp); + const FloatV V1 = FNegScaleSub(twoPi, b, a); + + // cos(V) ~= 1 - V^2 / 2! + V^4 / 4! - V^6 / 6! + V^8 / 8! - V^10 / 10! + V^12 / 12! - + // V^14 / 14! + V^16 / 16! - V^18 / 18! + V^20 / 20! - V^22 / 22! (for -PI <= V < PI) + const FloatV V2 = FMul(V1, V1); + const FloatV V4 = FMul(V2, V2); + const FloatV V6 = FMul(V4, V2); + const FloatV V8 = FMul(V4, V4); + const FloatV V10 = FMul(V6, V4); + const FloatV V12 = FMul(V6, V6); + const FloatV V14 = FMul(V8, V6); + const FloatV V16 = FMul(V8, V8); + const FloatV V18 = FMul(V10, V8); + const FloatV V20 = FMul(V10, V10); + const FloatV V22 = FMul(V12, V10); + + const Vec4V cosCoefficients0 = V4LoadA(g_PXCosCoefficients0.f); + const Vec4V cosCoefficients1 = V4LoadA(g_PXCosCoefficients1.f); + const Vec4V cosCoefficients2 = V4LoadA(g_PXCosCoefficients2.f); + + const FloatV C1 = V4GetY(cosCoefficients0); + const FloatV C2 = V4GetZ(cosCoefficients0); + const FloatV C3 = V4GetW(cosCoefficients0); + const FloatV C4 = V4GetX(cosCoefficients1); + const FloatV C5 = V4GetY(cosCoefficients1); + const FloatV C6 = V4GetZ(cosCoefficients1); + const FloatV C7 = V4GetW(cosCoefficients1); + const FloatV C8 = V4GetX(cosCoefficients2); + const FloatV C9 = V4GetY(cosCoefficients2); + const FloatV C10 = V4GetZ(cosCoefficients2); + const FloatV C11 = V4GetW(cosCoefficients2); + + FloatV Result; + Result = FScaleAdd(C1, V2, V4One()); + Result = FScaleAdd(C2, V4, Result); + Result = FScaleAdd(C3, V6, Result); + Result = FScaleAdd(C4, V8, Result); + Result = FScaleAdd(C5, V10, Result); + Result = FScaleAdd(C6, V12, Result); + Result = FScaleAdd(C7, V14, Result); + Result = FScaleAdd(C8, V16, Result); + Result = FScaleAdd(C9, V18, Result); + Result = FScaleAdd(C10, V20, Result); + Result = FScaleAdd(C11, V22, Result); + + return Result; +} + +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV min, const FloatV max) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(min); + ASSERT_ISVALIDFLOATV(max); + const BoolV c = BOr(FIsGrtr(a, max), FIsGrtr(min, a)); + return PxU32(!BAllEqFFFF(c)); +} + +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV min, const FloatV max) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(min); + ASSERT_ISVALIDFLOATV(max); + const BoolV c = BAnd(FIsGrtrOrEq(a, min), FIsGrtrOrEq(max, a)); + return BAllEqTTTT(c); +} + +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV bounds) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(bounds); + return FOutOfBounds(a, FNeg(bounds), bounds); +} + +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV bounds) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(bounds); + return FInBounds(a, FNeg(bounds), bounds); +} + +////////////////////////////////// +// VEC3V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V V3Splat(const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + const __m128 zero = _mm_setzero_ps(); + const __m128 fff0 = _mm_move_ss(f, zero); + return _mm_shuffle_ps(fff0, fff0, _MM_SHUFFLE(0, 1, 2, 3)); +} + +PX_FORCE_INLINE Vec3V V3Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z) +{ + ASSERT_ISVALIDFLOATV(x); + ASSERT_ISVALIDFLOATV(y); + ASSERT_ISVALIDFLOATV(z); + // static on zero causes compiler crash on x64 debug_opt + const __m128 zero = _mm_setzero_ps(); + const __m128 xy = _mm_move_ss(x, y); + const __m128 z0 = _mm_move_ss(zero, z); + + return _mm_shuffle_ps(xy, z0, _MM_SHUFFLE(1, 0, 0, 1)); +} + +PX_FORCE_INLINE FloatV V3GetX(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(0, 0, 0, 0)); +} + +PX_FORCE_INLINE FloatV V3GetY(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(1, 1, 1, 1)); +} + +PX_FORCE_INLINE FloatV V3GetZ(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(2, 2, 2, 2)); +} + +PX_FORCE_INLINE Vec3V V3SetX(const Vec3V v, const FloatV f) +{ + ASSERT_ISVALIDVEC3V(v); + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BFTTT(), v, f); +} + +PX_FORCE_INLINE Vec3V V3SetY(const Vec3V v, const FloatV f) +{ + ASSERT_ISVALIDVEC3V(v); + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTFTT(), v, f); +} + +PX_FORCE_INLINE Vec3V V3SetZ(const Vec3V v, const FloatV f) +{ + ASSERT_ISVALIDVEC3V(v); + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTTFT(), v, f); +} + +PX_FORCE_INLINE Vec3V V3ColX(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + const Vec3V r = _mm_shuffle_ps(a, c, _MM_SHUFFLE(3, 0, 3, 0)); + return V3SetY(r, V3GetX(b)); +} + +PX_FORCE_INLINE Vec3V V3ColY(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + const Vec3V r = _mm_shuffle_ps(a, c, _MM_SHUFFLE(3, 1, 3, 1)); + return V3SetY(r, V3GetY(b)); +} + +PX_FORCE_INLINE Vec3V V3ColZ(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + const Vec3V r = _mm_shuffle_ps(a, c, _MM_SHUFFLE(3, 2, 3, 2)); + return V3SetY(r, V3GetZ(b)); +} + +PX_FORCE_INLINE Vec3V V3Zero() +{ + return _mm_setzero_ps(); +} + +PX_FORCE_INLINE Vec3V V3One() +{ + return V3Load(1.0f); +} + +PX_FORCE_INLINE Vec3V V3Eps() +{ + return V3Load(PX_EPS_REAL); +} + +PX_FORCE_INLINE Vec3V V3Neg(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + return _mm_sub_ps(_mm_setzero_ps(), f); +} + +PX_FORCE_INLINE Vec3V V3Add(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_add_ps(a, b); +} + +PX_FORCE_INLINE Vec3V V3Sub(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_sub_ps(a, b); +} + +PX_FORCE_INLINE Vec3V V3Scale(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_mul_ps(a, b); +} + +PX_FORCE_INLINE Vec3V V3Mul(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_mul_ps(a, b); +} + +PX_FORCE_INLINE Vec3V V3ScaleInv(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_div_ps(a, b); +} + +PX_FORCE_INLINE Vec3V V3Div(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return V4ClearW(_mm_div_ps(a, b)); +} + +PX_FORCE_INLINE Vec3V V3ScaleInvFast(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + return _mm_mul_ps(a, _mm_rcp_ps(b)); +} + +PX_FORCE_INLINE Vec3V V3DivFast(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return V4ClearW(_mm_mul_ps(a, _mm_rcp_ps(b))); +} + +PX_FORCE_INLINE Vec3V V3Recip(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 zero = V3Zero(); + const __m128 tttf = BTTTF(); + const __m128 recipA = _mm_div_ps(V3One(), a); + return V4Sel(tttf, recipA, zero); +} + +PX_FORCE_INLINE Vec3V V3RecipFast(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 zero = V3Zero(); + const __m128 tttf = BTTTF(); + const __m128 recipA = _mm_rcp_ps(a); + return V4Sel(tttf, recipA, zero); +} + +PX_FORCE_INLINE Vec3V V3Rsqrt(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 zero = V3Zero(); + const __m128 tttf = BTTTF(); + const __m128 recipA = _mm_div_ps(V3One(), _mm_sqrt_ps(a)); + return V4Sel(tttf, recipA, zero); +} + +PX_FORCE_INLINE Vec3V V3RsqrtFast(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 zero = V3Zero(); + const __m128 tttf = BTTTF(); + const __m128 recipA = _mm_rsqrt_ps(a); + return V4Sel(tttf, recipA, zero); +} + +PX_FORCE_INLINE Vec3V V3ScaleAdd(const Vec3V a, const FloatV b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDVEC3V(c); + return V3Add(V3Scale(a, b), c); +} + +PX_FORCE_INLINE Vec3V V3NegScaleSub(const Vec3V a, const FloatV b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDVEC3V(c); + return V3Sub(c, V3Scale(a, b)); +} + +PX_FORCE_INLINE Vec3V V3MulAdd(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + return V3Add(V3Mul(a, b), c); +} + +PX_FORCE_INLINE Vec3V V3NegMulSub(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + return V3Sub(c, V3Mul(a, b)); +} + +PX_FORCE_INLINE Vec3V V3Abs(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return V3Max(a, V3Neg(a)); +} + +PX_FORCE_INLINE FloatV V3Dot(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); +#ifdef __SSE4_2__ + return _mm_dp_ps(a, b, 0x7f); +#else + const __m128 t0 = _mm_mul_ps(a, b); // aw*bw | az*bz | ay*by | ax*bx + const __m128 t1 = _mm_shuffle_ps(t0, t0, _MM_SHUFFLE(1,0,3,2)); // ay*by | ax*bx | aw*bw | az*bz + const __m128 t2 = _mm_add_ps(t0, t1); // ay*by + aw*bw | ax*bx + az*bz | aw*bw + ay*by | az*bz + ax*bx + const __m128 t3 = _mm_shuffle_ps(t2, t2, _MM_SHUFFLE(2,3,0,1)); // ax*bx + az*bz | ay*by + aw*bw | az*bz + ax*bx | aw*bw + ay*by + return _mm_add_ps(t3, t2); // ax*bx + az*bz + ay*by + aw*bw + // ay*by + aw*bw + ax*bx + az*bz + // az*bz + ax*bx + aw*bw + ay*by + // aw*bw + ay*by + az*bz + ax*bx +#endif +} + +PX_FORCE_INLINE Vec3V V3Cross(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); +/* if(0) + { + const __m128 r1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); // z,x,y,w + const __m128 r2 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 0, 2, 1)); // y,z,x,w + const __m128 l1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1)); // y,z,x,w + const __m128 l2 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 1, 0, 2)); // z,x,y,w + return _mm_sub_ps(_mm_mul_ps(l1, l2), _mm_mul_ps(r1, r2)); + } + else*/ + { + const __m128 b0 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3,0,2,1)); + const __m128 a1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3,0,2,1)); + __m128 v = _mm_mul_ps(a1, b); + v = _mm_sub_ps(_mm_mul_ps(a, b0), v); + __m128 res = _mm_shuffle_ps(v, v, _MM_SHUFFLE(3,0,2,1)); + ASSERT_ISVALIDVEC3V(res); + return res; + } +} + +PX_FORCE_INLINE VecCrossV V3PrepareCross(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + VecCrossV v; + v.mR1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); // z,x,y,w + v.mL1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1)); // y,z,x,w + return v; +} + +PX_FORCE_INLINE Vec3V V3Cross(const VecCrossV& a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(b); + const __m128 r2 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 0, 2, 1)); // y,z,x,w + const __m128 l2 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 1, 0, 2)); // z,x,y,w + return _mm_sub_ps(_mm_mul_ps(a.mL1, l2), _mm_mul_ps(a.mR1, r2)); +} + +PX_FORCE_INLINE Vec3V V3Cross(const Vec3V a, const VecCrossV& b) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 r2 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1)); // y,z,x,w + const __m128 l2 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); // z,x,y,w + return _mm_sub_ps(_mm_mul_ps(b.mR1, r2), _mm_mul_ps(b.mL1, l2)); +} + +PX_FORCE_INLINE Vec3V V3Cross(const VecCrossV& a, const VecCrossV& b) +{ + return _mm_sub_ps(_mm_mul_ps(a.mL1, b.mR1), _mm_mul_ps(a.mR1, b.mL1)); +} + +PX_FORCE_INLINE FloatV V3Length(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return _mm_sqrt_ps(V3Dot(a, a)); +} + +PX_FORCE_INLINE FloatV V3LengthSq(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return V3Dot(a, a); +} + +PX_FORCE_INLINE Vec3V V3Normalize(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISFINITELENGTH(a); + return V3ScaleInv(a, _mm_sqrt_ps(V3Dot(a, a))); +} + +PX_FORCE_INLINE Vec3V V3NormalizeFast(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISFINITELENGTH(a); + return V3Scale(a, _mm_rsqrt_ps(V3Dot(a, a))); +} + +PX_FORCE_INLINE Vec3V V3NormalizeSafe(const Vec3V a, const Vec3V unsafeReturnValue) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 eps = FEps(); + const __m128 length = V3Length(a); + const __m128 isGreaterThanZero = FIsGrtr(length, eps); + return V3Sel(isGreaterThanZero, V3ScaleInv(a, length), unsafeReturnValue); +} + +PX_FORCE_INLINE Vec3V V3Sel(const BoolV c, const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(_mm_or_ps(_mm_andnot_ps(c, b), _mm_and_ps(c, a))); + return _mm_or_ps(_mm_andnot_ps(c, b), _mm_and_ps(c, a)); +} + +PX_FORCE_INLINE BoolV V3IsGrtr(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_cmpgt_ps(a, b); +} + +PX_FORCE_INLINE BoolV V3IsGrtrOrEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_cmpge_ps(a, b); +} + +PX_FORCE_INLINE BoolV V3IsEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_cmpeq_ps(a, b); +} + +PX_FORCE_INLINE Vec3V V3Max(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_max_ps(a, b); +} + +PX_FORCE_INLINE Vec3V V3Min(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return _mm_min_ps(a, b); +} + +PX_FORCE_INLINE FloatV V3ExtractMax(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 shuf1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)); + const __m128 shuf2 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)); + const __m128 shuf3 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)); + return _mm_max_ps(_mm_max_ps(shuf1, shuf2), shuf3); +} + +PX_FORCE_INLINE FloatV V3ExtractMin(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 shuf1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)); + const __m128 shuf2 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)); + const __m128 shuf3 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)); + return _mm_min_ps(_mm_min_ps(shuf1, shuf2), shuf3); +} + +//// if(a > 0.0f) return 1.0f; else if a == 0.f return 0.f, else return -1.f; +// PX_FORCE_INLINE Vec3V V3MathSign(const Vec3V a) +//{ +// VECMATHAOS_ASSERT(isValidVec3V(a)); +// +// const __m128i ai = _mm_cvtps_epi32(a); +// const __m128i bi = _mm_cvtps_epi32(V3Neg(a)); +// const __m128 aa = _mm_cvtepi32_ps(_mm_srai_epi32(ai, 31)); +// const __m128 bb = _mm_cvtepi32_ps(_mm_srai_epi32(bi, 31)); +// return _mm_or_ps(aa, bb); +//} + +// return (a >= 0.0f) ? 1.0f : -1.0f; +PX_FORCE_INLINE Vec3V V3Sign(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const __m128 zero = V3Zero(); + const __m128 one = V3One(); + const __m128 none = V3Neg(one); + return V3Sel(V3IsGrtrOrEq(a, zero), one, none); +} + +PX_FORCE_INLINE Vec3V V3Clamp(const Vec3V a, const Vec3V minV, const Vec3V maxV) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(minV); + ASSERT_ISVALIDVEC3V(maxV); + return V3Max(V3Min(a, maxV), minV); +} + +PX_FORCE_INLINE PxU32 V3AllGrtr(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return internalSimd::BAllTrue3_R(V4IsGrtr(a, b)); +} + +PX_FORCE_INLINE PxU32 V3AllGrtrOrEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return internalSimd::BAllTrue3_R(V4IsGrtrOrEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V3AllEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return internalSimd::BAllTrue3_R(V4IsEq(a, b)); +} + +PX_FORCE_INLINE Vec3V V3Round(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); +#ifdef __SSE4_2__ + return _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); +#else + // return _mm_round_ps(a, 0x0); + const Vec3V half = V3Load(0.5f); + const __m128 signBit = _mm_cvtepi32_ps(_mm_srli_epi32(_mm_cvtps_epi32(a), 31)); + const Vec3V aRound = V3Sub(V3Add(a, half), signBit); + __m128i tmp = _mm_cvttps_epi32(aRound); + return _mm_cvtepi32_ps(tmp); +#endif +} + +PX_FORCE_INLINE Vec3V V3Sin(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const Vec4V twoPi = V4LoadA(g_PXTwoPi.f); + const Vec3V tmp = V3Scale(a, recipTwoPi); + const Vec3V b = V3Round(tmp); + const Vec3V V1 = V3NegScaleSub(b, twoPi, a); + + // sin(V) ~= V - V^3 / 3! + V^5 / 5! - V^7 / 7! + V^9 / 9! - V^11 / 11! + V^13 / 13! - + // V^15 / 15! + V^17 / 17! - V^19 / 19! + V^21 / 21! - V^23 / 23! (for -PI <= V < PI) + const Vec3V V2 = V3Mul(V1, V1); + const Vec3V V3 = V3Mul(V2, V1); + const Vec3V V5 = V3Mul(V3, V2); + const Vec3V V7 = V3Mul(V5, V2); + const Vec3V V9 = V3Mul(V7, V2); + const Vec3V V11 = V3Mul(V9, V2); + const Vec3V V13 = V3Mul(V11, V2); + const Vec3V V15 = V3Mul(V13, V2); + const Vec3V V17 = V3Mul(V15, V2); + const Vec3V V19 = V3Mul(V17, V2); + const Vec3V V21 = V3Mul(V19, V2); + const Vec3V V23 = V3Mul(V21, V2); + + const Vec4V sinCoefficients0 = V4LoadA(g_PXSinCoefficients0.f); + const Vec4V sinCoefficients1 = V4LoadA(g_PXSinCoefficients1.f); + const Vec4V sinCoefficients2 = V4LoadA(g_PXSinCoefficients2.f); + + const FloatV S1 = V4GetY(sinCoefficients0); + const FloatV S2 = V4GetZ(sinCoefficients0); + const FloatV S3 = V4GetW(sinCoefficients0); + const FloatV S4 = V4GetX(sinCoefficients1); + const FloatV S5 = V4GetY(sinCoefficients1); + const FloatV S6 = V4GetZ(sinCoefficients1); + const FloatV S7 = V4GetW(sinCoefficients1); + const FloatV S8 = V4GetX(sinCoefficients2); + const FloatV S9 = V4GetY(sinCoefficients2); + const FloatV S10 = V4GetZ(sinCoefficients2); + const FloatV S11 = V4GetW(sinCoefficients2); + + Vec3V Result; + Result = V3ScaleAdd(V3, S1, V1); + Result = V3ScaleAdd(V5, S2, Result); + Result = V3ScaleAdd(V7, S3, Result); + Result = V3ScaleAdd(V9, S4, Result); + Result = V3ScaleAdd(V11, S5, Result); + Result = V3ScaleAdd(V13, S6, Result); + Result = V3ScaleAdd(V15, S7, Result); + Result = V3ScaleAdd(V17, S8, Result); + Result = V3ScaleAdd(V19, S9, Result); + Result = V3ScaleAdd(V21, S10, Result); + Result = V3ScaleAdd(V23, S11, Result); + + ASSERT_ISVALIDVEC3V(Result); + return Result; +} + +PX_FORCE_INLINE Vec3V V3Cos(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const Vec4V twoPi = V4LoadA(g_PXTwoPi.f); + const Vec3V tmp = V3Scale(a, recipTwoPi); + const Vec3V b = V3Round(tmp); + const Vec3V V1 = V3NegScaleSub(b, twoPi, a); + + // cos(V) ~= 1 - V^2 / 2! + V^4 / 4! - V^6 / 6! + V^8 / 8! - V^10 / 10! + V^12 / 12! - + // V^14 / 14! + V^16 / 16! - V^18 / 18! + V^20 / 20! - V^22 / 22! (for -PI <= V < PI) + const Vec3V V2 = V3Mul(V1, V1); + const Vec3V V4 = V3Mul(V2, V2); + const Vec3V V6 = V3Mul(V4, V2); + const Vec3V V8 = V3Mul(V4, V4); + const Vec3V V10 = V3Mul(V6, V4); + const Vec3V V12 = V3Mul(V6, V6); + const Vec3V V14 = V3Mul(V8, V6); + const Vec3V V16 = V3Mul(V8, V8); + const Vec3V V18 = V3Mul(V10, V8); + const Vec3V V20 = V3Mul(V10, V10); + const Vec3V V22 = V3Mul(V12, V10); + + const Vec4V cosCoefficients0 = V4LoadA(g_PXCosCoefficients0.f); + const Vec4V cosCoefficients1 = V4LoadA(g_PXCosCoefficients1.f); + const Vec4V cosCoefficients2 = V4LoadA(g_PXCosCoefficients2.f); + + const FloatV C1 = V4GetY(cosCoefficients0); + const FloatV C2 = V4GetZ(cosCoefficients0); + const FloatV C3 = V4GetW(cosCoefficients0); + const FloatV C4 = V4GetX(cosCoefficients1); + const FloatV C5 = V4GetY(cosCoefficients1); + const FloatV C6 = V4GetZ(cosCoefficients1); + const FloatV C7 = V4GetW(cosCoefficients1); + const FloatV C8 = V4GetX(cosCoefficients2); + const FloatV C9 = V4GetY(cosCoefficients2); + const FloatV C10 = V4GetZ(cosCoefficients2); + const FloatV C11 = V4GetW(cosCoefficients2); + + Vec3V Result; + Result = V3ScaleAdd(V2, C1, V3One()); + Result = V3ScaleAdd(V4, C2, Result); + Result = V3ScaleAdd(V6, C3, Result); + Result = V3ScaleAdd(V8, C4, Result); + Result = V3ScaleAdd(V10, C5, Result); + Result = V3ScaleAdd(V12, C6, Result); + Result = V3ScaleAdd(V14, C7, Result); + Result = V3ScaleAdd(V16, C8, Result); + Result = V3ScaleAdd(V18, C9, Result); + Result = V3ScaleAdd(V20, C10, Result); + Result = V3ScaleAdd(V22, C11, Result); + + ASSERT_ISVALIDVEC3V(Result); + return Result; +} + +PX_FORCE_INLINE Vec3V V3PermYZZ(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 2, 2, 1)); +} + +PX_FORCE_INLINE Vec3V V3PermXYX(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 1, 0)); +} + +PX_FORCE_INLINE Vec3V V3PermYZX(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1)); +} + +PX_FORCE_INLINE Vec3V V3PermZXY(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); +} + +PX_FORCE_INLINE Vec3V V3PermZZY(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 2, 2)); +} + +PX_FORCE_INLINE Vec3V V3PermYXX(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 0, 1)); +} + +PX_FORCE_INLINE Vec3V V3Perm_Zero_1Z_0Y(const Vec3V v0, const Vec3V v1) +{ + ASSERT_ISVALIDVEC3V(v0); + ASSERT_ISVALIDVEC3V(v1); + return _mm_shuffle_ps(v1, v0, _MM_SHUFFLE(3, 1, 2, 3)); +} + +PX_FORCE_INLINE Vec3V V3Perm_0Z_Zero_1X(const Vec3V v0, const Vec3V v1) +{ + ASSERT_ISVALIDVEC3V(v0); + ASSERT_ISVALIDVEC3V(v1); + return _mm_shuffle_ps(v0, v1, _MM_SHUFFLE(3, 0, 3, 2)); +} + +PX_FORCE_INLINE Vec3V V3Perm_1Y_0X_Zero(const Vec3V v0, const Vec3V v1) +{ + ASSERT_ISVALIDVEC3V(v0); + ASSERT_ISVALIDVEC3V(v1); + // There must be a better way to do this. + Vec3V v2 = V3Zero(); + const FloatV y1 = V3GetY(v1); + const FloatV x0 = V3GetX(v0); + v2 = V3SetX(v2, y1); + return V3SetY(v2, x0); +} + +PX_FORCE_INLINE FloatV V3SumElems(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); +#ifdef __SSE4_2__ + Vec3V r = _mm_hadd_ps(a, a); + r = _mm_hadd_ps(r, r); + return r; +#else + const __m128 shuf1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)); // z,y,x,w + const __m128 shuf2 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)); // y,x,w,z + const __m128 shuf3 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)); // x,w,z,y + return _mm_add_ps(_mm_add_ps(shuf1, shuf2), shuf3); +#endif +} + +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V min, const Vec3V max) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(min); + ASSERT_ISVALIDVEC3V(max); + const BoolV c = BOr(V3IsGrtr(a, max), V3IsGrtr(min, a)); + return PxU32(!BAllEqFFFF(c)); +} + +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V min, const Vec3V max) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(min); + ASSERT_ISVALIDVEC3V(max); + const BoolV c = BAnd(V3IsGrtrOrEq(a, min), V3IsGrtrOrEq(max, a)); + return BAllEqTTTT(c); +} + +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V bounds) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(bounds); + return V3OutOfBounds(a, V3Neg(bounds), bounds); +} + +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V bounds) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(bounds); + return V3InBounds(a, V3Neg(bounds), bounds); +} + +PX_FORCE_INLINE void V3Transpose(Vec3V& col0, Vec3V& col1, Vec3V& col2) +{ + ASSERT_ISVALIDVEC3V(col0); + ASSERT_ISVALIDVEC3V(col1); + ASSERT_ISVALIDVEC3V(col2); + const Vec3V col3 = _mm_setzero_ps(); + const Vec3V tmp0 = _mm_unpacklo_ps(col0, col1); + const Vec3V tmp2 = _mm_unpacklo_ps(col2, col3); + const Vec3V tmp1 = _mm_unpackhi_ps(col0, col1); + const Vec3V tmp3 = _mm_unpackhi_ps(col2, col3); + col0 = _mm_movelh_ps(tmp0, tmp2); + col1 = _mm_movehl_ps(tmp2, tmp0); + col2 = _mm_movelh_ps(tmp1, tmp3); +} + +////////////////////////////////// +// VEC4V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V V4Splat(const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + // return _mm_shuffle_ps(f, f, _MM_SHUFFLE(0,0,0,0)); + return f; +} + +PX_FORCE_INLINE Vec4V V4Merge(const FloatV* const floatVArray) +{ + ASSERT_ISVALIDFLOATV(floatVArray[0]); + ASSERT_ISVALIDFLOATV(floatVArray[1]); + ASSERT_ISVALIDFLOATV(floatVArray[2]); + ASSERT_ISVALIDFLOATV(floatVArray[3]); + const __m128 xw = _mm_move_ss(floatVArray[1], floatVArray[0]); // y, y, y, x + const __m128 yz = _mm_move_ss(floatVArray[2], floatVArray[3]); // z, z, z, w + return _mm_shuffle_ps(xw, yz, _MM_SHUFFLE(0, 2, 1, 0)); +} + +PX_FORCE_INLINE Vec4V V4Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z, const FloatVArg w) +{ + ASSERT_ISVALIDFLOATV(x); + ASSERT_ISVALIDFLOATV(y); + ASSERT_ISVALIDFLOATV(z); + ASSERT_ISVALIDFLOATV(w); + const __m128 xw = _mm_move_ss(y, x); // y, y, y, x + const __m128 yz = _mm_move_ss(z, w); // z, z, z, w + return _mm_shuffle_ps(xw, yz, _MM_SHUFFLE(0, 2, 1, 0)); +} + +PX_FORCE_INLINE Vec4V V4MergeW(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const Vec4V xz = _mm_unpackhi_ps(x, z); + const Vec4V yw = _mm_unpackhi_ps(y, w); + return _mm_unpackhi_ps(xz, yw); +} + +PX_FORCE_INLINE Vec4V V4MergeZ(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const Vec4V xz = _mm_unpackhi_ps(x, z); + const Vec4V yw = _mm_unpackhi_ps(y, w); + return _mm_unpacklo_ps(xz, yw); +} + +PX_FORCE_INLINE Vec4V V4MergeY(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const Vec4V xz = _mm_unpacklo_ps(x, z); + const Vec4V yw = _mm_unpacklo_ps(y, w); + return _mm_unpackhi_ps(xz, yw); +} + +PX_FORCE_INLINE Vec4V V4MergeX(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const Vec4V xz = _mm_unpacklo_ps(x, z); + const Vec4V yw = _mm_unpacklo_ps(y, w); + return _mm_unpacklo_ps(xz, yw); +} + +PX_FORCE_INLINE Vec4V V4UnpackXY(const Vec4VArg a, const Vec4VArg b) +{ + return _mm_unpacklo_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4UnpackZW(const Vec4VArg a, const Vec4VArg b) +{ + return _mm_unpackhi_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4PermYXWZ(const Vec4V a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 0, 1)); +} + +PX_FORCE_INLINE Vec4V V4PermXZXZ(const Vec4V a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 0, 2, 0)); +} + +PX_FORCE_INLINE Vec4V V4PermYWYW(const Vec4V a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 3, 1)); +} + +PX_FORCE_INLINE Vec4V V4PermYZXW(const Vec4V a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1)); +} + +PX_FORCE_INLINE Vec4V V4PermZWXY(const Vec4V a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 0, 3, 2)); +} + +template +PX_FORCE_INLINE Vec4V V4Perm(const Vec4V a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(w, z, y, x)); +} + +PX_FORCE_INLINE FloatV V4GetW(const Vec4V f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(3, 3, 3, 3)); +} + +PX_FORCE_INLINE FloatV V4GetX(const Vec4V f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(0, 0, 0, 0)); +} + +PX_FORCE_INLINE FloatV V4GetY(const Vec4V f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(1, 1, 1, 1)); +} + +PX_FORCE_INLINE FloatV V4GetZ(const Vec4V f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(2, 2, 2, 2)); +} + +PX_FORCE_INLINE Vec4V V4SetW(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTTTF(), v, f); +} + +PX_FORCE_INLINE Vec4V V4SetX(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BFTTT(), v, f); +} + +PX_FORCE_INLINE Vec4V V4SetY(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTFTT(), v, f); +} + +PX_FORCE_INLINE Vec4V V4SetZ(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTTFT(), v, f); +} + +PX_FORCE_INLINE Vec4V V4Zero() +{ + return _mm_setzero_ps(); +} + +PX_FORCE_INLINE Vec4V V4One() +{ + return V4Load(1.0f); +} + +PX_FORCE_INLINE Vec4V V4Eps() +{ + return V4Load(PX_EPS_REAL); +} + +PX_FORCE_INLINE Vec4V V4Neg(const Vec4V f) +{ + return _mm_sub_ps(_mm_setzero_ps(), f); +} + +PX_FORCE_INLINE Vec4V V4Add(const Vec4V a, const Vec4V b) +{ + return _mm_add_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4Sub(const Vec4V a, const Vec4V b) +{ + return _mm_sub_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4Scale(const Vec4V a, const FloatV b) +{ + return _mm_mul_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4Mul(const Vec4V a, const Vec4V b) +{ + return _mm_mul_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4ScaleInv(const Vec4V a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(b); + return _mm_div_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4Div(const Vec4V a, const Vec4V b) +{ + return _mm_div_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4ScaleInvFast(const Vec4V a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(b); + return _mm_mul_ps(a, _mm_rcp_ps(b)); +} + +PX_FORCE_INLINE Vec4V V4DivFast(const Vec4V a, const Vec4V b) +{ + return _mm_mul_ps(a, _mm_rcp_ps(b)); +} + +PX_FORCE_INLINE Vec4V V4Recip(const Vec4V a) +{ + return _mm_div_ps(V4One(), a); +} + +PX_FORCE_INLINE Vec4V V4RecipFast(const Vec4V a) +{ + return _mm_rcp_ps(a); +} + +PX_FORCE_INLINE Vec4V V4Rsqrt(const Vec4V a) +{ + return _mm_div_ps(V4One(), _mm_sqrt_ps(a)); +} + +PX_FORCE_INLINE Vec4V V4RsqrtFast(const Vec4V a) +{ + return _mm_rsqrt_ps(a); +} + +PX_FORCE_INLINE Vec4V V4Sqrt(const Vec4V a) +{ + return _mm_sqrt_ps(a); +} + +PX_FORCE_INLINE Vec4V V4ScaleAdd(const Vec4V a, const FloatV b, const Vec4V c) +{ + ASSERT_ISVALIDFLOATV(b); + return V4Add(V4Scale(a, b), c); +} + +PX_FORCE_INLINE Vec4V V4NegScaleSub(const Vec4V a, const FloatV b, const Vec4V c) +{ + ASSERT_ISVALIDFLOATV(b); + return V4Sub(c, V4Scale(a, b)); +} + +PX_FORCE_INLINE Vec4V V4MulAdd(const Vec4V a, const Vec4V b, const Vec4V c) +{ + return V4Add(V4Mul(a, b), c); +} + +PX_FORCE_INLINE Vec4V V4NegMulSub(const Vec4V a, const Vec4V b, const Vec4V c) +{ + return V4Sub(c, V4Mul(a, b)); +} + +PX_FORCE_INLINE Vec4V V4Abs(const Vec4V a) +{ + return V4Max(a, V4Neg(a)); +} + +PX_FORCE_INLINE FloatV V4SumElements(const Vec4V a) +{ +#ifdef __SSE4_2__ + Vec4V r = _mm_hadd_ps(a, a); + r = _mm_hadd_ps(r, r); + return r; +#else + const Vec4V xy = V4UnpackXY(a, a); // x,x,y,y + const Vec4V zw = V4UnpackZW(a, a); // z,z,w,w + const Vec4V xz_yw = V4Add(xy, zw); // x+z,x+z,y+w,y+w + const FloatV xz = V4GetX(xz_yw); // x+z + const FloatV yw = V4GetZ(xz_yw); // y+w + return FAdd(xz, yw); // sum +#endif +} + +PX_FORCE_INLINE FloatV V4Dot(const Vec4V a, const Vec4V b) +{ +#ifdef __SSE4_2__ + return _mm_dp_ps(a, b, 0xff); +#else + //const __m128 dot1 = _mm_mul_ps(a, b); // x,y,z,w + //const __m128 shuf1 = _mm_shuffle_ps(dot1, dot1, _MM_SHUFFLE(2, 1, 0, 3)); // w,x,y,z + //const __m128 shuf2 = _mm_shuffle_ps(dot1, dot1, _MM_SHUFFLE(1, 0, 3, 2)); // z,w,x,y + //const __m128 shuf3 = _mm_shuffle_ps(dot1, dot1, _MM_SHUFFLE(0, 3, 2, 1)); // y,z,w,x + //return _mm_add_ps(_mm_add_ps(shuf2, shuf3), _mm_add_ps(dot1, shuf1)); + + // PT: this version has two less instructions but we should check its accuracy + // aw*bw | az*bz | ay*by | ax*bx + const __m128 t0 = _mm_mul_ps(a, b); + // ay*by | ax*bx | aw*bw | az*bz + const __m128 t1 = _mm_shuffle_ps(t0, t0, _MM_SHUFFLE(1, 0, 3, 2)); + // ay*by + aw*bw | ax*bx + az*bz | aw*bw + ay*by | az*bz + ax*bx + const __m128 t2 = _mm_add_ps(t0, t1); + // ax*bx + az*bz | ay*by + aw*bw | az*bz + ax*bx | aw*bw + ay*by + const __m128 t3 = _mm_shuffle_ps(t2, t2, _MM_SHUFFLE(2, 3, 0, 1)); + // ax*bx + az*bz + ay*by + aw*bw + return _mm_add_ps(t3, t2); + // ay*by + aw*bw + ax*bx + az*bz + // az*bz + ax*bx + aw*bw + ay*by + // aw*bw + ay*by + az*bz + ax*bx +#endif +} + +PX_FORCE_INLINE FloatV V4Dot3(const Vec4V a, const Vec4V b) +{ +#ifdef __SSE4_2__ + return _mm_dp_ps(a, b, 0x7f); +#else + const __m128 dot1 = _mm_mul_ps(a, b); // aw*bw | az*bz | ay*by | ax*bx + const __m128 shuf1 = _mm_shuffle_ps(dot1, dot1, _MM_SHUFFLE(0, 0, 0, 0)); // ax*bx | ax*bx | ax*bx | ax*bx + const __m128 shuf2 = _mm_shuffle_ps(dot1, dot1, _MM_SHUFFLE(1, 1, 1, 1)); // ay*by | ay*by | ay*by | ay*by + const __m128 shuf3 = _mm_shuffle_ps(dot1, dot1, _MM_SHUFFLE(2, 2, 2, 2)); // az*bz | az*bz | az*bz | az*bz + return _mm_add_ps(_mm_add_ps(shuf1, shuf2), shuf3); // ax*bx + ay*by + az*bz in each component +#endif +} + +PX_FORCE_INLINE Vec4V V4Cross(const Vec4V a, const Vec4V b) +{ +/* if(0) + { + const __m128 r1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); // z,x,y,w + const __m128 r2 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 0, 2, 1)); // y,z,x,w + const __m128 l1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1)); // y,z,x,w + const __m128 l2 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 1, 0, 2)); // z,x,y,w + return _mm_sub_ps(_mm_mul_ps(l1, l2), _mm_mul_ps(r1, r2)); + } + else*/ + { + const __m128 b0 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3,0,2,1)); + const __m128 a1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3,0,2,1)); + __m128 v = _mm_mul_ps(a1, b); + v = _mm_sub_ps(_mm_mul_ps(a, b0), v); + return _mm_shuffle_ps(v, v, _MM_SHUFFLE(3,0,2,1)); + } +} + +PX_FORCE_INLINE FloatV V4Length(const Vec4V a) +{ + return _mm_sqrt_ps(V4Dot(a, a)); +} + +PX_FORCE_INLINE FloatV V4LengthSq(const Vec4V a) +{ + return V4Dot(a, a); +} + +PX_FORCE_INLINE Vec4V V4Normalize(const Vec4V a) +{ + ASSERT_ISFINITELENGTH(a); + return V4ScaleInv(a, _mm_sqrt_ps(V4Dot(a, a))); +} + +PX_FORCE_INLINE Vec4V V4NormalizeFast(const Vec4V a) +{ + ASSERT_ISFINITELENGTH(a); + return V4ScaleInvFast(a, _mm_sqrt_ps(V4Dot(a, a))); +} + +PX_FORCE_INLINE Vec4V V4NormalizeSafe(const Vec4V a, const Vec4V unsafeReturnValue) +{ + const __m128 eps = V3Eps(); + const __m128 length = V4Length(a); + const __m128 isGreaterThanZero = V4IsGrtr(length, eps); + return V4Sel(isGreaterThanZero, V4ScaleInv(a, length), unsafeReturnValue); +} + +PX_FORCE_INLINE Vec4V V4Sel(const BoolV c, const Vec4V a, const Vec4V b) +{ + return _mm_or_ps(_mm_andnot_ps(c, b), _mm_and_ps(c, a)); +} + +PX_FORCE_INLINE BoolV V4IsGrtr(const Vec4V a, const Vec4V b) +{ + return _mm_cmpgt_ps(a, b); +} + +PX_FORCE_INLINE BoolV V4IsGrtrOrEq(const Vec4V a, const Vec4V b) +{ + return _mm_cmpge_ps(a, b); +} + +PX_FORCE_INLINE BoolV V4IsEq(const Vec4V a, const Vec4V b) +{ + return _mm_cmpeq_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4Max(const Vec4V a, const Vec4V b) +{ + return _mm_max_ps(a, b); +} + +PX_FORCE_INLINE Vec4V V4Min(const Vec4V a, const Vec4V b) +{ + return _mm_min_ps(a, b); +} + +PX_FORCE_INLINE FloatV V4ExtractMax(const Vec4V a) +{ + const __m128 shuf1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 1, 0, 3)); + const __m128 shuf2 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 0, 3, 2)); + const __m128 shuf3 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 3, 2, 1)); + + return _mm_max_ps(_mm_max_ps(a, shuf1), _mm_max_ps(shuf2, shuf3)); +} + +PX_FORCE_INLINE FloatV V4ExtractMin(const Vec4V a) +{ + const __m128 shuf1 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 1, 0, 3)); + const __m128 shuf2 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 0, 3, 2)); + const __m128 shuf3 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 3, 2, 1)); + + return _mm_min_ps(_mm_min_ps(a, shuf1), _mm_min_ps(shuf2, shuf3)); +} + +PX_FORCE_INLINE Vec4V V4Clamp(const Vec4V a, const Vec4V minV, const Vec4V maxV) +{ + return V4Max(V4Min(a, maxV), minV); +} + +PX_FORCE_INLINE PxU32 V4AllGrtr(const Vec4V a, const Vec4V b) +{ + return internalSimd::BAllTrue4_R(V4IsGrtr(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq(const Vec4V a, const Vec4V b) +{ + return internalSimd::BAllTrue4_R(V4IsGrtrOrEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq3(const Vec4V a, const Vec4V b) +{ + return internalSimd::BAllTrue3_R(V4IsGrtrOrEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AllEq(const Vec4V a, const Vec4V b) +{ + return internalSimd::BAllTrue4_R(V4IsEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AnyGrtr3(const Vec4V a, const Vec4V b) +{ + return internalSimd::BAnyTrue3_R(V4IsGrtr(a, b)); +} + +PX_FORCE_INLINE Vec4V V4Round(const Vec4V a) +{ +#ifdef __SSE4_2__ + return _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); +#else + // return _mm_round_ps(a, 0x0); + const Vec4V half = V4Load(0.5f); + const __m128 signBit = _mm_cvtepi32_ps(_mm_srli_epi32(_mm_cvtps_epi32(a), 31)); + const Vec4V aRound = V4Sub(V4Add(a, half), signBit); + const __m128i tmp = _mm_cvttps_epi32(aRound); + return _mm_cvtepi32_ps(tmp); +#endif +} + +PX_FORCE_INLINE Vec4V V4Sin(const Vec4V a) +{ + // PT: TODO: these should be FLoads + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const Vec4V twoPi = V4LoadA(g_PXTwoPi.f); + const Vec4V tmp = V4Mul(a, recipTwoPi); + const Vec4V b = V4Round(tmp); + const Vec4V V1 = V4NegMulSub(twoPi, b, a); + + // sin(V) ~= V - V^3 / 3! + V^5 / 5! - V^7 / 7! + V^9 / 9! - V^11 / 11! + V^13 / 13! - + // V^15 / 15! + V^17 / 17! - V^19 / 19! + V^21 / 21! - V^23 / 23! (for -PI <= V < PI) + const Vec4V V2 = V4Mul(V1, V1); + const Vec4V V3 = V4Mul(V2, V1); + const Vec4V V5 = V4Mul(V3, V2); + const Vec4V V7 = V4Mul(V5, V2); + const Vec4V V9 = V4Mul(V7, V2); + const Vec4V V11 = V4Mul(V9, V2); + const Vec4V V13 = V4Mul(V11, V2); + const Vec4V V15 = V4Mul(V13, V2); + const Vec4V V17 = V4Mul(V15, V2); + const Vec4V V19 = V4Mul(V17, V2); + const Vec4V V21 = V4Mul(V19, V2); + const Vec4V V23 = V4Mul(V21, V2); + + const Vec4V sinCoefficients0 = V4LoadA(g_PXSinCoefficients0.f); + const Vec4V sinCoefficients1 = V4LoadA(g_PXSinCoefficients1.f); + const Vec4V sinCoefficients2 = V4LoadA(g_PXSinCoefficients2.f); + + const FloatV S1 = V4GetY(sinCoefficients0); + const FloatV S2 = V4GetZ(sinCoefficients0); + const FloatV S3 = V4GetW(sinCoefficients0); + const FloatV S4 = V4GetX(sinCoefficients1); + const FloatV S5 = V4GetY(sinCoefficients1); + const FloatV S6 = V4GetZ(sinCoefficients1); + const FloatV S7 = V4GetW(sinCoefficients1); + const FloatV S8 = V4GetX(sinCoefficients2); + const FloatV S9 = V4GetY(sinCoefficients2); + const FloatV S10 = V4GetZ(sinCoefficients2); + const FloatV S11 = V4GetW(sinCoefficients2); + + Vec4V Result; + Result = V4MulAdd(S1, V3, V1); + Result = V4MulAdd(S2, V5, Result); + Result = V4MulAdd(S3, V7, Result); + Result = V4MulAdd(S4, V9, Result); + Result = V4MulAdd(S5, V11, Result); + Result = V4MulAdd(S6, V13, Result); + Result = V4MulAdd(S7, V15, Result); + Result = V4MulAdd(S8, V17, Result); + Result = V4MulAdd(S9, V19, Result); + Result = V4MulAdd(S10, V21, Result); + Result = V4MulAdd(S11, V23, Result); + + return Result; +} + +PX_FORCE_INLINE Vec4V V4Cos(const Vec4V a) +{ + // PT: TODO: these should be FLoads + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const FloatV twoPi = V4LoadA(g_PXTwoPi.f); + const Vec4V tmp = V4Mul(a, recipTwoPi); + const Vec4V b = V4Round(tmp); + const Vec4V V1 = V4NegMulSub(twoPi, b, a); + + // cos(V) ~= 1 - V^2 / 2! + V^4 / 4! - V^6 / 6! + V^8 / 8! - V^10 / 10! + V^12 / 12! - + // V^14 / 14! + V^16 / 16! - V^18 / 18! + V^20 / 20! - V^22 / 22! (for -PI <= V < PI) + const Vec4V V2 = V4Mul(V1, V1); + const Vec4V V4 = V4Mul(V2, V2); + const Vec4V V6 = V4Mul(V4, V2); + const Vec4V V8 = V4Mul(V4, V4); + const Vec4V V10 = V4Mul(V6, V4); + const Vec4V V12 = V4Mul(V6, V6); + const Vec4V V14 = V4Mul(V8, V6); + const Vec4V V16 = V4Mul(V8, V8); + const Vec4V V18 = V4Mul(V10, V8); + const Vec4V V20 = V4Mul(V10, V10); + const Vec4V V22 = V4Mul(V12, V10); + + const Vec4V cosCoefficients0 = V4LoadA(g_PXCosCoefficients0.f); + const Vec4V cosCoefficients1 = V4LoadA(g_PXCosCoefficients1.f); + const Vec4V cosCoefficients2 = V4LoadA(g_PXCosCoefficients2.f); + + const FloatV C1 = V4GetY(cosCoefficients0); + const FloatV C2 = V4GetZ(cosCoefficients0); + const FloatV C3 = V4GetW(cosCoefficients0); + const FloatV C4 = V4GetX(cosCoefficients1); + const FloatV C5 = V4GetY(cosCoefficients1); + const FloatV C6 = V4GetZ(cosCoefficients1); + const FloatV C7 = V4GetW(cosCoefficients1); + const FloatV C8 = V4GetX(cosCoefficients2); + const FloatV C9 = V4GetY(cosCoefficients2); + const FloatV C10 = V4GetZ(cosCoefficients2); + const FloatV C11 = V4GetW(cosCoefficients2); + + Vec4V Result; + Result = V4MulAdd(C1, V2, V4One()); + Result = V4MulAdd(C2, V4, Result); + Result = V4MulAdd(C3, V6, Result); + Result = V4MulAdd(C4, V8, Result); + Result = V4MulAdd(C5, V10, Result); + Result = V4MulAdd(C6, V12, Result); + Result = V4MulAdd(C7, V14, Result); + Result = V4MulAdd(C8, V16, Result); + Result = V4MulAdd(C9, V18, Result); + Result = V4MulAdd(C10, V20, Result); + Result = V4MulAdd(C11, V22, Result); + + return Result; +} + +PX_FORCE_INLINE void V4Transpose(Vec4V& col0, Vec4V& col1, Vec4V& col2, Vec4V& col3) +{ + const Vec4V tmp0 = _mm_unpacklo_ps(col0, col1); + const Vec4V tmp2 = _mm_unpacklo_ps(col2, col3); + const Vec4V tmp1 = _mm_unpackhi_ps(col0, col1); + const Vec4V tmp3 = _mm_unpackhi_ps(col2, col3); + col0 = _mm_movelh_ps(tmp0, tmp2); + col1 = _mm_movehl_ps(tmp2, tmp0); + col2 = _mm_movelh_ps(tmp1, tmp3); + col3 = _mm_movehl_ps(tmp3, tmp1); +} + +PX_FORCE_INLINE BoolV V4IsEqU32(const VecU32V a, const VecU32V b) +{ + return internalSimd::m128_I2F(_mm_cmpeq_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +////////////////////////////////// +// BoolV +////////////////////////////////// + +PX_FORCE_INLINE BoolV BFFFF() +{ + return _mm_setzero_ps(); +} + +PX_FORCE_INLINE BoolV BFFFT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0,0,0xFFFFFFFF}; + const __m128 ffft=_mm_load_ps((float*)&f); + return ffft;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, 0, 0, 0)); +} + +PX_FORCE_INLINE BoolV BFFTF() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0,0xFFFFFFFF,0}; + const __m128 fftf=_mm_load_ps((float*)&f); + return fftf;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, -1, 0, 0)); +} + +PX_FORCE_INLINE BoolV BFFTT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0,0xFFFFFFFF,0xFFFFFFFF}; + const __m128 fftt=_mm_load_ps((float*)&f); + return fftt;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, -1, 0, 0)); +} + +PX_FORCE_INLINE BoolV BFTFF() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0xFFFFFFFF,0,0}; + const __m128 ftff=_mm_load_ps((float*)&f); + return ftff;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, 0, -1, 0)); +} + +PX_FORCE_INLINE BoolV BFTFT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0xFFFFFFFF,0,0xFFFFFFFF}; + const __m128 ftft=_mm_load_ps((float*)&f); + return ftft;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, 0, -1, 0)); +} + +PX_FORCE_INLINE BoolV BFTTF() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0xFFFFFFFF,0xFFFFFFFF,0}; + const __m128 fttf=_mm_load_ps((float*)&f); + return fttf;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, -1, -1, 0)); +} + +PX_FORCE_INLINE BoolV BFTTT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF}; + const __m128 fttt=_mm_load_ps((float*)&f); + return fttt;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, -1, -1, 0)); +} + +PX_FORCE_INLINE BoolV BTFFF() +{ + // const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0,0,0}; + // const __m128 tfff=_mm_load_ps((float*)&f); + // return tfff; + return internalSimd::m128_I2F(_mm_set_epi32(0, 0, 0, -1)); +} + +PX_FORCE_INLINE BoolV BTFFT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0,0,0xFFFFFFFF}; + const __m128 tfft=_mm_load_ps((float*)&f); + return tfft;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, 0, 0, -1)); +} + +PX_FORCE_INLINE BoolV BTFTF() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0,0xFFFFFFFF,0}; + const __m128 tftf=_mm_load_ps((float*)&f); + return tftf;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, -1, 0, -1)); +} + +PX_FORCE_INLINE BoolV BTFTT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0,0xFFFFFFFF,0xFFFFFFFF}; + const __m128 tftt=_mm_load_ps((float*)&f); + return tftt;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, -1, 0, -1)); +} + +PX_FORCE_INLINE BoolV BTTFF() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0xFFFFFFFF,0,0}; + const __m128 ttff=_mm_load_ps((float*)&f); + return ttff;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, 0, -1, -1)); +} + +PX_FORCE_INLINE BoolV BTTFT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0xFFFFFFFF,0,0xFFFFFFFF}; + const __m128 ttft=_mm_load_ps((float*)&f); + return ttft;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, 0, -1, -1)); +} + +PX_FORCE_INLINE BoolV BTTTF() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0}; + const __m128 tttf=_mm_load_ps((float*)&f); + return tttf;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, -1, -1, -1)); +} + +PX_FORCE_INLINE BoolV BTTTT() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF}; + const __m128 tttt=_mm_load_ps((float*)&f); + return tttt;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, -1, -1, -1)); +} + +PX_FORCE_INLINE BoolV BXMask() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0xFFFFFFFF,0,0,0}; + const __m128 tfff=_mm_load_ps((float*)&f); + return tfff;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, 0, 0, -1)); +} + +PX_FORCE_INLINE BoolV BYMask() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0xFFFFFFFF,0,0}; + const __m128 ftff=_mm_load_ps((float*)&f); + return ftff;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, 0, -1, 0)); +} + +PX_FORCE_INLINE BoolV BZMask() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0,0xFFFFFFFF,0}; + const __m128 fftf=_mm_load_ps((float*)&f); + return fftf;*/ + return internalSimd::m128_I2F(_mm_set_epi32(0, -1, 0, 0)); +} + +PX_FORCE_INLINE BoolV BWMask() +{ + /*const PX_ALIGN(16, PxU32 f[4])={0,0,0,0xFFFFFFFF}; + const __m128 ffft=_mm_load_ps((float*)&f); + return ffft;*/ + return internalSimd::m128_I2F(_mm_set_epi32(-1, 0, 0, 0)); +} + +PX_FORCE_INLINE BoolV BGetX(const BoolV f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(0, 0, 0, 0)); +} + +PX_FORCE_INLINE BoolV BGetY(const BoolV f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(1, 1, 1, 1)); +} + +PX_FORCE_INLINE BoolV BGetZ(const BoolV f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(2, 2, 2, 2)); +} + +PX_FORCE_INLINE BoolV BGetW(const BoolV f) +{ + return _mm_shuffle_ps(f, f, _MM_SHUFFLE(3, 3, 3, 3)); +} + +PX_FORCE_INLINE BoolV BSetX(const BoolV v, const BoolV f) +{ + return V4Sel(BFTTT(), v, f); +} + +PX_FORCE_INLINE BoolV BSetY(const BoolV v, const BoolV f) +{ + return V4Sel(BTFTT(), v, f); +} + +PX_FORCE_INLINE BoolV BSetZ(const BoolV v, const BoolV f) +{ + return V4Sel(BTTFT(), v, f); +} + +PX_FORCE_INLINE BoolV BSetW(const BoolV v, const BoolV f) +{ + return V4Sel(BTTTF(), v, f); +} + +PX_FORCE_INLINE BoolV BAnd(const BoolV a, const BoolV b) +{ + return _mm_and_ps(a, b); +} + +PX_FORCE_INLINE BoolV BNot(const BoolV a) +{ + const BoolV bAllTrue(BTTTT()); + return _mm_xor_ps(a, bAllTrue); +} + +PX_FORCE_INLINE BoolV BAndNot(const BoolV a, const BoolV b) +{ + return _mm_andnot_ps(b, a); +} + +PX_FORCE_INLINE BoolV BOr(const BoolV a, const BoolV b) +{ + return _mm_or_ps(a, b); +} + +PX_FORCE_INLINE BoolV BAllTrue4(const BoolV a) +{ + const BoolV bTmp = _mm_and_ps(_mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 1, 0, 1)), _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 2, 3))); + return _mm_and_ps(_mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(0, 0, 0, 0)), + _mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(1, 1, 1, 1))); +} + +PX_FORCE_INLINE BoolV BAnyTrue4(const BoolV a) +{ + const BoolV bTmp = _mm_or_ps(_mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 1, 0, 1)), _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 2, 3))); + return _mm_or_ps(_mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(0, 0, 0, 0)), + _mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(1, 1, 1, 1))); +} + +PX_FORCE_INLINE BoolV BAllTrue3(const BoolV a) +{ + const BoolV bTmp = _mm_and_ps(_mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 1, 0, 1)), _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2))); + return _mm_and_ps(_mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(0, 0, 0, 0)), + _mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(1, 1, 1, 1))); +} + +PX_FORCE_INLINE BoolV BAnyTrue3(const BoolV a) +{ + const BoolV bTmp = _mm_or_ps(_mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 1, 0, 1)), _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2))); + return _mm_or_ps(_mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(0, 0, 0, 0)), + _mm_shuffle_ps(bTmp, bTmp, _MM_SHUFFLE(1, 1, 1, 1))); +} + +PX_FORCE_INLINE PxU32 BAllEq(const BoolV a, const BoolV b) +{ + const BoolV bTest = internalSimd::m128_I2F(_mm_cmpeq_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); + return internalSimd::BAllTrue4_R(bTest); +} + +PX_FORCE_INLINE PxU32 BAllEqTTTT(const BoolV a) +{ + return PxU32(_mm_movemask_ps(a)==15); +} + +PX_FORCE_INLINE PxU32 BAllEqFFFF(const BoolV a) +{ + return PxU32(_mm_movemask_ps(a)==0); +} + +PX_FORCE_INLINE PxU32 BGetBitMask(const BoolV a) +{ + return PxU32(_mm_movemask_ps(a)); +} + +////////////////////////////////// +// MAT33V +////////////////////////////////// + +PX_FORCE_INLINE Mat33V M33Identity() +{ + return Mat33V(V3UnitX(), V3UnitY(), V3UnitZ()); +} + +PX_FORCE_INLINE Vec3V M33MulV3(const Mat33V& a, const Vec3V b) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + const Vec3V v0 = V3Scale(a.col0, x); + const Vec3V v1 = V3Scale(a.col1, y); + const Vec3V v2 = V3Scale(a.col2, z); + const Vec3V v0PlusV1 = V3Add(v0, v1); + return V3Add(v0PlusV1, v2); +} + +PX_FORCE_INLINE Vec3V M33MulV3AddV3(const Mat33V& A, const Vec3V b, const Vec3V c) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + Vec3V result = V3ScaleAdd(A.col0, x, c); + result = V3ScaleAdd(A.col1, y, result); + return V3ScaleAdd(A.col2, z, result); +} + +PX_FORCE_INLINE Mat33V M33MulM33(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(M33MulV3(a, b.col0), M33MulV3(a, b.col1), M33MulV3(a, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Add(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(V3Add(a.col0, b.col0), V3Add(a.col1, b.col1), V3Add(a.col2, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Scale(const Mat33V& a, const FloatV& b) +{ + return Mat33V(V3Scale(a.col0, b), V3Scale(a.col1, b), V3Scale(a.col2, b)); +} + +PX_FORCE_INLINE Mat33V M33Sub(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(V3Sub(a.col0, b.col0), V3Sub(a.col1, b.col1), V3Sub(a.col2, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Neg(const Mat33V& a) +{ + return Mat33V(V3Neg(a.col0), V3Neg(a.col1), V3Neg(a.col2)); +} + +PX_FORCE_INLINE Mat33V M33Abs(const Mat33V& a) +{ + return Mat33V(V3Abs(a.col0), V3Abs(a.col1), V3Abs(a.col2)); +} + +PX_FORCE_INLINE Mat33V M33Inverse(const Mat33V& a) +{ + const BoolV tfft = BTFFT(); + const BoolV tttf = BTTTF(); + const FloatV zero = FZero(); + const Vec3V cross01 = V3Cross(a.col0, a.col1); + const Vec3V cross12 = V3Cross(a.col1, a.col2); + const Vec3V cross20 = V3Cross(a.col2, a.col0); + const FloatV dot = V3Dot(cross01, a.col2); + const FloatV invDet = _mm_rcp_ps(dot); + const Vec3V mergeh = _mm_unpacklo_ps(cross12, cross01); + const Vec3V mergel = _mm_unpackhi_ps(cross12, cross01); + Vec3V colInv0 = _mm_unpacklo_ps(mergeh, cross20); + colInv0 = _mm_or_ps(_mm_andnot_ps(tttf, zero), _mm_and_ps(tttf, colInv0)); + const Vec3V zppd = _mm_shuffle_ps(mergeh, cross20, _MM_SHUFFLE(3, 0, 0, 2)); + const Vec3V pbwp = _mm_shuffle_ps(cross20, mergeh, _MM_SHUFFLE(3, 3, 1, 0)); + const Vec3V colInv1 = _mm_or_ps(_mm_andnot_ps(BTFFT(), pbwp), _mm_and_ps(BTFFT(), zppd)); + const Vec3V xppd = _mm_shuffle_ps(mergel, cross20, _MM_SHUFFLE(3, 0, 0, 0)); + const Vec3V pcyp = _mm_shuffle_ps(cross20, mergel, _MM_SHUFFLE(3, 1, 2, 0)); + const Vec3V colInv2 = _mm_or_ps(_mm_andnot_ps(tfft, pcyp), _mm_and_ps(tfft, xppd)); + + return Mat33V(_mm_mul_ps(colInv0, invDet), _mm_mul_ps(colInv1, invDet), _mm_mul_ps(colInv2, invDet)); +} + +PX_FORCE_INLINE Mat33V M33Diagonal(const Vec3VArg d) +{ + const FloatV x = V3Mul(V3UnitX(), d); + const FloatV y = V3Mul(V3UnitY(), d); + const FloatV z = V3Mul(V3UnitZ(), d); + return Mat33V(x, y, z); +} + +PX_FORCE_INLINE Mat33V Mat33V_From_PxMat33(const PxMat33& m) +{ + return Mat33V(V3LoadU(m.column0), V3LoadU(m.column1), V3LoadU(m.column2)); +} + +PX_FORCE_INLINE void PxMat33_From_Mat33V(const Mat33V& m, PxMat33& out) +{ + V3StoreU(m.col0, out.column0); + V3StoreU(m.col1, out.column1); + V3StoreU(m.col2, out.column2); +} + +////////////////////////////////// +// MAT34V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M34MulV3(const Mat34V& a, const Vec3V b) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + const Vec3V v0 = V3Scale(a.col0, x); + const Vec3V v1 = V3Scale(a.col1, y); + const Vec3V v2 = V3Scale(a.col2, z); + const Vec3V v0PlusV1 = V3Add(v0, v1); + const Vec3V v0PlusV1Plusv2 = V3Add(v0PlusV1, v2); + return V3Add(v0PlusV1Plusv2, a.col3); +} + +PX_FORCE_INLINE Vec3V M34Mul33V3(const Mat34V& a, const Vec3V b) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + const Vec3V v0 = V3Scale(a.col0, x); + const Vec3V v1 = V3Scale(a.col1, y); + const Vec3V v2 = V3Scale(a.col2, z); + const Vec3V v0PlusV1 = V3Add(v0, v1); + return V3Add(v0PlusV1, v2); +} + +PX_FORCE_INLINE Mat34V M34MulM34(const Mat34V& a, const Mat34V& b) +{ + return Mat34V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2), M34MulV3(a, b.col3)); +} + +PX_FORCE_INLINE Mat33V M34MulM33(const Mat34V& a, const Mat33V& b) +{ + return Mat33V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2)); +} + +PX_FORCE_INLINE Mat33V M34Mul33MM34(const Mat34V& a, const Mat34V& b) +{ + return Mat33V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2)); +} + +PX_FORCE_INLINE Mat34V M34Add(const Mat34V& a, const Mat34V& b) +{ + return Mat34V(V3Add(a.col0, b.col0), V3Add(a.col1, b.col1), V3Add(a.col2, b.col2), V3Add(a.col3, b.col3)); +} + +////////////////////////////////// +// MAT44V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V M44MulV4(const Mat44V& a, const Vec4V b) +{ + const FloatV x = V4GetX(b); + const FloatV y = V4GetY(b); + const FloatV z = V4GetZ(b); + const FloatV w = V4GetW(b); + + const Vec4V v0 = V4Scale(a.col0, x); + const Vec4V v1 = V4Scale(a.col1, y); + const Vec4V v2 = V4Scale(a.col2, z); + const Vec4V v3 = V4Scale(a.col3, w); + const Vec4V v0PlusV1 = V4Add(v0, v1); + const Vec4V v0PlusV1Plusv2 = V4Add(v0PlusV1, v2); + return V4Add(v0PlusV1Plusv2, v3); +} + +PX_FORCE_INLINE Mat44V M44MulM44(const Mat44V& a, const Mat44V& b) +{ + return Mat44V(M44MulV4(a, b.col0), M44MulV4(a, b.col1), M44MulV4(a, b.col2), M44MulV4(a, b.col3)); +} + +PX_FORCE_INLINE Mat44V M44Add(const Mat44V& a, const Mat44V& b) +{ + return Mat44V(V4Add(a.col0, b.col0), V4Add(a.col1, b.col1), V4Add(a.col2, b.col2), V4Add(a.col3, b.col3)); +} + +PX_FORCE_INLINE Mat44V M44Trnsps(const Mat44V& a); + +PX_FORCE_INLINE Mat44V M44Inverse(const Mat44V& a) +{ + __m128 minor0, minor1, minor2, minor3; + __m128 row0, row1, row2, row3; + __m128 det, tmp1; + + tmp1 = V4Zero(); + row1 = V4Zero(); + row3 = V4Zero(); + + row0 = a.col0; + row1 = _mm_shuffle_ps(a.col1, a.col1, _MM_SHUFFLE(1, 0, 3, 2)); + row2 = a.col2; + row3 = _mm_shuffle_ps(a.col3, a.col3, _MM_SHUFFLE(1, 0, 3, 2)); + + tmp1 = _mm_mul_ps(row2, row3); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); + minor0 = _mm_mul_ps(row1, tmp1); + minor1 = _mm_mul_ps(row0, tmp1); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); + minor0 = _mm_sub_ps(_mm_mul_ps(row1, tmp1), minor0); + minor1 = _mm_sub_ps(_mm_mul_ps(row0, tmp1), minor1); + minor1 = _mm_shuffle_ps(minor1, minor1, 0x4E); + + tmp1 = _mm_mul_ps(row1, row2); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); + minor0 = _mm_add_ps(_mm_mul_ps(row3, tmp1), minor0); + minor3 = _mm_mul_ps(row0, tmp1); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); + minor0 = _mm_sub_ps(minor0, _mm_mul_ps(row3, tmp1)); + minor3 = _mm_sub_ps(_mm_mul_ps(row0, tmp1), minor3); + minor3 = _mm_shuffle_ps(minor3, minor3, 0x4E); + + tmp1 = _mm_mul_ps(_mm_shuffle_ps(row1, row1, 0x4E), row3); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); + row2 = _mm_shuffle_ps(row2, row2, 0x4E); + minor0 = _mm_add_ps(_mm_mul_ps(row2, tmp1), minor0); + minor2 = _mm_mul_ps(row0, tmp1); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); + minor0 = _mm_sub_ps(minor0, _mm_mul_ps(row2, tmp1)); + minor2 = _mm_sub_ps(_mm_mul_ps(row0, tmp1), minor2); + minor2 = _mm_shuffle_ps(minor2, minor2, 0x4E); + + tmp1 = _mm_mul_ps(row0, row1); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); + minor2 = _mm_add_ps(_mm_mul_ps(row3, tmp1), minor2); + minor3 = _mm_sub_ps(_mm_mul_ps(row2, tmp1), minor3); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); + minor2 = _mm_sub_ps(_mm_mul_ps(row3, tmp1), minor2); + minor3 = _mm_sub_ps(minor3, _mm_mul_ps(row2, tmp1)); + + tmp1 = _mm_mul_ps(row0, row3); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); + minor1 = _mm_sub_ps(minor1, _mm_mul_ps(row2, tmp1)); + minor2 = _mm_add_ps(_mm_mul_ps(row1, tmp1), minor2); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); + minor1 = _mm_add_ps(_mm_mul_ps(row2, tmp1), minor1); + minor2 = _mm_sub_ps(minor2, _mm_mul_ps(row1, tmp1)); + + tmp1 = _mm_mul_ps(row0, row2); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); + minor1 = _mm_add_ps(_mm_mul_ps(row3, tmp1), minor1); + minor3 = _mm_sub_ps(minor3, _mm_mul_ps(row1, tmp1)); + tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); + minor1 = _mm_sub_ps(minor1, _mm_mul_ps(row3, tmp1)); + minor3 = _mm_add_ps(_mm_mul_ps(row1, tmp1), minor3); + + det = _mm_mul_ps(row0, minor0); + det = _mm_add_ps(_mm_shuffle_ps(det, det, 0x4E), det); + det = _mm_add_ss(_mm_shuffle_ps(det, det, 0xB1), det); + tmp1 = _mm_rcp_ss(det); +#if 0 + det = _mm_sub_ss(_mm_add_ss(tmp1, tmp1), _mm_mul_ss(det, _mm_mul_ss(tmp1, tmp1))); + det = _mm_shuffle_ps(det, det, 0x00); +#else + det = _mm_shuffle_ps(tmp1, tmp1, _MM_SHUFFLE(0, 0, 0, 0)); +#endif + + minor0 = _mm_mul_ps(det, minor0); + minor1 = _mm_mul_ps(det, minor1); + minor2 = _mm_mul_ps(det, minor2); + minor3 = _mm_mul_ps(det, minor3); + Mat44V invTrans(minor0, minor1, minor2, minor3); + return M44Trnsps(invTrans); +} + +////////////////////////////////// +// Misc +////////////////////////////////// + +// PT: TODO: seems to be in the wrong section +PX_FORCE_INLINE Vec4V V4LoadXYZW(const PxF32& x, const PxF32& y, const PxF32& z, const PxF32& w) +{ + return _mm_set_ps(w, z, y, x); +} + +PX_FORCE_INLINE VecU32V V4U32Sel(const BoolV c, const VecU32V a, const VecU32V b) +{ + return internalSimd::m128_I2F(_mm_or_si128(_mm_andnot_si128(internalSimd::m128_F2I(c), internalSimd::m128_F2I(b)), _mm_and_si128(internalSimd::m128_F2I(c), internalSimd::m128_F2I(a)))); +} + +PX_FORCE_INLINE VecU32V V4U32or(VecU32V a, VecU32V b) +{ + return internalSimd::m128_I2F(_mm_or_si128(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE VecU32V V4U32xor(VecU32V a, VecU32V b) +{ + return internalSimd::m128_I2F(_mm_xor_si128(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE VecU32V V4U32and(VecU32V a, VecU32V b) +{ + return internalSimd::m128_I2F(_mm_and_si128(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE VecU32V V4U32Andc(VecU32V a, VecU32V b) +{ + return internalSimd::m128_I2F(_mm_andnot_si128(internalSimd::m128_F2I(b), internalSimd::m128_F2I(a))); +} + +PX_FORCE_INLINE VecU32V U4Load(const PxU32 i) +{ + return _mm_load1_ps(reinterpret_cast(&i)); +} + +PX_FORCE_INLINE VecU32V U4LoadU(const PxU32* i) +{ + return _mm_loadu_ps(reinterpret_cast(i)); +} + +PX_FORCE_INLINE VecU32V U4LoadA(const PxU32* i) +{ + ASSERT_ISALIGNED16(i); + return _mm_load_ps(reinterpret_cast(i)); +} + +PX_FORCE_INLINE VecI32V VecI32V_One() +{ + return I4Load(1); +} + +PX_FORCE_INLINE VecI32V VecI32V_Two() +{ + return I4Load(2); +} + +PX_FORCE_INLINE VecI32V VecI32V_MinusOne() +{ + return I4Load(-1); +} + +PX_FORCE_INLINE VecU32V U4Zero() +{ + return U4Load(0); +} + +PX_FORCE_INLINE VecU32V U4One() +{ + return U4Load(1); +} + +PX_FORCE_INLINE VecU32V U4Two() +{ + return U4Load(2); +} + +PX_FORCE_INLINE Vec4V V4Andc(const Vec4V a, const VecU32V b) +{ + VecU32V result32(a); + result32 = V4U32Andc(result32, b); + return Vec4V(result32); +} + +PX_FORCE_INLINE VecU32V V4IsGrtrV32u(const Vec4V a, const Vec4V b) +{ + return V4IsGrtr(a, b); +} + +PX_FORCE_INLINE VecU16V V4U16LoadAligned(const VecU16V* addr) +{ + return *addr; +} + +PX_FORCE_INLINE VecU16V V4U16LoadUnaligned(const VecU16V* addr) +{ + return *addr; +} + +PX_FORCE_INLINE VecU16V V4I16CompareGt(VecU16V a, VecU16V b) +{ + return internalSimd::m128_I2F(_mm_cmpgt_epi16(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +// unsigned compares are not supported on x86 +PX_FORCE_INLINE VecU16V V4U16CompareGt(VecU16V a, VecU16V b) +{ + // _mm_cmpgt_epi16 doesn't work for unsigned values unfortunately + // return m128_I2F(_mm_cmpgt_epi16(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); + VecU16V result; + result.m128_u16[0] = PxU16((a).m128_u16[0] > (b).m128_u16[0]); + result.m128_u16[1] = PxU16((a).m128_u16[1] > (b).m128_u16[1]); + result.m128_u16[2] = PxU16((a).m128_u16[2] > (b).m128_u16[2]); + result.m128_u16[3] = PxU16((a).m128_u16[3] > (b).m128_u16[3]); + result.m128_u16[4] = PxU16((a).m128_u16[4] > (b).m128_u16[4]); + result.m128_u16[5] = PxU16((a).m128_u16[5] > (b).m128_u16[5]); + result.m128_u16[6] = PxU16((a).m128_u16[6] > (b).m128_u16[6]); + result.m128_u16[7] = PxU16((a).m128_u16[7] > (b).m128_u16[7]); + return result; +} + +PX_FORCE_INLINE Vec4V Vec4V_From_VecU32V(VecU32V a) +{ + Vec4V result = V4LoadXYZW(PxF32(a.m128_u32[0]), PxF32(a.m128_u32[1]), PxF32(a.m128_u32[2]), PxF32(a.m128_u32[3])); + return result; +} + +PX_FORCE_INLINE VecU32V U4LoadXYZW(PxU32 x, PxU32 y, PxU32 z, PxU32 w) +{ + VecU32V result; + result.m128_u32[0] = x; + result.m128_u32[1] = y; + result.m128_u32[2] = z; + result.m128_u32[3] = w; + return result; +} + +} // namespace aos +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecQuat.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecQuat.h new file mode 100644 index 000000000..3bb2a882d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecQuat.h @@ -0,0 +1,497 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC_QUAT_H +#define PX_VEC_QUAT_H + +#if !PX_DOXYGEN +namespace physx +{ +#endif +namespace aos +{ + +#ifndef PX_PIDIV2 +#define PX_PIDIV2 1.570796327f +#endif + +////////////////////////////////// +// QuatV +////////////////////////////////// +PX_FORCE_INLINE QuatV QuatVLoadXYZW(const PxF32 x, const PxF32 y, const PxF32 z, const PxF32 w) +{ + return V4LoadXYZW(x, y, z, w); +} + +PX_FORCE_INLINE QuatV QuatVLoadU(const PxF32* v) +{ + return V4LoadU(v); +} + +PX_FORCE_INLINE QuatV QuatVLoadA(const PxF32* v) +{ + return V4LoadA(v); +} + +PX_FORCE_INLINE QuatV QuatV_From_RotationAxisAngle(const Vec3V u, const FloatV a) +{ + // q = cos(a/2) + u*sin(a/2) + const FloatV half = FLoad(0.5f); + const FloatV hangle = FMul(a, half); + const FloatV piByTwo(FLoad(PX_PIDIV2)); + const FloatV PiByTwoMinHangle(FSub(piByTwo, hangle)); + const Vec4V hangle2(Vec4V_From_Vec3V(V3Merge(hangle, PiByTwoMinHangle, hangle))); + + /*const FloatV sina = FSin(hangle); + const FloatV cosa = FCos(hangle);*/ + + const Vec4V _sina = V4Sin(hangle2); + const FloatV sina = V4GetX(_sina); + const FloatV cosa = V4GetY(_sina); + + const Vec3V v = V3Scale(u, sina); + // return V4Sel(BTTTF(), Vec4V_From_Vec3V(v), V4Splat(cosa)); + return V4SetW(Vec4V_From_Vec3V(v), cosa); +} + +// Normalize +PX_FORCE_INLINE QuatV QuatNormalize(const QuatV q) +{ + return V4Normalize(q); +} + +PX_FORCE_INLINE FloatV QuatLength(const QuatV q) +{ + return V4Length(q); +} + +PX_FORCE_INLINE FloatV QuatLengthSq(const QuatV q) +{ + return V4LengthSq(q); +} + +PX_FORCE_INLINE FloatV QuatDot(const QuatV a, const QuatV b) // convert this PxQuat to a unit quaternion +{ + return V4Dot(a, b); +} + +PX_FORCE_INLINE QuatV QuatConjugate(const QuatV q) +{ + return V4SetW(V4Neg(q), V4GetW(q)); +} + +PX_FORCE_INLINE Vec3V QuatGetImaginaryPart(const QuatV q) +{ + return Vec3V_From_Vec4V(q); +} + +/** brief computes rotation of x-axis */ +PX_FORCE_INLINE Vec3V QuatGetBasisVector0(const QuatV q) +{ + /*const PxF32 x2 = x*2.0f; + const PxF32 w2 = w*2.0f; + return PxVec3( (w * w2) - 1.0f + x*x2, + (z * w2) + y*x2, + (-y * w2) + z*x2);*/ + + const FloatV two = FLoad(2.0f); + const FloatV w = V4GetW(q); + const Vec3V u = Vec3V_From_Vec4V(q); + + const FloatV x2 = FMul(V3GetX(u), two); + const FloatV w2 = FMul(w, two); + + const Vec3V a = V3Scale(u, x2); + const Vec3V tmp = V3Merge(w, V3GetZ(u), FNeg(V3GetY(u))); + // const Vec3V b = V3Scale(tmp, w2); + // const Vec3V ab = V3Add(a, b); + const Vec3V ab = V3ScaleAdd(tmp, w2, a); + return V3SetX(ab, FSub(V3GetX(ab), FOne())); +} + +/** brief computes rotation of y-axis */ +PX_FORCE_INLINE Vec3V QuatGetBasisVector1(const QuatV q) +{ + /*const PxF32 y2 = y*2.0f; + const PxF32 w2 = w*2.0f; + return PxVec3( (-z * w2) + x*y2, + (w * w2) - 1.0f + y*y2, + (x * w2) + z*y2);*/ + + const FloatV two = FLoad(2.0f); + const FloatV w = V4GetW(q); + const Vec3V u = Vec3V_From_Vec4V(q); + + const FloatV y2 = FMul(V3GetY(u), two); + const FloatV w2 = FMul(w, two); + + const Vec3V a = V3Scale(u, y2); + const Vec3V tmp = V3Merge(FNeg(V3GetZ(u)), w, V3GetX(u)); + // const Vec3V b = V3Scale(tmp, w2); + // const Vec3V ab = V3Add(a, b); + const Vec3V ab = V3ScaleAdd(tmp, w2, a); + return V3SetY(ab, FSub(V3GetY(ab), FOne())); +} + +/** brief computes rotation of z-axis */ +PX_FORCE_INLINE Vec3V QuatGetBasisVector2(const QuatV q) +{ + /*const PxF32 z2 = z*2.0f; + const PxF32 w2 = w*2.0f; + return PxVec3( (y * w2) + x*z2, + (-x * w2) + y*z2, + (w * w2) - 1.0f + z*z2);*/ + + const FloatV two = FLoad(2.0f); + const FloatV w = V4GetW(q); + const Vec3V u = Vec3V_From_Vec4V(q); + + const FloatV z2 = FMul(V3GetZ(u), two); + const FloatV w2 = FMul(w, two); + + const Vec3V a = V3Scale(u, z2); + const Vec3V tmp = V3Merge(V3GetY(u), FNeg(V3GetX(u)), w); + /*const Vec3V b = V3Scale(tmp, w2); + const Vec3V ab = V3Add(a, b);*/ + const Vec3V ab = V3ScaleAdd(tmp, w2, a); + return V3SetZ(ab, FSub(V3GetZ(ab), FOne())); +} + +PX_FORCE_INLINE Vec3V QuatRotate(const QuatV q, const Vec3V v) +{ + /* + const PxVec3 qv(x,y,z); + return (v*(w*w-0.5f) + (qv.cross(v))*w + qv*(qv.dot(v)))*2; + */ + + const FloatV two = FLoad(2.0f); + // const FloatV half = FloatV_From_F32(0.5f); + const FloatV nhalf = FLoad(-0.5f); + const Vec3V u = Vec3V_From_Vec4V(q); + const FloatV w = V4GetW(q); + // const FloatV w2 = FSub(FMul(w, w), half); + const FloatV w2 = FScaleAdd(w, w, nhalf); + const Vec3V a = V3Scale(v, w2); + // const Vec3V b = V3Scale(V3Cross(u, v), w); + // const Vec3V c = V3Scale(u, V3Dot(u, v)); + // return V3Scale(V3Add(V3Add(a, b), c), two); + const Vec3V temp = V3ScaleAdd(V3Cross(u, v), w, a); + return V3Scale(V3ScaleAdd(u, V3Dot(u, v), temp), two); +} + +// PT: same as QuatRotate but operates on a Vec4V +PX_FORCE_INLINE Vec4V QuatRotate4V(const QuatV q, const Vec4V v) +{ + const FloatV two = FLoad(2.0f); + const FloatV nhalf = FLoad(-0.5f); + const Vec4V u = q; // PT: W not cleared here + const FloatV w = V4GetW(q); + const FloatV w2 = FScaleAdd(w, w, nhalf); + const Vec4V a = V4Scale(v, w2); // PT: W has non-zero data here + const Vec4V temp = V4ScaleAdd(V4Cross(u, v), w, a); + return V4Scale(V4ScaleAdd(u, V4Dot3(u, v), temp), two); // PT: beware, V4Dot3 has one more instruction here +} + +// PT: avoid some multiplies when immediately normalizing a rotated vector +PX_FORCE_INLINE Vec3V QuatRotateAndNormalize(const QuatV q, const Vec3V v) +{ + const FloatV nhalf = FLoad(-0.5f); + const Vec3V u = Vec3V_From_Vec4V(q); + const FloatV w = V4GetW(q); + const FloatV w2 = FScaleAdd(w, w, nhalf); + const Vec3V a = V3Scale(v, w2); + const Vec3V temp = V3ScaleAdd(V3Cross(u, v), w, a); + return V3Normalize(V3ScaleAdd(u, V3Dot(u, v), temp)); +} + +PX_FORCE_INLINE Vec3V QuatTransform(const QuatV q, const Vec3V p, const Vec3V v) +{ + // p + q.rotate(v) + const FloatV two = FLoad(2.0f); + // const FloatV half = FloatV_From_F32(0.5f); + const FloatV nhalf = FLoad(-0.5f); + const Vec3V u = Vec3V_From_Vec4V(q); + const FloatV w = V4GetW(q); + // const FloatV w2 = FSub(FMul(w, w), half); + const FloatV w2 = FScaleAdd(w, w, nhalf); + const Vec3V a = V3Scale(v, w2); + /*const Vec3V b = V3Scale(V3Cross(u, v), w); + const Vec3V c = V3Scale(u, V3Dot(u, v)); + return V3ScaleAdd(V3Add(V3Add(a, b), c), two, p);*/ + const Vec3V temp = V3ScaleAdd(V3Cross(u, v), w, a); + const Vec3V z = V3ScaleAdd(u, V3Dot(u, v), temp); + return V3ScaleAdd(z, two, p); +} + +PX_FORCE_INLINE Vec3V QuatRotateInv(const QuatV q, const Vec3V v) +{ + // const PxVec3 qv(x,y,z); + // return (v*(w*w-0.5f) - (qv.cross(v))*w + qv*(qv.dot(v)))*2; + + const FloatV two = FLoad(2.0f); + const FloatV nhalf = FLoad(-0.5f); + const Vec3V u = Vec3V_From_Vec4V(q); + const FloatV w = V4GetW(q); + const FloatV w2 = FScaleAdd(w, w, nhalf); + const Vec3V a = V3Scale(v, w2); + /*const Vec3V b = V3Scale(V3Cross(u, v), w); + const Vec3V c = V3Scale(u, V3Dot(u, v)); + return V3Scale(V3Add(V3Sub(a, b), c), two);*/ + const Vec3V temp = V3NegScaleSub(V3Cross(u, v), w, a); + return V3Scale(V3ScaleAdd(u, V3Dot(u, v), temp), two); +} + +PX_FORCE_INLINE QuatV QuatMul(const QuatV a, const QuatV b) +{ + const Vec4V imagA = a; + const Vec4V imagB = b; + const FloatV rA = V4GetW(a); + const FloatV rB = V4GetW(b); + + const FloatV real = FSub(FMul(rA, rB), V4Dot3(imagA, imagB)); + const Vec4V v0 = V4Scale(imagA, rB); + const Vec4V v1 = V4Scale(imagB, rA); + const Vec4V v2 = V4Cross(imagA, imagB); + const Vec4V imag = V4Add(V4Add(v0, v1), v2); + + return V4SetW(imag, real); +} + +PX_FORCE_INLINE QuatV QuatAdd(const QuatV a, const QuatV b) +{ + return V4Add(a, b); +} + +PX_FORCE_INLINE QuatV QuatNeg(const QuatV q) +{ + return V4Neg(q); +} + +PX_FORCE_INLINE QuatV QuatSub(const QuatV a, const QuatV b) +{ + return V4Sub(a, b); +} + +PX_FORCE_INLINE QuatV QuatScale(const QuatV a, const FloatV b) +{ + return V4Scale(a, b); +} + +PX_FORCE_INLINE QuatV QuatMerge(const FloatV* const floatVArray) +{ + return V4Merge(floatVArray); +} + +PX_FORCE_INLINE QuatV QuatMerge(const FloatVArg x, const FloatVArg y, const FloatVArg z, const FloatVArg w) +{ + return V4Merge(x, y, z, w); +} + +PX_FORCE_INLINE QuatV QuatIdentity() +{ + return V4SetW(V4Zero(), FOne()); +} + +PX_FORCE_INLINE bool isFiniteQuatV(const QuatV q) +{ + return isFiniteVec4V(q); +} + +#if (PX_LINUX || PX_SWITCH) && PX_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wbitwise-instead-of-logical" // bitwise intentionally chosen for performance +#endif + +PX_FORCE_INLINE bool isValidQuatV(const QuatV q) +{ + const FloatV unitTolerance = FLoad(1e-4f); + const FloatV tmp = FAbs(FSub(QuatLength(q), FOne())); + const BoolV con = FIsGrtr(unitTolerance, tmp); + return isFiniteVec4V(q) & (BAllEqTTTT(con) == 1); +} + +PX_FORCE_INLINE bool isSaneQuatV(const QuatV q) +{ + const FloatV unitTolerance = FLoad(1e-2f); + const FloatV tmp = FAbs(FSub(QuatLength(q), FOne())); + const BoolV con = FIsGrtr(unitTolerance, tmp); + return isFiniteVec4V(q) & (BAllEqTTTT(con) == 1); +} + +#if PX_LINUX && PX_CLANG +#pragma clang diagnostic pop +#endif + +PX_FORCE_INLINE Mat33V QuatGetMat33V(const QuatVArg q) +{ + // const FloatV two = FloatV_From_F32(2.0f); + // const FloatV one = FOne(); + + // const FloatV x = V4GetX(q); + // const FloatV y = V4GetY(q); + // const FloatV z = V4GetZ(q); + // const Vec4V _q = V4Mul(q, two); + // + ////const FloatV w = V4GetW(q); + + // const Vec4V t0 = V4Mul(_q, x); // 2xx, 2xy, 2xz, 2xw + // const Vec4V t1 = V4Mul(_q, y); // 2xy, 2yy, 2yz, 2yw + // const Vec4V t2 = V4Mul(_q, z); // 2xz, 2yz, 2zz, 2zw + ////const Vec4V t3 = V4Mul(_q, w); // 2xw, 2yw, 2zw, 2ww + + // const FloatV xx2 = V4GetX(t0); + // const FloatV xy2 = V4GetY(t0); + // const FloatV xz2 = V4GetZ(t0); + // const FloatV xw2 = V4GetW(t0); + + // const FloatV yy2 = V4GetY(t1); + // const FloatV yz2 = V4GetZ(t1); + // const FloatV yw2 = V4GetW(t1); + + // const FloatV zz2 = V4GetZ(t2); + // const FloatV zw2 = V4GetW(t2); + + ////const FloatV ww2 = V4GetW(t3); + + // const FloatV c00 = FSub(one, FAdd(yy2, zz2)); + // const FloatV c01 = FSub(xy2, zw2); + // const FloatV c02 = FAdd(xz2, yw2); + + // const FloatV c10 = FAdd(xy2, zw2); + // const FloatV c11 = FSub(one, FAdd(xx2, zz2)); + // const FloatV c12 = FSub(yz2, xw2); + + // const FloatV c20 = FSub(xz2, yw2); + // const FloatV c21 = FAdd(yz2, xw2); + // const FloatV c22 = FSub(one, FAdd(xx2, yy2)); + + // const Vec3V c0 = V3Merge(c00, c10, c20); + // const Vec3V c1 = V3Merge(c01, c11, c21); + // const Vec3V c2 = V3Merge(c02, c12, c22); + + // return Mat33V(c0, c1, c2); + + const FloatV one = FOne(); + const FloatV x = V4GetX(q); + const FloatV y = V4GetY(q); + const FloatV z = V4GetZ(q); + const FloatV w = V4GetW(q); + + const FloatV x2 = FAdd(x, x); + const FloatV y2 = FAdd(y, y); + const FloatV z2 = FAdd(z, z); + + const FloatV xx = FMul(x2, x); + const FloatV yy = FMul(y2, y); + const FloatV zz = FMul(z2, z); + + const FloatV xy = FMul(x2, y); + const FloatV xz = FMul(x2, z); + const FloatV xw = FMul(x2, w); + + const FloatV yz = FMul(y2, z); + const FloatV yw = FMul(y2, w); + const FloatV zw = FMul(z2, w); + + const FloatV v = FSub(one, xx); + + const Vec3V column0 = V3Merge(FSub(FSub(one, yy), zz), FAdd(xy, zw), FSub(xz, yw)); + const Vec3V column1 = V3Merge(FSub(xy, zw), FSub(v, zz), FAdd(yz, xw)); + const Vec3V column2 = V3Merge(FAdd(xz, yw), FSub(yz, xw), FSub(v, yy)); + return Mat33V(column0, column1, column2); +} + +PX_FORCE_INLINE QuatV Mat33GetQuatV(const Mat33V& a) +{ + const FloatV one = FOne(); + const FloatV zero = FZero(); + const FloatV half = FLoad(0.5f); + const FloatV two = FLoad(2.0f); + const FloatV scale = FLoad(0.25f); + const FloatV a00 = V3GetX(a.col0); + const FloatV a11 = V3GetY(a.col1); + const FloatV a22 = V3GetZ(a.col2); + + const FloatV a21 = V3GetZ(a.col1); // row=2, col=1; + const FloatV a12 = V3GetY(a.col2); // row=1, col=2; + const FloatV a02 = V3GetX(a.col2); // row=0, col=2; + const FloatV a20 = V3GetZ(a.col0); // row=2, col=0; + const FloatV a10 = V3GetY(a.col0); // row=1, col=0; + const FloatV a01 = V3GetX(a.col1); // row=0, col=1; + + const Vec3V vec0 = V3Merge(a21, a02, a10); + const Vec3V vec1 = V3Merge(a12, a20, a01); + const Vec3V v = V3Sub(vec0, vec1); + const Vec3V g = V3Add(vec0, vec1); + + const FloatV trace = FAdd(a00, FAdd(a11, a22)); + + if(FAllGrtrOrEq(trace, zero)) + { + const FloatV h = FSqrt(FAdd(trace, one)); + const FloatV w = FMul(half, h); + const FloatV s = FMul(half, FRecip(h)); + const Vec3V u = V3Scale(v, s); + return V4SetW(Vec4V_From_Vec3V(u), w); + } + else + { + const FloatV ntrace = FNeg(trace); + const Vec3V d = V3Merge(a00, a11, a22); + const BoolV con0 = BAllTrue3(V3IsGrtrOrEq(V3Splat(a00), d)); + const BoolV con1 = BAllTrue3(V3IsGrtrOrEq(V3Splat(a11), d)); + + const FloatV t0 = FAdd(one, FScaleAdd(a00, two, ntrace)); + const FloatV t1 = FAdd(one, FScaleAdd(a11, two, ntrace)); + const FloatV t2 = FAdd(one, FScaleAdd(a22, two, ntrace)); + + const FloatV t = FSel(con0, t0, FSel(con1, t1, t2)); + + const FloatV h = FMul(two, FSqrt(t)); + const FloatV s = FRecip(h); + const FloatV g0 = FMul(scale, h); + const Vec3V vs = V3Scale(v, s); + const Vec3V gs = V3Scale(g, s); + const FloatV gsx = V3GetX(gs); + const FloatV gsy = V3GetY(gs); + const FloatV gsz = V3GetZ(gs); + // vs.x= (a21 - a12)*s; vs.y=(a02 - a20)*s; vs.z=(a10 - a01)*s; + // gs.x= (a21 + a12)*s; gs.y=(a02 + a20)*s; gs.z=(a10 + a01)*s; + const Vec4V v0 = V4Merge(g0, gsz, gsy, V3GetX(vs)); + const Vec4V v1 = V4Merge(gsz, g0, gsx, V3GetY(vs)); + const Vec4V v2 = V4Merge(gsy, gsx, g0, V3GetZ(vs)); + return V4Sel(con0, v0, V4Sel(con1, v1, v2)); + } +} + +} // namespace aos +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecTransform.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecTransform.h new file mode 100644 index 000000000..ea476b17c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/PxVecTransform.h @@ -0,0 +1,290 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_VEC_TRANSFORM_H +#define PX_VEC_TRANSFORM_H + +#include "foundation/PxVecMath.h" +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif +namespace aos +{ + +class PxTransformV +{ + public: + QuatV q; + Vec3V p; + + PX_FORCE_INLINE PxTransformV(const PxTransform& transform) + { + // PT: this is now similar to loadTransformU below. + q = QuatVLoadU(&transform.q.x); + p = V3LoadU(&transform.p.x); + } + + PX_FORCE_INLINE PxTransformV(const Vec3VArg p0 = V3Zero(), const QuatVArg q0 = QuatIdentity()) : q(q0), p(p0) + { + PX_ASSERT(isSaneQuatV(q0)); + } + + PX_FORCE_INLINE PxTransformV operator*(const PxTransformV& x) const + { + PX_ASSERT(x.isSane()); + return transform(x); + } + + PX_FORCE_INLINE PxTransformV getInverse() const + { + PX_ASSERT(isFinite()); + // return PxTransform(q.rotateInv(-p),q.getConjugate()); + return PxTransformV(QuatRotateInv(q, V3Neg(p)), QuatConjugate(q)); + } + + PX_FORCE_INLINE void invalidate() + { + p = V3Splat(FMax()); + q = QuatIdentity(); + } + + PX_FORCE_INLINE Vec3V transform(const Vec3VArg input) const + { + PX_ASSERT(isFinite()); + // return q.rotate(input) + p; + return QuatTransform(q, p, input); + } + + PX_FORCE_INLINE Vec3V transformInv(const Vec3VArg input) const + { + PX_ASSERT(isFinite()); + // return q.rotateInv(input-p); + return QuatRotateInv(q, V3Sub(input, p)); + } + + PX_FORCE_INLINE Vec3V rotate(const Vec3VArg input) const + { + PX_ASSERT(isFinite()); + // return q.rotate(input); + return QuatRotate(q, input); + } + + // PT: avoid some multiplies when immediately normalizing a rotated vector + PX_FORCE_INLINE Vec3V rotateAndNormalize(const Vec3VArg input) const + { + PX_ASSERT(isFinite()); + return QuatRotateAndNormalize(q, input); + } + + PX_FORCE_INLINE Vec3V rotateInv(const Vec3VArg input) const + { + PX_ASSERT(isFinite()); + // return q.rotateInv(input); + return QuatRotateInv(q, input); + } + + //! Transform transform to parent (returns compound transform: first src, then *this) + PX_FORCE_INLINE PxTransformV transform(const PxTransformV& src) const + { + PX_ASSERT(src.isSane()); + PX_ASSERT(isSane()); + // src = [srct, srcr] -> [r*srct + t, r*srcr] + // return PxTransform(q.rotate(src.p) + p, q*src.q); + return PxTransformV(V3Add(QuatRotate(q, src.p), p), QuatMul(q, src.q)); + } + +#if PX_LINUX && PX_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wbitwise-instead-of-logical" // bitwise intentionally chosen for performance +#endif + + /** + \brief returns true if finite and q is a unit quaternion + */ + PX_FORCE_INLINE bool isValid() const + { + // return p.isFinite() && q.isFinite() && q.isValid(); + return isFiniteVec3V(p) & isFiniteQuatV(q) & isValidQuatV(q); + } + + /** + \brief returns true if finite and quat magnitude is reasonably close to unit to allow for some accumulation of error + vs isValid + */ + + PX_FORCE_INLINE bool isSane() const + { + // return isFinite() && q.isSane(); + return isFinite() & isSaneQuatV(q); + } + + /** + \brief returns true if all elems are finite (not NAN or INF, etc.) + */ + PX_FORCE_INLINE bool isFinite() const + { + // return p.isFinite() && q.isFinite(); + return isFiniteVec3V(p) & isFiniteQuatV(q); + } + +#if PX_LINUX && PX_CLANG +#pragma clang diagnostic pop +#endif + + //! Transform transform from parent (returns compound transform: first src, then this->inverse) + PX_FORCE_INLINE PxTransformV transformInv(const PxTransformV& src) const + { + PX_ASSERT(src.isSane()); + PX_ASSERT(isFinite()); + // src = [srct, srcr] -> [r^-1*(srct-t), r^-1*srcr] + /*PxQuat qinv = q.getConjugate(); + return PxTransform(qinv.rotate(src.p - p), qinv*src.q);*/ + const QuatV qinv = QuatConjugate(q); + const Vec3V v = QuatRotate(qinv, V3Sub(src.p, p)); + const QuatV rot = QuatMul(qinv, src.q); + return PxTransformV(v, rot); + } + + static PX_FORCE_INLINE PxTransformV createIdentity() + { + return PxTransformV(V3Zero()); + } +}; + +PX_FORCE_INLINE PxTransformV loadTransformA(const PxTransform& transform) +{ + const QuatV q0 = QuatVLoadA(&transform.q.x); + const Vec3V p0 = V3LoadA(&transform.p.x); + + return PxTransformV(p0, q0); +} + +PX_FORCE_INLINE PxTransformV loadTransformU(const PxTransform& transform) +{ + const QuatV q0 = QuatVLoadU(&transform.q.x); + const Vec3V p0 = V3LoadU(&transform.p.x); + + return PxTransformV(p0, q0); +} + +class PxMatTransformV +{ + public: + Mat33V rot; + Vec3V p; + + PX_FORCE_INLINE PxMatTransformV() + { + p = V3Zero(); + rot = M33Identity(); + } + PX_FORCE_INLINE PxMatTransformV(const Vec3VArg _p, const Mat33V& _rot) + { + p = _p; + rot = _rot; + } + + PX_FORCE_INLINE PxMatTransformV(const PxTransformV& other) + { + p = other.p; + QuatGetMat33V(other.q, rot.col0, rot.col1, rot.col2); + } + + PX_FORCE_INLINE PxMatTransformV(const Vec3VArg _p, const QuatV& quat) + { + p = _p; + QuatGetMat33V(quat, rot.col0, rot.col1, rot.col2); + } + + PX_FORCE_INLINE Vec3V getCol0() const + { + return rot.col0; + } + + PX_FORCE_INLINE Vec3V getCol1() const + { + return rot.col1; + } + + PX_FORCE_INLINE Vec3V getCol2() const + { + return rot.col2; + } + + PX_FORCE_INLINE void setCol0(const Vec3VArg col0) + { + rot.col0 = col0; + } + + PX_FORCE_INLINE void setCol1(const Vec3VArg col1) + { + rot.col1 = col1; + } + + PX_FORCE_INLINE void setCol2(const Vec3VArg col2) + { + rot.col2 = col2; + } + + PX_FORCE_INLINE Vec3V transform(const Vec3VArg input) const + { + return V3Add(p, M33MulV3(rot, input)); + } + + PX_FORCE_INLINE Vec3V transformInv(const Vec3VArg input) const + { + return M33TrnspsMulV3(rot, V3Sub(input, p)); // QuatRotateInv(q, V3Sub(input, p)); + } + + PX_FORCE_INLINE Vec3V rotate(const Vec3VArg input) const + { + return M33MulV3(rot, input); + } + + PX_FORCE_INLINE Vec3V rotateInv(const Vec3VArg input) const + { + return M33TrnspsMulV3(rot, input); + } + + PX_FORCE_INLINE PxMatTransformV transformInv(const PxMatTransformV& src) const + { + + const Vec3V v = M33TrnspsMulV3(rot, V3Sub(src.p, p)); + const Mat33V mat = M33MulM33(M33Trnsps(rot), src.rot); + return PxMatTransformV(v, mat); + } +}; +} +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixAoS.h new file mode 100644 index 000000000..7543dba1e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixAoS.h @@ -0,0 +1,46 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXAOS_H +#define PXFOUNDATION_PXUNIXAOS_H + +// no includes here! this file should be included from PxcVecMath.h only!!! + +#if !COMPILE_VECTOR_INTRINSICS +#error Vector intrinsics should not be included when using scalar implementation. +#endif + +#if PX_INTEL_FAMILY +#include "foundation/unix/sse2/PxUnixSse2AoS.h" +#elif PX_NEON +#include "foundation/unix/neon/PxUnixNeonAoS.h" +#else +#error No SIMD implementation for this unix platform. +#endif + +#endif // PXFOUNDATION_PXUNIXAOS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixFPU.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixFPU.h new file mode 100644 index 000000000..b6ecaad28 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixFPU.h @@ -0,0 +1,83 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXFPU_H +#define PXFOUNDATION_PXUNIXFPU_H + +#include "foundation/PxPreprocessor.h" + +#if PX_LINUX || PX_OSX + +#if PX_X86 || PX_X64 +#if PX_EMSCRIPTEN +#include +#endif +#include +#elif PX_NEON +#include +#endif + +PX_INLINE physx::PxSIMDGuard::PxSIMDGuard(bool enable) +#if !PX_EMSCRIPTEN && (PX_X86 || PX_X64) + : mEnabled(enable) +#endif +{ +#if !PX_EMSCRIPTEN && (PX_X86 || PX_X64) + if(enable) + { + mControlWord = _mm_getcsr(); + // set default (disable exceptions: _MM_MASK_MASK) and FTZ (_MM_FLUSH_ZERO_ON), DAZ (_MM_DENORMALS_ZERO_ON: (1<<6)) + _mm_setcsr(_MM_MASK_MASK | _MM_FLUSH_ZERO_ON | (1 << 6)); + } + else + { + PX_UNUSED(enable); + PX_ASSERT(_mm_getcsr() & _MM_FLUSH_ZERO_ON); + PX_ASSERT(_mm_getcsr() & (1 << 6)); + PX_ASSERT(_mm_getcsr() & _MM_MASK_MASK); + } +#endif +} + +PX_INLINE physx::PxSIMDGuard::~PxSIMDGuard() +{ +#if !PX_EMSCRIPTEN && (PX_X86 || PX_X64) + if(mEnabled) + { + // restore control word and clear exception flags + // (setting exception state flags cause exceptions on the first following fp operation) + _mm_setcsr(mControlWord & PxU32(~_MM_EXCEPT_MASK)); + } +#endif +} + +#else + #error No SIMD implementation for this unix platform. +#endif // PX_LINUX || PX_OSX + +#endif // #ifndef PXFOUNDATION_PXUNIXFPU_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixInlineAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixInlineAoS.h new file mode 100644 index 000000000..83f750840 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixInlineAoS.h @@ -0,0 +1,44 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXINLINEAOS_H +#define PXFOUNDATION_PXUNIXINLINEAOS_H + +#if !COMPILE_VECTOR_INTRINSICS +#error Vector intrinsics should not be included when using scalar implementation. +#endif + +#if PX_INTEL_FAMILY +#include "foundation/unix/sse2/PxUnixSse2InlineAoS.h" +#elif PX_NEON +#include "foundation/unix/neon/PxUnixNeonInlineAoS.h" +#else +#error No SIMD implementation for this unix platform. +#endif + +#endif // PXFOUNDATION_PXUNIXINLINEAOS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixIntrinsics.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixIntrinsics.h new file mode 100644 index 000000000..36bb371b6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixIntrinsics.h @@ -0,0 +1,127 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PSFOUNDATION_PSUNIXINTRINSICS_H +#define PSFOUNDATION_PSUNIXINTRINSICS_H + +#include "foundation/PxAssert.h" +#include + +// this file is for internal intrinsics - that is, intrinsics that are used in +// cross platform code but do not appear in the API + +#if !(PX_LINUX || PX_APPLE_FAMILY) +#error "This file should only be included by unix builds!!" +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +PX_FORCE_INLINE void PxMemoryBarrier() +{ + __sync_synchronize(); +} + +/*! +Return the index of the highest set bit. Undefined for zero arg. +*/ +PX_INLINE uint32_t PxHighestSetBitUnsafe(uint64_t v) +{ + return uint32_t(63 - __builtin_clzl(v)); +} + +/*! +Return the index of the highest set bit. Undefined for zero arg. +*/ +PX_INLINE uint32_t PxHighestSetBitUnsafe(uint32_t v) +{ + return uint32_t(31 - __builtin_clz(v)); +} + +/*! +Return the index of the lowest set bit. Undefined for zero arg. +*/ +PX_INLINE uint32_t PxLowestSetBitUnsafe(uint64_t v) +{ + return uint32_t(__builtin_ctzl(v)); +} + +/*! +Return the index of the lowest set bit. Undefined for zero arg. +*/ +PX_INLINE uint32_t PxLowestSetBitUnsafe(uint32_t v) +{ + return uint32_t(__builtin_ctz(v)); +} + +/*! +Returns the index of the highest set bit. Returns 32 for v=0. +*/ +PX_INLINE uint32_t PxCountLeadingZeros(uint32_t v) +{ + if(v) + return uint32_t(__builtin_clz(v)); + else + return 32u; +} + +/*! +Prefetch aligned 64B x86, 32b ARM around \c ptr+offset. +*/ +PX_FORCE_INLINE void PxPrefetchLine(const void* ptr, uint32_t offset = 0) +{ +#if PX_CUDA_COMPILER + __builtin_prefetch(reinterpret_cast(ptr) + offset, 0, 3); +#else + __builtin_prefetch(reinterpret_cast(ptr) + offset, 0, 3); +#endif +} + +/*! +Prefetch \c count bytes starting at \c ptr. +*/ +PX_FORCE_INLINE void PxPrefetch(const void* ptr, uint32_t count = 1) +{ + const char* cp = reinterpret_cast(ptr); + uint64_t p = size_t(ptr); + uint64_t startLine = p >> 6, endLine = (p + count - 1) >> 6; + uint64_t lines = endLine - startLine + 1; + do + { + PxPrefetchLine(cp); + cp += 64; + } while(--lines); +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // #ifndef PSFOUNDATION_PSUNIXINTRINSICS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixMathIntrinsics.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixMathIntrinsics.h new file mode 100644 index 000000000..7eff6e6f3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixMathIntrinsics.h @@ -0,0 +1,179 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXINTRINSICS_H +#define PXFOUNDATION_PXUNIXINTRINSICS_H + +#include "foundation/PxAssert.h" + +#if !(PX_LINUX || PX_APPLE_FAMILY) +#error "This file should only be included by Unix builds!!" +#endif + +#if PX_LINUX && !PX_CUDA_COMPILER && !PX_EMSCRIPTEN + // Linux and CUDA compilation does not work with std::isfnite, as it is not marked as CUDA callable + #include + #ifndef isfinite + using std::isfinite; + #endif +#endif + +#include +#include + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +namespace intrinsics +{ +//! \brief platform-specific absolute value +PX_CUDA_CALLABLE PX_FORCE_INLINE float abs(float a) +{ + return ::fabsf(a); +} + +//! \brief platform-specific select float +PX_CUDA_CALLABLE PX_FORCE_INLINE float fsel(float a, float b, float c) +{ + return (a >= 0.0f) ? b : c; +} + +//! \brief platform-specific sign +PX_CUDA_CALLABLE PX_FORCE_INLINE float sign(float a) +{ + return (a >= 0.0f) ? 1.0f : -1.0f; +} + +//! \brief platform-specific reciprocal +PX_CUDA_CALLABLE PX_FORCE_INLINE float recip(float a) +{ + return 1.0f / a; +} + +//! \brief platform-specific reciprocal estimate +PX_CUDA_CALLABLE PX_FORCE_INLINE float recipFast(float a) +{ + return 1.0f / a; +} + +//! \brief platform-specific square root +PX_CUDA_CALLABLE PX_FORCE_INLINE float sqrt(float a) +{ + return ::sqrtf(a); +} + +//! \brief platform-specific reciprocal square root +PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrt(float a) +{ + return 1.0f / ::sqrtf(a); +} + +PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrtFast(float a) +{ + return 1.0f / ::sqrtf(a); +} + +//! \brief platform-specific sine +PX_CUDA_CALLABLE PX_FORCE_INLINE float sin(float a) +{ + return ::sinf(a); +} + +//! \brief platform-specific cosine +PX_CUDA_CALLABLE PX_FORCE_INLINE float cos(float a) +{ + return ::cosf(a); +} + +//! \brief platform-specific minimum +PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMin(float a, float b) +{ + return a < b ? a : b; +} + +//! \brief platform-specific maximum +PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMax(float a, float b) +{ + return a > b ? a : b; +} + +//! \brief platform-specific finiteness check (not INF or NAN) +PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(float a) +{ + //std::isfinite not recommended as of Feb 2017, since it doesn't work with g++/clang's floating point optimization. + union localU { PxU32 i; float f; } floatUnion; + floatUnion.f = a; + return !((floatUnion.i & 0x7fffffff) >= 0x7f800000); +} + +//! \brief platform-specific finiteness check (not INF or NAN) +PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(double a) +{ + return !!isfinite(a); +} + +/*! +Sets \c count bytes starting at \c dst to zero. +*/ +PX_FORCE_INLINE void* memZero(void* dest, size_t count) +{ + return memset(dest, 0, count); +} + +/*! +Sets \c count bytes starting at \c dst to \c c. +*/ +PX_FORCE_INLINE void* memSet(void* dest, int32_t c, size_t count) +{ + return memset(dest, c, count); +} + +/*! +Copies \c count bytes from \c src to \c dst. User memMove if regions overlap. +*/ +PX_FORCE_INLINE void* memCopy(void* dest, const void* src, size_t count) +{ + return memcpy(dest, src, count); +} + +/*! +Copies \c count bytes from \c src to \c dst. Supports overlapping regions. +*/ +PX_FORCE_INLINE void* memMove(void* dest, const void* src, size_t count) +{ + return memmove(dest, src, count); +} + +} // namespace intrinsics +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif // #ifndef PXFOUNDATION_PXUNIXINTRINSICS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixTrigConstants.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixTrigConstants.h new file mode 100644 index 000000000..fa70ef2f6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/PxUnixTrigConstants.h @@ -0,0 +1,76 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXTRIGCONSTANTS_H +#define PXFOUNDATION_PXUNIXTRIGCONSTANTS_H + +#include "foundation/PxMath.h" +#include "foundation/PxPreprocessor.h" + +namespace physx +{ +namespace aos +{ + +#if PX_CLANG +#if PX_LINUX +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmissing-variable-declarations" +#endif +#endif + +#define PX_GLOBALCONST extern const __attribute__((weak)) + +PX_ALIGN_PREFIX(16) +struct PX_VECTORF32 +{ + float f[4]; +} PX_ALIGN_SUFFIX(16); + +PX_GLOBALCONST PX_VECTORF32 g_PXSinCoefficients0 = { { 1.0f, -0.166666667f, 8.333333333e-3f, -1.984126984e-4f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXSinCoefficients1 = { { 2.755731922e-6f, -2.505210839e-8f, 1.605904384e-10f, -7.647163732e-13f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXSinCoefficients2 = { { 2.811457254e-15f, -8.220635247e-18f, 1.957294106e-20f, -3.868170171e-23f } }; +PX_GLOBALCONST PX_VECTORF32 g_PXCosCoefficients0 = { { 1.0f, -0.5f, 4.166666667e-2f, -1.388888889e-3f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXCosCoefficients1 = { { 2.480158730e-5f, -2.755731922e-7f, 2.087675699e-9f, -1.147074560e-11f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXCosCoefficients2 = { { 4.779477332e-14f, -1.561920697e-16f, 4.110317623e-19f, -8.896791392e-22f } }; +PX_GLOBALCONST PX_VECTORF32 g_PXReciprocalTwoPi = { { PxInvTwoPi, PxInvTwoPi, PxInvTwoPi, PxInvTwoPi } }; +PX_GLOBALCONST PX_VECTORF32 g_PXTwoPi = { { PxTwoPi, PxTwoPi, PxTwoPi, PxTwoPi } }; + +#if PX_CLANG +#if PX_LINUX +#pragma clang diagnostic pop +#endif +#endif +} // namespace aos +} // namespace physx + +#endif //PXFOUNDATION_PXUNIXTRIGCONSTANTS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/neon/PxUnixNeonAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/neon/PxUnixNeonAoS.h new file mode 100644 index 000000000..d88b931c8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/neon/PxUnixNeonAoS.h @@ -0,0 +1,136 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXNEONAOS_H +#define PXFOUNDATION_PXUNIXNEONAOS_H + +// no includes here! this file should be included from PxcVecMath.h only!!! + +#if !COMPILE_VECTOR_INTRINSICS +#error Vector intrinsics should not be included when using scalar implementation. +#endif + +// only ARM NEON compatible platforms should reach this +#include + +namespace physx +{ +namespace aos +{ + +typedef float32x2_t FloatV; +typedef float32x4_t Vec3V; +typedef float32x4_t Vec4V; +typedef uint32x4_t BoolV; +typedef float32x4_t QuatV; + +typedef uint32x4_t VecU32V; +typedef int32x4_t VecI32V; +typedef uint16x8_t VecU16V; +typedef int16x8_t VecI16V; +typedef uint8x16_t VecU8V; + +#define FloatVArg FloatV & +#define Vec3VArg Vec3V & +#define Vec4VArg Vec4V & +#define BoolVArg BoolV & +#define VecU32VArg VecU32V & +#define VecI32VArg VecI32V & +#define VecU16VArg VecU16V & +#define VecI16VArg VecI16V & +#define VecU8VArg VecU8V & +#define QuatVArg QuatV & + +// KS - TODO - make an actual VecCrossV type for NEON +#define VecCrossV Vec3V + +typedef VecI32V VecShiftV; +#define VecShiftVArg VecShiftV & + +PX_ALIGN_PREFIX(16) +struct Mat33V +{ + Mat33V() + { + } + Mat33V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec3V PX_ALIGN(16, col0); + Vec3V PX_ALIGN(16, col1); + Vec3V PX_ALIGN(16, col2); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat34V +{ + Mat34V() + { + } + Mat34V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2, const Vec3V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec3V PX_ALIGN(16, col0); + Vec3V PX_ALIGN(16, col1); + Vec3V PX_ALIGN(16, col2); + Vec3V PX_ALIGN(16, col3); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat43V +{ + Mat43V() + { + } + Mat43V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec4V PX_ALIGN(16, col0); + Vec4V PX_ALIGN(16, col1); + Vec4V PX_ALIGN(16, col2); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat44V +{ + Mat44V() + { + } + Mat44V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2, const Vec4V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec4V PX_ALIGN(16, col0); + Vec4V PX_ALIGN(16, col1); + Vec4V PX_ALIGN(16, col2); + Vec4V PX_ALIGN(16, col3); +} PX_ALIGN_SUFFIX(16); + +} // namespace aos +} // namespace physx + +#endif // PXFOUNDATION_PXUNIXNEONAOS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/neon/PxUnixNeonInlineAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/neon/PxUnixNeonInlineAoS.h new file mode 100644 index 000000000..faeca80ea --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/neon/PxUnixNeonInlineAoS.h @@ -0,0 +1,3636 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXNEONINLINEAOS_H +#define PXFOUNDATION_PXUNIXNEONINLINEAOS_H + +#if !COMPILE_VECTOR_INTRINSICS +#error Vector intrinsics should not be included when using scalar implementation. +#endif + +namespace physx +{ +namespace aos +{ + +// improved estimates +#define VRECIPEQ recipq_newton<1> +#define VRECIPE recip_newton<1> +#define VRECIPSQRTEQ rsqrtq_newton<1> +#define VRECIPSQRTE rsqrt_newton<1> + +// "exact" +#define VRECIPQ recipq_newton<4> +#if PX_SWITCH +// StabilizationTests.AveragePoint needs more precision to succeed. +#define VRECIP recip_newton<5> +#else +#define VRECIP recip_newton<4> +#endif +#define VRECIPSQRTQ rsqrtq_newton<4> +#define VRECIPSQRT rsqrt_newton<4> + +#define VECMATH_AOS_EPSILON (1e-3f) + +////////////////////////////////////////////////////////////////////// +//Test that Vec3V and FloatV are legal +////////////////////////////////// + +#define FLOAT_COMPONENTS_EQUAL_THRESHOLD 0.01f +PX_FORCE_INLINE bool isValidFloatV(const FloatV a) +{ + /* + PX_ALIGN(16, PxF32) data[4]; + vst1_f32(reinterpret_cast(data), a); + return + PxU32* intData = reinterpret_cast(data); + return intData[0] == intData[1]; + */ + PX_ALIGN(16, PxF32) data[4]; + vst1_f32(reinterpret_cast(data), a); + const float32_t x = data[0]; + const float32_t y = data[1]; + + return (x == y); + + /*if (PxAbs(x - y) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) + { + return true; + } + + if (PxAbs((x - y) / x) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) + { + return true; + } + + return false;*/ +} + +PX_FORCE_INLINE bool isValidVec3V(const Vec3V a) +{ + const float32_t w = vgetq_lane_f32(a, 3); + return (0.0f == w); + //const PxU32* intData = reinterpret_cast(&w); + //return *intData == 0; +} + +PX_FORCE_INLINE bool isAligned16(const void* a) +{ + return(0 == (size_t(a) & 0x0f)); +} + +#if PX_DEBUG +#define ASSERT_ISVALIDVEC3V(a) PX_ASSERT(isValidVec3V(a)) +#define ASSERT_ISVALIDFLOATV(a) PX_ASSERT(isValidFloatV(a)) +#define ASSERT_ISALIGNED16(a) PX_ASSERT(isAligned16(static_cast(a))) +#else +#define ASSERT_ISVALIDVEC3V(a) +#define ASSERT_ISVALIDFLOATV(a) +#define ASSERT_ISALIGNED16(a) +#endif + +namespace internalUnitNeonSimd +{ +PX_FORCE_INLINE PxU32 BAllTrue4_R(const BoolV a) +{ + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + const uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + return PxU32(vget_lane_u32(finalReduce, 0) == 0xffffFFFF); +} + +PX_FORCE_INLINE PxU32 BAllTrue3_R(const BoolV a) +{ + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + const uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + return PxU32((vget_lane_u32(finalReduce, 0) & 0xffFFff) == 0xffFFff); +} + +PX_FORCE_INLINE PxU32 BAnyTrue4_R(const BoolV a) +{ + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + const uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + return PxU32(vget_lane_u32(finalReduce, 0) != 0x0); +} + +PX_FORCE_INLINE PxU32 BAnyTrue3_R(const BoolV a) +{ + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + const uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + return PxU32((vget_lane_u32(finalReduce, 0) & 0xffFFff) != 0); +} +} + +namespace vecMathTests +{ +// PT: this function returns an invalid Vec3V (W!=0.0f) just for unit-testing 'isValidVec3V' +PX_FORCE_INLINE Vec3V getInvalidVec3V() +{ + PX_ALIGN(16, PxF32) data[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE bool allElementsEqualFloatV(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vget_lane_u32(vceq_f32(a, b), 0) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualVec3V(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return V3AllEq(a, b) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualVec4V(const Vec4V a, const Vec4V b) +{ + return V4AllEq(a, b) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualBoolV(const BoolV a, const BoolV b) +{ + return internalUnitNeonSimd::BAllTrue4_R(vceqq_u32(a, b)) != 0; +} + +PX_FORCE_INLINE PxU32 V4U32AllEq(const VecU32V a, const VecU32V b) +{ + return internalUnitNeonSimd::BAllTrue4_R(V4IsEqU32(a, b)); +} + +PX_FORCE_INLINE bool allElementsEqualVecU32V(const VecU32V a, const VecU32V b) +{ + return V4U32AllEq(a, b) != 0; +} + +PX_FORCE_INLINE BoolV V4IsEqI32(const VecI32V a, const VecI32V b) +{ + return vceqq_s32(a, b); +} + +PX_FORCE_INLINE PxU32 V4I32AllEq(const VecI32V a, const VecI32V b) +{ + return internalUnitNeonSimd::BAllTrue4_R(V4IsEqI32(a, b)); +} + +PX_FORCE_INLINE bool allElementsEqualVecI32V(const VecI32V a, const VecI32V b) +{ + return V4I32AllEq(a, b) != 0; +} + +PX_FORCE_INLINE bool allElementsNearEqualFloatV(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + + const float32x2_t c = vsub_f32(a, b); + const float32x2_t error = vdup_n_f32(VECMATH_AOS_EPSILON); +// absolute compare abs(error) > abs(c) + const uint32x2_t greater = vcagt_f32(error, c); + const uint32x2_t min = vpmin_u32(greater, greater); + return vget_lane_u32(min, 0) != 0x0; +} + +PX_FORCE_INLINE bool allElementsNearEqualVec3V(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + const float32x4_t c = vsubq_f32(a, b); + const float32x4_t error = vdupq_n_f32(VECMATH_AOS_EPSILON); +// absolute compare abs(error) > abs(c) + const uint32x4_t greater = vcagtq_f32(error, c); + return internalUnitNeonSimd::BAllTrue3_R(greater) != 0; +} + +PX_FORCE_INLINE bool allElementsNearEqualVec4V(const Vec4V a, const Vec4V b) +{ + const float32x4_t c = vsubq_f32(a, b); + const float32x4_t error = vdupq_n_f32(VECMATH_AOS_EPSILON); +// absolute compare abs(error) > abs(c) + const uint32x4_t greater = vcagtq_f32(error, c); + return internalUnitNeonSimd::BAllTrue4_R(greater) != 0x0; +} +} + +#if 0 // debugging printfs +#include +PX_FORCE_INLINE void printVec(const float32x4_t& v, const char* name) +{ + PX_ALIGN(16, float32_t) data[4]; + vst1q_f32(data, v); + printf("%s: (%f, %f, %f, %f)\n", name, data[0], data[1], data[2], data[3]); +} + +PX_FORCE_INLINE void printVec(const float32x2_t& v, const char* name) +{ + PX_ALIGN(16, float32_t) data[2]; + vst1_f32(data, v); + printf("%s: (%f, %f)\n", name, data[0], data[1]); +} + +PX_FORCE_INLINE void printVec(const uint32x4_t& v, const char* name) +{ + PX_ALIGN(16, uint32_t) data[4]; + vst1q_u32(data, v); + printf("%s: (0x%x, 0x%x, 0x%x, 0x%x)\n", name, data[0], data[1], data[2], data[3]); +} + +PX_FORCE_INLINE void printVec(const uint16x8_t& v, const char* name) +{ + PX_ALIGN(16, uint16_t) data[8]; + vst1q_u16(data, v); + printf("%s: (0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x)\n", name, data[0], data[1], data[2], data[3], + data[4], data[5], data[6], data[7]); +} + +PX_FORCE_INLINE void printVec(const int32x4_t& v, const char* name) +{ + PX_ALIGN(16, int32_t) data[4]; + vst1q_s32(data, v); + printf("%s: (0x%x, 0x%x, 0x%x, 0x%x)\n", name, data[0], data[1], data[2], data[3]); +} + +PX_FORCE_INLINE void printVec(const int16x8_t& v, const char* name) +{ + PX_ALIGN(16, int16_t) data[8]; + vst1q_s16(data, v); + printf("%s: (0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x)\n", name, data[0], data[1], data[2], data[3], + data[4], data[5], data[6], data[7]); +} + +PX_FORCE_INLINE void printVec(const uint16x4_t& v, const char* name) +{ + PX_ALIGN(16, uint16_t) data[4]; + vst1_u16(data, v); + printf("%s: (0x%x, 0x%x, 0x%x, 0x%x)\n", name, data[0], data[1], data[2], data[3]); +} + +PX_FORCE_INLINE void printVec(const uint32x2_t& v, const char* name) +{ + PX_ALIGN(16, uint32_t) data[2]; + vst1_u32(data, v); + printf("%s: (0x%x, 0x%x)\n", name, data[0], data[1]); +} + +PX_FORCE_INLINE void printVar(const PxU32 v, const char* name) +{ + printf("%s: 0x%x\n", name, v); +} + +PX_FORCE_INLINE void printVar(const PxF32 v, const char* name) +{ + printf("%s: %f\n", name, v); +} + +#define PRINT_VAR(X) printVar((X), #X) +#define PRINT_VEC(X) printVec((X), #X) +#define PRINT_VEC_TITLE(TITLE, X) printVec((X), TITLE #X) +#endif // debugging printf + +///////////////////////////////////////////////////////////////////// +////FUNCTIONS USED ONLY FOR ASSERTS IN VECTORISED IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE bool isFiniteFloatV(const FloatV a) +{ + PX_ALIGN(16, PxF32) data[4]; + vst1_f32(reinterpret_cast(data), a); + return PxIsFinite(data[0]) && PxIsFinite(data[1]); +} + +PX_FORCE_INLINE bool isFiniteVec3V(const Vec3V a) +{ + PX_ALIGN(16, PxF32) data[4]; + vst1q_f32(reinterpret_cast(data), a); + return PxIsFinite(data[0]) && PxIsFinite(data[1]) && PxIsFinite(data[2]); +} + +PX_FORCE_INLINE bool isFiniteVec4V(const Vec4V a) +{ + PX_ALIGN(16, PxF32) data[4]; + vst1q_f32(reinterpret_cast(data), a); + return PxIsFinite(data[0]) && PxIsFinite(data[1]) && PxIsFinite(data[2]) && PxIsFinite(data[3]); +} + +PX_FORCE_INLINE bool hasZeroElementinFloatV(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return vget_lane_u32(vreinterpret_u32_f32(a), 0) == 0; +} + +PX_FORCE_INLINE bool hasZeroElementInVec3V(const Vec3V a) +{ + const uint32x2_t dLow = vget_low_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t dMin = vpmin_u32(dLow, dLow); + + return vget_lane_u32(dMin, 0) == 0 || vgetq_lane_u32(vreinterpretq_u32_f32(a), 2) == 0; +} + +PX_FORCE_INLINE bool hasZeroElementInVec4V(const Vec4V a) +{ + const uint32x2_t dHigh = vget_high_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t dLow = vget_low_u32(vreinterpretq_u32_f32(a)); + + const uint32x2_t dMin = vmin_u32(dHigh, dLow); + const uint32x2_t pairMin = vpmin_u32(dMin, dMin); + return vget_lane_u32(pairMin, 0) == 0; +} + +///////////////////////////////////////////////////////////////////// +////VECTORISED FUNCTION IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE FloatV FLoad(const PxF32 f) +{ + return vdup_n_f32(reinterpret_cast(f)); +} + +PX_FORCE_INLINE FloatV FLoadA(const PxF32* const f) +{ + ASSERT_ISALIGNED16(f); + return vld1_f32(reinterpret_cast(f)); +} + +PX_FORCE_INLINE Vec3V V3Load(const PxF32 f) +{ + PX_ALIGN(16, PxF32) data[4] = { f, f, f, 0.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE Vec4V V4Load(const PxF32 f) +{ + return vdupq_n_f32(reinterpret_cast(f)); +} + +PX_FORCE_INLINE BoolV BLoad(const bool f) +{ + const PxU32 i = static_cast(-(static_cast(f))); + return vdupq_n_u32(i); +} + +PX_FORCE_INLINE Vec3V V3LoadA(const PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + PX_ALIGN(16, PxF32) data[4] = { f.x, f.y, f.z, 0.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE Vec3V V3LoadU(const PxVec3& f) +{ + PX_ALIGN(16, PxF32) data[4] = { f.x, f.y, f.z, 0.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE Vec3V V3LoadUnsafeA(const PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + PX_ALIGN(16, PxF32) data[4] = { f.x, f.y, f.z, 0.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE Vec3V V3LoadA(const PxF32* f) +{ + ASSERT_ISALIGNED16(f); + PX_ALIGN(16, PxF32) data[4] = { f[0], f[1], f[2], 0.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE Vec3V V3LoadU(const PxF32* f) +{ + PX_ALIGN(16, PxF32) data[4] = { f[0], f[1], f[2], 0.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V(Vec4V v) +{ + return vsetq_lane_f32(0.0f, v, 3); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_Vec4V_WUndefined(Vec4V v) +{ + return v; +} + +PX_FORCE_INLINE Vec4V Vec4V_From_Vec3V(Vec3V f) +{ + return f; // ok if it is implemented as the same type. +} + +PX_FORCE_INLINE Vec4V Vec4V_From_FloatV(FloatV f) +{ + return vcombine_f32(f, f); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_FloatV(FloatV f) +{ + return Vec3V_From_Vec4V(Vec4V_From_FloatV(f)); +} + +PX_FORCE_INLINE Vec3V Vec3V_From_FloatV_WUndefined(FloatV f) +{ + return Vec3V_From_Vec4V_WUndefined(Vec4V_From_FloatV(f)); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_PxVec3_WUndefined(const PxVec3& f) +{ + PX_ALIGN(16, PxF32) data[4] = { f.x, f.y, f.z, 0.0f }; + return V4LoadA(data); +} + +PX_FORCE_INLINE Mat33V Mat33V_From_PxMat33(const PxMat33& m) +{ + return Mat33V(V3LoadU(m.column0), V3LoadU(m.column1), V3LoadU(m.column2)); +} + +PX_FORCE_INLINE void PxMat33_From_Mat33V(const Mat33V& m, PxMat33& out) +{ + V3StoreU(m.col0, out.column0); + V3StoreU(m.col1, out.column1); + V3StoreU(m.col2, out.column2); +} + +PX_FORCE_INLINE Vec4V V4LoadA(const PxF32* const f) +{ + ASSERT_ISALIGNED16(f); + return vld1q_f32(reinterpret_cast(f)); +} + +PX_FORCE_INLINE void V4StoreA(Vec4V a, PxF32* f) +{ + ASSERT_ISALIGNED16(f); + vst1q_f32(reinterpret_cast(f), a); +} + +PX_FORCE_INLINE void V4StoreU(const Vec4V a, PxF32* f) +{ + PX_ALIGN(16, PxF32) f2[4]; + vst1q_f32(reinterpret_cast(f2), a); + f[0] = f2[0]; + f[1] = f2[1]; + f[2] = f2[2]; + f[3] = f2[3]; +} + +PX_FORCE_INLINE void BStoreA(const BoolV a, PxU32* u) +{ + ASSERT_ISALIGNED16(u); + vst1q_u32(reinterpret_cast(u), a); +} + +PX_FORCE_INLINE void U4StoreA(const VecU32V uv, PxU32* u) +{ + ASSERT_ISALIGNED16(u); + vst1q_u32(reinterpret_cast(u), uv); +} + +PX_FORCE_INLINE void I4StoreA(const VecI32V iv, PxI32* i) +{ + ASSERT_ISALIGNED16(i); + vst1q_s32(reinterpret_cast(i), iv); +} + +PX_FORCE_INLINE Vec4V V4LoadU(const PxF32* const f) +{ + return vld1q_f32(reinterpret_cast(f)); +} + +PX_FORCE_INLINE BoolV BLoad(const bool* const f) +{ + const PX_ALIGN(16, PxU32) b[4] = { static_cast(-static_cast(f[0])), + static_cast(-static_cast(f[1])), + static_cast(-static_cast(f[2])), + static_cast(-static_cast(f[3])) }; + return vld1q_u32(b); +} + +PX_FORCE_INLINE void FStore(const FloatV a, PxF32* PX_RESTRICT f) +{ + ASSERT_ISVALIDFLOATV(a); + // vst1q_lane_f32(f, a, 0); // causes vst1 alignment bug + *f = vget_lane_f32(a, 0); +} + +PX_FORCE_INLINE void Store_From_BoolV(const BoolV a, PxU32* PX_RESTRICT f) +{ + *f = vget_lane_u32(vget_low_u32(a), 0); +} + +PX_FORCE_INLINE void V3StoreA(const Vec3V a, PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + PX_ALIGN(16, PxF32) f2[4]; + vst1q_f32(reinterpret_cast(f2), a); + f = PxVec3(f2[0], f2[1], f2[2]); +} + +PX_FORCE_INLINE void V3StoreU(const Vec3V a, PxVec3& f) +{ + PX_ALIGN(16, PxF32) f2[4]; + vst1q_f32(reinterpret_cast(f2), a); + f = PxVec3(f2[0], f2[1], f2[2]); +} + +////////////////////////////////// +// FLOATV +////////////////////////////////// + +PX_FORCE_INLINE FloatV FZero() +{ + return FLoad(0.0f); +} + +PX_FORCE_INLINE FloatV FOne() +{ + return FLoad(1.0f); +} + +PX_FORCE_INLINE FloatV FHalf() +{ + return FLoad(0.5f); +} + +PX_FORCE_INLINE FloatV FEps() +{ + return FLoad(PX_EPS_REAL); +} + +PX_FORCE_INLINE FloatV FEps6() +{ + return FLoad(1e-6f); +} + +PX_FORCE_INLINE FloatV FMax() +{ + return FLoad(PX_MAX_REAL); +} + +PX_FORCE_INLINE FloatV FNegMax() +{ + return FLoad(-PX_MAX_REAL); +} + +PX_FORCE_INLINE FloatV IZero() +{ + return vreinterpret_f32_u32(vdup_n_u32(0)); +} + +PX_FORCE_INLINE FloatV IOne() +{ + return vreinterpret_f32_u32(vdup_n_u32(1)); +} + +PX_FORCE_INLINE FloatV ITwo() +{ + return vreinterpret_f32_u32(vdup_n_u32(2)); +} + +PX_FORCE_INLINE FloatV IThree() +{ + return vreinterpret_f32_u32(vdup_n_u32(3)); +} + +PX_FORCE_INLINE FloatV IFour() +{ + return vreinterpret_f32_u32(vdup_n_u32(4)); +} + +PX_FORCE_INLINE FloatV FNeg(const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return vneg_f32(f); +} + +PX_FORCE_INLINE FloatV FAdd(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vadd_f32(a, b); +} + +PX_FORCE_INLINE FloatV FSub(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vsub_f32(a, b); +} + +PX_FORCE_INLINE FloatV FMul(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vmul_f32(a, b); +} + +template +PX_FORCE_INLINE float32x2_t recip_newton(const float32x2_t& in) +{ + float32x2_t recip = vrecpe_f32(in); + for(int i = 0; i < n; ++i) + recip = vmul_f32(recip, vrecps_f32(in, recip)); + return recip; +} + +template +PX_FORCE_INLINE float32x4_t recipq_newton(const float32x4_t& in) +{ + float32x4_t recip = vrecpeq_f32(in); + for(int i = 0; i < n; ++i) + recip = vmulq_f32(recip, vrecpsq_f32(recip, in)); + return recip; +} + +template +PX_FORCE_INLINE float32x2_t rsqrt_newton(const float32x2_t& in) +{ + float32x2_t rsqrt = vrsqrte_f32(in); + for(int i = 0; i < n; ++i) + rsqrt = vmul_f32(rsqrt, vrsqrts_f32(vmul_f32(rsqrt, rsqrt), in)); + return rsqrt; +} + +template +PX_FORCE_INLINE float32x4_t rsqrtq_newton(const float32x4_t& in) +{ + float32x4_t rsqrt = vrsqrteq_f32(in); + for(int i = 0; i < n; ++i) + rsqrt = vmulq_f32(rsqrt, vrsqrtsq_f32(vmulq_f32(rsqrt, rsqrt), in)); + return rsqrt; +} + +PX_FORCE_INLINE FloatV FDiv(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vmul_f32(a, VRECIP(b)); +} + +PX_FORCE_INLINE FloatV FDivFast(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vmul_f32(a, VRECIPE(b)); +} + +PX_FORCE_INLINE FloatV FRecip(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return VRECIP(a); +} + +PX_FORCE_INLINE FloatV FRecipFast(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return VRECIPE(a); +} + +PX_FORCE_INLINE FloatV FRsqrt(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return VRECIPSQRT(a); +} + +PX_FORCE_INLINE FloatV FSqrt(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return FSel(FIsEq(a, FZero()), a, vmul_f32(a, VRECIPSQRT(a))); +} + +PX_FORCE_INLINE FloatV FRsqrtFast(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return VRECIPSQRTE(a); +} + +PX_FORCE_INLINE FloatV FScaleAdd(const FloatV a, const FloatV b, const FloatV c) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDFLOATV(c); + return vmla_f32(c, a, b); +} + +PX_FORCE_INLINE FloatV FNegScaleSub(const FloatV a, const FloatV b, const FloatV c) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDFLOATV(c); + return vmls_f32(c, a, b); +} + +PX_FORCE_INLINE FloatV FAbs(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + return vabs_f32(a); +} + +PX_FORCE_INLINE FloatV FSel(const BoolV c, const FloatV a, const FloatV b) +{ + PX_ASSERT( vecMathTests::allElementsEqualBoolV(c, BTTTT()) || + vecMathTests::allElementsEqualBoolV(c, BFFFF())); + ASSERT_ISVALIDFLOATV(vbsl_f32(vget_low_u32(c), a, b)); + return vbsl_f32(vget_low_u32(c), a, b); +} + +PX_FORCE_INLINE BoolV FIsGrtr(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vdupq_lane_u32(vcgt_f32(a, b), 0); +} + +PX_FORCE_INLINE BoolV FIsGrtrOrEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vdupq_lane_u32(vcge_f32(a, b), 0); +} + +PX_FORCE_INLINE BoolV FIsEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vdupq_lane_u32(vceq_f32(a, b), 0); +} + +PX_FORCE_INLINE FloatV FMax(const FloatV a, const FloatV b) +{ + //ASSERT_ISVALIDFLOATV(a); + //ASSERT_ISVALIDFLOATV(b); + return vmax_f32(a, b); +} + +PX_FORCE_INLINE FloatV FMin(const FloatV a, const FloatV b) +{ + //ASSERT_ISVALIDFLOATV(a); + //ASSERT_ISVALIDFLOATV(b); + return vmin_f32(a, b); +} + +PX_FORCE_INLINE FloatV FClamp(const FloatV a, const FloatV minV, const FloatV maxV) +{ + ASSERT_ISVALIDFLOATV(minV); + ASSERT_ISVALIDFLOATV(maxV); + return vmax_f32(vmin_f32(a, maxV), minV); +} + +PX_FORCE_INLINE PxU32 FAllGrtr(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vget_lane_u32(vcgt_f32(a, b), 0); +} + +PX_FORCE_INLINE PxU32 FAllGrtrOrEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vget_lane_u32(vcge_f32(a, b), 0); +} + +PX_FORCE_INLINE PxU32 FAllEq(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + return vget_lane_u32(vceq_f32(a, b), 0); +} + +PX_FORCE_INLINE FloatV FRound(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + + // truncate(a + (0.5f - sign(a))) + const float32x2_t half = vdup_n_f32(0.5f); + const float32x2_t sign = vcvt_f32_u32((vshr_n_u32(vreinterpret_u32_f32(a), 31))); + const float32x2_t aPlusHalf = vadd_f32(a, half); + const float32x2_t aRound = vsub_f32(aPlusHalf, sign); + int32x2_t tmp = vcvt_s32_f32(aRound); + return vcvt_f32_s32(tmp); +} + +PX_FORCE_INLINE FloatV FSin(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const FloatV recipTwoPi = FLoadA(g_PXReciprocalTwoPi.f); + const FloatV twoPi = FLoadA(g_PXTwoPi.f); + const FloatV tmp = FMul(a, recipTwoPi); + const FloatV b = FRound(tmp); + const FloatV V1 = FNegScaleSub(twoPi, b, a); + + // sin(V) ~= V - V^3 / 3! + V^5 / 5! - V^7 / 7! + V^9 / 9! - V^11 / 11! + V^13 / 13! - + // V^15 / 15! + V^17 / 17! - V^19 / 19! + V^21 / 21! - V^23 / 23! (for -PI <= V < PI) + const FloatV V2 = FMul(V1, V1); + const FloatV V3 = FMul(V2, V1); + const FloatV V5 = FMul(V3, V2); + const FloatV V7 = FMul(V5, V2); + const FloatV V9 = FMul(V7, V2); + const FloatV V11 = FMul(V9, V2); + const FloatV V13 = FMul(V11, V2); + const FloatV V15 = FMul(V13, V2); + const FloatV V17 = FMul(V15, V2); + const FloatV V19 = FMul(V17, V2); + const FloatV V21 = FMul(V19, V2); + const FloatV V23 = FMul(V21, V2); + + const Vec4V sinCoefficients0 = V4LoadA(g_PXSinCoefficients0.f); + const Vec4V sinCoefficients1 = V4LoadA(g_PXSinCoefficients1.f); + const Vec4V sinCoefficients2 = V4LoadA(g_PXSinCoefficients2.f); + + const FloatV S1 = V4GetY(sinCoefficients0); + const FloatV S2 = V4GetZ(sinCoefficients0); + const FloatV S3 = V4GetW(sinCoefficients0); + const FloatV S4 = V4GetX(sinCoefficients1); + const FloatV S5 = V4GetY(sinCoefficients1); + const FloatV S6 = V4GetZ(sinCoefficients1); + const FloatV S7 = V4GetW(sinCoefficients1); + const FloatV S8 = V4GetX(sinCoefficients2); + const FloatV S9 = V4GetY(sinCoefficients2); + const FloatV S10 = V4GetZ(sinCoefficients2); + const FloatV S11 = V4GetW(sinCoefficients2); + + FloatV Result; + Result = FScaleAdd(S1, V3, V1); + Result = FScaleAdd(S2, V5, Result); + Result = FScaleAdd(S3, V7, Result); + Result = FScaleAdd(S4, V9, Result); + Result = FScaleAdd(S5, V11, Result); + Result = FScaleAdd(S6, V13, Result); + Result = FScaleAdd(S7, V15, Result); + Result = FScaleAdd(S8, V17, Result); + Result = FScaleAdd(S9, V19, Result); + Result = FScaleAdd(S10, V21, Result); + Result = FScaleAdd(S11, V23, Result); + + return Result; +} + +PX_FORCE_INLINE FloatV FCos(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const FloatV recipTwoPi = FLoadA(g_PXReciprocalTwoPi.f); + const FloatV twoPi = FLoadA(g_PXTwoPi.f); + const FloatV tmp = FMul(a, recipTwoPi); + const FloatV b = FRound(tmp); + const FloatV V1 = FNegScaleSub(twoPi, b, a); + + // cos(V) ~= 1 - V^2 / 2! + V^4 / 4! - V^6 / 6! + V^8 / 8! - V^10 / 10! + V^12 / 12! - + // V^14 / 14! + V^16 / 16! - V^18 / 18! + V^20 / 20! - V^22 / 22! (for -PI <= V < PI) + const FloatV V2 = FMul(V1, V1); + const FloatV V4 = FMul(V2, V2); + const FloatV V6 = FMul(V4, V2); + const FloatV V8 = FMul(V4, V4); + const FloatV V10 = FMul(V6, V4); + const FloatV V12 = FMul(V6, V6); + const FloatV V14 = FMul(V8, V6); + const FloatV V16 = FMul(V8, V8); + const FloatV V18 = FMul(V10, V8); + const FloatV V20 = FMul(V10, V10); + const FloatV V22 = FMul(V12, V10); + + const Vec4V cosCoefficients0 = V4LoadA(g_PXCosCoefficients0.f); + const Vec4V cosCoefficients1 = V4LoadA(g_PXCosCoefficients1.f); + const Vec4V cosCoefficients2 = V4LoadA(g_PXCosCoefficients2.f); + + const FloatV C1 = V4GetY(cosCoefficients0); + const FloatV C2 = V4GetZ(cosCoefficients0); + const FloatV C3 = V4GetW(cosCoefficients0); + const FloatV C4 = V4GetX(cosCoefficients1); + const FloatV C5 = V4GetY(cosCoefficients1); + const FloatV C6 = V4GetZ(cosCoefficients1); + const FloatV C7 = V4GetW(cosCoefficients1); + const FloatV C8 = V4GetX(cosCoefficients2); + const FloatV C9 = V4GetY(cosCoefficients2); + const FloatV C10 = V4GetZ(cosCoefficients2); + const FloatV C11 = V4GetW(cosCoefficients2); + + FloatV Result; + Result = FScaleAdd(C1, V2, FOne()); + Result = FScaleAdd(C2, V4, Result); + Result = FScaleAdd(C3, V6, Result); + Result = FScaleAdd(C4, V8, Result); + Result = FScaleAdd(C5, V10, Result); + Result = FScaleAdd(C6, V12, Result); + Result = FScaleAdd(C7, V14, Result); + Result = FScaleAdd(C8, V16, Result); + Result = FScaleAdd(C9, V18, Result); + Result = FScaleAdd(C10, V20, Result); + Result = FScaleAdd(C11, V22, Result); + + return Result; +} + +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV min, const FloatV max) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(min); + ASSERT_ISVALIDFLOATV(max); + + const BoolV c = BOr(FIsGrtr(a, max), FIsGrtr(min, a)); + return PxU32(!BAllEqFFFF(c)); +} + +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV min, const FloatV max) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(min); + ASSERT_ISVALIDFLOATV(max); + + const BoolV c = BAnd(FIsGrtrOrEq(a, min), FIsGrtrOrEq(max, a)); + return PxU32(BAllEqTTTT(c)); +} + +PX_FORCE_INLINE PxU32 FOutOfBounds(const FloatV a, const FloatV bounds) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(bounds); + const uint32x2_t greater = vcagt_f32(a, bounds); + return vget_lane_u32(greater, 0); +} + +PX_FORCE_INLINE PxU32 FInBounds(const FloatV a, const FloatV bounds) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(bounds); + const uint32x2_t geq = vcage_f32(bounds, a); + return vget_lane_u32(geq, 0); +} + +////////////////////////////////// +// VEC3V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V V3Splat(const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + + const uint32x2_t mask = { 0xffffFFFF, 0x0 }; + const uint32x2_t uHigh = vreinterpret_u32_f32(f); + const float32x2_t dHigh = vreinterpret_f32_u32(vand_u32(uHigh, mask)); + + return vcombine_f32(f, dHigh); +} + +PX_FORCE_INLINE Vec3V V3Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z) +{ + ASSERT_ISVALIDFLOATV(x); + ASSERT_ISVALIDFLOATV(y); + ASSERT_ISVALIDFLOATV(z); + + const uint32x2_t mask = { 0xffffFFFF, 0x0 }; + const uint32x2_t dHigh = vand_u32(vreinterpret_u32_f32(z), mask); + const uint32x2_t dLow = vext_u32(vreinterpret_u32_f32(x), vreinterpret_u32_f32(y), 1); + return vreinterpretq_f32_u32(vcombine_u32(dLow, dHigh)); +} + +PX_FORCE_INLINE Vec3V V3UnitX() +{ + const float32x4_t x = { 1.0f, 0.0f, 0.0f, 0.0f }; + return x; +} + +PX_FORCE_INLINE Vec3V V3UnitY() +{ + const float32x4_t y = { 0, 1.0f, 0, 0 }; + return y; +} + +PX_FORCE_INLINE Vec3V V3UnitZ() +{ + const float32x4_t z = { 0, 0, 1.0f, 0 }; + return z; +} + +PX_FORCE_INLINE FloatV V3GetX(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + const float32x2_t fLow = vget_low_f32(f); + return vdup_lane_f32(fLow, 0); +} + +PX_FORCE_INLINE FloatV V3GetY(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + const float32x2_t fLow = vget_low_f32(f); + return vdup_lane_f32(fLow, 1); +} + +PX_FORCE_INLINE FloatV V3GetZ(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + const float32x2_t fhigh = vget_high_f32(f); + return vdup_lane_f32(fhigh, 0); +} + +PX_FORCE_INLINE Vec3V V3SetX(const Vec3V v, const FloatV f) +{ + ASSERT_ISVALIDVEC3V(v); + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BFTTT(), v, vcombine_f32(f, f)); +} + +PX_FORCE_INLINE Vec3V V3SetY(const Vec3V v, const FloatV f) +{ + ASSERT_ISVALIDVEC3V(v); + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTFTT(), v, vcombine_f32(f, f)); +} + +PX_FORCE_INLINE Vec3V V3SetZ(const Vec3V v, const FloatV f) +{ + ASSERT_ISVALIDVEC3V(v); + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTTFT(), v, vcombine_f32(f, f)); +} + +PX_FORCE_INLINE Vec3V V3ColX(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + + const float32x2_t aLow = vget_low_f32(a); + const float32x2_t bLow = vget_low_f32(b); + const float32x2_t cLow = vget_low_f32(c); + const float32x2_t zero = vdup_n_f32(0.0f); + + const float32x2x2_t zipL = vzip_f32(aLow, bLow); + const float32x2x2_t zipH = vzip_f32(cLow, zero); + + return vcombine_f32(zipL.val[0], zipH.val[0]); +} + +PX_FORCE_INLINE Vec3V V3ColY(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + + const float32x2_t aLow = vget_low_f32(a); + const float32x2_t bLow = vget_low_f32(b); + const float32x2_t cLow = vget_low_f32(c); + const float32x2_t zero = vdup_n_f32(0.0f); + + const float32x2x2_t zipL = vzip_f32(aLow, bLow); + const float32x2x2_t zipH = vzip_f32(cLow, zero); + + return vcombine_f32(zipL.val[1], zipH.val[1]); +} + +PX_FORCE_INLINE Vec3V V3ColZ(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + + const float32x2_t aHi = vget_high_f32(a); + const float32x2_t bHi = vget_high_f32(b); + const float32x2_t cHi = vget_high_f32(c); + + const float32x2x2_t zipL = vzip_f32(aHi, bHi); + + return vcombine_f32(zipL.val[0], cHi); +} + +PX_FORCE_INLINE Vec3V V3Zero() +{ + return vdupq_n_f32(0.0f); +} + +PX_FORCE_INLINE Vec3V V3Eps() +{ + return V3Load(PX_EPS_REAL); +} + +PX_FORCE_INLINE Vec3V V3One() +{ + return V3Load(1.0f); +} + +PX_FORCE_INLINE Vec3V V3Neg(const Vec3V f) +{ + ASSERT_ISVALIDVEC3V(f); + const float32x4_t tmp = vnegq_f32(f); + return vsetq_lane_f32(0.0f, tmp, 3); +} + +PX_FORCE_INLINE Vec3V V3Add(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vaddq_f32(a, b); +} + +PX_FORCE_INLINE Vec3V V3Add(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + return vaddq_f32(a, Vec3V_From_FloatV(b)); +} + +PX_FORCE_INLINE Vec3V V3Sub(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vsubq_f32(a, b); +} + +PX_FORCE_INLINE Vec3V V3Sub(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + return vsubq_f32(a, Vec3V_From_FloatV(b)); +} + +PX_FORCE_INLINE Vec3V V3Scale(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + const float32x4_t tmp = vmulq_lane_f32(a, b, 0); + return vsetq_lane_f32(0.0f, tmp, 3); +} + +PX_FORCE_INLINE Vec3V V3Mul(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vmulq_f32(a, b); +} + +PX_FORCE_INLINE Vec3V V3ScaleInv(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + const float32x2_t invB = VRECIP(b); + const float32x4_t tmp = vmulq_lane_f32(a, invB, 0); + return vsetq_lane_f32(0.0f, tmp, 3); +} + +PX_FORCE_INLINE Vec3V V3Div(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + float32x4_t invB = VRECIPQ(b); + invB = vsetq_lane_f32(0.0f, invB, 3); + return vmulq_f32(a, invB); +} + +PX_FORCE_INLINE Vec3V V3ScaleInvFast(const Vec3V a, const FloatV b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + const float32x2_t invB = VRECIPE(b); + const float32x4_t tmp = vmulq_lane_f32(a, invB, 0); + return vsetq_lane_f32(0.0f, tmp, 3); +} + +PX_FORCE_INLINE Vec3V V3DivFast(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + float32x4_t invB = VRECIPEQ(b); + invB = vsetq_lane_f32(0.0f, invB, 3); + return vmulq_f32(a, invB); +} + +PX_FORCE_INLINE Vec3V V3Recip(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const float32x4_t recipA = VRECIPQ(a); + return vsetq_lane_f32(0.0f, recipA, 3); +} + +PX_FORCE_INLINE Vec3V V3RecipFast(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const float32x4_t recipA = VRECIPEQ(a); + return vsetq_lane_f32(0.0f, recipA, 3); +} + +PX_FORCE_INLINE Vec3V V3Rsqrt(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const float32x4_t rSqrA = VRECIPSQRTQ(a); + return vsetq_lane_f32(0.0f, rSqrA, 3); +} + +PX_FORCE_INLINE Vec3V V3RsqrtFast(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const float32x4_t rSqrA = VRECIPSQRTEQ(a); + return vsetq_lane_f32(0.0f, rSqrA, 3); +} + +PX_FORCE_INLINE Vec3V V3ScaleAdd(const Vec3V a, const FloatV b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDVEC3V(c); + + float32x4_t tmp = vmlaq_lane_f32(c, a, b, 0); + // using vsetq_lane_f32 resulted in failures, + // probably related to a compiler bug on + // ndk r9d-win32, gcc 4.8, cardhu/shield + + // code with issue + // return vsetq_lane_f32(0.0f, tmp, 3); + + // workaround + float32x2_t w_z = vget_high_f32(tmp); + float32x2_t y_x = vget_low_f32(tmp); + w_z = vset_lane_f32(0.0f, w_z, 1); + return vcombine_f32(y_x, w_z); +} + +PX_FORCE_INLINE Vec3V V3NegScaleSub(const Vec3V a, const FloatV b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDFLOATV(b); + ASSERT_ISVALIDVEC3V(c); + + float32x4_t tmp = vmlsq_lane_f32(c, a, b, 0); + // using vsetq_lane_f32 resulted in failures, + // probably related to a compiler bug on + // ndk r9d-win32, gcc 4.8, cardhu/shield + + // code with issue + // return vsetq_lane_f32(0.0f, tmp, 3); + + // workaround + float32x2_t w_z = vget_high_f32(tmp); + float32x2_t y_x = vget_low_f32(tmp); + w_z = vset_lane_f32(0.0f, w_z, 1); + return vcombine_f32(y_x, w_z); +} + +PX_FORCE_INLINE Vec3V V3MulAdd(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + return vmlaq_f32(c, a, b); +} + +PX_FORCE_INLINE Vec3V V3NegMulSub(const Vec3V a, const Vec3V b, const Vec3V c) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + ASSERT_ISVALIDVEC3V(c); + return vmlsq_f32(c, a, b); +} + +PX_FORCE_INLINE Vec3V V3Abs(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return vabsq_f32(a); +} + +PX_FORCE_INLINE FloatV V3Dot(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + + // const uint32x2_t mask = {0xffffFFFF, 0x0}; + const float32x4_t tmp = vmulq_f32(a, b); + + const float32x2_t low = vget_low_f32(tmp); + const float32x2_t high = vget_high_f32(tmp); + // const float32x2_t high = vreinterpret_f32_u32(vand_u32(vreinterpret_u32_f32(high_), mask)); + + const float32x2_t sumTmp = vpadd_f32(low, high); // = {0+z, x+y} + const float32x2_t sum0ZYX = vpadd_f32(sumTmp, sumTmp); // = {x+y+z, x+y+z} + + return sum0ZYX; +} + +PX_FORCE_INLINE Vec3V V3Cross(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + + const uint32x2_t TF = { 0xffffFFFF, 0x0 }; + const float32x2_t ay_ax = vget_low_f32(a); // d2 + const float32x2_t aw_az = vget_high_f32(a); // d3 + const float32x2_t by_bx = vget_low_f32(b); // d4 + const float32x2_t bw_bz = vget_high_f32(b); // d5 + // Hi, Lo + const float32x2_t bz_by = vext_f32(by_bx, bw_bz, 1); // bz, by + const float32x2_t az_ay = vext_f32(ay_ax, aw_az, 1); // az, ay + + const float32x2_t azbx = vmul_f32(aw_az, by_bx); // 0, az*bx + const float32x2_t aybz_axby = vmul_f32(ay_ax, bz_by); // ay*bz, ax*by + + const float32x2_t azbxSUBaxbz = vmls_f32(azbx, bw_bz, ay_ax); // 0, az*bx-ax*bz + const float32x2_t aybzSUBazby_axbySUBaybx = vmls_f32(aybz_axby, by_bx, az_ay); // ay*bz-az*by, ax*by-ay*bx + + const float32x2_t retLow = vext_f32(aybzSUBazby_axbySUBaybx, azbxSUBaxbz, 1); // az*bx-ax*bz, ay*bz-az*by + const uint32x2_t retHigh = vand_u32(TF, vreinterpret_u32_f32(aybzSUBazby_axbySUBaybx)); // 0, ax*by-ay*bx + + return vcombine_f32(retLow, vreinterpret_f32_u32(retHigh)); +} + +PX_FORCE_INLINE VecCrossV V3PrepareCross(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return a; +} + +PX_FORCE_INLINE FloatV V3Length(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + // const uint32x2_t mask = {0xffffFFFF, 0x0}; + + const float32x4_t tmp = vmulq_f32(a, a); + const float32x2_t low = vget_low_f32(tmp); + const float32x2_t high = vget_high_f32(tmp); + // const float32x2_t high = vreinterpret_f32_u32(vand_u32(vreinterpret_u32_f32(high_), mask)); + + const float32x2_t sumTmp = vpadd_f32(low, high); // = {0+z, x+y} + const float32x2_t sum0ZYX = vpadd_f32(sumTmp, sumTmp); // = {x+y+z, x+y+z} + + return FSqrt(sum0ZYX); +} + +PX_FORCE_INLINE FloatV V3LengthSq(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + return V3Dot(a, a); +} + +PX_FORCE_INLINE Vec3V V3Normalize(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + //PX_ASSERT(!FAllEq(V4LengthSq(a), FZero())); + return V3ScaleInv(a, V3Length(a)); +} + +PX_FORCE_INLINE Vec3V V3NormalizeFast(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + //PX_ASSERT(!FAllEq(V4LengthSq(a), FZero())); + return V3Scale(a, VRECIPSQRTE(V3Dot(a, a))); +} + +PX_FORCE_INLINE Vec3V V3NormalizeSafe(const Vec3V a, const Vec3V unsafeReturnValue) +{ + ASSERT_ISVALIDVEC3V(a); + const FloatV zero = vdup_n_f32(0.0f); + const FloatV length = V3Length(a); + const uint32x4_t isGreaterThanZero = FIsGrtr(length, zero); + return V3Sel(isGreaterThanZero, V3ScaleInv(a, length), unsafeReturnValue); +} + +PX_FORCE_INLINE Vec3V V3Sel(const BoolV c, const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V( vbslq_f32(c, a, b)); + return vbslq_f32(c, a, b); +} + +PX_FORCE_INLINE BoolV V3IsGrtr(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vcgtq_f32(a, b); +} + +PX_FORCE_INLINE BoolV V3IsGrtrOrEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vcgeq_f32(a, b); +} + +PX_FORCE_INLINE BoolV V3IsEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vceqq_f32(a, b); +} + +PX_FORCE_INLINE Vec3V V3Max(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vmaxq_f32(a, b); +} + +PX_FORCE_INLINE Vec3V V3Min(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return vminq_f32(a, b); +} + +PX_FORCE_INLINE FloatV V3ExtractMax(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + const float32x2_t low = vget_low_f32(a); + const float32x2_t high = vget_high_f32(a); + + const float32x2_t zz = vdup_lane_f32(high, 0); + const float32x2_t max0 = vpmax_f32(zz, low); + const float32x2_t max1 = vpmax_f32(max0, max0); + + return max1; +} + +PX_FORCE_INLINE FloatV V3ExtractMin(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + const float32x2_t low = vget_low_f32(a); + const float32x2_t high = vget_high_f32(a); + + const float32x2_t zz = vdup_lane_f32(high, 0); + const float32x2_t min0 = vpmin_f32(zz, low); + const float32x2_t min1 = vpmin_f32(min0, min0); + + return min1; +} + +// return (a >= 0.0f) ? 1.0f : -1.0f; +PX_FORCE_INLINE Vec3V V3Sign(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const Vec3V zero = V3Zero(); + const Vec3V one = V3One(); + const Vec3V none = V3Neg(one); + return V3Sel(V3IsGrtrOrEq(a, zero), one, none); +} + +PX_FORCE_INLINE Vec3V V3Clamp(const Vec3V a, const Vec3V minV, const Vec3V maxV) +{ + ASSERT_ISVALIDVEC3V(minV); + ASSERT_ISVALIDVEC3V(maxV); + return V3Max(V3Min(a, maxV), minV); +} + +PX_FORCE_INLINE PxU32 V3AllGrtr(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return internalUnitNeonSimd::BAllTrue3_R(V4IsGrtr(a, b)); +} + +PX_FORCE_INLINE PxU32 V3AllGrtrOrEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return internalUnitNeonSimd::BAllTrue3_R(V4IsGrtrOrEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V3AllEq(const Vec3V a, const Vec3V b) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(b); + return internalUnitNeonSimd::BAllTrue3_R(V4IsEq(a, b)); +} + +PX_FORCE_INLINE Vec3V V3Round(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + // truncate(a + (0.5f - sign(a))) + const Vec3V half = V3Load(0.5f); + const float32x4_t sign = vcvtq_f32_u32((vshrq_n_u32(vreinterpretq_u32_f32(a), 31))); + const Vec3V aPlusHalf = V3Add(a, half); + const Vec3V aRound = V3Sub(aPlusHalf, sign); + return vcvtq_f32_s32(vcvtq_s32_f32(aRound)); +} + +PX_FORCE_INLINE Vec3V V3Sin(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const Vec4V twoPi = V4LoadA(g_PXTwoPi.f); + const Vec3V tmp = V4Mul(a, recipTwoPi); + const Vec3V b = V3Round(tmp); + const Vec3V V1 = V4NegMulSub(twoPi, b, a); + + // sin(V) ~= V - V^3 / 3! + V^5 / 5! - V^7 / 7! + V^9 / 9! - V^11 / 11! + V^13 / 13! - + // V^15 / 15! + V^17 / 17! - V^19 / 19! + V^21 / 21! - V^23 / 23! (for -PI <= V < PI) + const Vec3V V2 = V3Mul(V1, V1); + const Vec3V V3 = V3Mul(V2, V1); + const Vec3V V5 = V3Mul(V3, V2); + const Vec3V V7 = V3Mul(V5, V2); + const Vec3V V9 = V3Mul(V7, V2); + const Vec3V V11 = V3Mul(V9, V2); + const Vec3V V13 = V3Mul(V11, V2); + const Vec3V V15 = V3Mul(V13, V2); + const Vec3V V17 = V3Mul(V15, V2); + const Vec3V V19 = V3Mul(V17, V2); + const Vec3V V21 = V3Mul(V19, V2); + const Vec3V V23 = V3Mul(V21, V2); + + const Vec4V sinCoefficients0 = V4LoadA(g_PXSinCoefficients0.f); + const Vec4V sinCoefficients1 = V4LoadA(g_PXSinCoefficients1.f); + const Vec4V sinCoefficients2 = V4LoadA(g_PXSinCoefficients2.f); + + const FloatV S1 = V4GetY(sinCoefficients0); + const FloatV S2 = V4GetZ(sinCoefficients0); + const FloatV S3 = V4GetW(sinCoefficients0); + const FloatV S4 = V4GetX(sinCoefficients1); + const FloatV S5 = V4GetY(sinCoefficients1); + const FloatV S6 = V4GetZ(sinCoefficients1); + const FloatV S7 = V4GetW(sinCoefficients1); + const FloatV S8 = V4GetX(sinCoefficients2); + const FloatV S9 = V4GetY(sinCoefficients2); + const FloatV S10 = V4GetZ(sinCoefficients2); + const FloatV S11 = V4GetW(sinCoefficients2); + + Vec3V Result; + Result = V4ScaleAdd(V3, S1, V1); + Result = V4ScaleAdd(V5, S2, Result); + Result = V4ScaleAdd(V7, S3, Result); + Result = V4ScaleAdd(V9, S4, Result); + Result = V4ScaleAdd(V11, S5, Result); + Result = V4ScaleAdd(V13, S6, Result); + Result = V4ScaleAdd(V15, S7, Result); + Result = V4ScaleAdd(V17, S8, Result); + Result = V4ScaleAdd(V19, S9, Result); + Result = V4ScaleAdd(V21, S10, Result); + Result = V4ScaleAdd(V23, S11, Result); + + return Result; +} + +PX_FORCE_INLINE Vec3V V3Cos(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + // Modulo the range of the given angles such that -XM_2PI <= Angles < XM_2PI + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const Vec4V twoPi = V4LoadA(g_PXTwoPi.f); + const Vec3V tmp = V4Mul(a, recipTwoPi); + const Vec3V b = V3Round(tmp); + const Vec3V V1 = V4NegMulSub(twoPi, b, a); + + // cos(V) ~= 1 - V^2 / 2! + V^4 / 4! - V^6 / 6! + V^8 / 8! - V^10 / 10! + V^12 / 12! - + // V^14 / 14! + V^16 / 16! - V^18 / 18! + V^20 / 20! - V^22 / 22! (for -PI <= V < PI) + const Vec3V V2 = V3Mul(V1, V1); + const Vec3V V4 = V3Mul(V2, V2); + const Vec3V V6 = V3Mul(V4, V2); + const Vec3V V8 = V3Mul(V4, V4); + const Vec3V V10 = V3Mul(V6, V4); + const Vec3V V12 = V3Mul(V6, V6); + const Vec3V V14 = V3Mul(V8, V6); + const Vec3V V16 = V3Mul(V8, V8); + const Vec3V V18 = V3Mul(V10, V8); + const Vec3V V20 = V3Mul(V10, V10); + const Vec3V V22 = V3Mul(V12, V10); + + const Vec4V cosCoefficients0 = V4LoadA(g_PXCosCoefficients0.f); + const Vec4V cosCoefficients1 = V4LoadA(g_PXCosCoefficients1.f); + const Vec4V cosCoefficients2 = V4LoadA(g_PXCosCoefficients2.f); + + const FloatV C1 = V4GetY(cosCoefficients0); + const FloatV C2 = V4GetZ(cosCoefficients0); + const FloatV C3 = V4GetW(cosCoefficients0); + const FloatV C4 = V4GetX(cosCoefficients1); + const FloatV C5 = V4GetY(cosCoefficients1); + const FloatV C6 = V4GetZ(cosCoefficients1); + const FloatV C7 = V4GetW(cosCoefficients1); + const FloatV C8 = V4GetX(cosCoefficients2); + const FloatV C9 = V4GetY(cosCoefficients2); + const FloatV C10 = V4GetZ(cosCoefficients2); + const FloatV C11 = V4GetW(cosCoefficients2); + + Vec3V Result; + Result = V4ScaleAdd(V2, C1, V4One()); + Result = V4ScaleAdd(V4, C2, Result); + Result = V4ScaleAdd(V6, C3, Result); + Result = V4ScaleAdd(V8, C4, Result); + Result = V4ScaleAdd(V10, C5, Result); + Result = V4ScaleAdd(V12, C6, Result); + Result = V4ScaleAdd(V14, C7, Result); + Result = V4ScaleAdd(V16, C8, Result); + Result = V4ScaleAdd(V18, C9, Result); + Result = V4ScaleAdd(V20, C10, Result); + Result = V4ScaleAdd(V22, C11, Result); + + return V4ClearW(Result); +} + +PX_FORCE_INLINE Vec3V V3PermYZZ(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + const float32x2_t xy = vget_low_f32(a); + const float32x2_t zw = vget_high_f32(a); + const float32x2_t yz = vext_f32(xy, zw, 1); + return vcombine_f32(yz, zw); +} + +PX_FORCE_INLINE Vec3V V3PermXYX(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + const uint32x2_t mask = { 0xffffFFFF, 0x0 }; + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t xw = vand_u32(xy, mask); + return vreinterpretq_f32_u32(vcombine_u32(xy, xw)); +} + +PX_FORCE_INLINE Vec3V V3PermYZX(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + const uint32x2_t mask = { 0xffffFFFF, 0x0 }; + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t zw = vget_high_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t yz = vext_u32(xy, zw, 1); + const uint32x2_t xw = vand_u32(xy, mask); + return vreinterpretq_f32_u32(vcombine_u32(yz, xw)); +} + +PX_FORCE_INLINE Vec3V V3PermZXY(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t zw = vget_high_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t wz = vrev64_u32(zw); + + const uint32x2_t zx = vext_u32(wz, xy, 1); + const uint32x2_t yw = vext_u32(xy, wz, 1); + + return vreinterpretq_f32_u32(vcombine_u32(zx, yw)); +} + +PX_FORCE_INLINE Vec3V V3PermZZY(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t zw = vget_high_u32(vreinterpretq_u32_f32(a)); + + const uint32x2_t wz = vrev64_u32(zw); + const uint32x2_t yw = vext_u32(xy, wz, 1); + const uint32x2_t zz = vdup_lane_u32(wz, 1); + + return vreinterpretq_f32_u32(vcombine_u32(zz, yw)); +} + +PX_FORCE_INLINE Vec3V V3PermYXX(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + const uint32x2_t mask = { 0xffffFFFF, 0x0 }; + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t yx = vrev64_u32(xy); + const uint32x2_t xw = vand_u32(xy, mask); + return vreinterpretq_f32_u32(vcombine_u32(yx, xw)); +} + +PX_FORCE_INLINE Vec3V V3Perm_Zero_1Z_0Y(const Vec3V v0, const Vec3V v1) +{ + ASSERT_ISVALIDVEC3V(v0); + ASSERT_ISVALIDVEC3V(v1); + + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(v0)); + const uint32x2_t zw = vget_high_u32(vreinterpretq_u32_f32(v1)); + const uint32x2_t wz = vrev64_u32(zw); + const uint32x2_t yw = vext_u32(xy, wz, 1); + + return vreinterpretq_f32_u32(vcombine_u32(wz, yw)); +} + +PX_FORCE_INLINE Vec3V V3Perm_0Z_Zero_1X(const Vec3V v0, const Vec3V v1) +{ + ASSERT_ISVALIDVEC3V(v0); + ASSERT_ISVALIDVEC3V(v1); + + const uint32x2_t mask = { 0xffffFFFF, 0x0 }; + const uint32x2_t zw = vget_high_u32(vreinterpretq_u32_f32(v0)); + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(v1)); + const uint32x2_t xw = vand_u32(xy, mask); + + return vreinterpretq_f32_u32(vcombine_u32(zw, xw)); +} + +PX_FORCE_INLINE Vec3V V3Perm_1Y_0X_Zero(const Vec3V v0, const Vec3V v1) +{ + ASSERT_ISVALIDVEC3V(v0); + ASSERT_ISVALIDVEC3V(v1); + + const uint32x2_t axy = vget_low_u32(vreinterpretq_u32_f32(v0)); + const uint32x2_t bxy = vget_low_u32(vreinterpretq_u32_f32(v1)); + const uint32x2_t byax = vext_u32(bxy, axy, 1); + const uint32x2_t ww = vdup_n_u32(0); + + return vreinterpretq_f32_u32(vcombine_u32(byax, ww)); +} + +PX_FORCE_INLINE FloatV V3SumElems(const Vec3V a) +{ + ASSERT_ISVALIDVEC3V(a); + + // const uint32x2_t mask = {0xffffFFFF, 0x0}; + + const float32x2_t low = vget_low_f32(a); + const float32x2_t high = vget_high_f32(a); + // const float32x2_t high = vreinterpret_f32_u32(vand_u32(vreinterpret_u32_f32(high_), mask)); + + const float32x2_t sumTmp = vpadd_f32(low, high); // = {0+z, x+y} + const float32x2_t sum0ZYX = vpadd_f32(sumTmp, sumTmp); // = {x+y+z, x+y+z} + + return sum0ZYX; +} + +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V min, const Vec3V max) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(min); + ASSERT_ISVALIDVEC3V(max); + + const BoolV c = BOr(V3IsGrtr(a, max), V3IsGrtr(min, a)); + return internalUnitNeonSimd::BAnyTrue3_R(c); +} + +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V min, const Vec3V max) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(min); + ASSERT_ISVALIDVEC3V(max); + + const BoolV c = BAnd(V3IsGrtrOrEq(a, min), V3IsGrtrOrEq(max, a)); + return internalUnitNeonSimd::BAllTrue4_R(c); +} + +PX_FORCE_INLINE PxU32 V3OutOfBounds(const Vec3V a, const Vec3V bounds) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(bounds); + + const BoolV greater = V3IsGrtr(V3Abs(a), bounds); + return internalUnitNeonSimd::BAnyTrue3_R(greater); +} + +PX_FORCE_INLINE PxU32 V3InBounds(const Vec3V a, const Vec3V bounds) +{ + ASSERT_ISVALIDVEC3V(a); + ASSERT_ISVALIDVEC3V(bounds); + + const BoolV greaterOrEq = V3IsGrtrOrEq(bounds, V3Abs(a)); + return internalUnitNeonSimd::BAllTrue4_R(greaterOrEq); +} + +PX_FORCE_INLINE void V3Transpose(Vec3V& col0, Vec3V& col1, Vec3V& col2) +{ + ASSERT_ISVALIDVEC3V(col0); + ASSERT_ISVALIDVEC3V(col1); + ASSERT_ISVALIDVEC3V(col2); + + Vec3V col3 = V3Zero(); + const float32x4x2_t v0v1 = vzipq_f32(col0, col2); + const float32x4x2_t v2v3 = vzipq_f32(col1, col3); + const float32x4x2_t zip0 = vzipq_f32(v0v1.val[0], v2v3.val[0]); + const float32x4x2_t zip1 = vzipq_f32(v0v1.val[1], v2v3.val[1]); + col0 = zip0.val[0]; + col1 = zip0.val[1]; + col2 = zip1.val[0]; + // col3 = zip1.val[1]; +} + +////////////////////////////////// +// VEC4V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V V4Splat(const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return vcombine_f32(f, f); +} + +PX_FORCE_INLINE Vec4V V4Merge(const FloatV* const floatVArray) +{ + ASSERT_ISVALIDFLOATV(floatVArray[0]); + ASSERT_ISVALIDFLOATV(floatVArray[1]); + ASSERT_ISVALIDFLOATV(floatVArray[2]); + ASSERT_ISVALIDFLOATV(floatVArray[3]); + + const uint32x2_t xLow = vreinterpret_u32_f32(floatVArray[0]); + const uint32x2_t yLow = vreinterpret_u32_f32(floatVArray[1]); + const uint32x2_t zLow = vreinterpret_u32_f32(floatVArray[2]); + const uint32x2_t wLow = vreinterpret_u32_f32(floatVArray[3]); + + const uint32x2_t dLow = vext_u32(xLow, yLow, 1); + const uint32x2_t dHigh = vext_u32(zLow, wLow, 1); + + return vreinterpretq_f32_u32(vcombine_u32(dLow, dHigh)); +} + +PX_FORCE_INLINE Vec4V V4Merge(const FloatVArg x, const FloatVArg y, const FloatVArg z, const FloatVArg w) +{ + ASSERT_ISVALIDFLOATV(x); + ASSERT_ISVALIDFLOATV(y); + ASSERT_ISVALIDFLOATV(z); + ASSERT_ISVALIDFLOATV(w); + + const uint32x2_t xLow = vreinterpret_u32_f32(x); + const uint32x2_t yLow = vreinterpret_u32_f32(y); + const uint32x2_t zLow = vreinterpret_u32_f32(z); + const uint32x2_t wLow = vreinterpret_u32_f32(w); + + const uint32x2_t dLow = vext_u32(xLow, yLow, 1); + const uint32x2_t dHigh = vext_u32(zLow, wLow, 1); + + return vreinterpretq_f32_u32(vcombine_u32(dLow, dHigh)); +} + +PX_FORCE_INLINE Vec4V V4MergeW(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const float32x2_t xx = vget_high_f32(x); + const float32x2_t yy = vget_high_f32(y); + const float32x2_t zz = vget_high_f32(z); + const float32x2_t ww = vget_high_f32(w); + + const float32x2x2_t zipL = vzip_f32(xx, yy); + const float32x2x2_t zipH = vzip_f32(zz, ww); + + return vcombine_f32(zipL.val[1], zipH.val[1]); +} + +PX_FORCE_INLINE Vec4V V4MergeZ(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const float32x2_t xx = vget_high_f32(x); + const float32x2_t yy = vget_high_f32(y); + const float32x2_t zz = vget_high_f32(z); + const float32x2_t ww = vget_high_f32(w); + + const float32x2x2_t zipL = vzip_f32(xx, yy); + const float32x2x2_t zipH = vzip_f32(zz, ww); + + return vcombine_f32(zipL.val[0], zipH.val[0]); +} + +PX_FORCE_INLINE Vec4V V4MergeY(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const float32x2_t xx = vget_low_f32(x); + const float32x2_t yy = vget_low_f32(y); + const float32x2_t zz = vget_low_f32(z); + const float32x2_t ww = vget_low_f32(w); + + const float32x2x2_t zipL = vzip_f32(xx, yy); + const float32x2x2_t zipH = vzip_f32(zz, ww); + + return vcombine_f32(zipL.val[1], zipH.val[1]); +} + +PX_FORCE_INLINE Vec4V V4MergeX(const Vec4VArg x, const Vec4VArg y, const Vec4VArg z, const Vec4VArg w) +{ + const float32x2_t xx = vget_low_f32(x); + const float32x2_t yy = vget_low_f32(y); + const float32x2_t zz = vget_low_f32(z); + const float32x2_t ww = vget_low_f32(w); + + const float32x2x2_t zipL = vzip_f32(xx, yy); + const float32x2x2_t zipH = vzip_f32(zz, ww); + + return vcombine_f32(zipL.val[0], zipH.val[0]); +} + +PX_FORCE_INLINE Vec4V V4UnpackXY(const Vec4VArg a, const Vec4VArg b) +{ + return vzipq_f32(a, b).val[0]; +} + +PX_FORCE_INLINE Vec4V V4UnpackZW(const Vec4VArg a, const Vec4VArg b) +{ + return vzipq_f32(a, b).val[1]; +} + +PX_FORCE_INLINE Vec4V V4UnitW() +{ + const float32x2_t zeros = vreinterpret_f32_u32(vmov_n_u32(0)); + const float32x2_t ones = vmov_n_f32(1.0f); + const float32x2_t zo = vext_f32(zeros, ones, 1); + return vcombine_f32(zeros, zo); +} + +PX_FORCE_INLINE Vec4V V4UnitX() +{ + const float32x2_t zeros = vreinterpret_f32_u32(vmov_n_u32(0)); + const float32x2_t ones = vmov_n_f32(1.0f); + const float32x2_t oz = vext_f32(ones, zeros, 1); + return vcombine_f32(oz, zeros); +} + +PX_FORCE_INLINE Vec4V V4UnitY() +{ + const float32x2_t zeros = vreinterpret_f32_u32(vmov_n_u32(0)); + const float32x2_t ones = vmov_n_f32(1.0f); + const float32x2_t zo = vext_f32(zeros, ones, 1); + return vcombine_f32(zo, zeros); +} + +PX_FORCE_INLINE Vec4V V4UnitZ() +{ + const float32x2_t zeros = vreinterpret_f32_u32(vmov_n_u32(0)); + const float32x2_t ones = vmov_n_f32(1.0f); + const float32x2_t oz = vext_f32(ones, zeros, 1); + return vcombine_f32(zeros, oz); +} + +PX_FORCE_INLINE FloatV V4GetW(const Vec4V f) +{ + const float32x2_t fhigh = vget_high_f32(f); + return vdup_lane_f32(fhigh, 1); +} + +PX_FORCE_INLINE FloatV V4GetX(const Vec4V f) +{ + const float32x2_t fLow = vget_low_f32(f); + return vdup_lane_f32(fLow, 0); +} + +PX_FORCE_INLINE FloatV V4GetY(const Vec4V f) +{ + const float32x2_t fLow = vget_low_f32(f); + return vdup_lane_f32(fLow, 1); +} + +PX_FORCE_INLINE FloatV V4GetZ(const Vec4V f) +{ + const float32x2_t fhigh = vget_high_f32(f); + return vdup_lane_f32(fhigh, 0); +} + +PX_FORCE_INLINE Vec4V V4SetW(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTTTF(), v, vcombine_f32(f, f)); +} + +PX_FORCE_INLINE Vec4V V4SetX(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BFTTT(), v, vcombine_f32(f, f)); +} + +PX_FORCE_INLINE Vec4V V4SetY(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTFTT(), v, vcombine_f32(f, f)); +} + +PX_FORCE_INLINE Vec4V V4SetZ(const Vec4V v, const FloatV f) +{ + ASSERT_ISVALIDFLOATV(f); + return V4Sel(BTTFT(), v, vcombine_f32(f, f)); +} + +PX_FORCE_INLINE Vec4V V4ClearW(const Vec4V v) +{ + return V4Sel(BTTTF(), v, V4Zero()); +} + +PX_FORCE_INLINE Vec4V V4PermYXWZ(const Vec4V a) +{ + const float32x2_t xy = vget_low_f32(a); + const float32x2_t zw = vget_high_f32(a); + const float32x2_t yx = vext_f32(xy, xy, 1); + const float32x2_t wz = vext_f32(zw, zw, 1); + return vcombine_f32(yx, wz); +} + +PX_FORCE_INLINE Vec4V V4PermXZXZ(const Vec4V a) +{ + const float32x2_t xy = vget_low_f32(a); + const float32x2_t zw = vget_high_f32(a); + const float32x2x2_t xzyw = vzip_f32(xy, zw); + return vcombine_f32(xzyw.val[0], xzyw.val[0]); +} + +PX_FORCE_INLINE Vec4V V4PermYWYW(const Vec4V a) +{ + const float32x2_t xy = vget_low_f32(a); + const float32x2_t zw = vget_high_f32(a); + const float32x2x2_t xzyw = vzip_f32(xy, zw); + return vcombine_f32(xzyw.val[1], xzyw.val[1]); +} + +PX_FORCE_INLINE Vec4V V4PermYZXW(const Vec4V a) +{ + const uint32x2_t xy = vget_low_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t zw = vget_high_u32(vreinterpretq_u32_f32(a)); + const uint32x2_t yz = vext_u32(xy, zw, 1); + const uint32x2_t xw = vrev64_u32(vext_u32(zw, xy, 1)); + return vreinterpretq_f32_u32(vcombine_u32(yz, xw)); +} + +PX_FORCE_INLINE Vec4V V4PermZWXY(const Vec4V a) +{ + const float32x2_t low = vget_low_f32(a); + const float32x2_t high = vget_high_f32(a); + return vcombine_f32(high, low); +} + +template +PX_FORCE_INLINE Vec4V V4Perm(const Vec4V V) +{ + static const uint32_t ControlElement[4] = + { +#if 1 + 0x03020100, // XM_SWIZZLE_X + 0x07060504, // XM_SWIZZLE_Y + 0x0B0A0908, // XM_SWIZZLE_Z + 0x0F0E0D0C, // XM_SWIZZLE_W +#else + 0x00010203, // XM_SWIZZLE_X + 0x04050607, // XM_SWIZZLE_Y + 0x08090A0B, // XM_SWIZZLE_Z + 0x0C0D0E0F, // XM_SWIZZLE_W +#endif + }; + + uint8x8x2_t tbl; + tbl.val[0] = vreinterpret_u8_f32(vget_low_f32(V)); + tbl.val[1] = vreinterpret_u8_f32(vget_high_f32(V)); + + uint8x8_t idx = + vcreate_u8(static_cast(ControlElement[E0]) | (static_cast(ControlElement[E1]) << 32)); + const uint8x8_t rL = vtbl2_u8(tbl, idx); + idx = vcreate_u8(static_cast(ControlElement[E2]) | (static_cast(ControlElement[E3]) << 32)); + const uint8x8_t rH = vtbl2_u8(tbl, idx); + return vreinterpretq_f32_u8(vcombine_u8(rL, rH)); +} + +// PT: this seems measurably slower than the hardcoded version +/*PX_FORCE_INLINE Vec4V V4PermYZXW(const Vec4V a) +{ + return V4Perm<1, 2, 0, 3>(a); +}*/ + +PX_FORCE_INLINE Vec4V V4Zero() +{ + return vreinterpretq_f32_u32(vmovq_n_u32(0)); + // return vmovq_n_f32(0.0f); +} + +PX_FORCE_INLINE Vec4V V4One() +{ + return vmovq_n_f32(1.0f); +} + +PX_FORCE_INLINE Vec4V V4Eps() +{ + // return vmovq_n_f32(PX_EPS_REAL); + return V4Load(PX_EPS_REAL); +} + +PX_FORCE_INLINE Vec4V V4Neg(const Vec4V f) +{ + return vnegq_f32(f); +} + +PX_FORCE_INLINE Vec4V V4Add(const Vec4V a, const Vec4V b) +{ + return vaddq_f32(a, b); +} + +PX_FORCE_INLINE Vec4V V4Sub(const Vec4V a, const Vec4V b) +{ + return vsubq_f32(a, b); +} + +PX_FORCE_INLINE Vec4V V4Scale(const Vec4V a, const FloatV b) +{ + return vmulq_lane_f32(a, b, 0); +} + +PX_FORCE_INLINE Vec4V V4Mul(const Vec4V a, const Vec4V b) +{ + return vmulq_f32(a, b); +} + +PX_FORCE_INLINE Vec4V V4ScaleInv(const Vec4V a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(b); + const float32x2_t invB = VRECIP(b); + return vmulq_lane_f32(a, invB, 0); +} + +PX_FORCE_INLINE Vec4V V4Div(const Vec4V a, const Vec4V b) +{ + const float32x4_t invB = VRECIPQ(b); + return vmulq_f32(a, invB); +} + +PX_FORCE_INLINE Vec4V V4ScaleInvFast(const Vec4V a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(b); + const float32x2_t invB = VRECIPE(b); + return vmulq_lane_f32(a, invB, 0); +} + +PX_FORCE_INLINE Vec4V V4DivFast(const Vec4V a, const Vec4V b) +{ + const float32x4_t invB = VRECIPEQ(b); + return vmulq_f32(a, invB); +} + +PX_FORCE_INLINE Vec4V V4Recip(const Vec4V a) +{ + return VRECIPQ(a); +} + +PX_FORCE_INLINE Vec4V V4RecipFast(const Vec4V a) +{ + return VRECIPEQ(a); +} + +PX_FORCE_INLINE Vec4V V4Rsqrt(const Vec4V a) +{ + return VRECIPSQRTQ(a); +} + +PX_FORCE_INLINE Vec4V V4RsqrtFast(const Vec4V a) +{ + return VRECIPSQRTEQ(a); +} + +PX_FORCE_INLINE Vec4V V4Sqrt(const Vec4V a) +{ + return V4Sel(V4IsEq(a, V4Zero()), a, V4Mul(a, VRECIPSQRTQ(a))); +} + +PX_FORCE_INLINE Vec4V V4ScaleAdd(const Vec4V a, const FloatV b, const Vec4V c) +{ + ASSERT_ISVALIDFLOATV(b); + return vmlaq_lane_f32(c, a, b, 0); +} + +PX_FORCE_INLINE Vec4V V4NegScaleSub(const Vec4V a, const FloatV b, const Vec4V c) +{ + ASSERT_ISVALIDFLOATV(b); + return vmlsq_lane_f32(c, a, b, 0); +} + +PX_FORCE_INLINE Vec4V V4MulAdd(const Vec4V a, const Vec4V b, const Vec4V c) +{ + return vmlaq_f32(c, a, b); +} + +PX_FORCE_INLINE Vec4V V4NegMulSub(const Vec4V a, const Vec4V b, const Vec4V c) +{ + return vmlsq_f32(c, a, b); +} + +PX_FORCE_INLINE Vec4V V4Abs(const Vec4V a) +{ + return vabsq_f32(a); +} + +PX_FORCE_INLINE FloatV V4SumElements(const Vec4V a) +{ + const Vec4V xy = V4UnpackXY(a, a); // x,x,y,y + const Vec4V zw = V4UnpackZW(a, a); // z,z,w,w + const Vec4V xz_yw = V4Add(xy, zw); // x+z,x+z,y+w,y+w + const FloatV xz = V4GetX(xz_yw); // x+z + const FloatV yw = V4GetZ(xz_yw); // y+w + return FAdd(xz, yw); // sum +} + +PX_FORCE_INLINE FloatV V4Dot(const Vec4V a, const Vec4V b) +{ + const float32x4_t tmp = vmulq_f32(a, b); + const float32x2_t low = vget_low_f32(tmp); + const float32x2_t high = vget_high_f32(tmp); + + const float32x2_t sumTmp = vpadd_f32(low, high); // = {z+w, x+y} + const float32x2_t sumWZYX = vpadd_f32(sumTmp, sumTmp); // = {x+y+z+w, x+y+z+w} + return sumWZYX; +} + +PX_FORCE_INLINE FloatV V4Dot3(const Vec4V aa, const Vec4V bb) +{ + // PT: the V3Dot code relies on the fact that W=0 so we can't reuse it as-is, we need to clear W first. + // TODO: find a better implementation that does not need to clear W. + const Vec4V a = V4ClearW(aa); + const Vec4V b = V4ClearW(bb); + + const float32x4_t tmp = vmulq_f32(a, b); + const float32x2_t low = vget_low_f32(tmp); + const float32x2_t high = vget_high_f32(tmp); + + const float32x2_t sumTmp = vpadd_f32(low, high); // = {0+z, x+y} + const float32x2_t sum0ZYX = vpadd_f32(sumTmp, sumTmp); // = {x+y+z, x+y+z} + return sum0ZYX; +} + +PX_FORCE_INLINE Vec4V V4Cross(const Vec4V a, const Vec4V b) +{ + const uint32x2_t TF = { 0xffffFFFF, 0x0 }; + const float32x2_t ay_ax = vget_low_f32(a); // d2 + const float32x2_t aw_az = vget_high_f32(a); // d3 + const float32x2_t by_bx = vget_low_f32(b); // d4 + const float32x2_t bw_bz = vget_high_f32(b); // d5 + // Hi, Lo + const float32x2_t bz_by = vext_f32(by_bx, bw_bz, 1); // bz, by + const float32x2_t az_ay = vext_f32(ay_ax, aw_az, 1); // az, ay + + const float32x2_t azbx = vmul_f32(aw_az, by_bx); // 0, az*bx + const float32x2_t aybz_axby = vmul_f32(ay_ax, bz_by); // ay*bz, ax*by + + const float32x2_t azbxSUBaxbz = vmls_f32(azbx, bw_bz, ay_ax); // 0, az*bx-ax*bz + const float32x2_t aybzSUBazby_axbySUBaybx = vmls_f32(aybz_axby, by_bx, az_ay); // ay*bz-az*by, ax*by-ay*bx + + const float32x2_t retLow = vext_f32(aybzSUBazby_axbySUBaybx, azbxSUBaxbz, 1); // az*bx-ax*bz, ay*bz-az*by + const uint32x2_t retHigh = vand_u32(TF, vreinterpret_u32_f32(aybzSUBazby_axbySUBaybx)); // 0, ax*by-ay*bx + + return vcombine_f32(retLow, vreinterpret_f32_u32(retHigh)); +} + +PX_FORCE_INLINE FloatV V4Length(const Vec4V a) +{ + const float32x4_t tmp = vmulq_f32(a, a); + const float32x2_t low = vget_low_f32(tmp); + const float32x2_t high = vget_high_f32(tmp); + + const float32x2_t sumTmp = vpadd_f32(low, high); // = {0+z, x+y} + const float32x2_t sumWZYX = vpadd_f32(sumTmp, sumTmp); // = {x+y+z, x+y+z} + return FSqrt(sumWZYX); +} + +PX_FORCE_INLINE FloatV V4LengthSq(const Vec4V a) +{ + return V4Dot(a, a); +} + +PX_FORCE_INLINE Vec4V V4Normalize(const Vec4V a) +{ + //PX_ASSERT(!FAllEq(V4LengthSq(a), FZero())); + return V4ScaleInv(a, V4Length(a)); +} + +PX_FORCE_INLINE Vec4V V4NormalizeFast(const Vec4V a) +{ + //PX_ASSERT(!FAllEq(V4LengthSq(a), FZero())); + return V4Scale(a, FRsqrtFast(V4Dot(a, a))); +} + +PX_FORCE_INLINE Vec4V V4NormalizeSafe(const Vec4V a, const Vec4V unsafeReturnValue) +{ + const FloatV zero = FZero(); + const FloatV length = V4Length(a); + const uint32x4_t isGreaterThanZero = FIsGrtr(length, zero); + return V4Sel(isGreaterThanZero, V4ScaleInv(a, length), unsafeReturnValue); +} + +PX_FORCE_INLINE BoolV V4IsEqU32(const VecU32V a, const VecU32V b) +{ + return vceqq_u32(a, b); +} + +PX_FORCE_INLINE Vec4V V4Sel(const BoolV c, const Vec4V a, const Vec4V b) +{ + return vbslq_f32(c, a, b); +} + +PX_FORCE_INLINE BoolV V4IsGrtr(const Vec4V a, const Vec4V b) +{ + return vcgtq_f32(a, b); +} + +PX_FORCE_INLINE BoolV V4IsGrtrOrEq(const Vec4V a, const Vec4V b) +{ + return vcgeq_f32(a, b); +} + +PX_FORCE_INLINE BoolV V4IsEq(const Vec4V a, const Vec4V b) +{ + return vceqq_f32(a, b); +} + +PX_FORCE_INLINE Vec4V V4Max(const Vec4V a, const Vec4V b) +{ + return vmaxq_f32(a, b); +} + +PX_FORCE_INLINE Vec4V V4Min(const Vec4V a, const Vec4V b) +{ + return vminq_f32(a, b); +} + +PX_FORCE_INLINE FloatV V4ExtractMax(const Vec4V a) +{ + const float32x2_t low = vget_low_f32(a); + const float32x2_t high = vget_high_f32(a); + + const float32x2_t max0 = vpmax_f32(high, low); + const float32x2_t max1 = vpmax_f32(max0, max0); + + return max1; +} + +PX_FORCE_INLINE FloatV V4ExtractMin(const Vec4V a) +{ + const float32x2_t low = vget_low_f32(a); + const float32x2_t high = vget_high_f32(a); + + const float32x2_t min0 = vpmin_f32(high, low); + const float32x2_t min1 = vpmin_f32(min0, min0); + + return min1; +} + +PX_FORCE_INLINE Vec4V V4Clamp(const Vec4V a, const Vec4V minV, const Vec4V maxV) +{ + return V4Max(V4Min(a, maxV), minV); +} + +PX_FORCE_INLINE PxU32 V4AllGrtr(const Vec4V a, const Vec4V b) +{ + return internalUnitNeonSimd::BAllTrue4_R(V4IsGrtr(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq(const Vec4V a, const Vec4V b) +{ + return internalUnitNeonSimd::BAllTrue4_R(V4IsGrtrOrEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AllGrtrOrEq3(const Vec4V a, const Vec4V b) +{ + return internalUnitNeonSimd::BAllTrue3_R(V4IsGrtrOrEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AllEq(const Vec4V a, const Vec4V b) +{ + return internalUnitNeonSimd::BAllTrue4_R(V4IsEq(a, b)); +} + +PX_FORCE_INLINE PxU32 V4AnyGrtr3(const Vec4V a, const Vec4V b) +{ + return internalUnitNeonSimd::BAnyTrue3_R(V4IsGrtr(a, b)); +} + +PX_FORCE_INLINE Vec4V V4Round(const Vec4V a) +{ + // truncate(a + (0.5f - sign(a))) + const Vec4V half = V4Load(0.5f); + const float32x4_t sign = vcvtq_f32_u32((vshrq_n_u32(vreinterpretq_u32_f32(a), 31))); + const Vec4V aPlusHalf = V4Add(a, half); + const Vec4V aRound = V4Sub(aPlusHalf, sign); + return vcvtq_f32_s32(vcvtq_s32_f32(aRound)); +} + +PX_FORCE_INLINE Vec4V V4Sin(const Vec4V a) +{ + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const Vec4V twoPi = V4LoadA(g_PXTwoPi.f); + const Vec4V tmp = V4Mul(a, recipTwoPi); + const Vec4V b = V4Round(tmp); + const Vec4V V1 = V4NegMulSub(twoPi, b, a); + + // sin(V) ~= V - V^3 / 3! + V^5 / 5! - V^7 / 7! + V^9 / 9! - V^11 / 11! + V^13 / 13! - + // V^15 / 15! + V^17 / 17! - V^19 / 19! + V^21 / 21! - V^23 / 23! (for -PI <= V < PI) + const Vec4V V2 = V4Mul(V1, V1); + const Vec4V V3 = V4Mul(V2, V1); + const Vec4V V5 = V4Mul(V3, V2); + const Vec4V V7 = V4Mul(V5, V2); + const Vec4V V9 = V4Mul(V7, V2); + const Vec4V V11 = V4Mul(V9, V2); + const Vec4V V13 = V4Mul(V11, V2); + const Vec4V V15 = V4Mul(V13, V2); + const Vec4V V17 = V4Mul(V15, V2); + const Vec4V V19 = V4Mul(V17, V2); + const Vec4V V21 = V4Mul(V19, V2); + const Vec4V V23 = V4Mul(V21, V2); + + const Vec4V sinCoefficients0 = V4LoadA(g_PXSinCoefficients0.f); + const Vec4V sinCoefficients1 = V4LoadA(g_PXSinCoefficients1.f); + const Vec4V sinCoefficients2 = V4LoadA(g_PXSinCoefficients2.f); + + const FloatV S1 = V4GetY(sinCoefficients0); + const FloatV S2 = V4GetZ(sinCoefficients0); + const FloatV S3 = V4GetW(sinCoefficients0); + const FloatV S4 = V4GetX(sinCoefficients1); + const FloatV S5 = V4GetY(sinCoefficients1); + const FloatV S6 = V4GetZ(sinCoefficients1); + const FloatV S7 = V4GetW(sinCoefficients1); + const FloatV S8 = V4GetX(sinCoefficients2); + const FloatV S9 = V4GetY(sinCoefficients2); + const FloatV S10 = V4GetZ(sinCoefficients2); + const FloatV S11 = V4GetW(sinCoefficients2); + + Vec4V Result; + Result = V4ScaleAdd(V3, S1, V1); + Result = V4ScaleAdd(V5, S2, Result); + Result = V4ScaleAdd(V7, S3, Result); + Result = V4ScaleAdd(V9, S4, Result); + Result = V4ScaleAdd(V11, S5, Result); + Result = V4ScaleAdd(V13, S6, Result); + Result = V4ScaleAdd(V15, S7, Result); + Result = V4ScaleAdd(V17, S8, Result); + Result = V4ScaleAdd(V19, S9, Result); + Result = V4ScaleAdd(V21, S10, Result); + Result = V4ScaleAdd(V23, S11, Result); + + return Result; +} + +PX_FORCE_INLINE Vec4V V4Cos(const Vec4V a) +{ + const Vec4V recipTwoPi = V4LoadA(g_PXReciprocalTwoPi.f); + const Vec4V twoPi = V4LoadA(g_PXTwoPi.f); + const Vec4V tmp = V4Mul(a, recipTwoPi); + const Vec4V b = V4Round(tmp); + const Vec4V V1 = V4NegMulSub(twoPi, b, a); + + // cos(V) ~= 1 - V^2 / 2! + V^4 / 4! - V^6 / 6! + V^8 / 8! - V^10 / 10! + V^12 / 12! - + // V^14 / 14! + V^16 / 16! - V^18 / 18! + V^20 / 20! - V^22 / 22! (for -PI <= V < PI) + const Vec4V V2 = V4Mul(V1, V1); + const Vec4V V4 = V4Mul(V2, V2); + const Vec4V V6 = V4Mul(V4, V2); + const Vec4V V8 = V4Mul(V4, V4); + const Vec4V V10 = V4Mul(V6, V4); + const Vec4V V12 = V4Mul(V6, V6); + const Vec4V V14 = V4Mul(V8, V6); + const Vec4V V16 = V4Mul(V8, V8); + const Vec4V V18 = V4Mul(V10, V8); + const Vec4V V20 = V4Mul(V10, V10); + const Vec4V V22 = V4Mul(V12, V10); + + const Vec4V cosCoefficients0 = V4LoadA(g_PXCosCoefficients0.f); + const Vec4V cosCoefficients1 = V4LoadA(g_PXCosCoefficients1.f); + const Vec4V cosCoefficients2 = V4LoadA(g_PXCosCoefficients2.f); + + const FloatV C1 = V4GetY(cosCoefficients0); + const FloatV C2 = V4GetZ(cosCoefficients0); + const FloatV C3 = V4GetW(cosCoefficients0); + const FloatV C4 = V4GetX(cosCoefficients1); + const FloatV C5 = V4GetY(cosCoefficients1); + const FloatV C6 = V4GetZ(cosCoefficients1); + const FloatV C7 = V4GetW(cosCoefficients1); + const FloatV C8 = V4GetX(cosCoefficients2); + const FloatV C9 = V4GetY(cosCoefficients2); + const FloatV C10 = V4GetZ(cosCoefficients2); + const FloatV C11 = V4GetW(cosCoefficients2); + + Vec4V Result; + Result = V4ScaleAdd(V2, C1, V4One()); + Result = V4ScaleAdd(V4, C2, Result); + Result = V4ScaleAdd(V6, C3, Result); + Result = V4ScaleAdd(V8, C4, Result); + Result = V4ScaleAdd(V10, C5, Result); + Result = V4ScaleAdd(V12, C6, Result); + Result = V4ScaleAdd(V14, C7, Result); + Result = V4ScaleAdd(V16, C8, Result); + Result = V4ScaleAdd(V18, C9, Result); + Result = V4ScaleAdd(V20, C10, Result); + Result = V4ScaleAdd(V22, C11, Result); + + return Result; +} + +PX_FORCE_INLINE void V4Transpose(Vec4V& col0, Vec4V& col1, Vec4V& col2, Vec4V& col3) +{ + const float32x4x2_t v0v1 = vzipq_f32(col0, col2); + const float32x4x2_t v2v3 = vzipq_f32(col1, col3); + const float32x4x2_t zip0 = vzipq_f32(v0v1.val[0], v2v3.val[0]); + const float32x4x2_t zip1 = vzipq_f32(v0v1.val[1], v2v3.val[1]); + col0 = zip0.val[0]; + col1 = zip0.val[1]; + col2 = zip1.val[0]; + col3 = zip1.val[1]; +} + +////////////////////////////////// +// VEC4V +////////////////////////////////// + +PX_FORCE_INLINE BoolV BFFFF() +{ + return vmovq_n_u32(0); +} + +PX_FORCE_INLINE BoolV BFFFT() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t zo = vext_u32(zeros, ones, 1); + return vcombine_u32(zeros, zo); +} + +PX_FORCE_INLINE BoolV BFFTF() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t oz = vext_u32(ones, zeros, 1); + return vcombine_u32(zeros, oz); +} + +PX_FORCE_INLINE BoolV BFFTT() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + return vcombine_u32(zeros, ones); +} + +PX_FORCE_INLINE BoolV BFTFF() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t zo = vext_u32(zeros, ones, 1); + return vcombine_u32(zo, zeros); +} + +PX_FORCE_INLINE BoolV BFTFT() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t zo = vext_u32(zeros, ones, 1); + return vcombine_u32(zo, zo); +} + +PX_FORCE_INLINE BoolV BFTTF() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t zo = vext_u32(zeros, ones, 1); + const uint32x2_t oz = vext_u32(ones, zeros, 1); + return vcombine_u32(zo, oz); +} + +PX_FORCE_INLINE BoolV BFTTT() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t zo = vext_u32(zeros, ones, 1); + return vcombine_u32(zo, ones); +} + +PX_FORCE_INLINE BoolV BTFFF() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + // const uint32x2_t zo = vext_u32(zeros, ones, 1); + const uint32x2_t oz = vext_u32(ones, zeros, 1); + return vcombine_u32(oz, zeros); +} + +PX_FORCE_INLINE BoolV BTFFT() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t zo = vext_u32(zeros, ones, 1); + const uint32x2_t oz = vext_u32(ones, zeros, 1); + return vcombine_u32(oz, zo); +} + +PX_FORCE_INLINE BoolV BTFTF() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t oz = vext_u32(ones, zeros, 1); + return vcombine_u32(oz, oz); +} + +PX_FORCE_INLINE BoolV BTFTT() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t oz = vext_u32(ones, zeros, 1); + return vcombine_u32(oz, ones); +} + +PX_FORCE_INLINE BoolV BTTFF() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + return vcombine_u32(ones, zeros); +} + +PX_FORCE_INLINE BoolV BTTFT() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t zo = vext_u32(zeros, ones, 1); + return vcombine_u32(ones, zo); +} + +PX_FORCE_INLINE BoolV BTTTF() +{ + const uint32x2_t zeros = vmov_n_u32(0); + const uint32x2_t ones = vmov_n_u32(0xffffFFFF); + const uint32x2_t oz = vext_u32(ones, zeros, 1); + return vcombine_u32(ones, oz); +} + +PX_FORCE_INLINE BoolV BTTTT() +{ + return vmovq_n_u32(0xffffFFFF); +} + +PX_FORCE_INLINE BoolV BXMask() +{ + return BTFFF(); +} + +PX_FORCE_INLINE BoolV BYMask() +{ + return BFTFF(); +} + +PX_FORCE_INLINE BoolV BZMask() +{ + return BFFTF(); +} + +PX_FORCE_INLINE BoolV BWMask() +{ + return BFFFT(); +} + +PX_FORCE_INLINE BoolV BGetX(const BoolV f) +{ + const uint32x2_t fLow = vget_low_u32(f); + return vdupq_lane_u32(fLow, 0); +} + +PX_FORCE_INLINE BoolV BGetY(const BoolV f) +{ + const uint32x2_t fLow = vget_low_u32(f); + return vdupq_lane_u32(fLow, 1); +} + +PX_FORCE_INLINE BoolV BGetZ(const BoolV f) +{ + const uint32x2_t fHigh = vget_high_u32(f); + return vdupq_lane_u32(fHigh, 0); +} + +PX_FORCE_INLINE BoolV BGetW(const BoolV f) +{ + const uint32x2_t fHigh = vget_high_u32(f); + return vdupq_lane_u32(fHigh, 1); +} + +PX_FORCE_INLINE BoolV BSetX(const BoolV v, const BoolV f) +{ + return vbslq_u32(BFTTT(), v, f); +} + +PX_FORCE_INLINE BoolV BSetY(const BoolV v, const BoolV f) +{ + return vbslq_u32(BTFTT(), v, f); +} + +PX_FORCE_INLINE BoolV BSetZ(const BoolV v, const BoolV f) +{ + return vbslq_u32(BTTFT(), v, f); +} + +PX_FORCE_INLINE BoolV BSetW(const BoolV v, const BoolV f) +{ + return vbslq_u32(BTTTF(), v, f); +} + +PX_FORCE_INLINE BoolV BAnd(const BoolV a, const BoolV b) +{ + return vandq_u32(a, b); +} + +PX_FORCE_INLINE BoolV BNot(const BoolV a) +{ + return vmvnq_u32(a); +} + +PX_FORCE_INLINE BoolV BAndNot(const BoolV a, const BoolV b) +{ + // return vbicq_u32(a, b); + return vandq_u32(a, vmvnq_u32(b)); +} + +PX_FORCE_INLINE BoolV BOr(const BoolV a, const BoolV b) +{ + return vorrq_u32(a, b); +} + +PX_FORCE_INLINE BoolV BAllTrue4(const BoolV a) +{ + const uint32x2_t allTrue = vmov_n_u32(0xffffFFFF); + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + const uint32x2_t result = vceq_u32(finalReduce, allTrue); + return vdupq_lane_u32(result, 0); +} + +PX_FORCE_INLINE BoolV BAnyTrue4(const BoolV a) +{ + const uint32x2_t allTrue = vmov_n_u32(0xffffFFFF); + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + const uint32x2_t result = vtst_u32(finalReduce, allTrue); + return vdupq_lane_u32(result, 0); +} + +PX_FORCE_INLINE BoolV BAllTrue3(const BoolV a) +{ + const uint32x2_t allTrue3 = vmov_n_u32(0x00ffFFFF); + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + const uint32x2_t result = vceq_u32(vand_u32(finalReduce, allTrue3), allTrue3); + return vdupq_lane_u32(result, 0); +} + +PX_FORCE_INLINE BoolV BAnyTrue3(const BoolV a) +{ + const uint32x2_t allTrue3 = vmov_n_u32(0x00ffFFFF); + const uint16x4_t dHigh = vget_high_u16(vreinterpretq_u16_u32(a)); + const uint16x4_t dLow = vmovn_u32(a); + uint16x8_t combined = vcombine_u16(dLow, dHigh); + const uint32x2_t finalReduce = vreinterpret_u32_u8(vmovn_u16(combined)); + const uint32x2_t result = vtst_u32(vand_u32(finalReduce, allTrue3), allTrue3); + return vdupq_lane_u32(result, 0); +} + +PX_FORCE_INLINE PxU32 BAllEq(const BoolV a, const BoolV b) +{ + const BoolV bTest = vceqq_u32(a, b); + return internalUnitNeonSimd::BAllTrue4_R(bTest); +} + +PX_FORCE_INLINE PxU32 BAllEqTTTT(const BoolV a) +{ + return BAllEq(a, BTTTT()); +} + +PX_FORCE_INLINE PxU32 BAllEqFFFF(const BoolV a) +{ + return BAllEq(a, BFFFF()); +} + +PX_FORCE_INLINE PxU32 BGetBitMask(const BoolV a) +{ + static PX_ALIGN(16, const PxU32) bitMaskData[4] = { 1, 2, 4, 8 }; + const uint32x4_t bitMask = *(reinterpret_cast(bitMaskData)); + const uint32x4_t t0 = vandq_u32(a, bitMask); + const uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); // Pairwise add (0 + 1), (2 + 3) + return PxU32(vget_lane_u32(vpadd_u32(t1, t1), 0)); +} + +////////////////////////////////// +// MAT33V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M33MulV3(const Mat33V& a, const Vec3V b) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + const Vec3V v0 = V3Scale(a.col0, x); + const Vec3V v1 = V3Scale(a.col1, y); + const Vec3V v2 = V3Scale(a.col2, z); + const Vec3V v0PlusV1 = V3Add(v0, v1); + return V3Add(v0PlusV1, v2); +} + +PX_FORCE_INLINE Vec3V M33TrnspsMulV3(const Mat33V& a, const Vec3V b) +{ + const FloatV x = V3Dot(a.col0, b); + const FloatV y = V3Dot(a.col1, b); + const FloatV z = V3Dot(a.col2, b); + return V3Merge(x, y, z); +} + +PX_FORCE_INLINE Vec3V M33MulV3AddV3(const Mat33V& A, const Vec3V b, const Vec3V c) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + Vec3V result = V3ScaleAdd(A.col0, x, c); + result = V3ScaleAdd(A.col1, y, result); + return V3ScaleAdd(A.col2, z, result); +} + +PX_FORCE_INLINE Mat33V M33MulM33(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(M33MulV3(a, b.col0), M33MulV3(a, b.col1), M33MulV3(a, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Add(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(V3Add(a.col0, b.col0), V3Add(a.col1, b.col1), V3Add(a.col2, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Scale(const Mat33V& a, const FloatV& b) +{ + return Mat33V(V3Scale(a.col0, b), V3Scale(a.col1, b), V3Scale(a.col2, b)); +} + +PX_FORCE_INLINE Mat33V M33Inverse(const Mat33V& a) +{ + const float32x2_t zeros = vreinterpret_f32_u32(vmov_n_u32(0)); + const BoolV btttf = BTTTF(); + + const Vec3V cross01 = V3Cross(a.col0, a.col1); + const Vec3V cross12 = V3Cross(a.col1, a.col2); + const Vec3V cross20 = V3Cross(a.col2, a.col0); + const FloatV dot = V3Dot(cross01, a.col2); + const FloatV invDet = FRecipFast(dot); + + const float32x4x2_t merge = vzipq_f32(cross12, cross01); + const float32x4_t mergeh = merge.val[0]; + const float32x4_t mergel = merge.val[1]; + + // const Vec3V colInv0 = XMVectorPermute(mergeh,cross20,PxPermuteControl(0,4,1,7)); + const float32x4_t colInv0_xxyy = vzipq_f32(mergeh, cross20).val[0]; + const float32x4_t colInv0 = vreinterpretq_f32_u32(vandq_u32(vreinterpretq_u32_f32(colInv0_xxyy), btttf)); + + // const Vec3V colInv1 = XMVectorPermute(mergeh,cross20,PxPermuteControl(2,5,3,7)); + const float32x2_t zw0 = vget_high_f32(mergeh); + const float32x2_t xy1 = vget_low_f32(cross20); + const float32x2_t yzero1 = vext_f32(xy1, zeros, 1); + const float32x2x2_t merge1 = vzip_f32(zw0, yzero1); + const float32x4_t colInv1 = vcombine_f32(merge1.val[0], merge1.val[1]); + + // const Vec3V colInv2 = XMVectorPermute(mergel,cross20,PxPermuteControl(0,6,1,7)); + const float32x2_t x0y0 = vget_low_f32(mergel); + const float32x2_t z1w1 = vget_high_f32(cross20); + const float32x2x2_t merge2 = vzip_f32(x0y0, z1w1); + const float32x4_t colInv2 = vcombine_f32(merge2.val[0], merge2.val[1]); + + return Mat33V(vmulq_lane_f32(colInv0, invDet, 0), vmulq_lane_f32(colInv1, invDet, 0), + vmulq_lane_f32(colInv2, invDet, 0)); +} + +PX_FORCE_INLINE Mat33V M33Trnsps(const Mat33V& a) +{ + return Mat33V(V3Merge(V3GetX(a.col0), V3GetX(a.col1), V3GetX(a.col2)), + V3Merge(V3GetY(a.col0), V3GetY(a.col1), V3GetY(a.col2)), + V3Merge(V3GetZ(a.col0), V3GetZ(a.col1), V3GetZ(a.col2))); +} + +PX_FORCE_INLINE Mat33V M33Identity() +{ + return Mat33V(V3UnitX(), V3UnitY(), V3UnitZ()); +} + +PX_FORCE_INLINE Mat33V M33Sub(const Mat33V& a, const Mat33V& b) +{ + return Mat33V(V3Sub(a.col0, b.col0), V3Sub(a.col1, b.col1), V3Sub(a.col2, b.col2)); +} + +PX_FORCE_INLINE Mat33V M33Neg(const Mat33V& a) +{ + return Mat33V(V3Neg(a.col0), V3Neg(a.col1), V3Neg(a.col2)); +} + +PX_FORCE_INLINE Mat33V M33Abs(const Mat33V& a) +{ + return Mat33V(V3Abs(a.col0), V3Abs(a.col1), V3Abs(a.col2)); +} + +PX_FORCE_INLINE Mat33V PromoteVec3V(const Vec3V v) +{ + const BoolV bTFFF = BTFFF(); + const BoolV bFTFF = BFTFF(); + const BoolV bFFTF = BTFTF(); + + const Vec3V zero = V3Zero(); + + return Mat33V(V3Sel(bTFFF, v, zero), V3Sel(bFTFF, v, zero), V3Sel(bFFTF, v, zero)); +} + +PX_FORCE_INLINE Mat33V M33Diagonal(const Vec3VArg d) +{ + const Vec3V x = V3Mul(V3UnitX(), d); + const Vec3V y = V3Mul(V3UnitY(), d); + const Vec3V z = V3Mul(V3UnitZ(), d); + return Mat33V(x, y, z); +} + +////////////////////////////////// +// MAT34V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M34MulV3(const Mat34V& a, const Vec3V b) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + const Vec3V v0 = V3Scale(a.col0, x); + const Vec3V v1 = V3Scale(a.col1, y); + const Vec3V v2 = V3Scale(a.col2, z); + const Vec3V v0PlusV1 = V3Add(v0, v1); + const Vec3V v0PlusV1Plusv2 = V3Add(v0PlusV1, v2); + return V3Add(v0PlusV1Plusv2, a.col3); +} + +PX_FORCE_INLINE Vec3V M34Mul33V3(const Mat34V& a, const Vec3V b) +{ + const FloatV x = V3GetX(b); + const FloatV y = V3GetY(b); + const FloatV z = V3GetZ(b); + const Vec3V v0 = V3Scale(a.col0, x); + const Vec3V v1 = V3Scale(a.col1, y); + const Vec3V v2 = V3Scale(a.col2, z); + const Vec3V v0PlusV1 = V3Add(v0, v1); + return V3Add(v0PlusV1, v2); +} + +PX_FORCE_INLINE Vec3V M34TrnspsMul33V3(const Mat34V& a, const Vec3V b) +{ + const FloatV x = V3Dot(a.col0, b); + const FloatV y = V3Dot(a.col1, b); + const FloatV z = V3Dot(a.col2, b); + return V3Merge(x, y, z); +} + +PX_FORCE_INLINE Mat34V M34MulM34(const Mat34V& a, const Mat34V& b) +{ + return Mat34V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2), M34MulV3(a, b.col3)); +} + +PX_FORCE_INLINE Mat33V M34MulM33(const Mat34V& a, const Mat33V& b) +{ + return Mat33V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2)); +} + +PX_FORCE_INLINE Mat33V M34Mul33MM34(const Mat34V& a, const Mat34V& b) +{ + return Mat33V(M34Mul33V3(a, b.col0), M34Mul33V3(a, b.col1), M34Mul33V3(a, b.col2)); +} + +PX_FORCE_INLINE Mat34V M34Add(const Mat34V& a, const Mat34V& b) +{ + return Mat34V(V3Add(a.col0, b.col0), V3Add(a.col1, b.col1), V3Add(a.col2, b.col2), V3Add(a.col3, b.col3)); +} + +PX_FORCE_INLINE Mat33V M34Trnsps33(const Mat34V& a) +{ + return Mat33V(V3Merge(V3GetX(a.col0), V3GetX(a.col1), V3GetX(a.col2)), + V3Merge(V3GetY(a.col0), V3GetY(a.col1), V3GetY(a.col2)), + V3Merge(V3GetZ(a.col0), V3GetZ(a.col1), V3GetZ(a.col2))); +} + +////////////////////////////////// +// MAT44V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V M44MulV4(const Mat44V& a, const Vec4V b) +{ + const FloatV x = V4GetX(b); + const FloatV y = V4GetY(b); + const FloatV z = V4GetZ(b); + const FloatV w = V4GetW(b); + + const Vec4V v0 = V4Scale(a.col0, x); + const Vec4V v1 = V4Scale(a.col1, y); + const Vec4V v2 = V4Scale(a.col2, z); + const Vec4V v3 = V4Scale(a.col3, w); + const Vec4V v0PlusV1 = V4Add(v0, v1); + const Vec4V v0PlusV1Plusv2 = V4Add(v0PlusV1, v2); + return V4Add(v0PlusV1Plusv2, v3); +} + +PX_FORCE_INLINE Vec4V M44TrnspsMulV4(const Mat44V& a, const Vec4V b) +{ + return V4Merge(V4Dot(a.col0, b), V4Dot(a.col1, b), V4Dot(a.col2, b), V4Dot(a.col3, b)); +} + +PX_FORCE_INLINE Mat44V M44MulM44(const Mat44V& a, const Mat44V& b) +{ + return Mat44V(M44MulV4(a, b.col0), M44MulV4(a, b.col1), M44MulV4(a, b.col2), M44MulV4(a, b.col3)); +} + +PX_FORCE_INLINE Mat44V M44Add(const Mat44V& a, const Mat44V& b) +{ + return Mat44V(V4Add(a.col0, b.col0), V4Add(a.col1, b.col1), V4Add(a.col2, b.col2), V4Add(a.col3, b.col3)); +} + +PX_FORCE_INLINE Mat44V M44Trnsps(const Mat44V& a) +{ + // asm volatile( + // "vzip.f32 %q0, %q2 \n\t" + // "vzip.f32 %q1, %q3 \n\t" + // "vzip.f32 %q0, %q1 \n\t" + // "vzip.f32 %q2, %q3 \n\t" + // : "+w" (a.col0), "+w" (a.col1), "+w" (a.col2), "+w" a.col3)); + + const float32x4x2_t v0v1 = vzipq_f32(a.col0, a.col2); + const float32x4x2_t v2v3 = vzipq_f32(a.col1, a.col3); + const float32x4x2_t zip0 = vzipq_f32(v0v1.val[0], v2v3.val[0]); + const float32x4x2_t zip1 = vzipq_f32(v0v1.val[1], v2v3.val[1]); + + return Mat44V(zip0.val[0], zip0.val[1], zip1.val[0], zip1.val[1]); +} + +PX_FORCE_INLINE Mat44V M44Inverse(const Mat44V& a) +{ + float32x4_t minor0, minor1, minor2, minor3; + float32x4_t row0, row1, row2, row3; + float32x4_t det, tmp1; + + tmp1 = vmovq_n_f32(0.0f); + row1 = vmovq_n_f32(0.0f); + row3 = vmovq_n_f32(0.0f); + + row0 = a.col0; + row1 = vextq_f32(a.col1, a.col1, 2); + row2 = a.col2; + row3 = vextq_f32(a.col3, a.col3, 2); + + tmp1 = vmulq_f32(row2, row3); + tmp1 = vrev64q_f32(tmp1); + minor0 = vmulq_f32(row1, tmp1); + minor1 = vmulq_f32(row0, tmp1); + tmp1 = vextq_f32(tmp1, tmp1, 2); + minor0 = vsubq_f32(vmulq_f32(row1, tmp1), minor0); + minor1 = vsubq_f32(vmulq_f32(row0, tmp1), minor1); + minor1 = vextq_f32(minor1, minor1, 2); + + tmp1 = vmulq_f32(row1, row2); + tmp1 = vrev64q_f32(tmp1); + minor0 = vaddq_f32(vmulq_f32(row3, tmp1), minor0); + minor3 = vmulq_f32(row0, tmp1); + tmp1 = vextq_f32(tmp1, tmp1, 2); + minor0 = vsubq_f32(minor0, vmulq_f32(row3, tmp1)); + minor3 = vsubq_f32(vmulq_f32(row0, tmp1), minor3); + minor3 = vextq_f32(minor3, minor3, 2); + + tmp1 = vmulq_f32(vextq_f32(row1, row1, 2), row3); + tmp1 = vrev64q_f32(tmp1); + row2 = vextq_f32(row2, row2, 2); + minor0 = vaddq_f32(vmulq_f32(row2, tmp1), minor0); + minor2 = vmulq_f32(row0, tmp1); + tmp1 = vextq_f32(tmp1, tmp1, 2); + minor0 = vsubq_f32(minor0, vmulq_f32(row2, tmp1)); + minor2 = vsubq_f32(vmulq_f32(row0, tmp1), minor2); + minor2 = vextq_f32(minor2, minor2, 2); + + tmp1 = vmulq_f32(row0, row1); + tmp1 = vrev64q_f32(tmp1); + minor2 = vaddq_f32(vmulq_f32(row3, tmp1), minor2); + minor3 = vsubq_f32(vmulq_f32(row2, tmp1), minor3); + tmp1 = vextq_f32(tmp1, tmp1, 2); + minor2 = vsubq_f32(vmulq_f32(row3, tmp1), minor2); + minor3 = vsubq_f32(minor3, vmulq_f32(row2, tmp1)); + + tmp1 = vmulq_f32(row0, row3); + tmp1 = vrev64q_f32(tmp1); + minor1 = vsubq_f32(minor1, vmulq_f32(row2, tmp1)); + minor2 = vaddq_f32(vmulq_f32(row1, tmp1), minor2); + tmp1 = vextq_f32(tmp1, tmp1, 2); + minor1 = vaddq_f32(vmulq_f32(row2, tmp1), minor1); + minor2 = vsubq_f32(minor2, vmulq_f32(row1, tmp1)); + + tmp1 = vmulq_f32(row0, row2); + tmp1 = vrev64q_f32(tmp1); + minor1 = vaddq_f32(vmulq_f32(row3, tmp1), minor1); + minor3 = vsubq_f32(minor3, vmulq_f32(row1, tmp1)); + tmp1 = vextq_f32(tmp1, tmp1, 2); + minor1 = vsubq_f32(minor1, vmulq_f32(row3, tmp1)); + minor3 = vaddq_f32(vmulq_f32(row1, tmp1), minor3); + + det = vmulq_f32(row0, minor0); + det = vaddq_f32(vextq_f32(det, det, 2), det); + det = vaddq_f32(vrev64q_f32(det), det); + det = vdupq_lane_f32(VRECIPE(vget_low_f32(det)), 0); + + minor0 = vmulq_f32(det, minor0); + minor1 = vmulq_f32(det, minor1); + minor2 = vmulq_f32(det, minor2); + minor3 = vmulq_f32(det, minor3); + Mat44V invTrans(minor0, minor1, minor2, minor3); + return M44Trnsps(invTrans); +} + +PX_FORCE_INLINE Vec4V V4LoadXYZW(const PxF32& x, const PxF32& y, const PxF32& z, const PxF32& w) +{ + const float32x4_t ret = { x, y, z, w }; + return ret; +} + +/* +PX_FORCE_INLINE VecU16V V4U32PK(VecU32V a, VecU32V b) +{ + return vcombine_u16(vqmovn_u32(a), vqmovn_u32(b)); +} +*/ + +PX_FORCE_INLINE VecU32V V4U32Sel(const BoolV c, const VecU32V a, const VecU32V b) +{ + return vbslq_u32(c, a, b); +} + +PX_FORCE_INLINE VecU32V V4U32or(VecU32V a, VecU32V b) +{ + return vorrq_u32(a, b); +} + +PX_FORCE_INLINE VecU32V V4U32xor(VecU32V a, VecU32V b) +{ + return veorq_u32(a, b); +} + +PX_FORCE_INLINE VecU32V V4U32and(VecU32V a, VecU32V b) +{ + return vandq_u32(a, b); +} + +PX_FORCE_INLINE VecU32V V4U32Andc(VecU32V a, VecU32V b) +{ + // return vbicq_u32(a, b); // creates gcc compiler bug in RTreeQueries.cpp + return vandq_u32(a, vmvnq_u32(b)); +} + +/* +PX_FORCE_INLINE VecU16V V4U16Or(VecU16V a, VecU16V b) +{ + return vorrq_u16(a, b); +} +*/ + +/* +PX_FORCE_INLINE VecU16V V4U16And(VecU16V a, VecU16V b) +{ + return vandq_u16(a, b); +} +*/ +/* +PX_FORCE_INLINE VecU16V V4U16Andc(VecU16V a, VecU16V b) +{ + return vbicq_u16(a, b); +} +*/ + +PX_FORCE_INLINE VecI32V I4LoadXYZW(const PxI32& x, const PxI32& y, const PxI32& z, const PxI32& w) +{ + const int32x4_t ret = { x, y, z, w }; + return ret; +} + +PX_FORCE_INLINE VecI32V I4Load(const PxI32 i) +{ + return vdupq_n_s32(i); +} + +PX_FORCE_INLINE VecI32V I4LoadU(const PxI32* i) +{ + return vld1q_s32(i); +} + +PX_FORCE_INLINE VecI32V I4LoadA(const PxI32* i) +{ + return vld1q_s32(i); +} + +PX_FORCE_INLINE VecI32V VecI32V_Add(const VecI32VArg a, const VecI32VArg b) +{ + return vaddq_s32(a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_Sub(const VecI32VArg a, const VecI32VArg b) +{ + return vsubq_s32(a, b); +} + +PX_FORCE_INLINE BoolV VecI32V_IsGrtr(const VecI32VArg a, const VecI32VArg b) +{ + return vcgtq_s32(a, b); +} + +PX_FORCE_INLINE BoolV VecI32V_IsEq(const VecI32VArg a, const VecI32VArg b) +{ + return vceqq_s32(a, b); +} + +PX_FORCE_INLINE VecI32V V4I32Sel(const BoolV c, const VecI32V a, const VecI32V b) +{ + return vbslq_s32(c, a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_Zero() +{ + return vdupq_n_s32(0); +} + +PX_FORCE_INLINE VecI32V VecI32V_One() +{ + return vdupq_n_s32(1); +} + +PX_FORCE_INLINE VecI32V VecI32V_Two() +{ + return vdupq_n_s32(2); +} + +PX_FORCE_INLINE VecI32V VecI32V_MinusOne() +{ + return vdupq_n_s32(-1); +} + +PX_FORCE_INLINE VecU32V U4Zero() +{ + return U4Load(0); +} + +PX_FORCE_INLINE VecU32V U4One() +{ + return U4Load(1); +} + +PX_FORCE_INLINE VecU32V U4Two() +{ + return U4Load(2); +} + +PX_FORCE_INLINE VecShiftV VecI32V_PrepareShift(const VecI32VArg shift) +{ + return shift; +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const VecShiftVArg count) +{ + return vshlq_s32(a, count); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const VecShiftVArg count) +{ + return vshlq_s32(a, VecI32V_Sub(I4Load(0), count)); +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const PxU32 count) +{ + const int32x4_t shiftCount = { (PxI32)count, (PxI32)count, (PxI32)count, (PxI32)count }; + return vshlq_s32(a, shiftCount); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const PxU32 count) +{ + const int32x4_t shiftCount = { -(PxI32)count, -(PxI32)count, -(PxI32)count, -(PxI32)count }; + return vshlq_s32(a, shiftCount); +} + +PX_FORCE_INLINE VecI32V VecI32V_And(const VecI32VArg a, const VecI32VArg b) +{ + return vandq_s32(a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_Or(const VecI32VArg a, const VecI32VArg b) +{ + return vorrq_s32(a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetX(const VecI32VArg f) +{ + const int32x2_t fLow = vget_low_s32(f); + return vdupq_lane_s32(fLow, 0); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetY(const VecI32VArg f) +{ + const int32x2_t fLow = vget_low_s32(f); + return vdupq_lane_s32(fLow, 1); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetZ(const VecI32VArg f) +{ + const int32x2_t fHigh = vget_high_s32(f); + return vdupq_lane_s32(fHigh, 0); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetW(const VecI32VArg f) +{ + const int32x2_t fHigh = vget_high_s32(f); + return vdupq_lane_s32(fHigh, 1); +} + +PX_FORCE_INLINE VecI32V VecI32V_Sel(const BoolV c, const VecI32VArg a, const VecI32VArg b) +{ + return vbslq_s32(c, a, b); +} + +PX_FORCE_INLINE void PxI32_From_VecI32V(const VecI32VArg a, PxI32* i) +{ + *i = vgetq_lane_s32(a, 0); +} + +PX_FORCE_INLINE VecI32V VecI32V_Merge(const VecI32VArg a, const VecI32VArg b, const VecI32VArg c, const VecI32VArg d) +{ + const int32x2_t aLow = vget_low_s32(a); + const int32x2_t bLow = vget_low_s32(b); + const int32x2_t cLow = vget_low_s32(c); + const int32x2_t dLow = vget_low_s32(d); + + const int32x2_t low = vext_s32(aLow, bLow, 1); + const int32x2_t high = vext_s32(cLow, dLow, 1); + + return vcombine_s32(low, high); +} + +PX_FORCE_INLINE VecI32V VecI32V_From_BoolV(const BoolVArg a) +{ + return vreinterpretq_s32_u32(a); +} + +PX_FORCE_INLINE VecU32V VecU32V_From_BoolV(const BoolVArg a) +{ + return a; +} + +/* +template PX_FORCE_INLINE VecI32V V4ISplat() +{ + return vdupq_n_s32(a); +} + +template PX_FORCE_INLINE VecU32V V4USplat() +{ + return vdupq_n_u32(a); +} +*/ + +/* +PX_FORCE_INLINE void V4U16StoreAligned(VecU16V val, VecU16V* address) +{ + vst1q_u16((uint16_t*)address, val); +} +*/ + +PX_FORCE_INLINE void V4U32StoreAligned(VecU32V val, VecU32V* address) +{ + vst1q_u32(reinterpret_cast(address), val); +} + +PX_FORCE_INLINE Vec4V V4LoadAligned(Vec4V* addr) +{ + return vld1q_f32(reinterpret_cast(addr)); +} + +PX_FORCE_INLINE Vec4V V4LoadUnaligned(Vec4V* addr) +{ + return vld1q_f32(reinterpret_cast(addr)); +} + +PX_FORCE_INLINE Vec4V V4Andc(const Vec4V a, const VecU32V b) +{ + return vreinterpretq_f32_u32(V4U32Andc(vreinterpretq_u32_f32(a), b)); +} + +PX_FORCE_INLINE VecU32V V4IsGrtrV32u(const Vec4V a, const Vec4V b) +{ + return V4IsGrtr(a, b); +} + +PX_FORCE_INLINE VecU16V V4U16LoadAligned(VecU16V* addr) +{ + return vld1q_u16(reinterpret_cast(addr)); +} + +PX_FORCE_INLINE VecU16V V4U16LoadUnaligned(VecU16V* addr) +{ + return vld1q_u16(reinterpret_cast(addr)); +} + +PX_FORCE_INLINE VecU16V V4U16CompareGt(VecU16V a, VecU16V b) +{ + return vcgtq_u16(a, b); +} + +PX_FORCE_INLINE VecU16V V4I16CompareGt(VecI16V a, VecI16V b) +{ + return vcgtq_s16(a, b); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_VecU32V(VecU32V a) +{ + return vcvtq_f32_u32(a); +} + +PX_FORCE_INLINE Vec4V Vec4V_From_VecI32V(VecI32V a) +{ + return vcvtq_f32_s32(a); +} + +PX_FORCE_INLINE VecI32V VecI32V_From_Vec4V(Vec4V a) +{ + return vcvtq_s32_f32(a); +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecU32V(VecU32V a) +{ + return vreinterpretq_f32_u32(a); +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecI32V(VecI32V a) +{ + return vreinterpretq_f32_s32(a); +} + +PX_FORCE_INLINE VecU32V VecU32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + return vreinterpretq_u32_f32(a); +} + +PX_FORCE_INLINE VecI32V VecI32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + return vreinterpretq_s32_f32(a); +} + +#if !PX_SWITCH +template +PX_FORCE_INLINE BoolV BSplatElement(BoolV a) +{ + if(index < 2) + { + return vdupq_lane_u32(vget_low_u32(a), index); + } + else if(index == 2) + { + return vdupq_lane_u32(vget_high_u32(a), 0); + } + else if(index == 3) + { + return vdupq_lane_u32(vget_high_u32(a), 1); + } +} +#else +//workaround for template compile issue +template PX_FORCE_INLINE BoolV BSplatElement(BoolV a); +template<> PX_FORCE_INLINE BoolV BSplatElement<0>(BoolV a) { return vdupq_lane_u32(vget_low_u32(a), 0); } +template<> PX_FORCE_INLINE BoolV BSplatElement<1>(BoolV a) { return vdupq_lane_u32(vget_low_u32(a), 1); } +template<> PX_FORCE_INLINE BoolV BSplatElement<2>(BoolV a) { return vdupq_lane_u32(vget_high_u32(a), 0); } +template<> PX_FORCE_INLINE BoolV BSplatElement<3>(BoolV a) { return vdupq_lane_u32(vget_high_u32(a), 1); } +#endif + +#if !PX_SWITCH +template +PX_FORCE_INLINE VecU32V V4U32SplatElement(VecU32V a) +{ + if(index < 2) + { + return vdupq_lane_u32(vget_low_u32(a), index); + } + else if(index == 2) + { + return vdupq_lane_u32(vget_high_u32(a), 0); + } + else if(index == 3) + { + return vdupq_lane_u32(vget_high_u32(a), 1); + } +} +#else +//workaround for template compile issue +template PX_FORCE_INLINE VecU32V V4U32SplatElement(VecU32V a); +template <> PX_FORCE_INLINE VecU32V V4U32SplatElement<0>(VecU32V a) { return vdupq_lane_u32(vget_low_u32(a), 0); } +template <> PX_FORCE_INLINE VecU32V V4U32SplatElement<1>(VecU32V a) { return vdupq_lane_u32(vget_low_u32(a), 1); } +template <> PX_FORCE_INLINE VecU32V V4U32SplatElement<2>(VecU32V a) { return vdupq_lane_u32(vget_high_u32(a), 0); } +template <> PX_FORCE_INLINE VecU32V V4U32SplatElement<3>(VecU32V a) { return vdupq_lane_u32(vget_high_u32(a), 1); } +#endif + +#if !PX_SWITCH +template +PX_FORCE_INLINE Vec4V V4SplatElement(Vec4V a) +{ + if(index < 2) + { + return vdupq_lane_f32(vget_low_f32(a), index); + } + else if(index == 2) + { + return vdupq_lane_f32(vget_high_f32(a), 0); + } + else if(index == 3) + { + return vdupq_lane_f32(vget_high_f32(a), 1); + } +} +#else +//workaround for template compile issue +template PX_FORCE_INLINE Vec4V V4SplatElement(Vec4V a); +template <> PX_FORCE_INLINE Vec4V V4SplatElement<0>(Vec4V a) { return vdupq_lane_f32(vget_low_f32(a), 0); } +template <> PX_FORCE_INLINE Vec4V V4SplatElement<1>(Vec4V a) { return vdupq_lane_f32(vget_low_f32(a), 1); } +template <> PX_FORCE_INLINE Vec4V V4SplatElement<2>(Vec4V a) { return vdupq_lane_f32(vget_high_f32(a), 0); } +template <> PX_FORCE_INLINE Vec4V V4SplatElement<3>(Vec4V a) { return vdupq_lane_f32(vget_high_f32(a), 1); } +#endif + +PX_FORCE_INLINE VecU32V U4LoadXYZW(PxU32 x, PxU32 y, PxU32 z, PxU32 w) +{ + const uint32x4_t ret = { x, y, z, w }; + return ret; +} + +PX_FORCE_INLINE VecU32V U4Load(const PxU32 i) +{ + return vdupq_n_u32(i); +} + +PX_FORCE_INLINE VecU32V U4LoadU(const PxU32* i) +{ + return vld1q_u32(i); +} + +PX_FORCE_INLINE VecU32V U4LoadA(const PxU32* i) +{ + return vld1q_u32(i); +} + +PX_FORCE_INLINE Vec4V V4Ceil(const Vec4V in) +{ + const float32x4_t ones = vdupq_n_f32(1.0f); + const float32x4_t rdToZero = vcvtq_f32_s32(vcvtq_s32_f32(in)); + const float32x4_t rdToZeroPlusOne = vaddq_f32(rdToZero, ones); + const uint32x4_t gt = vcgtq_f32(in, rdToZero); + return vbslq_f32(gt, rdToZeroPlusOne, rdToZero); +} + +PX_FORCE_INLINE Vec4V V4Floor(const Vec4V in) +{ + const float32x4_t ones = vdupq_n_f32(1.0f); + const float32x4_t rdToZero = vcvtq_f32_s32(vcvtq_s32_f32(in)); + const float32x4_t rdToZeroMinusOne = vsubq_f32(rdToZero, ones); + const uint32x4_t lt = vcltq_f32(in, rdToZero); + return vbslq_f32(lt, rdToZeroMinusOne, rdToZero); +} + +PX_FORCE_INLINE VecU32V V4ConvertToU32VSaturate(const Vec4V in, PxU32 power) +{ + PX_ASSERT(power == 0 && "Non-zero power not supported in convertToU32VSaturate"); + PX_UNUSED(power); // prevent warning in release builds + + return vcvtq_u32_f32(in); +} + +PX_FORCE_INLINE void QuatGetMat33V(const QuatVArg q, Vec3V& column0, Vec3V& column1, Vec3V& column2) +{ + const FloatV one = FOne(); + const FloatV x = V4GetX(q); + const FloatV y = V4GetY(q); + const FloatV z = V4GetZ(q); + const FloatV w = V4GetW(q); + + const FloatV x2 = FAdd(x, x); + const FloatV y2 = FAdd(y, y); + const FloatV z2 = FAdd(z, z); + + const FloatV xx = FMul(x2, x); + const FloatV yy = FMul(y2, y); + const FloatV zz = FMul(z2, z); + + const FloatV xy = FMul(x2, y); + const FloatV xz = FMul(x2, z); + const FloatV xw = FMul(x2, w); + + const FloatV yz = FMul(y2, z); + const FloatV yw = FMul(y2, w); + const FloatV zw = FMul(z2, w); + + const FloatV v = FSub(one, xx); + + column0 = V3Merge(FSub(FSub(one, yy), zz), FAdd(xy, zw), FSub(xz, yw)); + column1 = V3Merge(FSub(xy, zw), FSub(v, zz), FAdd(yz, xw)); + column2 = V3Merge(FAdd(xz, yw), FSub(yz, xw), FSub(v, yy)); +} + +} // namespace aos +} // namespace physx + +#endif // PXFOUNDATION_PXUNIXNEONINLINEAOS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/sse2/PxUnixSse2AoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/sse2/PxUnixSse2AoS.h new file mode 100644 index 000000000..f7b761af3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/sse2/PxUnixSse2AoS.h @@ -0,0 +1,187 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXSSE2AOS_H +#define PXFOUNDATION_PXUNIXSSE2AOS_H + +// no includes here! this file should be included from PxcVecMath.h only!!! + +#if !COMPILE_VECTOR_INTRINSICS +#error Vector intrinsics should not be included when using scalar implementation. +#endif + +namespace physx +{ +namespace aos +{ + +#if PX_EMSCRIPTEN +typedef int8_t __int8_t; +typedef int16_t __int16_t; +typedef int32_t __int32_t; +typedef int64_t __int64_t; +typedef uint16_t __uint16_t; +typedef uint32_t __uint32_t; +typedef uint64_t __uint64_t; +#endif + +typedef union UnionM128 +{ + UnionM128() + { + } + UnionM128(__m128 in) + { + m128 = in; + } + + UnionM128(__m128i in) + { + m128i = in; + } + + operator __m128() + { + return m128; + } + + operator __m128() const + { + return m128; + } + + float m128_f32[4]; + __int8_t m128_i8[16]; + __int16_t m128_i16[8]; + __int32_t m128_i32[4]; + __int64_t m128_i64[2]; + __uint16_t m128_u16[8]; + __uint32_t m128_u32[4]; + __uint64_t m128_u64[2]; + __m128 m128; + __m128i m128i; +} UnionM128; + +typedef __m128 FloatV; +typedef __m128 Vec3V; +typedef __m128 Vec4V; +typedef __m128 BoolV; +typedef __m128 QuatV; +typedef __m128i VecI32V; +typedef UnionM128 VecU32V; +typedef UnionM128 VecU16V; +typedef UnionM128 VecI16V; +typedef UnionM128 VecU8V; + +#define FloatVArg FloatV & +#define Vec3VArg Vec3V & +#define Vec4VArg Vec4V & +#define BoolVArg BoolV & +#define VecU32VArg VecU32V & +#define VecI32VArg VecI32V & +#define VecU16VArg VecU16V & +#define VecI16VArg VecI16V & +#define VecU8VArg VecU8V & +#define QuatVArg QuatV & + +// Optimization for situations in which you cross product multiple vectors with the same vector. +// Avoids 2X shuffles per product +struct VecCrossV +{ + Vec3V mL1; + Vec3V mR1; +}; + +struct VecShiftV +{ + VecI32V shift; +}; +#define VecShiftVArg VecShiftV & + +PX_ALIGN_PREFIX(16) +struct Mat33V +{ + Mat33V() + { + } + Mat33V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec3V PX_ALIGN(16, col0); + Vec3V PX_ALIGN(16, col1); + Vec3V PX_ALIGN(16, col2); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat34V +{ + Mat34V() + { + } + Mat34V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2, const Vec3V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec3V PX_ALIGN(16, col0); + Vec3V PX_ALIGN(16, col1); + Vec3V PX_ALIGN(16, col2); + Vec3V PX_ALIGN(16, col3); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat43V +{ + Mat43V() + { + } + Mat43V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec4V PX_ALIGN(16, col0); + Vec4V PX_ALIGN(16, col1); + Vec4V PX_ALIGN(16, col2); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat44V +{ + Mat44V() + { + } + Mat44V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2, const Vec4V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec4V PX_ALIGN(16, col0); + Vec4V PX_ALIGN(16, col1); + Vec4V PX_ALIGN(16, col2); + Vec4V PX_ALIGN(16, col3); +} PX_ALIGN_SUFFIX(16); + +} // namespace aos +} // namespace physx + +#endif // PXFOUNDATION_PXUNIXSSE2AOS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/sse2/PxUnixSse2InlineAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/sse2/PxUnixSse2InlineAoS.h new file mode 100644 index 000000000..4f2b881cf --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/unix/sse2/PxUnixSse2InlineAoS.h @@ -0,0 +1,719 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PXFOUNDATION_PXUNIXSSE2INLINEAOS_H +#define PXFOUNDATION_PXUNIXSSE2INLINEAOS_H + +namespace physx +{ +namespace aos +{ +////////////////////////////////////////////////////////////////////// +//Test that Vec3V and FloatV are legal +////////////////////////////////////////////////////////////////////// + +#define FLOAT_COMPONENTS_EQUAL_THRESHOLD 0.01f +PX_FORCE_INLINE static bool isValidFloatV(const FloatV a) +{ + const PxF32 x = V4ReadX(a); + const PxF32 y = V4ReadY(a); + const PxF32 z = V4ReadZ(a); + const PxF32 w = V4ReadW(a); + + return (x == y && x == z && x == w); + + /*if ( + (PxAbs(x - y) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs(x - z) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs(x - w) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) + ) + { + return true; + } + + if ( + (PxAbs((x - y) / x) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs((x - z) / x) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs((x - w) / x) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) + ) + { + return true; + } + return false;*/ +} + +} +} + +#include "../../PxVecMathSSE.h" + +namespace physx +{ +namespace aos +{ + +#define PX_FPCLASS_SNAN 0x0001 /* signaling NaN */ +#define PX_FPCLASS_QNAN 0x0002 /* quiet NaN */ +#define PX_FPCLASS_NINF 0x0004 /* negative infinity */ +#define PX_FPCLASS_PINF 0x0200 /* positive infinity */ + +namespace internalSimd +{ +#if !PX_EMSCRIPTEN +#if PX_CLANG +#if PX_LINUX +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wglobal-constructors" +#endif +#endif +const PX_ALIGN(16, PxF32 gMaskXYZ[4]) = { physx::PxUnionCast(0xffffffff), physx::PxUnionCast(0xffffffff), + physx::PxUnionCast(0xffffffff), 0 }; +#if PX_CLANG +#if PX_LINUX +#pragma clang diagnostic pop +#endif +#endif +#else +// emscripten doesn't like the PxUnionCast data structure +// the following is what windows and xbox does -- using these for emscripten +const PX_ALIGN(16, PxU32 gMaskXYZ[4]) = { 0xffffffff, 0xffffffff, 0xffffffff, 0 }; +#endif +} + +namespace vecMathTests +{ +PX_FORCE_INLINE bool allElementsEqualBoolV(const BoolV a, const BoolV b) +{ + return internalSimd::BAllTrue4_R(VecI32V_IsEq(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualVecI32V(const VecI32V a, const VecI32V b) +{ + BoolV c = internalSimd::m128_I2F(_mm_cmpeq_epi32(a, b)); + return internalSimd::BAllTrue4_R(c) != 0; +} + +#define VECMATH_AOS_EPSILON (1e-3f) + +PX_FORCE_INLINE bool allElementsNearEqualFloatV(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + const FloatV c = FSub(a, b); + const FloatV minError = FLoad(-VECMATH_AOS_EPSILON); + const FloatV maxError = FLoad(VECMATH_AOS_EPSILON); + return _mm_comigt_ss(c, minError) && _mm_comilt_ss(c, maxError); +} + +PX_FORCE_INLINE bool allElementsNearEqualVec3V(const Vec3V a, const Vec3V b) +{ + const Vec3V c = V3Sub(a, b); + const Vec3V minError = V3Load(-VECMATH_AOS_EPSILON); + const Vec3V maxError = V3Load(VECMATH_AOS_EPSILON); + return (_mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), minError) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), maxError) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), minError) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), maxError) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), minError) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), maxError)); +} + +PX_FORCE_INLINE bool allElementsNearEqualVec4V(const Vec4V a, const Vec4V b) +{ + const Vec4V c = V4Sub(a, b); + const Vec4V minError = V4Load(-VECMATH_AOS_EPSILON); + const Vec4V maxError = V4Load(VECMATH_AOS_EPSILON); + return (_mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), minError) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), maxError) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), minError) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), maxError) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), minError) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), maxError) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(3, 3, 3, 3)), minError) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(3, 3, 3, 3)), maxError)); +} +} //vecMathTests + +///////////////////////////////////////////////////////////////////// +////FUNCTIONS USED ONLY FOR ASSERTS IN VECTORISED IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE bool isFiniteFloatV(const FloatV a) +{ + PxF32 badNumber = + physx::PxUnionCast(PX_FPCLASS_SNAN | PX_FPCLASS_QNAN | PX_FPCLASS_NINF | PX_FPCLASS_PINF); + const FloatV vBadNum = FLoad(badNumber); + const BoolV vMask = BAnd(vBadNum, a); + return internalSimd::FiniteTestEq(vMask, BFFFF()) == 1; +} + +PX_FORCE_INLINE bool isFiniteVec3V(const Vec3V a) +{ + PxF32 badNumber = + physx::PxUnionCast(PX_FPCLASS_SNAN | PX_FPCLASS_QNAN | PX_FPCLASS_NINF | PX_FPCLASS_PINF); + const Vec3V vBadNum = V3Load(badNumber); + const BoolV vMask = BAnd(BAnd(vBadNum, a), BTTTF()); + return internalSimd::FiniteTestEq(vMask, BFFFF()) == 1; +} + +PX_FORCE_INLINE bool isFiniteVec4V(const Vec4V a) +{ + /*Vec4V a; + PX_ALIGN(16, PxF32 f[4]); + F32Array_Aligned_From_Vec4V(a, f); + return PxIsFinite(f[0]) + && PxIsFinite(f[1]) + && PxIsFinite(f[2]) + && PxIsFinite(f[3]);*/ + + PxF32 badNumber = + physx::PxUnionCast(PX_FPCLASS_SNAN | PX_FPCLASS_QNAN | PX_FPCLASS_NINF | PX_FPCLASS_PINF); + const Vec4V vBadNum = V4Load(badNumber); + const BoolV vMask = BAnd(vBadNum, a); + + return internalSimd::FiniteTestEq(vMask, BFFFF()) == 1; +} + +///////////////////////////////////////////////////////////////////// +////VECTORISED FUNCTION IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE Vec3V V3LoadA(const PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); +#if !PX_EMSCRIPTEN + return _mm_and_ps(reinterpret_cast(f), V4LoadA(internalSimd::gMaskXYZ)); +#else + return _mm_and_ps((Vec3V&)f, (VecI32V&)internalSimd::gMaskXYZ); +#endif +} + +PX_FORCE_INLINE Vec3V V3LoadUnsafeA(const PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + return _mm_set_ps(0.0f, f.z, f.y, f.x); +} + +PX_FORCE_INLINE Vec3V V3LoadA(const PxF32* const f) +{ + ASSERT_ISALIGNED16(f); +#if !PX_EMSCRIPTEN + return _mm_and_ps(V4LoadA(f), V4LoadA(internalSimd::gMaskXYZ)); +#else + return _mm_and_ps((Vec3V&)*f, (VecI32V&)internalSimd::gMaskXYZ); +#endif +} + +PX_FORCE_INLINE void I4StoreA(const VecI32V iv, PxI32* i) +{ + ASSERT_ISALIGNED16(i); + _mm_store_ps(reinterpret_cast(i), internalSimd::m128_I2F(iv)); +} + +PX_FORCE_INLINE BoolV BLoad(const bool* const f) +{ + const PX_ALIGN(16, PxI32) b[4] = { -PxI32(f[0]), -PxI32(f[1]), -PxI32(f[2]), -PxI32(f[3]) }; + return _mm_load_ps(reinterpret_cast(&b)); +} + +PX_FORCE_INLINE void V3StoreA(const Vec3V a, PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + PX_ALIGN(16, PxF32) f2[4]; + _mm_store_ps(f2, a); + f = PxVec3(f2[0], f2[1], f2[2]); +} + +PX_FORCE_INLINE void V3StoreU(const Vec3V a, PxVec3& f) +{ + PX_ALIGN(16, PxF32) f2[4]; + _mm_store_ps(f2, a); + f = PxVec3(f2[0], f2[1], f2[2]); +} + +////////////////////////////////// +// FLOATV +////////////////////////////////// + +PX_FORCE_INLINE FloatV FAbs(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + PX_ALIGN(16, const PxU32) absMask[4] = { 0x7fFFffFF, 0x7fFFffFF, 0x7fFFffFF, 0x7fFFffFF }; + return _mm_and_ps(a, _mm_load_ps(reinterpret_cast(absMask))); +} + +////////////////////////////////// +// VEC3V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V V3UnitX() +{ + const PX_ALIGN(16, PxF32) x[4] = { 1.0f, 0.0f, 0.0f, 0.0f }; + const __m128 x128 = _mm_load_ps(x); + return x128; +} + +PX_FORCE_INLINE Vec3V V3UnitY() +{ + const PX_ALIGN(16, PxF32) y[4] = { 0.0f, 1.0f, 0.0f, 0.0f }; + const __m128 y128 = _mm_load_ps(y); + return y128; +} + +PX_FORCE_INLINE Vec3V V3UnitZ() +{ + const PX_ALIGN(16, PxF32) z[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; + const __m128 z128 = _mm_load_ps(z); + return z128; +} + +////////////////////////////////// +// VEC4V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V V4UnitW() +{ + const PX_ALIGN(16, PxF32) w[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; + const __m128 w128 = _mm_load_ps(w); + return w128; +} + +PX_FORCE_INLINE Vec4V V4UnitX() +{ + const PX_ALIGN(16, PxF32) x[4] = { 1.0f, 0.0f, 0.0f, 0.0f }; + const __m128 x128 = _mm_load_ps(x); + return x128; +} + +PX_FORCE_INLINE Vec4V V4UnitY() +{ + const PX_ALIGN(16, PxF32) y[4] = { 0.0f, 1.0f, 0.0f, 0.0f }; + const __m128 y128 = _mm_load_ps(y); + return y128; +} + +PX_FORCE_INLINE Vec4V V4UnitZ() +{ + const PX_ALIGN(16, PxF32) z[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; + const __m128 z128 = _mm_load_ps(z); + return z128; +} + +PX_FORCE_INLINE Vec4V V4ClearW(const Vec4V v) +{ +#if !PX_EMSCRIPTEN + return _mm_and_ps(v, V4LoadA(internalSimd::gMaskXYZ)); +#else + return _mm_and_ps(v, (VecI32V&)internalSimd::gMaskXYZ); +#endif +} + +////////////////////////////////// +// BoolV +////////////////////////////////// + +/* +template PX_FORCE_INLINE BoolV BSplatElement(BoolV a) +{ + BoolV result; + result[0] = result[1] = result[2] = result[3] = a[index]; + return result; +} +*/ + +template +BoolV BSplatElement(BoolV a) +{ + float* data = reinterpret_cast(&a); + return V4Load(data[index]); +} + +////////////////////////////////// +// MAT33V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M33TrnspsMulV3(const Mat33V& a, const Vec3V b) +{ + const FloatV x = V3Dot(a.col0, b); + const FloatV y = V3Dot(a.col1, b); + const FloatV z = V3Dot(a.col2, b); + return V3Merge(x, y, z); +} + +PX_FORCE_INLINE Mat33V M33Trnsps(const Mat33V& a) +{ + return Mat33V(V3Merge(V3GetX(a.col0), V3GetX(a.col1), V3GetX(a.col2)), + V3Merge(V3GetY(a.col0), V3GetY(a.col1), V3GetY(a.col2)), + V3Merge(V3GetZ(a.col0), V3GetZ(a.col1), V3GetZ(a.col2))); +} + +/*PX_FORCE_INLINE Mat33V PromoteVec3V(const Vec3V v) +{ + const BoolV bTFFF = BTFFF(); + const BoolV bFTFF = BFTFF(); + const BoolV bFFTF = BTFTF(); + + const Vec3V zero = V3Zero(); + + return Mat33V(V3Sel(bTFFF, v, zero), V3Sel(bFTFF, v, zero), V3Sel(bFFTF, v, zero)); +}*/ + +////////////////////////////////// +// MAT34V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M34TrnspsMul33V3(const Mat34V& a, const Vec3V b) +{ + const FloatV x = V3Dot(a.col0, b); + const FloatV y = V3Dot(a.col1, b); + const FloatV z = V3Dot(a.col2, b); + return V3Merge(x, y, z); +} + +PX_FORCE_INLINE Mat33V M34Trnsps33(const Mat34V& a) +{ + return Mat33V(V3Merge(V3GetX(a.col0), V3GetX(a.col1), V3GetX(a.col2)), + V3Merge(V3GetY(a.col0), V3GetY(a.col1), V3GetY(a.col2)), + V3Merge(V3GetZ(a.col0), V3GetZ(a.col1), V3GetZ(a.col2))); +} + +////////////////////////////////// +// MAT44V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V M44TrnspsMulV4(const Mat44V& a, const Vec4V b) +{ + PX_ALIGN(16, FloatV) dotProdArray[4] = { V4Dot(a.col0, b), V4Dot(a.col1, b), V4Dot(a.col2, b), V4Dot(a.col3, b) }; + return V4Merge(dotProdArray); +} + +PX_FORCE_INLINE Mat44V M44Trnsps(const Mat44V& a) +{ + const Vec4V v0 = _mm_unpacklo_ps(a.col0, a.col2); + const Vec4V v1 = _mm_unpackhi_ps(a.col0, a.col2); + const Vec4V v2 = _mm_unpacklo_ps(a.col1, a.col3); + const Vec4V v3 = _mm_unpackhi_ps(a.col1, a.col3); + return Mat44V(_mm_unpacklo_ps(v0, v2), _mm_unpackhi_ps(v0, v2), _mm_unpacklo_ps(v1, v3), _mm_unpackhi_ps(v1, v3)); +} + +////////////////////////////////// +// Misc +////////////////////////////////// + +/* +// AP: work in progress - use proper SSE intrinsics where possible +PX_FORCE_INLINE VecU16V V4U32PK(VecU32V a, VecU32V b) +{ + VecU16V result; + result.m128_u16[0] = PxU16(PxClamp((a).m128_u32[0], 0, 0xFFFF)); + result.m128_u16[1] = PxU16(PxClamp((a).m128_u32[1], 0, 0xFFFF)); + result.m128_u16[2] = PxU16(PxClamp((a).m128_u32[2], 0, 0xFFFF)); + result.m128_u16[3] = PxU16(PxClamp((a).m128_u32[3], 0, 0xFFFF)); + result.m128_u16[4] = PxU16(PxClamp((b).m128_u32[0], 0, 0xFFFF)); + result.m128_u16[5] = PxU16(PxClamp((b).m128_u32[1], 0, 0xFFFF)); + result.m128_u16[6] = PxU16(PxClamp((b).m128_u32[2], 0, 0xFFFF)); + result.m128_u16[7] = PxU16(PxClamp((b).m128_u32[3], 0, 0xFFFF)); + return result; +} +*/ + +/* +PX_FORCE_INLINE VecU16V V4U16Or(VecU16V a, VecU16V b) +{ + return m128_I2F(_mm_or_si128(m128_F2I(a), m128_F2I(b))); +} +*/ + +/* +PX_FORCE_INLINE VecU16V V4U16And(VecU16V a, VecU16V b) +{ + return m128_I2F(_mm_and_si128(m128_F2I(a), m128_F2I(b))); +} +*/ + +/* +PX_FORCE_INLINE VecU16V V4U16Andc(VecU16V a, VecU16V b) +{ + return m128_I2F(_mm_andnot_si128(m128_F2I(b), m128_F2I(a))); +} +*/ + +PX_FORCE_INLINE VecI32V I4LoadXYZW(const PxI32& x, const PxI32& y, const PxI32& z, const PxI32& w) +{ + return _mm_set_epi32(w, z, y, x); +} + +PX_FORCE_INLINE VecI32V I4Load(const PxI32 i) +{ + return internalSimd::m128_F2I(_mm_load1_ps(reinterpret_cast(&i))); +} + +PX_FORCE_INLINE VecI32V I4LoadU(const PxI32* i) +{ + return internalSimd::m128_F2I(_mm_loadu_ps(reinterpret_cast(i))); +} + +PX_FORCE_INLINE VecI32V I4LoadA(const PxI32* i) +{ + ASSERT_ISALIGNED16(i); + return internalSimd::m128_F2I(_mm_load_ps(reinterpret_cast(i))); +} + +PX_FORCE_INLINE VecI32V VecI32V_Add(const VecI32VArg a, const VecI32VArg b) +{ + return _mm_add_epi32(a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_Sub(const VecI32VArg a, const VecI32VArg b) +{ + return _mm_sub_epi32(a, b); +} + +PX_FORCE_INLINE BoolV VecI32V_IsGrtr(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_cmpgt_epi32(a, b)); +} + +PX_FORCE_INLINE BoolV VecI32V_IsEq(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_cmpeq_epi32(a, b)); +} + +PX_FORCE_INLINE VecI32V V4I32Sel(const BoolV c, const VecI32V a, const VecI32V b) +{ + return _mm_or_si128(_mm_andnot_si128(internalSimd::m128_F2I(c), b), _mm_and_si128(internalSimd::m128_F2I(c), a)); +} + +PX_FORCE_INLINE VecI32V VecI32V_Zero() +{ + return _mm_setzero_si128(); +} + +PX_FORCE_INLINE VecI32V VecI32V_Sel(const BoolV c, const VecI32VArg a, const VecI32VArg b) +{ + return _mm_or_si128(_mm_andnot_si128(internalSimd::m128_F2I(c), b), _mm_and_si128(internalSimd::m128_F2I(c), a)); +} + +PX_FORCE_INLINE VecShiftV VecI32V_PrepareShift(const VecI32VArg shift) +{ + VecShiftV s; + s.shift = VecI32V_Sel(BTFFF(), shift, VecI32V_Zero()); + return s; +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const VecShiftVArg count) +{ + return _mm_sll_epi32(a, count.shift); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const VecShiftVArg count) +{ + return _mm_srl_epi32(a, count.shift); +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const PxU32 count) +{ + return _mm_slli_epi32(a, PxI32(count)); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const PxU32 count) +{ + return _mm_srai_epi32(a, PxI32(count)); +} + +PX_FORCE_INLINE VecI32V VecI32V_And(const VecI32VArg a, const VecI32VArg b) +{ + return _mm_and_si128(a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_Or(const VecI32VArg a, const VecI32VArg b) +{ + return _mm_or_si128(a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetX(const VecI32VArg a) +{ + return internalSimd::m128_F2I(_mm_shuffle_ps(internalSimd::m128_I2F(a), internalSimd::m128_I2F(a), _MM_SHUFFLE(0, 0, 0, 0))); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetY(const VecI32VArg a) +{ + return internalSimd::m128_F2I(_mm_shuffle_ps(internalSimd::m128_I2F(a), internalSimd::m128_I2F(a), _MM_SHUFFLE(1, 1, 1, 1))); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetZ(const VecI32VArg a) +{ + return internalSimd::m128_F2I(_mm_shuffle_ps(internalSimd::m128_I2F(a), internalSimd::m128_I2F(a), _MM_SHUFFLE(2, 2, 2, 2))); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetW(const VecI32VArg a) +{ + return internalSimd::m128_F2I(_mm_shuffle_ps(internalSimd::m128_I2F(a), internalSimd::m128_I2F(a), _MM_SHUFFLE(3, 3, 3, 3))); +} + +PX_FORCE_INLINE void PxI32_From_VecI32V(const VecI32VArg a, PxI32* i) +{ + _mm_store_ss(reinterpret_cast(i), internalSimd::m128_I2F(a)); +} + +PX_FORCE_INLINE VecI32V VecI32V_From_BoolV(const BoolVArg a) +{ + return internalSimd::m128_F2I(a); +} + +PX_FORCE_INLINE VecU32V VecU32V_From_BoolV(const BoolVArg a) +{ + return a; +} + +PX_FORCE_INLINE VecI32V VecI32V_Merge(const VecI32VArg x, const VecI32VArg y, const VecI32VArg z, const VecI32VArg w) +{ + const __m128 xw = _mm_move_ss(internalSimd::m128_I2F(y), internalSimd::m128_I2F(x)); // y, y, y, x + const __m128 yz = _mm_move_ss(internalSimd::m128_I2F(z), internalSimd::m128_I2F(w)); // z, z, z, w + return internalSimd::m128_F2I(_mm_shuffle_ps(xw, yz, _MM_SHUFFLE(0, 2, 1, 0))); +} + +/* +template PX_FORCE_INLINE VecI32V V4ISplat() +{ + VecI32V result; + result.m128_i32[0] = a; + result.m128_i32[1] = a; + result.m128_i32[2] = a; + result.m128_i32[3] = a; + return result; +} + +template PX_FORCE_INLINE VecU32V V4USplat() +{ + VecU32V result; + result.m128_u32[0] = a; + result.m128_u32[1] = a; + result.m128_u32[2] = a; + result.m128_u32[3] = a; + return result; +} +*/ + +/* +PX_FORCE_INLINE void V4U16StoreAligned(VecU16V val, VecU16V* address) +{ + *address = val; +} +*/ + +PX_FORCE_INLINE void V4U32StoreAligned(VecU32V val, VecU32V* address) +{ + *address = val; +} + +/*PX_FORCE_INLINE Vec4V V4LoadAligned(Vec4V* addr) +{ + return *addr; +} + +PX_FORCE_INLINE Vec4V V4LoadUnaligned(Vec4V* addr) +{ + return V4LoadU(reinterpret_cast(addr)); +}*/ + +PX_FORCE_INLINE Vec4V Vec4V_From_VecI32V(VecI32V in) +{ + return _mm_cvtepi32_ps(in); +} + +PX_FORCE_INLINE VecI32V VecI32V_From_Vec4V(Vec4V a) +{ + return _mm_cvttps_epi32(a); +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecU32V(VecU32V a) +{ + return Vec4V(a); +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecI32V(VecI32V a) +{ + return internalSimd::m128_I2F(a); +} + +PX_FORCE_INLINE VecU32V VecU32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + return VecU32V(a); +} + +PX_FORCE_INLINE VecI32V VecI32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + return internalSimd::m128_F2I(a); +} + +template +PX_FORCE_INLINE VecU32V V4U32SplatElement(VecU32V a) +{ + VecU32V result; + result.m128_u32[0] = result.m128_u32[1] = result.m128_u32[2] = result.m128_u32[3] = a.m128_u32[index]; + return result; +} + +template +PX_FORCE_INLINE Vec4V V4SplatElement(Vec4V a) +{ + float* data = reinterpret_cast(&a); + return V4Load(data[index]); +} + +/*PX_FORCE_INLINE Vec4V V4Ceil(const Vec4V in) +{ + UnionM128 a(in); + return V4LoadXYZW(PxCeil(a.m128_f32[0]), PxCeil(a.m128_f32[1]), PxCeil(a.m128_f32[2]), PxCeil(a.m128_f32[3])); +} + +PX_FORCE_INLINE Vec4V V4Floor(const Vec4V in) +{ + UnionM128 a(in); + return V4LoadXYZW(PxFloor(a.m128_f32[0]), PxFloor(a.m128_f32[1]), PxFloor(a.m128_f32[2]), PxFloor(a.m128_f32[3])); +} + +PX_FORCE_INLINE VecU32V V4ConvertToU32VSaturate(const Vec4V in, PxU32 power) +{ + PX_ASSERT(power == 0 && "Non-zero power not supported in convertToU32VSaturate"); + PX_UNUSED(power); // prevent warning in release builds + PxF32 ffffFFFFasFloat = PxF32(0xFFFF0000); + UnionM128 a(in); + VecU32V result; + result.m128_u32[0] = PxU32(PxClamp((a).m128_f32[0], 0.0f, ffffFFFFasFloat)); + result.m128_u32[1] = PxU32(PxClamp((a).m128_f32[1], 0.0f, ffffFFFFasFloat)); + result.m128_u32[2] = PxU32(PxClamp((a).m128_f32[2], 0.0f, ffffFFFFasFloat)); + result.m128_u32[3] = PxU32(PxClamp((a).m128_f32[3], 0.0f, ffffFFFFasFloat)); + return result; +}*/ + +} // namespace aos +} // namespace physx + +#endif // PXFOUNDATION_PXUNIXSSE2INLINEAOS_H diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsAoS.h new file mode 100644 index 000000000..8e126fcfe --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsAoS.h @@ -0,0 +1,143 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_AOS_H +#define PX_WINDOWS_AOS_H + +// no includes here! this file should be included from PxAOS.h only!!! + +#if !COMPILE_VECTOR_INTRINSICS +#error Vector intrinsics should not be included when using scalar implementation. +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif +namespace aos +{ + +typedef __m128 FloatV; +typedef __m128 Vec3V; +typedef __m128 Vec4V; +typedef __m128 BoolV; +typedef __m128 VecU32V; +typedef __m128 VecI32V; +typedef __m128 VecU16V; +typedef __m128 VecI16V; +typedef __m128 QuatV; + +#define FloatVArg FloatV & +#define Vec3VArg Vec3V & +#define Vec4VArg Vec4V & +#define BoolVArg BoolV & +#define VecU32VArg VecU32V & +#define VecI32VArg VecI32V & +#define VecU16VArg VecU16V & +#define VecI16VArg VecI16V & +#define QuatVArg QuatV & + +// Optimization for situations in which you cross product multiple vectors with the same vector. +// Avoids 2X shuffles per product +struct VecCrossV +{ + Vec3V mL1; + Vec3V mR1; +}; + +struct VecShiftV +{ + VecI32V shift; +}; +#define VecShiftVArg VecShiftV & + +PX_ALIGN_PREFIX(16) +struct Mat33V +{ + Mat33V() + { + } + Mat33V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec3V PX_ALIGN(16, col0); + Vec3V PX_ALIGN(16, col1); + Vec3V PX_ALIGN(16, col2); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat34V +{ + Mat34V() + { + } + Mat34V(const Vec3V& c0, const Vec3V& c1, const Vec3V& c2, const Vec3V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec3V PX_ALIGN(16, col0); + Vec3V PX_ALIGN(16, col1); + Vec3V PX_ALIGN(16, col2); + Vec3V PX_ALIGN(16, col3); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat43V +{ + Mat43V() + { + } + Mat43V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2) : col0(c0), col1(c1), col2(c2) + { + } + Vec4V PX_ALIGN(16, col0); + Vec4V PX_ALIGN(16, col1); + Vec4V PX_ALIGN(16, col2); +} PX_ALIGN_SUFFIX(16); + +PX_ALIGN_PREFIX(16) +struct Mat44V +{ + Mat44V() + { + } + Mat44V(const Vec4V& c0, const Vec4V& c1, const Vec4V& c2, const Vec4V& c3) : col0(c0), col1(c1), col2(c2), col3(c3) + { + } + Vec4V PX_ALIGN(16, col0); + Vec4V PX_ALIGN(16, col1); + Vec4V PX_ALIGN(16, col2); + Vec4V PX_ALIGN(16, col3); +} PX_ALIGN_SUFFIX(16); + +} // namespace aos +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsFPU.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsFPU.h new file mode 100644 index 000000000..f26a26569 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsFPU.h @@ -0,0 +1,63 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_FPU_H +#define PX_WINDOWS_FPU_H + +PX_INLINE physx::PxSIMDGuard::PxSIMDGuard(bool enable) : mEnabled(enable) +{ +#if !PX_ARM && !PX_A64 + if (enable) + { + mControlWord = _mm_getcsr(); + // set default (disable exceptions: _MM_MASK_MASK) and FTZ (_MM_FLUSH_ZERO_ON), DAZ (_MM_DENORMALS_ZERO_ON: (1<<6)) + _mm_setcsr(_MM_MASK_MASK | _MM_FLUSH_ZERO_ON | (1 << 6)); + } + else + { + PX_ASSERT(_mm_getcsr() & _MM_FLUSH_ZERO_ON); + PX_ASSERT(_mm_getcsr() & (1 << 6)); + PX_ASSERT(_mm_getcsr() & _MM_MASK_MASK); + } +#endif +} + +PX_INLINE physx::PxSIMDGuard::~PxSIMDGuard() +{ +#if !PX_ARM && !PX_A64 + if (mEnabled) + { + // restore control word and clear any exception flags + // (setting exception state flags cause exceptions on the first following fp operation) + _mm_setcsr(mControlWord & ~_MM_EXCEPT_MASK); + } +#endif +} + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsInclude.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsInclude.h new file mode 100644 index 000000000..1385c0cf4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsInclude.h @@ -0,0 +1,96 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_INCLUDE_H +#define PX_WINDOWS_INCLUDE_H + +#ifndef _WIN32 +#error "This file should only be included by Windows builds!!" +#endif + +#ifdef _WINDOWS_ // windows already included +#error "Only include windows.h through this file!!" +#endif + +// We only support >= Windows 7, and we need this for critical section and +// Setting this hides some important APIs (e.g. LoadPackagedLibrary), so don't do it +#define _WIN32_WINNT 0x0601 + +// turn off as much as we can for windows. All we really need is the thread functions(critical sections/Interlocked* +// etc) +#define NOGDICAPMASKS +#define NOVIRTUALKEYCODES +#define NOWINMESSAGES +#define NOWINSTYLES +#define NOSYSMETRICS +#define NOMENUS +#define NOICONS +#define NOKEYSTATES +#define NOSYSCOMMANDS +#define NORASTEROPS +#define NOSHOWWINDOW +#define NOATOM +#define NOCLIPBOARD +#define NOCOLOR +#define NOCTLMGR +#define NODRAWTEXT +#define NOGDI +#define NOMB +#define NOMEMMGR +#define NOMETAFILE +#define NOMINMAX +#define NOOPENFILE +#define NOSCROLL +#define NOSERVICE +#define NOSOUND +#define NOTEXTMETRIC +#define NOWH +#define NOWINOFFSETS +#define NOCOMM +#define NOKANJI +#define NOHELP +#define NOPROFILER +#define NODEFERWINDOWPOS +#define NOMCX +#define WIN32_LEAN_AND_MEAN +// We need a slightly wider API surface for e.g. MultiByteToWideChar +#define NOUSER +#define NONLS +#define NOMSG + +#pragma warning(push) +#pragma warning(disable : 4668) //'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' +#include +#pragma warning(pop) + +#if PX_SSE2 +#include +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsInlineAoS.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsInlineAoS.h new file mode 100644 index 000000000..1bc4f9abe --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsInlineAoS.h @@ -0,0 +1,610 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_INLINE_AOS_H +#define PX_WINDOWS_INLINE_AOS_H + +namespace physx +{ +namespace aos +{ +////////////////////////////////////////////////////////////////////// +//Test that Vec3V and FloatV are legal +////////////////////////////////////////////////////////////////////// + +#define FLOAT_COMPONENTS_EQUAL_THRESHOLD 0.01f +PX_FORCE_INLINE bool isValidFloatV(const FloatV a) +{ + const PxF32 x = V4ReadX(a); + const PxF32 y = V4ReadY(a); + const PxF32 z = V4ReadZ(a); + const PxF32 w = V4ReadW(a); + + return (!(x != y || x != z || x != w)); + + /*if ( + (PxAbs(x - y) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs(x - z) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs(x - w) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) + ) + { + return true; + } + + if ( + (PxAbs((x - y) / x) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs((x - z) / x) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) && + (PxAbs((x - w) / x) < FLOAT_COMPONENTS_EQUAL_THRESHOLD) + ) + { + return true; + } + return false;*/ +} + +} +} + +#include "../PxVecMathSSE.h" + +namespace physx +{ +namespace aos +{ + +///////////////////////////////////////////////////////////////////// +////FUNCTIONS USED ONLY FOR ASSERTS IN VECTORISED IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// USED ONLY INTERNALLY +////////////////////////////////////////////////////////////////////// + +namespace internalSimd +{ +const PX_ALIGN(16, PxU32 gMaskXYZ[4]) = { 0xffffffff, 0xffffffff, 0xffffffff, 0 }; +} //internalSimd + +namespace vecMathTests +{ +PX_FORCE_INLINE bool allElementsEqualBoolV(const BoolV a, const BoolV b) +{ + return internalSimd::BAllTrue4_R(VecI32V_IsEq(a, b)) != 0; +} + +PX_FORCE_INLINE bool allElementsEqualVecI32V(const VecI32V a, const VecI32V b) +{ + BoolV c = internalSimd::m128_I2F(_mm_cmpeq_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); + return internalSimd::BAllTrue4_R(c) != 0; +} + +#define VECMATH_AOS_EPSILON (1e-3f) +static const FloatV minFError = FLoad(-VECMATH_AOS_EPSILON); +static const FloatV maxFError = FLoad(VECMATH_AOS_EPSILON); +static const Vec3V minV3Error = V3Load(-VECMATH_AOS_EPSILON); +static const Vec3V maxV3Error = V3Load(VECMATH_AOS_EPSILON); +static const Vec4V minV4Error = V4Load(-VECMATH_AOS_EPSILON); +static const Vec4V maxV4Error = V4Load(VECMATH_AOS_EPSILON); + +PX_FORCE_INLINE bool allElementsNearEqualFloatV(const FloatV a, const FloatV b) +{ + ASSERT_ISVALIDFLOATV(a); + ASSERT_ISVALIDFLOATV(b); + const FloatV c = FSub(a, b); + return _mm_comigt_ss(c, minFError) && _mm_comilt_ss(c, maxFError); +} + +PX_FORCE_INLINE bool allElementsNearEqualVec3V(const Vec3V a, const Vec3V b) +{ + const Vec3V c = V3Sub(a, b); + return (_mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), minV3Error) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), maxV3Error) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), minV3Error) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), maxV3Error) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), minV3Error) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), maxV3Error)); +} + +PX_FORCE_INLINE bool allElementsNearEqualVec4V(const Vec4V a, const Vec4V b) +{ + const Vec4V c = V4Sub(a, b); + return (_mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), minV4Error) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0)), maxV4Error) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), minV4Error) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1)), maxV4Error) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), minV4Error) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2)), maxV4Error) && + _mm_comigt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(3, 3, 3, 3)), minV4Error) && + _mm_comilt_ss(_mm_shuffle_ps(c, c, _MM_SHUFFLE(3, 3, 3, 3)), maxV4Error)); +} +} //vecMathTests + +PX_FORCE_INLINE bool isFiniteFloatV(const FloatV a) +{ + PxF32 f; + FStore(a, &f); + return PxIsFinite(f); + /* + const PxU32 badNumber = (_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF); + const FloatV vBadNum = FloatV_From_F32((PxF32&)badNumber); + const BoolV vMask = BAnd(vBadNum, a); + return FiniteTestEq(vMask, BFFFF()) == 1; + */ +} + +PX_FORCE_INLINE bool isFiniteVec3V(const Vec3V a) +{ + PX_ALIGN(16, PxF32 f[4]); + V4StoreA((Vec4V&)a, f); + return PxIsFinite(f[0]) && PxIsFinite(f[1]) && PxIsFinite(f[2]); + + /* + const PxU32 badNumber = (_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF); + const Vec3V vBadNum = Vec3V_From_F32((PxF32&)badNumber); + const BoolV vMask = BAnd(BAnd(vBadNum, a), BTTTF()); + return FiniteTestEq(vMask, BFFFF()) == 1; + */ +} + +PX_FORCE_INLINE bool isFiniteVec4V(const Vec4V a) +{ + PX_ALIGN(16, PxF32 f[4]); + V4StoreA(a, f); + return PxIsFinite(f[0]) && PxIsFinite(f[1]) && PxIsFinite(f[2]) && PxIsFinite(f[3]); + + /* + const PxU32 badNumber = (_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF); + const Vec4V vBadNum = Vec4V_From_U32((PxF32&)badNumber); + const BoolV vMask = BAnd(vBadNum, a); + + return FiniteTestEq(vMask, BFFFF()) == 1; + */ +} + +///////////////////////////////////////////////////////////////////// +////VECTORISED FUNCTION IMPLEMENTATIONS +///////////////////////////////////////////////////////////////////// + +PX_FORCE_INLINE Vec3V V3LoadA(const PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + return _mm_and_ps(_mm_load_ps(&f.x), reinterpret_cast(internalSimd::gMaskXYZ)); +} + +// w component of result is undefined +PX_FORCE_INLINE Vec3V V3LoadUnsafeA(const PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + return _mm_load_ps(&f.x); +} + +PX_FORCE_INLINE Vec3V V3LoadA(const PxF32* const f) +{ + ASSERT_ISALIGNED16(f); + return V4ClearW(_mm_load_ps(f)); +} + +PX_FORCE_INLINE void I4StoreA(const VecI32V iv, PxI32* i) +{ + ASSERT_ISALIGNED16(i); + _mm_store_ps((PxF32*)i, iv); +} + +PX_FORCE_INLINE BoolV BLoad(const bool* const f) +{ + const PX_ALIGN(16, PxU32 b[4]) = { PxU32(-(PxI32)f[0]), PxU32(-(PxI32)f[1]), + PxU32(-(PxI32)f[2]), PxU32(-(PxI32)f[3]) }; + return _mm_load_ps((float*)&b); +} + +PX_FORCE_INLINE void V3StoreA(const Vec3V a, PxVec3& f) +{ + ASSERT_ISALIGNED16(&f); + PX_ALIGN(16, PxF32 f2[4]); + _mm_store_ps(f2, a); + f = PxVec3(f2[0], f2[1], f2[2]); +} + +PX_FORCE_INLINE void V3StoreU(const Vec3V a, PxVec3& f) +{ + PX_ALIGN(16, PxF32 f2[4]); + _mm_store_ps(f2, a); + f = PxVec3(f2[0], f2[1], f2[2]); +} + +////////////////////////////////// +// FLOATV +////////////////////////////////// + +PX_FORCE_INLINE FloatV FAbs(const FloatV a) +{ + ASSERT_ISVALIDFLOATV(a); + PX_ALIGN(16, const static PxU32 absMask[4]) = { 0x7fFFffFF, 0x7fFFffFF, 0x7fFFffFF, 0x7fFFffFF }; + return _mm_and_ps(a, _mm_load_ps(reinterpret_cast(absMask))); +} + +////////////////////////////////// +// VEC3V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V V3UnitX() +{ + const PX_ALIGN(16, PxF32 x[4]) = { 1.0f, 0.0f, 0.0f, 0.0f }; + const __m128 x128 = _mm_load_ps(x); + return x128; +} + +PX_FORCE_INLINE Vec3V V3UnitY() +{ + const PX_ALIGN(16, PxF32 y[4]) = { 0.0f, 1.0f, 0.0f, 0.0f }; + const __m128 y128 = _mm_load_ps(y); + return y128; +} + +PX_FORCE_INLINE Vec3V V3UnitZ() +{ + const PX_ALIGN(16, PxF32 z[4]) = { 0.0f, 0.0f, 1.0f, 0.0f }; + const __m128 z128 = _mm_load_ps(z); + return z128; +} + +////////////////////////////////// +// VEC4V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V V4UnitW() +{ + const PX_ALIGN(16, PxF32 w[4]) = { 0.0f, 0.0f, 0.0f, 1.0f }; + const __m128 w128 = _mm_load_ps(w); + return w128; +} + +PX_FORCE_INLINE Vec4V V4UnitX() +{ + const PX_ALIGN(16, PxF32 x[4]) = { 1.0f, 0.0f, 0.0f, 0.0f }; + const __m128 x128 = _mm_load_ps(x); + return x128; +} + +PX_FORCE_INLINE Vec4V V4UnitY() +{ + const PX_ALIGN(16, PxF32 y[4]) = { 0.0f, 1.0f, 0.0f, 0.0f }; + const __m128 y128 = _mm_load_ps(y); + return y128; +} + +PX_FORCE_INLINE Vec4V V4UnitZ() +{ + const PX_ALIGN(16, PxF32 z[4]) = { 0.0f, 0.0f, 1.0f, 0.0f }; + const __m128 z128 = _mm_load_ps(z); + return z128; +} + +PX_FORCE_INLINE Vec4V V4ClearW(const Vec4V v) +{ + return _mm_and_ps(v, (VecI32V&)internalSimd::gMaskXYZ); +} + +////////////////////////////////// +// BoolV +////////////////////////////////// + +template +BoolV BSplatElement(BoolV a) +{ + return internalSimd::m128_I2F( + _mm_shuffle_epi32(internalSimd::m128_F2I(a), _MM_SHUFFLE(index, index, index, index))); +} + +////////////////////////////////// +// MAT33V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M33TrnspsMulV3(const Mat33V& a, const Vec3V b) +{ + Vec3V v0 = V3Mul(a.col0, b); + Vec3V v1 = V3Mul(a.col1, b); + Vec3V v2 = V3Mul(a.col2, b); + V3Transpose(v0, v1, v2); + return V3Add(V3Add(v0, v1), v2); +} + +PX_FORCE_INLINE Mat33V M33Trnsps(const Mat33V& a) +{ + Vec3V col0 = a.col0, col1 = a.col1, col2 = a.col2; + V3Transpose(col0, col1, col2); + return Mat33V(col0, col1, col2); +} + +////////////////////////////////// +// MAT34V +////////////////////////////////// + +PX_FORCE_INLINE Vec3V M34TrnspsMul33V3(const Mat34V& a, const Vec3V b) +{ + Vec3V v0 = V3Mul(a.col0, b); + Vec3V v1 = V3Mul(a.col1, b); + Vec3V v2 = V3Mul(a.col2, b); + V3Transpose(v0, v1, v2); + return V3Add(V3Add(v0, v1), v2); +} + +PX_FORCE_INLINE Mat33V M34Trnsps33(const Mat34V& a) +{ + Vec3V col0 = a.col0, col1 = a.col1, col2 = a.col2; + V3Transpose(col0, col1, col2); + return Mat33V(col0, col1, col2); +} + +/*PX_FORCE_INLINE Mat34V M34Inverse(const Mat34V& a) +{ + Mat34V aInv; + const BoolV tfft = BTFFT(); + const BoolV tttf = BTTTF(); + const FloatV zero = V3Zero(); + const Vec3V cross01 = V3Cross(a.col0, a.col1); + const Vec3V cross12 = V3Cross(a.col1, a.col2); + const Vec3V cross20 = V3Cross(a.col2, a.col0); + const FloatV dot = V3Dot(cross01, a.col2); + const FloatV invDet = _mm_rcp_ps(dot); + const Vec3V mergeh = _mm_unpacklo_ps(cross12, cross01); + const Vec3V mergel = _mm_unpackhi_ps(cross12, cross01); + Vec3V colInv0 = _mm_unpacklo_ps(mergeh, cross20); + colInv0 = _mm_or_ps(_mm_andnot_ps(tttf, zero), _mm_and_ps(tttf, colInv0)); + const Vec3V zppd = _mm_shuffle_ps(mergeh, cross20, _MM_SHUFFLE(3, 0, 0, 2)); + const Vec3V pbwp = _mm_shuffle_ps(cross20, mergeh, _MM_SHUFFLE(3, 3, 1, 0)); + const Vec3V colInv1 = _mm_or_ps(_mm_andnot_ps(BTFFT(), pbwp), _mm_and_ps(BTFFT(), zppd)); + const Vec3V xppd = _mm_shuffle_ps(mergel, cross20, _MM_SHUFFLE(3, 0, 0, 0)); + const Vec3V pcyp = _mm_shuffle_ps(cross20, mergel, _MM_SHUFFLE(3, 1, 2, 0)); + const Vec3V colInv2 = _mm_or_ps(_mm_andnot_ps(tfft, pcyp), _mm_and_ps(tfft, xppd)); + aInv.col0 = _mm_mul_ps(colInv0, invDet); + aInv.col1 = _mm_mul_ps(colInv1, invDet); + aInv.col2 = _mm_mul_ps(colInv2, invDet); + aInv.col3 = M34Mul33V3(aInv, V3Neg(a.col3)); + return aInv; +}*/ + +////////////////////////////////// +// MAT44V +////////////////////////////////// + +PX_FORCE_INLINE Vec4V M44TrnspsMulV4(const Mat44V& a, const Vec4V b) +{ + Vec4V v0 = V4Mul(a.col0, b); + Vec4V v1 = V4Mul(a.col1, b); + Vec4V v2 = V4Mul(a.col2, b); + Vec4V v3 = V4Mul(a.col3, b); + V4Transpose(v0, v1, v2, v3); + return V4Add(V4Add(v0, v1), V4Add(v2, v3)); +} + +PX_FORCE_INLINE Mat44V M44Trnsps(const Mat44V& a) +{ + Vec4V col0 = a.col0, col1 = a.col1, col2 = a.col2, col3 = a.col3; + V4Transpose(col0, col1, col2, col3); + return Mat44V(col0, col1, col2, col3); +} + +////////////////////////////////// +// Misc +////////////////////////////////// + +PX_FORCE_INLINE VecI32V I4LoadXYZW(const PxI32& x, const PxI32& y, const PxI32& z, const PxI32& w) +{ + return internalSimd::m128_I2F(_mm_set_epi32(w, z, y, x)); +} + +PX_FORCE_INLINE VecI32V I4Load(const PxI32 i) +{ + return _mm_load1_ps(reinterpret_cast(&i)); +} + +PX_FORCE_INLINE VecI32V I4LoadU(const PxI32* i) +{ + return _mm_loadu_ps(reinterpret_cast(i)); +} + +PX_FORCE_INLINE VecI32V I4LoadA(const PxI32* i) +{ + ASSERT_ISALIGNED16(i); + return _mm_load_ps(reinterpret_cast(i)); +} + +PX_FORCE_INLINE VecI32V VecI32V_Add(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_add_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE VecI32V VecI32V_Sub(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_sub_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE BoolV VecI32V_IsGrtr(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_cmpgt_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE BoolV VecI32V_IsEq(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_cmpeq_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE VecI32V V4I32Sel(const BoolV c, const VecI32V a, const VecI32V b) +{ + return V4U32Sel(c, a, b); +} + +PX_FORCE_INLINE VecI32V VecI32V_Zero() +{ + return V4Zero(); // PT: TODO: unify VecI32V / VecU32V on Windows / Linux, not the same types (?!) +} + +PX_FORCE_INLINE VecI32V VecI32V_Sel(const BoolV c, const VecI32VArg a, const VecI32VArg b) +{ + PX_ASSERT(vecMathTests::allElementsEqualBoolV(c, BTTTT()) || + vecMathTests::allElementsEqualBoolV(c, BFFFF())); + return _mm_or_ps(_mm_andnot_ps(c, b), _mm_and_ps(c, a)); +} + +PX_FORCE_INLINE VecShiftV VecI32V_PrepareShift(const VecI32VArg shift) +{ + VecShiftV preparedShift; + preparedShift.shift = _mm_or_ps(_mm_andnot_ps(BTFFF(), VecI32V_Zero()), _mm_and_ps(BTFFF(), shift)); + return preparedShift; +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const VecShiftVArg count) +{ + return internalSimd::m128_I2F(_mm_sll_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(count.shift))); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const VecShiftVArg count) +{ + return internalSimd::m128_I2F(_mm_srl_epi32(internalSimd::m128_F2I(a), internalSimd::m128_F2I(count.shift))); +} + +PX_FORCE_INLINE VecI32V VecI32V_LeftShift(const VecI32VArg a, const PxU32 count) +{ + return internalSimd::m128_I2F(_mm_slli_epi32(internalSimd::m128_F2I(a), count)); +} + +PX_FORCE_INLINE VecI32V VecI32V_RightShift(const VecI32VArg a, const PxU32 count) +{ + return internalSimd::m128_I2F(_mm_srai_epi32(internalSimd::m128_F2I(a), count)); +} + +PX_FORCE_INLINE VecI32V VecI32V_And(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_and_si128(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE VecI32V VecI32V_Or(const VecI32VArg a, const VecI32VArg b) +{ + return internalSimd::m128_I2F(_mm_or_si128(internalSimd::m128_F2I(a), internalSimd::m128_F2I(b))); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetX(const VecI32VArg a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetY(const VecI32VArg a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetZ(const VecI32VArg a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)); +} + +PX_FORCE_INLINE VecI32V VecI32V_GetW(const VecI32VArg a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 3, 3, 3)); +} + +PX_FORCE_INLINE void PxI32_From_VecI32V(const VecI32VArg a, PxI32* i) +{ + _mm_store_ss(reinterpret_cast(i), a); +} + +PX_FORCE_INLINE VecI32V VecI32V_From_BoolV(const BoolVArg a) +{ + return a; +} + +PX_FORCE_INLINE VecU32V VecU32V_From_BoolV(const BoolVArg a) +{ + return a; +} + +PX_FORCE_INLINE VecI32V VecI32V_Merge(const VecI32VArg a, const VecI32VArg b, const VecI32VArg c, const VecI32VArg d) +{ + const __m128 xw = _mm_move_ss(b, a); // y, y, y, x + const __m128 yz = _mm_move_ss(c, d); // z, z, z, w + return _mm_shuffle_ps(xw, yz, _MM_SHUFFLE(0, 2, 1, 0)); +} + +PX_FORCE_INLINE void V4U32StoreAligned(VecU32V val, VecU32V* address) +{ + *address = val; +} + +PX_FORCE_INLINE Vec4V Vec4V_From_VecI32V(VecI32V a) +{ + return _mm_cvtepi32_ps(internalSimd::m128_F2I(a)); +} + +PX_FORCE_INLINE VecI32V VecI32V_From_Vec4V(Vec4V a) +{ + return internalSimd::m128_I2F(_mm_cvttps_epi32(a)); +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecU32V(VecU32V a) +{ + return Vec4V(a); +} + +PX_FORCE_INLINE Vec4V Vec4V_ReinterpretFrom_VecI32V(VecI32V a) +{ + return Vec4V(a); +} + +PX_FORCE_INLINE VecU32V VecU32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + return VecU32V(a); +} + +PX_FORCE_INLINE VecI32V VecI32V_ReinterpretFrom_Vec4V(Vec4V a) +{ + return VecI32V(a); +} + +template +PX_FORCE_INLINE VecU32V V4U32SplatElement(VecU32V a) +{ + return internalSimd::m128_I2F(_mm_shuffle_epi32(internalSimd::m128_F2I(a), _MM_SHUFFLE(index, index, index, index))); +} + +template +PX_FORCE_INLINE Vec4V V4SplatElement(Vec4V a) +{ + return internalSimd::m128_I2F(_mm_shuffle_epi32(internalSimd::m128_F2I(a), _MM_SHUFFLE(index, index, index, index))); +} + +/*PX_FORCE_INLINE Vec4V V4ConvertFromI32V(const VecI32V in) +{ + return _mm_cvtepi32_ps(internalSimd::m128_F2I(in)); +}*/ + +} // namespace aos +} // namespace physx + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsIntrinsics.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsIntrinsics.h new file mode 100644 index 000000000..80131614e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsIntrinsics.h @@ -0,0 +1,201 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_INTRINSICS_H +#define PX_WINDOWS_INTRINSICS_H + +#include "foundation/PxAssert.h" +#include + +// this file is for internal intrinsics - that is, intrinsics that are used in +// cross platform code but do not appear in the API + +#if !PX_WINDOWS_FAMILY +#error "This file should only be included by Windows builds!!" +#endif + +#pragma intrinsic(memcmp) +#pragma intrinsic(memcpy) +#pragma intrinsic(memset) + +#pragma warning(push) +//'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' +#pragma warning(disable : 4668) +#if PX_VC == 10 +#pragma warning(disable : 4987) // nonstandard extension used: 'throw (...)' +#endif +#include +#pragma warning(pop) + +#pragma warning(push) +#pragma warning(disable : 4985) // 'symbol name': attributes not present on previous declaration +#include +#pragma warning(pop) + +#include +// do not include for ARM target +#if !PX_ARM && !PX_A64 +#include +#endif + +#pragma intrinsic(_BitScanForward) +#pragma intrinsic(_BitScanReverse) + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/* +* Implements a memory barrier +*/ +PX_FORCE_INLINE void PxMemoryBarrier() +{ + _ReadWriteBarrier(); + /* long Barrier; + __asm { + xchg Barrier, eax + }*/ +} + +/*! +Returns the index of the highest set bit. Not valid for zero arg. +*/ +PX_FORCE_INLINE uint32_t PxHighestSetBitUnsafe(uint64_t v) +{ + unsigned long retval; +#ifndef PX_GENERATE_META_DATA + _BitScanReverse64(&retval, v); +#endif + return retval; +} + +/*! +Returns the index of the highest set bit. Not valid for zero arg. +*/ +PX_FORCE_INLINE uint32_t PxHighestSetBitUnsafe(uint32_t v) +{ + unsigned long retval; + _BitScanReverse(&retval, v); + return retval; +} + +/*! +Returns the index of the lowest set bit. Undefined for zero arg. +*/ +PX_FORCE_INLINE uint32_t PxLowestSetBitUnsafe(uint64_t v) +{ + unsigned long retval; +#ifndef PX_GENERATE_META_DATA + _BitScanForward64(&retval, v); +#endif + return retval; +} + +/*! +Returns the index of the lowest set bit. Undefined for zero arg. +*/ +PX_FORCE_INLINE uint32_t PxLowestSetBitUnsafe(uint32_t v) +{ + unsigned long retval; + _BitScanForward(&retval, v); + return retval; +} + +/*! +Returns the number of leading zeros in v. Returns 32 for v=0. +*/ +PX_FORCE_INLINE uint32_t PxCountLeadingZeros(uint32_t v) +{ + if(v) + { + unsigned long bsr = (unsigned long)-1; + _BitScanReverse(&bsr, v); + return 31 - bsr; + } + else + return 32; +} + +/*! +Prefetch aligned cache size around \c ptr+offset. +*/ +#if !PX_ARM && !PX_A64 +PX_FORCE_INLINE void PxPrefetchLine(const void* ptr, uint32_t offset = 0) +{ + // cache line on X86/X64 is 64-bytes so a 128-byte prefetch would require 2 prefetches. + // However, we can only dispatch a limited number of prefetch instructions so we opt to prefetch just 1 cache line + /*_mm_prefetch(((const char*)ptr + offset), _MM_HINT_T0);*/ + // We get slightly better performance prefetching to non-temporal addresses instead of all cache levels + _mm_prefetch(((const char*)ptr + offset), _MM_HINT_NTA); +} +#else +PX_FORCE_INLINE void PxPrefetchLine(const void* ptr, uint32_t offset = 0) +{ + // arm does have 32b cache line size + __prefetch(((const char*)ptr + offset)); +} +#endif + +/*! +Prefetch \c count bytes starting at \c ptr. +*/ +#if !PX_ARM +PX_FORCE_INLINE void PxPrefetch(const void* ptr, uint32_t count = 1) +{ + const char* cp = (char*)ptr; + uint64_t p = size_t(ptr); + uint64_t startLine = p >> 6, endLine = (p + count - 1) >> 6; + uint64_t lines = endLine - startLine + 1; + do + { + PxPrefetchLine(cp); + cp += 64; + } while(--lines); +} +#else +PX_FORCE_INLINE void PxPrefetch(const void* ptr, uint32_t count = 1) +{ + const char* cp = (char*)ptr; + uint32_t p = size_t(ptr); + uint32_t startLine = p >> 5, endLine = (p + count - 1) >> 5; + uint32_t lines = endLine - startLine + 1; + do + { + PxPrefetchLine(cp); + cp += 32; + } while(--lines); +} +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsMathIntrinsics.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsMathIntrinsics.h new file mode 100644 index 000000000..94c5c7778 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsMathIntrinsics.h @@ -0,0 +1,178 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_MATH_INTRINSICS_H +#define PX_WINDOWS_MATH_INTRINSICS_H + +#include "foundation/PxAssert.h" + +#if !PX_WINDOWS_FAMILY +#error "This file should only be included by Windows builds!!" +#endif + +#include +#include + +#if !PX_DOXYGEN +namespace physx +{ +namespace intrinsics +{ +#endif + +//! \brief platform-specific absolute value +PX_CUDA_CALLABLE PX_FORCE_INLINE float abs(float a) +{ + return ::fabsf(a); +} + +//! \brief platform-specific select float +PX_CUDA_CALLABLE PX_FORCE_INLINE float fsel(float a, float b, float c) +{ + return (a >= 0.0f) ? b : c; +} + +//! \brief platform-specific sign +PX_CUDA_CALLABLE PX_FORCE_INLINE float sign(float a) +{ + return (a >= 0.0f) ? 1.0f : -1.0f; +} + +//! \brief platform-specific reciprocal +PX_CUDA_CALLABLE PX_FORCE_INLINE float recip(float a) +{ + return 1.0f / a; +} + +//! \brief platform-specific reciprocal estimate +PX_CUDA_CALLABLE PX_FORCE_INLINE float recipFast(float a) +{ + return 1.0f / a; +} + +//! \brief platform-specific square root +PX_CUDA_CALLABLE PX_FORCE_INLINE float sqrt(float a) +{ + return ::sqrtf(a); +} + +//! \brief platform-specific reciprocal square root +PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrt(float a) +{ + return 1.0f / ::sqrtf(a); +} + +//! \brief platform-specific reciprocal square root estimate +PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrtFast(float a) +{ + return 1.0f / ::sqrtf(a); +} + +//! \brief platform-specific sine +PX_CUDA_CALLABLE PX_FORCE_INLINE float sin(float a) +{ + return ::sinf(a); +} + +//! \brief platform-specific cosine +PX_CUDA_CALLABLE PX_FORCE_INLINE float cos(float a) +{ + return ::cosf(a); +} + +//! \brief platform-specific minimum +PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMin(float a, float b) +{ + return a < b ? a : b; +} + +//! \brief platform-specific maximum +PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMax(float a, float b) +{ + return a > b ? a : b; +} + +//! \brief platform-specific finiteness check (not INF or NAN) +PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(float a) +{ +#if PX_CUDA_COMPILER + return !!isfinite(a); +#else + return (0 == ((_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF) & _fpclass(a))); +#endif +} + +//! \brief platform-specific finiteness check (not INF or NAN) +PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(double a) +{ +#if PX_CUDA_COMPILER + return !!isfinite(a); +#else + return (0 == ((_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF) & _fpclass(a))); +#endif +} + +/*! +Sets \c count bytes starting at \c dst to zero. +*/ +PX_FORCE_INLINE void* memZero(void* dest, size_t count) +{ + return memset(dest, 0, count); +} + +/*! +Sets \c count bytes starting at \c dst to \c c. +*/ +PX_FORCE_INLINE void* memSet(void* dest, int32_t c, size_t count) +{ + return memset(dest, c, count); +} + +/*! +Copies \c count bytes from \c src to \c dst. User memMove if regions overlap. +*/ +PX_FORCE_INLINE void* memCopy(void* dest, const void* src, size_t count) +{ + return memcpy(dest, src, count); +} + +/*! +Copies \c count bytes from \c src to \c dst. Supports overlapping regions. +*/ +PX_FORCE_INLINE void* memMove(void* dest, const void* src, size_t count) +{ + return memmove(dest, src, count); +} + +#if !PX_DOXYGEN +} // namespace intrinsics +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsTrigConstants.h b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsTrigConstants.h new file mode 100644 index 000000000..58180c842 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/foundation/windows/PxWindowsTrigConstants.h @@ -0,0 +1,60 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_WINDOWS_TRIG_CONSTANTS_H +#define PX_WINDOWS_TRIG_CONSTANTS_H + +namespace physx +{ +namespace aos +{ + +#define PX_GLOBALCONST extern const __declspec(selectany) + +__declspec(align(16)) struct PX_VECTORF32 +{ + float f[4]; +}; + +PX_GLOBALCONST PX_VECTORF32 g_PXSinCoefficients0 = { { 1.0f, -0.166666667f, 8.333333333e-3f, -1.984126984e-4f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXSinCoefficients1 = { { 2.755731922e-6f, -2.505210839e-8f, 1.605904384e-10f, -7.647163732e-13f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXSinCoefficients2 = { { 2.811457254e-15f, -8.220635247e-18f, 1.957294106e-20f, -3.868170171e-23f } }; +PX_GLOBALCONST PX_VECTORF32 g_PXCosCoefficients0 = { { 1.0f, -0.5f, 4.166666667e-2f, -1.388888889e-3f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXCosCoefficients1 = { { 2.480158730e-5f, -2.755731922e-7f, 2.087675699e-9f, -1.147074560e-11f } }; +PX_GLOBALCONST PX_VECTORF32 +g_PXCosCoefficients2 = { { 4.779477332e-14f, -1.561920697e-16f, 4.110317623e-19f, -8.896791392e-22f } }; +PX_GLOBALCONST PX_VECTORF32 g_PXReciprocalTwoPi = { { PxInvTwoPi, PxInvTwoPi, PxInvTwoPi, PxInvTwoPi } }; +PX_GLOBALCONST PX_VECTORF32 g_PXTwoPi = { { PxTwoPi, PxTwoPi, PxTwoPi, PxTwoPi } }; + +} // namespace aos +} // namespace physx + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBVH.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBVH.h new file mode 100644 index 000000000..cc3c8b4c9 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBVH.h @@ -0,0 +1,282 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BVH_H +#define PX_BVH_H + +#include "common/PxBase.h" +#include "foundation/PxTransform.h" +#include "foundation/PxBounds3.h" +#include "geometry/PxGeometryQueryFlags.h" +#include "geometry/PxReportCallback.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxGeometry; +class PxPlane; + +/** +\brief Class representing a bounding volume hierarchy. + +PxBVH can be provided to PxScene::addActor. In this case the scene query +pruning structure inside PhysX SDK will store/update one bound per actor. +The scene queries against such an actor will query actor bounds and then +make a local space query against the provided BVH, which is in actor's +local space. + +PxBVH can also be used as a standalone data-structure for arbitrary +purposes, unrelated to PxScene / PxActor. + +\see PxScene::addActor +*/ +class PxBVH : public PxBase +{ +public: + + struct RaycastCallback + { + RaycastCallback() {} + virtual ~RaycastCallback() {} + + // Reports one raycast or sweep hit. + // boundsIndex [in] Index of touched bounds + // distance [in/out] Impact distance. Shrinks the ray if written out. + // return false to abort the query + virtual bool reportHit(PxU32 boundsIndex, PxReal& distance) = 0; + }; + + struct OverlapCallback + { + OverlapCallback() {} + virtual ~OverlapCallback() {} + + // Reports one overlap hit. + // boundsIndex [in] Index of touched bounds + // return false to abort the query + virtual bool reportHit(PxU32 boundsIndex) = 0; + }; + + struct TraversalCallback + { + TraversalCallback() {} + virtual ~TraversalCallback() {} + + // Reports one visited node. + // bounds [in] node bounds + // return true to continue traversing this branch + virtual bool visitNode(const PxBounds3& bounds) = 0; + + // Reports one validated leaf node. Called on leaf nodes after visitNode returns true on them. + // nbPrims [in] number of primitives in the node + // prims [in] primitives in the node (nbPrims entries) + // return false to abort the query + virtual bool reportLeaf(PxU32 nbPrims, const PxU32* prims) = 0; + }; + + /** + \brief Raycast test against a BVH. + + \param[in] origin The origin of the ray. + \param[in] unitDir Normalized direction of the ray. + \param[in] maxDist Maximum ray length, has to be in the [0, inf) range + \param[in] cb Raycast callback, called once per hit + \param[in] queryFlags Optional flags controlling the query. + \return false if query has been aborted + */ + virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, RaycastCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0; + + /** + \brief Sweep test against a BVH. + + \param[in] geom The query volume + \param[in] pose The pose of the query volume + \param[in] unitDir Normalized direction of the sweep. + \param[in] maxDist Maximum sweep length, has to be in the [0, inf) range + \param[in] cb Raycast callback, called once per hit + \param[in] queryFlags Optional flags controlling the query. + \return false if query has been aborted + */ + virtual bool sweep(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, RaycastCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0; + + /** + \brief Overlap test against a BVH. + + \param[in] geom The query volume + \param[in] pose The pose of the query volume + \param[in] cb Overlap callback, called once per hit + \param[in] queryFlags Optional flags controlling the query. + \return false if query has been aborted + */ + virtual bool overlap(const PxGeometry& geom, const PxTransform& pose, OverlapCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0; + + /** + \brief Frustum culling test against a BVH. + + This is similar in spirit to an overlap query using a convex object around the frustum. + However this specialized query has better performance, and can support more than the 6 planes + of a frustum, which can be useful in portal-based engines. + + On the other hand this test only returns a conservative number of bounds, i.e. some of the returned + bounds may actually be outside the frustum volume, close to it but not touching it. This is usually + an ok performance trade-off when the function is used for view-frustum culling. + + \param[in] nbPlanes Number of planes. Only 32 planes max are supported. + \param[in] planes Array of planes, should be in the same space as the BVH. + \param[in] cb Overlap callback, called once per visible object + \param[in] queryFlags Optional flags controlling the query. + \return false if query has been aborted + */ + virtual bool cull(PxU32 nbPlanes, const PxPlane* planes, OverlapCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0; + + /** + \brief Returns the number of bounds in the BVH. + + You can use #getBounds() to retrieve the bounds. + + \note These are the user-defined bounds passed to the BVH builder, not the internal bounds around each BVH node. + + \return Number of bounds in the BVH. + + \see getBounds() getBoundsForModification() + */ + virtual PxU32 getNbBounds() const = 0; + + /** + \brief Retrieve the read-only bounds in the BVH. + + \note These are the user-defined bounds passed to the BVH builder, not the internal bounds around each BVH node. + + \see PxBounds3 getNbBounds() getBoundsForModification() + */ + virtual const PxBounds3* getBounds() const = 0; + + /** + \brief Retrieve the bounds in the BVH. + + These bounds can be modified. Call refit() after modifications are done. + + \note These are the user-defined bounds passed to the BVH builder, not the internal bounds around each BVH node. + + \see PxBounds3 getNbBounds() getBounds() refit() updateBounds() partialRefit() + */ + PX_FORCE_INLINE PxBounds3* getBoundsForModification() + { + return const_cast(getBounds()); + } + + /** + \brief Refit the BVH. + + This function "refits" the tree, i.e. takes the new (leaf) bounding boxes into account and + recomputes all the BVH bounds accordingly. This is an O(n) operation with n = number of bounds in the BVH. + + This works best with minor bounds modifications, i.e. when the bounds remain close to their initial values. + With large modifications the tree quality degrades more and more, and subsequent query performance suffers. + It might be a better strategy to create a brand new BVH if bounds change drastically. + + This function refits the whole tree after an arbitrary number of bounds have potentially been modified by + users (via getBoundsForModification()). If you only have a small number of bounds to update, it might be + more efficient to use setBounds() and partialRefit() instead. + + \see getNbBounds() getBoundsForModification() updateBounds() partialRefit() + */ + virtual void refit() = 0; + + /** + \brief Update single bounds. + + This is an alternative to getBoundsForModification() / refit(). If you only have a small set of bounds to + update, it can be inefficient to call the refit() function, because it refits the whole BVH. + + Instead, one can update individual bounds with this updateBounds() function. It sets the new bounds and + marks the corresponding BVH nodes for partial refit. Once all the individual bounds have been updated, + call partialRefit() to only refit the subset of marked nodes. + + \param[in] boundsIndex Index of updated bounds. Valid range is between 0 and getNbBounds(). + \param[in] newBounds Updated bounds. + + \return true if success + + \see getNbBounds() getBoundsForModification() refit() partialRefit() + */ + virtual bool updateBounds(PxU32 boundsIndex, const PxBounds3& newBounds) = 0; + + /** + \brief Refits subset of marked nodes. + + This is an alternative to the refit() function, to be called after updateBounds() calls. + See updateBounds() for details. + + \see getNbBounds() getBoundsForModification() refit() updateBounds() + */ + virtual void partialRefit() = 0; + + /** + \brief Generic BVH traversal function. + + This can be used to implement custom BVH traversal functions if provided ones are not enough. + In particular this can be used to visualize the tree's bounds. + + \param[in] cb Traversal callback, called for each visited node + \return false if query has been aborted + */ + virtual bool traverse(TraversalCallback& cb) const = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxBVH"; } +protected: + PX_INLINE PxBVH(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {} + PX_INLINE PxBVH(PxBaseFlags baseFlags) : PxBase(baseFlags) {} + virtual ~PxBVH() {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBVH", PxBase); } +}; + + struct PxGeomIndexPair; + + /** + \brief BVH-vs-BVH overlap test + + This function returns pairs of box indices that belong to both the first & second input bvhs. + + \param[in] callback The callback object used to report results + \param[in] bvh0 First bvh + \param[in] bvh1 Second bvh + \return true if an overlap has been detected + + \see PxBVH PxReportCallback + */ + PX_C_EXPORT PX_PHYSX_COMMON_API bool PX_CALL_CONV PxFindOverlap(PxReportCallback& callback, const PxBVH& bvh0, const PxBVH& bvh1); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBVHBuildStrategy.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBVHBuildStrategy.h new file mode 100644 index 000000000..e7d514397 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBVHBuildStrategy.h @@ -0,0 +1,58 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BVH_BUILD_STRATEGY_H +#define PX_BVH_BUILD_STRATEGY_H + +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Desired build strategy for bounding-volume hierarchies +*/ +struct PxBVHBuildStrategy +{ + enum Enum + { + eFAST = 0, //!< Fast build strategy. Fast build speed, good runtime performance in most cases. Recommended for runtime cooking. + eDEFAULT = 1, //!< Default build strategy. Medium build speed, good runtime performance in all cases. + eSAH = 2, //!< SAH build strategy. Slower builds, slightly improved runtime performance in some cases. + + eLAST + }; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBoxGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBoxGeometry.h new file mode 100644 index 000000000..92dab5833 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxBoxGeometry.h @@ -0,0 +1,113 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_BOX_GEOMETRY_H +#define PX_BOX_GEOMETRY_H +#include "geometry/PxGeometry.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Class representing the geometry of a box. + +The geometry of a box can be fully specified by its half extents. This is the half of its width, height, and depth. +\note The scaling of the box is expected to be baked into these values, there is no additional scaling parameter. +*/ +class PxBoxGeometry : public PxGeometry +{ +public: + /** + \brief Constructor to initialize half extents from scalar parameters. + \param hx Initial half extents' x component. + \param hy Initial half extents' y component. + \param hz Initial half extents' z component. + */ + PX_INLINE PxBoxGeometry(PxReal hx=0.0f, PxReal hy=0.0f, PxReal hz=0.0f) : PxGeometry(PxGeometryType::eBOX), halfExtents(hx, hy, hz) {} + + /** + \brief Constructor to initialize half extents from vector parameter. + \param halfExtents_ Initial half extents. + */ + PX_INLINE PxBoxGeometry(PxVec3 halfExtents_) : PxGeometry(PxGeometryType::eBOX), halfExtents(halfExtents_) {} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxBoxGeometry(const PxBoxGeometry& that) : PxGeometry(that), halfExtents(that.halfExtents) {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxBoxGeometry& that) + { + mType = that.mType; + halfExtents = that.halfExtents; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid + + \note A valid box has a positive extent in each direction (halfExtents.x > 0, halfExtents.y > 0, halfExtents.z > 0). + It is illegal to call PxPhysics::createShape with a box that has zero extent in any direction. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + +public: + /** + \brief Half of the width, height, and depth of the box. + */ + PxVec3 halfExtents; +}; + +PX_INLINE bool PxBoxGeometry::isValid() const +{ + if(mType != PxGeometryType::eBOX) + return false; + if(!halfExtents.isFinite()) + return false; + if(halfExtents.x <= 0.0f || halfExtents.y <= 0.0f || halfExtents.z <= 0.0f) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxCapsuleGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxCapsuleGeometry.h new file mode 100644 index 000000000..bd5ad868a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxCapsuleGeometry.h @@ -0,0 +1,115 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CAPSULE_GEOMETRY_H +#define PX_CAPSULE_GEOMETRY_H +#include "geometry/PxGeometry.h" +#include "foundation/PxFoundationConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Class representing the geometry of a capsule. + +Capsules are shaped as the union of a cylinder of length 2 * halfHeight and with the +given radius centered at the origin and extending along the x axis, and two hemispherical ends. +\note The scaling of the capsule is expected to be baked into these values, there is no additional scaling parameter. + +The function PxTransformFromSegment is a helper for generating an appropriate transform for the capsule from the capsule's interior line segment. + +\see PxTransformFromSegment +*/ +class PxCapsuleGeometry : public PxGeometry +{ +public: + /** + \brief Constructor, initializes to a capsule with passed radius and half height. + */ + PX_INLINE PxCapsuleGeometry(PxReal radius_=0.0f, PxReal halfHeight_=0.0f) : PxGeometry(PxGeometryType::eCAPSULE), radius(radius_), halfHeight(halfHeight_) {} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxCapsuleGeometry(const PxCapsuleGeometry& that) : PxGeometry(that), radius(that.radius), halfHeight(that.halfHeight) {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxCapsuleGeometry& that) + { + mType = that.mType; + radius = that.radius; + halfHeight = that.halfHeight; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid. + + \note A valid capsule has radius > 0, halfHeight >= 0. + It is illegal to call PxPhysics::createShape with a capsule that has zero radius or height. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + +public: + /** + \brief The radius of the capsule. + */ + PxReal radius; + + /** + \brief half of the capsule's height, measured between the centers of the hemispherical ends. + */ + PxReal halfHeight; +}; + +PX_INLINE bool PxCapsuleGeometry::isValid() const +{ + if(mType != PxGeometryType::eCAPSULE) + return false; + if(!PxIsFinite(radius) || !PxIsFinite(halfHeight)) + return false; + if(radius <= 0.0f || halfHeight < 0.0f) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexCoreGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexCoreGeometry.h new file mode 100644 index 000000000..ca18a91c4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexCoreGeometry.h @@ -0,0 +1,360 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONVEX_CORE_GEOMETRY_H +#define PX_CONVEX_CORE_GEOMETRY_H + +#include "foundation/PxVec3.h" +#include "foundation/PxMemory.h" +#include "geometry/PxGeometry.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Pre-authored cores for convex core geometry + */ + class PxConvexCore + { + public: + /** + \brief Enumeration of core types for convex core geometries. + + This enum defines the various cores that can be used as the basis + for creating convex core geometries. Each type represents a different + fundamental shape that can be extended with a margin to create more + complex convex shapes. + */ + enum Type + { + ePOINT, + eSEGMENT, + eBOX, + eELLIPSOID, + eCYLINDER, + eCONE, + + eCOUNT + }; + + /** + \brief Point core data + + The point core has no additional data. The point is located + at the origin of the geometry's local space + */ + struct Point + { + static const Type TYPE = ePOINT; + }; + + /** + \brief Segment core data + + The segment is defined by its length and goes along the geometry's + local space X axis, from -length/2 to length/2 + */ + struct Segment + { + static const Type TYPE = eSEGMENT; + + /// Segment length + PxReal length; + + PX_INLINE Segment() {} + + /** + \brief Constructs a SegmentCore with a specified length + \param _length Segment length + */ + PX_INLINE Segment(PxReal _length) : length(_length) {} + }; + + /** + \brief Box core data + + The box is defined by its extents, centered at the origin of the + geometry's local space, and aligned with the local space's axes + */ + struct Box + { + static const Type TYPE = eBOX; + + /// Box extents + PxVec3 extents; + + PX_INLINE Box() {} + + /** + \brief Constructs a BoxCore with specified extents + \param eX Extent in the x direction + \param eY Extent in the y direction + \param eZ Extent in the z direction + */ + PX_INLINE Box(PxReal eX, PxReal eY, PxReal eZ) : extents(eX, eY, eZ) {} + + /** + \brief Constructs a BoxCore with specified extents + \param _extents Vector containing extents in x, y, and z directions + */ + PX_INLINE Box(const PxVec3& _extents) : extents(_extents) {} + }; + + /** + \brief Ellipsoid core data + + The ellipsoid is defined by its radii and is centered at the origin + of the geometry's local space + */ + struct Ellipsoid + { + static const Type TYPE = eELLIPSOID; + + /// Ellipsoid radii + PxVec3 radii; + + PX_INLINE Ellipsoid() {} + + /** + \brief Constructs an EllipsoidCore with specified radii + \param rX Radius in the x direction + \param rY Radius in the y direction + \param rZ Radius in the z direction + */ + PX_INLINE Ellipsoid(PxReal rX, PxReal rY, PxReal rZ) : radii(rX, rY, rZ) {} + + /** + \brief Constructs an EllipsoidCore with specified radii + \param _radii Vector containing radii in x, y, and z directions + */ + PX_INLINE Ellipsoid(const PxVec3& _radii) : radii(_radii) {} + }; + + /** + \brief Cylinder core data + + The cylinder is defined by its height and radius. It is centered at the origin + of the geometry's local space with its axis along the X axis + */ + struct Cylinder + { + static const Type TYPE = eCYLINDER; + + /// Cylinder height + PxReal height; + + /// Cylinder radius + PxReal radius; + + PX_INLINE Cylinder() {} + + /** + \brief Constructs a CylinderCore with specified height and radius + \param _height Cylinder height + \param _radius Cylinder radius + */ + PX_INLINE Cylinder(PxReal _height, PxReal _radius) : height(_height), radius(_radius) {} + }; + + /** + \brief Cone core data + + The cone is defined by its height and base radius. It is centered at the origin + of the geometry's local space with its axis along the X axis and the base + at x = -height/2 + */ + struct Cone + { + static const Type TYPE = eCONE; + + /// Cone height + PxReal height; + + /// Cone base radius + PxReal radius; + + PX_INLINE Cone() {} + + /** + \brief Constructs a ConeCore with specified height and radius + \param _height Cone height + \param _radius Cone base radius + */ + PX_INLINE Cone(PxReal _height, PxReal _radius) : height(_height), radius(_radius) {} + }; + }; + + /** + \brief Convex core geometry class. + + This class allows users to create a variety of convex shapes. Each shape is defined by: + 1. A core, specified by one of the pre-authored GJK support functions. + 2. A margin, which is an arbitrary distance that extends the core. + + The resulting convex shape includes both the core and the surrounding space within the margin. + + Simple examples include: + - A sphere: created from a point core with a non-zero margin (radius). + - A capsule: created from a segment core with a non-zero margin. + */ + class PxConvexCoreGeometry : public PxGeometry + { + public: + + /** + \brief Default constructor + */ + PX_INLINE PxConvexCoreGeometry(); + + /** + \brief Constructor + \tparam Core The type of the core + \param core The core to use + \param margin The margin to add around the core. Defaults to 0 + */ + template + PX_INLINE PxConvexCoreGeometry(const Core& core, PxReal margin = 0); + + /** + \brief Copy constructor + \param that The geometry to copy from + */ + PX_INLINE PxConvexCoreGeometry(const PxConvexCoreGeometry& that); + + /** + \brief Assignment operator + \param that The geometry to assign from + */ + PX_INLINE PxConvexCoreGeometry& operator=(const PxConvexCoreGeometry& that); + + /** + \brief Get the type of the core + \return The type of the core + */ + PX_INLINE PxConvexCore::Type getCoreType() const; + + /// Maximum size of the core data in bytes. + static const PxU32 MAX_CORE_SIZE = sizeof(PxReal) * 6; + + /** + \brief Get a pointer to the core data. + \return A pointer to the core data. + */ + PX_INLINE const void* getCoreData() const; + + /** + \brief Get the core. + \return The core. + */ + template + PX_INLINE const Core& getCore() const; + + /** + \brief Get the margin of the convex core geometry. + \return The margin size. + */ + PX_INLINE PxReal getMargin() const; + + /** + \brief Check if the convex core geometry is valid. + \return True if the geometry is valid, false otherwise. + */ + PX_PHYSX_COMMON_API bool isValid() const; + + private: + + // Core type + PxConvexCore::Type mCoreType; + // Core data + PxU8 mCore[MAX_CORE_SIZE]; + // Margin + PxReal mMargin; + }; + + PX_INLINE PxConvexCoreGeometry::PxConvexCoreGeometry() + : + PxGeometry(PxGeometryType::eCONVEXCORE), + mCoreType(PxConvexCore::Type(-1)), mMargin(0) + {} + + template + PX_INLINE PxConvexCoreGeometry::PxConvexCoreGeometry(const Core& core, PxReal margin) + : + PxGeometry(PxGeometryType::eCONVEXCORE), + mCoreType(Core::TYPE), mMargin(margin) + { + PX_ASSERT(sizeof(Core) <= MAX_CORE_SIZE); + PxMemCopy(mCore, &core, sizeof(Core)); + } + + PX_INLINE PxConvexCoreGeometry::PxConvexCoreGeometry(const PxConvexCoreGeometry& that) + : + PxGeometry(that), + mCoreType(that.getCoreType()), mMargin(that.getMargin()) + { + PxMemCopy(mCore, that.mCore, MAX_CORE_SIZE); + } + + PX_INLINE PxConvexCoreGeometry& PxConvexCoreGeometry::operator = (const PxConvexCoreGeometry& that) + { + mType = that.mType; + mCoreType = that.mCoreType; + mMargin = that.mMargin; + PxMemCopy(mCore, that.mCore, MAX_CORE_SIZE); + return *this; + } + + PX_INLINE PxConvexCore::Type PxConvexCoreGeometry::getCoreType() const + { + return mCoreType; + } + + PX_INLINE const void* PxConvexCoreGeometry::getCoreData() const + { + return mCore; + } + + template + PX_INLINE const Core& PxConvexCoreGeometry::getCore() const + { + PX_ASSERT(Core::TYPE == mCoreType); + return *reinterpret_cast(getCoreData()); + } + + PX_INLINE PxReal PxConvexCoreGeometry::getMargin() const + { + return mMargin; + } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexMesh.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexMesh.h new file mode 100644 index 000000000..b7495e33d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexMesh.h @@ -0,0 +1,184 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONVEX_MESH_H +#define PX_CONVEX_MESH_H + +#include "foundation/PxVec3.h" +#include "foundation/PxMat33.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +class PxBounds3; +#endif + +/** +\brief Polygon data + +Plane format: (mPlane[0],mPlane[1],mPlane[2]).dot(x) + mPlane[3] = 0 +With the normal outward-facing from the hull. +*/ +struct PxHullPolygon +{ + PxReal mPlane[4]; //!< Plane equation for this polygon + PxU16 mNbVerts; //!< Number of vertices/edges in the polygon + PxU16 mIndexBase; //!< Offset in index buffer +}; + +/** +\brief A convex mesh. + +Internally represented as a list of convex polygons. The number +of polygons is limited to 256. + +To avoid duplicating data when you have several instances of a particular +mesh positioned differently, you do not use this class to represent a +convex object directly. Instead, you create an instance of this mesh via +the PxConvexMeshGeometry and PxShape classes. + +

Creation

+ +To create an instance of this class call PxPhysics::createConvexMesh(), +and PxConvexMesh::release() to delete it. This is only possible +once you have released all of its #PxShape instances. + +

Visualizations:

+\li #PxVisualizationParameter::eCOLLISION_AABBS +\li #PxVisualizationParameter::eCOLLISION_SHAPES +\li #PxVisualizationParameter::eCOLLISION_AXES +\li #PxVisualizationParameter::eCOLLISION_FNORMALS +\li #PxVisualizationParameter::eCOLLISION_EDGES + +\see PxConvexMeshDesc PxPhysics.createConvexMesh() +*/ +class PxConvexMesh : public PxRefCounted +{ +public: + + /** + \brief Returns the number of vertices. + \return Number of vertices. + \see getVertices() + */ + virtual PxU32 getNbVertices() const = 0; + + /** + \brief Returns the vertices. + \return Array of vertices. + \see getNbVertices() + */ + virtual const PxVec3* getVertices() const = 0; + + /** + \brief Returns the index buffer. + \return Index buffer. + \see getNbPolygons() getPolygonData() + */ + virtual const PxU8* getIndexBuffer() const = 0; + + /** + \brief Returns the number of polygons. + \return Number of polygons. + \see getIndexBuffer() getPolygonData() + */ + virtual PxU32 getNbPolygons() const = 0; + + /** + \brief Returns the polygon data. + \param[in] index Polygon index in [0 ; getNbPolygons()[. + \param[out] data Polygon data. + \return True if success. + \see getIndexBuffer() getNbPolygons() + */ + virtual bool getPolygonData(PxU32 index, PxHullPolygon& data) const = 0; + + /** + \brief Decrements the reference count of a convex mesh and releases it if the new reference count is zero. + + \see PxPhysics.createConvexMesh() PxConvexMeshGeometry PxShape + */ + virtual void release() = 0; + + /** + \brief Returns the mass properties of the mesh assuming unit density. + + The following relationship holds between mass and volume: + + mass = volume * density + + The mass of a unit density mesh is equal to its volume, so this function returns the volume of the mesh. + + Similarly, to obtain the localInertia of an identically shaped object with a uniform density of d, simply multiply the + localInertia of the unit density mesh by d. + + \param[out] mass The mass of the mesh assuming unit density. + \param[out] localInertia The inertia tensor in mesh local space assuming unit density. + \param[out] localCenterOfMass Position of center of mass (or centroid) in mesh local space. + */ + virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const = 0; + + /** + \brief Returns the local-space (vertex space) AABB from the convex mesh. + + \return local-space bounds + */ + virtual PxBounds3 getLocalBounds() const = 0; + + /** + \brief Returns the local-space Signed Distance Field for this mesh if it has one. + \return local-space SDF. + */ + virtual const PxReal* getSDF() const = 0; + + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxConvexMesh"; } + + /** + \brief This method decides whether a convex mesh is gpu compatible. If the total number of vertices are more than 64 or any number of vertices in a polygon is more than 32, or + convex hull data was not cooked with GPU data enabled during cooking or was loaded from a serialized collection, the convex hull is incompatible with GPU collision detection. Otherwise + it is compatible. + + \return True if the convex hull is gpu compatible + */ + virtual bool isGpuCompatible() const = 0; + + +protected: + PX_INLINE PxConvexMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {} + PX_INLINE PxConvexMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + virtual ~PxConvexMesh() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxConvexMesh", PxRefCounted); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexMeshGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexMeshGeometry.h new file mode 100644 index 000000000..d10184507 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxConvexMeshGeometry.h @@ -0,0 +1,158 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONVEX_MESH_GEOMETRY_H +#define PX_CONVEX_MESH_GEOMETRY_H +#include "geometry/PxGeometry.h" +#include "geometry/PxMeshScale.h" +#include "common/PxCoreUtilityTypes.h" +#include "geometry/PxConvexMesh.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxConvexMesh; + +/** +\brief Flags controlling the simulated behavior of the convex mesh geometry. + +Used in ::PxConvexMeshGeometryFlags. +*/ +struct PxConvexMeshGeometryFlag +{ + enum Enum + { + eTIGHT_BOUNDS = (1<<0) //!< Use tighter (but more expensive to compute) bounds around the convex geometry. + }; +}; + +/** +\brief collection of set bits defined in PxConvexMeshGeometryFlag. + +\see PxConvexMeshGeometryFlag +*/ +typedef PxFlags PxConvexMeshGeometryFlags; +PX_FLAGS_OPERATORS(PxConvexMeshGeometryFlag::Enum,PxU8) + +/** +\brief Convex mesh geometry class. + +This class unifies a convex mesh object with a scaling transform, and +lets the combined object be used anywhere a PxGeometry is needed. + +The scaling is a transform along arbitrary axes contained in the scale object. +The vertices of the mesh in geometry (or shape) space is the +PxMeshScale::toMat33() transform, multiplied by the vertex space vertices +in the PxConvexMesh object. +*/ +class PxConvexMeshGeometry : public PxGeometry +{ +public: + /** + \brief Constructor. By default creates an empty object with a NULL mesh and identity scale. + + \param[in] mesh Mesh pointer. May be NULL, though this will not make the object valid for shape construction. + \param[in] scaling Scale factor. + \param[in] flags Mesh flags. + \ + */ + PX_INLINE PxConvexMeshGeometry( PxConvexMesh* mesh = NULL, + const PxMeshScale& scaling = PxMeshScale(), + PxConvexMeshGeometryFlags flags = PxConvexMeshGeometryFlag::eTIGHT_BOUNDS) : + PxGeometry (PxGeometryType::eCONVEXMESH), + scale (scaling), + convexMesh (mesh), + meshFlags (flags) + { + } + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxConvexMeshGeometry(const PxConvexMeshGeometry& that) : + PxGeometry (that), + scale (that.scale), + convexMesh (that.convexMesh), + meshFlags (that.meshFlags) + { + } + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxConvexMeshGeometry& that) + { + mType = that.mType; + scale = that.scale; + convexMesh = that.convexMesh; + meshFlags = that.meshFlags; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid for shape creation. + + \note A valid convex mesh has a positive scale value in each direction (scale.x > 0, scale.y > 0, scale.z > 0). + It is illegal to call PxPhysics::createShape with a convex that has zero extent in any direction. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + +public: + PxMeshScale scale; //!< The scaling transformation (from vertex space to shape space). + PxConvexMesh* convexMesh; //!< A reference to the convex mesh object. + PxConvexMeshGeometryFlags meshFlags; //!< Mesh flags. + PxPadding<3> paddingFromFlags; //!< padding for mesh flags +}; + + +PX_INLINE bool PxConvexMeshGeometry::isValid() const +{ + if(mType != PxGeometryType::eCONVEXMESH) + return false; + if(!scale.scale.isFinite() || !scale.rotation.isUnit()) + return false; + if(!scale.isValidForConvexMesh()) + return false; + if(!convexMesh) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxCustomGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxCustomGeometry.h new file mode 100644 index 000000000..ac0a38891 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxCustomGeometry.h @@ -0,0 +1,308 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CUSTOMGEOMETRY_H +#define PX_CUSTOMGEOMETRY_H + +#include "foundation/PxTransform.h" +#include "foundation/PxBounds3.h" +#include "geometry/PxGeometry.h" +#include "geometry/PxGeometryHit.h" +#include "geometry/PxGeometryQueryContext.h" +#include "foundation/PxFoundationConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + class PxContactBuffer; + class PxRenderOutput; + class PxMassProperties; + + /** + \brief Custom geometry class. This class allows user to create custom geometries by providing a set of virtual callback functions. + */ + class PxCustomGeometry : public PxGeometry + { + public: + /** + \brief For internal use + */ + PX_PHYSX_COMMON_API static PxU32 getUniqueID(); + + /** + \brief The type of a custom geometry. Allows to identify a particular kind of it. + */ + struct Type + { + /** + \brief Default constructor + */ + PX_INLINE Type() : mID(getUniqueID()) {} + + /** + \brief Default constructor + */ + PX_INLINE Type(const Type& t) : mID(t.mID) {} + + /** + \brief Assigment operator + */ + PX_INLINE Type& operator = (const Type& t) { mID = t.mID; return *this; } + + /** + \brief Equality operator + */ + PX_INLINE bool operator == (const Type& t) const { return mID == t.mID; } + + /** + \brief Inequality operator + */ + PX_INLINE bool operator != (const Type& t) const { return mID != t.mID; } + + /** + \brief Invalid type + */ + PX_INLINE static Type INVALID() { PxU32 z(0); return reinterpret_cast(z); } + + private: + PxU32 mID; + }; + + /** + \brief Custom geometry callbacks structure. User should inherit this and implement all pure virtual functions. + */ + struct Callbacks + { + /** + \brief Return custom type. The type purpose is for user to differentiate custom geometries. Not used by PhysX. + + \return Unique ID of a custom geometry type. + + \note User should use DECLARE_CUSTOM_GEOMETRY_TYPE and IMPLEMENT_CUSTOM_GEOMETRY_TYPE intead of overwriting this function. + */ + virtual Type getCustomType() const = 0; + + /** + \brief Return local bounds. + + \param[in] geometry This geometry. + + \return Bounding box in the geometry local space. + */ + virtual PxBounds3 getLocalBounds(const PxGeometry& geometry) const = 0; + + /** + \brief Contacts generation. Generate collision contacts between two geometries in given poses. + + \param[in] geom0 This custom geometry + \param[in] geom1 The other geometry + \param[in] pose0 This custom geometry pose + \param[in] pose1 The other geometry pose + \param[in] contactDistance The distance at which contacts begin to be generated between the pairs + \param[in] meshContactMargin The mesh contact margin. + \param[in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units + \param[out] contactBuffer A buffer to write contacts to. + + \return True if there are contacts. False otherwise. + */ + virtual bool generateContacts(const PxGeometry& geom0, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, + const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, + PxContactBuffer& contactBuffer) const = 0; + + /** + \brief Raycast. Cast a ray against the geometry in given pose. + + \param[in] origin Origin of the ray. + \param[in] unitDir Normalized direction of the ray. + \param[in] geom This custom geometry + \param[in] pose This custom geometry pose + \param[in] maxDist Length of the ray. Has to be in the [0, inf) range. + \param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback. + \param[in] maxHits max number of returned hits = size of 'rayHits' buffer + \param[out] rayHits Ray hits. + \param[in] stride Ray hit structure stride. + \param[in] threadContext Optional user-defined per-thread context. + + \return Number of hits. + */ + virtual PxU32 raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose, + PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* rayHits, PxU32 stride, PxRaycastThreadContext* threadContext) const = 0; + + /** + \brief Overlap. Test if geometries overlap. + + \param[in] geom0 This custom geometry + \param[in] pose0 This custom geometry pose + \param[in] geom1 The other geometry + \param[in] pose1 The other geometry pose + \param[in] threadContext Optional user-defined per-thread context. + + \return True if there is overlap. False otherwise. + */ + virtual bool overlap(const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext* threadContext) const = 0; + + /** + \brief Sweep. Sweep geom1 against geom0. + + \param[in] unitDir Normalized direction of the sweep. geom1 is swept along this direction. + \param[in] maxDist Length of the sweep. Has to be in the [0, inf) range. + \param[in] geom0 This custom geometry + \param[in] pose0 This custom geometry pose + \param[in] geom1 The other geometry + \param[in] pose1 The other geometry pose + \param[out] sweepHit Used to report the sweep hit. + \param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. + \param[in] threadContext Optional user-defined per-thread context. + + \return True if there is hit. False otherwise. + */ + virtual bool sweep(const PxVec3& unitDir, const PxReal maxDist, + const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, + PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext* threadContext) const = 0; + + /** + \brief Visualize custom geometry for debugging. Optional. + + \param[in] geometry This geometry. + \param[in] out Render output. + \param[in] absPose Geometry absolute transform. + \param[in] cullbox Region to visualize. + */ + virtual void visualize(const PxGeometry& geometry, PxRenderOutput& out, const PxTransform& absPose, const PxBounds3& cullbox) const = 0; + + /** + \brief Compute custom geometry mass properties. For geometries usable with dynamic rigidbodies. + + \param[in] geometry This geometry. + \param[out] massProperties Mass properties to compute. + */ + virtual void computeMassProperties(const PxGeometry& geometry, PxMassProperties& massProperties) const = 0; + + /** + \brief Compatible with PhysX's PCM feature. Allows to optimize contact generation. + + \param[in] geometry This geometry. + \param[out] breakingThreshold The threshold to trigger contacts re-generation. + */ + virtual bool usePersistentContactManifold(const PxGeometry& geometry, PxReal& breakingThreshold) const = 0; + + /* Destructor */ + virtual ~Callbacks() {} + }; + + /** + \brief Default constructor. + + Creates an empty object with a NULL callbacks pointer. + */ + PX_INLINE PxCustomGeometry() : + PxGeometry(PxGeometryType::eCUSTOM), + callbacks(NULL) + {} + + /** + \brief Constructor. + */ + PX_INLINE PxCustomGeometry(Callbacks& _callbacks) : + PxGeometry(PxGeometryType::eCUSTOM), + callbacks(&_callbacks) + {} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxCustomGeometry(const PxCustomGeometry& that) : + PxGeometry(that), + callbacks(that.callbacks) + {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxCustomGeometry& that) + { + mType = that.mType; + callbacks = that.callbacks; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid for shape creation. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + + /** + \brief Returns the custom type of the custom geometry. + */ + PX_INLINE Type getCustomType() const + { + return callbacks ? callbacks->getCustomType() : Type::INVALID(); + } + + public: + Callbacks* callbacks; //!< A reference to the callbacks object. + }; + + PX_INLINE bool PxCustomGeometry::isValid() const + { + return mType == PxGeometryType::eCUSTOM && callbacks != NULL; + } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +/** +\brief Used in pair with IMPLEMENT_CUSTOM_GEOMETRY_TYPE to overwrite Callbacks::getCustomType() callback. +*/ +#define DECLARE_CUSTOM_GEOMETRY_TYPE \ + static ::physx::PxCustomGeometry::Type TYPE(); \ + virtual ::physx::PxCustomGeometry::Type getCustomType() const; + +/** +\brief Used in pair with DECLARE_CUSTOM_GEOMETRY_TYPE to overwrite Callbacks::getCustomType() callback. +*/ +#define IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CLASS) \ +::physx::PxCustomGeometry::Type CLASS::TYPE() \ +{ \ + static ::physx::PxCustomGeometry::Type customType; \ + return customType; \ +} \ +::physx::PxCustomGeometry::Type CLASS::getCustomType() const \ +{ \ + return TYPE(); \ +} + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometry.h new file mode 100644 index 000000000..6873438a9 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometry.h @@ -0,0 +1,106 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEOMETRY_H +#define PX_GEOMETRY_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxFlags.h" +#include "foundation/PxMath.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief A geometry type. + +Used to distinguish the type of a ::PxGeometry object. +*/ +struct PxGeometryType +{ + enum Enum + { + eSPHERE, + ePLANE, + eCAPSULE, + eBOX, + eCONVEXCORE, + eCONVEXMESH, + ePARTICLESYSTEM, + eTETRAHEDRONMESH, + eTRIANGLEMESH, + eHEIGHTFIELD, + eCUSTOM, + + eGEOMETRY_COUNT, //!< internal use only! + eINVALID = -1 //!< internal use only! + }; +}; + +/** +\brief A geometry object. + +A geometry object defines the characteristics of a spatial object, but without any information +about its placement in the world. + +\note This is an abstract class. You cannot create instances directly. Create an instance of one of the derived classes instead. +*/ +class PxGeometry +{ +public: + /** + \brief Returns the type of the geometry. + \return The type of the object. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxGeometryType::Enum getType() const { return mType; } + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxGeometry& that) + { + mType = that.mType; + } + +protected: + PX_CUDA_CALLABLE PX_FORCE_INLINE PxGeometry(PxGeometryType::Enum type) : mType(type) {} + PX_CUDA_CALLABLE PX_FORCE_INLINE PxGeometry(const PxGeometry& that) : mType(that.mType) {} + + PxGeometryType::Enum mType; + +public: + float mTypePadding; // PT: padding bytes on x64, used internally +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryHelpers.h new file mode 100644 index 000000000..f90360cf7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryHelpers.h @@ -0,0 +1,187 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEOMETRY_HELPERS_H +#define PX_GEOMETRY_HELPERS_H + +#include "foundation/PxPlane.h" +#include "foundation/PxTransform.h" +#include "foundation/PxUnionCast.h" +#include "common/PxPhysXCommonConfig.h" +#include "geometry/PxGeometry.h" +#include "geometry/PxBoxGeometry.h" +#include "geometry/PxSphereGeometry.h" +#include "geometry/PxCapsuleGeometry.h" +#include "geometry/PxPlaneGeometry.h" +#include "geometry/PxConvexMeshGeometry.h" +#include "geometry/PxHeightFieldGeometry.h" +#include "geometry/PxParticleSystemGeometry.h" +#include "geometry/PxTetrahedronMeshGeometry.h" +#include "geometry/PxCustomGeometry.h" +#include "geometry/PxConvexCoreGeometry.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Geometry holder class + +This class contains enough space to hold a value of any PxGeometry subtype. + +Its principal use is as a convenience class to allow geometries to be returned polymorphically from functions. +*/ + +PX_ALIGN_PREFIX(8) +class PxGeometryHolder +{ + class PxInvalidGeometry : public PxGeometry + { + public: + PX_INLINE PxInvalidGeometry() : PxGeometry(PxGeometryType::eINVALID) {} + }; + +public: + PX_FORCE_INLINE PxGeometryType::Enum getType() const + { + return any().getType(); + } + + PX_FORCE_INLINE PxGeometry& any() + { + return *PxUnionCast(&bytes.geometry); + } + + PX_FORCE_INLINE const PxGeometry& any() const + { + return *PxUnionCast(&bytes.geometry); + } + +//! \cond + PX_FORCE_INLINE PxSphereGeometry& sphere() { return get(); } + PX_FORCE_INLINE const PxSphereGeometry& sphere() const { return get(); } + + PX_FORCE_INLINE PxPlaneGeometry& plane() { return get(); } + PX_FORCE_INLINE const PxPlaneGeometry& plane() const { return get(); } + + PX_FORCE_INLINE PxCapsuleGeometry& capsule() { return get(); } + PX_FORCE_INLINE const PxCapsuleGeometry& capsule() const { return get(); } + + PX_FORCE_INLINE PxBoxGeometry& box() { return get(); } + PX_FORCE_INLINE const PxBoxGeometry& box() const { return get(); } + + PX_FORCE_INLINE PxConvexCoreGeometry& convexCore() { return get(); } + PX_FORCE_INLINE const PxConvexCoreGeometry& convexCore() const { return get(); } + + PX_FORCE_INLINE PxConvexMeshGeometry& convexMesh() { return get(); } + PX_FORCE_INLINE const PxConvexMeshGeometry& convexMesh() const { return get(); } + + PX_FORCE_INLINE PxTetrahedronMeshGeometry& tetMesh() { return get(); } + PX_FORCE_INLINE const PxTetrahedronMeshGeometry& tetMesh() const { return get(); } + + PX_FORCE_INLINE PxTriangleMeshGeometry& triangleMesh() { return get(); } + PX_FORCE_INLINE const PxTriangleMeshGeometry& triangleMesh() const { return get(); } + + PX_FORCE_INLINE PxHeightFieldGeometry& heightField() { return get(); } + PX_FORCE_INLINE const PxHeightFieldGeometry& heightField() const { return get(); } + + PX_FORCE_INLINE PxParticleSystemGeometry& particleSystem() { return get(); } + PX_FORCE_INLINE const PxParticleSystemGeometry& particleSystem() const { return get(); } + + PX_FORCE_INLINE PxCustomGeometry& custom() { return get(); } + PX_FORCE_INLINE const PxCustomGeometry& custom() const { return get(); } +//! \endcond + + PX_FORCE_INLINE void storeAny(const PxGeometry& geometry) + { + PX_ASSERT_WITH_MESSAGE( (geometry.getType() >= PxGeometryType::eSPHERE) && + (geometry.getType() < PxGeometryType::eGEOMETRY_COUNT), + "Unexpected GeometryType in PxGeometryHolder::storeAny"); + + switch(geometry.getType()) + { + case PxGeometryType::eSPHERE: put(geometry); break; + case PxGeometryType::ePLANE: put(geometry); break; + case PxGeometryType::eCAPSULE: put(geometry); break; + case PxGeometryType::eBOX: put(geometry); break; + case PxGeometryType::eCONVEXCORE: put(geometry); break; + case PxGeometryType::eCONVEXMESH: put(geometry); break; + case PxGeometryType::eTRIANGLEMESH: put(geometry); break; + case PxGeometryType::eTETRAHEDRONMESH: put(geometry); break; + case PxGeometryType::eHEIGHTFIELD: put(geometry); break; + case PxGeometryType::ePARTICLESYSTEM: put(geometry); break; + case PxGeometryType::eCUSTOM: put(geometry); break; + case PxGeometryType::eGEOMETRY_COUNT: + case PxGeometryType::eINVALID: break; + } + } + + PX_FORCE_INLINE PxGeometryHolder() { put(PxInvalidGeometry()); } + PX_FORCE_INLINE PxGeometryHolder(const PxGeometry& geometry){ storeAny(geometry); } + + private: + template void put(const PxGeometry& geometry) + { + static_cast(any()) = static_cast(geometry); + } + + template T& get() + { + PX_ASSERT(getType() == type); + return static_cast(any()); + } + + template T& get() const + { + PX_ASSERT(getType() == type); + return static_cast(any()); + } + + union { + PxU8 geometry[sizeof(PxGeometry)]; + PxU8 box[sizeof(PxBoxGeometry)]; + PxU8 sphere[sizeof(PxSphereGeometry)]; + PxU8 capsule[sizeof(PxCapsuleGeometry)]; + PxU8 plane[sizeof(PxPlaneGeometry)]; + PxU8 convex[sizeof(PxConvexCoreGeometry)]; + PxU8 convexMesh[sizeof(PxConvexMeshGeometry)]; + PxU8 tetMesh[sizeof(PxTetrahedronMeshGeometry)]; + PxU8 mesh[sizeof(PxTriangleMeshGeometry)]; + PxU8 heightfield[sizeof(PxHeightFieldGeometry)]; + PxU8 particleSystem[sizeof(PxParticleSystemGeometry)]; + PxU8 custom[sizeof(PxCustomGeometry)]; + } bytes; +} +PX_ALIGN_SUFFIX(8); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryHit.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryHit.h new file mode 100644 index 000000000..303734f70 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryHit.h @@ -0,0 +1,202 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEOMETRY_HIT_H +#define PX_GEOMETRY_HIT_H +#include "foundation/PxVec3.h" +#include "foundation/PxFlags.h" +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Scene query and geometry query behavior flags. + +PxHitFlags are used for 3 different purposes: + +1) To request hit fields to be filled in by scene queries (such as hit position, normal, face index or UVs). +2) Once query is completed, to indicate which fields are valid (note that a query may produce more valid fields than requested). +3) To specify additional options for the narrow phase and mid-phase intersection routines. + +All these flags apply to both scene queries and geometry queries (PxGeometryQuery). + +\see PxRaycastHit PxSweepHit PxOverlapHit PxScene.raycast PxScene.sweep PxScene.overlap PxGeometryQuery PxFindFaceIndex +*/ +struct PxHitFlag +{ + enum Enum + { + ePOSITION = (1<<0), //!< "position" member of #PxQueryHit is valid + eNORMAL = (1<<1), //!< "normal" member of #PxQueryHit is valid + eUV = (1<<3), //!< "u" and "v" barycentric coordinates of #PxQueryHit are valid. Not applicable to sweep queries. + eASSUME_NO_INITIAL_OVERLAP = (1<<4), //!< Performance hint flag for sweeps when it is known upfront there's no initial overlap. + //!< NOTE: using this flag may cause undefined results if shapes are initially overlapping. + eANY_HIT = (1<<5), //!< Report any first hit. Used for geometries that contain more than one primitive. For meshes, + //!< if neither eMESH_MULTIPLE nor eANY_HIT is specified, a single closest hit will be reported. + eMESH_MULTIPLE = (1<<6), //!< Report all hits for meshes rather than just the first. Not applicable to sweep queries. + eMESH_BOTH_SIDES = (1<<7), //!< Report hits with back faces of mesh triangles. Also report hits for raycast + //!< originating on mesh surface and facing away from the surface normal. Not applicable to sweep queries. + //!< Please refer to the user guide for heightfield-specific differences. + ePRECISE_SWEEP = (1<<8), //!< Use more accurate but slower narrow phase sweep tests. + //!< May provide better compatibility with PhysX 3.2 sweep behavior. + eMTD = (1<<9), //!< Report the minimum translation depth, normal and contact point. + eFACE_INDEX = (1<<10), //!< "face index" member of #PxQueryHit is valid + + eDEFAULT = ePOSITION|eNORMAL|eFACE_INDEX, + + /** \brief Only this subset of flags can be modified by pre-filter. Other modifications will be discarded. */ + eMODIFIABLE_FLAGS = eMESH_MULTIPLE|eMESH_BOTH_SIDES|eASSUME_NO_INITIAL_OVERLAP|ePRECISE_SWEEP + }; +}; + +/** +\brief collection of set bits defined in PxHitFlag. + +\see PxHitFlag +*/ +PX_FLAGS_TYPEDEF(PxHitFlag, PxU16) + +/** +\brief Scene query hit information. +*/ +struct PxQueryHit +{ + PX_INLINE PxQueryHit() : faceIndex(0xFFFFffff) {} + + /** + Face index of touched triangle, for triangle meshes, convex meshes and height fields. + + \note This index will default to 0xFFFFffff value for overlap queries. + \note Please refer to the user guide for more details for sweep queries. + \note This index is remapped by mesh cooking. Use #PxTriangleMesh::getTrianglesRemap() to convert to original mesh index. + \note For convex meshes use #PxConvexMesh::getPolygonData() to retrieve touched polygon data. + */ + PxU32 faceIndex; +}; + +/** +\brief Scene query hit information for raycasts and sweeps returning hit position and normal information. + +::PxHitFlag flags can be passed to scene query functions, as an optimization, to cause the SDK to +only generate specific members of this structure. +*/ +struct PxLocationHit : PxQueryHit +{ + PX_INLINE PxLocationHit() : flags(0), position(PxVec3(0)), normal(PxVec3(0)), distance(PX_MAX_REAL) {} + + /** + \note For raycast hits: true for shapes overlapping with raycast origin. + \note For sweep hits: true for shapes overlapping at zero sweep distance. + + \see PxRaycastHit PxSweepHit + */ + PX_INLINE bool hadInitialOverlap() const { return (distance <= 0.0f); } + + // the following fields are set in accordance with the #PxHitFlags + PxHitFlags flags; //!< Hit flags specifying which members contain valid values. + PxVec3 position; //!< World-space hit position (flag: #PxHitFlag::ePOSITION) + PxVec3 normal; //!< World-space hit normal (flag: #PxHitFlag::eNORMAL) + + /** + \brief Distance to hit. + \note If the eMTD flag is used, distance will be a negative value if shapes are overlapping indicating the penetration depth. + \note Otherwise, this value will be >= 0 */ + PxF32 distance; +}; + +/** +\brief Stores results of raycast queries. + +::PxHitFlag flags can be passed to raycast function, as an optimization, to cause the SDK to only compute specified members of this +structure. + +Some members like barycentric coordinates are currently only computed for triangle meshes and height fields, but next versions +might provide them in other cases. The client code should check #flags to make sure returned values are valid. + +\see PxScene.raycast +*/ +struct PxGeomRaycastHit : PxLocationHit +{ + PX_INLINE PxGeomRaycastHit() : u(0.0f), v(0.0f) {} + + // the following fields are set in accordance with the #PxHitFlags + + PxReal u, v; //!< barycentric coordinates of hit point, for triangle mesh and height field (flag: #PxHitFlag::eUV) +}; + +/** +\brief Stores results of overlap queries. + +\see PxScene.overlap +*/ +struct PxGeomOverlapHit : PxQueryHit +{ + PX_INLINE PxGeomOverlapHit() {} +}; + +/** +\brief Stores results of sweep queries. + +\see PxScene.sweep +*/ +struct PxGeomSweepHit : PxLocationHit +{ + PX_INLINE PxGeomSweepHit() {} +}; + +/** +\brief Pair of indices, typically either object or triangle indices. +*/ +struct PxGeomIndexPair +{ + PX_FORCE_INLINE PxGeomIndexPair() {} + PX_FORCE_INLINE PxGeomIndexPair(PxU32 _id0, PxU32 _id1) : id0(_id0), id1(_id1) {} + + PxU32 id0, id1; +}; + +/** +\brief Pair of indices and a distance between involved objects or triangles. +*/ +struct PxGeomIndexClosePair : PxGeomIndexPair +{ + PX_FORCE_INLINE PxGeomIndexClosePair() {} + PX_FORCE_INLINE PxGeomIndexClosePair(PxU32 _id0, PxU32 _id1, float d) : + PxGeomIndexPair(_id0, _id1), distance(d) {} + + float distance; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryInternal.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryInternal.h new file mode 100644 index 000000000..7ba7ce205 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryInternal.h @@ -0,0 +1,120 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEOMETRY_INTERNAL_H +#define PX_GEOMETRY_INTERNAL_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxVec3.h" +#include "geometry/PxTriangleMesh.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxTriangleMesh; + + struct PxTriangleMeshInternalData + { + PxU32 mNbVertices; + PxU32 mNbTriangles; + PxVec3* mVertices; + void* mTriangles; + PxU32* mFaceRemap; + PxVec3 mAABB_Center; + PxVec3 mAABB_Extents; + PxReal mGeomEpsilon; + PxU8 mFlags; + // + PxU32 mNbNodes; + PxU32 mNodeSize; + void* mNodes; + PxU32 mInitData; + PxVec3 mCenterOrMinCoeff; + PxVec3 mExtentsOrMaxCoeff; + bool mQuantized; + + PX_FORCE_INLINE PxU32 getSizeofVerticesInBytes() const + { + return mNbVertices * sizeof(PxVec3); + } + + PX_FORCE_INLINE PxU32 getSizeofTrianglesInBytes() const + { + const PxU32 triangleSize = mFlags & PxTriangleMeshFlag::e16_BIT_INDICES ? sizeof(PxU16) : sizeof(PxU32); + return mNbTriangles * 3 * triangleSize; + } + + PX_FORCE_INLINE PxU32 getSizeofFaceRemapInBytes() const + { + return mNbTriangles * sizeof(PxU32); + } + + PX_FORCE_INLINE PxU32 getSizeofNodesInBytes() const + { + return mNbNodes * mNodeSize; + } + }; + + PX_C_EXPORT PX_PHYSX_COMMON_API bool PX_CALL_CONV PxGetTriangleMeshInternalData(PxTriangleMeshInternalData& data, const PxTriangleMesh& mesh, bool takeOwnership); + + class PxBVH; + + struct PxBVHInternalData + { + PxU32 mNbIndices; + PxU32 mNbNodes; + PxU32 mNodeSize; + void* mNodes; + PxU32* mIndices; // Can be null + void* mBounds; + + PX_FORCE_INLINE PxU32 getSizeofNodesInBytes() const + { + return mNbNodes * mNodeSize; + } + + PX_FORCE_INLINE PxU32 getSizeofIndicesInBytes() const + { + return mNbIndices * sizeof(PxU32); + } + + PX_FORCE_INLINE PxU32 getSizeofBoundsInBytes() const + { + return (mNbIndices+1)*6; + } + }; + + PX_C_EXPORT PX_PHYSX_COMMON_API bool PX_CALL_CONV PxGetBVHInternalData(PxBVHInternalData& data, const PxBVH& bvh, bool takeOwnership); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQuery.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQuery.h new file mode 100644 index 000000000..56695b1b3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQuery.h @@ -0,0 +1,251 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEOMETRY_QUERY_H +#define PX_GEOMETRY_QUERY_H + +/** +\brief Maximum sweep distance for scene sweeps. The distance parameter for sweep functions will be clamped to this value. +The reason for this is GJK support cannot be evaluated near infinity. A viable alternative can be a sweep followed by an infinite raycast. + +\see PxScene +*/ +#define PX_MAX_SWEEP_DISTANCE 1e8f + + +#include "foundation/PxTransform.h" +#include "common/PxPhysXCommonConfig.h" +#include "geometry/PxGeometryHit.h" +#include "geometry/PxGeometryQueryFlags.h" +#include "geometry/PxGeometryQueryContext.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxGeometry; +class PxContactBuffer; +class PxBounds3; + +/** +\brief Collection of geometry object queries (sweeps, raycasts, overlaps, ...). +*/ +class PxGeometryQuery +{ +public: + + /** + \brief Raycast test against a geometry object. + + All geometry types are supported except PxParticleSystemGeometry and PxTetrahedronMeshGeometry. + + \param[in] origin The origin of the ray to test the geometry object against + \param[in] unitDir Normalized direction of the ray to test the geometry object against + \param[in] geom The geometry object to test the ray against + \param[in] pose Pose of the geometry object + \param[in] maxDist Maximum ray length, has to be in the [0, inf) range + \param[in] hitFlags Specification of the kind of information to retrieve on hit. Combination of #PxHitFlag flags + \param[in] maxHits max number of returned hits = size of 'rayHits' buffer + \param[out] rayHits Raycast hits information + \param[in] stride Stride value (in number of bytes) for rayHits array. Typically sizeof(PxGeomRaycastHit) for packed arrays. + \param[in] queryFlags Optional flags controlling the query. + \param[in] threadContext Optional user-defined per-thread context. + + \return Number of hits between the ray and the geometry object + + \see PxGeomRaycastHit PxGeometry PxTransform + */ + PX_PHYSX_COMMON_API static PxU32 raycast( const PxVec3& origin, const PxVec3& unitDir, + const PxGeometry& geom, const PxTransform& pose, + PxReal maxDist, PxHitFlags hitFlags, + PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT rayHits, PxU32 stride = sizeof(PxGeomRaycastHit), PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT, + PxRaycastThreadContext* threadContext = NULL); + + /** + \brief Overlap test for two geometry objects. + + All combinations are supported except: + \li PxPlaneGeometry vs. {PxPlaneGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry} + \li PxTriangleMeshGeometry vs. PxHeightFieldGeometry + \li PxHeightFieldGeometry vs. PxHeightFieldGeometry + \li Anything involving PxParticleSystemGeometry or PxTetrahedronMeshGeometry + + \param[in] geom0 The first geometry object + \param[in] pose0 Pose of the first geometry object + \param[in] geom1 The second geometry object + \param[in] pose1 Pose of the second geometry object + \param[in] queryFlags Optional flags controlling the query. + \param[in] threadContext Optional user-defined per-thread context. + + \return True if the two geometry objects overlap + + \see PxGeometry PxTransform + */ + PX_PHYSX_COMMON_API static bool overlap(const PxGeometry& geom0, const PxTransform& pose0, + const PxGeometry& geom1, const PxTransform& pose1, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT, PxOverlapThreadContext* threadContext=NULL); + + /** + \brief Sweep a specified geometry object in space and test for collision with a given object. + + The following combinations are supported. + + \li PxSphereGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexCoreGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry} + \li PxCapsuleGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexCoreGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry} + \li PxBoxGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexCoreGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry} + \li PxConvexCoreGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexCoreGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry} + \li PxConvexMeshGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexCoreGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry} + + \param[in] unitDir Normalized direction along which object geom0 should be swept + \param[in] maxDist Maximum sweep distance, has to be in the [0, inf) range + \param[in] geom0 The geometry object to sweep. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry, #PxBoxGeometry, #PxConvexCoreGeometry, and #PxConvexMeshGeometry + \param[in] pose0 Pose of the geometry object to sweep + \param[in] geom1 The geometry object to test the sweep against + \param[in] pose1 Pose of the geometry object to sweep against + \param[out] sweepHit The sweep hit information. Only valid if this method returns true. + \param[in] hitFlags Specify which properties per hit should be computed and written to result hit array. Combination of #PxHitFlag flags + \param[in] inflation Surface of the swept shape is additively extruded in the normal direction, rounding corners and edges. + \param[in] queryFlags Optional flags controlling the query. + \param[in] threadContext Optional user-defined per-thread context. + + \return True if the swept geometry object geom0 hits the object geom1 + + \see PxGeomSweepHit PxGeometry PxTransform + */ + PX_PHYSX_COMMON_API static bool sweep( const PxVec3& unitDir, const PxReal maxDist, + const PxGeometry& geom0, const PxTransform& pose0, + const PxGeometry& geom1, const PxTransform& pose1, + PxGeomSweepHit& sweepHit, PxHitFlags hitFlags = PxHitFlag::eDEFAULT, + const PxReal inflation = 0.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT, + PxSweepThreadContext* threadContext = NULL); + + /** + \brief Compute minimum translational distance (MTD) between two geometry objects. + + All combinations of geom objects are supported except: + - plane/plane + - plane/mesh + - plane/heightfield + - mesh/mesh + - mesh/heightfield + - heightfield/heightfield + - anything involving PxParticleSystemGeometry, PxTetrahedronMeshGeometry + + The function returns a unit vector ('direction') and a penetration depth ('depth'). + + The depenetration vector D = direction * depth should be applied to the first object, to + get out of the second object. + + Returned depth should always be positive or null. + + If objects do not overlap, the function can not compute the MTD and returns false. + + \param[out] direction Computed MTD unit direction + \param[out] depth Penetration depth. Always positive or null. + \param[in] geom0 The first geometry object + \param[in] pose0 Pose of the first geometry object + \param[in] geom1 The second geometry object + \param[in] pose1 Pose of the second geometry object + \param[in] queryFlags Optional flags controlling the query. + \return True if the MTD has successfully been computed, i.e. if objects do overlap. + + \see PxGeometry PxTransform + */ + PX_PHYSX_COMMON_API static bool computePenetration( PxVec3& direction, PxF32& depth, + const PxGeometry& geom0, const PxTransform& pose0, + const PxGeometry& geom1, const PxTransform& pose1, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT); + + /** + \brief Computes distance between a point and a geometry object. + + Currently supported geometry objects: box, sphere, capsule, convex core, convex mesh, mesh. + + \note For meshes, only the BVH34 midphase data-structure is supported. + + \param[in] point The point P + \param[in] geom The geometry object + \param[in] pose Pose of the geometry object + \param[out] closestPoint Optionally returned closest point to P on the geom object. Only valid when returned distance is strictly positive. + \param[out] closestIndex Optionally returned closest (triangle) index. Only valid for triangle meshes. + \param[in] queryFlags Optional flags controlling the query. + \return Square distance between the point and the geom object, or 0.0 if the point is inside the object, or -1.0 if an error occured (geometry type is not supported, or invalid pose) + + \see PxGeometry PxTransform + */ + PX_PHYSX_COMMON_API static PxReal pointDistance(const PxVec3& point, const PxGeometry& geom, const PxTransform& pose, + PxVec3* closestPoint=NULL, PxU32* closestIndex=NULL, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT); + + /** + \brief computes the bounds for a geometry object + + \param[out] bounds Returned computed bounds + \param[in] geom The geometry object + \param[in] pose Pose of the geometry object + \param[in] offset Offset for computed bounds. This value is added to the geom's extents. + \param[in] inflation Scale factor for computed bounds. The geom's extents are multiplied by this value. + \param[in] queryFlags Optional flags controlling the query. + + \see PxGeometry PxTransform + */ + PX_PHYSX_COMMON_API static void computeGeomBounds(PxBounds3& bounds, const PxGeometry& geom, const PxTransform& pose, float offset=0.0f, float inflation=1.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT); + + /** + \brief Generate collision contacts between a convex geometry and a single triangle + + \param[in] geom The geometry object. Can be a capsule, a box or a convex mesh + \param[in] pose Pose of the geometry object + \param[in] triangleVertices Triangle vertices in local space + \param[in] triangleIndex Triangle index + \param[in] contactDistance The distance at which contacts begin to be generated between the pairs + \param[in] meshContactMargin The mesh contact margin. + \param[in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units + \param[out] contactBuffer A buffer to write contacts to. + + \return True if there was collision + */ + PX_PHYSX_COMMON_API static bool generateTriangleContacts(const PxGeometry& geom, const PxTransform& pose, const PxVec3 triangleVertices[3], PxU32 triangleIndex, PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength, PxContactBuffer& contactBuffer); + + /** + \brief Checks if provided geometry is valid. + + \param[in] geom The geometry object. + \return True if geometry is valid. + + \see PxGeometry + */ + PX_PHYSX_COMMON_API static bool isValid(const PxGeometry& geom); +}; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQueryContext.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQueryContext.h new file mode 100644 index 000000000..ebda0a90c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQueryContext.h @@ -0,0 +1,74 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEOMETRY_QUERY_CONTEXT_H +#define PX_GEOMETRY_QUERY_CONTEXT_H + +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief A per-thread context passed to low-level query functions. + + This is a user-defined optional parameter that gets passed down to low-level query functions (raycast / overlap / sweep). + + This is not used directly in PhysX, although the context in this case is the PxHitCallback used in the query. This allows + user-defined query functions, such as the ones from PxCustomGeometry, to get some additional data about the query. In this + case this is a 'per-query' context rather than 'per-thread', but the initial goal of this parameter is to give custom + query callbacks access to per-thread data structures (e.g. caches) that could be needed to implement the callbacks. + + In any case this is mostly for user-controlled query systems. + */ + struct PxQueryThreadContext + { + }; + + /** + \brief A per-thread context passed to low-level raycast functions. + */ + typedef PxQueryThreadContext PxRaycastThreadContext; + + /** + \brief A per-thread context passed to low-level overlap functions. + */ + typedef PxQueryThreadContext PxOverlapThreadContext; + + /** + \brief A per-thread context passed to low-level sweep functions. + */ + typedef PxQueryThreadContext PxSweepThreadContext; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQueryFlags.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQueryFlags.h new file mode 100644 index 000000000..2d22f9671 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGeometryQueryFlags.h @@ -0,0 +1,68 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GEOMETRY_QUERY_FLAGS_H +#define PX_GEOMETRY_QUERY_FLAGS_H + +#include "foundation/PxFlags.h" +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Geometry-level query flags. + + \see PxScene::raycast PxScene::overlap PxScene::sweep PxBVH::raycast PxBVH::overlap PxBVH::sweep PxGeometryQuery::raycast PxGeometryQuery::overlap PxGeometryQuery::sweep + \see PxGeometryQuery::computePenetration PxGeometryQuery::pointDistance PxGeometryQuery::computeGeomBounds + \see PxMeshQuery::findOverlapTriangleMesh PxMeshQuery::findOverlapHeightField PxMeshQuery::sweep + */ + struct PxGeometryQueryFlag + { + enum Enum + { + eSIMD_GUARD = (1<<0), //!< Saves/restores SIMD control word for each query (safer but slower). Omit this if you took care of it yourself in your app. + + eDEFAULT = eSIMD_GUARD + }; + }; + + /** + \brief collection of set bits defined in PxGeometryQueryFlag. + + \see PxGeometryQueryFlag + */ + PX_FLAGS_TYPEDEF(PxGeometryQueryFlag, PxU32) + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGjkQuery.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGjkQuery.h new file mode 100644 index 000000000..211ea5550 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxGjkQuery.h @@ -0,0 +1,143 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_GJK_QUERY_H +#define PX_GJK_QUERY_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxTransform.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Collection of GJK query functions (sweeps, raycasts, overlaps, ...). +*/ +class PxGjkQuery +{ +public: + + /** + \brief Abstract interface for a user defined shape GJK mapping support. + A user defined shape consists of a core shape and a margin. If the distance + between two shapes' cores is equal to the sum of their margins, these shapes are + considered touching. + */ + struct Support + { + virtual ~Support() {} + /** + \brief Return the user defined shape margin. Margin should be greater than or equal to 0 + + \return Margin. + */ + virtual PxReal getMargin() const = 0; + /** + \brief Return the farthest point on the user defined shape's core in given direction. + + \param[in] dir Direction + + \return Farthest point in given direction. + */ + virtual PxVec3 supportLocal(const PxVec3& dir) const = 0; + }; + + /** + \brief Computes proximity information for two shapes using GJK-EPA algorithm + + \param[in] a Shape A support mapping + \param[in] b Shape B support mapping + \param[in] poseA Shape A transformation + \param[in] poseB Shape B transformation + \param[in] contactDistance The distance at which proximity info begins to be computed between the shapes + \param[in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units + \param[out] pointA The closest/deepest point on shape A surface + \param[out] pointB The closest/deepest point on shape B surface + \param[out] separatingAxis Translating shape B along 'separatingAxis' by 'separation' makes the shapes touching + \param[out] separation Translating shape B along 'separatingAxis' by 'separation' makes the shapes touching + + \return False if the distance is greater than contactDistance. + */ + PX_PHYSX_COMMON_API static bool proximityInfo(const Support& a, const Support& b, const PxTransform& poseA, const PxTransform& poseB, + PxReal contactDistance, PxReal toleranceLength, PxVec3& pointA, PxVec3& pointB, PxVec3& separatingAxis, PxReal& separation); + + /** + \brief Raycast test against the given shape. + + \param[in] shape Shape support mapping + \param[in] pose Shape transformation + \param[in] rayStart The start point of the ray to test the shape against + \param[in] unitDir Normalized direction of the ray to test the shape against + \param[in] maxDist Maximum ray length, has to be in the [0, inf) range + \param[out] t Hit distance + \param[out] n Hit normal + \param[out] p Hit point + + \return True if there is a hit. + */ + PX_PHYSX_COMMON_API static bool raycast(const Support& shape, const PxTransform& pose, const PxVec3& rayStart, + const PxVec3& unitDir, PxReal maxDist, PxReal& t, PxVec3& n, PxVec3& p); + + /** + \brief Overlap test for two shapes. + + \param[in] a Shape A support mapping + \param[in] b Shape B support mapping + \param[in] poseA Shape A transformation + \param[in] poseB Shape B transformation + + \return True if the shapes overlap. + */ + PX_PHYSX_COMMON_API static bool overlap(const Support& a, const Support& b, const PxTransform& poseA, const PxTransform& poseB); + + /** + \brief Sweep the shape B in space and test for collision with the shape A. + + \param[in] a Shape A support mapping + \param[in] b Shape B support mapping + \param[in] poseA Shape A transformation + \param[in] poseB Shape B transformation + \param[in] unitDir Normalized direction of the ray to test the shape against + \param[in] maxDist Maximum ray length, has to be in the [0, inf) range + \param[out] t Hit distance + \param[out] n Hit normal + \param[out] p Hit point + + \return True if there is a hit. + */ + PX_PHYSX_COMMON_API static bool sweep(const Support& a, const Support& b, const PxTransform& poseA, const PxTransform& poseB, + const PxVec3& unitDir, PxReal maxDist, PxReal& t, PxVec3& n, PxVec3& p); +}; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightField.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightField.h new file mode 100644 index 000000000..38cd5dab9 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightField.h @@ -0,0 +1,240 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HEIGHTFIELD_H +#define PX_HEIGHTFIELD_H + +#include "foundation/PxVec3.h" +#include "geometry/PxHeightFieldFlag.h" +#include "geometry/PxHeightFieldSample.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxHeightFieldDesc; + +/** +\brief A height field class. + +Height fields work in a similar way as triangle meshes specified to act as +height fields, with some important differences: + +Triangle meshes can be made of nonuniform geometry, while height fields are +regular, rectangular grids. This means that with PxHeightField, you sacrifice +flexibility in return for improved performance and decreased memory consumption. + +In local space rows extend in X direction, columns in Z direction and height in Y direction. + +Like Convexes and TriangleMeshes, HeightFields are referenced by shape instances +(see #PxHeightFieldGeometry, #PxShape). + +To avoid duplicating data when you have several instances of a particular +height field differently, you do not use this class to represent a +height field object directly. Instead, you create an instance of this height field +via the PxHeightFieldGeometry and PxShape classes. + +

Creation

+ +To create an instance of this class call PxPhysics::createHeightField() or +PxCooking::createHeightField(const PxHeightFieldDesc&, PxInsertionCallback&). +To delete it call release(). This is only possible +once you have released all of its PxHeightFiedShape instances. + +

Visualizations:

+\li #PxVisualizationParameter::eCOLLISION_AABBS +\li #PxVisualizationParameter::eCOLLISION_SHAPES +\li #PxVisualizationParameter::eCOLLISION_AXES +\li #PxVisualizationParameter::eCOLLISION_FNORMALS +\li #PxVisualizationParameter::eCOLLISION_EDGES + +\see PxHeightFieldDesc PxHeightFieldGeometry PxShape PxPhysics.createHeightField() PxCooking.createHeightField() +*/ + +class PxHeightField : public PxRefCounted +{ + public: + /** + \brief Decrements the reference count of a height field and releases it if the new reference count is zero. + + \see PxPhysics.createHeightField() PxHeightFieldDesc PxHeightFieldGeometry PxShape + */ + virtual void release() = 0; + + /** + \brief Writes out the sample data array. + + The user provides destBufferSize bytes storage at destBuffer. + The data is formatted and arranged as PxHeightFieldDesc.samples. + + \param[out] destBuffer The destination buffer for the sample data. + \param[in] destBufferSize The size of the destination buffer. + \return The number of bytes written. + + \see PxHeightFieldDesc.samples + */ + virtual PxU32 saveCells(void* destBuffer, PxU32 destBufferSize) const = 0; + + /** + \brief Replaces a rectangular subfield in the sample data array. + + The user provides the description of a rectangular subfield in subfieldDesc. + The data is formatted and arranged as PxHeightFieldDesc.samples. + + \param[in] startCol First cell in the destination heightfield to be modified. Can be negative. + \param[in] startRow First row in the destination heightfield to be modified. Can be negative. + \param[in] subfieldDesc Description of the source subfield to read the samples from. + \param[in] shrinkBounds If left as false, the bounds will never shrink but only grow. If set to true the bounds will be recomputed from all HF samples at O(nbColums*nbRows) perf cost. + \return True on success, false on failure. Failure can occur due to format mismatch. + + \note Modified samples are constrained to the same height quantization range as the original heightfield. + Source samples that are out of range of target heightfield will be clipped with no error. + PhysX does not keep a mapping from the heightfield to heightfield shapes that reference it. + Call PxShape::setGeometry on each shape which references the height field, to ensure that internal data structures are updated to reflect the new geometry. + Please note that PxShape::setGeometry does not guarantee correct/continuous behavior when objects are resting on top of old or new geometry. + + \see PxHeightFieldDesc.samples PxShape.setGeometry + */ + virtual bool modifySamples(PxI32 startCol, PxI32 startRow, const PxHeightFieldDesc& subfieldDesc, bool shrinkBounds = false) = 0; + + /** + \brief Retrieves the number of sample rows in the samples array. + + \return The number of sample rows in the samples array. + + \see PxHeightFieldDesc.nbRows + */ + virtual PxU32 getNbRows() const = 0; + + /** + \brief Retrieves the number of sample columns in the samples array. + + \return The number of sample columns in the samples array. + + \see PxHeightFieldDesc.nbColumns + */ + virtual PxU32 getNbColumns() const = 0; + + /** + \brief Retrieves the format of the sample data. + + \return The format of the sample data. + + \see PxHeightFieldDesc.format PxHeightFieldFormat + */ + virtual PxHeightFieldFormat::Enum getFormat() const = 0; + + /** + \brief Retrieves the offset in bytes between consecutive samples in the array. + + \return The offset in bytes between consecutive samples in the array. + + \see PxHeightFieldDesc.sampleStride + */ + virtual PxU32 getSampleStride() const = 0; + + /** + \brief Retrieves the convex edge threshold. + + \return The convex edge threshold. + + \see PxHeightFieldDesc.convexEdgeThreshold + */ + virtual PxReal getConvexEdgeThreshold() const = 0; + + /** + \brief Retrieves the flags bits, combined from values of the enum ::PxHeightFieldFlag. + + \return The flags bits, combined from values of the enum ::PxHeightFieldFlag. + + \see PxHeightFieldDesc.flags PxHeightFieldFlag + */ + virtual PxHeightFieldFlags getFlags() const = 0; + + /** + \brief Retrieves the height at the given coordinates in grid space. + + \return The height at the given coordinates or 0 if the coordinates are out of range. + */ + virtual PxReal getHeight(PxReal x, PxReal z) const = 0; + + /** + \brief Returns material table index of given triangle + + \note This function takes a post cooking triangle index. + + \param[in] triangleIndex (internal) index of desired triangle + \return Material table index, or 0xffff if no per-triangle materials are used + */ + virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const = 0; + + /** + \brief Returns a triangle face normal for a given triangle index + + \note This function takes a post cooking triangle index. + + \param[in] triangleIndex (internal) index of desired triangle + \return Triangle normal for a given triangle index + */ + virtual PxVec3 getTriangleNormal(PxTriangleID triangleIndex) const = 0; + + /** + \brief Returns heightfield sample of given row and column + + \param[in] row Given heightfield row + \param[in] column Given heightfield column + \return Heightfield sample + */ + virtual const PxHeightFieldSample& getSample(PxU32 row, PxU32 column) const = 0; + + /** + \brief Returns the number of times the heightfield data has been modified + + This method returns the number of times modifySamples has been called on this heightfield, so that code that has + retained state that depends on the heightfield can efficiently determine whether it has been modified. + + \return the number of times the heightfield sample data has been modified. + */ + virtual PxU32 getTimestamp() const = 0; + + virtual const char* getConcreteTypeName() const PX_OVERRIDE PX_FINAL { return "PxHeightField"; } + +protected: + PX_INLINE PxHeightField(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {} + PX_INLINE PxHeightField(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + virtual ~PxHeightField() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxHeightField", PxRefCounted); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldDesc.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldDesc.h new file mode 100644 index 000000000..57455073f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldDesc.h @@ -0,0 +1,181 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HEIGHTFIELD_DESC_H +#define PX_HEIGHTFIELD_DESC_H + +#include "common/PxPhysXCommonConfig.h" +#include "geometry/PxHeightFieldFlag.h" +#include "common/PxCoreUtilityTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Descriptor class for #PxHeightField. + +\note The heightfield data is *copied* when a PxHeightField object is created from this descriptor. After the call the +user may discard the height data. + +\see PxHeightField PxHeightFieldGeometry PxShape PxPhysics.createHeightField() PxCooking.createHeightField() +*/ +class PxHeightFieldDesc +{ +public: + + /** + \brief Number of sample rows in the height field samples array. + + \note Local space X-axis corresponds to rows. + + Range: >1
+ Default: 0 + */ + PxU32 nbRows; + + /** + \brief Number of sample columns in the height field samples array. + + \note Local space Z-axis corresponds to columns. + + Range: >1
+ Default: 0 + */ + PxU32 nbColumns; + + /** + \brief Format of the sample data. + + Currently the only supported format is PxHeightFieldFormat::eS16_TM: + + Default: PxHeightFieldFormat::eS16_TM + + \see PxHeightFormat PxHeightFieldDesc.samples + */ + PxHeightFieldFormat::Enum format; + + /** + \brief The samples array. + + It is copied to the SDK's storage at creation time. + + There are nbRows * nbColumn samples in the array, + which define nbRows * nbColumn vertices and cells, + of which (nbRows - 1) * (nbColumns - 1) cells are actually used. + + The array index of sample(row, column) = row * nbColumns + column. + The byte offset of sample(row, column) = sampleStride * (row * nbColumns + column). + The sample data follows at the offset and spans the number of bytes defined by the format. + Then there are zero or more unused bytes depending on sampleStride before the next sample. + + Default: NULL + + \see PxHeightFormat + */ + PxStridedData samples; + + /** + This threshold is used by the collision detection to determine if a height field edge is convex + and can generate contact points. + Usually the convexity of an edge is determined from the angle (or cosine of the angle) between + the normals of the faces sharing that edge. + The height field allows a more efficient approach by comparing height values of neighboring vertices. + This parameter offsets the comparison. Smaller changes than 0.5 will not alter the set of convex edges. + The rule of thumb is that larger values will result in fewer edge contacts. + + This parameter is ignored in contact generation with sphere and capsule primitives. + + Range: [0, PX_MAX_F32)
+ Default: 0 + */ + PxReal convexEdgeThreshold; + + /** + \brief Flags bits, combined from values of the enum ::PxHeightFieldFlag. + + Default: 0 + + \see PxHeightFieldFlag PxHeightFieldFlags + */ + PxHeightFieldFlags flags; + + /** + \brief Constructor sets to default. + */ + PX_INLINE PxHeightFieldDesc(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + \brief Returns true if the descriptor is valid. + \return True if the current settings are valid. + */ + PX_INLINE bool isValid() const; +}; + +PX_INLINE PxHeightFieldDesc::PxHeightFieldDesc() //constructor sets to default +{ + nbColumns = 0; + nbRows = 0; + format = PxHeightFieldFormat::eS16_TM; + convexEdgeThreshold = 0.0f; + flags = PxHeightFieldFlags(); +} + +PX_INLINE void PxHeightFieldDesc::setToDefault() +{ + *this = PxHeightFieldDesc(); +} + +PX_INLINE bool PxHeightFieldDesc::isValid() const +{ + if (nbColumns < 2) + return false; + if (nbRows < 2) + return false; + if(format != PxHeightFieldFormat::eS16_TM) + return false; + if (samples.stride < 4) + return false; + if (convexEdgeThreshold < 0) + return false; + if ((flags & PxHeightFieldFlag::eNO_BOUNDARY_EDGES) != flags) + return false; + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldFlag.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldFlag.h new file mode 100644 index 000000000..6263a4029 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldFlag.h @@ -0,0 +1,156 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HEIGHT_FIELD_FLAG_H +#define PX_HEIGHT_FIELD_FLAG_H + +#include "foundation/PxFlags.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Describes the format of height field samples. +\see PxHeightFieldDesc.format PxHeightFieldDesc.samples +*/ +struct PxHeightFieldFormat +{ + enum Enum + { + /** + \brief Height field height data is 16 bit signed integers, followed by triangle materials. + + Each sample is 32 bits wide arranged as follows: + + \image html heightFieldFormat_S16_TM.png + + 1) First there is a 16 bit height value. + 2) Next, two one byte material indices, with the high bit of each byte reserved for special use. + (so the material index is only 7 bits). + The high bit of material0 is the tess-flag. + The high bit of material1 is reserved for future use. + + There are zero or more unused bytes before the next sample depending on PxHeightFieldDesc.sampleStride, + where the application may eventually keep its own data. + + This is the only format supported at the moment. + + \see PxHeightFieldDesc.format PxHeightFieldDesc.samples + */ + eS16_TM = (1 << 0) + }; +}; + +/** +\brief Determines the tessellation of height field cells. +\see PxHeightFieldDesc.format PxHeightFieldDesc.samples +*/ +struct PxHeightFieldTessFlag +{ + enum Enum + { + /** + \brief This flag determines which way each quad cell is subdivided. + + The flag lowered indicates subdivision like this: (the 0th vertex is referenced by only one triangle) + + \image html heightfieldTriMat2.PNG + +
+		+--+--+--+---> column
+		| /| /| /|
+		|/ |/ |/ |
+		+--+--+--+
+		| /| /| /|
+		|/ |/ |/ |
+		+--+--+--+
+		|
+		|
+		V row
+		
+ + The flag raised indicates subdivision like this: (the 0th vertex is shared by two triangles) + + \image html heightfieldTriMat1.PNG + +
+		+--+--+--+---> column
+		|\ |\ |\ |
+		| \| \| \|
+		+--+--+--+
+		|\ |\ |\ |
+		| \| \| \|
+		+--+--+--+
+		|
+		|
+		V row
+		
+ + \see PxHeightFieldDesc.format PxHeightFieldDesc.samples + */ + e0TH_VERTEX_SHARED = (1 << 0) + }; +}; + + +/** +\brief Enum with flag values to be used in PxHeightFieldDesc.flags. +*/ +struct PxHeightFieldFlag +{ + enum Enum + { + /** + \brief Disable collisions with height field with boundary edges. + + Raise this flag if several terrain patches are going to be placed adjacent to each other, + to avoid a bump when sliding across. + + This flag is ignored in contact generation with sphere and capsule shapes. + + \see PxHeightFieldDesc.flags + */ + eNO_BOUNDARY_EDGES = (1 << 0) + }; +}; + +/** +\brief collection of set bits defined in PxHeightFieldFlag. + +\see PxHeightFieldFlag +*/ +typedef PxFlags PxHeightFieldFlags; +PX_FLAGS_OPERATORS(PxHeightFieldFlag::Enum,PxU16) + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldGeometry.h new file mode 100644 index 000000000..674336ff3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldGeometry.h @@ -0,0 +1,159 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HEIGHT_FIELD_GEOMETRY_H +#define PX_HEIGHT_FIELD_GEOMETRY_H +#include "geometry/PxTriangleMeshGeometry.h" +#include "common/PxCoreUtilityTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#define PX_MIN_HEIGHTFIELD_XZ_SCALE 1e-8f +#define PX_MIN_HEIGHTFIELD_Y_SCALE (0.0001f / PxReal(0xFFFF)) + +class PxHeightField; + +/** +\brief Height field geometry class. + +This class allows to create a scaled height field geometry instance. + +There is a minimum allowed value for Y and XZ scaling - PX_MIN_HEIGHTFIELD_XZ_SCALE, heightfield creation will fail if XZ value is below this value. +*/ +class PxHeightFieldGeometry : public PxGeometry +{ +public: + /** + \brief Constructor. + */ + PX_INLINE PxHeightFieldGeometry(PxHeightField* hf = NULL, + PxMeshGeometryFlags flags = PxMeshGeometryFlag::Enum(0), + PxReal heightScale_ = 1.0f, + PxReal rowScale_ = 1.0f, + PxReal columnScale_ = 1.0f) : + PxGeometry (PxGeometryType::eHEIGHTFIELD), + heightField (hf), + heightScale (heightScale_), + rowScale (rowScale_), + columnScale (columnScale_), + heightFieldFlags (flags) + { + } + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxHeightFieldGeometry(const PxHeightFieldGeometry& that) : + PxGeometry (that), + heightField (that.heightField), + heightScale (that.heightScale), + rowScale (that.rowScale), + columnScale (that.columnScale), + heightFieldFlags (that.heightFieldFlags) + { + } + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxHeightFieldGeometry& that) + { + mType = that.mType; + heightField = that.heightField; + heightScale = that.heightScale; + rowScale = that.rowScale; + columnScale = that.columnScale; + heightFieldFlags = that.heightFieldFlags; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid + + \note A valid height field has a positive scale value in each direction (heightScale > 0, rowScale > 0, columnScale > 0). + It is illegal to call PxPhysics::createShape with a height field that has zero extents in any direction. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + +public: + /** + \brief The height field data. + */ + PxHeightField* heightField; + + /** + \brief The scaling factor for the height field in vertical direction (y direction in local space). + */ + PxReal heightScale; + + /** + \brief The scaling factor for the height field in the row direction (x direction in local space). + */ + PxReal rowScale; + + /** + \brief The scaling factor for the height field in the column direction (z direction in local space). + */ + PxReal columnScale; + + /** + \brief Flags to specify some collision properties for the height field. + */ + PxMeshGeometryFlags heightFieldFlags; + + PxPadding<3> paddingFromFlags; //!< padding for mesh flags. +}; + + +PX_INLINE bool PxHeightFieldGeometry::isValid() const +{ + if(mType != PxGeometryType::eHEIGHTFIELD) + return false; + if(!PxIsFinite(heightScale) || !PxIsFinite(rowScale) || !PxIsFinite(columnScale)) + return false; + if(rowScale < PX_MIN_HEIGHTFIELD_XZ_SCALE || columnScale < PX_MIN_HEIGHTFIELD_XZ_SCALE || heightScale < PX_MIN_HEIGHTFIELD_Y_SCALE) + return false; + if(!heightField) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldSample.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldSample.h new file mode 100644 index 000000000..48a783274 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxHeightFieldSample.h @@ -0,0 +1,112 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_HEIGHT_FIELD_SAMPLE_H +#define PX_HEIGHT_FIELD_SAMPLE_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxBitAndData.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Special material index values for height field samples. + +\see PxHeightFieldSample.materialIndex0 PxHeightFieldSample.materialIndex1 +*/ +struct PxHeightFieldMaterial +{ + enum Enum + { + eHOLE = 127 //!< A material indicating that the triangle should be treated as a hole in the mesh. + }; +}; + +/** +\brief Heightfield sample format. + +This format corresponds to the #PxHeightFieldFormat member PxHeightFieldFormat::eS16_TM. + +An array of heightfield samples are used when creating a PxHeightField to specify +the elevation of the heightfield points. In addition the material and tessellation of the adjacent +triangles are specified. + +\see PxHeightField PxHeightFieldDesc PxHeightFieldDesc.samples +*/ +struct PxHeightFieldSample +{ + /** + \brief The height of the heightfield sample + + This value is scaled by PxHeightFieldGeometry::heightScale. + + \see PxHeightFieldGeometry + */ + PxI16 height; + + /** + \brief The triangle material index of the quad's lower triangle + tesselation flag + + An index pointing into the material table of the shape which instantiates the heightfield. + This index determines the material of the lower of the quad's two triangles (i.e. the quad whose + upper-left corner is this sample, see the Guide for illustrations). + + Special values of the 7 data bits are defined by PxHeightFieldMaterial + + The tesselation flag specifies which way the quad is split whose upper left corner is this sample. + If the flag is set, the diagonal of the quad will run from this sample to the opposite vertex; if not, + it will run between the other two vertices (see the Guide for illustrations). + + \see PxHeightFieldGeometry materialIndex1 PxShape.setmaterials() PxShape.getMaterials() + */ + PxBitAndByte materialIndex0; + + PX_CUDA_CALLABLE PX_FORCE_INLINE PxU8 tessFlag() const { return PxU8(materialIndex0.isBitSet() ? 1 : 0); } // PT: explicit conversion to make sure we don't break the code + PX_CUDA_CALLABLE PX_FORCE_INLINE void setTessFlag() { materialIndex0.setBit(); } + PX_CUDA_CALLABLE PX_FORCE_INLINE void clearTessFlag() { materialIndex0.clearBit(); } + + /** + \brief The triangle material index of the quad's upper triangle + reserved flag + + An index pointing into the material table of the shape which instantiates the heightfield. + This index determines the material of the upper of the quad's two triangles (i.e. the quad whose + upper-left corner is this sample, see the Guide for illustrations). + + \see PxHeightFieldGeometry materialIndex0 PxShape.setmaterials() PxShape.getMaterials() + */ + PxBitAndByte materialIndex1; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxMeshQuery.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxMeshQuery.h new file mode 100644 index 000000000..daf2f50a2 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxMeshQuery.h @@ -0,0 +1,283 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MESH_QUERY_H +#define PX_MESH_QUERY_H + + +#include "foundation/PxTransform.h" +#include "common/PxPhysXCommonConfig.h" +#include "geometry/PxGeometryHit.h" +#include "geometry/PxGeometryQueryFlags.h" +#include "geometry/PxReportCallback.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxGeometry; +class PxConvexMeshGeometry; +class PxTriangleMeshGeometry; +class PxHeightFieldGeometry; + +class PxTriangle; + + struct PxMeshMeshQueryFlag + { + enum Enum + { + eDEFAULT = 0, //!< Report all overlaps + eDISCARD_COPLANAR = (1<<0), //!< Ignore coplanar triangle-triangle overlaps + eRESERVED = (1<<1), //!< Reserved flag + eRESERVED1 = (1<<1), //!< Reserved flag + eRESERVED2 = (1<<2), //!< Reserved flag + eRESERVED3 = (1<<3) //!< Reserved flag + }; + }; + + PX_FLAGS_TYPEDEF(PxMeshMeshQueryFlag, PxU32) + +class PxMeshQuery +{ +public: + + /** + \brief Retrieves triangle data from a triangle ID. + + This function can be used together with #findOverlapTriangleMesh() to retrieve triangle properties. + + \param[in] triGeom Geometry of the triangle mesh to extract the triangle from. + \param[in] transform Transform for the triangle mesh + \param[in] triangleIndex The index of the triangle to retrieve. + \param[out] triangle Triangle points in world space. + \param[out] vertexIndices Returned vertex indices for given triangle + \param[out] adjacencyIndices Returned 3 triangle adjacency internal face indices (0xFFFFFFFF if no adjacency). The mesh must be cooked with cooking param buildTriangleAdjacencies enabled. + + \note This function will flip the triangle normal whenever triGeom.scale.hasNegativeDeterminant() is true. + + \see PxTriangle PxTriangleFlags PxTriangleID findOverlapTriangleMesh() + */ + PX_PHYSX_COMMON_API static void getTriangle(const PxTriangleMeshGeometry& triGeom, const PxTransform& transform, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices=NULL, PxU32* adjacencyIndices=NULL); + + + /** + \brief Retrieves triangle data from a triangle ID. + + This function can be used together with #findOverlapHeightField() to retrieve triangle properties. + + \param[in] hfGeom Geometry of the height field to extract the triangle from. + \param[in] transform Transform for the height field. + \param[in] triangleIndex The index of the triangle to retrieve. + \param[out] triangle Triangle points in world space. + \param[out] vertexIndices Returned vertex indices for given triangle + \param[out] adjacencyIndices Returned 3 triangle adjacency triangle indices (0xFFFFFFFF if no adjacency). + + \note This function will flip the triangle normal whenever triGeom.scale.hasNegativeDeterminant() is true. + \note TriangleIndex is an index used in internal format, which does have an index out of the bounds in last row. + To traverse all tri indices in the HF, the following code can be applied: + for (PxU32 row = 0; row < (nbRows - 1); row++) + { + for (PxU32 col = 0; col < (nbCols - 1); col++) + { + for (PxU32 k = 0; k < 2; k++) + { + const PxU32 triIndex = 2 * (row*nbCols + col) + k; + .... + } + } + } + \see PxTriangle PxTriangleFlags PxTriangleID findOverlapHeightField() + */ + PX_PHYSX_COMMON_API static void getTriangle(const PxHeightFieldGeometry& hfGeom, const PxTransform& transform, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices=NULL, PxU32* adjacencyIndices=NULL); + + + /** + \brief Find the mesh triangles which touch the specified geometry object. + + For mesh-vs-mesh overlap tests, please use the specialized function below. + + Returned triangle indices can be used with #getTriangle() to retrieve the triangle properties. + + \param[in] geom The geometry object to test for mesh triangle overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry + \param[in] geomPose Pose of the geometry object + \param[in] meshGeom The triangle mesh geometry to check overlap against + \param[in] meshPose Pose of the triangle mesh + \param[out] results Indices of overlapping triangles + \param[in] maxResults Size of 'results' buffer + \param[in] startIndex Index of first result to be retrieved. Previous indices are skipped. + \param[out] overflow True if a buffer overflow occurred + \param[in] queryFlags Optional flags controlling the query. + \return Number of overlaps found, i.e. number of elements written to the results buffer + + \see PxTriangleMeshGeometry getTriangle() PxGeometryQueryFlags + */ + PX_PHYSX_COMMON_API static PxU32 findOverlapTriangleMesh( const PxGeometry& geom, const PxTransform& geomPose, + const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose, + PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT); + + /** + \brief Mesh-vs-mesh overlap test + + A specialized findOverlapTriangleMesh function for mesh-vs-mesh. The other findOverlapTriangleMesh() function above cannot be used + directly since it only returns a single set of triangle indices that belongs to one of the meshes only. This function returns pairs + of triangle indices that belong to both the first & second input meshes. + + Returned triangle indices can be used with #getTriangle() to retrieve the triangle properties. + + \note This is only implemented for the PxMeshMidPhase::eBVH34 data structure. + + \param[in] callback The callback object used to report results + \param[in] meshGeom0 First triangle mesh geometry + \param[in] meshPose0 Pose of first triangle mesh geometry + \param[in] meshGeom1 Second triangle mesh geometry + \param[in] meshPose1 Pose of second triangle mesh geometry + \param[in] queryFlags Optional flags controlling the query. + \param[in] meshMeshFlags Optional flags controlling the query. + \param[in] tolerance Optional tolerance distance + \return true if an overlap has been detected, false if the meshes are disjoint + + \see PxTriangleMeshGeometry getTriangle() PxReportCallback PxGeometryQueryFlags PxMeshMeshQueryFlags + */ + PX_DEPRECATED PX_PHYSX_COMMON_API static bool findOverlapTriangleMesh(PxReportCallback& callback, + const PxTriangleMeshGeometry& meshGeom0, const PxTransform& meshPose0, + const PxTriangleMeshGeometry& meshGeom1, const PxTransform& meshPose1, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT, + PxMeshMeshQueryFlags meshMeshFlags = PxMeshMeshQueryFlag::eDEFAULT, + float tolerance = 0.0f); + + /** + \brief Mesh-vs-mesh overlap test + + A specialized findOverlapTriangleMesh function for mesh-vs-mesh. The other findOverlapTriangleMesh() function above cannot be used + directly since it only returns a single set of triangle indices that belongs to one of the meshes only. This function returns pairs + of triangle indices that belong to both the first & second input meshes. + + Returned triangle indices can be used with #getTriangle() to retrieve the triangle properties. + + If a non-zero tolerance is used, the function performs distance queries (rather than pure overlaps) between involved triangles, + and returned data also includes the distance between reported triangles. + + \note This is only implemented for the PxMeshMidPhase::eBVH34 data structure. + + \param[in] callback The callback object used to report results + \param[in] meshGeom0 First triangle mesh geometry + \param[in] meshPose0 Pose of first triangle mesh geometry + \param[in] meshGeom1 Second triangle mesh geometry + \param[in] meshPose1 Pose of second triangle mesh geometry + \param[in] queryFlags Optional flags controlling the query. + \param[in] meshMeshFlags Optional flags controlling the query. + \param[in] tolerance Optional tolerance distance + \return true if an overlap has been detected, false if the meshes are disjoint + + \see PxTriangleMeshGeometry getTriangle() PxReportCallback PxGeometryQueryFlags PxMeshMeshQueryFlags + */ + PX_PHYSX_COMMON_API static bool findOverlapTriangleMesh(PxReportCallback& callback, + const PxTriangleMeshGeometry& meshGeom0, const PxTransform& meshPose0, + const PxTriangleMeshGeometry& meshGeom1, const PxTransform& meshPose1, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT, + PxMeshMeshQueryFlags meshMeshFlags = PxMeshMeshQueryFlag::eDEFAULT, + float tolerance = 0.0f); + + /** + \brief Find the height field triangles which touch the specified geometry object. + + Returned triangle indices can be used with #getTriangle() to retrieve the triangle properties. + + \param[in] geom The geometry object to test for height field overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry. The sphere and capsule queries are currently conservative estimates. + \param[in] geomPose Pose of the geometry object + \param[in] hfGeom The height field geometry to check overlap against + \param[in] hfPose Pose of the height field + \param[out] results Indices of overlapping triangles + \param[in] maxResults Size of 'results' buffer + \param[in] startIndex Index of first result to be retrieved. Previous indices are skipped. + \param[out] overflow True if a buffer overflow occurred + \param[in] queryFlags Optional flags controlling the query. + \return Number of overlaps found, i.e. number of elements written to the results buffer + + \see PxHeightFieldGeometry getTriangle() PxGeometryQueryFlags + */ + PX_PHYSX_COMMON_API static PxU32 findOverlapHeightField(const PxGeometry& geom, const PxTransform& geomPose, + const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose, + PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT); + + + /** + \brief Sweep a specified geometry object in space and test for collision with a set of given triangles. + + This function simply sweeps input geometry against each input triangle, in the order they are given. + This is an O(N) operation with N = number of input triangles. It does not use any particular acceleration structure. + + \param[in] unitDir Normalized direction of the sweep. + \param[in] distance Sweep distance. Needs to be larger than 0. Clamped to PX_MAX_SWEEP_DISTANCE. + \param[in] geom The geometry object to sweep. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry + \param[in] pose Pose of the geometry object to sweep. + \param[in] triangleCount Number of specified triangles + \param[in] triangles Array of triangles to sweep against + \param[out] sweepHit The sweep hit information. See the notes below for limitations about returned results. + \param[in] hitFlags Specification of the kind of information to retrieve on hit. Combination of #PxHitFlag flags. See the notes below for limitations about supported flags. + \param[in] cachedIndex Cached triangle index for subsequent calls. Cached triangle is tested first. Optional parameter. + \param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal. + \param[in] doubleSided Counterpart of PxMeshGeometryFlag::eDOUBLE_SIDED for input triangles. + \param[in] queryFlags Optional flags controlling the query. + \return True if the swept geometry object hits the specified triangles + + \note Only the following geometry types are currently supported: PxSphereGeometry, PxCapsuleGeometry, PxBoxGeometry + \note If a shape from the scene is already overlapping with the query shape in its starting position, the hit is returned unless eASSUME_NO_INITIAL_OVERLAP was specified. + \note This function returns a single closest hit across all the input triangles. Multiple hits are not supported. + \note Supported hitFlags are PxHitFlag::eDEFAULT, PxHitFlag::eASSUME_NO_INITIAL_OVERLAP, PxHitFlag::ePRECISE_SWEEP, PxHitFlag::eMESH_BOTH_SIDES, PxHitFlag::eANY_HIT. + \note ePOSITION is only defined when there is no initial overlap (sweepHit.hadInitialOverlap() == false) + \note The returned normal for initially overlapping sweeps is set to -unitDir. + \note Otherwise the returned normal is the front normal of the triangle even if PxHitFlag::eMESH_BOTH_SIDES is set. + \note The returned PxGeomSweepHit::faceIndex parameter will hold the index of the hit triangle in input array, i.e. the range is [0; triangleCount). For initially overlapping sweeps, this is the index of overlapping triangle. + \note The inflation parameter is not compatible with PxHitFlag::ePRECISE_SWEEP. + + \see PxTriangle PxSweepHit PxGeometry PxTransform PxGeometryQueryFlags + */ + PX_PHYSX_COMMON_API static bool sweep(const PxVec3& unitDir, + const PxReal distance, + const PxGeometry& geom, + const PxTransform& pose, + PxU32 triangleCount, + const PxTriangle* triangles, + PxGeomSweepHit& sweepHit, + PxHitFlags hitFlags = PxHitFlag::eDEFAULT, + const PxU32* cachedIndex = NULL, + const PxReal inflation = 0.0f, + bool doubleSided = false, + PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT); +}; + + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxMeshScale.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxMeshScale.h new file mode 100644 index 000000000..fc2576bea --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxMeshScale.h @@ -0,0 +1,162 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_MESH_SCALE_H +#define PX_MESH_SCALE_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxMat33.h" +#include "foundation/PxAssert.h" + +/** \brief Minimum allowed absolute magnitude for each of mesh scale's components (x,y,z). + \note Only positive scale values are allowed for convex meshes. */ +#define PX_MESH_SCALE_MIN 1e-6f + +/** \brief Maximum allowed absolute magnitude for each of mesh scale's components (x,y,z). + \note Only positive scale values are allowed for convex meshes. */ +#define PX_MESH_SCALE_MAX 1e6f + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief A class expressing a nonuniform scaling transformation. + +The scaling is along arbitrary axes that are specified by PxMeshScale::rotation. Specifically, PxMeshScale::rotation +describes the rotation from the scaling-axes frame to the mesh-local frame, i.e. PxMeshScale::rotation.rotate(v) transforms +the coordinates of vertex v from the mesh-local frame to the scaling-axes frame. + +\note Negative scale values are supported for PxTriangleMeshGeometry + with absolute values for each component within [PX_MIN_ABS_MESH_SCALE, PX_MAX_ABS_MESH_SCALE] range. + Negative scale causes a reflection around the specified axis, in addition PhysX will flip the normals + for mesh triangles when scale.x*scale.y*scale.z < 0. +\note Only positive scale values are supported for PxConvexMeshGeometry + with values for each component within [PX_MIN_ABS_MESH_SCALE, PX_MAX_ABS_MESH_SCALE] range). + +\see PxConvexMeshGeometry PxTriangleMeshGeometry +*/ +class PxMeshScale +{ +public: + /** + \brief Constructor initializes to identity scale. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(): scale(1.0f), rotation(PxIdentity) + { + } + + /** + \brief Constructor from scalar. + */ + explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(PxReal r): scale(r), rotation(PxIdentity) + { + } + + /** + \brief Constructor to initialize to arbitrary scale and identity scale rotation. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(const PxVec3& s) + { + scale = s; + rotation = PxQuat(PxIdentity); + } + + /** + \brief Constructor to initialize to arbitrary scaling. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(const PxVec3& s, const PxQuat& r) + { + PX_ASSERT(r.isUnit()); + scale = s; + rotation = r; + } + + /** + \brief Returns true if the scaling is an identity transformation. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool isIdentity() const + { + return (scale.x == 1.0f && scale.y == 1.0f && scale.z == 1.0f); + } + + /** + \brief Returns the inverse of this scaling transformation. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale getInverse() const + { + return PxMeshScale(PxVec3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z), rotation); + } + + /** + \brief Converts this transformation to a 3x3 matrix representation. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33 toMat33() const + { + PxMat33 rot(rotation); + PxMat33 trans = rot.getTranspose(); + trans.column0 *= scale[0]; + trans.column1 *= scale[1]; + trans.column2 *= scale[2]; + return trans * rot; + } + + /** + \brief Returns true if combination of negative scale components will cause the triangle normal to flip. The SDK will flip the normals internally. + */ + PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNegativeDeterminant() const + { + return (scale.x * scale.y * scale.z < 0.0f); + } + + PxVec3 transform(const PxVec3& v) const + { + return rotation.rotateInv(scale.multiply(rotation.rotate(v))); + } + + bool isValidForTriangleMesh() const + { + PxVec3 absXYZ = scale.abs(); + return (absXYZ.maxElement() <= PX_MESH_SCALE_MAX) && (absXYZ.minElement() >= PX_MESH_SCALE_MIN); + } + + bool isValidForConvexMesh() const + { + return (scale.maxElement() <= PX_MESH_SCALE_MAX) && (scale.minElement() >= PX_MESH_SCALE_MIN); + } + + PxVec3 scale; //!< A nonuniform scaling + PxQuat rotation; //!< The orientation of the scaling axes +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxParticleSystemGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxParticleSystemGeometry.h new file mode 100644 index 000000000..f08066473 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxParticleSystemGeometry.h @@ -0,0 +1,95 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PARTICLESYSTEM_GEOMETRY_H +#define PX_PARTICLESYSTEM_GEOMETRY_H +#include "geometry/PxGeometry.h" +#include "common/PxCoreUtilityTypes.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxVec4.h" +#include "PxParticleSystem.h" +#include "PxParticleSolverType.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Particle system geometry class. + + */ + class PxParticleSystemGeometry : public PxGeometry + { + public: + /** + \brief Default constructor. + + Creates an empty object with no particles. + */ + PX_INLINE PxParticleSystemGeometry() : PxGeometry(PxGeometryType::ePARTICLESYSTEM){} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxParticleSystemGeometry(const PxParticleSystemGeometry& that) : PxGeometry(that) {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxParticleSystemGeometry& that) + { + mType = that.mType; + mSolverType = that.mSolverType; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid for shape creation. + + \see PxPhysics::createShape + */ + PX_FORCE_INLINE bool isValid() const + { + if(mType != PxGeometryType::ePARTICLESYSTEM) + return false; + + return true; + } + + PX_DEPRECATED PxParticleSolverType::Enum mSolverType; + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxPlaneGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxPlaneGeometry.h new file mode 100644 index 000000000..9cdb9a83c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxPlaneGeometry.h @@ -0,0 +1,95 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PLANE_GEOMETRY_H +#define PX_PLANE_GEOMETRY_H +#include "geometry/PxGeometry.h" +#include "foundation/PxFoundationConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Class describing a plane geometry. + +The plane geometry specifies the half-space volume x<=0. As with other geometry types, +when used in a PxShape the collision volume is obtained by transforming the halfspace +by the shape local pose and the actor global pose. + +To generate a PxPlane from a PxTransform, transform PxPlane(1,0,0,0). + +To generate a PxTransform from a PxPlane, use PxTransformFromPlaneEquation. + +\see PxShape.setGeometry() PxShape.getPlaneGeometry() PxTransformFromPlaneEquation +*/ +class PxPlaneGeometry : public PxGeometry +{ +public: + /** + \brief Constructor. + */ + PX_INLINE PxPlaneGeometry() : PxGeometry(PxGeometryType::ePLANE) {} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxPlaneGeometry(const PxPlaneGeometry& that) : PxGeometry(that) {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxPlaneGeometry& that) + { + mType = that.mType; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid + */ + PX_INLINE bool isValid() const; +}; + +PX_INLINE bool PxPlaneGeometry::isValid() const +{ + if(mType != PxGeometryType::ePLANE) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxReportCallback.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxReportCallback.h new file mode 100644 index 000000000..f6b027d74 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxReportCallback.h @@ -0,0 +1,268 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_REPORT_CALLBACK_H +#define PX_REPORT_CALLBACK_H + + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxArray.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Base class for all report callbacks. + + \see PxRegularReportCallback PxLocalStorageReportCallback PxExternalStorageReportCallback PxDynamicArrayReportCallback + */ + class PxReportCallbackBase + { + public: + PxReportCallbackBase(PxU32 capacity=0) : mCapacity(capacity), mSize(0) {} + virtual ~PxReportCallbackBase() {} + + PxU32 mCapacity; // Capacity of mBuffer. If mBuffer is NULL, this controls how many items are reported to users at the same time (with a limit of 256). + PxU32 mSize; // Current number of items in the buffer. This is entirely managed by the system. + }; + + /** + \brief Base class for callback reporting an unknown number of items to users. + + This can be used as-is and customized by users, or several pre-designed callbacks can be used instead (see below). + + This design lets users decide how to retrieve the results of a query: + - either one by one via a regular callback + - or one batch at a time via a callback + - or written out directly to their own C-style buffer + - or pushed back to their own PxArray + - etc + + \see PxRegularReportCallback PxLocalStorageReportCallback PxExternalStorageReportCallback PxDynamicArrayReportCallback + */ + template + class PxReportCallback : public PxReportCallbackBase + { + public: + PxReportCallback(T* buffer=NULL, PxU32 capacity=0) : PxReportCallbackBase(capacity), mBuffer(buffer) {} + virtual ~PxReportCallback() {} + + T* mBuffer; // Destination buffer for writing results. if NULL, the system will use its internal buffer and set that pointer as it sees fit. + // Otherwise users can set it to where they want the results to be written. + + /** + \brief Reports query results to users. + + This will be called by the system as many times as necessary to report all results. + + \param[in] nbItems Number of reported items + \param[in] items array of reported items + + \return true to continue the query, false to abort the query + */ + virtual bool flushResults(PxU32 nbItems, const T* items) = 0; + }; + + /** + \brief Regular report callback + + This reports results like a regular callback would: + - without explicit buffer management from users + - by default, one item at a time + + This customized callback sends results to users via the processResults() function. + + The capacity parameter dictates how many items can be reported at a time, + i.e. how many times the flushResults/processResults function will be called by the system. + + \see PxReportCallback + */ + template + class PxRegularReportCallback : public PxReportCallback + { + public: + PxRegularReportCallback(const PxU32 capacity=1) + { + PX_ASSERT(capacity<=256); + this->mCapacity = capacity; + } + + virtual bool flushResults(PxU32 nbItems, const T* items) + { + PX_ASSERT(nbItems<=this->mCapacity); + PX_ASSERT(items==this->mBuffer); + return processResults(nbItems, items); + } + + /** + \brief Reports query results to users. + + \param[in] nbItems Number of reported items + \param[in] items array of reported items + + \return true to continue the query, false to abort the query + */ + virtual bool processResults(PxU32 nbItems, const T* items) = 0; + }; + + /** + \brief Local storage report callback + + This is the same as a regular callback, except the destination buffer is a local buffer within the class. + + This customized callback sends results to users via the processResults() function. + + The capacity of the embedded buffer (determined by a template parameter) dictates how many items can be reported at a time, + i.e. how many times the flushResults/processResults function will be called by the system. + + \see PxReportCallback + */ + template + class PxLocalStorageReportCallback : public PxReportCallback + { + T mLocalStorage[capacityT]; + + public: + PxLocalStorageReportCallback() + { + this->mBuffer = mLocalStorage; + this->mCapacity = capacityT; + } + + virtual bool flushResults(PxU32 nbItems, const T* items) + { + PX_ASSERT(items==mLocalStorage); + PX_ASSERT(nbItems<=this->mCapacity); + return processResults(nbItems, items); + } + + /** + \brief Reports query results to users. + + \param[in] nbItems Number of reported items + \param[in] items array of reported items + + \return true to continue the query, false to abort the query + */ + virtual bool processResults(PxU32 nbItems, const T* items) = 0; + }; + + /** + \brief External storage report callback + + This is the same as a regular callback, except the destination buffer is a user-provided external buffer. + + Typically the provided buffer can be larger here than for PxLocalStorageReportCallback, and it could + even be a scratchpad-kind of memory shared by multiple sub-systems. + + This would be the same as having a C-style buffer to write out results in the query interface. + + This customized callback sends results to users via the processResults() function. + + The capacity parameter dictates how many items can be reported at a time, + i.e. how many times the flushResults/processResults function will be called by the system. + + \see PxReportCallback + */ + template + class PxExternalStorageReportCallback : public PxReportCallback + { + public: + PxExternalStorageReportCallback(T* buffer, PxU32 capacity) + { + this->mBuffer = buffer; + this->mCapacity = capacity; + } + + virtual bool flushResults(PxU32 nbItems, const T* items) + { + PX_ASSERT(items==this->mBuffer); + PX_ASSERT(nbItems<=this->mCapacity); + return processResults(nbItems, items); + } + + /** + \brief Reports query results to users. + + \param[in] nbItems Number of reported items + \param[in] items array of reported items + + \return true to continue the query, false to abort the query + */ + virtual bool processResults(PxU32 nbItems, const T* items) = 0; + }; + + /** + \brief Dynamic array report callback + + This callback emulates the behavior of pushing results to a (user-provided) dynamic array. + + This customized callback does not actually call users back during the query, results are + available afterwards in the provided dynamic array. This would be the same as having a PxArray + directly in the query interface. + + \see PxReportCallback + */ + template + class PxDynamicArrayReportCallback : public PxReportCallback + { + public: + PxDynamicArrayReportCallback(PxArray& results) : mResults(results) + { + mResults.reserve(32); + this->mBuffer = mResults.begin(); + this->mCapacity = mResults.capacity(); + } + + virtual bool flushResults(PxU32 nbItems, const T* /*items*/) + { + const PxU32 size = mResults.size(); + const PxU32 capa = mResults.capacity(); + const PxU32 newSize = size+nbItems; + PX_ASSERT(newSize<=capa); + mResults.forceSize_Unsafe(newSize); + if(newSize==capa) + { + const PxU32 newCapa = capa*2; + mResults.reserve(newCapa); + this->mBuffer = mResults.begin() + newSize; + this->mCapacity = mResults.capacity() - newSize; + } + return true; + } + + PxArray& mResults; + }; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxSimpleTriangleMesh.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxSimpleTriangleMesh.h new file mode 100644 index 000000000..077b6538a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxSimpleTriangleMesh.h @@ -0,0 +1,160 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SIMPLE_TRIANGLE_MESH_H +#define PX_SIMPLE_TRIANGLE_MESH_H + +#include "foundation/PxVec3.h" +#include "foundation/PxFlags.h" +#include "common/PxCoreUtilityTypes.h" +#include "common/PxPhysXCommonConfig.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Enum with flag values to be used in PxSimpleTriangleMesh::flags. +*/ +struct PxMeshFlag +{ + enum Enum + { + /** + \brief Specifies if the SDK should flip normals. + + The PhysX libraries assume that the face normal of a triangle with vertices [a,b,c] can be computed as: + edge1 = b-a + edge2 = c-a + face_normal = edge1 x edge2. + + Note: This is the same as a counterclockwise winding in a right handed coordinate system or + alternatively a clockwise winding order in a left handed coordinate system. + + If this does not match the winding order for your triangles, raise the below flag. + */ + eFLIPNORMALS = (1<<0), + e16_BIT_INDICES = (1<<1) //!< Denotes the use of 16-bit vertex indices + }; +}; + +/** +\brief collection of set bits defined in PxMeshFlag. + +\see PxMeshFlag +*/ +typedef PxFlags PxMeshFlags; +PX_FLAGS_OPERATORS(PxMeshFlag::Enum,PxU16) + + +/** +\brief A structure describing a triangle mesh. +*/ +class PxSimpleTriangleMesh +{ +public: + + /** + \brief Pointer to first vertex point. + */ + PxBoundedData points; + + /** + \brief Pointer to first triangle. + + Caller may add triangleStrideBytes bytes to the pointer to access the next triangle. + + These are triplets of 0 based indices: + vert0 vert1 vert2 + vert0 vert1 vert2 + vert0 vert1 vert2 + ... + + where vertex is either a 32 or 16 bit unsigned integer. There are numTriangles*3 indices. + + This is declared as a void pointer because it is actually either an PxU16 or a PxU32 pointer. + */ + PxBoundedData triangles; + + /** + \brief Flags bits, combined from values of the enum ::PxMeshFlag + */ + PxMeshFlags flags; + + /** + \brief constructor sets to default. + */ + PX_INLINE PxSimpleTriangleMesh(); + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + /** + \brief returns true if the current settings are valid + */ + PX_INLINE bool isValid() const; +}; + + +PX_INLINE PxSimpleTriangleMesh::PxSimpleTriangleMesh() +{ +} + +PX_INLINE void PxSimpleTriangleMesh::setToDefault() +{ + *this = PxSimpleTriangleMesh(); +} + +PX_INLINE bool PxSimpleTriangleMesh::isValid() const +{ + // Check geometry + if(points.count > 0xffff && flags & PxMeshFlag::e16_BIT_INDICES) + return false; + if(!points.data) + return false; + if(points.stride < sizeof(PxVec3)) //should be at least one point's worth of data + return false; + + // Check topology + // The triangles pointer is not mandatory + if(triangles.data) + { + // Indexed mesh + PxU32 limit = (flags & PxMeshFlag::e16_BIT_INDICES) ? sizeof(PxU16)*3 : sizeof(PxU32)*3; + if(triangles.stride < limit) + return false; + } + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxSphereGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxSphereGeometry.h new file mode 100644 index 000000000..0ae981635 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxSphereGeometry.h @@ -0,0 +1,104 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SPHERE_GEOMETRY_H +#define PX_SPHERE_GEOMETRY_H +#include "geometry/PxGeometry.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief A class representing the geometry of a sphere. + +Spheres are defined by their radius. +\note The scaling of the sphere is expected to be baked into this value, there is no additional scaling parameter. +*/ +class PxSphereGeometry : public PxGeometry +{ +public: + /** + \brief Constructor. + */ + PX_INLINE PxSphereGeometry(PxReal ir=0.0f) : PxGeometry(PxGeometryType::eSPHERE), radius(ir) {} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxSphereGeometry(const PxSphereGeometry& that) : PxGeometry(that), radius(that.radius) {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxSphereGeometry& that) + { + mType = that.mType; + radius = that.radius; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid + + \note A valid sphere has radius > 0. + It is illegal to call PxPhysics::createShape with a sphere that has zero radius. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + +public: + + /** + \brief The radius of the sphere. + */ + PxReal radius; +}; + +PX_INLINE bool PxSphereGeometry::isValid() const +{ + if(mType != PxGeometryType::eSPHERE) + return false; + if(!PxIsFinite(radius)) + return false; + if(radius <= 0.0f) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedron.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedron.h new file mode 100644 index 000000000..6b27a87a2 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedron.h @@ -0,0 +1,107 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TETRAHEDRON_H +#define PX_TETRAHEDRON_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + /** + \brief Tetrahedron class. + */ + class PxTetrahedron + { + public: + /** + \brief Constructor + */ + PX_FORCE_INLINE PxTetrahedron() {} + + /** + \brief Constructor + + \param[in] p0 Point 0 + \param[in] p1 Point 1 + \param[in] p2 Point 2 + \param[in] p3 Point 3 + */ + PX_FORCE_INLINE PxTetrahedron(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxVec3& p3) + { + verts[0] = p0; + verts[1] = p1; + verts[2] = p2; + verts[3] = p3; + } + + /** + \brief Copy constructor + + \param[in] tetrahedron copy + */ + PX_FORCE_INLINE PxTetrahedron(const PxTetrahedron& tetrahedron) + { + verts[0] = tetrahedron.verts[0]; + verts[1] = tetrahedron.verts[1]; + verts[2] = tetrahedron.verts[2]; + verts[3] = tetrahedron.verts[3]; + } + + /** + \brief Destructor + */ + PX_FORCE_INLINE ~PxTetrahedron() {} + + /** + \brief Assignment operator + */ + PX_FORCE_INLINE void operator=(const PxTetrahedron& tetrahedron) + { + verts[0] = tetrahedron.verts[0]; + verts[1] = tetrahedron.verts[1]; + verts[2] = tetrahedron.verts[2]; + verts[3] = tetrahedron.verts[3]; + } + /** + \brief Array of Vertices. + */ + PxVec3 verts[4]; + + }; + + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedronMesh.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedronMesh.h new file mode 100644 index 000000000..7d577c07a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedronMesh.h @@ -0,0 +1,392 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TETRAHEDRON_MESH_H +#define PX_TETRAHEDRON_MESH_H + +#include "foundation/PxVec3.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxUserAllocated.h" +#include "common/PxPhysXCommonConfig.h" +#include "common/PxBase.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + struct PxTetrahedronMeshFlag + { + enum Enum + { + e16_BIT_INDICES = (1 << 1) //!< The tetrahedron mesh has 16bits vertex indices + }; + }; + + /** + \brief collection of set bits defined in PxTetrahedronMeshFlag. + + \see PxTetrahedronMeshFlag + */ + typedef PxFlags PxTetrahedronMeshFlags; + PX_FLAGS_OPERATORS(PxTetrahedronMeshFlag::Enum, PxU8) + + + /** + \brief A data container providing mass, rest pose and other information required for deformable simulation + + Stores properties of deformable volume like inverse mass per node, rest pose matrix per tetrahedral element etc. + Mainly used internally to store runtime data. + + */ + class PxDeformableVolumeAuxData : public PxRefCounted + { + public: + /** + \brief Decrements the reference count of a tetrahedron mesh and releases it if the new reference count is zero. + + \see PxPhysics.createTetrahedronMesh() + */ + virtual void release() = 0; + + /** + \brief Get the inverse mass of each vertex of the tetrahedron mesh. + + \return PxReal* A pointer to an array of inverse mass for each vertex of the tetrahedron mesh. Size: number of vertices * sizeof(PxReal). + */ + virtual PxReal* getGridModelInvMass() = 0; + + protected: + PX_INLINE PxDeformableVolumeAuxData(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {} + PX_INLINE PxDeformableVolumeAuxData(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + virtual ~PxDeformableVolumeAuxData() {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxDeformableVolumeAuxData", PxRefCounted); } + }; + + typedef PX_DEPRECATED PxDeformableVolumeAuxData PxSoftBodyAuxData; + + /** + \brief A tetramedron mesh, also called a 'tetrahedron soup'. + + It is represented as an indexed tetrahedron list. There are no restrictions on the + tetrahedron data. + + To avoid duplicating data when you have several instances of a particular + mesh positioned differently, you do not use this class to represent a + mesh object directly. Instead, you create an instance of this mesh via + the PxTetrahedronMeshGeometry and PxShape classes. + +

Creation

+ + To create an instance of this class call PxPhysics::createTetrahedronMesh(), + and release() to delete it. This is only possible + once you have released all of its PxShape instances. + + +

Visualizations:

+ \li #PxVisualizationParameter::eCOLLISION_AABBS + \li #PxVisualizationParameter::eCOLLISION_SHAPES + \li #PxVisualizationParameter::eCOLLISION_AXES + \li #PxVisualizationParameter::eCOLLISION_FNORMALS + \li #PxVisualizationParameter::eCOLLISION_EDGES + + \see PxTetrahedronMeshDesc PxTetrahedronMeshGeometry PxShape PxPhysics.createTetrahedronMesh() + */ + class PxTetrahedronMesh : public PxRefCounted + { + public: + /** + \brief Returns the number of vertices. + \return number of vertices + \see getVertices() + */ + virtual PxU32 getNbVertices() const = 0; + + /** + \brief Returns the vertices + \return array of vertices + \see getNbVertices() + */ + virtual const PxVec3* getVertices() const = 0; + + + /** + \brief Returns the number of tetrahedrons. + \return number of tetrahedrons + \see getTetrahedrons() + */ + virtual PxU32 getNbTetrahedrons() const = 0; + + /** + \brief Returns the tetrahedron indices. + + The indices can be 16 or 32bit depending on the number of tetrahedrons in the mesh. + Call getTetrahedronMeshFlags() to know if the indices are 16 or 32 bits. + + The number of indices is the number of tetrahedrons * 4. + + \return array of tetrahedrons + \see getNbTetrahedron() getTetrahedronMeshFlags() getTetrahedraRemap() + */ + virtual const void* getTetrahedrons() const = 0; + + /** + \brief Reads the PxTetrahedronMesh flags. + + See the list of flags #PxTetrahedronMeshFlags + + \return The values of the PxTetrahedronMesh flags. + */ + virtual PxTetrahedronMeshFlags getTetrahedronMeshFlags() const = 0; + + + /** + \brief Returns the tetrahedra remapping table. + + The tetrahedra are internally sorted according to various criteria. Hence the internal tetrahedron order + does not always match the original (user-defined) order. The remapping table helps finding the old + indices knowing the new ones: + + remapTable[ internalTetrahedronIndex ] = originalTetrahedronIndex + + \return the remapping table (or NULL if 'PxCookingParams::suppressTriangleMeshRemapTable' has been used) + \see getNbTetrahedron() getTetrahedrons() PxCookingParams::suppressTriangleMeshRemapTable + */ + virtual const PxU32* getTetrahedraRemap() const = 0; + + /** + \brief Returns the local-space (vertex space) AABB from the tetrahedron mesh. + + \return local-space bounds + */ + virtual PxBounds3 getLocalBounds() const = 0; + + /** + \brief Decrements the reference count of a tetrahedron mesh and releases it if the new reference count is zero. + + \see PxPhysics.createTetrahedronMesh() + */ + virtual void release() = 0; + + protected: + PX_INLINE PxTetrahedronMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {} + PX_INLINE PxTetrahedronMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + virtual ~PxTetrahedronMesh() {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxTetrahedronMesh", PxRefCounted); } + }; + + /** + \brief A deformable volume mesh, containing structures to store collision shape, simulation shape and deformation state + + The class bundles shapes and deformation state of a deformable volume that is simulated using FEM. The meshes used for + collision detection and for the FEM calculations are both tetrahedral meshes. While collision detection requires + a mesh that matches the surface of the simulated body as exactly as possible, the simulation mesh has more freedom + such that it can be optimized for tetrahedra without small angles and nodes that aren't shared by too many elements. + +

Creation

+ + To create an instance of this class call PxPhysics::createDeformableVolumeMesh(), + and release() to delete it. This is only possible + once you have released all of its PxShape instances. + + */ + class PxDeformableVolumeMesh : public PxRefCounted + { + public: + /** + \brief Const accecssor to the deformable volume's collision mesh. + + \see PxTetrahedronMesh + */ + virtual const PxTetrahedronMesh* getCollisionMesh() const = 0; + + /** + \brief Accecssor to the deformable volume's collision mesh. + + \see PxTetrahedronMesh + */ + virtual PxTetrahedronMesh* getCollisionMesh() = 0; + + /** + \brief Const accessor to the deformable volume's simulation mesh. + + \see PxTetrahedronMesh + */ + virtual const PxTetrahedronMesh* getSimulationMesh() const = 0; + + /** + \brief Accecssor to the deformable volume's simulation mesh. + + \see PxTetrahedronMesh + */ + virtual PxTetrahedronMesh* getSimulationMesh() = 0; + + + /** + \brief Const accessor to the deformable volume's simulation state. + + \see PxDeformableVolumeAuxData + */ + virtual const PxDeformableVolumeAuxData* getDeformableVolumeAuxData() const = 0; + + /** + \brief Deprecated + \see getDeformableVolumeAuxData + */ + PX_DEPRECATED PX_FORCE_INLINE const PxDeformableVolumeAuxData* getSoftBodyAuxData() const + { + return getDeformableVolumeAuxData(); + } + + /** + \brief Accessor to the deformable volume's auxilary data like mass and rest pose information + + \see PxDeformableVolumeAuxData + */ + virtual PxDeformableVolumeAuxData* getDeformableVolumeAuxData() = 0; + + /** + \brief Deprecated + \see getDeformableVolumeAuxData + */ + PX_DEPRECATED PX_FORCE_INLINE PxDeformableVolumeAuxData* getSoftBodyAuxData() + { + return getDeformableVolumeAuxData(); + } + + /** + \brief Decrements the reference count of a tetrahedron mesh and releases it if the new reference count is zero. + + \see PxPhysics.createTetrahedronMesh() + */ + virtual void release() = 0; + + + protected: + PX_INLINE PxDeformableVolumeMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {} + PX_INLINE PxDeformableVolumeMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + virtual ~PxDeformableVolumeMesh() {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxDeformableVolumeMesh", PxRefCounted); } + }; + + typedef PX_DEPRECATED PxDeformableVolumeMesh PxSoftBodyMesh; + + + /** + + \brief Contains information about how to update the collision mesh's vertices given a deformed simulation tetmesh. + + \see PxTetrahedronMeshData + */ + class PxCollisionMeshMappingData : public PxUserAllocated + { + public: + virtual void release() = 0; + + virtual ~PxCollisionMeshMappingData() {} + }; + + /** + + \brief Stores data to accelerate collision detection of a tetrahedral mesh + + \see PxTetrahedronMeshData + */ + class PxDeformableVolumeCollisionData : public PxUserAllocated + { + + }; + + typedef PX_DEPRECATED PxDeformableVolumeCollisionData PxSoftBodyCollisionData; + + /** + + \brief Contains raw geometry information describing the tetmesh's vertices and its elements (tetrahedra) + + \see PxTetrahedronMeshData + */ + class PxTetrahedronMeshData : public PxUserAllocated + { + + }; + + /** + + \brief Stores data to compute and store the state of a deformed tetrahedral mesh + + \see PxTetrahedronMeshData + */ + class PxDeformableVolumeSimulationData : public PxUserAllocated + { + + }; + + typedef PX_DEPRECATED PxDeformableVolumeSimulationData PxSoftBodySimulationData; + + /** + + \brief Conbines PxTetrahedronMeshData and PxDeformableVolumeCollisionData + + \see PxTetrahedronMeshData PxDeformableVolumeCollisionData + */ + class PxCollisionTetrahedronMeshData : public PxUserAllocated + { + public: + virtual const PxTetrahedronMeshData* getMesh() const = 0; + virtual PxTetrahedronMeshData* getMesh() = 0; + virtual const PxDeformableVolumeCollisionData* getData() const = 0; + virtual PxDeformableVolumeCollisionData* getData() = 0; + virtual void release() = 0; + + virtual ~PxCollisionTetrahedronMeshData() {} + }; + + /** + + \brief Conbines PxTetrahedronMeshData and PxDeformableVolumeSimulationData + + \see PxTetrahedronMeshData PxDeformableVolumeSimulationData + */ + class PxSimulationTetrahedronMeshData : public PxUserAllocated + { + public: + virtual PxTetrahedronMeshData* getMesh() = 0; + virtual PxDeformableVolumeSimulationData* getData() = 0; + virtual void release() = 0; + + virtual ~PxSimulationTetrahedronMeshData() {} + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedronMeshGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedronMeshGeometry.h new file mode 100644 index 000000000..f171790b6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTetrahedronMeshGeometry.h @@ -0,0 +1,107 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TETRAHEDRON_GEOMETRY_H +#define PX_TETRAHEDRON_GEOMETRY_H +#include "geometry/PxGeometry.h" +#include "geometry/PxMeshScale.h" +#include "common/PxCoreUtilityTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + class PxTetrahedronMesh; + + /** + \brief Tetrahedron mesh geometry class. + + This class wraps a tetrahedron mesh such that it can be used in contexts where a PxGeometry type is needed. + */ + class PxTetrahedronMeshGeometry : public PxGeometry + { + public: + /** + \brief Constructor. By default creates an empty object with a NULL mesh and identity scale. + */ + PX_INLINE PxTetrahedronMeshGeometry(PxTetrahedronMesh* mesh = NULL) : + PxGeometry(PxGeometryType::eTETRAHEDRONMESH), + tetrahedronMesh(mesh) + {} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxTetrahedronMeshGeometry(const PxTetrahedronMeshGeometry& that) : + PxGeometry(that), + tetrahedronMesh(that.tetrahedronMesh) + {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxTetrahedronMeshGeometry& that) + { + mType = that.mType; + tetrahedronMesh = that.tetrahedronMesh; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid for shape creation. + + \note A valid tetrahedron mesh has a positive scale value in each direction (scale.scale.x > 0, scale.scale.y > 0, scale.scale.z > 0). + It is illegal to call PxPhysics::createShape with a tetrahedron mesh that has zero extents in any direction. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + + public: + PxTetrahedronMesh* tetrahedronMesh; //!< A reference to the mesh object. + }; + + PX_INLINE bool PxTetrahedronMeshGeometry::isValid() const + { + if(mType != PxGeometryType::eTETRAHEDRONMESH) + return false; + + if(!tetrahedronMesh) + return false; + + return true; + } + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangle.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangle.h new file mode 100644 index 000000000..5cf0227fd --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangle.h @@ -0,0 +1,153 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TRIANGLE_H +#define PX_TRIANGLE_H + +#include "common/PxPhysXCommonConfig.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Triangle class. +*/ +class PxTriangle +{ + public: + /** + \brief Constructor + */ + PX_FORCE_INLINE PxTriangle() {} + + /** + \brief Constructor + + \param[in] p0 Point 0 + \param[in] p1 Point 1 + \param[in] p2 Point 2 + */ + PX_FORCE_INLINE PxTriangle(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2) + { + verts[0] = p0; + verts[1] = p1; + verts[2] = p2; + } + + /** + \brief Copy constructor + + \param[in] triangle Tri to copy + */ + PX_FORCE_INLINE PxTriangle(const PxTriangle& triangle) + { + verts[0] = triangle.verts[0]; + verts[1] = triangle.verts[1]; + verts[2] = triangle.verts[2]; + } + + /** + \brief Destructor + */ + PX_FORCE_INLINE ~PxTriangle() {} + + /** + \brief Assignment operator + */ + PX_FORCE_INLINE void operator=(const PxTriangle& triangle) + { + verts[0] = triangle.verts[0]; + verts[1] = triangle.verts[1]; + verts[2] = triangle.verts[2]; + } + + /** + \brief Compute the normal of the Triangle. + + \param[out] _normal Triangle normal. + */ + PX_FORCE_INLINE void normal(PxVec3& _normal) const + { + _normal = (verts[1]-verts[0]).cross(verts[2]-verts[0]); + _normal.normalize(); + } + + /** + \brief Compute the unnormalized normal of the triangle. + + \param[out] _normal Triangle normal (not normalized). + */ + PX_FORCE_INLINE void denormalizedNormal(PxVec3& _normal) const + { + _normal = (verts[1]-verts[0]).cross(verts[2]-verts[0]); + } + + /** + \brief Compute the area of the triangle. + + \return Area of the triangle. + */ + PX_FORCE_INLINE PxReal area() const + { + const PxVec3& p0 = verts[0]; + const PxVec3& p1 = verts[1]; + const PxVec3& p2 = verts[2]; + return ((p0 - p1).cross(p0 - p2)).magnitude() * 0.5f; + } + + /** + \return Computes a point on the triangle from u and v barycentric coordinates. + */ + PX_FORCE_INLINE PxVec3 pointFromUV(PxReal u, PxReal v) const + { + return (1.0f-u-v)*verts[0] + u*verts[1] + v*verts[2]; + } + + /** + \brief Array of Vertices. + */ + PxVec3 verts[3]; +}; + +//! A padded version of PxTriangle, to safely load its data using SIMD +class PxTrianglePadded : public PxTriangle +{ +public: + PX_FORCE_INLINE PxTrianglePadded() {} + PX_FORCE_INLINE ~PxTrianglePadded() {} + PxU32 padding; +}; + +#if !PX_DOXYGEN +} +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangleMesh.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangleMesh.h new file mode 100644 index 000000000..44ba962a6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangleMesh.h @@ -0,0 +1,335 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TRIANGLE_MESH_H +#define PX_TRIANGLE_MESH_H + +#include "foundation/PxVec3.h" +#include "foundation/PxBounds3.h" +#include "common/PxPhysXCommonConfig.h" +#include "common/PxBase.h" +#include "foundation/PxUserAllocated.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief Mesh midphase structure. This enum is used to select the desired acceleration structure for midphase queries + (i.e. raycasts, overlaps, sweeps vs triangle meshes). + + The PxMeshMidPhase::eBVH33 structure is the one used in recent PhysX versions (up to PhysX 3.3). It has great performance and is + supported on all platforms. It is deprecated since PhysX 5.x. + + The PxMeshMidPhase::eBVH34 structure is a revisited implementation introduced in PhysX 3.4. It can be significantly faster both + in terms of cooking performance and runtime performance. +*/ +struct PxMeshMidPhase +{ + enum Enum + { + eBVH33 = 0, //!< \deprecated Use eBVH34 instead. Used to be default midphase mesh structure up to PhysX 3.3 + eBVH34 = 1, //!< New midphase mesh structure, introduced in PhysX 3.4 + + eLAST + }; +}; + +/** +\brief Flags for the mesh geometry properties. + +Used in ::PxTriangleMeshFlags. +*/ +struct PxTriangleMeshFlag +{ + enum Enum + { + e16_BIT_INDICES = (1<<1), //!< The triangle mesh has 16bits vertex indices. + eADJACENCY_INFO = (1<<2), //!< The triangle mesh has adjacency information build. + ePREFER_NO_SDF_PROJ = (1<<3)//!< Indicates that this mesh would preferably not be the mesh projected for mesh-mesh collision. This can indicate that the mesh is not well tessellated. + }; +}; + +/** +\brief collection of set bits defined in PxTriangleMeshFlag. + +\see PxTriangleMeshFlag +*/ +typedef PxFlags PxTriangleMeshFlags; +PX_FLAGS_OPERATORS(PxTriangleMeshFlag::Enum,PxU8) + +/** + +\brief A triangle mesh, also called a 'polygon soup'. + +It is represented as an indexed triangle list. There are no restrictions on the +triangle data. + +To avoid duplicating data when you have several instances of a particular +mesh positioned differently, you do not use this class to represent a +mesh object directly. Instead, you create an instance of this mesh via +the PxTriangleMeshGeometry and PxShape classes. + +

Creation

+ +To create an instance of this class call PxPhysics::createTriangleMesh(), +and release() to delete it. This is only possible +once you have released all of its PxShape instances. + + +

Visualizations:

+\li #PxVisualizationParameter::eCOLLISION_AABBS +\li #PxVisualizationParameter::eCOLLISION_SHAPES +\li #PxVisualizationParameter::eCOLLISION_AXES +\li #PxVisualizationParameter::eCOLLISION_FNORMALS +\li #PxVisualizationParameter::eCOLLISION_EDGES + +\see PxTriangleMeshDesc PxTriangleMeshGeometry PxShape PxPhysics.createTriangleMesh() +*/ +class PxTriangleMesh : public PxRefCounted +{ + public: + /** + \brief Returns the number of vertices. + \return number of vertices + \see getVertices() + */ + virtual PxU32 getNbVertices() const = 0; + + /** + \brief Returns the vertices. + \return array of vertices + \see getNbVertices() + */ + virtual const PxVec3* getVertices() const = 0; + + /** + \brief Returns all mesh vertices for modification. + + This function will return the vertices of the mesh so that their positions can be changed in place. + After modifying the vertices you must call refitBVH for the refitting to actually take place. + This function maintains the old mesh topology (triangle indices). + + \return inplace vertex coordinates for each existing mesh vertex. + + \note It is recommended to use this feature for scene queries only. + \note Size of array returned is equal to the number returned by getNbVertices(). + \note This function operates on cooked vertex indices. + \note This means the index mapping and vertex count can be different from what was provided as an input to the cooking routine. + \note To achieve unchanged 1-to-1 index mapping with orignal mesh data (before cooking) please use the following cooking flags: + \note eWELD_VERTICES = 0, eDISABLE_CLEAN_MESH = 1. + \note It is also recommended to make sure that a call to validateTriangleMesh returns true if mesh cleaning is disabled. + \see getNbVertices() + \see refitBVH() + */ + virtual PxVec3* getVerticesForModification() = 0; + + /** + \brief Refits BVH for mesh vertices. + + This function will refit the mesh BVH to correctly enclose the new positions updated by getVerticesForModification. + Mesh BVH will not be reoptimized by this function so significantly different new positions will cause significantly reduced performance. + + \return New bounds for the entire mesh. + + \note For PxMeshMidPhase::eBVH34 trees the refit operation is only available on non-quantized trees (see PxBVH34MidphaseDesc::quantized) + \note PhysX does not keep a mapping from the mesh to mesh shapes that reference it. + \note Call PxShape::setGeometry on each shape which references the mesh, to ensure that internal data structures are updated to reflect the new geometry. + \note PxShape::setGeometry does not guarantee correct/continuous behavior when objects are resting on top of old or new geometry. + \note It is also recommended to make sure that a call to validateTriangleMesh returns true if mesh cleaning is disabled. + \note Active edges information will be lost during refit, the rigid body mesh contact generation might not perform as expected. + \see getNbVertices() + \see getVerticesForModification() + \see PxBVH34MidphaseDesc::quantized + */ + virtual PxBounds3 refitBVH() = 0; + + /** + \brief Returns the number of triangles. + \return number of triangles + \see getTriangles() getTrianglesRemap() + */ + virtual PxU32 getNbTriangles() const = 0; + + /** + \brief Returns the triangle indices. + + The indices can be 16 or 32bit depending on the number of triangles in the mesh. + Call getTriangleMeshFlags() to know if the indices are 16 or 32 bits. + + The number of indices is the number of triangles * 3. + + \return array of triangles + \see getNbTriangles() getTriangleMeshFlags() getTrianglesRemap() + */ + virtual const void* getTriangles() const = 0; + + /** + \brief Reads the PxTriangleMesh flags. + + See the list of flags #PxTriangleMeshFlag + + \return The values of the PxTriangleMesh flags. + + \see PxTriangleMesh + */ + virtual PxTriangleMeshFlags getTriangleMeshFlags() const = 0; + + /** + \brief Returns the triangle remapping table. + + The triangles are internally sorted according to various criteria. Hence the internal triangle order + does not always match the original (user-defined) order. The remapping table helps finding the old + indices knowing the new ones: + + remapTable[ internalTriangleIndex ] = originalTriangleIndex + + \return the remapping table (or NULL if 'PxCookingParams::suppressTriangleMeshRemapTable' has been used) + \see getNbTriangles() getTriangles() PxCookingParams::suppressTriangleMeshRemapTable + */ + virtual const PxU32* getTrianglesRemap() const = 0; + + /** + \brief Decrements the reference count of a triangle mesh and releases it if the new reference count is zero. + + \see PxPhysics.createTriangleMesh() + */ + virtual void release() = 0; + + /** + \brief Returns material table index of given triangle + + This function takes a post cooking triangle index. + + \param[in] triangleIndex (internal) index of desired triangle + \return Material table index, or 0xffff if no per-triangle materials are used + */ + virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const = 0; + + /** + \brief Returns the local-space (vertex space) AABB from the triangle mesh. + + \return local-space bounds + */ + virtual PxBounds3 getLocalBounds() const = 0; + + /** + \brief Returns the local-space Signed Distance Field for this mesh if it has one. + \return local-space SDF. + */ + virtual const PxReal* getSDF() const = 0; + + /** + \brief Returns the resolution of the local-space dense SDF. + */ + virtual void getSDFDimensions(PxU32& numX, PxU32& numY, PxU32& numZ) const = 0; + + /** + \brief Sets whether this mesh should be preferred for SDF projection. + + By default, meshes are flagged as preferring projection and the decisions on which mesh to project is based on the triangle and vertex + count. The model with the fewer triangles is projected onto the SDF of the more detailed mesh. + If one of the meshes is set to prefer SDF projection (default) and the other is set to not prefer SDF projection, model flagged as + preferring SDF projection will be projected onto the model flagged as not preferring, regardless of the detail of the respective meshes. + Where both models are flagged as preferring no projection, the less detailed model will be projected as before. + + \param[in] preferProjection Indicates if projection is preferred + */ + virtual void setPreferSDFProjection(bool preferProjection) = 0; + + /** + \brief Returns whether this mesh prefers SDF projection. + \return whether this mesh prefers SDF projection. + */ + virtual bool getPreferSDFProjection() const = 0; + + /** + \brief Returns the mass properties of the mesh assuming unit density. + + The following relationship holds between mass and volume: + + mass = volume * density + + The mass of a unit density mesh is equal to its volume, so this function returns the volume of the mesh. + + Similarly, to obtain the localInertia of an identically shaped object with a uniform density of d, simply multiply the + localInertia of the unit density mesh by d. + + \param[out] mass The mass of the mesh assuming unit density. + \param[out] localInertia The inertia tensor in mesh local space assuming unit density. + \param[out] localCenterOfMass Position of center of mass (or centroid) in mesh local space. + */ + virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const = 0; + +protected: + PX_INLINE PxTriangleMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {} + PX_INLINE PxTriangleMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {} + virtual ~PxTriangleMesh() {} + + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxTriangleMesh", PxRefCounted); } +}; + +/** +\deprecated Use PxBVH34TriangleMesh instead. + +\brief A triangle mesh containing the PxMeshMidPhase::eBVH33 structure. + +\see PxMeshMidPhase +*/ +class PX_DEPRECATED PxBVH33TriangleMesh : public PxTriangleMesh +{ + public: +protected: + PX_INLINE PxBVH33TriangleMesh(PxType concreteType, PxBaseFlags baseFlags) : PxTriangleMesh(concreteType, baseFlags) {} + PX_INLINE PxBVH33TriangleMesh(PxBaseFlags baseFlags) : PxTriangleMesh(baseFlags) {} + virtual ~PxBVH33TriangleMesh() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBVH33TriangleMesh", PxTriangleMesh); } +}; + +/** + +\brief A triangle mesh containing the PxMeshMidPhase::eBVH34 structure. + +\see PxMeshMidPhase +*/ +class PxBVH34TriangleMesh : public PxTriangleMesh +{ + public: +protected: + PX_INLINE PxBVH34TriangleMesh(PxType concreteType, PxBaseFlags baseFlags) : PxTriangleMesh(concreteType, baseFlags) {} + PX_INLINE PxBVH34TriangleMesh(PxBaseFlags baseFlags) : PxTriangleMesh(baseFlags) {} + virtual ~PxBVH34TriangleMesh() {} + virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBVH34TriangleMesh", PxTriangleMesh); } +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangleMeshGeometry.h b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangleMeshGeometry.h new file mode 100644 index 000000000..719c49540 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geometry/PxTriangleMeshGeometry.h @@ -0,0 +1,157 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_TRIANGLE_MESH_GEOMETRY_H +#define PX_TRIANGLE_MESH_GEOMETRY_H +#include "geometry/PxGeometry.h" +#include "geometry/PxMeshScale.h" +#include "common/PxCoreUtilityTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxTriangleMesh; + +/** +\brief Flags controlling the simulated behavior of the triangle mesh geometry. + +Used in ::PxMeshGeometryFlags. +*/ +struct PxMeshGeometryFlag +{ + enum Enum + { + eTIGHT_BOUNDS = (1<<0), //!< Use tighter (but more expensive to compute) bounds around the triangle mesh geometry. + eDOUBLE_SIDED = (1<<1) //!< Meshes with this flag set are treated as double-sided. + //!< This flag is currently only used for raycasts and sweeps. It is ignored for overlap queries and has no effect on contact generation, i.e. simulation. + //!< For detailed specifications of this flag for meshes and heightfields please refer to the Geometry Query section of the user guide. + //!< For double-sided collision meshes, consider duplicating their faces with flipped normals. + }; +}; + +/** +\brief collection of set bits defined in PxMeshGeometryFlag. + +\see PxMeshGeometryFlag +*/ +typedef PxFlags PxMeshGeometryFlags; +PX_FLAGS_OPERATORS(PxMeshGeometryFlag::Enum,PxU8) + +/** +\brief Triangle mesh geometry class. + +This class unifies a mesh object with a scaling transform, and +lets the combined object be used anywhere a PxGeometry is needed. + +The scaling is a transform along arbitrary axes contained in the scale object. +The vertices of the mesh in geometry (or shape) space is the +PxMeshScale::toMat33() transform, multiplied by the vertex space vertices +in the PxTriangleMeshGeometry object. +*/ +class PxTriangleMeshGeometry : public PxGeometry +{ +public: + /** + \brief Constructor. By default creates an empty object with a NULL mesh and identity scale. + + \param[in] mesh Mesh pointer. May be NULL, though this will not make the object valid for shape construction. + \param[in] scaling Scale factor. + \param[in] flags Mesh flags. + */ + PX_INLINE PxTriangleMeshGeometry( PxTriangleMesh* mesh = NULL, + const PxMeshScale& scaling = PxMeshScale(), + PxMeshGeometryFlags flags = PxMeshGeometryFlags()) : + PxGeometry (PxGeometryType::eTRIANGLEMESH), + scale (scaling), + meshFlags (flags), + triangleMesh(mesh) + {} + + /** + \brief Copy constructor. + + \param[in] that Other object + */ + PX_INLINE PxTriangleMeshGeometry(const PxTriangleMeshGeometry& that) : + PxGeometry (that), + scale (that.scale), + meshFlags (that.meshFlags), + triangleMesh(that.triangleMesh) + {} + + /** + \brief Assignment operator + */ + PX_INLINE void operator=(const PxTriangleMeshGeometry& that) + { + mType = that.mType; + scale = that.scale; + meshFlags = that.meshFlags; + triangleMesh = that.triangleMesh; + } + + /** + \brief Returns true if the geometry is valid. + + \return True if the current settings are valid for shape creation. + + \note A valid triangle mesh has a positive scale value in each direction (scale.scale.x > 0, scale.scale.y > 0, scale.scale.z > 0). + It is illegal to call PxPhysics::createShape with a triangle mesh that has zero extents in any direction. + + \see PxPhysics::createShape + */ + PX_INLINE bool isValid() const; + +public: + PxMeshScale scale; //!< The scaling transformation. + PxMeshGeometryFlags meshFlags; //!< Mesh flags. + PxPadding<3> paddingFromFlags; //!< padding for mesh flags + PxTriangleMesh* triangleMesh; //!< A reference to the mesh object. +}; + +PX_INLINE bool PxTriangleMeshGeometry::isValid() const +{ + if(mType != PxGeometryType::eTRIANGLEMESH) + return false; + if(!scale.scale.isFinite() || !scale.rotation.isUnit()) + return false; + if(!scale.isValidForTriangleMesh()) + return false; + if(!triangleMesh) + return false; + + return true; +} + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geomutils/PxContactBuffer.h b/Jusin154_Team3D/Engine/Public/PhysX/geomutils/PxContactBuffer.h new file mode 100644 index 000000000..96ff81266 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geomutils/PxContactBuffer.h @@ -0,0 +1,91 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTACTBUFFER_H +#define PX_CONTACTBUFFER_H + +#include "PxPhysXConfig.h" +#include "geomutils/PxContactPoint.h" +#include "PxContact.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + class PxContactBuffer + { + public: + + static const PxU32 MAX_CONTACTS = 256; + + PxContactPoint contacts[MAX_CONTACTS]; + PxU32 count; + PxU32 pad; + + PX_FORCE_INLINE void reset() + { + count = 0; + } + + PX_FORCE_INLINE bool contact(const PxVec3& worldPoint, const PxVec3& worldNormalIn, PxReal separation, PxU32 faceIndex1 = PXC_CONTACT_NO_FACE_INDEX) + { + PX_ASSERT(PxAbs(worldNormalIn.magnitude()-1)<1e-3f); + + if(count>=MAX_CONTACTS) + return false; + + PxContactPoint& p = contacts[count++]; + p.normal = worldNormalIn; + p.point = worldPoint; + p.separation = separation; + p.internalFaceIndex1= faceIndex1; + return true; + } + + PX_FORCE_INLINE bool contact(const PxContactPoint& pt) + { + if(count>=MAX_CONTACTS) + return false; + contacts[count++] = pt; + return true; + } + + PX_FORCE_INLINE PxContactPoint* contact() + { + if(count>=MAX_CONTACTS) + return NULL; + return &contacts[count++]; + } + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/geomutils/PxContactPoint.h b/Jusin154_Team3D/Engine/Public/PhysX/geomutils/PxContactPoint.h new file mode 100644 index 000000000..38850e3c6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/geomutils/PxContactPoint.h @@ -0,0 +1,102 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_CONTACT_POINT_H +#define PX_CONTACT_POINT_H + +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + + struct PxContactPoint + { + /** + \brief The normal of the contacting surfaces at the contact point. + + For two shapes s0 and s1, the normal points in the direction that s0 needs to move in to resolve the contact with s1. + */ + PX_ALIGN(16, PxVec3 normal); + + /** + \brief The separation of the shapes at the contact point. A negative separation denotes a penetration. + */ + PxReal separation; + + /** + \brief The point of contact between the shapes, in world space. + */ + PX_ALIGN(16, PxVec3 point); + + /** + \brief The max impulse permitted at this point + */ + PxReal maxImpulse; + + PX_ALIGN(16, PxVec3 targetVel); + + /** + \brief The static friction coefficient + */ + PxReal staticFriction; + + /** + \brief Material flags for this contact (eDISABLE_FRICTION, eDISABLE_STRONG_FRICTION). \see PxMaterialFlag + */ + PxU8 materialFlags; + + /** + \brief The surface index of shape 1 at the contact point. This is used to identify the surface material. + + \note This field is only supported by triangle meshes and heightfields, else it will be set to PXC_CONTACT_NO_FACE_INDEX. + */ + PxU32 internalFaceIndex1; + + /** + \brief The dynamic friction coefficient + */ + PxReal dynamicFriction; + + /** + \brief The restitution coefficient + */ + PxReal restitution; + + /** + \brief Damping coefficient (for compliant contacts) + */ + PxReal damping; + }; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/gpu/PxGpu.h b/Jusin154_Team3D/Engine/Public/PhysX/gpu/PxGpu.h new file mode 100644 index 000000000..228ea481e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/gpu/PxGpu.h @@ -0,0 +1,149 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_GPU_H +#define PX_GPU_H + +#include "PxPhysXConfig.h" + + +#if PX_SUPPORT_GPU_PHYSX + +#include "cudamanager/PxCudaContextManager.h" +#include "foundation/PxPreprocessor.h" +#include "foundation/PxFoundation.h" +#include "common/PxPhysXCommonConfig.h" + +/** +\brief PxGpuLoadHook + +This is a helper class for loading the PhysXGpu dll. +If a PhysXGpu dll with a non-default file name needs to be loaded, +PxGpuLoadHook can be sub-classed to provide the custom filenames. + +Once the names are set, the instance must be set for use by PhysX.dll using PxSetPhysXGpuLoadHook(), + +\see PxSetPhysXGpuLoadHook() +*/ +class PxGpuLoadHook +{ +public: + PxGpuLoadHook() {} + virtual ~PxGpuLoadHook() {} + + virtual const char* getPhysXGpuDllName() const = 0; + +protected: +private: +}; + +/** +\brief Sets GPU load hook instance for PhysX dll. + +\param[in] hook GPU load hook. + +\see PxGpuLoadHook +*/ +PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXGpuLoadHook(const PxGpuLoadHook* hook); + +/** + * \brief Ask the NVIDIA control panel which GPU has been selected for use by + * PhysX. Returns -1 if no PhysX capable GPU is found or GPU PhysX has + * been disabled. + */ +PX_C_EXPORT PX_PHYSX_CORE_API int PX_CALL_CONV PxGetSuggestedCudaDeviceOrdinal(physx::PxErrorCallback& errc); + +/** + * \brief Allocate a CUDA Context manager, complete with heaps. + * You only need one CUDA context manager per GPU device you intend to use for + * CUDA tasks. + \param[in] foundation PhysXFoundation instance. + \param[in] desc Cuda context manager desc. + \param[in] profilerCallback PhysX profiler callback instance. + \param[in] launchSynchronous Set launchSynchronous to true for CUDA to report the actual point of failure. + + \see PxGetProfilerCallback() + */ +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxCudaContextManager* PX_CALL_CONV PxCreateCudaContextManager(physx::PxFoundation& foundation, const physx::PxCudaContextManagerDesc& desc, physx::PxProfilerCallback* profilerCallback = NULL, bool launchSynchronous = false); + +/** + * \brief Sets profiler callback to PhysX GPU + \param[in] profilerCallback PhysX profiler callback instance. + + \see PxGetProfilerCallback() + */ +PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXGpuProfilerCallback(physx::PxProfilerCallback* profilerCallback); + +/** + * \brief Sets PhysXFoundation instance + \param[in] foundation PhysXFoundation instance. + + \see PxGetFoundation() + */ +PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXGpuFoundationInstance(physx::PxFoundation& foundation); + +/** +\brief Internally used callback to register function names of cuda kernels +*/ +PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxCudaRegisterFunction(int moduleIndex, const char* functionName); + +/** +\brief Internally used callback to register cuda modules at load time +*/ +PX_C_EXPORT PX_PHYSX_CORE_API void** PX_CALL_CONV PxCudaRegisterFatBinary(void*); + +/** +\brief Access to the registered cuda modules +*/ +PX_C_EXPORT PX_PHYSX_CORE_API void** PX_CALL_CONV PxGetCudaModuleTable(); + +/** +\brief Number of registered cuda modules +*/ +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxU32 PX_CALL_CONV PxGetCudaModuleTableSize(); + +/** +\brief Access to the loaded cuda functions (kernels) +*/ +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxKernelIndex* PX_CALL_CONV PxGetCudaFunctionTable(); + +/** +\brief Number of loaded cuda functions (kernels) +*/ +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxU32 PX_CALL_CONV PxGetCudaFunctionTableSize(); + + +namespace physx +{ + class PxPhysicsGpu; +} + +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxPhysicsGpu* PX_CALL_CONV PxGetPhysicsGpu(); + + +#endif // PX_SUPPORT_GPU_PHYSX + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/gpu/PxPhysicsGpu.h b/Jusin154_Team3D/Engine/Public/PhysX/gpu/PxPhysicsGpu.h new file mode 100644 index 000000000..035e3346a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/gpu/PxPhysicsGpu.h @@ -0,0 +1,165 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PHYSICS_GPU_H +#define PX_PHYSICS_GPU_H + + +#include "cudamanager/PxCudaContext.h" +#include "cudamanager/PxCudaContextManager.h" + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec4.h" +#include "PxParticleSystem.h" + +#include "foundation/PxArray.h" +#include "PxParticleGpu.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +#if PX_SUPPORT_GPU_PHYSX + + class PxSceneDesc; + + class PxIsosurfaceExtractor; + class PxSparseGridIsosurfaceExtractor; + class PxAnisotropyGenerator; + class PxSmoothedPositionGenerator; + class PxParticleNeighborhoodProvider; + + class PxArrayConverter; + class PxSDFBuilder; + class PxDeformableSkinning; + + struct PxIsosurfaceParams; + struct PxSparseGridParams; + + class PxPhysicsGpu + { + public: + /** + \brief Creates an isosurface extractor operating on a dense grid + + \param[in] cudaContextManager A cuda context manager + \param[in] worldBounds The bounds of the internally used dense grid. The isosurface can only be generated inside those bounds. + \param[in] cellSize The size of a single grid cell + \param[in] isosurfaceParams The isosurface parameters to control the isolevel etc. + \param[in] maxNumParticles The maximal number of particles that can be processed + \param[in] maxNumVertices The maximal number of vertices the output buffer can hold + \param[in] maxNumTriangles The maximal number of triangles the output buffer can hold + */ + virtual PxIsosurfaceExtractor* createDenseGridIsosurfaceExtractor(PxCudaContextManager* cudaContextManager, const PxBounds3& worldBounds, + PxReal cellSize, const PxIsosurfaceParams& isosurfaceParams, PxU32 maxNumParticles, PxU32 maxNumVertices = 512 * 1024, PxU32 maxNumTriangles = 1024 * 1024) = 0; + + /** + \brief Creates an isosurface extractor operating on a sparse grid + + \param[in] cudaContextManager A cuda context manager + \param[in] sparseGridParams The sparse grid parameters defining the cell size etc. + \param[in] isosurfaceParams The isosurface parameters to control the isolevel etc. + \param[in] maxNumParticles The maximal number of particles that can be processed + \param[in] maxNumVertices The maximal number of vertices the output buffer can hold + \param[in] maxNumTriangles The maximal number of triangles the output buffer can hold + */ + virtual PxSparseGridIsosurfaceExtractor* createSparseGridIsosurfaceExtractor(PxCudaContextManager* cudaContextManager, const PxSparseGridParams& sparseGridParams, + const PxIsosurfaceParams& isosurfaceParams, PxU32 maxNumParticles, PxU32 maxNumVertices = 512 * 1024, PxU32 maxNumTriangles = 1024 * 1024) = 0; + + + /** + \brief Creates an anisotropy generator + + \param[in] cudaContextManager A cuda context manager + \param[in] maxNumParticles The number of particles + \param[in] anisotropyScale A uniform scaling factor to increase or decrease anisotropy + \param[in] minAnisotropy The minimum scaling factor in any dimension that anisotropy can have + \param[in] maxAnisotropy The maximum scaling factor in any dimension that anisotropy can have + */ + virtual PxAnisotropyGenerator* createAnisotropyGenerator(PxCudaContextManager* cudaContextManager, PxU32 maxNumParticles, + PxReal anisotropyScale = 1.0f, PxReal minAnisotropy = 0.1f, PxReal maxAnisotropy = 2.0f) = 0; + + /** + \brief Creates a smoothed position generator + + \param[in] cudaContextManager A cuda context manager + \param[in] maxNumParticles The number of particles + \param[in] smoothingStrength Controls the strength of the smoothing effect + */ + virtual PxSmoothedPositionGenerator* createSmoothedPositionGenerator(PxCudaContextManager* cudaContextManager, PxU32 maxNumParticles, PxReal smoothingStrength = 0.5f) = 0; + + + /** + \brief Creates a neighborhood provider + + \param[in] cudaContextManager A cuda context manager + \param[in] maxNumParticles The number of particles + \param[in] cellSize The grid cell size. Should be equal to 2*contactOffset for PBD particle systems. + \param[in] maxNumSparseGridCells The maximal number of cells the internally used sparse grid can provide + */ + virtual PxParticleNeighborhoodProvider* createParticleNeighborhoodProvider(PxCudaContextManager* cudaContextManager, const PxU32 maxNumParticles, + const PxReal cellSize, const PxU32 maxNumSparseGridCells = 262144) = 0; + + /** + \brief Creates an array converter. If not used anymore, the caller needs to delete the returned pointer. + + \param[in] cudaContextManager A cuda context manager + */ + virtual PxArrayConverter* createArrayConverter(PxCudaContextManager* cudaContextManager) = 0; + + /** + \brief Creates sdf builder to construct sdfs quickly on the GPU. If not used anymore, the caller needs to delete the returned pointer. + + \param[in] cudaContextManager A cuda context manager + + \return Pointer to a new instance of a PxSDFBuilder + */ + virtual PxSDFBuilder* createSDFBuilder(PxCudaContextManager* cudaContextManager) = 0; + + /** + \brief Creates a deformable skinning instance to perform skinning operations on the GPU. If not used anymore, the caller needs to delete the returned pointer. + + \param[in] cudaContextManager A cuda context manager + + \return Pointer to a new instance of a PxDeformableSkinning + */ + virtual PxDeformableSkinning* createDeformableSkinning(PxCudaContextManager* cudaContextManager) = 0; + + virtual void release() = 0; + + virtual ~PxPhysicsGpu() {} + }; + +#endif + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/omnipvd/PxOmniPvd.h b/Jusin154_Team3D/Engine/Public/PhysX/omnipvd/PxOmniPvd.h new file mode 100644 index 000000000..f605ee9e7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/omnipvd/PxOmniPvd.h @@ -0,0 +1,163 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_OMNI_PVD_H +#define PX_OMNI_PVD_H + +#include "PxPhysXConfig.h" + +class OmniPvdWriter; +class OmniPvdFileWriteStream; + +// The OVD integration version: +// +// Major version indicates breaking changes in how PhysX SDK objects +// are streamed using the OmniPVD API, or if certain attributes changed +// name/type or set size, or was removed, hence subtractive changes. +// +// Minor version version indicates non-breaking changes such as the +// addition of a class or attribute on top of those already existing, +// hence additive changes. +#define PX_PHYSICS_OVD_INTEGRATION_VERSION_MAJOR 3 +#define PX_PHYSICS_OVD_INTEGRATION_VERSION_MINOR 0 + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxFoundation; + +class PxOmniPvd +{ +public: + class ScopedExclusiveWriter + { + public: + PX_FORCE_INLINE ScopedExclusiveWriter(PxOmniPvd* omniPvd) + { + mOmniPvd = omniPvd; + mWriter = NULL; + if (mOmniPvd) { + mWriter = mOmniPvd->acquireExclusiveWriterAccess(); + } + } + + PX_FORCE_INLINE ~ScopedExclusiveWriter() + { + if (mOmniPvd && mWriter) { + mOmniPvd->releaseExclusiveWriterAccess(); + } + } + + PX_FORCE_INLINE OmniPvdWriter* operator-> () + { + return mWriter; + } + + PX_FORCE_INLINE OmniPvdWriter* getWriter() + { + return mWriter; + } + private: + OmniPvdWriter* mWriter; + PxOmniPvd* mOmniPvd; + }; + + virtual ~PxOmniPvd() + { + } + /** + \brief Get the OmniPvd writer. + + Gets an instance of the OmniPvd writer. The writer access will not be thread safe since the OmniPVD API is not thread safe itself. Writing concurrently and simultaneously using the OmniPVD API is undefined. + + For thread safe exlcusive access use the mechanism acquireExclusiveWriterAccess/releaseExclusiveWriterAccess. + + \return OmniPvdWriter instance on succes, NULL otherwise. + */ + virtual OmniPvdWriter* getWriter() = 0; + + /** + \brief Acquires an exclusive writer access. + + This call blocks until exclusive access to the writer can be acquired. Once access has been granted, it is guaranteed that no other caller can access the writer through this method until releaseExclusiveWriterAccess() has been called. + + This allows to safely write PVD data in environments with concurrent processing workflows. + + \return OmniPvdWriter instance on succes, NULL otherwise. + */ + virtual OmniPvdWriter* acquireExclusiveWriterAccess() = 0; + + /** + \brief Releases the exclusive writer access + + Releases the access to the writer that was previously acquired using acquireExclusiveWriterAccess. + + */ + virtual void releaseExclusiveWriterAccess() = 0; + + /** + \brief Gets an instance to the OmniPvd file write stream + + \return OmniPvdFileWriteStream instance on succes, NULL otherwise. + */ + virtual OmniPvdFileWriteStream* getFileWriteStream() = 0; + + /** + \brief Starts the OmniPvd sampling + + \return True if sampling started correctly, false if not. + */ + virtual bool startSampling() = 0; + + /** + \brief Releases the PxOmniPvd object + + */ + virtual void release() = 0; + +}; +#if !PX_DOXYGEN +} // namespace physx +#endif +/** +\brief Creates an instance of the OmniPvd object + +Creates an instance of the OmniPvd class. There may be only one instance of this class per process. Calling this method after an instance +has been created already will return the same instance over and over. + +\param foundation Foundation instance (see PxFoundation) + +\return PxOmniPvd instance on succes, NULL otherwise. + +*/ +PX_C_EXPORT PX_PHYSX_CORE_API physx::PxOmniPvd* PX_CALL_CONV PxCreateOmniPvd(physx::PxFoundation& foundation); + + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvd.h b/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvd.h new file mode 100644 index 000000000..39fc2d7e8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvd.h @@ -0,0 +1,174 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PVD_H +#define PX_PVD_H + +#include "foundation/PxFlags.h" +#include "foundation/PxProfiler.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxFoundation; +class PxPvdTransport; + +/** +\brief types of instrumentation that PVD can do. +*/ +struct PxPvdInstrumentationFlag +{ + enum Enum + { + /** + \brief Send debugging information to PVD. + + This information is the actual object data of the rigid statics, shapes, + articulations, etc. Sending this information has a noticeable impact on + performance and thus this flag should not be set if you want an accurate + performance profile. + */ + eDEBUG = 1 << 0, + + /** + \brief Send profile information to PVD. + + This information populates PVD's profile view. It has (at this time) negligible + cost compared to Debug information and makes PVD *much* more useful so it is quite + highly recommended. + + This flag works together with a PxCreatePhysics parameter. + Using it allows the SDK to send profile events to PVD. + */ + ePROFILE = 1 << 1, + + /** + \brief Send memory information to PVD. + + The PVD sdk side hooks into the Foundation memory controller and listens to + allocation/deallocation events. This has a noticable hit on the first frame, + however, this data is somewhat compressed and the PhysX SDK doesn't allocate much + once it hits a steady state. This information also has a fairly negligible + impact and thus is also highly recommended. + + This flag works together with a PxCreatePhysics parameter, + trackOutstandingAllocations. Using both of them together allows users to have + an accurate view of the overall memory usage of the simulation at the cost of + a hashtable lookup per allocation/deallocation. Again, PhysX makes a best effort + attempt not to allocate or deallocate during simulation so this hashtable lookup + tends to have no effect past the first frame. + + Sending memory information without tracking outstanding allocations means that + PVD will accurate information about the state of the memory system before the + actual connection happened. + */ + eMEMORY = 1 << 2, + + eALL = (eDEBUG | ePROFILE | eMEMORY) + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxPvdInstrumentationFlag. + +\see PxPvdInstrumentationFlag +*/ +typedef PxFlags PxPvdInstrumentationFlags; +PX_FLAGS_OPERATORS(PxPvdInstrumentationFlag::Enum, uint8_t) + +/** +\brief PxPvd is the top-level class for the PVD framework, and the main customer interface for PVD +configuration.It is a singleton class, instantiated and owned by the application. +*/ +class PxPvd : public physx::PxProfilerCallback +{ + public: + /** + Connects the SDK to the PhysX Visual Debugger application. + \param transport transport for pvd captured data. + \param flags Flags to set. + return True if success + */ + virtual bool connect(PxPvdTransport& transport, PxPvdInstrumentationFlags flags) = 0; + + /** + Disconnects the SDK from the PhysX Visual Debugger application. + If we are still connected, this will kill the entire debugger connection. + */ + virtual void disconnect() = 0; + + /** + * Return if connection to PVD is created. + \param useCachedStatus + 1> When useCachedStaus is false, isConnected() checks the lowlevel network status. + This can be slow because it needs to lock the lowlevel network stream. If isConnected() is + called frequently, the expense of locking can be significant. + 2> When useCachedStatus is true, isConnected() checks the highlevel cached status with atomic access. + It is faster than locking, but the status may be different from the lowlevel network with latency of up to + one frame. + The reason for this is that the cached status is changed inside socket listener, which is not + called immediately when the lowlevel connection status changes. + */ + virtual bool isConnected(bool useCachedStatus = true) = 0; + + /** + returns the PVD data transport + returns NULL if no transport is present. + */ + virtual PxPvdTransport* getTransport() = 0; + + /** + Retrieves the PVD flags. See PxPvdInstrumentationFlags. + */ + virtual PxPvdInstrumentationFlags getInstrumentationFlags() = 0; + + /** + \brief Releases the pvd instance. + */ + virtual void release() = 0; + + protected: + virtual ~PxPvd() + { + } +}; + +/** + \brief Create a pvd instance. + \param foundation is the foundation instance that stores the allocator and error callbacks. +*/ +PX_C_EXPORT PxPvd* PX_CALL_CONV PxCreatePvd(PxFoundation& foundation); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvdSceneClient.h b/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvdSceneClient.h new file mode 100644 index 000000000..da676b643 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvdSceneClient.h @@ -0,0 +1,142 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PVD_SCENE_CLIENT_H +#define PX_PVD_SCENE_CLIENT_H + + +#include "foundation/PxFlags.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + namespace pvdsdk + { + class PvdClient; + } + struct PxDebugPoint; + struct PxDebugLine; + struct PxDebugTriangle; + struct PxDebugText; +#if !PX_DOXYGEN +} // namespace physx +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief PVD scene Flags. They are disabled by default, and only works if PxPvdInstrumentationFlag::eDEBUG is set. +*/ +struct PxPvdSceneFlag +{ + enum Enum + { + eTRANSMIT_CONTACTS = (1 << 0), //! Transmits contact stream to PVD. + eTRANSMIT_SCENEQUERIES = (1 << 1), //! Transmits scene query stream to PVD. + eTRANSMIT_CONSTRAINTS = (1 << 2) //! Transmits constraints visualize stream to PVD. + }; +}; + +/** +\brief Bitfield that contains a set of raised flags defined in PxPvdSceneFlag. + +\see PxPvdSceneFlag +*/ +typedef PxFlags PxPvdSceneFlags; +PX_FLAGS_OPERATORS(PxPvdSceneFlag::Enum, PxU8) + +/** +\brief Special client for PxScene. +It provides access to the PxPvdSceneFlag. +It also provides simple user debug services that associated scene position such as immediate rendering and camera updates. +*/ +class PxPvdSceneClient +{ + public: + /** + Sets the PVD flag. See PxPvdSceneFlag. + \param flag Flag to set. + \param value value the flag gets set to. + */ + virtual void setScenePvdFlag(PxPvdSceneFlag::Enum flag, bool value) = 0; + + /** + Sets the PVD flags. See PxPvdSceneFlags. + \param flags Flags to set. + */ + virtual void setScenePvdFlags(PxPvdSceneFlags flags) = 0; + + /** + Retrieves the PVD flags. See PxPvdSceneFlags. + */ + virtual PxPvdSceneFlags getScenePvdFlags() const = 0; + + /** + update camera on PVD application's render window + */ + virtual void updateCamera(const char* name, const PxVec3& origin, const PxVec3& up, const PxVec3& target) = 0; + + /** + draw points on PVD application's render window + */ + virtual void drawPoints(const physx::PxDebugPoint* points, PxU32 count) = 0; + + /** + draw lines on PVD application's render window + */ + virtual void drawLines(const physx::PxDebugLine* lines, PxU32 count) = 0; + + /** + draw triangles on PVD application's render window + */ + virtual void drawTriangles(const physx::PxDebugTriangle* triangles, PxU32 count) = 0; + + /** + draw text on PVD application's render window + */ + virtual void drawText(const physx::PxDebugText& text) = 0; + + /** + get the underlying client, for advanced users + */ + virtual physx::pvdsdk::PvdClient* getClientInternal() = 0; + +protected: + virtual ~PxPvdSceneClient(){} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvdTransport.h b/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvdTransport.h new file mode 100644 index 000000000..0ec58d283 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/pvd/PxPvdTransport.h @@ -0,0 +1,125 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_PVD_TRANSPORT_H +#define PX_PVD_TRANSPORT_H + +#include "foundation/PxErrors.h" +#include "foundation/PxFlags.h" +#include "pvd/PxPvd.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** +\brief PxPvdTransport is an interface representing the data transport mechanism. +This class defines all services associated with the transport: configuration, connection, reading, writing etc. +It is owned by the application, and can be realized as a file or a socket (using one-line PxDefault<...> methods in +PhysXExtensions) or in a custom implementation. This is a class that is intended for use by PVD, not by the +application, the application entry points are PxPvd and PvdClient. +*/ + +class PxPvdTransport +{ + public: + // connect, isConnected, disconnect, read, write, flush + + /** + Connects to the Visual Debugger application. + return True if success + */ + virtual bool connect() = 0; + + /** + Disconnects from the Visual Debugger application. + If we are still connected, this will kill the entire debugger connection. + */ + virtual void disconnect() = 0; + + /** + * Return if connection to PVD is created. + */ + virtual bool isConnected() = 0; + + /** + * write bytes to the other endpoint of the connection. should lock before witre. If an error occurs + * this connection will assume to be dead. + */ + virtual bool write(const uint8_t* inBytes, uint32_t inLength) = 0; + + /* + lock this transport and return it + */ + virtual PxPvdTransport& lock() = 0; + + /* + unlock this transport + */ + virtual void unlock() = 0; + + /** + * send any data and block until we know it is at least on the wire. + */ + virtual void flush() = 0; + + /** + * Return size of written data. + */ + virtual uint64_t getWrittenDataSize() = 0; + + virtual void release() = 0; + + protected: + virtual ~PxPvdTransport() + { + } +}; + +/** + \brief Create a default socket transport. + \param host host address of the pvd application. + \param port ip port used for pvd, should same as the port setting in pvd application. + \param timeoutInMilliseconds timeout when connect to pvd host. +*/ +PX_C_EXPORT PxPvdTransport* PX_CALL_CONV +PxDefaultPvdSocketTransportCreate(const char* host, int port, unsigned int timeoutInMilliseconds); + +/** + \brief Create a default file transport. + \param name full path filename used save captured pvd data, or NULL for a fake/test file transport. +*/ +PX_C_EXPORT PxPvdTransport* PX_CALL_CONV PxDefaultPvdFileTransportCreate(const char* name); + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/solver/PxSolverDefs.h b/Jusin154_Team3D/Engine/Public/PhysX/solver/PxSolverDefs.h new file mode 100644 index 000000000..1f66eb052 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/solver/PxSolverDefs.h @@ -0,0 +1,709 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#ifndef PX_SOLVER_DEFS_H +#define PX_SOLVER_DEFS_H + +#include "PxPhysXConfig.h" +#include "foundation/PxVec3.h" +#include "foundation/PxMat33.h" +#include "foundation/PxTransform.h" +#include "PxConstraintDesc.h" +#include "geomutils/PxContactPoint.h" + +#if PX_VC +#pragma warning(push) +#pragma warning(disable : 4324) // structure was padded due to alignment +#endif + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +struct PxTGSSolverBodyVel; + +/** +\brief Struct that the solver uses to store velocity updates for a body +*/ +struct PxSolverBody +{ + PX_ALIGN(16, PxVec3) linearVelocity; //!< Delta linear velocity computed by the solver + PxU16 maxSolverNormalProgress; //!< Progress counter used by constraint batching and parallel island solver. + PxU16 maxSolverFrictionProgress; //!< Progress counter used by constraint batching and parallel island solver. + + PxVec3 angularState; //!< Delta angular velocity state computed by the solver. + + PxU32 solverProgress; //!< Progress counter used by constraint batching and parallel island solver + + PxSolverBody() : linearVelocity(0.f), maxSolverNormalProgress(0), maxSolverFrictionProgress(0), angularState(0), solverProgress(0) + { + } +}; +PX_COMPILE_TIME_ASSERT(sizeof(PxSolverBody) == 32); +PX_COMPILE_TIME_ASSERT((PX_OFFSET_OF(PxSolverBody, angularState) & 15) == 0); + +/** +\brief Struct that the solver uses to store the state and other properties of a body +*/ +struct PxSolverBodyData +{ + PX_ALIGN(16, PxVec3 linearVelocity); //!< 12 Pre-solver linear velocity + PxReal invMass; //!< 16 inverse mass + PxVec3 angularVelocity; //!< 28 Pre-solver angular velocity + PxReal reportThreshold; //!< 32 contact force threshold + PxMat33 sqrtInvInertia; //!< 68 inverse inertia in world space + PxReal penBiasClamp; //!< 72 the penetration bias clamp + PxU32 nodeIndex; //!< 76 the node idx of this solverBodyData. Used by solver to reference between solver bodies and island bodies. Not required by immediate mode + PxReal maxContactImpulse; //!< 80 the max contact impulse + PxTransform body2World; //!< 108 the body's transform + PxU16 pad; //!< 112 pad + + PX_FORCE_INLINE PxReal projectVelocity(const PxVec3& lin, const PxVec3& ang) const + { + return linearVelocity.dot(lin) + angularVelocity.dot(ang); + } +}; +PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxSolverBodyData) & 15)); +// PT: ensure that sqrtInvInertia is not the last member of PxSolverBodyData, i.e. it is safe to load 4 bytes after sqrtInvInertia +PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxSolverBodyData, sqrtInvInertia)+sizeof(PxSolverBodyData::sqrtInvInertia) + 4 <= sizeof(PxSolverBodyData)); + +//---------------------------------- +/** +\brief A header that defines the size of a specific batch of constraints (of same type and without dependencies) +*/ +struct PxConstraintBatchHeader +{ + PxU32 startIndex; //!< Start index for this batch + PxU16 stride; //!< Number of constraints in this batch (range: 1-4) + PxU16 constraintType; //!< The type of constraint this batch references +}; + +/** +\brief Constraint descriptor used inside the solver +*/ +PX_ALIGN_PREFIX(16) +struct PxSolverConstraintDesc +{ + static const PxU16 RIGID_BODY = 0xffff; + + enum ConstraintType + { + eCONTACT_CONSTRAINT, //!< Defines this pair is a contact constraint + eJOINT_CONSTRAINT //!< Defines this pair is a joint constraint + }; + + union + { + PxSolverBody* bodyA; //!< bodyA pointer + PxTGSSolverBodyVel* tgsBodyA; //!< bodyA pointer + void* articulationA; //!< Articulation pointer for body A + }; + + union + { + PxSolverBody* bodyB; //!< BodyB pointer + PxTGSSolverBodyVel* tgsBodyB; //!< BodyB pointer + void* articulationB; //!< Articulation pointer for body B + }; + PxU32 bodyADataIndex; //!< Body A's index into the SolverBodyData array + PxU32 bodyBDataIndex; //!< Body B's index into the SolverBodyData array + + PxU32 linkIndexA; //!< Link index defining which link in Articulation A this constraint affects. If not an articulation, must be PxSolverConstraintDesc::RIGID_BODY + PxU32 linkIndexB; //!< Link index defining which link in Articulation B this constraint affects. If not an articulation, must be PxSolverConstraintDesc::RIGID_BODY + PxU8* constraint; //!< Pointer to the constraint rows to be solved + void* writeBack; //!< Pointer to the writeback structure results for this given constraint are to be written to + void* writeBackFriction; //!< Pointer to writeback contact friction impulses. Points to a PxVec3* buffer + + PxU16 progressA; //!< Internal progress counter + PxU16 progressB; //!< Internal progress counter + + union + { + PxU16 constraintType; //!< type of constraint. Union member active until constraint prepping, afterwards memory used for constraint length + PxU16 constraintLengthOver16; //!< constraintLength/16, max constraint length is 1MB. + }; +}PX_ALIGN_SUFFIX(16); +PX_COMPILE_TIME_ASSERT(sizeof(PxSolverConstraintDesc) % 16 == 0); + +/** +\brief Data structure used for preparing constraints before solving them +*/ +struct PxSolverConstraintPrepDescBase +{ + enum BodyState + { + eDYNAMIC_BODY = 1 << 0, + eSTATIC_BODY = 1 << 1, + eKINEMATIC_BODY = 1 << 2, + eARTICULATION = 1 << 3 + }; + + PxConstraintInvMassScale invMassScales; //!< In: The local mass scaling for this pair. + + PxSolverConstraintDesc* desc; //!< Output: The PxSolverConstraintDesc filled in by contact prep + + const PxSolverBody* body0; //!< In: The first body. Stores velocity information. Unused unless contact involves articulations. + const PxSolverBody* body1; //!< In: The second body. Stores velocity information. Unused unless contact involves articulations. + + const PxSolverBodyData* data0; //!< In: The first PxSolverBodyData. Stores mass and miscellaneous information for the first body. + const PxSolverBodyData* data1; //!< In: The second PxSolverBodyData. Stores mass and miscellaneous information for the second body + + PxTransform bodyFrame0; //!< In: The world-space transform of the first body. + PxTransform bodyFrame1; //!< In: The world-space transform of the second body. + + // PT: these two use 4 bytes each but we only need 4 bits (or even just 2 bits) for a type + BodyState bodyState0; //!< In: Defines what kind of actor the first body is + BodyState bodyState1; //!< In: Defines what kind of actor the second body is + + // PT: the following pointers have been moved here from derived structures to fill padding bytes + union + { + // PT: moved from PxSolverConstraintPrepDesc + void* writeback; //!< Pointer to constraint writeback structure. Reports back joint breaking. If not required, set to NULL. + + // PT: moved from PxSolverContactDesc + void* shapeInteraction; //!< Pointer to shape interaction. Used for force threshold reports in solver. Set to NULL if using immediate mode. + }; +}; +PX_COMPILE_TIME_ASSERT(sizeof(PxSolverConstraintPrepDescBase)<=128); +// PT: ensure that we can safely read 4 bytes after the bodyFrames +PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxSolverConstraintPrepDescBase, bodyFrame0)+sizeof(PxSolverConstraintPrepDescBase::bodyFrame0) + 4 <= sizeof(PxSolverConstraintPrepDescBase)); +PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxSolverConstraintPrepDescBase, bodyFrame1)+sizeof(PxSolverConstraintPrepDescBase::bodyFrame1) + 4 <= sizeof(PxSolverConstraintPrepDescBase)); + +/** +\brief Data structure used for preparing constraints before solving them +*/ +struct PxSolverConstraintPrepDesc : public PxSolverConstraintPrepDescBase +{ + PX_ALIGN(16, Px1DConstraint* rows); //!< The start of the constraint rows + PxU32 numRows; //!< The number of rows + + PxReal linBreakForce, angBreakForce; //!< Break forces + PxReal minResponseThreshold; //!< The minimum response threshold + bool disablePreprocessing; //!< Disable joint pre-processing. Pre-processing can improve stability but under certain circumstances, e.g. when some invInertia rows are zero/almost zero, can cause instabilities. + bool improvedSlerp; //!< Use improved slerp model + bool driveLimitsAreForces; //!< Indicates whether drive limits are forces + bool extendedLimits; //!< Indicates whether we want to use extended limits + bool disableConstraint; //!< Disables constraint + + PxVec3p body0WorldOffset; //!< Body0 world offset +}; + +/** +\brief Data structure used for preparing constraints before solving them +*/ +struct PxSolverContactDesc : public PxSolverConstraintPrepDescBase +{ + PxU8* frictionPtr; //!< InOut: Friction patch correlation data. Set each frame by solver. Can be retained for improved behavior or discarded each frame. + const PxContactPoint* contacts; //!< The start of the contacts for this pair + PxU32 numContacts; //!< The total number of contacts this pair references. + + PxU8 frictionCount; //!< The total number of friction patches in this pair + bool hasMaxImpulse; //!< Defines whether this pairs has maxImpulses clamping enabled + bool disableStrongFriction; //!< Defines whether this pair disables strong friction (sticky friction correlation) + bool hasForceThresholds; //!< Defines whether this pair requires force thresholds + + PxReal restDistance; //!< A distance at which the solver should aim to hold the bodies separated. Default is 0 + PxReal maxCCDSeparation; //!< A distance used to configure speculative CCD behavior. Default is PX_MAX_F32. Set internally in PhysX for bodies with eENABLE_SPECULATIVE_CCD on. Do not set directly! + + PxReal* contactForces; //!< Out: A buffer for the solver to write applied contact forces to. + + PxU32 startFrictionPatchIndex; //!< Start index of friction patch in the correlation buffer. Set by friction correlation + PxU32 numFrictionPatches; //!< Total number of friction patches in this pair. Set by friction correlation + + PxU32 startContactPatchIndex; //!< The start index of this pair's contact patches in the correlation buffer. For internal use only + PxU16 numContactPatches; //!< Total number of contact patches. + PxU16 axisConstraintCount; //!< Axis constraint count. Defines how many constraint rows this pair has produced. Useful for statistical purposes. + + PxReal offsetSlop; //!< Slop value used to snap contact line of action back in-line with the COM. +}; + +class PxConstraintAllocator +{ +public: + /** + \brief Allocates constraint data. It is the application's responsibility to release this memory after PxSolveConstraints has completed. + \param[in] byteSize Allocation size in bytes + \return The allocated memory. This address must be 16-byte aligned. + */ + virtual PxU8* reserveConstraintData(const PxU32 byteSize) = 0; + + /** + \brief Allocates friction data. Friction data can be retained by the application for a given pair and provided as an input to PxSolverContactDesc to improve simulation stability. + It is the application's responsibility to release this memory. If this memory is released, the application should ensure it does not pass pointers to this memory to PxSolverContactDesc. + \param[in] byteSize Allocation size in bytes + \return The allocated memory. This address must be 4-byte aligned. + */ + virtual PxU8* reserveFrictionData(const PxU32 byteSize) = 0; + + virtual ~PxConstraintAllocator() {} +}; + +struct PxArticulationAxis +{ + enum Enum + { + eTWIST = 0, //!< Rotational about eX + eSWING1 = 1, //!< Rotational about eY + eSWING2 = 2, //!< Rotational about eZ + eX = 3, //!< Linear in eX + eY = 4, //!< Linear in eY + eZ = 5, //!< Linear in eZ + eCOUNT = 6 + }; +}; + +PX_FLAGS_OPERATORS(PxArticulationAxis::Enum, PxU8) + +struct PxArticulationMotion +{ + enum Enum + { + eLOCKED = 0, //!< Locked axis, i.e. degree of freedom (DOF) + eLIMITED = 1, //!< Limited DOF - set limits of joint DOF together with this flag, see PxArticulationJointReducedCoordinate::setLimitParams + eFREE = 2 //!< Free DOF + }; +}; + +typedef PxFlags PxArticulationMotions; +PX_FLAGS_OPERATORS(PxArticulationMotion::Enum, PxU8) + +struct PxArticulationJointType +{ + enum Enum + { + eFIX = 0, //!< All joint axes, i.e. degrees of freedom (DOFs) locked + ePRISMATIC = 1, //!< Single linear DOF, e.g. cart on a rail + eREVOLUTE = 2, //!< Single rotational DOF, e.g. an elbow joint or a rotational motor, position wrapped at 2pi radians + eREVOLUTE_UNWRAPPED = 3, //!< Single rotational DOF, e.g. an elbow joint or a rotational motor, position not wrapped + eSPHERICAL = 4, //!< Ball and socket joint with two or three DOFs + eUNDEFINED = 5 + }; +}; + +struct PxArticulationFlag +{ + enum Enum + { + eFIX_BASE = (1 << 0), //!< Set articulation base to be fixed. + eDRIVE_LIMITS_ARE_FORCES = (1<<1), //!< Limits for drive effort are forces and torques rather than impulses, see PxArticulationDrive::maxForce. + eDISABLE_SELF_COLLISION = (1<<2) //!< Disable collisions between the articulation's links (note that parent/child collisions are disabled internally in either case). + }; +}; + +typedef PxFlags PxArticulationFlags; +PX_FLAGS_OPERATORS(PxArticulationFlag::Enum, PxU8) + +struct PxArticulationDriveType +{ + enum Enum + { + eFORCE = 0, //!< The output of the implicit spring drive controller is a force/torque. + eACCELERATION = 1, //!< The output of the implicit spring drive controller is a joint acceleration (use this to get (spatial)-inertia-invariant behavior of the drive). + eNONE = 2 + }; +}; + +/** +\brief Data structure to set articulation joint limits. + +- The lower limit should be strictly smaller than the higher limit. If the limits should be equal, use PxArticulationMotion::eLOCKED +and an appropriate offset in the parent/child joint frames. +- The limit units are linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis. + +\see PxArticulationJointReducedCoordinate::setLimitParams, PxArticulationReducedCoordinate +*/ +struct PxArticulationLimit +{ + PxArticulationLimit(){} + + PxArticulationLimit(const PxReal low_, const PxReal high_) + { + low = low_; + high = high_; + } + + /** + \brief The lower limit on the joint axis position. + + Range: [-PX_MAX_F32, high)
+ Default: 0.0f
+ */ + PxReal low; + + /** + \brief The higher limit on the joint axis position. + + Range: (low, PX_MAX_F32]
+ Default: 0.0f
+ */ + PxReal high; +}; + +/** +\brief Data structure to enforce static model of a DC motor. + +Performance envelope is composed of 2 constraints: +1. effort-velocity curve: |Effort| <= maxEffort - velDependentResistance * |jointVelocity| +2. velocity-effort curve: |JointVelocity| <= maxActuatorVelocity - speedEffortGradient * |Effort| +where Effort refers to the sum of the articulation cache effort to the joint and the drive effort. +*/ +struct PxPerformanceEnvelope +{ + + // PX_SERIALIZATION + PxPerformanceEnvelope(const PxEMPTY&){} + // ~PX_SERIALIZATION + + PxPerformanceEnvelope( + PxReal maxEffort_ = 0.0f, + PxReal maxActuatorVelocity_ = 0.0f, + PxReal velocityDependentResistance_ = 0.0f, + PxReal speedEffortGradient_ = 0.0f + ) : maxEffort(maxEffort_), + maxActuatorVelocity(maxActuatorVelocity_), + velocityDependentResistance(velocityDependentResistance_), + speedEffortGradient(speedEffortGradient_) + {} + + /** + \brief Max effort the actuator can produce at zero velocity. For linear actuators, effort refers to force; for rotational actuators, effort refers to torque. + + Range: [0, PX_MAX_F32] + Default: 0.0f + */ + PxReal maxEffort; + + /** + \brief The maximum velocity of the actuator at zero effort. + + Range: [0, PX_MAX_F32] + Default: 0.0f + */ + PxReal maxActuatorVelocity; + + /** + \brief The rate at which available effort decreases as velocity increases. + + This represents the slope of the effort-velocity curve. + Range: [0, PX_MAX_F32] + Default: 0.0f + */ + PxReal velocityDependentResistance; + + /** + \brief The rate at which maximum velocity decreases as effort increases. + + This represents the inverse slope of the velocity-effort curve. + Range: [0, PX_MAX_F32] + Default: 0.0f + */ + PxReal speedEffortGradient; +}; + +/** +\brief Data structure to store friction parameters. + +\see PxArticulationJointReducedCoordinate::setFrictionParams, PxArticulationReducedCoordinate +*/ +struct PxJointFrictionParams +{ + PxJointFrictionParams(){} + + PxJointFrictionParams(const PxReal staticFrictionEffort_, const PxReal dynamicFrictionEffort_, const PxReal viscousFrictionCoefficient_) + : staticFrictionEffort(staticFrictionEffort_) + , dynamicFrictionEffort(dynamicFrictionEffort_) + , viscousFrictionCoefficient(viscousFrictionCoefficient_) + { + } + + /** + \brief Coulomb static friction effort. For linear motion effort refers to force, for rotational - to torque. + + Range: [0, PX_MAX_F32]
+ Default: 0.0f
+ */ + PxReal staticFrictionEffort; + + /** + \brief Coulomb dynamic friction effort. For linear motion effort refers to force, for rotational - to torque. + + Range: [0, PX_MAX_F32]
+ Default: 0.0f
+ */ + PxReal dynamicFrictionEffort; + + /** + \brief Viscous friction coefficient. viscousFrictionForce(Torque) = -viscousFrictionCoefficient * speed. + + Range: [0, PX_MAX_F32]
+ Default: 0.0f
+ */ + PxReal viscousFrictionCoefficient; +}; + +/** +\brief Data structure for articulation joint drive configuration. + +\see PxArticulationJointReducedCoordinate::setDriveParams, PxArticulationReducedCoordinate +*/ +struct PxArticulationDrive +{ + // PX_SERIALIZATION + PxArticulationDrive(const PxEMPTY&): envelope(PxEmpty) {} + //~PX_SERIALIZATION + + PxArticulationDrive() {} + + PxArticulationDrive(const PxReal stiffness_, const PxReal damping_, const PxReal maxForce_, + PxArticulationDriveType::Enum driveType_ = PxArticulationDriveType::eFORCE) + { + stiffness = stiffness_; + damping = damping_; + maxForce = maxForce_; + driveType = driveType_; + envelope = PxPerformanceEnvelope(0.0f, 0.0f, 0.0f, 0.0f); + } + + PxArticulationDrive(const PxReal stiffness_, const PxReal damping_, + const PxPerformanceEnvelope envelope_, + PxArticulationDriveType::Enum driveType_ = PxArticulationDriveType::eFORCE) + { + stiffness = stiffness_; + damping = damping_; + driveType = driveType_; + envelope = envelope_; + maxForce = 0.0f; + } + + /** + \brief The drive stiffness, i.e. the proportional gain of the implicit PD controller. + + See manual for further information, and the drives' implicit spring-damper (i.e. PD control) implementation in particular. + + Units: (distance = linear scene units)
+ Rotational axis: torque/rad if driveType = PxArticulationDriveType::eFORCE; or (rad/s^2)/rad if driveType = PxArticulationDriveType::eACCELERATION
+ Translational axis: force/distance if driveType = PxArticulationDriveType::eFORCE; or (distance/s^2)/distance if driveType = PxArticulationDriveType::eACCELERATION
+ Range: [0, PX_MAX_F32]
+ Default: 0.0f
+ */ + PxReal stiffness; + + /** + \brief The drive damping, i.e. the derivative gain of the implicit PD controller. + + See manual for further information, and the drives' implicit spring-damper (i.e. PD control) implementation in particular. + + Units: (distance = linear scene units)
+ Rotational axis: torque/(rad/s) if driveType = PxArticulationDriveType::eFORCE; or (rad/s^2)/(rad/s) if driveType = PxArticulationDriveType::eACCELERATION
+ Translational axis: force/(distance/s) if driveType = PxArticulationDriveType::eFORCE; or (distance/s^2)/(distance/s) if driveType = PxArticulationDriveType::eACCELERATION
+ Range: [0, PX_MAX_F32]
+ Default: 0.0f
+ */ + PxReal damping; + + /** + \deprecated Will be removed in a future version + \brief The drive force limit. + + - The limit is enforced regardless of the drive type #PxArticulationDriveType. + - The limit corresponds to a force (linear axis) or torque (rotational axis) if PxArticulationFlag::eDRIVE_LIMITS_ARE_FORCES is set, and to an impulse (force|torque * dt) otherwise. + + Range: [0, PX_MAX_F32]
+ Default: 0.0f
+ + \see PxArticulationFlag::eDRIVE_LIMITS_ARE_FORCES + */ + PxReal maxForce; + + /** + \brief The performance envelope of a motor. + + When an envelope with a non-zero maxEffort is explicitly set (via constructor or otherwise), the envelope takes precedence over maxForce. + In such cases, the joint force is clamped according to the performance envelope. If the default envelope (with zero maxEffort) is used, + clamping is instead based on the maxForce parameter and the PxArticulationFlag::eDRIVE_LIMITS_ARE_FORCES flag. + + \see PxPerformanceEnvelope + */ + PxPerformanceEnvelope envelope; + + /** + \brief The drive type. + + \see PxArticulationDriveType + */ + PxArticulationDriveType::Enum driveType; +}; + +struct PxTGSSolverBodyVel +{ + PX_ALIGN(16, PxVec3) linearVelocity; //12 + PxU16 maxDynamicPartition; //14 Used to accumulate the max partition of dynamic interactions + PxU16 nbStaticInteractions; //16 Used to accumulate the number of static interactions + PxVec3 angularVelocity; //28 + PxU32 partitionMask; //32 Used in partitioning as a bit-field + PxVec3 deltaAngDt; //44 + PxReal maxAngVel; //48 + PxVec3 deltaLinDt; //60 + PxU16 lockFlags; //62 + bool isKinematic; //63 + PxU8 pad; //64 + + PX_FORCE_INLINE PxReal projectVelocity(const PxVec3& lin, const PxVec3& ang) const + { + return linearVelocity.dot(lin) + angularVelocity.dot(ang); + } +}; + +//Needed only by prep, integration and 1D constraints +//Solver body state at time = simulationTime + simStepDt*posIter/nbPosIters +struct PxTGSSolverBodyTxInertia +{ + //Accumulated change to quaternion that has accumulated since solver started. + PxQuat deltaBody2WorldQ; + //Absolute body position at t + PxVec3 body2WorldP; + //RotMatrix * I0^(-1/2) * RotMatrixTranspose + PxMat33 sqrtInvInertia; //!< inverse inertia in world space +}; +PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxTGSSolverBodyTxInertia) & 15)); + +struct PxTGSSolverBodyData +{ + PX_ALIGN(16, PxVec3) originalLinearVelocity; //!< Pre-solver linear velocity. + PxReal maxContactImpulse; //!< The max contact impulse. + PxVec3 originalAngularVelocity; //!< Pre-solver angular velocity + PxReal penBiasClamp; //!< The penetration bias clamp. + + PxReal invMass; //!< Inverse mass. + PxU32 nodeIndex; //!< The node idx of this solverBodyData. Used by solver to reference between solver bodies and island bodies. Not required by immediate mode. + PxReal reportThreshold; //!< Contact force threshold. + PxU32 pad; + + PxReal projectVelocity(const PxVec3& linear, const PxVec3& angular) const + { + return originalLinearVelocity.dot(linear) + originalAngularVelocity.dot(angular); + } +}; + +struct PxTGSSolverConstraintPrepDescBase +{ + PxConstraintInvMassScale invMassScales; //!< In: The local mass scaling for this pair. + + PxSolverConstraintDesc* desc; //!< Output: The PxSolverConstraintDesc filled in by contact prep + + const PxTGSSolverBodyVel* body0; //!< In: The first body. Stores velocity information. Unused unless contact involves articulations. + const PxTGSSolverBodyVel* body1; //!< In: The second body. Stores velocity information. Unused unless contact involves articulations. + + const PxTGSSolverBodyTxInertia* body0TxI; //!< In: The first PxTGSSolverBodyTxInertia. Stores the delta body to world transform and sqrtInvInertia for first body. + const PxTGSSolverBodyTxInertia* body1TxI; //!< In: The second PxTGSSolverBodyTxInertia. Stores the delta body to world transform and sqrtInvInertia for second body. + + const PxTGSSolverBodyData* bodyData0; //!< In: The first PxTGSSolverBodyData. Stores mass and miscellaneous information for the first body. + const PxTGSSolverBodyData* bodyData1; //!< In: The second PxTGSSolverBodyData. Stores mass and miscellaneous information for the second body. + + PxTransform bodyFrame0; //!< In: The world-space transform of the first body. + PxTransform bodyFrame1; //!< In: The world-space transform of the second body. + + // PT: these two use 4 bytes each but we only need 4 bits (or even just 2 bits) for a type + PxSolverContactDesc::BodyState bodyState0; //!< In: Defines what kind of actor the first body is + PxSolverContactDesc::BodyState bodyState1; //!< In: Defines what kind of actor the second body is + + // PT: the following pointers have been moved here from derived structures to fill padding bytes + union + { + // PT: moved from PxTGSSolverConstraintPrepDesc + void* writeback; //!< Pointer to constraint writeback structure. Reports back joint breaking. If not required, set to NULL. + + // PT: moved from PxTGSSolverContactDesc + void* shapeInteraction; //!< Pointer to shape interaction. Used for force threshold reports in solver. Set to NULL if using immediate mode. + }; +}; + +// PT: ensure that we can safely read 4 bytes after the bodyFrames +PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxTGSSolverConstraintPrepDescBase, bodyFrame0)+sizeof(PxTGSSolverConstraintPrepDescBase::bodyFrame0) + 4 <= sizeof(PxTGSSolverConstraintPrepDescBase)); +PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxTGSSolverConstraintPrepDescBase, bodyFrame1)+sizeof(PxTGSSolverConstraintPrepDescBase::bodyFrame1) + 4 <= sizeof(PxTGSSolverConstraintPrepDescBase)); + +struct PxTGSSolverConstraintPrepDesc : public PxTGSSolverConstraintPrepDescBase +{ + Px1DConstraint* rows; //!< The start of the constraint rows + PxU32 numRows; //!< The number of rows + + PxReal linBreakForce, angBreakForce; //!< Break forces + PxReal minResponseThreshold; //!< The minimum response threshold + bool disablePreprocessing; //!< Disable joint pre-processing. Pre-processing can improve stability but under certain circumstances, e.g. when some invInertia rows are zero/almost zero, can cause instabilities. + bool improvedSlerp; //!< Use improved slerp model + bool driveLimitsAreForces; //!< Indicates whether drive limits are forces + bool extendedLimits; //!< Indicates whether extended limits are used + bool disableConstraint; //!< Disables constraint + + PxVec3p body0WorldOffset; //!< Body0 world offset + PxVec3p cA2w; //!< Location of anchor point A in world space + PxVec3p cB2w; //!< Location of anchor point B in world space +}; + +struct PxTGSSolverContactDesc : public PxTGSSolverConstraintPrepDescBase +{ + PxU8* frictionPtr; //!< InOut: Friction patch correlation data. Set each frame by solver. Can be retained for improved behavior or discarded each frame. + const PxContactPoint* contacts; //!< The start of the contacts for this pair + PxU32 numContacts; //!< The total number of contacts this pair references. + + PxU8 frictionCount; //!< The total number of friction patches in this pair + bool hasMaxImpulse; //!< Defines whether this pairs has maxImpulses clamping enabled + bool disableStrongFriction; //!< Defines whether this pair disables strong friction (sticky friction correlation) + bool hasForceThresholds; //!< Defines whether this pair requires force thresholds + + PxReal restDistance; //!< A distance at which the solver should aim to hold the bodies separated. Default is 0 + PxReal maxCCDSeparation; //!< A distance used to configure speculative CCD behavior. Default is PX_MAX_F32. Set internally in PhysX for bodies with eENABLE_SPECULATIVE_CCD on. Do not set directly! + + PxReal* contactForces; //!< Out: A buffer for the solver to write applied contact forces to. + + PxU32 startFrictionPatchIndex; //!< Start index of friction patch in the correlation buffer. Set by friction correlation + PxU32 numFrictionPatches; //!< Total number of friction patches in this pair. Set by friction correlation + + PxU32 startContactPatchIndex; //!< The start index of this pair's contact patches in the correlation buffer. For internal use only + PxU16 numContactPatches; //!< Total number of contact patches. + PxU16 axisConstraintCount; //!< Axis constraint count. Defines how many constraint rows this pair has produced. Useful for statistical purposes. + + PxReal maxImpulse; //!< The maximum impulse the solver is allowed to introduce for this pair of bodies. + + PxReal torsionalPatchRadius; //!< This defines the radius of the contact patch used to apply torsional friction. + PxReal minTorsionalPatchRadius; //!< This defines the minimum radius of the contact patch used to apply torsional friction. + PxReal offsetSlop; //!< Slop value used to snap contact line of action back in-line with the COM. +}; + +#if !PX_DOXYGEN +} +#endif + +#if PX_VC +#pragma warning(pop) +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/task/PxCpuDispatcher.h b/Jusin154_Team3D/Engine/Public/PhysX/task/PxCpuDispatcher.h new file mode 100644 index 000000000..717e968be --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/task/PxCpuDispatcher.h @@ -0,0 +1,82 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_CPU_DISPATCHER_H +#define PX_CPU_DISPATCHER_H + +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxBaseTask; + +/** + \brief A CpuDispatcher is responsible for scheduling the execution of tasks passed to it by the SDK. + + A typical implementation would for example use a thread pool with the dispatcher + pushing tasks onto worker thread queues or a global queue. + + \see PxBaseTask + \see PxTask + \see PxTaskManager +*/ +class PxCpuDispatcher +{ +public: + /** + \brief Called by the TaskManager when a task is to be queued for execution. + + Upon receiving a task, the dispatcher should schedule the task to run. + After the task has been run, it should call the release() method and + discard its pointer. + + \param[in] task The task to be run. + + \see PxBaseTask + */ + virtual void submitTask(PxBaseTask& task) = 0; + + /** + \brief Returns the number of available worker threads for this dispatcher. + + The SDK will use this count to control how many tasks are submitted. By + matching the number of tasks with the number of execution units task + overhead can be reduced. + */ + virtual uint32_t getWorkerCount() const = 0; + + virtual ~PxCpuDispatcher() {} +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/task/PxTask.h b/Jusin154_Team3D/Engine/Public/PhysX/task/PxTask.h new file mode 100644 index 000000000..0da86ade3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/task/PxTask.h @@ -0,0 +1,331 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_TASK_H +#define PX_TASK_H + +#include "task/PxTaskManager.h" +#include "task/PxCpuDispatcher.h" +#include "foundation/PxAssert.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +/** + * \brief Base class of all task types + * + * PxBaseTask defines a runnable reference counted task with built-in profiling. + */ +class PxBaseTask +{ +public: + PxBaseTask() : mContextID(0), mTm(NULL) {} + virtual ~PxBaseTask() {} + + /** + * \brief The user-implemented run method where the task's work should be performed + * + * run() methods must be thread safe, stack friendly (no alloca, etc), and + * must never block. + */ + virtual void run() = 0; + + /** + * \brief Return a user-provided task name for profiling purposes. + * + * It does not have to be unique, but unique names are helpful. + * + * \return The name of this task + */ + virtual const char* getName() const = 0; + + //! \brief Implemented by derived implementation classes + virtual void addReference() = 0; + //! \brief Implemented by derived implementation classes + virtual void removeReference() = 0; + //! \brief Implemented by derived implementation classes + virtual int32_t getReference() const = 0; + + /** \brief Implemented by derived implementation classes + * + * A task may assume in its release() method that the task system no longer holds + * references to it - so it may safely run its destructor, recycle itself, etc. + * provided no additional user references to the task exist + */ + virtual void release() = 0; + + /** + * \brief Tells the scheduler if a task is high priority or not. + * + * This function is a hint to the scheduler, to let it know that some tasks are + * higher priority than others. The scheduler should try to execute high priority + * tasks first, but there is no guarantee that it does (some schedulers can ignore + * this information). + * + * \return True for high priority task, false for regular tasks + */ + virtual bool isHighPriority() const { return false; } + + /** + * \brief Return PxTaskManager to which this task was submitted + * + * Note, can return NULL if task was not submitted, or has been + * completed. + */ + PX_FORCE_INLINE PxTaskManager* getTaskManager() const + { + return mTm; + } + + PX_FORCE_INLINE void setContextId(PxU64 id) { mContextID = id; } + PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; } + +protected: + PxU64 mContextID; //!< Context ID for profiler interface + PxTaskManager* mTm; //!< Owning PxTaskManager instance + + friend class PxTaskMgr; +}; + + +/** + * \brief A PxBaseTask implementation with deferred execution and full dependencies + * + * A PxTask must be submitted to a PxTaskManager to to be executed, Tasks may + * optionally be named when they are submitted. + */ +class PxTask : public PxBaseTask +{ +public: + PxTask() : mTaskID(0) {} + virtual ~PxTask() {} + + //! \brief Release method implementation + virtual void release() PX_OVERRIDE + { + PX_ASSERT(mTm); + + // clear mTm before calling taskCompleted() for safety + PxTaskManager* save = mTm; + mTm = NULL; + save->taskCompleted(*this); + } + + //! \brief Inform the PxTaskManager this task must finish before the given + // task is allowed to start. + PX_INLINE void finishBefore(PxTaskID taskID) + { + PX_ASSERT(mTm); + mTm->finishBefore(*this, taskID); + } + + //! \brief Inform the PxTaskManager this task cannot start until the given + // task has completed. + PX_INLINE void startAfter(PxTaskID taskID) + { + PX_ASSERT(mTm); + mTm->startAfter(*this, taskID); + } + + /** + * \brief Manually increment this task's reference count. The task will + * not be allowed to run until removeReference() is called. + */ + virtual void addReference() PX_OVERRIDE + { + PX_ASSERT(mTm); + mTm->addReference(mTaskID); + } + + /** + * \brief Manually decrement this task's reference count. If the reference + * count reaches zero, the task will be dispatched. + */ + virtual void removeReference() PX_OVERRIDE + { + PX_ASSERT(mTm); + mTm->decrReference(mTaskID); + } + + /** + * \brief Return the ref-count for this task + */ + virtual int32_t getReference() const PX_OVERRIDE + { + return mTm->getReference(mTaskID); + } + + /** + * \brief Return the unique ID for this task + */ + PX_INLINE PxTaskID getTaskID() const + { + return mTaskID; + } + + /** + * \brief Called by PxTaskManager at submission time for initialization + * + * Perform simulation step initialization here. + */ + virtual void submitted() + { + } + +protected: + PxTaskID mTaskID; //!< ID assigned at submission + + friend class PxTaskMgr; +}; + + +/** + * \brief A PxBaseTask implementation with immediate execution and simple dependencies + * + * A PxLightCpuTask bypasses the PxTaskManager launch dependencies and will be + * submitted directly to your scene's CpuDispatcher. When the run() function + * completes, it will decrement the reference count of the specified + * continuation task. + * + * You must use a full-blown PxTask if you want your task to be resolved + * by another PxTask, or you need more than a single dependency to be + * resolved when your task completes, or your task will not run on the + * CpuDispatcher. + */ +class PxLightCpuTask : public PxBaseTask +{ +public: + PxLightCpuTask() + : mCont( NULL ) + , mRefCount( 0 ) + { + } + virtual ~PxLightCpuTask() + { + mTm = NULL; + } + + /** + * \brief Initialize this task and specify the task that will have its ref count decremented on completion. + * + * Submission is deferred until the task's mRefCount is decremented to zero. + * Note that we only use the PxTaskManager to query the appropriate dispatcher. + * + * \param[in] tm The PxTaskManager this task is managed by + * \param[in] c The task to be executed when this task has finished running + */ + PX_INLINE void setContinuation(PxTaskManager& tm, PxBaseTask* c) + { + PX_ASSERT(mRefCount == 0); + mRefCount = 1; + mCont = c; + mTm = &tm; + if(c) + c->addReference(); + } + + /** + * \brief Initialize this task and specify the task that will have its ref count decremented on completion. + * + * This overload of setContinuation() queries the PxTaskManager from the continuation + * task, which cannot be NULL. + * \param[in] c The task to be executed after this task has finished running + */ + PX_INLINE void setContinuation(PxBaseTask* c) + { + PX_ASSERT(c); + PX_ASSERT(mRefCount == 0); + mRefCount = 1; + mCont = c; + if(c) + { + c->addReference(); + mTm = c->getTaskManager(); + PX_ASSERT(mTm); + } + } + + /** + * \brief Retrieves continuation task + */ + PX_INLINE PxBaseTask* getContinuation() const + { + return mCont; + } + + /** + * \brief Manually decrement this task's reference count. If the reference + * count reaches zero, the task will be dispatched. + */ + virtual void removeReference() PX_OVERRIDE + { + mTm->decrReference(*this); + } + + /** \brief Return the ref-count for this task */ + virtual int32_t getReference() const PX_OVERRIDE + { + return mRefCount; + } + + /** + * \brief Manually increment this task's reference count. The task will + * not be allowed to run until removeReference() is called. + */ + virtual void addReference() PX_OVERRIDE + { + mTm->addReference(*this); + } + + /** + * \brief called by CpuDispatcher after run method has completed + * + * Decrements the continuation task's reference count, if specified. + */ + virtual void release() PX_OVERRIDE + { + if(mCont) + mCont->removeReference(); + } + +protected: + + PxBaseTask* mCont; //!< Continuation task, can be NULL + volatile int32_t mRefCount; //!< PxTask is dispatched when reaches 0 + + friend class PxTaskMgr; +}; + + +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/task/PxTaskManager.h b/Jusin154_Team3D/Engine/Public/PhysX/task/PxTaskManager.h new file mode 100644 index 000000000..853f090fb --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/task/PxTaskManager.h @@ -0,0 +1,203 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. + +#ifndef PX_TASK_MANAGER_H +#define PX_TASK_MANAGER_H + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxErrorCallback.h" + +#if !PX_DOXYGEN +namespace physx +{ +#endif + +class PxBaseTask; +class PxTask; +class PxLightCpuTask; +typedef unsigned int PxTaskID; + +/** +\brief Identifies the type of each heavyweight PxTask object + +\note This enum type is only used by PxTask objects, PxLightCpuTasks do not use this enum. + +\see PxTask +\see PxLightCpuTask +*/ +struct PxTaskType +{ + /** + * \brief Identifies the type of each heavyweight PxTask object + */ + enum Enum + { + eCPU, //!< PxTask will be run on the CPU + eNOT_PRESENT, //!< Return code when attempting to find a task that does not exist + eCOMPLETED //!< PxTask execution has been completed + }; +}; + +class PxCpuDispatcher; + +/** + \brief The PxTaskManager interface + + A PxTaskManager instance holds references to user-provided dispatcher objects. When tasks are + submitted the PxTaskManager routes them to the appropriate dispatcher and handles task profiling if enabled. + Users should not implement the PxTaskManager interface, the SDK creates its own concrete PxTaskManager object + per-scene which users can configure by passing dispatcher objects into the PxSceneDesc. + + \see PxCpuDispatcher + +*/ +class PxTaskManager +{ +public: + + /** + \brief Set the user-provided dispatcher object for CPU tasks + + \param[in] ref The dispatcher object. + + \see PxCpuDispatcher + */ + virtual void setCpuDispatcher(PxCpuDispatcher& ref) = 0; + + /** + \brief Get the user-provided dispatcher object for CPU tasks + + \return The CPU dispatcher object. + + \see PxCpuDispatcher + */ + virtual PxCpuDispatcher* getCpuDispatcher() const = 0; + + /** + \brief Reset any dependencies between Tasks + + \note Will be called at the start of every frame before tasks are submitted. + + \see PxTask + */ + virtual void resetDependencies() = 0; + + /** + \brief Called by the owning scene to start the task graph. + + \note All tasks with ref count of 1 will be dispatched. + + \see PxTask + */ + virtual void startSimulation() = 0; + + /** + \brief Called by the owning scene at the end of a simulation step. + */ + virtual void stopSimulation() = 0; + + /** + \brief Called by the worker threads to inform the PxTaskManager that a task has completed processing. + + \param[in] task The task which has been completed + */ + virtual void taskCompleted(PxTask& task) = 0; + + /** + \brief Retrieve a task by name + + \param[in] name The unique name of a task + \return The ID of the task with that name, or eNOT_PRESENT if not found + */ + virtual PxTaskID getNamedTask(const char* name) = 0; + + /** + \brief Submit a task with a unique name. + + \param[in] task The task to be executed + \param[in] name The unique name of a task + \param[in] type The type of the task (default eCPU) + \return The ID of the task with that name, or eNOT_PRESENT if not found + */ + virtual PxTaskID submitNamedTask(PxTask* task, const char* name, PxTaskType::Enum type = PxTaskType::eCPU) = 0; + + /** + \brief Submit an unnamed task. + + \param[in] task The task to be executed + \param[in] type The type of the task (default eCPU) + + \return The ID of the task with that name, or eNOT_PRESENT if not found + */ + virtual PxTaskID submitUnnamedTask(PxTask& task, PxTaskType::Enum type = PxTaskType::eCPU) = 0; + + /** + \brief Retrieve a task given a task ID + + \param[in] id The ID of the task to return, a valid ID must be passed or results are undefined + + \return The task associated with the ID + */ + virtual PxTask* getTaskFromID(PxTaskID id) = 0; + + /** + \brief Release the PxTaskManager object, referenced dispatchers will not be released + */ + virtual void release() = 0; + + /** + \brief Construct a new PxTaskManager instance with the given [optional] dispatchers + */ + static PxTaskManager* createTaskManager(PxErrorCallback& errorCallback, PxCpuDispatcher* = NULL); + +protected: + virtual ~PxTaskManager() {} + + /*! \cond PRIVATE */ + + virtual void finishBefore(PxTask& task, PxTaskID taskID) = 0; + virtual void startAfter(PxTask& task, PxTaskID taskID) = 0; + + virtual void addReference(PxTaskID taskID) = 0; + virtual void decrReference(PxTaskID taskID) = 0; + virtual int32_t getReference(PxTaskID taskID) const = 0; + + virtual void decrReference(PxLightCpuTask&) = 0; + virtual void addReference(PxLightCpuTask&) = 0; + + /*! \endcond */ + + friend class PxBaseTask; + friend class PxTask; + friend class PxLightCpuTask; +}; + +#if !PX_DOXYGEN +} // namespace physx +#endif + + +#endif diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleAPI.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleAPI.h new file mode 100644 index 000000000..b0a283ab7 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleAPI.h @@ -0,0 +1,143 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleLimits.h" +#include "vehicle2/PxVehicleComponent.h" +#include "vehicle2/PxVehicleComponentSequence.h" +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleFunctions.h" +#include "vehicle2/PxVehicleMaths.h" + +#include "vehicle2/braking/PxVehicleBrakingParams.h" +#include "vehicle2/braking/PxVehicleBrakingFunctions.h" + +#include "vehicle2/commands/PxVehicleCommandParams.h" +#include "vehicle2/commands/PxVehicleCommandStates.h" +#include "vehicle2/commands/PxVehicleCommandHelpers.h" + +#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h" +#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h" +#include "vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h" +#include "vehicle2/drivetrain/PxVehicleDrivetrainFunctions.h" +#include "vehicle2/drivetrain/PxVehicleDrivetrainComponents.h" + +#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h" +#include "vehicle2/physxActor/PxVehiclePhysXActorHelpers.h" +#include "vehicle2/physxActor/PxVehiclePhysXActorFunctions.h" +#include "vehicle2/physxActor/PxVehiclePhysXActorComponents.h" + +#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h" +#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h" +#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h" +#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintFunctions.h" +#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintComponents.h" + +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryHelpers.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryComponents.h" + +#include "vehicle2/pvd/PxVehiclePvdHelpers.h" +#include "vehicle2/pvd/PxVehiclePvdFunctions.h" +#include "vehicle2/pvd/PxVehiclePvdComponents.h" + +#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h" +#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h" +#include "vehicle2/rigidBody/PxVehicleRigidBodyFunctions.h" +#include "vehicle2/rigidBody/PxVehicleRigidBodyComponents.h" + +#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h" + +#include "vehicle2/steering/PxVehicleSteeringParams.h" +#include "vehicle2/steering/PxVehicleSteeringFunctions.h" + +#include "vehicle2/suspension/PxVehicleSuspensionParams.h" +#include "vehicle2/suspension/PxVehicleSuspensionStates.h" +#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h" +#include "vehicle2/suspension/PxVehicleSuspensionFunctions.h" +#include "vehicle2/suspension/PxVehicleSuspensionComponents.h" + +#include "vehicle2/tire/PxVehicleTireParams.h" +#include "vehicle2/tire/PxVehicleTireStates.h" +#include "vehicle2/tire/PxVehicleTireHelpers.h" +#include "vehicle2/tire/PxVehicleTireFunctions.h" +#include "vehicle2/tire/PxVehicleTireComponents.h" + +#include "vehicle2/wheel/PxVehicleWheelParams.h" +#include "vehicle2/wheel/PxVehicleWheelStates.h" +#include "vehicle2/wheel/PxVehicleWheelHelpers.h" +#include "vehicle2/wheel/PxVehicleWheelFunctions.h" +#include "vehicle2/wheel/PxVehicleWheelComponents.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + + /** \brief Initialize the PhysX Vehicle library. + + This should be called before calling any functions or methods in extensions which may require allocation. + \note This function does not need to be called before creating a PxDefaultAllocator object. + + \param foundation a PxFoundation object + + \see PxCloseVehicleExtension PxFoundation + */ + PX_FORCE_INLINE bool PxInitVehicleExtension(physx::PxFoundation& foundation) + { + PX_UNUSED(foundation); + PX_CHECK_AND_RETURN_VAL(&PxGetFoundation() == &foundation, "Supplied foundation must match the one that will be used to perform allocations", false); + PxIncFoundationRefCount(); + return true; + } + + /** \brief Shut down the PhysX Vehicle library. + + This function should be called to cleanly shut down the PhysX Vehicle library before application exit. + + \note This function is required to be called to release foundation usage. + + \see PxInitVehicleExtension + */ + PX_FORCE_INLINE void PxCloseVehicleExtension() + { + PxDecFoundationRefCount(); + } + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleComponent.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleComponent.h new file mode 100644 index 000000000..2026b25a6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleComponent.h @@ -0,0 +1,66 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif +struct PxVehicleSimulationContext; + +class PxVehicleComponent +{ +public: + + virtual ~PxVehicleComponent() {} + + /** + \brief Update function for a vehicle component. + + \param[in] dt The timestep size to use for the update step. + \param[in] context Vehicle simulation context holding global data or data that usually applies to a + large group of vehicles. + \return True if subsequent components in a sequence should get updated, false if the sequence should + be aborted. + + \see PxVehicleComponentSequence + */ + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) = 0; + +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleComponentSequence.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleComponentSequence.h new file mode 100644 index 000000000..d6462c3ec --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleComponentSequence.h @@ -0,0 +1,322 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once +#include "foundation/PxAssert.h" +#include "foundation/PxErrors.h" +#include "foundation/PxFoundation.h" +#include "PxVehicleComponent.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + + +struct PxVehicleComponentSequenceLimits +{ + enum Enum + { + eMAX_NB_SUBGROUPS = 16, + eMAX_NB_COMPONENTS = 64, + eMAX_NB_SUBGROUPELEMENTS = eMAX_NB_SUBGROUPS + eMAX_NB_COMPONENTS + }; +}; + +struct PxVehicleComponentSequence +{ + enum + { + eINVALID_SUBSTEP_GROUP = 0xff + }; + + PxVehicleComponentSequence() + : mNbComponents(0), mNbSubgroups(1), mNbSubGroupElements(0), mActiveSubgroup(0) + { + } + + /** + \brief Add a component to the sequence. + + \param[in] component The component to add to the sequence. + \return True on success, else false (for example due to component count limit being reached). + */ + PX_FORCE_INLINE bool add(PxVehicleComponent* component); + + /** + \brief Start a substepping group. + \note All components added using #add() will be added to the new substepping group until either the group + is marked as complete with a call to #endSubstepGroup() or a subsequent substepping group is started with + a call to #beginSubstepGroup(). + \note Groups can be nested with stacked calls to #beginSubstepGroup(). + \note Each group opened by #beginSubstepGroup() must be closed with a complementary #endSubstepGroup() prior to calling #update(). + \param[in] nbSubSteps is the number of substeps for the group's sequence. This can be changed with a call to #setSubsteps(). + \return Handle for the substepping group on success, else eINVALID_SUBSTEP_GROUP + \see setSubsteps() + \see endSubstepGroup() + */ + PX_FORCE_INLINE PxU8 beginSubstepGroup(const PxU8 nbSubSteps = 1); + + /** + \brief End a substepping group + \note The group most recently opened with #beginSubstepGroup() will be closed by this call. + \see setSubsteps() + \see beginSubstepGroup() + */ + PX_FORCE_INLINE void endSubstepGroup() + { + mActiveSubgroup = mSubGroups[mActiveSubgroup].parentGroup; + } + + /** + \brief Set the number of substeps to perform for a specific substepping group. + \param[in] subGroupHandle specifies the substepping group + \param[in] nbSteps is the number of times to invoke the sequence of components and groups in the specified substepping group. + \see beginSubstepGroup() + \see endSubstepGroup() + */ + void setSubsteps(const PxU8 subGroupHandle, const PxU8 nbSteps) + { + PX_ASSERT(subGroupHandle < mNbSubgroups); + mSubGroups[subGroupHandle].nbSteps = nbSteps; + } + + /** + \brief Update each component in the sequence. + + \note If the update method of a component in the sequence returns false, the update process gets aborted. + + \param[in] dt is the timestep of the update. The provided value has to be positive. + \param[in] context specifies global quantities of the simulation such as gravitational acceleration. + */ + void update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_ASSERT(0 == mActiveSubgroup); + + if (dt > 0.0f) + { + updateSubGroup(dt, context, 0, 1); + } + else + { + PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, + "PxVehicleComponentSequence::update: The timestep must be positive!"); + } + } + +private: + enum + { + eINVALID_COMPONENT = 0xff, + eINVALID_SUB_GROUP_ELEMENT = 0xff + }; + + //Elements have the form of a linked list to allow traversal over a list of elements. + //Each element is either a single component or a subgroup. + struct SubGroupElement + { + SubGroupElement() + : childGroup(eINVALID_SUBSTEP_GROUP), + component(eINVALID_COMPONENT), + nextElement(eINVALID_SUB_GROUP_ELEMENT) + { + } + + PxU8 childGroup; + PxU8 component; + PxU8 nextElement; + }; + + //A group is a linked list of elements to be processed in sequence. + //Each group stores the first element in the sequence. + //Each element in the sequence stores the next element in the sequence + //to allow traversal over the list of elements in the group. + struct Group + { + Group() + : parentGroup(eINVALID_SUBSTEP_GROUP), + firstElement(eINVALID_SUB_GROUP_ELEMENT), + nbSteps(1) + { + } + PxU8 parentGroup; + PxU8 firstElement; + PxU8 nbSteps; + }; + + PxVehicleComponent* mComponents[PxVehicleComponentSequenceLimits::eMAX_NB_COMPONENTS]; + PxU8 mNbComponents; + + Group mSubGroups[PxVehicleComponentSequenceLimits::eMAX_NB_SUBGROUPS]; + PxU8 mNbSubgroups; + + SubGroupElement mSubGroupElements[PxVehicleComponentSequenceLimits::eMAX_NB_SUBGROUPELEMENTS]; + PxU8 mNbSubGroupElements; + + PxU8 mActiveSubgroup; + + bool updateSubGroup(const PxReal dt, const PxVehicleSimulationContext& context, const PxU8 groupId, const PxU8 parentSepMultiplier) + { + const PxU8 nbSteps = mSubGroups[groupId].nbSteps; + const PxU8 stepMultiplier = parentSepMultiplier * nbSteps; + const PxReal timestepForGroup = dt / PxReal(stepMultiplier); + for (PxU8 k = 0; k < nbSteps; k++) + { + PxU8 nextElement = mSubGroups[groupId].firstElement; + while (eINVALID_SUB_GROUP_ELEMENT != nextElement) + { + const SubGroupElement& e = mSubGroupElements[nextElement]; + PX_ASSERT(e.component != eINVALID_COMPONENT || e.childGroup != eINVALID_SUBSTEP_GROUP); + if (eINVALID_COMPONENT != e.component) + { + PxVehicleComponent* c = mComponents[e.component]; + if (!c->update(timestepForGroup, context)) + return false; + } + else + { + PX_ASSERT(eINVALID_SUBSTEP_GROUP != e.childGroup); + if (!updateSubGroup(dt, context, e.childGroup, stepMultiplier)) + return false; + } + nextElement = e.nextElement; + } + } + + return true; + } + + PxU8 getLastKnownElementInGroup(const PxU8 groupId) const + { + PxU8 currElement = mSubGroups[groupId].firstElement; + PxU8 nextElement = mSubGroups[groupId].firstElement; + while (nextElement != eINVALID_SUB_GROUP_ELEMENT) + { + currElement = nextElement; + nextElement = mSubGroupElements[nextElement].nextElement; + } + return currElement; + } +}; + + +bool PxVehicleComponentSequence::add(PxVehicleComponent* c) +{ + if (PxVehicleComponentSequenceLimits::eMAX_NB_COMPONENTS == mNbComponents) + return false; + if (PxVehicleComponentSequenceLimits::eMAX_NB_SUBGROUPELEMENTS == mNbSubGroupElements) + return false; + + //Create a new element and point it at the component. + SubGroupElement& nextElementInGroup = mSubGroupElements[mNbSubGroupElements]; + nextElementInGroup.childGroup = eINVALID_SUBSTEP_GROUP; + nextElementInGroup.component = mNbComponents; + nextElementInGroup.nextElement = eINVALID_SUB_GROUP_ELEMENT; + + if (eINVALID_SUB_GROUP_ELEMENT == mSubGroups[mActiveSubgroup].firstElement) + { + //The group is empty so add the first element to it. + //Point the group at the new element because this will + //be the first element in the group. + mSubGroups[mActiveSubgroup].firstElement = mNbSubGroupElements; + } + else + { + //We are extending the sequence of element of the group. + //Add the new element to the end of the group's sequence. + mSubGroupElements[getLastKnownElementInGroup(mActiveSubgroup)].nextElement = mNbSubGroupElements; + } + + //Increment the number of elements. + mNbSubGroupElements++; + + //Record the component and increment the number of components. + mComponents[mNbComponents] = c; + mNbComponents++; + + return true; +} + +PxU8 PxVehicleComponentSequence::beginSubstepGroup(const PxU8 nbSubSteps) +{ + if (mNbSubgroups == PxVehicleComponentSequenceLimits::eMAX_NB_SUBGROUPS) + return eINVALID_SUBSTEP_GROUP; + if (mNbSubGroupElements == PxVehicleComponentSequenceLimits::eMAX_NB_SUBGROUPELEMENTS) + return eINVALID_SUBSTEP_GROUP; + + //We have a parent and child group relationship. + const PxU8 parentGroup = mActiveSubgroup; + const PxU8 childGroup = mNbSubgroups; + + //Set up the child group. + mSubGroups[childGroup].parentGroup = parentGroup; + mSubGroups[childGroup].firstElement = eINVALID_SUB_GROUP_ELEMENT; + mSubGroups[childGroup].nbSteps = nbSubSteps; + + //Create a new element to add to the parent group and point it at the child group. + SubGroupElement& nextElementIInGroup = mSubGroupElements[mNbSubGroupElements]; + nextElementIInGroup.childGroup = childGroup; + nextElementIInGroup.nextElement = eINVALID_SUB_GROUP_ELEMENT; + nextElementIInGroup.component = eINVALID_COMPONENT; + + //Add the new element to the parent group. + if (eINVALID_SUB_GROUP_ELEMENT == mSubGroups[parentGroup].firstElement) + { + //The parent group is empty so add the first element to it. + //Point the parent group at the new element because this will + //be the first element in the group. + mSubGroups[parentGroup].firstElement = mNbSubGroupElements; + } + else + { + //We are extending the sequence of elements of the parent group. + //Add the new element to the end of the group's sequence. + mSubGroupElements[getLastKnownElementInGroup(parentGroup)].nextElement = mNbSubGroupElements; + } + + //Push the active group. + //All subsequent operations will now address the child group and we push or pop the group. + mActiveSubgroup = childGroup; + + //Increment the number of elements. + mNbSubGroupElements++; + + //Increment the number of groups. + mNbSubgroups++; + + //Return the group id. + return mActiveSubgroup; +} + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleFunctions.h new file mode 100644 index 000000000..6b9330b2e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleFunctions.h @@ -0,0 +1,195 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxTransform.h" +#include "foundation/PxMat33.h" +#include "foundation/PxSimpleTypes.h" +#include "PxRigidBody.h" +#include "PxVehicleParams.h" +#include "roadGeometry/PxVehicleRoadGeometryState.h" +#include "rigidBody/PxVehicleRigidBodyStates.h" +#include "physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h" +#include "physxActor/PxVehiclePhysXActorStates.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif +PX_FORCE_INLINE PxVec3 PxVehicleTransformFrameToFrame +(const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVec3& v) +{ + PxVec3 result = v; + if ((srcFrame.lngAxis != trgFrame.lngAxis) || (srcFrame.latAxis != trgFrame.latAxis) || (srcFrame.vrtAxis != trgFrame.vrtAxis)) + { + const PxMat33 a = srcFrame.getFrame(); + const PxMat33 r = trgFrame.getFrame(); + result = (r * a.getTranspose() * v); + } + return result; +} + +PX_FORCE_INLINE PxVec3 PxVehicleTransformFrameToFrame +(const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, + const PxVehicleScale& srcScale, const PxVehicleScale& trgScale, + const PxVec3& v) +{ + PxVec3 result = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, v); + if((srcScale.scale != trgScale.scale)) + result *= (trgScale.scale / srcScale.scale); + return result; +} + +PX_FORCE_INLINE PxTransform PxVehicleTransformFrameToFrame +(const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, + const PxVehicleScale& srcScale, const PxVehicleScale& trgScale, + const PxTransform& v) +{ + PxTransform result(PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, v.p), v.q); + if ((srcFrame.lngAxis != trgFrame.lngAxis) || (srcFrame.latAxis != trgFrame.latAxis) || (srcFrame.vrtAxis != trgFrame.vrtAxis)) + { + PxF32 angle; + PxVec3 axis; + v.q.toRadiansAndUnitAxis(angle, axis); + result.q = PxQuat(angle, PxVehicleTransformFrameToFrame(srcFrame, trgFrame, axis)); + } + return result; +} + +PX_FORCE_INLINE PxVec3 PxVehicleComputeTranslation(const PxVehicleFrame& frame, const PxReal lng, const PxReal lat, const PxReal vrt) +{ + const PxVec3 v = frame.getFrame()*PxVec3(lng, lat, vrt); + return v; +} + +PX_FORCE_INLINE PxQuat PxVehicleComputeRotation(const PxVehicleFrame& frame, const PxReal roll, const PxReal pitch, const PxReal yaw) +{ + const PxMat33 m = frame.getFrame(); + const PxVec3& lngAxis = m.column0; + const PxVec3& latAxis = m.column1; + const PxVec3& vrtAxis = m.column2; + const PxQuat quatPitch(pitch, latAxis); + const PxQuat quatRoll(roll, lngAxis); + const PxQuat quatYaw(yaw, vrtAxis); + const PxQuat result = quatYaw * quatRoll * quatPitch; + return result; +} + +PX_FORCE_INLINE PxF32 PxVehicleComputeSign(const PxReal f) +{ + return physx::intrinsics::fsel(f, physx::intrinsics::fsel(-f, 0.0f, 1.0f), -1.0f); +} + + +/** +\brief Shift the origin of a vehicle by the specified vector. + +Call this method to adjust the internal data structures of vehicles to reflect the shifted origin location +(the shift vector will get subtracted from all world space spatial data). + +\param[in] axleDesc is a description of the wheels on the vehicle. +\param[in] shift is the translation vector used to shift the origin. +\param[in] rigidBodyState stores the current position of the vehicle +\param[in] roadGeometryStates stores the hit plane under each wheel. +\param[in] physxActor stores the PxRigidActor that is the vehicle's PhysX representation. +\param[in] physxQueryStates stores the hit point of the most recent execution of PxVehiclePhysXRoadGeometryQueryUpdate() for each wheel. +\note It is the user's responsibility to keep track of the summed total origin shift and adjust all input/output to/from the vehicle accordingly. +\note This call will not automatically shift the PhysX scene and its objects. PxScene::shiftOrigin() must be called separately to keep the systems in sync. +\note If there is no associated PxRigidActor then set physxActor to NULL. +\note If there is an associated PxRigidActor and it is already in a PxScene then the complementary call to PxScene::shiftOrigin() will take care of +shifting the associated PxRigidActor. This being the case, set physxActor to NULL. physxActor should be a non-NULL pointer only when there is an +associated PxRigidActor and it is not part of a PxScene. This can occur if the associated PxRigidActor is updated using PhysX immediate mode. +\note If scene queries are independent of PhysX geometry then set queryStates to NULL. +*/ +PX_FORCE_INLINE void PxVehicleShiftOrigin +(const PxVehicleAxleDescription& axleDesc, const PxVec3& shift, + PxVehicleRigidBodyState& rigidBodyState, PxVehicleRoadGeometryState* roadGeometryStates, + PxVehiclePhysXActor* physxActor = NULL, PxVehiclePhysXRoadGeometryQueryState* physxQueryStates = NULL) +{ + //Adjust the vehicle's internal pose. + rigidBodyState.pose.p -= shift; + + //Optionally adjust the PxRigidActor pose. + if (physxActor && !physxActor->rigidBody->getScene()) + { + const PxTransform oldPose = physxActor->rigidBody->getGlobalPose(); + const PxTransform newPose(oldPose.p - shift, oldPose.q); + physxActor->rigidBody->setGlobalPose(newPose); + } + + for (PxU32 i = 0; i < axleDesc.nbWheels; i++) + { + const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; + + //Optionally adjust the hit position. + if (physxQueryStates && physxQueryStates[wheelId].actor) + physxQueryStates[wheelId].hitPosition -= shift; + + //Adjust the hit plane. + if (roadGeometryStates[wheelId].hitState) + { + const PxPlane plane = roadGeometryStates[wheelId].plane; + PxU32 largestNormalComponentAxis = 0; + PxReal largestNormalComponent = 0.0f; + const PxF32 normalComponents[3] = { plane.n.x, plane.n.y, plane.n.z }; + for (PxU32 k = 0; k < 3; k++) + { + if (PxAbs(normalComponents[k]) > largestNormalComponent) + { + largestNormalComponent = PxAbs(normalComponents[k]); + largestNormalComponentAxis = k; + } + } + PxVec3 pointInPlane(PxZero); + switch (largestNormalComponentAxis) + { + case 0: + pointInPlane.x = -plane.d / plane.n.x; + break; + case 1: + pointInPlane.y = -plane.d / plane.n.y; + break; + case 2: + pointInPlane.z = -plane.d / plane.n.z; + break; + default: + break; + } + roadGeometryStates[wheelId].plane.d = -plane.n.dot(pointInPlane - shift); + } + } +} + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleLimits.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleLimits.h new file mode 100644 index 000000000..96be3e50c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleLimits.h @@ -0,0 +1,53 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxPreprocessor.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif +struct PxVehicleLimits +{ + enum Enum + { + eMAX_NB_WHEELS = 20, + eMAX_NB_AXLES = eMAX_NB_WHEELS + }; +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleMaths.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleMaths.h new file mode 100644 index 000000000..9958220ae --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleMaths.h @@ -0,0 +1,233 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxMemory.h" + +#include "PxVehicleLimits.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +class PxVehicleVectorN +{ +public: + enum + { + eMAX_SIZE = PxVehicleLimits::eMAX_NB_WHEELS + 3 + }; + + PxVehicleVectorN(const PxU32 size) + : mSize(size) + { + PX_ASSERT(mSize <= PxVehicleVectorN::eMAX_SIZE); + PxMemZero(mValues, sizeof(PxReal)*PxVehicleVectorN::eMAX_SIZE); + } + + ~PxVehicleVectorN() + { + } + + PxVehicleVectorN(const PxVehicleVectorN& src) + { + for (PxU32 i = 0; i < src.mSize; i++) + { + mValues[i] = src.mValues[i]; + } + mSize = src.mSize; + } + + PX_FORCE_INLINE PxVehicleVectorN& operator=(const PxVehicleVectorN& src) + { + for (PxU32 i = 0; i < src.mSize; i++) + { + mValues[i] = src.mValues[i]; + } + mSize = src.mSize; + return *this; + } + + PX_FORCE_INLINE PxReal& operator[] (const PxU32 i) + { + PX_ASSERT(i < mSize); + return (mValues[i]); + } + + PX_FORCE_INLINE const PxReal& operator[] (const PxU32 i) const + { + //PX_ASSERT(i < mSize); + return (mValues[i]); + } + + PX_FORCE_INLINE PxU32 getSize() const { return mSize; } + +private: + + PxReal mValues[PxVehicleVectorN::eMAX_SIZE]; + PxU32 mSize; +}; + +class PxVehicleMatrixNN +{ +public: + + PxVehicleMatrixNN() + : mSize(0) + { + } + + PxVehicleMatrixNN(const PxU32 size) + : mSize(size) + { + PX_ASSERT(mSize <= PxVehicleVectorN::eMAX_SIZE); + PxMemZero(mValues, sizeof(PxReal)*PxVehicleVectorN::eMAX_SIZE*PxVehicleVectorN::eMAX_SIZE); + } + + PxVehicleMatrixNN(const PxVehicleMatrixNN& src) + { + for (PxU32 i = 0; i < src.mSize; i++) + { + for (PxU32 j = 0; j < src.mSize; j++) + { + mValues[i][j] = src.mValues[i][j]; + } + } + mSize = src.mSize; + } + + ~PxVehicleMatrixNN() + { + } + + PX_FORCE_INLINE PxVehicleMatrixNN& operator=(const PxVehicleMatrixNN& src) + { + for (PxU32 i = 0; i < src.mSize; i++) + { + for (PxU32 j = 0; j < src.mSize; j++) + { + mValues[i][j] = src.mValues[i][j]; + } + } + mSize = src.mSize; + return *this; + } + + PX_FORCE_INLINE PxReal get(const PxU32 i, const PxU32 j) const + { + PX_ASSERT(i < mSize); + PX_ASSERT(j < mSize); + return mValues[i][j]; + } + + PX_FORCE_INLINE void set(const PxU32 i, const PxU32 j, const PxReal val) + { + PX_ASSERT(i < mSize); + PX_ASSERT(j < mSize); + mValues[i][j] = val; + } + + PX_FORCE_INLINE PxU32 getSize() const { return mSize; } + + PX_FORCE_INLINE void setSize(const PxU32 size) + { + PX_ASSERT(size <= PxVehicleVectorN::eMAX_SIZE); + mSize = size; + } + +public: + + PxReal mValues[PxVehicleVectorN::eMAX_SIZE][PxVehicleVectorN::eMAX_SIZE]; + PxU32 mSize; +}; + + +/* + LUPQ decomposition + + Based upon "Outer Product LU with Complete Pivoting," from Matrix Computations (4th Edition), Golub and Van Loan + + Solve A*x = b using: + + MatrixNNLUSolver solver; + solver.decomposeLU(A); + solver.solve(b, x); +*/ +class PxVehicleMatrixNNLUSolver +{ +private: + + PxVehicleMatrixNN mLU; + PxU32 mP[PxVehicleVectorN::eMAX_SIZE - 1]; // Row permutation + PxU32 mQ[PxVehicleVectorN::eMAX_SIZE - 1]; // Column permutation + PxReal mDetM; + +public: + + PxVehicleMatrixNNLUSolver() {} + ~PxVehicleMatrixNNLUSolver() {} + + PxReal getDet() const { return mDetM; } + + void decomposeLU(const PxVehicleMatrixNN& A); + + //Given a matrix A and a vector b find x that satisfies Ax = b, where the matrix A is the matrix that was passed to #decomposeLU. + //Returns true if the lu decomposition indicates that the matrix has an inverse and x was successfully computed. + //Returns false if the lu decomposition resulted in zero determinant ie the matrix has no inverse and no solution exists for x. + //Returns false if the size of either b or x doesn't match the size of the matrix passed to #decomposeLU. + //If false is returned then each relevant element of x is set to zero. + bool solve(const PxVehicleVectorN& b, PxVehicleVectorN& x) const; +}; + + +class PxVehicleMatrixNGaussSeidelSolver +{ +public: + + void solve(const PxU32 maxIterations, const PxReal tolerance, const PxVehicleMatrixNN& A, const PxVehicleVectorN& b, PxVehicleVectorN& result) const; +}; + +class PxVehicleMatrix33Solver +{ +public: + + bool solve(const PxVehicleMatrixNN& A_, const PxVehicleVectorN& b_, PxVehicleVectorN& result) const; +}; + +#if !PX_DOXYGEN +} //namespace vehicle2 +} //namespace physx +#endif + + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleParams.h new file mode 100644 index 000000000..dd10e0449 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/PxVehicleParams.h @@ -0,0 +1,910 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once +#include "foundation/PxFoundation.h" +#include "foundation/PxAssert.h" +#include "foundation/PxMemory.h" +#include "foundation/PxVec3.h" +#include "foundation/PxMat33.h" + +#include "PxVehicleLimits.h" + +class OmniPvdWriter; + +#if !PX_DOXYGEN +namespace physx +{ +class PxConvexMesh; +class PxScene; +namespace vehicle2 +{ +#endif + +struct PxVehicleAxleDescription +{ + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleAxleDescription)); + } + + /** + \brief Add an axle to the vehicle by specifying the number of wheels on the axle and an array of wheel ids specifying each wheel on the axle. + \param[in] nbWheelsOnAxle is the number of wheels on the axle to be added. + \param[in] wheelIdsOnAxle is an array of wheel ids specifying all the wheels on the axle to be added. + */ + void addAxle(const PxU32 nbWheelsOnAxle, const PxU32* const wheelIdsOnAxle) + { + PX_ASSERT((nbWheels + nbWheelsOnAxle) < PxVehicleLimits::eMAX_NB_WHEELS); + PX_ASSERT(nbAxles < PxVehicleLimits::eMAX_NB_AXLES); + nbWheelsPerAxle[nbAxles] = nbWheelsOnAxle; + axleToWheelIds[nbAxles] = nbWheels; + for (PxU32 i = 0; i < nbWheelsOnAxle; i++) + { + wheelIdsInAxleOrder[nbWheels + i] = wheelIdsOnAxle[i]; + } + nbWheels += nbWheelsOnAxle; + nbAxles++; + } + + /** + \brief Return the number of axles on the vehicle. + \return The number of axles. + \see getNbWheelsOnAxle() + */ + PX_FORCE_INLINE PxU32 getNbAxles() const + { + return nbAxles; + } + + /** + \brief Return the number of wheels on the ith axle. + \param[in] i specifies the axle to be queried for its wheel count. + \return The number of wheels on the specified axle. + \see getWheelOnAxle() + */ + PX_FORCE_INLINE PxU32 getNbWheelsOnAxle(const PxU32 i) const + { + return nbWheelsPerAxle[i]; + } + + /** + \brief Return the wheel id of the jth wheel on the ith axle. + \param[in] j specifies that the wheel id to be returned is the jth wheel in the list of wheels on the specified axle. + \param[in] i specifies the axle to be queried. + \return The wheel id of the jth wheel on the ith axle. + \see getNbWheelsOnAxle() + */ + PX_FORCE_INLINE PxU32 getWheelOnAxle(const PxU32 j, const PxU32 i) const + { + return wheelIdsInAxleOrder[axleToWheelIds[i] + j]; + } + + /** + \brief Return the number of wheels on the vehicle. + \return The number of wheels. + */ + PX_FORCE_INLINE PxU32 getNbWheels() const + { + return nbWheels; + } + + /** + \brief Return the axle of a specified wheel. + \param[in] wheelId is the wheel whose axle is to be queried. + \return The axle of the specified wheel. + */ + PX_FORCE_INLINE PxU32 getAxle(const PxU32 wheelId) const + { + for (PxU32 i = 0; i < getNbAxles(); i++) + { + for (PxU32 j = 0; j < getNbWheelsOnAxle(i); j++) + { + if (getWheelOnAxle(j, i) == wheelId) + return i; + } + } + return 0xffffffff; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(nbAxles > 0, "PxVehicleAxleDescription.nbAxles must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(nbWheels > 0, "PxVehicleAxleDescription.nbWheels must be greater than zero", false); + return true; + } + + PxU32 nbAxles; //!< The number of axles on the vehicle + PxU32 nbWheelsPerAxle[PxVehicleLimits::eMAX_NB_AXLES]; //!< The number of wheels on each axle. + PxU32 axleToWheelIds[PxVehicleLimits::eMAX_NB_AXLES]; //!< The list of wheel ids for the ith axle begins at wheelIdsInAxleOrder[axleToWheelIds[i]] + + PxU32 wheelIdsInAxleOrder[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The list of all wheel ids on the vehicle. + PxU32 nbWheels; //!< The number of wheels on the vehicle. + + + PX_COMPILE_TIME_ASSERT(PxVehicleLimits::eMAX_NB_AXLES == PxVehicleLimits::eMAX_NB_WHEELS); + // It should be possible to support cases where each wheel is controlled individually and thus + // having a wheel per axle for up to the max wheel count. +}; + + +struct PxVehicleAxes +{ + enum Enum + { + ePosX = 0, //!< The +x axis + eNegX, //!< The -x axis + ePosY, //!< The +y axis + eNegY, //!< The -y axis + ePosZ, //!< The +z axis + eNegZ, //!< The -z axis + eMAX_NB_AXES + }; +}; + +struct PxVehicleFrame +{ + PxVehicleAxes::Enum lngAxis; //!< The axis defining the longitudinal (forward) direction of the vehicle. + PxVehicleAxes::Enum latAxis; //!< The axis defining the lateral (side) direction of the vehicle. + PxVehicleAxes::Enum vrtAxis; //!< The axis defining the vertical (up) direction of the vehicle. + + PX_FORCE_INLINE void setToDefault() + { + lngAxis = PxVehicleAxes::ePosX; + latAxis = PxVehicleAxes::ePosY; + vrtAxis = PxVehicleAxes::ePosZ; + } + + PX_FORCE_INLINE PxMat33 getFrame() const + { + const PxVec3 basisDirs[6] = { PxVec3(1,0,0), PxVec3(-1,0,0), PxVec3(0,1,0), PxVec3(0,-1,0), PxVec3(0,0,1), PxVec3(0,0,-1) }; + const PxMat33 mat33(basisDirs[lngAxis], basisDirs[latAxis], basisDirs[vrtAxis]); + return mat33; + } + + PX_FORCE_INLINE PxVec3 getLngAxis() const + { + const PxVec3 basisDirs[6] = { PxVec3(1,0,0), PxVec3(-1,0,0), PxVec3(0,1,0), PxVec3(0,-1,0), PxVec3(0,0,1), PxVec3(0,0,-1) }; + return basisDirs[lngAxis]; + } + + PX_FORCE_INLINE PxVec3 getLatAxis() const + { + const PxVec3 basisDirs[6] = { PxVec3(1,0,0), PxVec3(-1,0,0), PxVec3(0,1,0), PxVec3(0,-1,0), PxVec3(0,0,1), PxVec3(0,0,-1) }; + return basisDirs[latAxis]; + } + + PX_FORCE_INLINE PxVec3 getVrtAxis() const + { + const PxVec3 basisDirs[6] = { PxVec3(1,0,0), PxVec3(-1,0,0), PxVec3(0,1,0), PxVec3(0,-1,0), PxVec3(0,0,1), PxVec3(0,0,-1) }; + return basisDirs[vrtAxis]; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(lngAxis < PxVehicleAxes::eMAX_NB_AXES, "PxVehicleFrame.lngAxis is invalid", false); + PX_CHECK_AND_RETURN_VAL(latAxis < PxVehicleAxes::eMAX_NB_AXES, "PxVehicleFrame.latAxis is invalid", false); + PX_CHECK_AND_RETURN_VAL(vrtAxis < PxVehicleAxes::eMAX_NB_AXES, "PxVehicleFrame.vrtAxis is invalid", false); + const PxMat33 frame = getFrame(); + const PxQuat quat(frame); + PX_CHECK_AND_RETURN_VAL(quat.isFinite() && quat.isUnit() && quat.isSane(), "PxVehicleFrame is not a legal frame", false); + return true; + } +}; + +struct PxVehicleScale +{ + PxReal scale; //!< The length scale used for the vehicle. For example, if 1.0 is considered meters, then 100.0 would be for centimeters. + + PX_FORCE_INLINE void setToDefault() + { + scale = 1.0f; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(scale > 0.0f, "PxVehicleScale.scale must be greater than zero", false); + return true; + } +}; + +/** +\brief Helper struct to pass array type data to vehice components and functions. + +The Vehicle SDK tries to give the user a certain freedom in how the parameters and +states are stored. This helper struct presents a way to either use array of structs +or array of pointers to structs to pass data into the provided vehicle components +and functions. +*/ +template +struct PxVehicleArrayData +{ + enum DataFormat + { + eARRAY_OF_STRUCTS = 0, //!< The data is provided as an array of structs and stored in #arrayOfStructs. + eARRAY_OF_POINTERS //!< The data is provided as an array of pointers and stored in #arrayOfPointers. + }; + + /** + \brief Set the data as an array of structs. + + \param[in] data The data as an array of structs. + */ + PX_FORCE_INLINE void setData(T* data) + { + arrayOfStructs = data; + dataFormat = eARRAY_OF_STRUCTS; + } + + /** + \brief Set the data as an array of pointers. + + \param[in] data The data as an array of pointers. + */ + PX_FORCE_INLINE void setData(T*const* data) + { + arrayOfPointers = data; + dataFormat = eARRAY_OF_POINTERS; + } + + PX_FORCE_INLINE PxVehicleArrayData() + { + } + + PX_FORCE_INLINE explicit PxVehicleArrayData(T* data) + { + setData(data); + } + + PX_FORCE_INLINE explicit PxVehicleArrayData(T*const* data) + { + setData(data); + } + + /** + \brief Get the data entry at a given index. + + \param[in] index The index to retrieve the data entry for. + \return Reference to the requested data entry. + */ + PX_FORCE_INLINE T& getData(PxU32 index) + { + if (dataFormat == eARRAY_OF_STRUCTS) + return arrayOfStructs[index]; + else + return *arrayOfPointers[index]; + } + + PX_FORCE_INLINE T& operator[](PxU32 index) + { + return getData(index); + } + + /** + \brief Get the data entry at a given index. + + \param[in] index The index to retrieve the data entry for. + \return Reference to the requested data entry. + */ + PX_FORCE_INLINE const T& getData(PxU32 index) const + { + if (dataFormat == eARRAY_OF_STRUCTS) + return arrayOfStructs[index]; + else + return *arrayOfPointers[index]; + } + + PX_FORCE_INLINE const T& operator[](PxU32 index) const + { + return getData(index); + } + + /** + \brief Set as empty. + */ + PX_FORCE_INLINE void setEmpty() + { + arrayOfStructs = NULL; + } + + /** + \brief Check if declared as empty. + + \return True if empty, else false. + */ + PX_FORCE_INLINE bool isEmpty() const + { + return (arrayOfStructs == NULL); + } + + /** + \brief Get a reference to the array but read only. + + \return Read only version of the data. + */ + PX_FORCE_INLINE const PxVehicleArrayData& getConst() const + { + return reinterpret_cast&>(*this); + } + + + union + { + T* arrayOfStructs; //!< The data stored as an array of structs. + T*const* arrayOfPointers; //!< The data stored as an array of pointers. + }; + PxU8 dataFormat; +}; + +template +struct PxVehicleSizedArrayData : public PxVehicleArrayData +{ + /** + \brief Set the data as an array of structs and set the number of data entries. + + \param[in] data The data as an array of structs. + \param[in] count The number of entries in the data array. + */ + PX_FORCE_INLINE void setDataAndCount(T* data, const PxU32 count) + { + PxVehicleArrayData::setData(data); + size = count; + } + + /** + \brief Set the data as an array of pointers and set the number of data entries. + + \param[in] data The data as an array of pointers. + \param[in] count The number of entries in the data array. + */ + PX_FORCE_INLINE void setDataAndCount(T*const* data, const PxU32 count) + { + PxVehicleArrayData::setData(data); + size = count; + } + + /** + \brief Set as empty. + */ + PX_FORCE_INLINE void setEmpty() + { + PxVehicleArrayData::setEmpty(); + size = 0; + } + + /** + \brief Check if declared as empty. + + \return True if empty, else false. + */ + PX_FORCE_INLINE bool isEmpty() const + { + return ((size == 0) || PxVehicleArrayData::isEmpty()); + } + + PxU32 size; +}; + +/** +\brief Determine whether the PhysX actor associated with a vehicle is to be updated with a velocity change or an acceleration change. +A velocity change will be immediately reflected in linear and angular velocity queries against the vehicle. An acceleration change, on the other hand, +will leave the linear and angular velocities unchanged until the next PhysX scene update has applied the acceleration update to the actor's linear and +angular velocities. +\see PxVehiclePhysXActorEndComponent +\see PxVehicleWriteRigidBodyStateToPhysXActor +*/ +struct PxVehiclePhysXActorUpdateMode +{ + enum Enum + { + eAPPLY_VELOCITY = 0, + eAPPLY_ACCELERATION + }; +}; + +/** +\brief Tire slip values are computed using ratios with potential for divide-by-zero errors. PxVehicleTireSlipParams +introduces a minimum value for the denominator of each of these ratios. +*/ +struct PxVehicleTireSlipParams +{ + /** + \brief The lateral slip angle is typically computed as a function of the ratio of lateral and longitudinal speeds + of the rigid body in the tire's frame. This leads to a divide-by-zero in the event that the longitudinal speed + approaches zero. The parameter minLatSlipDenominator sets a minimum denominator for the ratio of speeds used to + compute the lateral slip angle. + \note Larger timesteps typically require larger values of minLatSlipDenominator. + + Range: (0, inf)
+ Unit: velocity = length / time + */ + PxReal minLatSlipDenominator; + + /** + \brief The longitudinal slip represents the difference between the longitudinal speed of the rigid body in the tire's + frame and the linear speed arising from the rotation of the wheel. This is typically normalized using the reciprocal + of the longitudinal speed of the rigid body in the tire's frame. This leads to a divide-by-zero in the event that the + longitudinal speed approaches zero. The parameter minPassiveLongSlipDenominator sets a minimum denominator for the normalized + longitudinal slip when the wheel experiences zero drive torque and zero brake torque and zero handbrake torque. The aim is + to bring the vehicle to rest without experiencing wheel rotational speeds that oscillate around zero. + \note The vehicle will come to rest more smoothly with larger values of minPassiveLongSlipDenominator, particularly + with large timesteps that often lead to oscillation in wheel rotation speeds when the wheel rotation speed approaches + zero. + \note It is recommended that minActiveLongSlipDenominator < minPassiveLongSlipDenominator. + + Range: (0, inf)
+ Unit: velocity = length / time + */ + PxReal minPassiveLongSlipDenominator; + + /** + \brief The longitudinal slip represents the difference between the longitudinal speed of the rigid body in the tire's + frame and the linear speed arising from the rotation of the wheel. This is typically normalized using the reciprocal + of the longitudinal speed of the rigid body in the tire's frame. This leads to a divide-by-zero in the event that the + longitudinal speed approaches zero. The parameter minActiveLongSlipDenominator sets a minimum denominator for the normalized + longitudinal slip when the wheel experiences either a non-zero drive torque or a non-zero brake torque or a non-zero handbrake + torque. + \note Larger timesteps typically require larger values of minActiveLongSlipDenominator to avoid instabilities occurring when + the vehicle is aggressively throttled from rest. + \note It is recommended that minActiveLongSlipDenominator < minPassiveLongSlipDenominator. + + Range: (0, inf)
+ Unit: velocity = length / time + */ + PxReal minActiveLongSlipDenominator; + + PX_FORCE_INLINE void setToDefault() + { + minLatSlipDenominator = 1.0f; + minActiveLongSlipDenominator = 0.1f; + minPassiveLongSlipDenominator = 4.0f; + } + + PX_FORCE_INLINE PxVehicleTireSlipParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleTireSlipParams p = *this; + const PxReal scaleRatio = trgScale.scale / srcScale.scale; + p.minLatSlipDenominator *= scaleRatio; + p.minPassiveLongSlipDenominator *= scaleRatio; + p.minActiveLongSlipDenominator *= scaleRatio; + return p; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(minLatSlipDenominator > 0.0f, "PxVehicleTireSlipParams.minLatSlipDenominator must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(minPassiveLongSlipDenominator > 0.0f, "PxVehicleTireSlipParams.minPassiveLongSlipDenominator must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(minActiveLongSlipDenominator > 0.0f, "PxVehicleTireSlipParams.minActiveLongSlipDenominator must be greater than zero", false); + return true; + } +}; + +/** +\brief Tires have two important directions for the purposes of tire force computation: longitudinal and lateral. +*/ +struct PxVehicleTireDirectionModes +{ + enum Enum + { + eLONGITUDINAL = 0, + eLATERAL, + eMAX_NB_PLANAR_DIRECTIONS + }; +}; + +/** +\brief The low speed regime often presents numerical difficulties for the tire model due to the potential for divide-by-zero errors. +This particularly affects scenarios where the vehicle is slowing down due to damping and drag. In scenarios where there is no +significant brake or drive torque, numerical error begins to dominate and it can be difficult to bring the vehicle to rest. A solution +to this problem is to recognise that the vehicle is close to rest and to replace the tire forces with velocity constraints that will +bring the vehicle to rest. This regime is known as the "sticky tire" regime. PxVehicleTireAxisStickyParams describes velocity and time +thresholds that categorise the "sticky tire" regime. It also describes the rate at which the velocity constraints approach zero speed. +*/ +struct PxVehicleTireAxisStickyParams +{ + /** + \brief A tire enters the "sticky tire" regime when it has been below a speed specified by #thresholdSpeed for a continuous time + specified by #thresholdTime. + + Range: [0, inf)
+ Unit: velocity = length / time + */ + PxReal thresholdSpeed; + + /** + \brief A tire enters the "sticky tire" regime when it has been below a speed specified by #thresholdSpeed for a continuous time + specified by #thresholdTime. + + Range: [0, inf)
+ Unit: time + */ + PxReal thresholdTime; + + /** + \brief The rate at which the velocity constraint approaches zero is controlled by the damping parameter. + \note Larger values of damping lead to faster approaches to zero. Since the damping behaves like a + stiffness with respect to the velocity, too large a value can lead to instabilities. + + Range: [0, inf)
+ Unit: 1 / time (acceleration instead of force based damping, thus not mass/time) + */ + PxReal damping; + + + PX_FORCE_INLINE PxVehicleTireAxisStickyParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleTireAxisStickyParams p = *this; + const PxReal scaleRatio = trgScale.scale / srcScale.scale; + p.thresholdSpeed *= scaleRatio; + return p; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(thresholdSpeed >= 0.0f, "PxVehicleTireAxisStickyParams.thresholdSpeed must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(thresholdTime >= 0.0f, "PxVehicleTireAxisStickyParams.thresholdTime must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(damping >= 0.0f, "PxVehicleTireAxisStickyParams.damping must be greater than or equal to zero", false); + return true; + } +}; + +/** +\brief For each tire, the forces of the tire model may be replaced by velocity constraints when the tire enters the "sticky tire" +regime. The "sticky tire" regime of the lateral and longitudinal directions of the tire are managed separately. +*/ +struct PxVehicleTireStickyParams +{ + /** + The "sticky tire" regime of the lateral and longitudinal directions of the tire are managed separately and are individually + parameterized. + */ + PxVehicleTireAxisStickyParams stickyParams[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + PX_FORCE_INLINE void setToDefault() + { + stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].thresholdSpeed = 0.2f; + stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].thresholdTime = 1.0f; + stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].damping = 1.0f; + stickyParams[PxVehicleTireDirectionModes::eLATERAL].thresholdSpeed = 0.2f; + stickyParams[PxVehicleTireDirectionModes::eLATERAL].thresholdTime = 1.0f; + stickyParams[PxVehicleTireDirectionModes::eLATERAL].damping = 0.1f; + } + + PX_FORCE_INLINE PxVehicleTireStickyParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PxVehicleTireStickyParams p = *this; + p.stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL] = + stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); + p.stickyParams[PxVehicleTireDirectionModes::eLATERAL] = + stickyParams[PxVehicleTireDirectionModes::eLATERAL].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); + return p; + } + + PX_FORCE_INLINE bool isValid() const + { + if (!stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].isValid()) + return false; + if (!stickyParams[PxVehicleTireDirectionModes::eLATERAL].isValid()) + return false; + return true; + } +}; + +struct PxVehicleSimulationContextType +{ + enum Enum + { + eDEFAULT, //!< The simulation context inherits from PxVehicleSimulationContext + ePHYSX //!< The simulation context inherits from PxVehiclePhysXSimulationContext + }; +}; + +/** +\brief Structure to support Omni PVD, the PhysX Visual Debugger. +*/ +struct PxVehiclePvdContext +{ +public: + PX_FORCE_INLINE void setToDefault() + { + attributeHandles = NULL; + writer = NULL; + } + + + /** + \brief The attribute handles used to reflect vehicle parameter and state data in omnipvd. + \note A null value will result in no values being reflected in omnipvd. + \note #attributeHandles and #writer both need to be non-NULL to reflect vehicle values in omnipvd. + \see PxVehiclePvdAttributesCreate + \see PxVehiclePvdAttributesRelease + \see PxVehiclePVDComponent + */ + const struct PxVehiclePvdAttributeHandles* attributeHandles; + + /** + \brief An instance of OmniPvdWriter used to write vehicle prameter and state data to omnipvd. + \note A null value will result in no values being reflected in omnipvd. + \note #attributeHandles and #writer both need to be non-NULL to reflect vehicle values in omnipvd. + \see PxVehiclePvdAttributesCreate + \see PxVehiclePvdAttributesRelease + \see PxVehiclePVDComponent + */ + OmniPvdWriter* writer; +}; + +struct PxVehicleSimulationContext +{ + PxVehicleSimulationContext() + : type(PxVehicleSimulationContextType::eDEFAULT) + {} + + PxVec3 gravity; + + PxVehicleFrame frame; + PxVehicleScale scale; + + //Tire + PxVehicleTireSlipParams tireSlipParams; + PxVehicleTireStickyParams tireStickyParams; + + /** + \brief Forward wheel speed below which the wheel rotation speed gets blended with the rolling speed. + + The blended rotation speed is used to integrate the wheel rotation angle. At low forward wheel speed, + the wheel rotation speed can get unstable (depending on the tire model used) and, for example, oscillate. + + \note If brake or throttle is applied, there will be no blending. + + Unit: velocity = length / time + */ + PxReal thresholdForwardSpeedForWheelAngleIntegration; + + /** + \brief Structure to support Omni PVD, the PhysX Visual Debugger. + */ + PxVehiclePvdContext pvdContext; + +protected: + PxVehicleSimulationContextType::Enum type; + + +public: + PX_FORCE_INLINE PxVehicleSimulationContextType::Enum getType() const { return type; } + + PX_FORCE_INLINE void setToDefault() + { + frame.setToDefault(); + scale.setToDefault(); + + gravity = frame.getVrtAxis() * (-9.81f * scale.scale); + + tireSlipParams.setToDefault(); + tireStickyParams.setToDefault(); + + thresholdForwardSpeedForWheelAngleIntegration = 5.0f * scale.scale; + + pvdContext.setToDefault(); + } + + PX_FORCE_INLINE PxVehicleSimulationContext transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PxVehicleSimulationContext c = *this; + const PxReal scaleRatio = trgScale.scale / srcScale.scale; + c.gravity = trgFrame.getFrame()*srcFrame.getFrame().getTranspose()*c.gravity; + c.gravity *= scaleRatio; + c.tireSlipParams = tireSlipParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); + c.tireStickyParams = tireStickyParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); + c.thresholdForwardSpeedForWheelAngleIntegration *= scaleRatio; + c.frame = trgFrame; + c.scale = trgScale; + return c; + } +}; + +struct PxVehiclePhysXSimulationContext : public PxVehicleSimulationContext +{ + PxVehiclePhysXSimulationContext() + : PxVehicleSimulationContext() + { + type = PxVehicleSimulationContextType::ePHYSX; + } + + //Road geometry queries to find the plane under the wheel. + const PxConvexMesh* physxUnitCylinderSweepMesh; + const PxScene* physxScene; + + //PhysX actor update + PxVehiclePhysXActorUpdateMode::Enum physxActorUpdateMode; + + /** + \brief Wake counter value to set on the physx actor if a reset is required. + + Certain vehicle states should keep a physx actor of a vehicle awake. This + will be achieved by resetting the wake counter value if needed. The wake + counter value is the minimum simulation time that a physx actor will stay + awake. + + Unit: time + + \see physxActorWakeCounterThreshold PxVehiclePhysxActorKeepAwakeCheck + */ + PxReal physxActorWakeCounterResetValue; + + /** + \brief Threshold below which to check whether the physx actor wake counter + should get reset. + + Unit: time + + \see physxActorWakeCounterResetValue PxVehiclePhysxActorKeepAwakeCheck + */ + PxReal physxActorWakeCounterThreshold; + + + PX_FORCE_INLINE void setToDefault() + { + PxVehicleSimulationContext::setToDefault(); + + physxUnitCylinderSweepMesh = NULL; + physxScene = NULL; + + physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_VELOCITY; + + physxActorWakeCounterResetValue = 20.0f * 0.02f; // 20 timesteps of size 0.02 + physxActorWakeCounterThreshold = 0.5f * physxActorWakeCounterResetValue; + } + + PX_FORCE_INLINE PxVehiclePhysXSimulationContext transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PxVehiclePhysXSimulationContext r = *this; + static_cast(r) = PxVehicleSimulationContext::transformAndScale(srcFrame, trgFrame, srcScale, trgScale); + return r; + } +}; + +/** +* \brief Express a function as a sequence of points {(x, y)} that form a piecewise polynomial. +*/ +template +class PxVehicleFixedSizeLookupTable +{ +public: + + PxVehicleFixedSizeLookupTable() + : nbDataPairs(0) + { + } + + PxVehicleFixedSizeLookupTable(const PxVehicleFixedSizeLookupTable& src) + { + PxMemCopy(xVals, src.xVals, sizeof(PxReal)* src.nbDataPairs); + PxMemCopy(yVals, src.yVals, sizeof(T)*src.nbDataPairs); + nbDataPairs = src.nbDataPairs; + } + + ~PxVehicleFixedSizeLookupTable() + { + } + + PxVehicleFixedSizeLookupTable& operator=(const PxVehicleFixedSizeLookupTable& src) + { + PxMemCopy(xVals, src.xVals, sizeof(PxReal)*src.nbDataPairs); + PxMemCopy(yVals, src.yVals, sizeof(T)*src.nbDataPairs); + nbDataPairs = src.nbDataPairs; + return *this; + } + + /** + \brief Add one more point to create one more polynomial segment of a piecewise polynomial. + */ + PX_FORCE_INLINE bool addPair(const PxReal x, const T y) + { + PX_CHECK_AND_RETURN_VAL(nbDataPairs < NB_ELEMENTS, "PxVehicleFixedSizeLookupTable::addPair() exceeded fixed size capacity", false); + xVals[nbDataPairs] = x; + yVals[nbDataPairs] = y; + nbDataPairs++; + return true; + } + + /** + \brief Identify the segment of the piecewise polynomial that includes x and compute the corresponding y value by linearly interpolating the gradient of the segment. + \param[in] x is the value on the x-axis of the piecewise polynomial. + \return Returns the y value that corresponds to the input x. + */ + PX_FORCE_INLINE T interpolate(const PxReal x) const + { + if (0 == nbDataPairs) + { + return T(0); + } + + if (1 == nbDataPairs || x < xVals[0]) + { + return yVals[0]; + } + + PxReal x0 = xVals[0]; + T y0 = yVals[0]; + + for (PxU32 i = 1; i < nbDataPairs; i++) + { + const PxReal x1 = xVals[i]; + const T y1 = yVals[i]; + + if ((x >= x0) && (x < x1)) + { + return (y0 + (y1 - y0) * (x - x0) / (x1 - x0)); + } + + x0 = x1; + y0 = y1; + } + + PX_ASSERT(x >= xVals[nbDataPairs - 1]); + return yVals[nbDataPairs - 1]; + } + + void clear() + { + PxMemSet(xVals, 0, NB_ELEMENTS * sizeof(PxReal)); + PxMemSet(yVals, 0, NB_ELEMENTS * sizeof(T)); + nbDataPairs = 0; + } + + PxReal xVals[NB_ELEMENTS]; + T yVals[NB_ELEMENTS]; + PxU32 nbDataPairs; + + PX_FORCE_INLINE bool isValid() const + { + for (PxU32 i = 1; i < nbDataPairs; i++) + { + PX_CHECK_AND_RETURN_VAL(xVals[i] > xVals[i - 1], "PxVehicleFixedSizeLookupTable:: xVals[i+1] must be greater than xVals[i]", false); + } + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/braking/PxVehicleBrakingFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/braking/PxVehicleBrakingFunctions.h new file mode 100644 index 000000000..ebf7afe8e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/braking/PxVehicleBrakingFunctions.h @@ -0,0 +1,75 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxMath.h" +#include "PxVehicleBrakingParams.h" +#include "../commands/PxVehicleCommandStates.h" +#include "../commands/PxVehicleCommandHelpers.h" +#include "../drivetrain/PxVehicleDrivetrainParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Compute the brake torque response to an array of brake commands. +\param[in] brakeCommands is the array of input brake commands to be applied to the vehicle. +\param[in] nbBrakeCommands is the number of input brake commands to be applied to the vehicle. +\param[in] longitudinalSpeed is the longitudinal speed of the vehicle. +\param[in] wheelId specifies the wheel that is to have its brake response computed. +\param[in] brakeResponseParams specifies the per wheel brake torque response to each brake command as a nonlinear function of brake command and longitudinal speed. +\param[out] brakeResponseState is the brake torque response to the input brake command. +\note commands.brakes[i] and brakeResponseParams[i] are treated as pairs of brake command and brake command response. +*/ +PX_FORCE_INLINE void PxVehicleBrakeCommandResponseUpdate +(const PxReal* brakeCommands, const PxU32 nbBrakeCommands, const PxReal longitudinalSpeed, + const PxU32 wheelId, const PxVehicleSizedArrayData& brakeResponseParams, + PxReal& brakeResponseState) +{ + PX_CHECK_AND_RETURN(nbBrakeCommands <= brakeResponseParams.size, "PxVehicleBrakeCommandLinearUpdate: nbBrakes must be less than or equal to brakeResponseParams.size"); + PxReal sum = 0.0f; + for (PxU32 i = 0; i < nbBrakeCommands; i++) + { + sum += PxVehicleNonLinearResponseCompute(brakeCommands[i], longitudinalSpeed, wheelId, brakeResponseParams[i]); + } + brakeResponseState = sum; +} + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/braking/PxVehicleBrakingParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/braking/PxVehicleBrakingParams.h new file mode 100644 index 000000000..44a949b4b --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/braking/PxVehicleBrakingParams.h @@ -0,0 +1,82 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" + +#include "vehicle2/PxVehicleParams.h" + +#include "vehicle2/commands/PxVehicleCommandParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Distribute a brake response to the wheels of a vehicle. +\note The brake torque of each wheel on the ith wheel is brakeCommand * maxResponse * wheelResponseMultipliers[i]. +\note A typical use case is to set maxResponse to be the vehicle's maximum achievable brake torque +that occurs when the brake command is equal to 1.0. The array wheelResponseMultipliers[i] would then be used +to specify the maximum achievable brake torque per wheel as a fractional multiplier of the vehicle's maximum achievable brake torque. +*/ +struct PxVehicleBrakeCommandResponseParams : public PxVehicleCommandResponseParams +{ + PX_FORCE_INLINE PxVehicleBrakeCommandResponseParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleBrakeCommandResponseParams r = *this; + const PxReal scale = trgScale.scale/srcScale.scale; + r.maxResponse *= (scale*scale); //maxResponse is a torque! + return r; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + if (!axleDesc.isValid()) + return false; + PX_CHECK_AND_RETURN_VAL(maxResponse >= 0.0f, "PxVehicleBrakeCommandResponseParams.maxResponse must be greater than or equal to zero", false); + for (PxU32 i = 0; i < axleDesc.nbWheels; i++) + { + PX_CHECK_AND_RETURN_VAL(wheelResponseMultipliers[axleDesc.wheelIdsInAxleOrder[i]] >= 0.0f, "PxVehicleBrakeCommandResponseParams.wheelResponseMultipliers[i] must be greater than or equal to zero.", false); + } + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandHelpers.h new file mode 100644 index 000000000..eea1af908 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandHelpers.h @@ -0,0 +1,72 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleParams.h" +#include "PxVehicleCommandParams.h" +#include "PxVehicleCommandStates.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Compute the linear response to a command. +\param[in] command is a normalised command value. +\param[in] wheelId specifies the wheel that is to respond to the command. +\param[in] responseParams specifies the wheel responses for all wheels on a vehicle. +\return The linear response of the specified wheel to the command. +*/ +PX_FORCE_INLINE PxReal PxVehicleLinearResponseCompute +(const PxReal command, const PxU32 wheelId, const PxVehicleCommandResponseParams& responseParams) +{ + return command*responseParams.maxResponse*responseParams.wheelResponseMultipliers[wheelId]; +} + +/** +\brief Compute the non-linear response to a command. +\param[in] command is a normalised command value. +\param[in] longitudinalSpeed is the longitudional speed of the vehicle. +\param[in] wheelId specifies the wheel that is to respond to the command. +\param[in] responseParams specifies the wheel responses for all wheels on a vehicle. +\note responseParams is used to compute an interpolated normalized response to the combination of command and longitudinalSpeed. +The interpolated normalized response is then used in place of the command as input to PxVehicleComputeLinearResponse(). +*/ +PxReal PxVehicleNonLinearResponseCompute +(const PxReal command, const PxReal longitudinalSpeed, const PxU32 wheelId, const PxVehicleCommandResponseParams& responseParams); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandParams.h new file mode 100644 index 000000000..ec3fee01e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandParams.h @@ -0,0 +1,198 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" +#include "vehicle2/PxVehicleLimits.h" +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + + + +/** +\brief Each command value may be associated with a table specifying a normalized response as a function of longitudinal speed. +Multiple instances of PxVehicleCommandValueResponseTable allow a normalized response to be authored as a multi-variate +piecewise polynomial with normalized command response expressed as a nonlinear function of command value and speed. +*/ +struct PxVehicleCommandValueResponseTable +{ + enum Enum + { + eMAX_NB_SPEED_RESPONSES = 64 + }; + + /** + \brief The command value associated with the table of speed responses. + */ + PxReal commandValue; + + /** + \brief A lookup table specifying the normalised response to the specified command value as a function of longitudinal speed. + \note Each entry in the speedResponses table must be of the form (speed, normalizedResponse). + \note The longitudinal speeds in the table must form a strictly increasing series. + \note The normalized responses must be in range [0, 1]. + */ + PxVehicleFixedSizeLookupTable speedResponses; +}; + +/** +\note Brake, drive and steer response typically reduce at increased longitudinal speed. Moreover, response to a brake, throttle or steer command is typically +nonlinear and may be subject to dead zones where response is constant with either zero or non-zero response. PxVehicleCommandNonLinearResponseParams allows +command responses to be authored as multi-variate piecewise polynomials with normalized command response a function of command value and longitudinal speed. +*/ +class PxVehicleCommandNonLinearResponseParams +{ +public: + + enum Enum + { + eMAX_NB_COMMAND_VALUES = 8 + }; + + PxVehicleCommandNonLinearResponseParams() + : nbSpeedResponses(0), + nbCommandValues(0) + { + } + + void clear() + { + nbCommandValues = 0; + nbSpeedResponses = 0; + } + + /** + \brief Add a table of normalised response vs speed and associated it with a specified command value. + \note commandValueSpeedResponses must be authored as a series of strictly increasing speeds with form {speed, normalizedResponse} + \note The responses added must form a series of strictly increasing command values. + */ + bool addResponse(const PxVehicleCommandValueResponseTable& commandValueSpeedResponses) + { + const PxReal commandValue = commandValueSpeedResponses.commandValue; + const PxReal* speeds = commandValueSpeedResponses.speedResponses.xVals; + const PxReal* responses = commandValueSpeedResponses.speedResponses.yVals; + const PxU16 nb = PxU16(commandValueSpeedResponses.speedResponses.nbDataPairs); + + PX_CHECK_AND_RETURN_VAL(commandValue >= 0.0f && commandValue <= 1.0f, "PxVehicleCommandAndResponseTable::commandValue must be in range [0, 1]", false); + + PX_CHECK_AND_RETURN_VAL(nbCommandValues < eMAX_NB_COMMAND_VALUES, "PxVehicleNonLinearCommandResponse::addResponse - exceeded maximum number of command responses", false); + + PX_CHECK_AND_RETURN_VAL(((nbSpeedResponses + nb) <= PxVehicleCommandValueResponseTable::eMAX_NB_SPEED_RESPONSES), "PxVehicleNonLinearCommandResponse::addResponse - exceeded maximum number of command responses", false); + + PX_CHECK_AND_RETURN_VAL((0 == nbCommandValues) || (commandValue > commandValues[nbCommandValues - 1]), "PxVehicleNonLinearCommandResponse::addResponse - command must be part of a strictly increasing series", false); + + PX_CHECK_AND_RETURN_VAL(nb > 0, "PxVehicleNonLinearCommandResponse::addResponse - each command response must have at least 1 point", false); + +#if PX_CHECKED + for (PxU32 i = 1; i < nb; i++) + { + PX_CHECK_AND_RETURN_VAL(speeds[i] > speeds[i - 1], "PxVehicleNonLinearCommandResponse::addResponse - speeds array must be a strictly increasing series", false); + PX_CHECK_AND_RETURN_VAL(responses[i] >= 0.0f && responses[i] <= 1.0f , "PxVehicleNonLinearCommandResponse::addResponse - response must be in range [0, 1]", false); + } +#endif + + commandValues[nbCommandValues] = commandValue; + nbSpeedResponsesPerCommandValue[nbCommandValues] = nb; + speedResponsesPerCommandValue[nbCommandValues] = nbSpeedResponses; + PxMemCopy(speedResponses + 2 * nbSpeedResponses, speeds, sizeof(PxReal)*nb); + PxMemCopy(speedResponses + 2 * nbSpeedResponses + nb, responses, sizeof(PxReal)*nb); + nbCommandValues++; + nbSpeedResponses += nb; + return true; + } + +public: + + /** + \brief A ragged array of speeds and normalized responses. + */ + PxReal speedResponses[PxVehicleCommandValueResponseTable::eMAX_NB_SPEED_RESPONSES * 2]; + + /** + \brief The number of speeds and normalized responses. + */ + PxU16 nbSpeedResponses; + + /** + \brief The table of speed responses for the ith command value begins at speedResponses[2*speedResponsesPerCommandValue[i]] + */ + PxU16 speedResponsesPerCommandValue[eMAX_NB_COMMAND_VALUES]; + + /** + \brief The ith command value has N speed responses with N = nbSpeedRenponsesPerCommandValue[i]. + */ + PxU16 nbSpeedResponsesPerCommandValue[eMAX_NB_COMMAND_VALUES]; + + /** + \brief The command values. + */ + PxReal commandValues[eMAX_NB_COMMAND_VALUES]; + + /** + \brief The number of command values. + */ + PxU16 nbCommandValues; +}; + +/** +\brief A description of the per wheel response to an input command. +*/ +struct PxVehicleCommandResponseParams +{ + /** + \brief A nonlinear response to command value expressed as a lookup table of normalized response as a function of command value and longitudinal speed. + \note The effect of the default state of nonlinearResponse is a linear response to command value that is independent of longitudinal speed. + */ + PxVehicleCommandNonLinearResponseParams nonlinearResponse; + + /** + \brief A description of the per wheel response multiplier to an input command. + */ + PxReal wheelResponseMultipliers[PxVehicleLimits::eMAX_NB_WHEELS]; + + /** + \brief The maximum response that occurs when the wheel response multiplier has value 1.0 and nonlinearResponse is in the default state of linear response. + */ + PxF32 maxResponse; +}; + + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandStates.h new file mode 100644 index 000000000..9fc690ee9 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/commands/PxVehicleCommandStates.h @@ -0,0 +1,136 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxMemory.h" +#include "vehicle2/PxVehicleLimits.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + + +/** +\brief A description of the state of commands that are applied to the vehicle +\note brakes[0] and brakes[1] may be used to distinguish brake and handbrake controls. +*/ +struct PxVehicleCommandState +{ + PxReal brakes[2]; //!< The instantaneous state of the brake controllers in range [0,1] with 1 denoting fully pressed and 0 fully depressed. + PxU32 nbBrakes; //|< The number of brake commands. + PxReal throttle; //!< The instantaneous state of the throttle controller in range [0,1] with 1 denoting fully pressed and 0 fully depressed. + PxReal steer; //!< The instantaneous state of the steer controller in range [-1,1]. + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleCommandState)); + } +}; + +/** +\brief A description of the state of transmission-related commands that are applied to a vehicle with direct drive. +*/ +struct PxVehicleDirectDriveTransmissionCommandState +{ + /** + \brief Direct drive vehicles only have reverse, neutral or forward gear. + */ + enum Enum + { + eREVERSE = 0, + eNEUTRAL, + eFORWARD + }; + + Enum gear; //!< The desired gear of the input gear controller. + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleDirectDriveTransmissionCommandState)); + } +}; + +/** +\brief A description of the state of transmission-related commands that are applied to a vehicle with engine drive. +*/ +struct PxVehicleEngineDriveTransmissionCommandState +{ + enum Enum + { + /** + \brief Special gear value to denote the automatic shift mode (often referred to as DRIVE). + + When using automatic transmission, setting this value as target gear will enable automatic + gear shifts between first and highest gear. If the current gear is a reverse gear or + the neutral gear, then this value will trigger a shift to first gear. If this value is + used even though there is no automatic transmission available, the gear state will remain + unchanged. + */ + eAUTOMATIC_GEAR = 0xff + }; + + PxReal clutch; //!< The instantaneous state of the clutch controller in range [0,1] with 1 denoting fully pressed and 0 fully depressed. + PxU32 targetGear; //!< The desired gear of the input gear controller. + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleEngineDriveTransmissionCommandState)); + } +}; + +/** +\brief A description of the state of transmission-related commands that are applied to a vehicle with tank drive. +*/ +struct PxVehicleTankDriveTransmissionCommandState : public PxVehicleEngineDriveTransmissionCommandState +{ + /** + \brief The wheels of each tank track are either all connected to thrusts[0] or all connected to thrusts[1]. + \note The thrust commands are used to divert torque from the engine to the wheels of the tank tracks controlled by each thrust. + \note thrusts[0] and thrusts[1] are in range [-1,1] with the sign dictating whether the thrust will be applied positively or negatively with respect to the gearing ratio. + */ + PxReal thrusts[2]; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTankDriveTransmissionCommandState)); + } +}; + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainComponents.h new file mode 100644 index 000000000..de4224f81 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainComponents.h @@ -0,0 +1,798 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleFunctions.h" +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "vehicle2/braking/PxVehicleBrakingFunctions.h" +#include "vehicle2/commands/PxVehicleCommandHelpers.h" +#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h" +#include "vehicle2/steering/PxVehicleSteeringFunctions.h" +#include "vehicle2/steering/PxVehicleSteeringParams.h" +#include "vehicle2/wheel/PxVehicleWheelStates.h" +#include "vehicle2/wheel/PxVehicleWheelParams.h" +#include "vehicle2/tire/PxVehicleTireStates.h" + +#include "PxVehicleDrivetrainStates.h" +#include "PxVehicleDrivetrainFunctions.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleBrakeCommandResponseParams; +struct PxVehicleDirectDriveThrottleCommandResponseParams; + +/** +\brief Forward the applicable set of control values for a direct drive vehicle to a command response state for each +applicable control value. +\note The applicable control values are brake, handbrake, throttle and steer. +\see PxVehicleDirectDriveActuationStateComponent +\see PxVehicleDirectDrivetrainComponent +\see PxVehicleBrakeCommandLinearUpdate +\see PxVehicleDirectDriveThrottleLinearCommandUpdate +\see PxVehicleSteerCommandLinearUpdate +\see PxVehicleAckermannSteerUpdate +*/ +class PxVehicleDirectDriveCommandResponseComponent : public PxVehicleComponent +{ +public: + + PxVehicleDirectDriveCommandResponseComponent() : PxVehicleComponent() {} + virtual ~PxVehicleDirectDriveCommandResponseComponent() {} + + /** + \brief Provide vehicle data items for this component. + + \param[out] axleDescription identifies the wheels on each axle. + \param[out] brakeResponseParams An array of brake response parameters with a brake response for each brake command. + \param[out] throttleResponseParams The throttle response parameters. + \param[out] steerResponseParams The steer response parameters. + \param[out] ackermannParams The parameters defining Ackermann steering. NULL if no Ackermann steering is desired. + \param[out] commands The throttle, brake, steer etc. command states. + \param[out] transmissionCommands The transmission command state describing the current gear. + \param[out] rigidBodyState The state of the vehicle's rigid body. + \param[out] brakeResponseStates The resulting brake response states given the command input and brake response parameters. + \param[out] throttleResponseStates The resulting throttle response states given the command input and throttle response parameters. + \param[out] steerResponseStates The resulting steer response states given the command input, steer response and (optionally) Ackermann parameters. + */ + virtual void getDataForDirectDriveCommandResponseComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleSizedArrayData& brakeResponseParams, + const PxVehicleDirectDriveThrottleCommandResponseParams*& throttleResponseParams, + const PxVehicleSteerCommandResponseParams*& steerResponseParams, + PxVehicleSizedArrayData& ackermannParams, + const PxVehicleCommandState*& commands, const PxVehicleDirectDriveTransmissionCommandState*& transmissionCommands, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& brakeResponseStates, + PxVehicleArrayData& throttleResponseStates, + PxVehicleArrayData& steerResponseStates) = 0; + + /** + \brief Compute a per wheel response to the input brake/handbrake/throttle/steer commands + and determine if there is an intention to accelerate the vehicle. + */ + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleDirectDriveCommandResponseComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleSizedArrayData brakeResponseParams; + const PxVehicleDirectDriveThrottleCommandResponseParams* throttleResponseParams; + const PxVehicleSteerCommandResponseParams* steerResponseParams; + PxVehicleSizedArrayData ackermannParams; + const PxVehicleCommandState* commands; + const PxVehicleDirectDriveTransmissionCommandState* transmissionCommands; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData brakeResponseStates; + PxVehicleArrayData throttleResponseStates; + PxVehicleArrayData steerResponseStates; + + getDataForDirectDriveCommandResponseComponent(axleDescription, + brakeResponseParams, throttleResponseParams, steerResponseParams, ackermannParams, + commands, transmissionCommands, + rigidBodyState, + brakeResponseStates, throttleResponseStates, steerResponseStates); + + const PxReal longitudinalSpeed = rigidBodyState->getLongitudinalSpeed(context.frame); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + PxVehicleBrakeCommandResponseUpdate( + commands->brakes, commands->nbBrakes, longitudinalSpeed, + wheelId, brakeResponseParams, + brakeResponseStates[wheelId]); + + PxVehicleDirectDriveThrottleCommandResponseUpdate( + commands->throttle, *transmissionCommands, longitudinalSpeed, + wheelId, *throttleResponseParams, + throttleResponseStates[wheelId]); + + PxVehicleSteerCommandResponseUpdate( + commands->steer, longitudinalSpeed, + wheelId, *steerResponseParams, + steerResponseStates[wheelId]); + } + if (ackermannParams.size > 0) + PxVehicleAckermannSteerUpdate( + commands->steer, + *steerResponseParams, ackermannParams, + steerResponseStates); + + return true; + } +}; + + +/** +\brief Determine the actuation state for each wheel of a direct drive vehicle. +\note The actuation state for each wheel contains a binary record of whether brake and drive torque are to be applied to the wheel. +\see PxVehicleDirectDriveCommandResponseComponent +\see PxVehicleDirectDrivetrainComponent +\see PxVehicleDirectDriveActuationStateUpdate +*/ +class PxVehicleDirectDriveActuationStateComponent : public PxVehicleComponent +{ +public: + + PxVehicleDirectDriveActuationStateComponent() : PxVehicleComponent() {} + virtual ~PxVehicleDirectDriveActuationStateComponent() {} + + + /** + \brief Provide vehicle data items for this component. + + \param[out] axleDescription identifies the wheels on each axle. + \param[out] brakeResponseStates The brake response states. + \param[out] throttleResponseStates The throttle response states. + \param[out] actuationStates The actuation states. + */ + virtual void getDataForDirectDriveActuationStateComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleArrayData& brakeResponseStates, + PxVehicleArrayData& throttleResponseStates, + PxVehicleArrayData& actuationStates) = 0; + + /** + \brief Compute the actuation state for each wheel given the brake, handbrake and throttle states. + \*/ + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleDirectDriveActuationStateComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleArrayData brakeResponseStates; + PxVehicleArrayData throttleResponseStates; + PxVehicleArrayData actuationStates; + + getDataForDirectDriveActuationStateComponent( + axleDescription, + brakeResponseStates, throttleResponseStates, + actuationStates); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + PxVehicleDirectDriveActuationStateUpdate( + brakeResponseStates[wheelId], throttleResponseStates[wheelId], + actuationStates[wheelId]); + } + + return true; + } +}; + +/** +\brief Forward integrate the angular speed of each wheel on a vehicle by integrating the +brake and drive torque applied to each wheel and the torque that develops on the tire as a response +to the longitudinal tire force. +\see PxVehicleDirectDriveUpdate +*/ +class PxVehicleDirectDrivetrainComponent : public PxVehicleComponent +{ +public: + + PxVehicleDirectDrivetrainComponent() : PxVehicleComponent() {} + virtual ~PxVehicleDirectDrivetrainComponent() {} + + virtual void getDataForDirectDrivetrainComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleArrayData& brakeResponseStates, + PxVehicleArrayData& throttleResponseStates, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& actuationStates, + PxVehicleArrayData& tireForces, + PxVehicleArrayData& wheelRigidBody1dStates) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleDirectDrivetrainComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleArrayData brakeResponseStates; + PxVehicleArrayData throttleResponseStates; + PxVehicleArrayData wheelParams; + PxVehicleArrayData actuationStates; + PxVehicleArrayData tireForces; + PxVehicleArrayData wheelRigidBody1dStates; + + getDataForDirectDrivetrainComponent(axleDescription, + brakeResponseStates, throttleResponseStates, + wheelParams, actuationStates, tireForces, + wheelRigidBody1dStates); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + PxVehicleDirectDriveUpdate( + wheelParams[wheelId], actuationStates[wheelId], + brakeResponseStates[wheelId], throttleResponseStates[wheelId], + tireForces[wheelId], + dt, + wheelRigidBody1dStates[wheelId]); + } + + return true; + } +}; + +/** +\brief Forward the applicable set of control values for a vehicle driven by an engine to a command response state for each +applicable control value. + +If parameters for an autobox are provided, the autobox will determine if a gear change should begin in order to +maintain a desired engine revs. + +\see PxVehicleBrakeCommandLinearUpdate +\see PxVehicleClutchCommandResponseLinearUpdate +\see PxVehicleEngineDriveThrottleCommandResponseUpdate +\see PxVehicleSteerCommandLinearUpdate +\see PxVehicleAckermannSteerUpdate +\see PxVehicleAutoBoxUpdate +\see PxVehicleGearCommandResponseUpdate +*/ +class PxVehicleEngineDriveCommandResponseComponent : public PxVehicleComponent +{ +public: + + PxVehicleEngineDriveCommandResponseComponent() : PxVehicleComponent() {} + virtual ~PxVehicleEngineDriveCommandResponseComponent() {} + + /** + \brief Provide vehicle data items for this component. + \param[out] axleDescription identifies the wheels on each axle. + \param[out] brakeResponseParams An array of brake response parameters with a brake response for each brake command. + \param[out] steerResponseParams The steer response parameters. + \param[out] ackermannParams The parameters defining Ackermann steering. NULL if no Ackermann steering is desired. + \param[out] gearboxParams The gearbox parameters. + \param[out] clutchResponseParams The clutch response parameters. + \param[out] engineParams The engine parameters. Only needed if an autobox is provided (see autoboxParams), else it can be set to NULL. + \param[out] engineState The engine state. Only needed if an autobox is provided (see autoboxParams), else it can be set to NULL. + \param[out] autoboxParams The autobox parameters. If not NULL, the autobox will determine the target gear. Requires the parameters + engineParams, engineState and autoboxState to be available. If no autobox is desired, NULL can be used in which case + the aforementioned additional parameters can be set to NULL too. + \param[out] rigidBodyState The state of the vehicle's rigid body. + \param[out] commands The throttle, brake, steer etc. command states. + \param[out] transmissionCommands The clutch, target gear etc. command states. If an autobox is provided (see autoboxParams) + and the target gear is set to PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR, then the autobox will trigger + gear shifts. + \param[out] brakeResponseStates The resulting brake response states given the command input and brake response parameters. + \param[out] throttleResponseState The resulting throttle response to the input throttle command. + \param[out] steerResponseStates The resulting steer response states given the command input, steer response and (optionally) Ackermann parameters. + \param[out] gearboxResponseState The resulting gearbox response state given the command input and gearbox parameters. + \param[out] clutchResponseState The resulting clutch state given the command input and clutch response parameters. + \param[out] autoboxState The resulting autobox state given the autobox/engine/gear params and engine state. Only needed if an autobox is + provided (see autoboxParams), else it can be set to NULL. + */ + virtual void getDataForEngineDriveCommandResponseComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleSizedArrayData& brakeResponseParams, + const PxVehicleSteerCommandResponseParams*& steerResponseParams, + PxVehicleSizedArrayData& ackermannParams, + const PxVehicleGearboxParams*& gearboxParams, + const PxVehicleClutchCommandResponseParams*& clutchResponseParams, + const PxVehicleEngineParams*& engineParams, + const PxVehicleRigidBodyState*& rigidBodyState, + const PxVehicleEngineState*& engineState, + const PxVehicleAutoboxParams*& autoboxParams, + const PxVehicleCommandState*& commands, + const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, + PxVehicleArrayData& brakeResponseStates, + PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, + PxVehicleArrayData& steerResponseStates, + PxVehicleGearboxState*& gearboxResponseState, + PxVehicleClutchCommandResponseState*& clutchResponseState, + PxVehicleAutoboxState*& autoboxState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleEngineDriveCommandResponseComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleSizedArrayData brakeResponseParams; + const PxVehicleSteerCommandResponseParams* steerResponseParams; + PxVehicleSizedArrayData ackermannParams; + const PxVehicleGearboxParams* gearboxParams; + const PxVehicleClutchCommandResponseParams* clutchResponseParams; + const PxVehicleEngineParams* engineParams; + const PxVehicleRigidBodyState* rigidBodyState; + const PxVehicleEngineState* engineState; + const PxVehicleAutoboxParams* autoboxParams; + const PxVehicleCommandState* commands; + const PxVehicleEngineDriveTransmissionCommandState* transmissionCommands; + PxVehicleArrayData brakeResponseStates; + PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState; + PxVehicleArrayData steerResponseStates; + PxVehicleGearboxState* gearboxResponseState; + PxVehicleClutchCommandResponseState* clutchResponseState; + PxVehicleAutoboxState* autoboxState; + + getDataForEngineDriveCommandResponseComponent(axleDescription, + brakeResponseParams, steerResponseParams, ackermannParams, + gearboxParams, clutchResponseParams, engineParams, rigidBodyState, + engineState, autoboxParams, + commands, transmissionCommands, + brakeResponseStates, throttleResponseState, + steerResponseStates, + gearboxResponseState, clutchResponseState, autoboxState); + + //The autobox can modify commands like throttle and target gear. Since the user defined + //values should not be overwritten, a copy is used to compute the response. + PxVehicleCommandState commandsTmp = *commands; + PxVehicleEngineDriveTransmissionCommandState transmissionCommandsTmp = *transmissionCommands; + + const PxReal longitudinalSpeed = rigidBodyState->getLongitudinalSpeed(context.frame); + + //Let the autobox set the target gear, unless the user defined target gear requests + //a shift already + if (autoboxParams) + { + PX_ASSERT(engineParams); + PX_ASSERT(engineState); + PX_ASSERT(autoboxState); + + PxVehicleAutoBoxUpdate( + *engineParams, *gearboxParams, *autoboxParams, + *engineState, *gearboxResponseState, dt, + transmissionCommandsTmp.targetGear, *autoboxState, commandsTmp.throttle); + } + else if (transmissionCommandsTmp.targetGear == PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR) + { + //If there is no autobox but eAUTOMATIC_GEAR was specified, use the current target gear + transmissionCommandsTmp.targetGear = gearboxResponseState->targetGear; + } + + //Distribute brake torque to the wheels across each axle. + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + PxVehicleBrakeCommandResponseUpdate( + commandsTmp.brakes, commandsTmp.nbBrakes, longitudinalSpeed, + wheelId, brakeResponseParams, + brakeResponseStates[i]); + } + + //Update target gear as required. + PxVehicleGearCommandResponseUpdate( + transmissionCommandsTmp.targetGear, + *gearboxParams, + *gearboxResponseState); + + //Compute the response to the clutch command. + PxVehicleClutchCommandResponseLinearUpdate( + transmissionCommandsTmp.clutch, + *clutchResponseParams, + *clutchResponseState); + + //Compute the response to the throttle command. + PxVehicleEngineDriveThrottleCommandResponseLinearUpdate( + commandsTmp, + *throttleResponseState); + + //Update the steer angles and Ackermann correction. + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + PxVehicleSteerCommandResponseUpdate(commandsTmp.steer, longitudinalSpeed, wheelId, *steerResponseParams, steerResponseStates[i]); + } + if (ackermannParams.size > 0) + PxVehicleAckermannSteerUpdate(commandsTmp.steer, *steerResponseParams, ackermannParams, steerResponseStates); + + return true; + } +}; + +/** +\brief Compute the per wheel drive torque split of a multi-wheel drive differential. +\see PxVehicleDifferentialStateUpdate +*/ +class PxVehicleMultiWheelDriveDifferentialStateComponent : public PxVehicleComponent +{ +public: + + PxVehicleMultiWheelDriveDifferentialStateComponent() : PxVehicleComponent() {} + virtual ~PxVehicleMultiWheelDriveDifferentialStateComponent() {} + + virtual void getDataForMultiWheelDriveDifferentialStateComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleMultiWheelDriveDifferentialParams*& differentialParams, + PxVehicleDifferentialState*& differentialState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleMultiWheelDriveDifferentialStateComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleMultiWheelDriveDifferentialParams* differentialParams; + PxVehicleDifferentialState* differentialState; + + getDataForMultiWheelDriveDifferentialStateComponent(axleDescription, + differentialParams, differentialState); + + PxVehicleDifferentialStateUpdate( + *axleDescription, + *differentialParams, + *differentialState); + + return true; + } +}; + +/** +\brief Compute the per wheel drive torque split of a differential delivering torque to multiple wheels +with limited slip applied to specified wheel pairs. +\see PxVehicleDifferentialStateUpdate +*/ +class PxVehicleFourWheelDriveDifferentialStateComponent : public PxVehicleComponent +{ +public: + + PxVehicleFourWheelDriveDifferentialStateComponent() : PxVehicleComponent() {} + virtual ~PxVehicleFourWheelDriveDifferentialStateComponent() {} + + virtual void getDataForFourWheelDriveDifferentialStateComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleFourWheelDriveDifferentialParams*& differentialParams, + PxVehicleArrayData& wheelRigidbody1dStates, + PxVehicleDifferentialState*& differentialState, + PxVehicleWheelConstraintGroupState*& wheelConstraintGroupState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleFourWheelDriveDifferentialStateComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleFourWheelDriveDifferentialParams* differentialParams; + PxVehicleArrayData wheelRigidbody1dStates; + PxVehicleDifferentialState* differentialState; + PxVehicleWheelConstraintGroupState* wheelConstraintGroupState; + + getDataForFourWheelDriveDifferentialStateComponent(axleDescription, differentialParams, + wheelRigidbody1dStates, + differentialState, wheelConstraintGroupState); + + PxVehicleDifferentialStateUpdate( + *axleDescription, *differentialParams, + wheelRigidbody1dStates, dt, + *differentialState, *wheelConstraintGroupState); + + return true; + } +}; + +/** +\brief Compute the per wheel drive torque split of a tank drive differential. +\see PxVehicleDifferentialStateUpdate +*/ +class PxVehicleTankDriveDifferentialStateComponent : public PxVehicleComponent +{ +public: + + PxVehicleTankDriveDifferentialStateComponent() : PxVehicleComponent() {} + virtual ~PxVehicleTankDriveDifferentialStateComponent() {} + + /** + \brief Provide vehicle data items for this component. + + \param[out] axleDescription identifies the wheels on each axle. + \param[out] transmissionCommands specifies the values of the thrust controllers that divert torque to the tank tracks. + \param[out] wheelParams is an array describing the radius of each wheel. + \param[out] differentialParams describes the operation of the tank differential by + specifying the default torque split between all wheels connected to the differential and by + specifying the wheels coupled to each tank track. + \param[out] differentialState stores the instantaneous torque split between all wheels arising from the difference between the thrust controllers. + \param[out] constraintGroupState stores the groups of wheels that are connected by sharing a tank track. + */ + virtual void getDataForTankDriveDifferentialStateComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleTankDriveTransmissionCommandState*& transmissionCommands, + PxVehicleArrayData& wheelParams, + const PxVehicleTankDriveDifferentialParams*& differentialParams, + PxVehicleDifferentialState*& differentialState, + PxVehicleWheelConstraintGroupState*& constraintGroupState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleTankDriveDifferentialStateComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleTankDriveTransmissionCommandState* transmissionCommands; + PxVehicleArrayData wheelParams; + const PxVehicleTankDriveDifferentialParams* differentialParams; + PxVehicleDifferentialState* differentialState; + PxVehicleWheelConstraintGroupState* constraintGroupState; + + getDataForTankDriveDifferentialStateComponent( + axleDescription, + transmissionCommands, + wheelParams, + differentialParams, + differentialState, constraintGroupState); + + PxVehicleDifferentialStateUpdate( + *axleDescription, + wheelParams, *differentialParams, + transmissionCommands->thrusts[0], transmissionCommands->thrusts[1], + *differentialState, *constraintGroupState); + + return true; + } +}; + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Compute the per wheel drive torque split of a four wheel drive differential. +\see PxVehicleDifferentialStateUpdate +*/ +class PX_DEPRECATED PxVehicleLegacyFourWheelDriveDifferentialStateComponent : public PxVehicleComponent +{ +public: + + PxVehicleLegacyFourWheelDriveDifferentialStateComponent() : PxVehicleComponent() {} + virtual ~PxVehicleLegacyFourWheelDriveDifferentialStateComponent() {} + + virtual void getDataForLegacyFourWheelDriveDifferentialStateComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleFourWheelDriveDifferentialLegacyParams*& differentialParams, + PxVehicleArrayData& wheelRigidbody1dStates, + PxVehicleDifferentialState*& differentialState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleLegacyFourWheelDriveDifferentialStateComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleFourWheelDriveDifferentialLegacyParams* differentialParams; + PxVehicleArrayData wheelRigidbody1dStates; + PxVehicleDifferentialState* differentialState; + + getDataForLegacyFourWheelDriveDifferentialStateComponent(axleDescription, differentialParams, + wheelRigidbody1dStates, + differentialState); + + PxVehicleDifferentialStateUpdate( + *differentialParams, wheelRigidbody1dStates, + *differentialState); + + return true; + } +}; + +/** +\brief Determine the actuation state for each wheel for a vehicle propelled by engine torque. +\note The actuation state for each wheel contains a binary record of whether brake and drive torque are to be applied to the wheel. +\see PxVehicleEngineDriveActuationStateUpdate +*/ +class PxVehicleEngineDriveActuationStateComponent : public PxVehicleComponent +{ +public: + + PxVehicleEngineDriveActuationStateComponent() : PxVehicleComponent() {} + virtual ~PxVehicleEngineDriveActuationStateComponent() {} + + virtual void getDataForEngineDriveActuationStateComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleGearboxParams*& gearboxParams, + PxVehicleArrayData& brakeResponseStates, + const PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, + const PxVehicleGearboxState*& gearboxState, + const PxVehicleDifferentialState*& differentialState, + const PxVehicleClutchCommandResponseState*& clutchResponseState, + PxVehicleArrayData& actuationStates) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleEngineDriveActuationStateComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleGearboxParams* gearboxParams; + PxVehicleArrayData brakeResponseStates; + const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState; + const PxVehicleGearboxState* gearboxState; + const PxVehicleDifferentialState* differentialState; + const PxVehicleClutchCommandResponseState* clutchResponseState; + PxVehicleArrayData actuationStates; + + getDataForEngineDriveActuationStateComponent(axleDescription, gearboxParams, + brakeResponseStates, throttleResponseState, + gearboxState, differentialState, clutchResponseState, + actuationStates); + + PxVehicleEngineDriveActuationStateUpdate( + *axleDescription, + *gearboxParams, + brakeResponseStates, + *throttleResponseState, + *gearboxState, *differentialState, *clutchResponseState, + actuationStates); + + return true; + } +}; + +/** +\brief Forward integrate the angular speed of each wheel and of the engine, accounting for the +state of the clutch, gearbox and differential. +\see PxVehicleGearboxUpdate +\see PxVehicleEngineDrivetrainUpdate +*/ +class PxVehicleEngineDrivetrainComponent : public PxVehicleComponent +{ +public: + + PxVehicleEngineDrivetrainComponent() : PxVehicleComponent() {} + virtual ~PxVehicleEngineDrivetrainComponent() {} + + /** + \brief Provide vehicle data items for this component. + + \param[out] axleDescription identifies the wheels on each axle. + \param[out] wheelParams specifies the radius of each wheel. + \param[out] engineParams specifies the engine's torque curve, idle revs and max revs. + \param[out] clutchParams specifies the maximum strength of the clutch. + \param[out] gearboxParams specifies the gear ratio of each gear. + \param[out] brakeResponseStates stores the instantaneous brake brake torque to apply to each wheel. + \param[out] actuationStates stores whether a brake and/or drive torque are to be applied to each wheel. + \param[out] tireForces stores the lateral and longitudinal tire force that has developed on each tire. + \param[out] throttleResponseState stores the response of the throttle to the input throttle command. + \param[out] clutchResponseState stores the instantaneous clutch strength that arises from the input clutch command. + \param[out] differentialState stores the instantaneous torque split between the wheels. + \param[out] constraintGroupState stores the groups of wheels that are subject to constraints that require them to have the same angular or linear velocity. + \param[out] wheelRigidBody1dStates stores the per wheel angular speed to be computed by the component. + \param[out] engineState stores the engine rotation speed to be computed by the component. + \param[out] gearboxState stores the state of the gearbox to be computed by the component. + \param[out] clutchState stores the clutch slip to be computed by the component. + \note If constraintGroupState is set to NULL it is assumed that there are no requirements for any wheels to have the same angular or linear velocity. + */ + virtual void getDataForEngineDrivetrainComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleArrayData& wheelParams, + const PxVehicleEngineParams*& engineParams, + const PxVehicleClutchParams*& clutchParams, + const PxVehicleGearboxParams*& gearboxParams, + PxVehicleArrayData& brakeResponseStates, + PxVehicleArrayData& actuationStates, + PxVehicleArrayData& tireForces, + const PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, + const PxVehicleClutchCommandResponseState*& clutchResponseState, + const PxVehicleDifferentialState*& differentialState, + const PxVehicleWheelConstraintGroupState*& constraintGroupState, + PxVehicleArrayData& wheelRigidBody1dStates, + PxVehicleEngineState*& engineState, + PxVehicleGearboxState*& gearboxState, + PxVehicleClutchSlipState*& clutchState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehicleEngineDrivetrainComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleArrayData wheelParams; + const PxVehicleEngineParams* engineParams; + const PxVehicleClutchParams* clutchParams; + const PxVehicleGearboxParams* gearboxParams; + PxVehicleArrayData brakeResponseStates; + PxVehicleArrayData actuationStates; + PxVehicleArrayData tireForces; + const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState; + const PxVehicleClutchCommandResponseState* clutchResponseState; + const PxVehicleDifferentialState* differentialState; + const PxVehicleWheelConstraintGroupState* constraintGroupState; + PxVehicleArrayData wheelRigidBody1dStates; + PxVehicleEngineState* engineState; + PxVehicleGearboxState* gearboxState; + PxVehicleClutchSlipState* clutchState; + + getDataForEngineDrivetrainComponent(axleDescription, wheelParams, + engineParams, clutchParams, gearboxParams, + brakeResponseStates, actuationStates, tireForces, + throttleResponseState, clutchResponseState, differentialState, constraintGroupState, + wheelRigidBody1dStates, engineState, gearboxState, clutchState); + + PxVehicleGearboxUpdate(*gearboxParams, dt, *gearboxState); + + PxVehicleEngineDrivetrainUpdate( + *axleDescription, + wheelParams, + *engineParams, *clutchParams, *gearboxParams, + brakeResponseStates, actuationStates, + tireForces, + *gearboxState, *throttleResponseState, *clutchResponseState, *differentialState, constraintGroupState, + dt, + wheelRigidBody1dStates, *engineState, *clutchState); + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainFunctions.h new file mode 100644 index 000000000..690f9dac0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainFunctions.h @@ -0,0 +1,314 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxSimpleTypes.h" +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleCommandState; +struct PxVehicleDirectDriveTransmissionCommandState; +struct PxVehicleEngineDriveTransmissionCommandState; +struct PxVehicleDirectDriveThrottleCommandResponseParams; +struct PxVehicleWheelActuationState; +struct PxVehicleWheelParams; +struct PxVehicleTireForce; +struct PxVehicleWheelRigidBody1dState; +struct PxVehicleEngineParams; +struct PxVehicleGearboxParams; +struct PxVehicleAutoboxParams; +struct PxVehicleEngineState; +struct PxVehicleGearboxState; +struct PxVehicleAutoboxState; +struct PxVehicleClutchCommandResponseParams; +struct PxVehicleClutchCommandResponseState; +struct PxVehicleEngineDriveThrottleCommandResponseState; +struct PxVehicleDifferentialState; +struct PxVehicleMultiWheelDriveDifferentialParams; +struct PxVehicleFourWheelDriveDifferentialParams; +struct PxVehicleTankDriveDifferentialParams; +struct PxVehicleFourWheelDriveDifferentialLegacyParams; +struct PxVehicleClutchParams; +struct PxVehicleWheelConstraintGroupState; +struct PxVehicleClutchSlipState; + +/** +\brief Compute the drive torque response to a throttle command. +\param[in] throttle is the throttle command. +\param[in] transmissionCommands is the gearing command to apply to the direct drive tranmission. +\param[in] longitudinalSpeed is the longitudinal speed of the vehicle's rigid body. +\param[in] wheelId specifies the wheel that is to have its throttle response computed. +\param[in] throttleResponseParams specifies the per wheel drive torque response to the throttle command as a nonlinear function of throttle command and longitudinal speed. +\param[out] throttleResponseState is the drive torque response to the input throttle command. +*/ +void PxVehicleDirectDriveThrottleCommandResponseUpdate +(const PxReal throttle, const PxVehicleDirectDriveTransmissionCommandState& transmissionCommands, const PxReal longitudinalSpeed, + const PxU32 wheelId, const PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams, + PxReal& throttleResponseState); + +/** +\brief Determine the actuation state of a wheel given the brake torque, handbrake torque and drive torque applied to it. +\param[in] brakeTorque is the brake torque to be applied to the wheel. +\param[in] driveTorque is the drive torque to be applied to the wheel. +\param[out] actuationState contains a binary record of whether brake or drive torque is applied to the wheel. +*/ +void PxVehicleDirectDriveActuationStateUpdate +(const PxReal brakeTorque, const PxReal driveTorque, + PxVehicleWheelActuationState& actuationState); + +/** +\brief Forward integrate the angular speed of a wheel given the brake and drive torque applied to it +\param[in] wheelParams specifies the moment of inertia of the wheel. +\param[in] actuationState is a binary record of whether brake and drive torque are to be applied to the wheel. +\param[in] brakeTorque is the brake torque to be applied to the wheel. +\param[in] driveTorque is the drive torque to be applied to the wheel. +\param[in] tireForce specifies the torque to apply to the wheel as a response to the longitudinal tire force. +\param[in] dt is the timestep of the forward integration. +\param[out] wheelRigidBody1dState describes the angular speed of the wheel. +*/ +void PxVehicleDirectDriveUpdate +(const PxVehicleWheelParams& wheelParams, + const PxVehicleWheelActuationState& actuationState, + const PxReal brakeTorque, const PxReal driveTorque, const PxVehicleTireForce& tireForce, + const PxF32 dt, + PxVehicleWheelRigidBody1dState& wheelRigidBody1dState); + +/** +\param[in] engineParams specifies the engine configuration. +\param[in] gearboxParams specifies the gear ratios and the time required to complete a gear change. +\param[in] autoboxParams specifies the conditions for switching gear. +\param[in] engineState contains the current angular speed of the engine. +\param[in] gearboxState describes the current and target gear. +\param[in] dt is the time that has lapsed since the last call to PxVehicleAutoBoxUpdate. +\param[in,out] targetGearCommand specifies the desired target gear for the gearbox. If set to + PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR, the value will get overwritten + with a target gear chosen by the autobox. +\param[out] autoboxState specifies the time that has lapsed since the last automated gear change and contains a record of +any ongoing automated gear change. +\param[out] throttle A throttle command value in [0, 1] that will be set to 0 if a gear change is initiated or is ongoing. + +\note The autobox will not begin a gear change if a gear change is already ongoing. +\note The autobox will not begin a gear change until a threshold time has lapsed since the last automated gear change. +\note A gear change is considered as ongoing for as long as PxVehicleGearboxState::currentGear is different from + PxVehicleGearboxState::targetGear. +\note The autobox will not shift down from 1st gear or up from reverse gear. +\note The autobox shifts in single gear increments or decrements. +\note The autobox instantiates a gear change by setting PxVehicleCommandState::targetGear to be different from +from PxVehicleGearboxState::currentGear +*/ +void PxVehicleAutoBoxUpdate +(const PxVehicleEngineParams& engineParams, const PxVehicleGearboxParams& gearboxParams, const PxVehicleAutoboxParams& autoboxParams, + const PxVehicleEngineState& engineState, const PxVehicleGearboxState& gearboxState, + const PxReal dt, + PxU32& targetGearCommand, PxVehicleAutoboxState& autoboxState, + PxReal& throttle); + +/** +\brief Propagate input gear commands to the gearbox state. +\param[in] targetGearCommand specifies the target gear for the gearbox. +\param[in] gearboxParams specifies the number of gears and the index of neutral gear. +\param[out] gearboxState contains a record of the current and target gear. +\note Any ongoing gear change must complete before starting another. +\note A gear change is considered as ongoing for as long as PxVehicleGearboxState::currentGear is different from + PxVehicleGearboxState::targetGear. + \note The gearbox remains in neutral for the duration of the gear change. + \note A gear change begins if PxVehicleCommandState::targetGear is different from PxVehicleGearboxState::currentGear. +*/ +void PxVehicleGearCommandResponseUpdate +(const PxU32 targetGearCommand, + const PxVehicleGearboxParams& gearboxParams, + PxVehicleGearboxState& gearboxState); + +/** +\brief Propagate the input clutch command to the clutch response state. +\param[in] clutchCommand specifies the state of the clutch pedal. +\param[in] clutchResponseParams specifies how the clutch responds to the input clutch command. +\param[out] clutchResponse specifies the response of the clutch to the input clutch command. +*/ +void PxVehicleClutchCommandResponseLinearUpdate +(const PxReal clutchCommand, + const PxVehicleClutchCommandResponseParams& clutchResponseParams, + PxVehicleClutchCommandResponseState& clutchResponse); + +/** +\brief Propagate the input throttle command to the throttle response state. +\param[in] commands specifies the state of the throttle pedal. +\param[out] throttleResponse specifies how the clutch responds to the input throttle command. +*/ +void PxVehicleEngineDriveThrottleCommandResponseLinearUpdate +(const PxVehicleCommandState& commands, + PxVehicleEngineDriveThrottleCommandResponseState& throttleResponse); + +/** +\brief Determine the actuation state of all wheels on a vehicle. +\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle. +\param[in] gearboxParams specifies the index of the neutral gear of the gearbox. +\param[in] brakeResponseStates specifies the response of each wheel to the input brake command. +\param[in] throttleResponseState specifies the response of the engine to the input throttle command. +\param[in] gearboxState specifies the current gear. +\param[in] diffState specifies the fraction of available drive torque to be delivered to each wheel. +\param[in] clutchResponseState specifies the response of the clutch to the input throttle command. +\param[out] actuationStates is an array of binary records determining whether brake and drive torque are to be applied to each wheel. +\note Drive torque is not applied to a wheel if + a) the gearbox is in neutral + b) the differential delivers no torque to the wheel + c) no throttle is applied to the engine + c) the clutch is fully disengaged. +*/ +void PxVehicleEngineDriveActuationStateUpdate +(const PxVehicleAxleDescription& axleDescription, + const PxVehicleGearboxParams& gearboxParams, + const PxVehicleArrayData& brakeResponseStates, + const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState, + const PxVehicleGearboxState& gearboxState, const PxVehicleDifferentialState& diffState, const PxVehicleClutchCommandResponseState& clutchResponseState, + PxVehicleArrayData& actuationStates); + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all +wheels connected to the differential. +\param[in] diffParams specifies the operation of a differential that can be connected to up to four wheels. +\param[in] wheelStates describes the angular speed of each wheel +\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel. +\note If the handbrake is on then torque is only delivered to the wheels specified as the front wheels of the differential. +*/ +void PX_DEPRECATED PxVehicleDifferentialStateUpdate +(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams, + const PxVehicleArrayData& wheelStates, + PxVehicleDifferentialState& diffState); + +/** +\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all +wheels connected to the differential. Additionally, add wheel constraints for wheel pairs whose +rotational speed ratio exceeds the corresponding differential bias. +\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle. +\param[in] diffParams describe the division of available drive torque and the biases of the limited +slip differential. +\param[in] wheelStates describes the rotational speeds of each wheel. +\param[in] dt is the simulation time that has passes since the last call to PxVehicleDifferentialStateUpdate() +\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel. +\param[out] wheelConstraintGroupState describes the groups of wheels that have exceeded their corresponding +differential biases. +*/ +void PxVehicleDifferentialStateUpdate +(const PxVehicleAxleDescription& axleDescription, const PxVehicleFourWheelDriveDifferentialParams& diffParams, + const PxVehicleArrayData& wheelStates, + const PxReal dt, + PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState); + +/** +\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all +wheels connected to the differential. +\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle. +\param[in] diffParams specifies the operation of a differential that can be connected to any combination of wheels. +\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel connected to the differential. +*/ +void PxVehicleDifferentialStateUpdate +(const PxVehicleAxleDescription& axleDescription, const PxVehicleMultiWheelDriveDifferentialParams& diffParams, + PxVehicleDifferentialState& diffState); + +/** +\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all +wheels connected to the differential. +\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle. +\param[in] wheelParams is an array that describes the wheel radius of each wheel. +\param[in] diffParams specifies the operation of a tank differential. +\param[in] thrustCommand0 is the state of one of the two thrust controllers. +\param[in] thrustCommand1 is the state of one of the two thrust controllers. +\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel connected to the differential. +\param[out] wheelConstraintGroupState describes the groups of wheels connected by sharing a tank track. +*/ +void PxVehicleDifferentialStateUpdate +(const PxVehicleAxleDescription& axleDescription, + const PxVehicleArrayData& wheelParams, const PxVehicleTankDriveDifferentialParams& diffParams, + const PxReal thrustCommand0, PxReal thrustCommand1, + PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState); + + +/** +\brief Update the current gear of the gearbox. If a gear change is ongoing then complete the gear change if a threshold +time has passed since the beginning of the gear change. +\param[in] gearboxParams describes the time required to complete a gear change. +\param[in] dt is the time that has lapsed since the last call to PxVehicleGearboxUpdate. +\param[out] gearboxState is the gearbox state to be updated. +\note A gear change is considered as ongoing for as long as PxVehicleGearboxState::currentGear is different from + PxVehicleGearboxState::targetGear. +*/ +void PxVehicleGearboxUpdate +(const PxVehicleGearboxParams& gearboxParams, + const PxF32 dt, + PxVehicleGearboxState& gearboxState); + +/** +\brief Forward integrate the angular speed of the vehicle's wheels and engine, given the state of clutch, differential and gearbox. +\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle. +\param[in] wheelParams specifies the moment of inertia of each wheel. +\param[in] engineParams specifies the torque curve of the engine and its moment of inertia. +\param[in] clutchParams specifies the maximum clutch strength that happens when the clutch is fully engaged. +\param[in] gearboxParams specifies the gearing ratios of the gearbox. +\param[in] brakeResponseStates describes the per wheel response to the input brake command. +\param[in] actuationStates is a binary record of whether brake or drive torque is applied to each wheel. +\param[in] tireForces describes the torque to apply to each wheel as a response to the longitudinal tire force. +\param[in] gearboxState describes the current gear. +\param[in] throttleResponse describes the engine response to the input throttle pedal. +\param[in] clutchResponse describes the clutch response to the input clutch pedal. +\param[in] diffState describes the fraction of available drive torque to be delivered to each wheel. +\param[in] constraintGroupState describes groups of wheels with rotational speed constrained to the same value. +\param[in] dt is the time that has lapsed since the last call to PxVehicleEngineDrivetrainUpdate +\param[out] wheelRigidbody1dStates describes the angular speed of each wheel. +\param[out] engineState describes the angular speed of the engine. +\param[out] clutchState describes the clutch slip. +\note If constraintGroupState is NULL then it is assumed that there are no wheels subject to rotational speed constraints. +*/ +void PxVehicleEngineDrivetrainUpdate +(const PxVehicleAxleDescription& axleDescription, + const PxVehicleArrayData& wheelParams, + const PxVehicleEngineParams& engineParams, const PxVehicleClutchParams& clutchParams, const PxVehicleGearboxParams& gearboxParams, + const PxVehicleArrayData& brakeResponseStates, + const PxVehicleArrayData& actuationStates, + const PxVehicleArrayData& tireForces, + const PxVehicleGearboxState& gearboxState, const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponse, const PxVehicleClutchCommandResponseState& clutchResponse, + const PxVehicleDifferentialState& diffState, const PxVehicleWheelConstraintGroupState* constraintGroupState, + const PxReal dt, + PxVehicleArrayData& wheelRigidbody1dStates, + PxVehicleEngineState& engineState, PxVehicleClutchSlipState& clutchState); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h new file mode 100644 index 000000000..96e583448 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h @@ -0,0 +1,156 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h" +#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleWheelRigidBody1dState; + +/** +\brief Compute the coupling strength of the clutch. +\param[in] clutchResponseState describes the response of the clutch to the input clutch command. +\param[in] gearboxParams holds the index of neutral gear. +\param[in] gearboxState describes the current gear. +\note If the gear is in neutral the clutch is fully disengaged and the clutch strength is 0. +\note A clutch response state of 0.0 denotes a fully engaged clutch with maximum strength. +\note A clutch response state of 1.0 denotes a fully disengaged clutch with a strength of 0.0. +*/ +PX_FORCE_INLINE PxReal PxVehicleClutchStrengthCompute(const PxVehicleClutchCommandResponseState& clutchResponseState, const PxVehicleGearboxParams& gearboxParams, const PxVehicleGearboxState& gearboxState) +{ + return (gearboxParams.neutralGear != gearboxState.currentGear) ? clutchResponseState.commandResponse : 0.0f; +} + +/** +\brief Compute the damping rate of the engine. +\param[in] engineParams describes various damping rates of the engine in different operational states. +\param[in] gearboxParams holds the index of neutral gear. +\param[in] gearboxState describes the current gear. +\param[in] clutchResponseState is the response of the clutch to the clutch command. +\param[in] throttleResponseState is the response of the throttle to the throttle command. +\note Engines typically have different damping rates with clutch engaged and disengaged. +\note Engines typically have different damping rates at different throttle pedal values. +\see PxVehicleClutchStrengthCompute() +\note In neutral gear the clutch is considered to be fully disengaged. +*/ +PX_FORCE_INLINE PxReal PxVehicleEngineDampingRateCompute +(const PxVehicleEngineParams& engineParams, + const PxVehicleGearboxParams& gearboxParams, const PxVehicleGearboxState& gearboxState, + const PxVehicleClutchCommandResponseState& clutchResponseState, + const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState) +{ + const PxReal K = (gearboxParams.neutralGear != gearboxState.currentGear) ? clutchResponseState.normalisedCommandResponse : 0.0f; + const PxReal zeroThrottleDamping = engineParams.dampingRateZeroThrottleClutchEngaged + + (1.0f - K)* (engineParams.dampingRateZeroThrottleClutchDisengaged - engineParams.dampingRateZeroThrottleClutchEngaged); + const PxReal appliedThrottle = throttleResponseState.commandResponse; + const PxReal fullThrottleDamping = engineParams.dampingRateFullThrottle; + const PxReal engineDamping = zeroThrottleDamping + (fullThrottleDamping - zeroThrottleDamping)*appliedThrottle; + return engineDamping; +} + +/** +\brief Compute the gear ratio delivered by the gearbox in the current gear. +\param[in] gearboxParams describes the gear ratio of each gear and the final ratio. +\param[in] gearboxState describes the current gear. +\note The gear ratio is the product of the gear ratio of the current gear and the final gear ratio of the gearbox. +*/ +PX_FORCE_INLINE PxReal PxVehicleGearRatioCompute +(const PxVehicleGearboxParams& gearboxParams, const PxVehicleGearboxState& gearboxState) +{ + const PxReal gearRatio = gearboxParams.ratios[gearboxState.currentGear] * gearboxParams.finalRatio; + return gearRatio; +} + +/** +\brief Compute the drive torque to deliver to the engine. +\param[in] engineParams describes the profile of maximum available torque across the full range of engine rotational speed. +\param[in] engineState describes the engine rotational speed. +\param[in] throttleCommandResponseState describes the engine's response to input throttle command. +*/ +PX_FORCE_INLINE PxReal PxVehicleEngineDriveTorqueCompute +(const PxVehicleEngineParams& engineParams, const PxVehicleEngineState& engineState, const PxVehicleEngineDriveThrottleCommandResponseState& throttleCommandResponseState) +{ + const PxReal appliedThrottle = throttleCommandResponseState.commandResponse; + const PxReal peakTorque = engineParams.peakTorque; + const PxVehicleFixedSizeLookupTable& torqueCurve = engineParams.torqueCurve; + const PxReal normalisedRotSpeed = engineState.rotationSpeed/engineParams.maxOmega; + const PxReal engineDriveTorque = appliedThrottle*peakTorque*torqueCurve.interpolate(normalisedRotSpeed); + return engineDriveTorque; +} + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Compute the contribution that each wheel makes to the averaged wheel speed at the clutch plate connected to the wheels driven by +the differential. +\param[in] diffParams describes the wheels coupled to the differential and the operation of the torque split at the differential. +\param[in] nbWheels The number of wheels. Can be larger than the number of wheels connected to the differential. +\param[out] diffAveWheelSpeedContributions describes the contribution that each wheel makes to the averaged wheel speed at the clutch. + The buffer needs to be sized to be able to hold at least nbWheels entries. +\note Any wheel on an axle connected to the differential could have a non-zero value, depending on the way the differential couples to the wheels. +\note Any wheel on an axle not connected to the differential will have a zero contribution to the averaged wheel speed. +*/ +void PX_DEPRECATED PxVehicleLegacyDifferentialWheelSpeedContributionsCompute +(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams, + const PxU32 nbWheels, PxReal* diffAveWheelSpeedContributions); + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Compute the fraction of available torque that is delivered to each wheel through the differential. +\param[in] diffParams describes the wheels coupled to the differential and the operation of the torque split at the differential. +\param[in] wheelOmegas describes the rotational speeds of the wheels. Is expected to have nbWheels entries. +\param[in] nbWheels The number of wheels. Can be larger than the number of wheels connected to the differential. +\param[out] diffTorqueRatios describes the fraction of available torque delivered to each wheel. + The buffer needs to be sized to be able to hold at least nbWheels entries. +\note Any wheel on an axle connected to the diff could receive a non-zero ratio, depending on the way the differential couples to the wheels. +\note Any wheel not on an axle connected to the diff will have a zero value. +\note The sum of all the ratios adds to 1.0. +\note Slipping wheels driven by the differential will typically receive less torque than non-slipping wheels in the event that the +differential has a limited slip configuration. +*/ +void PX_DEPRECATED PxVehicleLegacyDifferentialTorqueRatiosCompute +(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams, + const PxVehicleArrayData& wheelOmegas, + const PxU32 nbWheels, PxReal* diffTorqueRatios); + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainParams.h new file mode 100644 index 000000000..1e7dd602d --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainParams.h @@ -0,0 +1,993 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" +#include "common/PxCoreUtilityTypes.h" + +#include "vehicle2/PxVehicleParams.h" + +#include "vehicle2/commands/PxVehicleCommandParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Distribute a throttle response to the wheels of a direct drive vehicle. +\note The drive torque applied to each wheel on the ith axle is throttleCommand * maxResponse * wheelResponseMultipliers[i]. +\note A typical use case is to set maxResponse to be the vehicle's maximum achievable drive torque +that occurs when the steer command is equal to 1.0. The array wheelResponseMultipliers[i] would then be used +to specify the maximum achievable drive torque per wheel as a fractional multiplier of the vehicle's maximum achievable steer angle. +*/ +struct PxVehicleDirectDriveThrottleCommandResponseParams : public PxVehicleCommandResponseParams +{ + PX_FORCE_INLINE PxVehicleDirectDriveThrottleCommandResponseParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleDirectDriveThrottleCommandResponseParams r = *this; + const PxReal scale = trgScale.scale/srcScale.scale; + r.maxResponse *= (scale*scale); //Max response is a torque! + return r; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + PX_CHECK_AND_RETURN_VAL(PxIsFinite(maxResponse), "PxVehicleDirectDriveThrottleCommandResponseParams.maxResponse must be a finite value", false); + for (PxU32 i = 0; i < axleDesc.nbWheels; i++) + { + PX_CHECK_AND_RETURN_VAL(PxIsFinite(wheelResponseMultipliers[axleDesc.wheelIdsInAxleOrder[i]]), "PxVehicleDirectDriveThrottleCommandResponseParams.wheelResponseMultipliers[i] must be a finite value", false); + } + return true; + } +}; + +/** +\brief Specifies the maximum clutch strength that occurs when the clutch pedal is fully disengaged and the clutch is fully engaged. +*/ +struct PxVehicleClutchCommandResponseParams +{ + /** + \brief Strength of clutch. + + \note The clutch is the mechanism that couples the engine to the wheels. + A stronger clutch more strongly couples the engine to the wheels, while a + clutch of strength zero completely decouples the engine from the wheels. + Stronger clutches more quickly bring the wheels and engine into equilibrium, while weaker + clutches take longer, resulting in periods of clutch slip and delays in power transmission + from the engine to the wheels. + The torque generated by the clutch is proportional to the clutch strength and + the velocity difference between the engine's rotational speed and the rotational speed of the + driven wheels after accounting for the gear ratio. + The torque at the clutch is applied negatively to the engine and positively to the driven wheels. + + Range: [0,inf)
+ Unit: torque * time = mass * (length^2) / time + */ + PxReal maxResponse; + + PX_FORCE_INLINE PxVehicleClutchCommandResponseParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + const PxReal scale = trgScale.scale/srcScale.scale; + PxVehicleClutchCommandResponseParams r = *this; + r.maxResponse *= (scale*scale); + return r; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(maxResponse >= 0.0f, "PxVehicleClutchCommandResponseParams.maxResponse must be greater than or equal to zero", false); + return true; + } +}; + +/** +\brief Choose between a potentially more expensive but more accurate solution to the clutch model or a potentially cheaper but less accurate solution. +\see PxVehicleClutchParams +*/ +struct PxVehicleClutchAccuracyMode +{ + enum Enum + { + eESTIMATE = 0, + eBEST_POSSIBLE + }; +}; + +/** +\brief The clutch connects two plates together. One plate rotates with the speed of the engine. The second plate rotates with a weighted average of all +wheels connected to the differential after accounting for the gear ratio. The difference in rotation speeds generates a restoring torque applied to engine and wheels +that aims to reduce the difference in rotational speed. The restoring torque is proportional to the clutch strength and the clutch pedal position. +*/ +struct PxVehicleClutchParams +{ +public: + + /** + \brief The engine and wheel rotation speeds that are coupled through the clutch can be updated by choosing + one of two modes: eESTIMATE and eBEST_POSSIBLE. + + \note If eESTIMATE is chosen the vehicle sdk will update the wheel and engine rotation speeds + with estimated values to the implemented clutch model. + + \note If eBEST_POSSIBLE is chosen the vehicle sdk will compute the best possible + solution (within floating point tolerance) to the implemented clutch model. + This is the recommended mode. + + \note The clutch model remains the same if either eESTIMATE or eBEST_POSSIBLE is chosen but the accuracy and + computational cost of the solution to the model can be tuned as required. + */ + PxVehicleClutchAccuracyMode::Enum accuracyMode; + + /** + \brief Tune the mathematical accuracy and computational cost of the computed estimate to the wheel and + engine rotation speeds if eESTIMATE is chosen. + + \note As estimateIterations increases the computational cost of the clutch also increases and the solution + approaches the solution that would be computed if eBEST_POSSIBLE was chosen instead. + + \note This has no effect if eBEST_POSSIBLE is chosen as the accuracy mode. + + \note A value of zero is not allowed if eESTIMATE is chosen as the accuracy mode. + */ + PxU32 estimateIterations; + + PX_FORCE_INLINE PxVehicleClutchParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL((PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == accuracyMode) || ((PxVehicleClutchAccuracyMode::eESTIMATE == accuracyMode) && (estimateIterations > 0)), "PxVehicleClutchParams.estimateIterations must be greater than zero if PxVehicleClutchAccuracyMode::eESTIMATE is selected", false); + return true; + } +}; + + +struct PxVehicleEngineParams +{ + /** + \brief Maximum supported number of points in the #torqueCurve graph. + */ + enum + { + eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES = 8 + }; + + /** + \brief Graph of normalized torque (torque/#peakTorque) against normalized engine speed ( engineRotationSpeed / #maxOmega ). + + \note The normalized engine speed is the x-axis of the graph, while the normalized torque is the y-axis of the graph. + */ + PxVehicleFixedSizeLookupTable torqueCurve; + + /** + \brief Moment of inertia of the engine around the axis of rotation. + + Range: (0, inf)
+ Unit: mass * (length^2) + */ + PxReal moi; + + /** + \brief Maximum torque available to apply to the engine when the accelerator pedal is at maximum. + + \note The torque available is the value of the accelerator pedal (in range [0, 1]) multiplied by the normalized torque as computed from #torqueCurve multiplied by #peakTorque. + + Range: [0, inf)
+ Unit: mass * (length^2) / (time^2) + */ + PxReal peakTorque; + + /** + \brief Minimum rotation speed of the engine. + + Range: [0, inf)
+ Unit: radians / time + */ + PxReal idleOmega; + + /** + \brief Maximum rotation speed of the engine. + + Range: [0, inf)
+ Unit: radians / time + */ + PxReal maxOmega; + + /** + \brief Damping rate of engine when full throttle is applied. + + \note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation + between #dampingRateZeroThrottleClutchEngaged and #dampingRateFullThrottle: + #dampingRateZeroThrottleClutchEngaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchEngaged)*acceleratorPedal; + + \note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation + between #dampingRateZeroThrottleClutchDisengaged and #dampingRateFullThrottle: + #dampingRateZeroThrottleClutchDisengaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchDisengaged)*acceleratorPedal; + + Range: [0, inf)
+ Unit: torque * time = mass * (length^2) / time + */ + PxReal dampingRateFullThrottle; + + /** + \brief Damping rate of engine when no throttle is applied and with engaged clutch. + + \note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation + between #dampingRateZeroThrottleClutchEngaged and #dampingRateFullThrottle: + #dampingRateZeroThrottleClutchEngaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchEngaged)*acceleratorPedal; + + \note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation + between #dampingRateZeroThrottleClutchDisengaged and #dampingRateFullThrottle: + #dampingRateZeroThrottleClutchDisengaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchDisengaged)*acceleratorPedal; + + Range: [0, inf)
+ Unit: torque * time = mass * (length^2) / time + */ + PxReal dampingRateZeroThrottleClutchEngaged; + + /** + \brief Damping rate of engine when no throttle is applied and with disengaged clutch. + + \note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation + between #dampingRateZeroThrottleClutchEngaged and #dampingRateFullThrottle: + #dampingRateZeroThrottleClutchEngaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchEngaged)*acceleratorPedal; + + \note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation + between #dampingRateZeroThrottleClutchDisengaged and #dampingRateFullThrottle: + #dampingRateZeroThrottleClutchDisengaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchDisengaged)*acceleratorPedal; + + Range: [0, inf)
+ Unit: torque * time = mass * (length^2) / time + */ + PxReal dampingRateZeroThrottleClutchDisengaged; + + PX_FORCE_INLINE PxVehicleEngineParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleEngineParams r = *this; + const PxReal scale = trgScale.scale/srcScale.scale; + r.moi *= (scale*scale); + r.peakTorque *= (scale*scale); + r.dampingRateFullThrottle *= (scale*scale); + r.dampingRateZeroThrottleClutchDisengaged *= (scale*scale); + r.dampingRateZeroThrottleClutchEngaged *= (scale*scale); + return r; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(moi > 0.0f, "PxVehicleEngineParams.moi must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(peakTorque >= 0.0f, "PxVehicleEngineParams.peakTorque must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(torqueCurve.isValid(), "PxVehicleEngineParams.torqueCurve is invalid", false); + PX_CHECK_AND_RETURN_VAL(maxOmega >= 0.0f, "PxVehicleEngineParams.maxOmega must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(idleOmega >= 0.0f, "PxVehicleEngineParams.idleOmega must be greater or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(dampingRateFullThrottle >= 0.0f, "PxVehicleEngineParams.dampingRateFullThrottle must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(dampingRateZeroThrottleClutchEngaged >= 0.0f, "PxVehicleEngineParams.dampingRateZeroThrottleClutchEngaged must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(dampingRateZeroThrottleClutchDisengaged >= 0.0f, "PxVehicleEngineParams.dampingRateZeroThrottleClutchDisengaged must be greater than or equal to zero", false) + return true; + } +}; + +struct PxVehicleGearboxParams +{ +public: + + /** + \brief The gear that denotes neutral gear + */ + PxU32 neutralGear; + + /** + \brief Maximum supported number of gears, including reverse and neutral. + */ + enum Enum + { + eMAX_NB_GEARS = 32 + }; + + /** + \brief Gear ratios + + The ratio for reverse gears must be negative, the ratio for the neutral gear + has to be 0 and the ratio for forward gears must be positive. + */ + PxReal ratios[eMAX_NB_GEARS]; + + /** + \brief Gear ratio applied is #ratios[currentGear]*#finalRatio + + Range: (0, inf)
+ */ + PxReal finalRatio; + + /** + \brief Number of gears (including reverse and neutral). + + Range: [1, eMAX_NB_GEARS]
+ */ + PxU32 nbRatios; + + /** + \brief Time it takes to switch gear. + + Range: [0, inf)
+ Unit: time + */ + PxReal switchTime; + + PX_FORCE_INLINE PxVehicleGearboxParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(finalRatio > 0, "PxVehicleGearboxParams.finalRatio must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(nbRatios >= 1, "PxVehicleGearboxParams.nbRatios must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(nbRatios <= eMAX_NB_GEARS, "PxVehicleGearboxParams.nbRatios must be less than or equal to eMAX_NB_GEARS", false); + PX_CHECK_AND_RETURN_VAL(neutralGear < nbRatios, "PxVehicleGearboxParams.neutralGear must be less than PxVehicleGearboxParams.nbRatios", false); + PX_CHECK_AND_RETURN_VAL(switchTime >= 0.0f, "PxVehicleGearboxParams.switchTime must be greater than or equal to zero", false); + for(PxU32 i = 0; i < neutralGear; i++) + { + PX_CHECK_AND_RETURN_VAL(ratios[i] < 0.0f, "Reverse gear ratios must be less than zero", false); + } + { + PX_CHECK_AND_RETURN_VAL(ratios[neutralGear] == 0.0f, "Neutral gear ratio must be equal to zero", false); + } + for (PxU32 i = neutralGear + 1; i < nbRatios; i++) + { + PX_CHECK_AND_RETURN_VAL(ratios[i] > 0.0f, "Forward gear ratios must be greater than zero", false); + } + for (PxU32 i = neutralGear + 2; i < nbRatios; i++) + { + PX_CHECK_AND_RETURN_VAL(ratios[i] < ratios[i - 1], "Forward gear ratios must be a descending sequence of gear ratios", false); + } + return true; + } +}; + + +struct PxVehicleAutoboxParams +{ +public: + + /** + \brief Value of ( engineRotationSpeed /maxEngineRevs ) that is high enough to increment gear. + + \note When ( engineRotationSpeed / #PxVehicleEngineParams::maxOmega ) > upRatios[currentGear] the autobox will begin + a transition to currentGear+1 unless currentGear is the highest possible gear or neutral or reverse. + + Range: [0, 1]
+ */ + PxReal upRatios[PxVehicleGearboxParams::eMAX_NB_GEARS]; + + /** + \brief Value of engineRevs/maxEngineRevs that is low enough to decrement gear. + + \note When ( engineRotationSpeed / #PxVehicleEngineParams::maxOmega) < downRatios[currentGear] the autobox will begin + a transition to currentGear-1 unless currentGear is first gear or neutral or reverse. + + Range: [0, 1]
+ */ + PxReal downRatios[PxVehicleGearboxParams::eMAX_NB_GEARS]; + + /** + \brief Set the latency time of the autobox. + + \note Latency time is the minimum time that must pass between each gear change that is initiated by the autobox. + The auto-box will only attempt to initiate another gear change up or down if the simulation time that has passed since the most recent + automated gear change is greater than the specified latency. + + Range: [0, inf)
+ Unit: time + */ + PxReal latency; + + PX_FORCE_INLINE PxVehicleAutoboxParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleGearboxParams& gearboxParams) const + { + if (!gearboxParams.isValid()) + return false; + + for (PxU32 i = gearboxParams.neutralGear + 1; i < gearboxParams.nbRatios-1; i++) + { + PX_CHECK_AND_RETURN_VAL(upRatios[i] >= 0.0f, "PxVehicleAutoboxParams.upRatios must be greater than or equal to zero", false); + } + for (PxU32 i = gearboxParams.neutralGear + 2; i < gearboxParams.nbRatios; i++) + { + PX_CHECK_AND_RETURN_VAL(downRatios[i] >= 0.0f, "PxVehicleAutoboxParams.downRatios must be greater than or equal to zero", false); + } + PX_CHECK_AND_RETURN_VAL(latency >= 0.0f, "PxVehicleAutoboxParams.latency must be greater than or equal to zero", false); + return true; + } +}; + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. +*/ +struct PX_DEPRECATED PxVehicleFourWheelDriveDifferentialLegacyParams +{ +public: + + enum Enum + { + eDIFF_TYPE_LS_4WD, //limited slip differential for car with 4 driven wheels + eDIFF_TYPE_LS_FRONTWD, //limited slip differential for car with front-wheel drive + eDIFF_TYPE_LS_REARWD, //limited slip differential for car with rear-wheel drive + eMAX_NB_DIFF_TYPES + }; + + /** + \brief The two front wheels are specified by the array frontWheelIds. + \note The states eDIFF_TYPE_LS_4WD, eDIFF_TYPE_LS_FRONTWD require knowledge of the front wheels + to allow torque splits between front and rear axles as well as torque splits across the front axle. + \note frontWheelIds[0] should specify the wheel on the front axle that is negatively placed on the lateral axis. + \note frontWheelIds[1] should specify the wheel on the front axle that is positively placed on the lateral axis. + \note If #frontNegPosSplit > 0.5, more torque will be delivered to the wheel specified by frontWheelIds[0] than to the wheel + specified by frontWheelIds[1]. The converse is true if #frontNegPosSplit < 0.5. + */ + PxU32 frontWheelIds[2]; + + + /** + \brief The two rear wheels are specified by the array rearWheelIds. + \note The states eDIFF_TYPE_LS_4WD, eDIFF_TYPE_LS_REARWD require knowledge of the rear wheels + to allow torque splits between front and rear axles as well as torque splits across the rear axle. + \note rearWheelIds[0] should specify the wheel on the rear axle that is negatively placed on the lateral axis. + \note rearWheelIds[1] should specify the wheel on the rear axle that is positively placed on the lateral axis. + \note If #rearNegPosSplit > 0.5, more torque will be delivered to the wheel specified by rearWheelIds[0] than to the wheel + specified by rearWheelIds[1]. The converse is true if #rearNegPosSplit < 0.5. + */ + PxU32 rearWheelIds[2]; + + /** + \brief Ratio of torque split between front and rear wheels (>0.5 means more front, <0.5 means more to rear). + + \note Only applied to DIFF_TYPE_LS_4WD + + Range: [0, 1]
+ */ + PxReal frontRearSplit; + + /** + \brief Ratio of torque split between front-negative and front-positive wheels (>0.5 means more to #frontWheelIds[0], <0.5 means more to #frontWheelIds[1]). + + \note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_FRONTWD + + Range: [0, 1]
+ */ + PxReal frontNegPosSplit; + + /** + \brief Ratio of torque split between rear-negative wheel and rear-positive wheels (>0.5 means more to #rearWheelIds[0], <0.5 means more to #rearWheelIds[1]). + + \note Only applied to DIFF_TYPE_LS_4WD and eDIFF_TYPE_LS_REARWD + + Range: [0, 1]
+ */ + PxReal rearNegPosSplit; + + /** + \brief Maximum allowed ratio of average front wheel rotation speed and rear wheel rotation speeds. + The differential will divert more torque to the slower wheels when the bias is exceeded. + + \note Only applied to DIFF_TYPE_LS_4WD + + Range: [1, inf)
+ */ + PxReal centerBias; + + /** + \brief Maximum allowed ratio of front-left and front-right wheel rotation speeds. + The differential will divert more torque to the slower wheel when the bias is exceeded. + + \note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_FRONTWD + + Range: [1, inf)
+ */ + PxReal frontBias; + + /** + \brief Maximum allowed ratio of rear-left and rear-right wheel rotation speeds. + The differential will divert more torque to the slower wheel when the bias is exceeded. + + \note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_REARWD + + Range: [1, inf)
+ */ + PxReal rearBias; + + /** + \brief Type of differential. + + Range: [DIFF_TYPE_LS_4WD, eDIFF_TYPE_LS_REARWD]
+ */ + Enum type; + + PX_FORCE_INLINE PxVehicleFourWheelDriveDifferentialLegacyParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + PX_UNUSED(axleDesc); + PX_CHECK_AND_RETURN_VAL((axleDesc.getAxle(frontWheelIds[0]) != 0xffffffff) && (axleDesc.getAxle(frontWheelIds[0])== axleDesc.getAxle(frontWheelIds[1])), "frontWheelIds[0] and frontWheelIds[1] must reference wheels on the same axle", false); + PX_CHECK_AND_RETURN_VAL((axleDesc.getAxle(rearWheelIds[0]) != 0xffffffff) && (axleDesc.getAxle(rearWheelIds[0]) == axleDesc.getAxle(rearWheelIds[1])), "rearWheelIds[0] and rearWheelIds[1] must reference wheels on the same axle", false); + PX_CHECK_AND_RETURN_VAL(frontRearSplit <= 1.0f && frontRearSplit >= 0.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.frontRearSplit must be in range [0,1]", false); + PX_CHECK_AND_RETURN_VAL(frontNegPosSplit <= 1.0f && frontNegPosSplit >= 0.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.frontNegPosSplit must be in range [0,1]", false); + PX_CHECK_AND_RETURN_VAL(rearNegPosSplit <= 1.0f && rearNegPosSplit >= 0.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.rearNegPosSplit must be in range [0,1]", false); + PX_CHECK_AND_RETURN_VAL(centerBias >= 1.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.centerBias must be greater than or equal to 1.0f", false); + PX_CHECK_AND_RETURN_VAL(frontBias >= 1.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.frontBias must be greater than or equal to 1.0f", false); + PX_CHECK_AND_RETURN_VAL(rearBias >= 1.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.rearBias must be greater than or equal to 1.0f", false); + PX_CHECK_AND_RETURN_VAL(type < PxVehicleFourWheelDriveDifferentialLegacyParams::eMAX_NB_DIFF_TYPES, "PxVehicleLegacyFourWheelDriveDifferentialParams.type has illegal value", false); + return true; + } +}; + +/** +\brief PxVehicleMultiWheelDriveDifferentialParams specifies the wheels that are to receive drive torque from the differential +and the division of torque between the wheels that are connected to the differential. +*/ +struct PxVehicleMultiWheelDriveDifferentialParams +{ + /** + \brief torqueRatios describes the fraction of torque delivered to each wheel through the differential. + \note Wheels not connected to the differential must receive zero torque. + \note Wheels connected to the differential may receive a non-zero torque. + \note The sum of the absolute of the ratios of all wheels must equal to 1.0. + \note A negative torque ratio simulates a wheel with negative gearing applied. + + Range: [1, -1]
+ */ + PxReal torqueRatios[PxVehicleLimits::eMAX_NB_WHEELS]; + + /** + \brief aveWheelSpeedRatios describes the contribution of each wheel to the average wheel speed measured at the clutch. + \note Wheels not connected to the differential do not contribute to the average wheel speed measured at the clutch. + \note Wheels connected to the differential may delivere a non-zero contribution to the average wheel speed measured at the clutch. + \note The sum of all ratios of all wheels must equal to 1.0. + + Range: [0, 1]
+ */ + PxReal aveWheelSpeedRatios[PxVehicleLimits::eMAX_NB_WHEELS]; + + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleMultiWheelDriveDifferentialParams)); + } + + PX_FORCE_INLINE PxVehicleMultiWheelDriveDifferentialParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + if (!axleDesc.isValid()) + return false; + PxReal aveWheelSpeedSum = 0.0f; + PxReal torqueRatioSum = 0.0f; + for (PxU32 i = 0; i < axleDesc.nbWheels; i++) + { + const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; + PX_CHECK_AND_RETURN_VAL(PxAbs(torqueRatios[wheelId]) <= 1.0f, "PxVehicleMultiWheelDriveDifferentialParams.torqueRatios[i] must be in range [-1, 1] for all wheels connected to the differential", false); + PX_CHECK_AND_RETURN_VAL(aveWheelSpeedRatios[wheelId] >= 0.0f && aveWheelSpeedRatios[wheelId] <= 1.0f, "PxVehicleMultiWheelDriveDifferentialParams.aveWheelSpeedRatios[i] must be in range [0, 1] for all wheels connected to the differential", false); + aveWheelSpeedSum += aveWheelSpeedRatios[wheelId]; + torqueRatioSum += PxAbs(torqueRatios[wheelId]); + } + PX_CHECK_AND_RETURN_VAL(aveWheelSpeedSum >= 0.99f && aveWheelSpeedSum <= 1.01f, "Sum of PxVehicleMultiWheelDriveDifferentialParams.aveWheelSpeedRatios[i] must be 1.0.", false); + PX_CHECK_AND_RETURN_VAL(torqueRatioSum >= 0.99f && torqueRatioSum <= 1.01f, "Sum of PxVehicleMultiWheelDriveDifferentialParams.torqueRatios[i] must be 1.0.", false); + PX_UNUSED(aveWheelSpeedSum); + PX_UNUSED(torqueRatioSum); + return true; + } +}; + +/** +\brief A special value that indicates instantaneous resolution of a slip that exceeds a differential bias. +*/ +#define PX_VEHICLE_FOUR_WHEEL_DIFFERENTIAL_MAXIMUM_STRENGTH PX_MAX_F32 + +/** +\brief PxVehicleFourWheelDriveDifferentialParams specifies the wheels that are to receive drive torque from the differential +and the division of torque between the wheels that are connected to the differential. Additionally, it specifies the biases +and strength of a limited slip differential that operates on two wheels specified as front wheels and two wheels specified +as rear wheels. +*/ +struct PxVehicleFourWheelDriveDifferentialParams : public PxVehicleMultiWheelDriveDifferentialParams +{ + /** + \brief The ids of the two wheels considered by the differential to be the front pair. + \note When the ratio of the rotational speeds of the front wheels exceeds frontBias, drive torque is diverted so + that the ratio approaches the value specified by frontTarget. When the bias is not breached, the drive torque + is specified by the corresponding entries in PxVehicleMultiWheelDriveDifferentialParams::torqueRatios. + */ + PxU32 frontWheelIds[2]; + + /** + \brief The ids of the two wheels considered by the differential to be the rear pair. + \note When the ratio of the rotational speeds of the rear wheels exceeds rearBias, drive torque is diverted so + that the ratio approaches the value specified by rearTarget. When the bias is not breached, the drive torque + is specified by the corresponding entries in PxVehicleMultiWheelDriveDifferentialParams::torqueRatios. + */ + PxU32 rearWheelIds[2]; + + /** + \brief The parameter frontBias specifies the maximum angular speed ratio of the two front wheels specified by frontWheelIds[2]. + \note If frontBias has value 0.0, the differential will not try to enforce any relationship between the rotational speeds of the two front wheels. + \note If frontBias has value 0.0, the torque split between the front wheels is specified by the array torqueRatios. + \note frontBias must have value 0.0 (deactivated limited slip) or be greater than 1.0 (activated limited slip) or be equal to 1.0 (locked axle). + \note If frontBias has value greater than or equal to 1.0 then the array frontWheelIds must be specified and the corresponding entries of + the isConnected[] array must be set true. + \note If frontBias has value greater than or equal to 1.0 then frontTarget must also be specified. + \note A locked axle may be achieved by setting frontBias and frontTarget to 1.0. + \note A limited slip differential may be achieved by setting frontBias > 1.0 and frontBias > frontTarget > 1.0. + */ + PxReal frontBias; + + /** + \brief The parameter frontTarget specifies the target rotational speed ratio of the two front wheels in the event that the ratio exceeds frontBias and frontBias + is configured for an activated limited slip or locked axle. + \note frontTarget must be less than frontBias and greater than 1.0 to implement a limited slip differential. + \note Set frontTarget and frontBias to 1.0 to implement a locked axle. + */ + PxReal frontTarget; + + /** + \brief The parameter rearBias specifies the maximum angular speed ratio of the two rear wheels specified by rearWheelIds[2]. + \note If rearBias has value 0.0, the differential will not try to enforce any relationship between the rotational speeds of the two rear wheels. + \note If rearBias has value 0.0, the torque split between the rear wheels is specified by the array torqueRatios. + \note rearBias must have value 0.0 (deactivated limited slip) or be greater than 1.0 (activated limited slip) or be equal to 1.0 (locked axle). + \note If rearBias has value greater than or equal to 1.0 then the array rearWheelIds must be specified and the corresponding entries of + the isConnected[] array must be set true. + \note If rearBias has value greater than or equal to 1.0 then rearTarget must also be specified. + \note A locked axle may be achieved by setting rearBias and rearTarget to 1.0. + \note A limited slip differential may be achieved by setting rearBias > 1.0 and rearBias > rearTarget > 1.0 + */ + PxReal rearBias; + + /** + \brief The parameter rearTarget specifies the target rotational speed ratio of the two rear wheels in the event that the ratio exceeds rearBias and rearBias + is configured for an activated limited slip or locked axle. + \note rearTarget must be less than rearBias and greater than 1.0 to implement a limited slip differential. + \note Set rearTarget and rearBias to 1.0 to implement a locked axle. + */ + PxReal rearTarget; + + /** + \brief The parameter centerBias specifies the maximum angular speed ratio of the sum of the two front wheels and the sum of the two rear wheels, + as specified by frontWheelIds[2] and rearWheelIds[2]. + \note If centerBias has value 0.0, the differential will not try to enforce any relationship between the rotational speeds of the front and rear wheels. + \note If centerBias has value 0.0, the torque split between the front and rear rear wheels is specified by the array torqueRatios. + \note centerBias must have value 0.0 (deactivated limited slip) or be greater than 1.0 (activated limited slip) or be equal to 1.0 (locked). + \note If centerBias has value greater than or equal to 1.0 then the arrays frontWheelIds and rearWheelIds must be specified and the corresponding entries of + the isConnected[] array must be set true. + \note If centerBias has value greater than or equal to 1.0 then centerTarget must also be specified. + \note A locked front/rear differential may be achieved by setting centerBias and centerTarget to 1.0. + \note A limited slip differential may be achieved by setting centerBias > 1.0 and centerBias > centerTarget > 1.0 + */ + PxReal centerBias; + + /** + \brief The parameter centerTarget specifies the target rotational speed ratio of the sum of the two front wheels and the sum of the two rear wheels + in the event that the ratio exceeds centerBias and centerBias is configured for an activated limited slip. + \note centerTarget must be less than centerBias and greater than 1.0 to implement a limited slip differential. + \note Set centerTarget and centerBias to 1.0 to implement a locked differential. + */ + PxReal centerTarget; + + /** + \brief The parameter rate specifies how quickly the ratio of rotational speeds approaches the target rotational speed ratio. + \note strength must be in range [0,PX_VEHICLE_FOUR_WHEEL_DIFF_MAXIMUM_STRENGTH]. + \note The ratio of rotational speeds is decremented each update by rate*dt until the ratio is equal to the target ratio. + \note A value of 0 will result in a deactivated limited slip. + \note A value of PX_VEHICLE_FOUR_WHEEL_DIFF_MAXIMUM_STRENGTH will result in instantaneous correction of the rotational speed ratios. + */ + PxReal rate; + + + PX_FORCE_INLINE void setToDefault() + { + PxVehicleMultiWheelDriveDifferentialParams::setToDefault(); + frontBias = 0.0f; + rearBias = 0.0f; + centerBias = 0.0f; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + if (!PxVehicleMultiWheelDriveDifferentialParams::isValid(axleDesc)) + return false; + + PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) || + (centerBias > 1.0f && + frontWheelIds[0] < axleDesc.nbWheels && frontWheelIds[1] < axleDesc.nbWheels && + rearWheelIds[0] < axleDesc.nbWheels && rearWheelIds[1] < axleDesc.nbWheels), + "PxVehicleFourWheelDriveDifferentialParams:: centreBias is enabled but the frontWheelIds and rearWheelIds are not configured correctly.", false); + PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) || + (centerBias > 1.0f && + frontWheelIds[0] != frontWheelIds[1] && frontWheelIds[0] != rearWheelIds[0] && frontWheelIds[0] != rearWheelIds[1] && + frontWheelIds[1] != rearWheelIds[0] && frontWheelIds[1] != rearWheelIds[1] && + rearWheelIds[0] != rearWheelIds[1]), + "PxVehicleFourWheelDriveDifferentialParams:: centreBias is enabled but the frontWheelIds and rearWheelIds are not configured correctly.", false); + PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) || + (centerBias > 1.0f && + torqueRatios[frontWheelIds[0]] != 0.0f && torqueRatios[frontWheelIds[1]] != 0.0f && torqueRatios[rearWheelIds[0]] != 0.0f && torqueRatios[rearWheelIds[1]] != 0.0f), + "PxVehicleFourWheelDriveDifferentialParams:: centreBias is enabled but the front and rear wheels are not connected.", false); + + PX_CHECK_AND_RETURN_VAL((0.0f == rearBias) || + (rearBias > 1.0f && rearWheelIds[0] < axleDesc.nbWheels && rearWheelIds[1] < axleDesc.nbWheels), + "PxVehicleFourWheelDriveDifferentialParams:: rearBias is enabled but the rearWheelIds are not configured correctly.", false); + PX_CHECK_AND_RETURN_VAL((0.0f == rearBias) || + (rearBias > 1.0f && rearWheelIds[0] != rearWheelIds[1]), + "PxVehicleFourWheelDriveDifferentialParams:: rearBias is enabled but the rearWheelIds are not configured correctly.", false); + PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) || + (rearBias > 1.0f && torqueRatios[rearWheelIds[0]] != 0.0f && torqueRatios[rearWheelIds[1]] != 0.0f), + "PxVehicleFourWheelDriveDifferentialParams:: rearBias is enabled but the rear wheels are not connected.", false); + + PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) || + (frontBias > 1.0f && frontWheelIds[0] < axleDesc.nbWheels && frontWheelIds[1] < axleDesc.nbWheels), + "PxVehicleFourWheelDriveDifferentialParams:: frontBias is enabled but the frontWheelIds are not configured correctly.", false); + PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) || + (frontBias > 1.0f && frontWheelIds[0] != frontWheelIds[1]), + "PxVehicleFourWheelDriveDifferentialParams:: frontBias is enabled but the frontWheelIds are not configured correctly.", false); + PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) || + (frontBias > 1.0f && torqueRatios[frontWheelIds[0]] != 0.0f && frontWheelIds[frontWheelIds[1]]), + "PxVehicleFourWheelDriveDifferentialParams:: frontBias is enabled but the front wheels are not connected.", false); + + PX_CHECK_AND_RETURN_VAL(((0.0f == frontBias) && (0.0f == rearBias) && (0.0f == centerBias)) || (rate >= 0.0f), + "PxVehicleFourWheelDriveDifferentialParams:: strength must be greater than or equal to zero", false); + + PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) || ((1.0f == frontTarget && 1.0f == rearTarget) || (frontTarget > 1.0f && frontTarget < frontBias)), + "PxVehicleFourWheelDriveDifferentialParams: frontBias is enabled but frontTarget not in range (1.0f, frontBias)", false); + PX_CHECK_AND_RETURN_VAL((0.0f == rearBias) || ((1.0f == rearTarget && 1.0f == rearBias) || (rearTarget > 1.0f && rearTarget < rearBias)), + "PxVehicleFourWheelDriveDifferentialParams: rearBias is enabled but rearTarget not in range (1.0f, rearBias)", false); + PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) || ((1.0f == centerTarget && 1.0f == centerBias) || (centerTarget > 1.0f && centerTarget < centerBias)), + "PxVehicleFourWheelDriveDifferentialParams: centerBias is enabled but centerTarget not in range (1.0f, centerBias)", false); + + return true; + } + + PX_FORCE_INLINE PxVehicleFourWheelDriveDifferentialParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + PxVehicleFourWheelDriveDifferentialParams r = *this; + static_cast(r) = PxVehicleMultiWheelDriveDifferentialParams::transformAndScale(srcFrame, trgFrame, srcScale, trgScale); + return r; + } +}; + +/** +\brief A description of a tank differential. +\note The wheels on a tank may be connected to the differential or not connected to the differential. +\note The wheels on a tank track may be connected to a tank track or not connected to a tank track. +\note Wheels connected to the differential but not to a tank track receive the torque split specified by the +corresponding elements of PxVehicleMultiWheelDriveDifferentialParams::torqueRatios[]. +\note Wheels connected to a tank track but not to the differential receive no torque from the engine. +\note Wheels connected to a tank track and to the differential receive the torque split specified by the +corresponding elements of PxVehicleMultiWheelDriveDifferentialParams::torqueRatios[] multiplied by the corresponding +thrust controller value. If the thrust controller has a negative value, the wheels will receive a torque that is negative +with respect to the gearing ratio. +\note The wheels in each tank track have a constraint applied to them to enforce the rule that they all have the same longitudinal speed +at the contact point between the wheel and the tank track. +*/ +struct PxVehicleTankDriveDifferentialParams : public PxVehicleMultiWheelDriveDifferentialParams +{ + PX_FORCE_INLINE void setToDefault() + { + PxVehicleMultiWheelDriveDifferentialParams::setToDefault(); + nbTracks = 0; + } + + /** + \brief Add a tank track by specifying the number of wheels along the track and an array of wheel ids specifying each wheel in the tank track. + \param[in] nbWheelsInTrackToAdd is the number of wheels in the track to be added. + \param[in] wheelIdsInTrackToAdd is an array of wheel ids specifying all the wheels in the track to be added. + \param[in] thrustControllerIndex specifies the index of the thrust controller that will be used to control the tank track. + */ + void addTankTrack(const PxU32 nbWheelsInTrackToAdd, const PxU32* const wheelIdsInTrackToAdd, const PxU32 thrustControllerIndex) + { + PxU32 trackToWheelIdsOffset = nbTracks ? trackToWheelIds[nbTracks - 1] + nbWheelsPerTrack[nbTracks - 1] : 0; + PX_ASSERT((trackToWheelIdsOffset + nbWheelsInTrackToAdd) <= PxVehicleLimits::eMAX_NB_WHEELS); + PX_ASSERT(nbTracks < PxVehicleLimits::eMAX_NB_WHEELS); + PX_ASSERT(thrustControllerIndex < 2); + nbWheelsPerTrack[nbTracks] = nbWheelsInTrackToAdd; + thrustIdPerTrack[nbTracks] = thrustControllerIndex; + trackToWheelIds[nbTracks] = trackToWheelIdsOffset; + for (PxU32 i = 0; i < nbWheelsInTrackToAdd; i++) + { + wheelIdsInTrackOrder[trackToWheelIdsOffset + i] = wheelIdsInTrackToAdd[i]; + } + nbTracks++; + } + + /** + \brief Return the number of tracks. + \return The number of tracks. + \see getNbWheelsInTrack() + */ + PX_FORCE_INLINE PxU32 getNbTracks() const + { + return nbTracks; + } + + /** + \brief Return the number of wheels in the ith track. + \param[in] i specifies the track to be queried for its wheel count. + \return The number of wheels in the specified track. + \see getWheelInTrack() + */ + PX_FORCE_INLINE PxU32 getNbWheelsInTrack(const PxU32 i) const + { + return nbWheelsPerTrack[i]; + } + + /** + \brief Return the array of all wheels in the ith track. + \param[in] i specifies the track to be queried for its wheels. + \return The array of wheels in the specified track. + */ + PX_FORCE_INLINE const PxU32* getWheelsInTrack(const PxU32 i) const + { + return (wheelIdsInTrackOrder + trackToWheelIds[i]); + } + + /** + \brief Return the wheel id of the jth wheel in the ith track. + \param[in] j specifies that the wheel id to be returned is the jth wheel in the list of wheels on the specified track. + \param[in] i specifies the track to be queried. + \return The wheel id of the jth wheel in the ith track. + \see getNbWheelsInTrack() + */ + PX_FORCE_INLINE PxU32 getWheelInTrack(const PxU32 j, const PxU32 i) const + { + return wheelIdsInTrackOrder[trackToWheelIds[i] + j]; + } + + /** + \brief Return the index of the thrust controller that will control a specified track. + \param[in] i specifies the track to be queried for its thrust controller index + \return The index of the thrust controller that will control the ith track. + */ + PX_FORCE_INLINE PxU32 getThrustControllerIndex(const PxU32 i) const + { + return thrustIdPerTrack[i]; + } + + PX_FORCE_INLINE PxVehicleTankDriveDifferentialParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + PxVehicleTankDriveDifferentialParams r = *this; + static_cast(r) = PxVehicleMultiWheelDriveDifferentialParams::transformAndScale(srcFrame, trgFrame, srcScale, trgScale); + return r; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + if (!PxVehicleMultiWheelDriveDifferentialParams::isValid(axleDesc)) + return false; + + PX_CHECK_AND_RETURN_VAL(nbTracks <= PxVehicleLimits::eMAX_NB_WHEELS, "PxVehicleTankDriveDifferentialParams.nbTracks must not exceed PxVehicleLimits::eMAX_NB_WHEELS", false); + + const PxU32 nbWheelsInTracksSize = nbTracks ? trackToWheelIds[nbTracks - 1] + nbWheelsPerTrack[nbTracks - 1] : 0; + PX_UNUSED(nbWheelsInTracksSize); + PX_CHECK_AND_RETURN_VAL(nbWheelsInTracksSize <= PxVehicleLimits::eMAX_NB_WHEELS, "PxVehicleTankDriveDifferentialParams.nbWheelsInTracks must not exceed PxVehicleLimits::eMAX_NB_WHEELS", false); + for (PxU32 i = 0; i < nbTracks; i++) + { + PX_CHECK_AND_RETURN_VAL(thrustIdPerTrack[i] < 2, "PxVehicleTankDriveDifferentialParams.thrustId must be less than 2", false); + } + + for (PxU32 i = 0; i < axleDesc.nbWheels; i++) + { + const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; + PxU32 count = 0; + for (PxU32 j = 0; j < nbTracks; j++) + { + const PxU32 nbWheels = getNbWheelsInTrack(j); + const PxU32* wheelIds = getWheelsInTrack(j); + + for (PxU32 k = 0; k < nbWheels; k++) + { + if (wheelIds[k] == wheelId) + count++; + } + } + PX_CHECK_AND_RETURN_VAL(count <= 1, "PxVehicleTankDriveDifferentialParams - a wheel cannot be in more than one tank track", false); + } + return true; + } + + PxU32 nbTracks; //!< The number of tracks + PxU32 thrustIdPerTrack[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The id of the thrust that will control the track. Must have value 0 or 1. + PxU32 nbWheelsPerTrack[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The number of wheels in each track + PxU32 trackToWheelIds[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The list of wheel ids for the ith tank track begins at wheelIdsInTrackOrder[trackToWheelIds[i]] + + PxU32 wheelIdsInTrackOrder[PxVehicleLimits::eMAX_NB_WHEELS];//!< The list of all wheel ids in all tracks +}; + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainStates.h new file mode 100644 index 000000000..359220a69 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/drivetrain/PxVehicleDrivetrainStates.h @@ -0,0 +1,284 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/commands/PxVehicleCommandStates.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + + +struct PxVehicleClutchCommandResponseState +{ + PxReal normalisedCommandResponse; + PxReal commandResponse; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleClutchCommandResponseState)); + } +}; + +struct PxVehicleEngineDriveThrottleCommandResponseState +{ + PxReal commandResponse; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleEngineDriveThrottleCommandResponseState)); + } +}; + +struct PxVehicleEngineState +{ + /** + \brief The rotation speed of the engine (radians per second). + + Unit: radians / time + */ + PxReal rotationSpeed; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleEngineState)); + } +}; + +#define PX_VEHICLE_NO_GEAR_SWITCH_PENDING -1.0f +#define PX_VEHICLE_GEAR_SWITCH_INITIATED -2.0f + +struct PxVehicleGearboxState +{ + /** + \brief Current gear + */ + PxU32 currentGear; + + /** + \brief Target gear (different from current gear if a gear change is underway) + */ + PxU32 targetGear; + + /** + \brief Reported time that has passed since gear change started. + + The special value PX_VEHICLE_NO_GEAR_SWITCH_PENDING denotes that there is currently + no gear change underway. + + If a gear switch was initiated, the special value PX_VEHICLE_GEAR_SWITCH_INITIATED + will be used temporarily but get translated to 0 in the gearbox update immediately. + This state might only get encountered, if the vehicle component update is split into + multiple sequences that do not run in one go. + + Unit: time + */ + PxReal gearSwitchTime; + + PX_FORCE_INLINE void setToDefault() + { + currentGear = 0; + targetGear = 0; + gearSwitchTime = PX_VEHICLE_NO_GEAR_SWITCH_PENDING; + } +}; + +#define PX_VEHICLE_UNSPECIFIED_TIME_SINCE_LAST_SHIFT PX_MAX_F32 + +struct PxVehicleAutoboxState +{ + /** + \brief Time that has lapsed since the last autobox gear shift. + + Unit: time + */ + PxReal timeSinceLastShift; + + /** + \brief Describes whether a gear shift triggered by the autobox is still in flight. + */ + bool activeAutoboxGearShift; + + PX_FORCE_INLINE void setToDefault() + { + timeSinceLastShift = PX_VEHICLE_UNSPECIFIED_TIME_SINCE_LAST_SHIFT; + activeAutoboxGearShift = false; + } +}; + +struct PxVehicleDifferentialState +{ + /** + \brief A list of wheel indices that are connected to the differential. + */ + PxU32 connectedWheels[PxVehicleLimits::eMAX_NB_WHEELS]; + + /** + \brief The number of wheels that are connected to the differential. + */ + PxU32 nbConnectedWheels; + + /** + \brief The fraction of available torque that is delivered to each wheel through the differential. + \note If a wheel is not connected to the differential then the fraction of available torque delivered to that wheel will be zero. + \note A negative torque ratio for a wheel indicates a negative gearing is to be applied to that wheel. + \note The sum of the absolute value of each fraction must equal 1.0. + */ + PxReal torqueRatiosAllWheels[PxVehicleLimits::eMAX_NB_WHEELS]; + + /** + \brief The contribution of each wheel to the average wheel rotation speed measured at the clutch. + \note If a wheel is not connected to the differential then the contribution to the average rotation speed measured at the clutch must be zero. + \note The sum of all contributions must equal 1.0. + */ + PxReal aveWheelSpeedContributionAllWheels[PxVehicleLimits::eMAX_NB_WHEELS]; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleDifferentialState)); + } +}; + +/** +\brief Specify groups of wheels that are to be constrained to have pre-determined angular velocity relationship. +*/ +struct PxVehicleWheelConstraintGroupState +{ + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleWheelConstraintGroupState)); + } + + /** + \brief Add a wheel constraint group by specifying the number of wheels in the group, an array of wheel ids specifying each wheel in the group + and a desired rotational speed relationship. + \param[in] nbWheelsInGroupToAdd is the number of wheels in the group to be added. + \param[in] wheelIdsInGroupToAdd is an array of wheel ids specifying all the wheels in the group to be added. + \param[in] constraintMultipliers is an array of constraint multipliers describing the desired relationship of the wheel rotational speeds. + \note constraintMultipliers[j] specifies the target rotational speed of the jth wheel in the constraint group as a multiplier of the rotational + speed of the zeroth wheel in the group. + */ + void addConstraintGroup(const PxU32 nbWheelsInGroupToAdd, const PxU32* const wheelIdsInGroupToAdd, const PxF32* constraintMultipliers) + { + PX_ASSERT((nbWheelsInGroups + nbWheelsInGroupToAdd) < PxVehicleLimits::eMAX_NB_WHEELS); + PX_ASSERT(nbGroups < PxVehicleLimits::eMAX_NB_WHEELS); + nbWheelsPerGroup[nbGroups] = nbWheelsInGroupToAdd; + groupToWheelIds[nbGroups] = nbWheelsInGroups; + for (PxU32 i = 0; i < nbWheelsInGroupToAdd; i++) + { + wheelIdsInGroupOrder[nbWheelsInGroups + i] = wheelIdsInGroupToAdd[i]; + wheelMultipliersInGroupOrder[nbWheelsInGroups + i] = constraintMultipliers[i]; + } + nbWheelsInGroups += nbWheelsInGroupToAdd; + nbGroups++; + } + + /** + \brief Return the number of wheel constraint groups in the vehicle. + \return The number of wheel constraint groups. + \see getNbWheelsInConstraintGroup() + */ + PX_FORCE_INLINE PxU32 getNbConstraintGroups() const + { + return nbGroups; + } + + /** + \brief Return the number of wheels in the ith constraint group. + \param[in] i specifies the constraint group to be queried for its wheel count. + \return The number of wheels in the specified constraint group. + \see getWheelInConstraintGroup() + */ + PX_FORCE_INLINE PxU32 getNbWheelsInConstraintGroup(const PxU32 i) const + { + return nbWheelsPerGroup[i]; + } + + /** + \brief Return the wheel id of the jth wheel in the ith constraint group. + \param[in] j specifies that the wheel id to be returned is the jth wheel in the list of wheels on the specified constraint group. + \param[in] i specifies the constraint group to be queried. + \return The wheel id of the jth wheel in the ith constraint group. + \see getNbWheelsInConstraintGroup() + */ + PX_FORCE_INLINE PxU32 getWheelInConstraintGroup(const PxU32 j, const PxU32 i) const + { + return wheelIdsInGroupOrder[groupToWheelIds[i] + j]; + } + + /** + \brief Return the constraint multiplier of the jth wheel in the ith constraint group + \param[in] j specifies that the wheel id to be returned is the jth wheel in the list of wheels on the specified constraint group. + \param[in] i specifies the constraint group to be queried. + \return The constraint multiplier of the jth wheel in the ith constraint group. + */ + PX_FORCE_INLINE PxReal getMultiplierInConstraintGroup(const PxU32 j, const PxU32 i) const + { + return wheelMultipliersInGroupOrder[groupToWheelIds[i] + j]; + } + + PxU32 nbGroups; //!< The number of constraint groups in the vehicle + PxU32 nbWheelsPerGroup[PxVehicleLimits::eMAX_NB_AXLES]; //!< The number of wheels in each group + PxU32 groupToWheelIds[PxVehicleLimits::eMAX_NB_AXLES]; //!< The list of wheel ids for the ith group begins at wheelIdsInGroupOrder[groupToWheelIds[i]] + + PxU32 wheelIdsInGroupOrder[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The list of all wheel ids in constraint groups + PxF32 wheelMultipliersInGroupOrder[PxVehicleLimits::eMAX_NB_WHEELS];//!< The constraint multipliers for each constraint group. + PxU32 nbWheelsInGroups; //!< The number of wheels in a constraint group. +}; + +/** +\brief The clutch is modelled as two spinning plates with one connected to the wheels through the gearing and the other connected to the engine. The clutch slip is angular speed difference of the two plates. +*/ +struct PxVehicleClutchSlipState +{ + /** + \brief The slip at the clutch. + + Unit: radians / time + */ + PxReal clutchSlip; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleClutchSlipState)); + } +}; + + + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorComponents.h new file mode 100644 index 000000000..a75db6f35 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorComponents.h @@ -0,0 +1,239 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "vehicle2/wheel/PxVehicleWheelStates.h" + +#include "PxVehiclePhysXActorFunctions.h" +#include "PxVehiclePhysXActorStates.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Work items at the beginning of an update step for a PhysX actor based vehicle. + +Includes: + - Waking the actor up if it is sleeping and a throttle or steer command is issued. + - Clearing certain states if the actor is sleeping. + - Reading the state from the PhysX actor and copy to the vehicle internal state. + +\see PxVehiclePhysxActorWakeup PxVehiclePhysxActorSleepCheck PxVehicleReadRigidBodyStateFromPhysXActor +*/ +class PxVehiclePhysXActorBeginComponent : public PxVehicleComponent +{ +public: + + PxVehiclePhysXActorBeginComponent() : PxVehicleComponent() {} + virtual ~PxVehiclePhysXActorBeginComponent() {} + + /** + \brief Provide vehicle data items for this component. + + \param[out] axleDescription identifies the wheels on each axle. + \param[out] commands are the brake, throttle and steer values that will drive the vehicle. + \param[out] transmissionCommands are the target gear and clutch values that will control + the transmission. Can be set to NULL if the vehicle does not have a gearbox. If + specified, then gearParams and gearState has to be specifed too. + \param[out] gearParams The gearbox parameters. Can be set to NULL if the vehicle does + not have a gearbox and transmissionCommands is NULL. + \param[out] gearState The state of the gearbox. Can be set to NULL if the vehicle does + not have a gearbox and transmissionCommands is NULL. + \param[out] engineParams The engine parameters. Can be set to NULL if the vehicle does + not have an engine. Must be specified, if engineState is specified. + \param[out] physxActor is the PxRigidBody instance associated with the vehicle. + \param[out] physxSteerState is the previous state of the steer and is used to determine if the + steering wheel has changed by comparing with PxVehicleCommandState::steer. + \param[out] physxConstraints The state of the suspension limit and low speed tire constraints. + If the vehicle actor is sleeping and constraints are active, they will be + deactivated and marked as dirty. + \param[out] rigidBodyState is the state of the rigid body used by the Vehicle SDK. + \param[out] wheelRigidBody1dStates describes the angular speed of each wheel. + \param[out] engineState The engine state. Can be set to NULL if the vehicle does + not have an engine. If specified, then engineParams has to be specifed too. + */ + virtual void getDataForPhysXActorBeginComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleCommandState*& commands, + const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, + const PxVehicleGearboxParams*& gearParams, + const PxVehicleGearboxState*& gearState, + const PxVehicleEngineParams*& engineParams, + PxVehiclePhysXActor*& physxActor, + PxVehiclePhysXSteerState*& physxSteerState, + PxVehiclePhysXConstraints*& physxConstraints, + PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& wheelRigidBody1dStates, + PxVehicleEngineState*& engineState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehiclePhysXActorBeginComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleCommandState* commands; + const PxVehicleEngineDriveTransmissionCommandState* transmissionCommands; + const PxVehicleGearboxParams* gearParams; + const PxVehicleGearboxState* gearState; + const PxVehicleEngineParams* engineParams; + PxVehiclePhysXActor* physxActor; + PxVehiclePhysXSteerState* physxSteerState; + PxVehiclePhysXConstraints* physxConstraints; + PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData wheelRigidBody1dStates; + PxVehicleEngineState* engineState; + + getDataForPhysXActorBeginComponent(axleDescription, commands, transmissionCommands, + gearParams, gearState, engineParams, + physxActor, physxSteerState, physxConstraints, + rigidBodyState, wheelRigidBody1dStates, engineState); + + if (physxActor->rigidBody->getScene()) // Considering case where actor is not in a scene and constraints get solved via immediate mode + { + PxVehiclePhysxActorWakeup(*commands, transmissionCommands, gearParams, gearState, + *physxActor->rigidBody, *physxSteerState); + + if (PxVehiclePhysxActorSleepCheck(*axleDescription, *physxActor->rigidBody, engineParams, + *rigidBodyState, *physxConstraints, wheelRigidBody1dStates, engineState)) + { + return false; + } + } + + PxVehicleReadRigidBodyStateFromPhysXActor(*physxActor->rigidBody, *rigidBodyState); + + return true; + } +}; + +/** +\brief Work items at the end of an update step for a PhysX actor based vehicle. + +Includes: + - Writing vehicle internal state to the PhysX actor. + - Keeping the vehicle awake if certain criteria are met. +*/ +class PxVehiclePhysXActorEndComponent : public PxVehicleComponent +{ +public: + + PxVehiclePhysXActorEndComponent() : PxVehicleComponent() {} + virtual ~PxVehiclePhysXActorEndComponent() {} + + /** + \brief Provide vehicle data items for this component. + + \param[out] axleDescription identifies the wheels on each axle. + \param[out] rigidBodyState is the state of the rigid body used by the Vehicle SDK. + \param[out] wheelParams describes the radius, mass etc. of the wheels. + \param[out] wheelShapeLocalPoses are the local poses in the wheel's frame to apply to the PxShape instances that represent the wheel + \param[out] wheelRigidBody1dStates describes the angular speed of the wheels. + \param[out] wheelLocalPoses describes the local poses of the wheels in the rigid body frame. + \param[out] gearState The gear state. Can be set to NULL if the vehicle does + not have gears. + \param[out] throttle The throttle command state (see #PxVehicleCommandState). + Can be set to NULL if the vehicle is not controlled through + PxVehicleCommandState. + \param[out] physxActor is the PxRigidBody instance associated with the vehicle. + */ + virtual void getDataForPhysXActorEndComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& wheelShapeLocalPoses, + PxVehicleArrayData& wheelRigidBody1dStates, + PxVehicleArrayData& wheelLocalPoses, + const PxVehicleGearboxState*& gearState, + const PxReal*& throttle, + PxVehiclePhysXActor*& physxActor) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + + PX_PROFILE_ZONE("PxVehiclePhysXActorEndComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData wheelParams; + PxVehicleArrayData wheelShapeLocalPoses; + PxVehicleArrayData wheelRigidBody1dStates; + PxVehicleArrayData wheelLocalPoses; + const PxVehicleGearboxState* gearState; + const PxReal* throttle; + PxVehiclePhysXActor* physxActor; + + getDataForPhysXActorEndComponent(axleDescription, rigidBodyState, + wheelParams, wheelShapeLocalPoses, wheelRigidBody1dStates, wheelLocalPoses, gearState, throttle, + physxActor); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + PxVehicleWriteWheelLocalPoseToPhysXWheelShape(wheelLocalPoses[wheelId].localPose, wheelShapeLocalPoses[wheelId], + physxActor->wheelShapes[wheelId]); + } + + if (context.getType() == PxVehicleSimulationContextType::ePHYSX) + { + const PxVehiclePhysXSimulationContext& physxContext = static_cast(context); + + PxVehicleWriteRigidBodyStateToPhysXActor(physxContext.physxActorUpdateMode, *rigidBodyState, dt, *physxActor->rigidBody); + + PxVehiclePhysxActorKeepAwakeCheck(*axleDescription, wheelParams, wheelRigidBody1dStates, + physxContext.physxActorWakeCounterThreshold, physxContext.physxActorWakeCounterResetValue, gearState, throttle, + *physxActor->rigidBody); + } + else + { + PX_ALWAYS_ASSERT(); + } + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorFunctions.h new file mode 100644 index 000000000..0522d49d3 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorFunctions.h @@ -0,0 +1,196 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxTransform.h" + +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ + +class PxRigidBody; +class PxShape; + +namespace vehicle2 +{ +#endif + +struct PxVehicleCommandState; +struct PxVehicleEngineDriveTransmissionCommandState; +struct PxVehicleEngineParams; +struct PxVehicleEngineState; +struct PxVehicleGearboxParams; +struct PxVehicleGearboxState; +struct PxVehicleRigidBodyState; +struct PxVehiclePhysXConstraints; +struct PxVehicleWheelLocalPose; +struct PxVehicleWheelParams; +struct PxVehicleWheelRigidBody1dState; +struct PxVehiclePhysXSteerState; + +/** +\brief Wake up the physx actor if the actor is asleep and the commands signal an intent to +change the state of the vehicle. +\param[in] commands are the brake, throttle and steer values that will drive the vehicle. +\param[in] transmissionCommands are the target gear and clutch values that will control + the transmission. If the target gear is different from the current gearbox + target gear, then the physx actor will get woken up. Can be set to NULL if the + vehicle does not have a gearbox or if this is not a desired behavior. If + specified, then gearParams and gearState has to be specifed too. +\param[in] gearParams The gearbox parameters. Can be set to NULL if the vehicle does + not have a gearbox and transmissionCommands is NULL. +\param[in] gearState The state of the gearbox. Can be set to NULL if the vehicle does + not have a gearbox and transmissionCommands is NULL. +\param[in] physxActor is the PxRigidBody instance associated with the vehicle. +\param[in,out] physxSteerState and commands are compared to +determine if the steering state has changed since the last call to PxVehiclePhysxActorWakeup(). +\note If the steering has changed, the actor will be woken up. +\note On exit from PxVehiclePhysxActorWakeup, physxSteerState.previousSteerCommand is assigned to the value +of commands.steer so that the steer state may be propagated to the subsequent call to PxVehiclePhysxActorWakeup(). +\note If physxSteerState.previousSteerCommand has value PX_VEHICLE_UNSPECIFIED_STEER_STATE, the steering state +is treated as though it has not changed. +*/ +void PxVehiclePhysxActorWakeup( + const PxVehicleCommandState& commands, + const PxVehicleEngineDriveTransmissionCommandState* transmissionCommands, + const PxVehicleGearboxParams* gearParams, + const PxVehicleGearboxState* gearState, + PxRigidBody& physxActor, + PxVehiclePhysXSteerState& physxSteerState); + +/** +\brief Check if the physx actor is sleeping and clear certain vehicle states if it is. + +\param[in] axleDescription identifies the wheels on each axle. +\param[in] physxActor is the PxRigidBody instance associated with the vehicle. +\param[in] engineParams The engine parameters. Can be set to NULL if the vehicle does + not have an engine. Must be specified, if engineState is specified. +\param[in,out] rigidBodyState is the state of the rigid body used by the Vehicle SDK. +\param[in,out] physxConstraints The state of the suspension limit and low speed tire constraints. + If the vehicle actor is sleeping and constraints are active, they will be + deactivated and marked as dirty. +\param[in,out] wheelRigidBody1dStates describes the angular speed of the wheels. +\param[out] engineState The engine state. Can be set to NULL if the vehicle does + not have an engine. If specified, then engineParams has to be specifed too. + The engine rotation speed will get set to the idle rotation speed if + the actor is sleeping. +\return True if the actor was sleeping, else false. +*/ +bool PxVehiclePhysxActorSleepCheck +(const PxVehicleAxleDescription& axleDescription, + const PxRigidBody& physxActor, + const PxVehicleEngineParams* engineParams, + PxVehicleRigidBodyState& rigidBodyState, + PxVehiclePhysXConstraints& physxConstraints, + PxVehicleArrayData& wheelRigidBody1dStates, + PxVehicleEngineState* engineState); + +/** +\brief Check if the physx actor has to be kept awake. + +Certain criteria should keep the vehicle physx actor awake, for example, if the +(mass normalized) rotational kinetic energy of the wheels is above a certain +threshold or if a gear change is pending or if throttle is applied. +This method will reset the wake counter of the physx actor to a specified value, +if any of the mentioned criteria are met. + +\note The physx actor's sleep threshold will be used as threshold to test against + for the energy criteria. + +\param[in] axleDescription identifies the wheels on each axle. +\param[in] wheelParams describes the radius, mass etc. of the wheels. +\param[in] wheelRigidBody1dStates describes the angular speed of the wheels. +\param[in] wakeCounterThreshold Once the wake counter of the physx actor falls + below this threshold, the method will start testing if the wake + counter needs to be reset. +\param[in] wakeCounterResetValue The value to set the physx actor wake counter + to, if any of the criteria to do so are met. +\param[in] gearState The gear state. Can be set to NULL if the vehicle does + not have gears or if the mentioned behavior is not desired. +\param[in] throttle The throttle command state (see #PxVehicleCommandState). + Can be set to NULL if the vehicle is not controlled through + PxVehicleCommandState or if the mentioned behavior is not desired. +\param[in] physxActor is the PxRigidBody instance associated with the vehicle. +*/ +void PxVehiclePhysxActorKeepAwakeCheck +(const PxVehicleAxleDescription& axleDescription, + const PxVehicleArrayData& wheelParams, + const PxVehicleArrayData& wheelRigidBody1dStates, + const PxReal wakeCounterThreshold, + const PxReal wakeCounterResetValue, + const PxVehicleGearboxState* gearState, + const PxReal* throttle, + PxRigidBody& physxActor); + + +/** +\brief Read the rigid body state from a PhysX actor. +\param[in] physxActor is a reference to a PhysX actor. +\param[out] rigidBodyState is the state of the rigid body used by the Vehicle SDK. +*/ +void PxVehicleReadRigidBodyStateFromPhysXActor +(const PxRigidBody& physxActor, + PxVehicleRigidBodyState& rigidBodyState); + +/** +\brief Update the local pose of a PxShape that is associated with a wheel. +\param[in] wheelLocalPose describes the local pose of each wheel in the rigid body frame. +\param[in] wheelShapeLocalPose describes the local pose to apply to the PxShape instance in the wheel's frame. +\param[in] shape is the target PxShape. +*/ +void PxVehicleWriteWheelLocalPoseToPhysXWheelShape +(const PxTransform& wheelLocalPose, const PxTransform& wheelShapeLocalPose, PxShape* shape); + +/** +\brief Write the rigid body state to a PhysX actor. +\param[in] physxActorUpdateMode controls whether the PhysX actor is to be updated with +instantaneous velocity changes or with accumulated accelerations to be applied in +the next simulation step of the associated PxScene. +\param[in] rigidBodyState is the state of the rigid body. +\param[in] dt is the simulation time that has elapsed since the last call to +PxVehicleWriteRigidBodyStateToPhysXActor(). +\param[out] physXActor is a reference to the PhysX actor. +*/ +void PxVehicleWriteRigidBodyStateToPhysXActor +(const PxVehiclePhysXActorUpdateMode::Enum physxActorUpdateMode, + const PxVehicleRigidBodyState& rigidBodyState, + const PxReal dt, + PxRigidBody& physXActor); + + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorHelpers.h new file mode 100644 index 000000000..b663b7619 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorHelpers.h @@ -0,0 +1,205 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "PxFiltering.h" +#include "PxShape.h" + +#if !PX_DOXYGEN +namespace physx +{ + +class PxGeometry; +class PxMaterial; +struct PxCookingParams; + +namespace vehicle2 +{ +#endif + +struct PxVehicleRigidBodyParams; +struct PxVehicleAxleDescription; +struct PxVehicleWheelParams; +struct PxVehiclePhysXActor; +struct PxVehicleFrame; +struct PxVehicleSuspensionParams; + +class PxVehiclePhysXRigidActorParams +{ + PX_NOCOPY(PxVehiclePhysXRigidActorParams) + +public: + + PxVehiclePhysXRigidActorParams(const PxVehicleRigidBodyParams& _physxActorRigidBodyParams, const char* _physxActorName) + : rigidBodyParams(_physxActorRigidBodyParams), + physxActorName(_physxActorName) + { + } + + const PxVehicleRigidBodyParams& rigidBodyParams; + const char* physxActorName; +}; + +class PxVehiclePhysXRigidActorShapeParams +{ + PX_NOCOPY(PxVehiclePhysXRigidActorShapeParams) + +public: + + PxVehiclePhysXRigidActorShapeParams + (const PxGeometry& _geometry, const PxTransform& _localPose, const PxMaterial& _material, + const PxShapeFlags _flags, const PxFilterData& _simulationFilterData, const PxFilterData& _queryFilterData) + : geometry(_geometry), + localPose(_localPose), + material(_material), + flags(_flags), + simulationFilterData(_simulationFilterData), + queryFilterData(_queryFilterData) + { + } + + const PxGeometry& geometry; + const PxTransform& localPose; + const PxMaterial& material; + PxShapeFlags flags; + PxFilterData simulationFilterData; + PxFilterData queryFilterData; +}; + +class PxVehiclePhysXWheelParams +{ + PX_NOCOPY(PxVehiclePhysXWheelParams) + +public: + + PxVehiclePhysXWheelParams(const PxVehicleAxleDescription& _axleDescription, const PxVehicleWheelParams* _wheelParams) + : axleDescription(_axleDescription), + wheelParams(_wheelParams) + { + } + + const PxVehicleAxleDescription& axleDescription; + const PxVehicleWheelParams* wheelParams; +}; + +class PxVehiclePhysXWheelShapeParams +{ + PX_NOCOPY(PxVehiclePhysXWheelShapeParams) + +public: + + PxVehiclePhysXWheelShapeParams(const PxMaterial& _material, const PxShapeFlags _flags, const PxFilterData _simulationFilterData, const PxFilterData _queryFilterData) + : material(_material), + flags(_flags), + simulationFilterData(_simulationFilterData), + queryFilterData(_queryFilterData) + { + } + + const PxMaterial& material; + PxShapeFlags flags; + PxFilterData simulationFilterData; + PxFilterData queryFilterData; +}; + +/** +\brief Create a PxRigidDynamic instance, instantiate it with desired properties and populate it with PxShape instances. +\param[in] vehicleFrame describes the frame of the vehicle. +\param[in] rigidActorParams describes the mass and moment of inertia of the rigid body. +\param[in] rigidActorCmassLocalPose specifies the mapping between actor and rigid body frame. +\param[in] rigidActorShapeParams describes the collision geometry associated with the rigid body. +\param[in] wheelParams describes the radius and half-width of the wheels. +\param[in] wheelShapeParams describes the PxMaterial and PxShapeFlags to apply to the wheel shapes. +\param[in] physics is a PxPhysics instance. +\param[in] params is a PxCookingParams instance +\param[in] vehiclePhysXActor is a record of the PxRigidDynamic and PxShape instances instantiated. +\note This is an alternative to PxVehiclePhysXArticulationLinkCreate. +\note PxVehiclePhysXActorCreate primarily serves as an illustration of the instantiation of the PhysX class instances +required to simulate a vehicle with a PxRigidDynamic. +\see PxVehiclePhysXActorDestroy +*/ +void PxVehiclePhysXActorCreate +(const PxVehicleFrame& vehicleFrame, + const PxVehiclePhysXRigidActorParams& rigidActorParams, const PxTransform& rigidActorCmassLocalPose, + const PxVehiclePhysXRigidActorShapeParams& rigidActorShapeParams, + const PxVehiclePhysXWheelParams& wheelParams, const PxVehiclePhysXWheelShapeParams& wheelShapeParams, + PxPhysics& physics, const PxCookingParams& params, + PxVehiclePhysXActor& vehiclePhysXActor); + + +/** +\brief Configure an actor so that it is ready for vehicle simulation. +\param[in] rigidActorParams describes the mass and moment of inertia of the rigid body. +\param[in] rigidActorCmassLocalPose specifies the mapping between actor and rigid body frame. +\param[out] rigidBody is the body to be prepared for simulation. +*/ +void PxVehiclePhysXActorConfigure +(const PxVehiclePhysXRigidActorParams& rigidActorParams, const PxTransform& rigidActorCmassLocalPose, + PxRigidBody& rigidBody); + +/** +\brief Create a PxArticulationReducedCoordinate and a single PxArticulationLink, +instantiate the PxArticulationLink with desired properties and populate it with PxShape instances. +\param[in] vehicleFrame describes the frame of the vehicle. +\param[in] rigidActorParams describes the mass and moment of inertia of the rigid body. +\param[in] rigidActorCmassLocalPose specifies the mapping between actor and rigid body frame. +\param[in] rigidActorShapeParams describes the collision geometry associated with the rigid body. +\param[in] wheelParams describes the radius and half-width of the wheels. +\param[in] wheelShapeParams describes the PxMaterial and PxShapeFlags to apply to the wheel shapes. +\param[in] physics is a PxPhysics instance. +\param[in] params is a PxCookingParams instance +\param[in] vehiclePhysXActor is a record of the PxArticulationReducedCoordinate, PxArticulationLink and PxShape instances instantiated. +\note This is an alternative to PxVehiclePhysXActorCreate. +\note PxVehiclePhysXArticulationLinkCreate primarily serves as an illustration of the instantiation of the PhysX class instances +required to simulate a vehicle as part of an articulated ensemble. +\see PxVehiclePhysXActorDestroy +*/ +void PxVehiclePhysXArticulationLinkCreate +(const PxVehicleFrame& vehicleFrame, + const PxVehiclePhysXRigidActorParams& rigidActorParams, const PxTransform& rigidActorCmassLocalPose, + const PxVehiclePhysXRigidActorShapeParams& rigidActorShapeParams, + const PxVehiclePhysXWheelParams& wheelParams, const PxVehiclePhysXWheelShapeParams& wheelShapeParams, + PxPhysics& physics, const PxCookingParams& params, + PxVehiclePhysXActor& vehiclePhysXActor); + +/** +\brief Release the PxRigidDynamic, PxArticulationReducedCoordinate, PxArticulationLink and PxShape instances +instantiated by PxVehiclePhysXActorCreate or PxVehiclePhysXArticulationLinkCreate. +\param[in] vehiclePhysXActor is a description of the PhysX instances to be released. +*/ +void PxVehiclePhysXActorDestroy(PxVehiclePhysXActor& vehiclePhysXActor); + + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorStates.h new file mode 100644 index 000000000..894b56ae2 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxActor/PxVehiclePhysXActorStates.h @@ -0,0 +1,94 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxMemory.h" + +#include "PxRigidBody.h" + +#include "vehicle2/PxVehicleLimits.h" + +#if !PX_DOXYGEN +namespace physx +{ + +class PxShape; + +namespace vehicle2 +{ +#endif + +/** +\brief A description of the PhysX actor and shapes that represent the vehicle in an associated PxScene. +*/ +struct PxVehiclePhysXActor +{ + /** + \brief The PhysX rigid body that represents the vehcle in the associated PhysX scene. + \note PxActorFlag::eDISABLE_GRAVITY must be set true on the PxRigidBody + */ + PxRigidBody* rigidBody; + + /** + \brief An array of shapes with one shape pointer (or NULL) for each wheel. + */ + PxShape* wheelShapes[PxVehicleLimits::eMAX_NB_WHEELS]; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehiclePhysXActor)); + } +}; + + +#define PX_VEHICLE_UNSPECIFIED_STEER_STATE PX_MAX_F32 + +/** +\brief A description of the previous steer command applied to the vehicle. +*/ +struct PxVehiclePhysXSteerState +{ + + /** + \brief The steer command that was most previously applied to the vehicle. + */ + PxReal previousSteerCommand; + + PX_FORCE_INLINE void setToDefault() + { + previousSteerCommand = PX_VEHICLE_UNSPECIFIED_STEER_STATE; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintComponents.h new file mode 100644 index 000000000..84545459c --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintComponents.h @@ -0,0 +1,119 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h" +#include "vehicle2/suspension/PxVehicleSuspensionParams.h" +#include "vehicle2/suspension/PxVehicleSuspensionStates.h" + +#include "PxVehiclePhysXConstraintFunctions.h" +#include "PxVehiclePhysXConstraintHelpers.h" +#include "PxVehiclePhysXConstraintStates.h" +#include "PxVehiclePhysXConstraintParams.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +class PxVehiclePhysXConstraintComponent : public PxVehicleComponent +{ +public: + PxVehiclePhysXConstraintComponent() : PxVehicleComponent() {} + virtual ~PxVehiclePhysXConstraintComponent() {} + + virtual void getDataForPhysXConstraintComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& suspensionParams, + PxVehicleArrayData& suspensionLimitParams, + PxVehicleArrayData& suspensionStates, + PxVehicleArrayData& suspensionComplianceStates, + PxVehicleArrayData& wheelRoadGeomStates, + PxVehicleArrayData& tireDirectionStates, + PxVehicleArrayData& tireStickyStates, + PxVehiclePhysXConstraints*& constraints) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + PX_PROFILE_ZONE("PxVehiclePhysXConstraintComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData suspensionParams; + PxVehicleArrayData suspensionLimitParams; + PxVehicleArrayData suspensionStates; + PxVehicleArrayData suspensionComplianceStates; + PxVehicleArrayData wheelRoadGeomStates; + PxVehicleArrayData tireDirectionStates; + PxVehicleArrayData tireStickyStates; + PxVehiclePhysXConstraints* constraints; + + getDataForPhysXConstraintComponent(axleDescription, rigidBodyState, + suspensionParams, suspensionLimitParams, suspensionStates, suspensionComplianceStates, + wheelRoadGeomStates, tireDirectionStates, tireStickyStates, + constraints); + + PxVehicleConstraintsDirtyStateUpdate(*constraints); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + PxVehiclePhysXConstraintStatesUpdate( + suspensionParams[wheelId], suspensionLimitParams[wheelId], + suspensionStates[wheelId], suspensionComplianceStates[wheelId], + wheelRoadGeomStates[wheelId].plane.n, + context.tireStickyParams.stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].damping, + context.tireStickyParams.stickyParams[PxVehicleTireDirectionModes::eLATERAL].damping, + tireDirectionStates[wheelId], tireStickyStates[wheelId], + *rigidBodyState, + constraints->constraintStates[wheelId]); + } + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintFunctions.h new file mode 100644 index 000000000..2aa05e4f2 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintFunctions.h @@ -0,0 +1,88 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleSuspensionParams; +struct PxVehiclePhysXSuspensionLimitConstraintParams; +struct PxVehicleSuspensionState; +struct PxVehicleSuspensionComplianceState; +struct PxVehicleTireDirectionState; +struct PxVehicleTireStickyState; +struct PxVehicleRigidBodyState; +struct PxVehiclePhysXConstraintState; + +/** +\brief Read constraint data from the vehicle's internal state for a single wheel and write it to a +structure that will be read by the associated PxScene and used to impose the constraints during the next +PxScene::simulate() step. +\param[in] suspensionParams describes the suspension frame. +\param[in] suspensionLimitParams describes the restitution value applied to any constraint triggered by +the suspension travel limit. +\param[in] suspensionState describes the excess suspension compression beyond the suspension travel limit that will be +resolved with a constraint. +\param[in] suspensionComplianceState describes the effect of suspension compliance on the effective application point +of the suspension force. +\param[in] groundPlaneNormal The normal direction of the ground plane the wheel is driving on. A normalized vector is + expected. +\param[in] tireStickyDampingLong The damping coefficient to use in the constraint to approach a zero target velocity + along the longitudinal tire axis. +\param[in] tireStickyDampingLat Same concept as tireStickyDampingLong but for the lateral tire axis. +\param[in] tireDirectionState describes the longitudinal and lateral directions of the tire in the world frame. +\param[in] tireStickyState describes the low speed state of the tire in the longitudinal and lateral directions. +\param[in] rigidBodyState describes the pose of the rigid body. +\param[out] constraintState is the data structure that will be read by the associated PxScene in the next call to +PxScene::simulate(). +\note Constraints include suspension constraints to account for suspension travel limit and sticky +tire constraints that bring the vehicle to rest at low longitudinal and lateral speed. +*/ +void PxVehiclePhysXConstraintStatesUpdate +(const PxVehicleSuspensionParams& suspensionParams, + const PxVehiclePhysXSuspensionLimitConstraintParams& suspensionLimitParams, + const PxVehicleSuspensionState& suspensionState, const PxVehicleSuspensionComplianceState& suspensionComplianceState, + const PxVec3& groundPlaneNormal, + const PxReal tireStickyDampingLong, const PxReal tireStickyDampingLat, + const PxVehicleTireDirectionState& tireDirectionState, const PxVehicleTireStickyState& tireStickyState, + const PxVehicleRigidBodyState& rigidBodyState, + PxVehiclePhysXConstraintState& constraintState); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h new file mode 100644 index 000000000..de3af744e --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h @@ -0,0 +1,88 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxPreprocessor.h" + + +#if !PX_DOXYGEN +namespace physx +{ + +class PxPhysics; +class PxRigidBody; + +namespace vehicle2 +{ +#endif + +struct PxVehicleAxleDescription; +struct PxVehiclePhysXConstraints; + +/** +\brief Instantiate the PhysX custom constraints. + +Custom constraints will resolve excess suspension compression and velocity constraints that serve as +a replacement low speed tire model. + +\param[in] axleDescription describes the axles of the vehicle and the wheels on each axle. +\param[in] physics is a PxPhysics instance. +\param[in] physxActor is the vehicle's PhysX representation as a PxRigidBody +\param[in] vehicleConstraints is a wrapper class that holds pointers to PhysX objects required to implement the custom constraint. +*/ +void PxVehicleConstraintsCreate +(const PxVehicleAxleDescription& axleDescription, + PxPhysics& physics, PxRigidBody& physxActor, + PxVehiclePhysXConstraints& vehicleConstraints); + +/** +\brief To ensure the constraints are processed by the PhysX scene they are marked as dirty prior to each simulate step. + +\param[in] vehicleConstraints is a wrapper class that holds pointers to PhysX objects required to implement the custom constraint. + +\see PxVehicleConstraintsCreate +*/ +void PxVehicleConstraintsDirtyStateUpdate +(PxVehiclePhysXConstraints& vehicleConstraints); + +/** +\brief Destroy the PhysX custom constraints. + +\param[in,out] vehicleConstraints describes the PhysX custom constraints to be released. + +\see PxVehicleConstraintsCreate +*/ +void PxVehicleConstraintsDestroy +(PxVehiclePhysXConstraints& vehicleConstraints); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h new file mode 100644 index 000000000..d882a7d70 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h @@ -0,0 +1,106 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleFrame; +struct PxVehicleScale; + +/** +\brief A description of the PhysX models employed to resolve suspension limit constraints. +\see PxVehiclePhysXConstraintState +*/ +struct PxVehiclePhysXSuspensionLimitConstraintParams +{ + /** + \brief restitution is used by the restitution model used to generate a target velocity when resolving suspension limit + constraints. + \note A value of 0.0 means that the restitution model is not employed. + \note Restitution has no effect if directionForSuspensionLimitConstraint has value Enum::eNONE. + \see Px1DConstraintFlag::eRESTITUTION + \see Px1DConstraint::RestitutionModifiers::restitution + */ + PxReal restitution; + + /** + \brief Set the direction to apply a constraint impulse when the suspension cannot place the wheel on the ground + and simultaneously respect the limits of suspension travel. The choices are to push along the ground normal to resolve the + geometric error or to push along the suspension direction. The former choice can be thought of as mimicing a force applied + by the tire's contact with the ground, while the latter can be thought of as mimicing a force arising from a suspension limit spring. + When the ground normal and the suspension direction are approximately aligned, both do an equivalent job of maintaining the wheel above + the ground. When the vehicle is on its side, eSUSPENSION does a better job of keeping the wheels above + the ground but comes at the cost of an unnaturally strong torque that can lead to unwanted self-righting behaviour. + eROAD_GEOMETRY_NORMAL is a good choice to avoid self-righting behaviour and still do a reasonable job at maintaining + the wheel above the ground in the event that the vehicle is tending towards a roll onto its side. + eNONE should be chosen if it is desired that no extra impulse is applied when the suspension alone cannot keep the wheels above + the ground plane. + */ + enum DirectionSpecifier + { + eSUSPENSION, + eROAD_GEOMETRY_NORMAL, + eNONE + }; + DirectionSpecifier directionForSuspensionLimitConstraint; + + PX_FORCE_INLINE PxVehiclePhysXSuspensionLimitConstraintParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL( + PxVehiclePhysXSuspensionLimitConstraintParams::eSUSPENSION == directionForSuspensionLimitConstraint || + PxVehiclePhysXSuspensionLimitConstraintParams::eROAD_GEOMETRY_NORMAL == directionForSuspensionLimitConstraint || + PxVehiclePhysXSuspensionLimitConstraintParams::eNONE == directionForSuspensionLimitConstraint, "PxVehiclePhysXSuspensionLimitConstraintParams.directionForSuspensionLimitConstraint must have legal value", false); + PX_CHECK_AND_RETURN_VAL(restitution >= 0.0f && restitution <= 1.0f, "PxVehiclePhysXSuspensionLimitConstraintParams.restitution must be in range [0, 1]", false); + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h new file mode 100644 index 000000000..3b825b5df --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h @@ -0,0 +1,353 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxAssert.h" +#include "foundation/PxTransform.h" +#include "extensions/PxConstraintExt.h" + +#include "vehicle2/PxVehicleLimits.h" +#include "vehicle2/tire/PxVehicleTireStates.h" + +#include "PxConstraint.h" +#include "PxConstraintDesc.h" + +#if !PX_DOXYGEN +namespace physx +{ + +class PxConstraint; + +namespace vehicle2 +{ +#endif + + +/** +\brief A description of the number of PxConstraintConnector instances per vehicle required to maintain suspension limit +and sticky tire instances. +*/ +struct PxVehiclePhysXConstraintLimits +{ + enum Enum + { + eNB_DOFS_PER_PXCONSTRAINT = 12, + eNB_DOFS_PER_WHEEL = 3, + eNB_WHEELS_PER_PXCONSTRAINT = eNB_DOFS_PER_PXCONSTRAINT / eNB_DOFS_PER_WHEEL, + eNB_CONSTRAINTS_PER_VEHICLE = (PxVehicleLimits::eMAX_NB_WHEELS + (eNB_WHEELS_PER_PXCONSTRAINT - 1)) / (eNB_WHEELS_PER_PXCONSTRAINT) + }; +}; + +/** +\brief PxVehiclePhysXConstraintState is a data structure used to write +constraint data to the internal state of the associated PxScene. +\see Px1dConstraint +*/ +struct PxVehiclePhysXConstraintState +{ + /** + \brief a boolean describing whether to trigger a low speed constraint along the tire longitudinal and lateral directions. + */ + bool tireActiveStatus[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + /** + \brief linear component of velocity jacobian in world space for the tire's longitudinal and lateral directions. + */ + PxVec3 tireLinears[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + /** + \brief angular component of velocity jacobian in world space for the tire's longitudinal and lateral directions. + */ + PxVec3 tireAngulars[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + /** + \brief damping coefficient applied to the tire's longitudinal and lateral velocities. + + The constraint sets a target velocity of 0 and the damping coefficient will impact the size of the + impulse applied to reach the target. Since damping acts as a stiffness with respect to the velocity, + too large a value can cause instabilities. + */ + PxReal tireDamping[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + + /** + \brief a boolean describing whether to trigger a suspension limit constraint. + */ + bool suspActiveStatus; + /** + \brief linear component of velocity jacobian in the world frame. + */ + PxVec3 suspLinear; + /** + \brief angular component of velocity jacobian in the world frame. + */ + PxVec3 suspAngular; + /** + \brief the excess suspension compression to be resolved by the constraint that cannot be resolved due to the travel limit + of the suspension spring. + + \note The expected error value is the excess suspension compression projected onto the ground plane normal and should have + a negative sign. + */ + PxReal suspGeometricError; + /** + \brief restitution value of the restitution model used to generate a target velocity that will resolve the geometric error. + \note A value of 0.0 means that the restitution model is not employed. + \see Px1DConstraintFlag::eRESTITUTION + \see Px1DConstraint::RestitutionModifiers::restitution + */ + PxReal restitution; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehiclePhysXConstraintState)); + } +}; + +//TAG:solverprepshader +PX_FORCE_INLINE PxU32 vehicleConstraintSolverPrep +(Px1DConstraint* constraints, + PxVec3p& body0WorldOffset, + PxU32 maxConstraints, + PxConstraintInvMassScale&, + const void* constantBlock, + const PxTransform& bodyAToWorld, + const PxTransform& bodyBToWorld, + bool, + PxVec3p& cA2w, PxVec3p& cB2w) +{ + PX_UNUSED(maxConstraints); + PX_UNUSED(body0WorldOffset); + PX_UNUSED(bodyBToWorld); + PX_ASSERT(bodyAToWorld.isValid()); PX_ASSERT(bodyBToWorld.isValid()); + + const PxVehiclePhysXConstraintState* data = static_cast(constantBlock); + PxU32 numActive = 0; + + //KS - the TGS solver will use raXn to try to add to the angular part of the linear constraints. + //We overcome this by setting the ra and rb offsets to be 0. + cA2w = bodyAToWorld.p; + cB2w = bodyBToWorld.p; + // note: this is only needed for PxSolverType::eTGS and even then it should not have an effect as + // long as a constraint raises Px1DConstraintFlag::eANGULAR_CONSTRAINT + + //Susp limit constraints. + for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT; i++) + { + if (data[i].suspActiveStatus) + { + // Going beyond max suspension compression should be treated similar to rigid body contacts. + // Thus setting up constraints that try to emulate such contacts. + // + // linear l = contact normal = n + // angular a = suspension force application offset x contact normal = cross(r, n) + // + // velocity at contact: + // vl: part from linear vehicle velocity v + // vl = dot(n, v) = dot(l, v) + // + // va: part from angular vehicle velocity w + // va = dot(n, cross(w, r)) = dot(w, cross(r, n)) = dot(w, a) + // + // ve: part from excess suspension compression + // ve = (geomError / dt) (note: geomError is expected to be negative here) + // + // velocity target vt = vl + va + ve + // => should become 0 by applying positive impulse along l. If vt is positive, + // nothing will happen as a negative impulse would have to be applied (but + // min impulse is set to 0). If vt is negative, a positive impulse will get + // applied to push vt towards 0. + // + + Px1DConstraint& p = constraints[numActive]; + p.linear0 = data[i].suspLinear; + p.angular0 = data[i].suspAngular; + p.geometricError = data[i].suspGeometricError; + p.linear1 = PxVec3(0); + p.angular1 = PxVec3(0); + p.minImpulse = 0; + p.maxImpulse = FLT_MAX; + p.velocityTarget = 0; + p.solveHint = PxConstraintSolveHint::eINEQUALITY; + + // note: this is only needed for PxSolverType::eTGS to not have the angular part + // be modified based on the linear part during substeps. Basically, it will + // disable the constraint re-projection etc. to emulate PxSolverType::ePGS. + p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT; + + if (data[i].restitution > 0.0f) + { + p.flags |= Px1DConstraintFlag::eRESTITUTION; + p.mods.bounce.restitution = data[i].restitution; + p.mods.bounce.velocityThreshold = -FLT_MAX; + } + numActive++; + } + } + + //Sticky tire friction constraints. + for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT; i++) + { + if (data[i].tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL]) + { + Px1DConstraint& p = constraints[numActive]; + p.linear0 = data[i].tireLinears[PxVehicleTireDirectionModes::eLONGITUDINAL]; + p.angular0 = data[i].tireAngulars[PxVehicleTireDirectionModes::eLONGITUDINAL]; + p.geometricError = 0.0f; + p.linear1 = PxVec3(0); + p.angular1 = PxVec3(0); + p.minImpulse = -FLT_MAX; + p.maxImpulse = FLT_MAX; + p.velocityTarget = 0.0f; + p.mods.spring.damping = data[i].tireDamping[PxVehicleTireDirectionModes::eLONGITUDINAL]; + // note: no stiffness specified as this will have no effect with geometricError=0 + p.flags = Px1DConstraintFlag::eSPRING | Px1DConstraintFlag::eACCELERATION_SPRING; + p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT; // see explanation of same flag usage further above + numActive++; + } + } + + //Sticky tire friction constraints. + for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT; i++) + { + if (data[i].tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL]) + { + Px1DConstraint& p = constraints[numActive]; + p.linear0 = data[i].tireLinears[PxVehicleTireDirectionModes::eLATERAL]; + p.angular0 = data[i].tireAngulars[PxVehicleTireDirectionModes::eLATERAL]; + p.geometricError = 0.0f; + p.linear1 = PxVec3(0); + p.angular1 = PxVec3(0); + p.minImpulse = -FLT_MAX; + p.maxImpulse = FLT_MAX; + p.velocityTarget = 0.0f; + p.mods.spring.damping = data[i].tireDamping[PxVehicleTireDirectionModes::eLATERAL]; + // note: no stiffness specified as this will have no effect with geometricError=0 + p.flags = Px1DConstraintFlag::eSPRING | Px1DConstraintFlag::eACCELERATION_SPRING; + p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT; // see explanation of same flag usage further above + numActive++; + } + } + + return numActive; +} + +PX_FORCE_INLINE void visualiseVehicleConstraint +(PxConstraintVisualizer &viz, + const void* constantBlock, + const PxTransform& body0Transform, + const PxTransform& body1Transform, + PxU32 flags) +{ + PX_UNUSED(&viz); + PX_UNUSED(constantBlock); + PX_UNUSED(body0Transform); + PX_UNUSED(body1Transform); + PX_UNUSED(flags); + PX_ASSERT(body0Transform.isValid()); + PX_ASSERT(body1Transform.isValid()); +} + +class PxVehicleConstraintConnector : public PxConstraintConnector +{ +public: + + PxVehicleConstraintConnector() : mVehicleConstraintState(NULL) {} + PxVehicleConstraintConnector(PxVehiclePhysXConstraintState* vehicleConstraintState) : mVehicleConstraintState(vehicleConstraintState) {} + ~PxVehicleConstraintConnector() {} + + void setConstraintState(PxVehiclePhysXConstraintState* constraintState) { mVehicleConstraintState = constraintState; } + + virtual void* prepareData() { return mVehicleConstraintState; } + virtual const void* getConstantBlock() const { return mVehicleConstraintState; } + virtual PxConstraintSolverPrep getPrep() const { return vehicleConstraintSolverPrep; } + + //Is this necessary if physx no longer supports double-buffering? + virtual void onConstraintRelease() { } + + //Can be empty functions. + virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream& pvdConnection, const PxConstraint* c, PxPvdUpdateType::Enum updateType) const + { + PX_UNUSED(pvdConnection); + PX_UNUSED(c); + PX_UNUSED(updateType); + return true; + } + virtual void updateOmniPvdProperties() const { } + virtual void onComShift(PxU32 actor) { PX_UNUSED(actor); } + virtual void onOriginShift(const PxVec3& shift) { PX_UNUSED(shift); } + virtual void* getExternalReference(PxU32& typeID) { typeID = PxConstraintExtIDs::eVEHICLE_JOINT; return this; } + virtual PxBase* getSerializable() { return NULL; } + +private: + + PxVehiclePhysXConstraintState* mVehicleConstraintState; +}; + +/** +\brief A mapping between constraint state data and the associated PxConstraint instances. +*/ +struct PxVehiclePhysXConstraints +{ + /** + \brief PxVehiclePhysXConstraintComponent writes to the constraintStates array and a + callback invoked by PxScene::simulate() reads a portion from it for a block of wheels + and writes that portion to an associated PxConstraint instance. + */ + PxVehiclePhysXConstraintState constraintStates[PxVehicleLimits::eMAX_NB_WHEELS]; + + /** + \brief PxVehiclePhysXConstraintComponent writes to the constraintStates array and a + callback invoked by PxScene::simulate() reads a portion from it for a block of wheels + and writes that portion to an associated PxConstraint instance. + */ + PxConstraint* constraints[PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE]; + + /** + \brief A constraint connector is necessary to connect each PxConstraint to a portion of the constraintStates array. + */ + PxVehicleConstraintConnector* constraintConnectors[PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE]; + + PX_FORCE_INLINE void setToDefault() + { + for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) + { + constraintStates[i].setToDefault(); + } + for(PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE; i++) + { + constraints[i] = NULL; + constraintConnectors[i] = NULL; + } + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryComponents.h new file mode 100644 index 000000000..e93b892c0 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryComponents.h @@ -0,0 +1,144 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "vehicle2/commands/PxVehicleCommandHelpers.h" +#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h" +#include "vehicle2/suspension/PxVehicleSuspensionParams.h" +#include "vehicle2/wheel/PxVehicleWheelParams.h" + +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +class PxVehiclePhysXRoadGeometrySceneQueryComponent : public PxVehicleComponent +{ +public: + PxVehiclePhysXRoadGeometrySceneQueryComponent() : PxVehicleComponent() {} + virtual ~PxVehiclePhysXRoadGeometrySceneQueryComponent() {} + + /** + \brief Provide vehicle data items for this component. + + \param[out] axleDescription identifies the wheels on each axle. + \param[out] roadGeomParams The road geometry parameters of the vehicle. + \param[out] steerResponseStates The steer response state of the wheels. + \param[out] rigidBodyState The pose, velocity etc. of the vehicle rigid body. + \param[out] wheelParams The wheel parameters for the wheels. + \param[out] suspensionParams The suspension parameters for the wheels. + \param[out] materialFrictionParams The tire friction tables for the wheels. + \param[out] roadGeometryStates The detected ground surface plane, friction value etc. for the wheels. + \param[out] physxRoadGeometryStates Optional buffer to store additional information about the query (like actor/shape that got hit etc.). + Set to empty if not desired. + */ + virtual void getDataForPhysXRoadGeometrySceneQueryComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehiclePhysXRoadGeometryQueryParams*& roadGeomParams, + PxVehicleArrayData& steerResponseStates, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& suspensionParams, + PxVehicleArrayData& materialFrictionParams, + PxVehicleArrayData& roadGeometryStates, + PxVehicleArrayData& physxRoadGeometryStates) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + + PX_PROFILE_ZONE("PxVehiclePhysXRoadGeometrySceneQueryComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehiclePhysXRoadGeometryQueryParams* roadGeomParams; + PxVehicleArrayData steerResponseStates; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData wheelParams; + PxVehicleArrayData suspensionParams; + PxVehicleArrayData materialFrictionParams; + PxVehicleArrayData roadGeometryStates; + PxVehicleArrayData physxRoadGeometryStates; + + getDataForPhysXRoadGeometrySceneQueryComponent(axleDescription, + roadGeomParams, steerResponseStates, rigidBodyState, + wheelParams, suspensionParams, materialFrictionParams, + roadGeometryStates, physxRoadGeometryStates); + + if (context.getType() == PxVehicleSimulationContextType::ePHYSX) + { + const PxVehiclePhysXSimulationContext& physxContext = static_cast(context); + + for(PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + const PxQueryFilterData* fdPtr = roadGeomParams->filterDataEntries ? (roadGeomParams->filterDataEntries + wheelId) : &roadGeomParams->defaultFilterData; + + PxVehiclePhysXRoadGeometryQueryUpdate( + wheelParams[wheelId], suspensionParams[wheelId], + roadGeomParams->roadGeometryQueryType, roadGeomParams->filterCallback, *fdPtr, + materialFrictionParams[wheelId], + steerResponseStates[wheelId], *rigidBodyState, + *physxContext.physxScene, physxContext.physxUnitCylinderSweepMesh, context.frame, + roadGeometryStates[wheelId], + !physxRoadGeometryStates.isEmpty() ? &physxRoadGeometryStates[wheelId] : NULL); + } + } + else + { + PX_ALWAYS_ASSERT(); + + for(PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + roadGeometryStates[wheelId].setToDefault(); + } + } + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.h new file mode 100644 index 000000000..2b5876a4f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.h @@ -0,0 +1,91 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxSimpleTypes.h" + +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +class PxScene; +class PxConvexMesh; + +namespace vehicle2 +{ +#endif + +struct PxVehicleWheelParams; +struct PxVehicleSuspensionParams; +struct PxVehiclePhysXRoadGeometryQueryState; +struct PxVehicleRigidBodyState; +struct PxVehicleFrame; +struct PxVehicleRoadGeometryState; + +/** +\brief Compute the plane of the road geometry under a wheel and the tire friction of the contact. +\param[in] wheelParams describes the radius and halfwidth of the wheel. +\param[in] suspParams describes the frame of the suspension and wheel and the maximum suspension travel. +\param[in] queryType describes what type of PhysX scene query to use (see #PxVehiclePhysXRoadGeometryQueryType). + If PxVehiclePhysXRoadGeometryQueryType::eNONE is used, no work will be done. +\param[in] filterCallback describes the filter callback to use for the PhysX scene query. NULL is a valid input. +\param[in] filterData describes the filter data to use for the PhysX scene query. +\param[in] materialFrictionParams describes a mapping between PxMaterial and friction in order to compute a tire friction value. +\param[in] wheelYawAngle is the yaw angle (in radians) of the wheel. +\param[in] rigidBodyState describes the pose of the rigid body. +\param[in] scene is the PhysX scene that will be queried by the scene query. +\param[in] unitCylinderSweepMesh is a convex cylindrical mesh of unit radius and half-width to be used in +the event that a sweep query is to be used. +\param[in] frame describes the lateral, longitudinal and vertical axes and is used to scale unitCylinderSweepMesh +by the wheel's radius and half-width. +\param[out] roadGeomState contains the plane and friction of the road geometry under the wheel. +\param[out] physxRoadGeometryState Optional buffer to store additional information about the query (like actor/shape that got hit etc.). + Set to NULL if not needed. +\note PxVehicleRoadGeometryState::hitState will have value false in the event that the there is no reachable road geometry under the wheel and +true if there is reachable road geometry under the wheel. Road geometry is considered reachable if the suspension can elongate from its +reference pose far enough to place wheel on the ground. +*/ +void PxVehiclePhysXRoadGeometryQueryUpdate +(const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspParams, + const PxVehiclePhysXRoadGeometryQueryType::Enum queryType, + PxQueryFilterCallback* filterCallback, const PxQueryFilterData& filterData, + const PxVehiclePhysXMaterialFrictionParams& materialFrictionParams, + const PxReal wheelYawAngle, const PxVehicleRigidBodyState& rigidBodyState, + const PxScene& scene, const PxConvexMesh* unitCylinderSweepMesh, + const PxVehicleFrame& frame, + PxVehicleRoadGeometryState& roadGeomState, + PxVehiclePhysXRoadGeometryQueryState* physxRoadGeometryState); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryHelpers.h new file mode 100644 index 000000000..f80959e7f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryHelpers.h @@ -0,0 +1,69 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxPreprocessor.h" + +#if !PX_DOXYGEN +namespace physx +{ + +class PxConvexMesh; +class PxPhysics; +struct PxCookingParams; + +namespace vehicle2 +{ +#endif + +struct PxVehicleFrame; + +/** +\brief Create a cylindrical mesh with unit radius and half-width. +\param[in] vehicleFrame is a description of the lateral and longitudinal axes. +\param[in] physics is a PxPhysics instance. +\param[in] params is a PxCookingParams instance +\return Return a PxConvexMesh instance that represents a convex hull with unit radius and half-width. +\see PxVehicleUnitCylinderSweepMeshDestroy +*/ +PxConvexMesh* PxVehicleUnitCylinderSweepMeshCreate(const PxVehicleFrame& vehicleFrame, PxPhysics& physics, const PxCookingParams& params); + +/** +\brief Release the mesh created with PxVehicleUnitCylinderSweepMeshCreate. +\param[in] mesh is a PxConvexMesh instance. +\see PxVehicleUnitCylinderSweepMeshCreate +*/ +void PxVehicleUnitCylinderSweepMeshDestroy(PxConvexMesh* mesh); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h new file mode 100644 index 000000000..8bccd7321 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h @@ -0,0 +1,174 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" + +#include "PxQueryFiltering.h" + +#if !PX_DOXYGEN +namespace physx +{ +class PxMaterial; + +namespace vehicle2 +{ +#endif + +struct PxVehicleFrame; +struct PxVehicleScale; + +/** +\brief PhysX scene queries may be raycasts or sweeps. +\note eNONE will result in no PhysX scene query. This option will not overwrite the associated PxVehicleRoadGeometryState. +*/ +struct PxVehiclePhysXRoadGeometryQueryType +{ + enum Enum + { + eNONE = 0, //!< Info about the road geometry below the wheel is provided by the user + eRAYCAST, //!< The road geometry below the wheel is analyzed using a raycast query + eSWEEP, //!< The road geometry below the wheel is analyzed using a sweep query + eMAX_NB + }; +}; + +/** +\brief A description of type of PhysX scene query and the filter data to apply to the query. +*/ +struct PxVehiclePhysXRoadGeometryQueryParams +{ + /** + \brief The default filter data to use for the physx scene query. + + If per wheel filter data is provided in #filterDataEntries, then this member + will be ignored. + + \see PxSceneQuerySystemBase::raycast + \see PxSceneQuerySystemBase::sweep + */ + PxQueryFilterData defaultFilterData; + + /** + \brief Array of filter data entries (one per wheel) to use for the physx scene query. + + A null pointer is allowed in which case #defaultFilterData will be used for all wheels. + + \see PxSceneQuerySystemBase::raycast + \see PxSceneQuerySystemBase::sweep + */ + PxQueryFilterData* filterDataEntries; + + /** + \brief A filter callback to be used by the physx scene query + \note A null pointer is allowed. + \see PxSceneQuerySystemBase::raycast + \see PxSceneQuerySystemBase::sweep + */ + PxQueryFilterCallback* filterCallback; + + /** + \brief A description of the type of physx scene query to employ. + \see PxSceneQuerySystemBase::raycast + \see PxSceneQuerySystemBase::sweep + */ + PxVehiclePhysXRoadGeometryQueryType::Enum roadGeometryQueryType; + + PX_FORCE_INLINE PxVehiclePhysXRoadGeometryQueryParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(roadGeometryQueryType < PxVehiclePhysXRoadGeometryQueryType::eMAX_NB, "PxVehiclePhysXRoadGeometryQueryParams.roadGeometryQueryType has illegal value", false); + return true; + } +}; + +/** +A mapping between PxMaterial and a friction value to be used by the tire model. +\see PxVehiclePhysXMaterialFrictionParams +*/ +struct PxVehiclePhysXMaterialFriction +{ + /** + \brief A PxMaterial instance that is to be mapped to a friction value. + */ + const PxMaterial* material; + + /** + \brief A friction value that is to be mapped to a PxMaterial instance. + \note friction must have value greater than or equal to zero. + + Range: [0, inf)
+ + \see PxVehicleTireGripState::friction + */ + PxReal friction; + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(friction >= 0.0f, "PxVehiclePhysXMaterialFriction.friction must be greater than or equal to zero", false); + return true; + } +}; + +/** +\brief A mappping between PxMaterial instance and friction for multiple PxMaterial intances. +*/ +struct PxVehiclePhysXMaterialFrictionParams +{ + PxVehiclePhysXMaterialFriction* materialFrictions; //!< An array of mappings between PxMaterial and friction. + PxU32 nbMaterialFrictions; //!< The number of mappings between PxMaterial and friction. + PxReal defaultFriction; //!< A default friction value to be used in the event that the PxMaterial under the tire is not found in the array #materialFrictions. + + PX_FORCE_INLINE bool isValid() const + { + for (PxU32 i = 0; i < nbMaterialFrictions; i++) + { + if (!materialFrictions[i].isValid()) + return false; + } + PX_CHECK_AND_RETURN_VAL(defaultFriction >= 0.0f, "PxVehiclePhysXMaterialFrictionParams.defaultFriction must be greater than or equal to zero", false); + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h new file mode 100644 index 000000000..a872bae01 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h @@ -0,0 +1,65 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxMemory.h" +#include "foundation/PxVec3.h" + +#if !PX_DOXYGEN +namespace physx +{ + +class PxRigidActor; +class PxShape; +class PxMaterial; + +namespace vehicle2 +{ +#endif + +struct PxVehiclePhysXRoadGeometryQueryState +{ + PxRigidActor* actor; //!< The actor that got hit by the query. + PxShape* shape; //!< The shape that got hit by the query. + PxMaterial* material; //!< The material at the hit point. + PxVec3 hitPosition; //!< The hit position in world space. + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehiclePhysXRoadGeometryQueryState)); + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdComponents.h new file mode 100644 index 000000000..c888f380f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdComponents.h @@ -0,0 +1,351 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleComponent.h" +#include "vehicle2/PxVehicleParams.h" +#include "PxVehiclePvdFunctions.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +#define VEHICLE_FLOAT_ARRAY_DATA(b) PxVehicleArrayData b; b.setEmpty(); +#define VEHICLE_ARRAY_DATA(a, b) PxVehicleArrayData b; b.setEmpty(); +#define VEHICLE_SIZED_ARRAY_DATA(a, b) PxVehicleSizedArrayData b; b.setEmpty(); + +class PxVehiclePVDComponent : public PxVehicleComponent +{ +public: + + PxVehiclePVDComponent() : PxVehicleComponent() , firstTime(true) {} + virtual ~PxVehiclePVDComponent() {} + + virtual void getDataForPVDComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleRigidBodyParams*& rbodyParams, const PxVehicleRigidBodyState*& rbodyState, + const PxVehicleSuspensionStateCalculationParams*& suspStateCalcParams, + PxVehicleSizedArrayData& brakeResponseParams, + const PxVehicleSteerCommandResponseParams*& steerResponseParams, + const PxVehicleAckermannParams*& ackermannParams, + PxVehicleArrayData& brakeResponseStates, + PxVehicleArrayData& steerResponseStates, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& wheelActuationStates, + PxVehicleArrayData& wheelRigidBody1dStates, + PxVehicleArrayData& wheelLocalPoses, + PxVehicleArrayData& roadGeomStates, + PxVehicleArrayData& suspParams, + PxVehicleArrayData& suspCompParams, + PxVehicleArrayData& suspForceParams, + PxVehicleArrayData& suspStates, + PxVehicleArrayData& suspCompStates, + PxVehicleArrayData& suspForces, + PxVehicleArrayData& tireForceParams, + PxVehicleArrayData& tireDirectionStates, + PxVehicleArrayData& tireSpeedStates, + PxVehicleArrayData& tireSlipStates, + PxVehicleArrayData& tireStickyStates, + PxVehicleArrayData& tireGripStates, + PxVehicleArrayData& tireCamberStates, + PxVehicleArrayData& tireForces, + PxVehicleSizedArrayData& antiRollForceParams, + const PxVehicleAntiRollTorque*& antiRollTorque, + const PxVehicleCommandState*& commandState, + const PxVehicleDirectDriveThrottleCommandResponseParams*& directDriveThrottleResponseParams, + const PxVehicleDirectDriveTransmissionCommandState*& directDriveTransmissionState, + PxVehicleArrayData& directDrivethrottleResponseState, + const PxVehicleClutchCommandResponseParams*& clutchResponseParams, + const PxVehicleClutchParams*& clutchParams, + const PxVehicleEngineParams*& engineParams, + const PxVehicleGearboxParams*& gearboxParams, + const PxVehicleAutoboxParams*& autoboxParams, + const PxVehicleMultiWheelDriveDifferentialParams*& multiWheelDiffParams, + const PxVehicleFourWheelDriveDifferentialParams*& fourWheelDiffParams, + const PxVehicleTankDriveDifferentialParams*& tankDiffParams, + const PxVehicleEngineDriveTransmissionCommandState*& engineDriveTransmissionState, + const PxVehicleTankDriveTransmissionCommandState*& tankDriveTransmissionState, + const PxVehicleClutchCommandResponseState*& clutchResponseState, + const PxVehicleEngineDriveThrottleCommandResponseState*& engineDriveThrottleResponseState, + const PxVehicleEngineState*& engineState, + const PxVehicleGearboxState*& gearboxState, + const PxVehicleAutoboxState*& autoboxState, + const PxVehicleDifferentialState*& diffState, + const PxVehicleClutchSlipState*& clutchSlipState, + PxVehicleArrayData& physxConstraintParams, + PxVehicleArrayData& physxMaterialFrictionParams, + const PxVehiclePhysXActor*& physxActor, + const PxVehiclePhysXRoadGeometryQueryParams*& physxRoadGeomQryParams, + PxVehicleArrayData& physxRoadGeomStates, + PxVehicleArrayData& physxConstraintStates, + const PxVehiclePhysXSteerState*& physxSteerState, + PxVehiclePvdObjectHandles*& objectHandles) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_UNUSED(dt); + PX_UNUSED(context); + + OmniPvdWriter* pvdWriter = context.pvdContext.writer; + + if(!context.pvdContext.attributeHandles || !pvdWriter) + return true; + + const PxVehicleAxleDescription* axleDesc = NULL; + const PxVehicleRigidBodyParams* rbodyParams = NULL; + const PxVehicleRigidBodyState* rbodyState = NULL; + const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams = NULL; + VEHICLE_SIZED_ARRAY_DATA(PxVehicleBrakeCommandResponseParams, brakeResponseParams); + const PxVehicleSteerCommandResponseParams* steerResponseParams = NULL; + const PxVehicleAckermannParams* ackermannParams = NULL; + VEHICLE_FLOAT_ARRAY_DATA(brakeResponseStates); + VEHICLE_FLOAT_ARRAY_DATA(steerResponseStates); + VEHICLE_ARRAY_DATA(PxVehicleWheelParams, wheelParams); + VEHICLE_ARRAY_DATA(PxVehicleWheelActuationState, wheelActuationStates); + VEHICLE_ARRAY_DATA(PxVehicleWheelRigidBody1dState, wheelRigidBody1dStates); + VEHICLE_ARRAY_DATA(PxVehicleWheelLocalPose, wheelLocalPoses); + VEHICLE_ARRAY_DATA(PxVehicleRoadGeometryState, roadGeomStates); + VEHICLE_ARRAY_DATA(PxVehicleSuspensionParams, suspParams); + VEHICLE_ARRAY_DATA(PxVehicleSuspensionComplianceParams, suspComplianceParams); + VEHICLE_ARRAY_DATA(PxVehicleSuspensionForceParams, suspForceParams); + VEHICLE_ARRAY_DATA(PxVehicleSuspensionState, suspStates); + VEHICLE_ARRAY_DATA(PxVehicleSuspensionComplianceState, suspComplianceStates); + VEHICLE_ARRAY_DATA(PxVehicleSuspensionForce, suspForces); + VEHICLE_ARRAY_DATA(PxVehicleTireForceParams, tireForceParams); + VEHICLE_ARRAY_DATA(PxVehicleTireDirectionState, tireDirectionStates); + VEHICLE_ARRAY_DATA(PxVehicleTireSpeedState, tireSpeedStates); + VEHICLE_ARRAY_DATA(PxVehicleTireSlipState, tireSlipStates); + VEHICLE_ARRAY_DATA(PxVehicleTireStickyState, tireStickyStates); + VEHICLE_ARRAY_DATA(PxVehicleTireGripState, tireGripStates); + VEHICLE_ARRAY_DATA(PxVehicleTireCamberAngleState, tireCamberStates); + VEHICLE_ARRAY_DATA(PxVehicleTireForce, tireForces); + VEHICLE_SIZED_ARRAY_DATA(PxVehicleAntiRollForceParams, antiRollParams); + const PxVehicleAntiRollTorque* antiRollTorque = NULL; + const PxVehicleCommandState* commandState = NULL; + const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams = NULL; + const PxVehicleDirectDriveTransmissionCommandState* directDriveTransmissionState = NULL; + VEHICLE_FLOAT_ARRAY_DATA(directDrivethrottleResponseState); + const PxVehicleClutchCommandResponseParams* clutchResponseParams = NULL; + const PxVehicleClutchParams* clutchParams = NULL; + const PxVehicleEngineParams* engineParams = NULL; + const PxVehicleGearboxParams* gearboxParams = NULL; + const PxVehicleAutoboxParams* autoboxParams = NULL; + const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams = NULL; + const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffParams = NULL; + const PxVehicleTankDriveDifferentialParams* tankDiffParams = NULL; + const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState = NULL; + const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState = NULL; + const PxVehicleClutchCommandResponseState* clutchResponseState = NULL; + const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState = NULL; + const PxVehicleEngineState* engineState = NULL; + const PxVehicleGearboxState* gearboxState = NULL; + const PxVehicleAutoboxState* autoboxState = NULL; + const PxVehicleDifferentialState* diffState = NULL; + const PxVehicleClutchSlipState* clutchSlipState = NULL; + VEHICLE_ARRAY_DATA(PxVehiclePhysXSuspensionLimitConstraintParams, physxConstraintParams); + VEHICLE_ARRAY_DATA(PxVehiclePhysXMaterialFrictionParams, physxMaterialFrictionParams); + const PxVehiclePhysXActor* physxActor = NULL; + const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams = NULL; + VEHICLE_ARRAY_DATA(PxVehiclePhysXRoadGeometryQueryState, physxRoadGeomStates); + VEHICLE_ARRAY_DATA(PxVehiclePhysXConstraintState, physxConstraintStates); + const PxVehiclePhysXSteerState* physxSteerState = NULL; + PxVehiclePvdObjectHandles* omniPvdObjectHandles = NULL; + + getDataForPVDComponent( + axleDesc, + rbodyParams, rbodyState, + suspStateCalcParams, + brakeResponseParams, steerResponseParams, ackermannParams, + brakeResponseStates, steerResponseStates, + wheelParams, + wheelActuationStates, wheelRigidBody1dStates, wheelLocalPoses, + roadGeomStates, + suspParams, suspComplianceParams, suspForceParams, + suspStates, suspComplianceStates, + suspForces, + tireForceParams, + tireDirectionStates, tireSpeedStates, tireSlipStates, tireStickyStates, tireGripStates, tireCamberStates, + tireForces, + antiRollParams, antiRollTorque, + commandState, + directDriveThrottleResponseParams, directDriveTransmissionState, directDrivethrottleResponseState, + clutchResponseParams, clutchParams, engineParams, gearboxParams, autoboxParams, + multiWheelDiffParams, fourWheelDiffParams, tankDiffParams, + engineDriveTransmissionCommandState, tankDriveTransmissionCommandState, + clutchResponseState, throttleResponseState, engineState, gearboxState, autoboxState, diffState, clutchSlipState, + physxConstraintParams, physxMaterialFrictionParams, + physxActor, physxRoadGeomQryParams, physxRoadGeomStates, physxConstraintStates, physxSteerState, + omniPvdObjectHandles); + + if(!omniPvdObjectHandles) + return true; + + if(firstTime) + { + PxVehiclePvdRigidBodyRegister( + rbodyParams, rbodyState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdSuspensionStateCalculationParamsRegister( + suspStateCalcParams, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdCommandResponseRegister( + brakeResponseParams, steerResponseParams, ackermannParams, + brakeResponseStates, steerResponseStates, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdWheelAttachmentsRegister( + *axleDesc, + wheelParams, wheelActuationStates, wheelRigidBody1dStates, wheelLocalPoses, + roadGeomStates, + suspParams, suspComplianceParams, suspForceParams, suspStates, suspComplianceStates, + suspForces, + tireForceParams, + tireDirectionStates, tireSpeedStates, tireSlipStates, tireStickyStates, tireGripStates, tireCamberStates, + tireForces, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdAntiRollsRegister( + antiRollParams, antiRollTorque, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + if (engineParams) + { + PxVehiclePvdEngineDrivetrainRegister( + commandState, engineDriveTransmissionCommandState, tankDriveTransmissionCommandState, + clutchResponseParams, clutchParams, engineParams, gearboxParams, autoboxParams, + multiWheelDiffParams, fourWheelDiffParams, tankDiffParams, + clutchResponseState, throttleResponseState, engineState, gearboxState, autoboxState, diffState, clutchSlipState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + } + else + { + PxVehiclePvdDirectDrivetrainRegister( + commandState, directDriveTransmissionState, + directDriveThrottleResponseParams, + directDrivethrottleResponseState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + } + + PxVehiclePvdPhysXWheelAttachmentRegister( + *axleDesc, + physxConstraintParams, physxMaterialFrictionParams, + physxActor, physxRoadGeomQryParams, physxRoadGeomStates, physxConstraintStates, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdPhysXRigidActorRegister( + physxActor, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdPhysXSteerStateRegister( + physxSteerState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + firstTime = false; + } + + PxVehiclePvdRigidBodyWrite( + rbodyParams, rbodyState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdSuspensionStateCalculationParamsWrite( + suspStateCalcParams, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdCommandResponseWrite( + *axleDesc, brakeResponseParams, steerResponseParams, ackermannParams, + brakeResponseStates, steerResponseStates, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdWheelAttachmentsWrite( + *axleDesc, + wheelParams, wheelActuationStates, wheelRigidBody1dStates, wheelLocalPoses, + roadGeomStates, + suspParams, suspComplianceParams, suspForceParams, suspStates, suspComplianceStates, + suspForces, + tireForceParams, + tireDirectionStates, tireSpeedStates, tireSlipStates, tireStickyStates, tireGripStates, tireCamberStates, + tireForces, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdAntiRollsWrite( + antiRollParams, antiRollTorque, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + if (engineParams) + { + PxVehiclePvdEngineDrivetrainWrite( + commandState, engineDriveTransmissionCommandState, tankDriveTransmissionCommandState, + clutchResponseParams, clutchParams, engineParams, gearboxParams, autoboxParams, + multiWheelDiffParams, fourWheelDiffParams, tankDiffParams, + clutchResponseState, throttleResponseState, engineState, gearboxState, autoboxState, diffState, clutchSlipState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + } + else + { + PxVehiclePvdDirectDrivetrainWrite( + *axleDesc, + commandState, directDriveTransmissionState, + directDriveThrottleResponseParams, + directDrivethrottleResponseState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + } + + PxVehiclePvdPhysXWheelAttachmentWrite( + *axleDesc, + physxConstraintParams, physxMaterialFrictionParams, + physxActor, physxRoadGeomQryParams, physxRoadGeomStates, physxConstraintStates, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdPhysXRigidActorWrite( + physxActor, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + PxVehiclePvdPhysXSteerStateWrite( + physxSteerState, + *context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter); + + return true; + } + +private: + + bool firstTime; +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdFunctions.h new file mode 100644 index 000000000..962406dd4 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdFunctions.h @@ -0,0 +1,634 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/braking/PxVehicleBrakingParams.h" +#include "vehicle2/commands/PxVehicleCommandStates.h" +#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h" +#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h" +#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h" +#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h" +#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h" +#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h" +#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h" +#include "vehicle2/steering/PxVehicleSteeringParams.h" +#include "vehicle2/suspension/PxVehicleSuspensionParams.h" +#include "vehicle2/suspension/PxVehicleSuspensionStates.h" +#include "vehicle2/tire/PxVehicleTireParams.h" +#include "vehicle2/tire/PxVehicleTireStates.h" +#include "vehicle2/wheel/PxVehicleWheelParams.h" +#include "vehicle2/wheel/PxVehicleWheelStates.h" + +class OmniPvdWriter; +namespace physx +{ +class PxAllocatorCallback; +namespace vehicle2 +{ +struct PxVehiclePvdAttributeHandles; +struct PxVehiclePvdObjectHandles; +} // namespace vehicle2 +} // namespace physx + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Create object instances in omnipvd that will be used to reflect the parameters and state of the rigid body of a vehicle instance. +Handles to the created object instances will be stored in a PxVehiclePvdObjectHandles instance. +\param[in] rbodyParams describes the parameters of the vehicle's rigid body. +\param[in] rbodyState describes the state of the vehicle's rigid body. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If rbodyParams is NULL, omnipvd will not reflect rigid body parameters. +\note If rbodyState is NULL, omnipvd will not reflect rigid body state. +\note PxVehiclePvdRigidBodyRegister should be called once for each vehicle instance. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdRigidBodyWrite +*/ +void PxVehiclePvdRigidBodyRegister +(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write the parameters and state of the rigid body of a vehicle instance to omnipvd. +\param[in] rbodyParams describes the parameters of the vehicle's rigid body. +\param[in] rbodyState describes the state of the vehicle's rigid body. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If rbodyParams is NULL but a non-NULL value was used in PxVehiclePvdRigidBodyRegister(), the rigid body parameters will not be updated in omnipvd. +\note If rbodyState is NULL but a non-NULL value was used in PxVehiclePvdRigidBodyRegister(), the rigid body state will not be updated in omnipvd. +\note omniWriter must be the same instance used in PxVehiclePvdRigidBodyRegister(). +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdRigidBodyRegister +*/ +void PxVehiclePvdRigidBodyWrite +(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register object instances in omnipvd that will be used to reflect the suspension state calculation parameters of a vehicle instance. +\param[in] suspStateCalcParams describes parameters used to calculate suspension state. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If suspStateCalcParams is NULL, omnipvd will not reflect the suspension state calculation parameters. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdSuspensionStateCalculationParamsWrite +*/ +void PxVehiclePvdSuspensionStateCalculationParamsRegister +(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write the parameters and state of the rigid body of a vehicle instance to omnipvd. +\param[in] suspStateCalcParams describes parameters used to calculate suspension state. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If suspStateCalcParams is NULL but a non-NULL value was used in void PxVehiclePvdSuspensionStateCalculationParamsRegister(), +the suspension state calculation parameters will not be updated in omnipvd. +\note omniWriter must be the same instance used in PxVehiclePvdSuspensionStateCalculationParamsRegister(). +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdSuspensionStateCalculationParamsRegister +*/ +void PxVehiclePvdSuspensionStateCalculationParamsWrite +(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register object instances in omnipvd that will be used to reflect the brake and steer command response parameters of a vehicle instance. +\param[in] brakeResponseParams is an array of brake command response parameters. +\param[in] steerResponseParams describes the steer command response parameters. +\param[in] ackermannParams defines the Ackermann steer correction. +\param[in] brakeResponseStates is an array of brake responses torqyes, +\param[in] steerResponseStates is an array of steer response angles. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If brakeResponseParams is empty, omnipvd will not reflect any brake command response parameters. +\note If steerResponseParams is NULL, omnipvd will not reflect the steer command response parameters. +\note If ackermannParams is NULL, omnipvd will not reflect any Ackermann steer correction parameters. +\note If brakeResponseStates is empty, omnipvd will not reflect any brake command response state. +\note If steerResponseStates is empty, omnipvd will not reflect any steer command response state. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdCommandResponseWrite +*/ +void PxVehiclePvdCommandResponseRegister +(const PxVehicleSizedArrayData& brakeResponseParams, + const PxVehicleSteerCommandResponseParams* steerResponseParams, + const PxVehicleAckermannParams* ackermannParams, + const PxVehicleArrayData& brakeResponseStates, + const PxVehicleArrayData& steerResponseStates, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write brake and steer command response parameters to omnipvd. +\param[in] axleDesc is a description of the wheels and axles of a vehicle. +\param[in] brakeResponseParams is an array of brake command response parameters. +\param[in] steerResponseParams describes the steer command response parameters. +\param[in] ackermannParams defines the Ackermann steer correction. +\param[in] brakeResponseStates is an array of brake response torques. +\param[in] steerResponseStates is an array of steer response angles. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If brakeResponseParams is empty but a non-empty array was used in PxVehiclePvdCommandResponseRegister(), +the brake command response parameters will not be updated in omnipvd. +\note If steerResponseParams is non-NULL but a NULL value was used in PxVehiclePvdCommandResponseRegister(), +the steer command parameters will not be updated in omnipvd. +\note If ackermannParams is non-NULL but a NULL value was used in PxVehiclePvdCommandResponseRegister(), +the Ackermann steer correction parameters will not be updated in omnipvd. +\note If brakeResponseStates is empty but a non-empty array was used in PxVehiclePvdCommandResponseRegister(), +the brake response states will not be updated in omnipvd. +\note If steerResponseStates is empty but a non-empty array was used in PxVehiclePvdCommandResponseRegister(), +the steer response states will not be updated in omnipvd. +\note omniWriter must be the same instance used in PxVehiclePvdCommandResponseRegister(). +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdCommandResponseRegister +*/ +void PxVehiclePvdCommandResponseWrite +(const PxVehicleAxleDescription& axleDesc, + const PxVehicleSizedArrayData& brakeResponseParams, + const PxVehicleSteerCommandResponseParams* steerResponseParams, + const PxVehicleAckermannParams* ackermannParams, + const PxVehicleArrayData& brakeResponseStates, + const PxVehicleArrayData& steerResponseStates, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register object instances in omnipvd that will be used to reflect wheel attachment data such as tires, suspensions and wheels. +\param[in] axleDesc is a description of the wheels and axles of a vehicle. +\param[in] wheelParams is an array of wheel parameters. +\param[in] wheelActuationStates is an array of wheel actuation states. +\param[in] wheelRigidBody1dStates is an array of wheel rigid body states. +\param[in] wheelLocalPoses is an array of wheel local poses. +\param[in] roadGeometryStates is an array of road geometry states. +\param[in] suspParams is an array of suspension parameters. +\param[in] suspCompParams is an array of suspension compliance parameters. +\param[in] suspForceParams is an array of suspension force parameters. +\param[in] suspStates is an array of suspension states. +\param[in] suspCompStates is an array of suspension compliance states. +\param[in] suspForces is an array of suspension forces. +\param[in] tireForceParams is an array of tire force parameters. +\param[in] tireDirectionStates is an array of tire direction states. +\param[in] tireSpeedStates is an array of tire speed states. +\param[in] tireSlipStates is an array of tire slip states. +\param[in] tireStickyStates is an array of tire sticky states. +\param[in] tireGripStates is an array of tire grip states. +\param[in] tireCamberStates is an array of tire camber states. +\param[in] tireForces is an array of tire forces. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If any array is empty, the corresponding data will not be reflected in omnipvd. +\note Each array must either be empty or contain an entry for each wheel present in axleDesc. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdWheelAttachmentsWrite +*/ +void PxVehiclePvdWheelAttachmentsRegister +(const PxVehicleAxleDescription& axleDesc, + const PxVehicleArrayData& wheelParams, + const PxVehicleArrayData& wheelActuationStates, + const PxVehicleArrayData& wheelRigidBody1dStates, + const PxVehicleArrayData& wheelLocalPoses, + const PxVehicleArrayData& roadGeometryStates, + const PxVehicleArrayData& suspParams, + const PxVehicleArrayData& suspCompParams, + const PxVehicleArrayData& suspForceParams, + const PxVehicleArrayData& suspStates, + const PxVehicleArrayData& suspCompStates, + const PxVehicleArrayData& suspForces, + const PxVehicleArrayData& tireForceParams, + const PxVehicleArrayData& tireDirectionStates, + const PxVehicleArrayData& tireSpeedStates, + const PxVehicleArrayData& tireSlipStates, + const PxVehicleArrayData& tireStickyStates, + const PxVehicleArrayData& tireGripStates, + const PxVehicleArrayData& tireCamberStates, + const PxVehicleArrayData& tireForces, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write wheel attachment data such as tire, suspension and wheel data to omnipvd. +\param[in] axleDesc is a description of the wheels and axles of a vehicle. +\param[in] wheelParams is an array of wheel parameters. +\param[in] wheelActuationStates is an array of wheel actuation states. +\param[in] wheelRigidBody1dStates is an array of wheel rigid body states. +\param[in] wheelLocalPoses is an array of wheel local poses. +\param[in] roadGeometryStates is an array of road geometry states. +\param[in] suspParams is an array of suspension parameters. +\param[in] suspCompParams is an array of suspension compliance parameters. +\param[in] suspForceParams is an array of suspension force parameters. +\param[in] suspStates is an array of suspension states. +\param[in] suspCompStates is an array of suspension compliance states. +\param[in] suspForces is an array of suspension forces. +\param[in] tireForceParams is an array of tire force parameters. +\param[in] tireDirectionStates is an array of tire direction states. +\param[in] tireSpeedStates is an array of tire speed states. +\param[in] tireSlipStates is an array of tire slip states. +\param[in] tireStickyStates is an array of tire sticky states. +\param[in] tireGripStates is an array of tire grip states. +\param[in] tireCamberStates is an array of tire camber states. +\param[in] tireForces is an array of tire forces. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If any array is empty but the corresponding argument in PxVehiclePvdWheelAttachmentsRegister was not empty, the corresponding data will not be updated in omnipvd. +\note Each array must either be empty or contain an entry for each wheel present in axleDesc. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdWheelAttachmentsRegister +*/ +void PxVehiclePvdWheelAttachmentsWrite +(const PxVehicleAxleDescription& axleDesc, + const PxVehicleArrayData& wheelParams, + const PxVehicleArrayData& wheelActuationStates, + const PxVehicleArrayData& wheelRigidBody1dStates, + const PxVehicleArrayData& wheelLocalPoses, + const PxVehicleArrayData& roadGeometryStates, + const PxVehicleArrayData& suspParams, + const PxVehicleArrayData& suspCompParams, + const PxVehicleArrayData& suspForceParams, + const PxVehicleArrayData& suspStates, + const PxVehicleArrayData& suspCompStates, + const PxVehicleArrayData& suspForces, + const PxVehicleArrayData& tireForceParams, + const PxVehicleArrayData& tireDirectionStates, + const PxVehicleArrayData& tireSpeedStates, + const PxVehicleArrayData& tireSlipStates, + const PxVehicleArrayData& tireStickyStates, + const PxVehicleArrayData& tireGripStates, + const PxVehicleArrayData& tireCamberStates, + const PxVehicleArrayData& tireForces, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register object instances in omnipvd that will be used to reflect the antiroll bars of a vehicle instance. +\param[in] antiRollForceParams is an array of antiroll parameters. +\param[in] antiRollTorque describes the instantaneous accumulated torque from all antiroll bas. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If antiRollForceParams is empty, the corresponding data will not be reflected in omnipvd. +\note If antiRollTorque is NULL, the corresponding data will not be reflected in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdAntiRollsWrite +*/ +void PxVehiclePvdAntiRollsRegister +(const PxVehicleSizedArrayData& antiRollForceParams, const PxVehicleAntiRollTorque* antiRollTorque, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write antiroll data to omnipvd. +\param[in] antiRollForceParams is an array of antiroll parameters. +\param[in] antiRollTorque describes the instantaneous accumulated torque from all antiroll bas. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If antiRollForceParams is empty but the corresponding argument was not empty, the corresponding data will not be updated in omnipvd. +\note If antiRollTorque is NULL but the corresponding argument was not NULL, the corresponding data will not be updated in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdAntiRollsRegister +*/ +void PxVehiclePvdAntiRollsWrite +(const PxVehicleSizedArrayData& antiRollForceParams, const PxVehicleAntiRollTorque* antiRollTorque, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register object instances in omnipvd that will be used to reflect the direct drivetrain of a vehicle instance. +\param[in] commandState describes the control values applied to the vehicle. +\param[in] transmissionCommandState describes the state of the direct drive transmission. +\param[in] directDriveThrottleResponseParams describes the vehicle's torque response to a throttle command. +\param[in] directDriveThrottleResponseState is the instantaneous torque response of each wheel to a throttle command. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If commandState is NULL, the corresponding data will not be reflected in omnipvd. +\note If transmissionCommandState is NULL, the corresponding data will not be reflected in omnipvd. +\note If directDriveThrottleResponseParams is NULL, the corresponding data will not be reflected in omnipvd. +\note If directDriveThrottleResponseState is empty, the corresponding data will not be reflected in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdDirectDrivetrainWrite +*/ +void PxVehiclePvdDirectDrivetrainRegister +(const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionCommandState, + const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams, + const PxVehicleArrayData& directDriveThrottleResponseState, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write direct drivetrain data to omnipvd. +\param[in] axleDesc is a description of the wheels and axles of a vehicle. +\param[in] commandState describes the control values applied to the vehicle. +\param[in] transmissionCommandState describes the state of the direct drive transmission. +\param[in] directDriveThrottleResponseParams describes the vehicle's torque response to a throttle command. +\param[in] directDriveThrottleResponseState is the instantaneous torque response of each wheel to a throttle command. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If commandState is NULL but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not NULL, the corresponding data will not be updated in omnipvd. +\note If transmissionCommandState is NULL but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not NULL, the corresponding data will not be updated in omnipvd. +\note If directDriveThrottleResponseParams is NULL but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not NULL, the corresponding data will not be updated in omnipvd. +\note If directDriveThrottleResponseState is empty but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not empty, the corresponding data will not be updated in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdDirectDrivetrainRegister +*/ +void PxVehiclePvdDirectDrivetrainWrite +(const PxVehicleAxleDescription& axleDesc, + const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionCommandState, + const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams, + const PxVehicleArrayData& directDriveThrottleResponseState, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register object instances in omnipvd that will be used to reflect the engine drivetrain of a vehicle instance. +\param[in] commandState describes the control values applied to the vehicle. +\param[in] engineDriveTransmissionCommandState describes the state of the engine drive transmission. +\param[in] tankDriveTransmissionCommandState describes the state of the tank drive transmission. +\param[in] clutchResponseParams describes the vehicle's response to a clutch command. +\param[in] clutchParams describes the vehicle's clutch. +\param[in] engineParams describes the engine. +\param[in] gearboxParams describes the gearbox. +\param[in] autoboxParams describes the automatic gearbox. +\param[in] multiWheelDiffParams describes a multiwheel differential without limited slip compensation. +\param[in] fourWheelDiffPrams describes a differential that delivers torque to four drive wheels with limited slip compensation. +\param[in] tankDiffParams describes the operation of the tank differential. +\param[in] clutchResponseState is the instantaneous reponse of the clutch to a clutch command. +\param[in] throttleResponseState is the instantaneous response to a throttle command. +\param[in] engineState is the instantaneous state of the engine. +\param[in] gearboxState is the instantaneous state of the gearbox. +\param[in] autoboxState is the instantaneous state of the automatic gearbox. +\param[in] diffState is the instantaneous state of the differential. +\param[in] clutchSlipState is the instantaneous slip recorded at the clutch. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If any pointer is NULL, the corresponding data will not be reflected in omnipvd. +\note At most one of engineDriveTransmissionCommandState and tankDriveTransmissionCommandState is expected to be non-NULL. +\note At most one of multiWheelDiffParams, fourWheelDiffParams and tankDiffParams is expected to be non-NULL. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdEngineDrivetrainWrite +*/ +void PxVehiclePvdEngineDrivetrainRegister +(const PxVehicleCommandState* commandState, + const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState, + const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState, + const PxVehicleClutchCommandResponseParams* clutchResponseParams, + const PxVehicleClutchParams* clutchParams, + const PxVehicleEngineParams* engineParams, + const PxVehicleGearboxParams* gearboxParams, + const PxVehicleAutoboxParams* autoboxParams, + const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams, + const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffPrams, + const PxVehicleTankDriveDifferentialParams* tankDiffParams, + const PxVehicleClutchCommandResponseState* clutchResponseState, + const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState, + const PxVehicleEngineState* engineState, + const PxVehicleGearboxState* gearboxState, + const PxVehicleAutoboxState* autoboxState, + const PxVehicleDifferentialState* diffState, + const PxVehicleClutchSlipState* clutchSlipState, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write engine drivetrain data of a vehicle instance to omnipvd. +\param[in] commandState describes the control values applied to the vehicle. +\param[in] engineDriveTransmissionCommandState describes the state of the engine drive transmission. +\param[in] tankDriveTransmissionCommandState describes the state of the tank drive transmission. +\param[in] clutchResponseParams describes the vehicle's response to a clutch command. +\param[in] clutchParams describes the vehicle's clutch. +\param[in] engineParams describes the engine. +\param[in] gearboxParams describes the gearbox. +\param[in] autoboxParams describes the automatic gearbox. +\param[in] multiWheelDiffParams describes a multiwheel differential without limited slip compensation. +\param[in] fourWheelDiffParams describes a differential that delivers torque to four drive wheels with limited slip compensation. +\param[in] tankDiffParams describes the operation of the tank differential. +\param[in] clutchResponseState is the instantaneous reponse of the clutch to a clutch command. +\param[in] throttleResponseState is the instantaneous response to a throttle command. +\param[in] engineState is the instantaneous state of the engine. +\param[in] gearboxState is the instantaneous state of the gearbox. +\param[in] autoboxState is the instantaneous state of the automatic gearbox. +\param[in] diffState is the instantaneous state of the differential. +\param[in] clutchSlipState is the instantaneous slip recorded at the clutch. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If any pointer is NULL and the corresponding argument in PxVehiclePvdEngineDrivetrainRegister() was not NULL, the corresponding data will not be reflected in omnipvd. +\note At most one of engineDriveTransmissionCommandState and tankDriveTransmissionCommandState is expected to be non-NULL. +\note At most one of multiWheelDiffParams, fourWheelDiffParams and tankDiffParams is expected to be non-NULL. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdEngineDrivetrainRegister +*/ +void PxVehiclePvdEngineDrivetrainWrite +(const PxVehicleCommandState* commandState, + const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState, + const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState, + const PxVehicleClutchCommandResponseParams* clutchResponseParams, + const PxVehicleClutchParams* clutchParams, + const PxVehicleEngineParams* engineParams, + const PxVehicleGearboxParams* gearboxParams, + const PxVehicleAutoboxParams* autoboxParams, + const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams, + const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffParams, + const PxVehicleTankDriveDifferentialParams* tankDiffParams, + const PxVehicleClutchCommandResponseState* clutchResponseState, + const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState, + const PxVehicleEngineState* engineState, + const PxVehicleGearboxState* gearboxState, + const PxVehicleAutoboxState* autoboxState, + const PxVehicleDifferentialState* diffState, + const PxVehicleClutchSlipState* clutchSlipState, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register per wheel attachment data that involves the vehicle's integration with a PhysX scene. +\param[in] axleDesc is a description of the wheels and axles of a vehicle. +\param[in] physxSuspLimitConstraintParams describes the method used by PhysX to enforce suspension travel limits. +\param[in] physxMaterialFrictionParams describes the friction response of each wheel to a set of PxMaterial instances. +\param[in] physxActor describes the PxRigidActor and PxShape instances that are used to represent the vehicle's rigid body and wheel shapes in PhysX. +\param[in] physxRoadGeometryQueryParams describes the physx scene query method used to place each wheel on the ground. +\param[in] physxRoadGeomState is an array of per wheel physx scene query results. +\param[in] physxConstraintStates is an array of constraints states used by PhysX to enforce sticky tire and suspension travel limit constraints. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If any array is empty, the corresponding data will not be reflected in omnipvd. +\note If physxActor is NULL, the corresponding data will not be reflected in omnipvd. +\note If physxRoadGeometryQueryParams is NULL, the corresponding data will not be reflected in omnipvd. +\note Each array must either be empty or contain an entry for each wheel present in axleDesc. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdPhysXWheelAttachmentWrite +*/ +void PxVehiclePvdPhysXWheelAttachmentRegister +(const PxVehicleAxleDescription& axleDesc, + const PxVehicleArrayData& physxSuspLimitConstraintParams, + const PxVehicleArrayData& physxMaterialFrictionParams, + const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeometryQueryParams, + const PxVehicleArrayData& physxRoadGeomState, + const PxVehicleArrayData& physxConstraintStates, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write to omnipvd the per wheel attachment data that involves the vehicle's integration with a PhysX scene. +\param[in] axleDesc is a description of the wheels and axles of a vehicle. +\param[in] physxSuspLimitConstraintParams describes the method used by PhysX to enforce suspension travel limits. +\param[in] physxMaterialFrictionParams describes the friction response of each wheel to a set of PxMaterial instances. +\param[in] physxActor describes the PxShape instances that are used to represent the vehicle's wheel shapes in PhysX. +\param[in] physxRoadGeometryQueryParams describes the physx scene query method used to place each wheel on the ground. +\param[in] physxRoadGeomState is an array of per wheel physx scene query results. +\param[in] physxConstraintStates is an array of constraints states used by PhysX to enforce sticky tire and suspension travel limit constraints. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If any array is empty but the corresponding array in PxVehiclePvdPhysXWheelAttachmentRegister() was not empty, the corresponding data will not be updated in omnipvd. +\note If physxActor is NULL but the corresponding argument in PxVehiclePvdPhysXWheelAttachmentRegister was not NULL, the corresponding data will not be reflected in omnipvd. +\note If physxRoadGeometryQueryParams is NULL but the corresponding argument in PxVehiclePvdPhysXWheelAttachmentRegister was not NULL, the corresponding data will not be reflected in omnipvd. +\note Each array must either be empty or contain an entry for each wheel present in axleDesc. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdPhysXWheelAttachmentWrite +*/ +void PxVehiclePvdPhysXWheelAttachmentWrite +(const PxVehicleAxleDescription& axleDesc, + const PxVehicleArrayData& physxSuspLimitConstraintParams, + const PxVehicleArrayData& physxMaterialFrictionParams, + const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeometryQueryParams, + const PxVehicleArrayData& physxRoadGeomState, + const PxVehicleArrayData& physxConstraintStates, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register the PxRigidActor instance that represents the vehicle's rigid body in a PhysX scene. +\param[in] physxActor describes the PxRigidActor instance that is used to represent the vehicle's rigid body in PhysX. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If physxActor is NULL, the corresponding data will not be reflected in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdPhysXRigidActorWrite +*/ +void PxVehiclePvdPhysXRigidActorRegister +(const PxVehiclePhysXActor* physxActor, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write the PxRigidActor instance to omnipvd. +\param[in] physxActor describes the PxRigidActor instance that is used to represent the vehicle's rigid body in PhysX. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If physxActor is NULL and the corresponding argument in PxVehiclePvdPhysXRigidActorRegister was not NULL, the corresponding data will not be updated in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdPhysXRigidActorRegister +*/ +void PxVehiclePvdPhysXRigidActorWrite +(const PxVehiclePhysXActor* physxActor, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Register the PhysX related steer state class. +\param[in] physxSteerState describes the PxVehiclePhysXSteerState instance that holds steer related state information. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If physxSteerState is NULL, the corresponding data will not be reflected in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdPhysXSteerStateWrite +*/ +void PxVehiclePvdPhysXSteerStateRegister +(const PxVehiclePhysXSteerState* physxSteerState, + const PxVehiclePvdAttributeHandles& attributeHandles, + PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +/** +\brief Write the PxVehiclePhysXSteerState instance to omnipvd. +\param[in] physxSteerState describes the PxVehiclePhysXSteerState instance that holds steer related state information. +\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd. +\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance. +\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd. +\note If physxSteerState is NULL and the corresponding argument in PxVehiclePvdPhysXSteerStateRegister was not NULL, the corresponding data will not be updated in omnipvd. +\see PxVehiclePvdAttributesCreate +\see PxVehiclePvdObjectCreate +\see PxVehiclePvdPhysXSteerStateRegister +*/ +void PxVehiclePvdPhysXSteerStateWrite +(const PxVehiclePhysXSteerState* physxSteerState, + const PxVehiclePvdAttributeHandles& attributeHandles, + const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdHelpers.h new file mode 100644 index 000000000..d9c125217 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/pvd/PxVehiclePvdHelpers.h @@ -0,0 +1,103 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxSimpleTypes.h" + +class OmniPvdWriter; +namespace physx +{ +class PxAllocatorCallback; +namespace vehicle2 +{ +struct PxVehiclePvdAttributeHandles; +struct PxVehiclePvdObjectHandles; +} +} + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Create the attribute handles necessary to reflect vehicles in omnipvd. +\param[in] allocator is used to allocate the memory used to store the attribute handles. +\param[in] omniWriter is used to register the attribute handles with omnipvd. +\see PxVehicleSimulationContext +\see PxVehiclePVDComponent +\see PxVehiclePvdAttributesRelease +*/ +PxVehiclePvdAttributeHandles* PxVehiclePvdAttributesCreate +(PxAllocatorCallback& allocator, OmniPvdWriter& omniWriter); + +/** +\brief Destory the attribute handles created by PxVehiclePvdAttributesCreate(). +\param[in] allocator must be the instance used by PxVehiclePvdObjectCreate(). +\param[in] attributeHandles is the PxVehiclePvdAttributeHandles created by PxVehiclePvdAttributesCreate(). +\see PxVehiclePvdAttributesCreate +*/ +void PxVehiclePvdAttributesRelease +(PxAllocatorCallback& allocator, PxVehiclePvdAttributeHandles& attributeHandles); + +/** +\brief Create omnipvd objects that will be used to reflect an individual veicle in omnipvd. +\param[in] nbWheels must be greater than or equal to the number of wheels on the vehicle. +\param[in] nbAntirolls must be greater than or equal to the number of antiroll bars on the vehicle. +\param[in] maxNbPhysxMaterialFrictions must be greater than or equal to the number of PxPhysXMaterialFriction instances associated with any wheel of the vehicle. +\param[in] contextHandle is typically used to associated vehicles with a particular scene or group. +\param[in] allocator is used to allocate the memory used to store handles to the created omnipvd objects. +\note PxVehiclePvdObjectCreate() must be called after PxVehiclePvdAttributesCreate(). +\see PxVehicleAxleDescription +\see PxVehicleAntiRollForceParams +\see PxVehiclePhysXMaterialFrictionParams +\see PxVehiclePVDComponent +\see PxVehiclePvdAttributesCreate +*/ +PxVehiclePvdObjectHandles* PxVehiclePvdObjectCreate +(const PxU32 nbWheels, const PxU32 nbAntirolls, const PxU32 maxNbPhysxMaterialFrictions, + const PxU64 contextHandle, PxAllocatorCallback& allocator); + +/** +\brief Destroy the PxVehiclePvdObjectHandles instance created by PxVehiclePvdObjectCreate(). +\param[in] omniWriter is used to register the attribute handles with omnipvd. +\param[in] allocator must be the instance used by PxVehiclePvdObjectCreate(). +\param[in] objectHandles is the PxVehiclePvdObjectHandles that was created by PxVehiclePvdObjectCreate(). +*/ +void PxVehiclePvdObjectRelease +(OmniPvdWriter& omniWriter, PxAllocatorCallback& allocator, PxVehiclePvdObjectHandles& objectHandles); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyComponents.h new file mode 100644 index 000000000..675f4b1ee --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyComponents.h @@ -0,0 +1,110 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "PxVehicleRigidBodyFunctions.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Forward integrate the momentum and pose of the vehicle's rigid body after applying forces and torques +from the suspension, tires and anti-roll bars. +*/ +class PxVehicleRigidBodyComponent : public PxVehicleComponent +{ +public: + + PxVehicleRigidBodyComponent() : PxVehicleComponent() {} + virtual ~PxVehicleRigidBodyComponent() {} + + /** + \brief Retrieve pointers to the parameter and state data required to update the dynamic state of a rigid body. + \param[out] axleDescription must be returned as a non-null pointer to a single PxVehicleAxleDescription instance that describes the wheels and axles + of the vehicle. + \param[out] rigidBodyParams must be returned as a non-null pointer to a single PxVehicleRigidBodyParams instance that describes the mass and moment of + inertia of the rigid body. + \param[out] suspensionForces must be returned as a non-null pointer to an array of suspension forces and torques in the world frame. + The suspension forces and torques will be applied to the rigid body to update *rigidBodyState*. + \param[out] tireForces must be returned as a non-null pointer to an array of tire forces and torques in the world frame. + The tire forces and torques will be applied to the rigid body to update *rigidBodyState*. + \param[out] antiRollTorque may be returned an optionally non-null pointer to a single PxVehicleAntiRollTorque instance that contains the accumulated anti-roll + torque to apply to the rigid body. + \param[out] rigidBodyState imust be returned as a non-null pointer to a single PxVehicleRigidBodyState instance that is to be forward integrated. + \note The suspensionForces array must contain an entry for each wheel listed as an active wheel in axleDescription. + \note The tireForces array must contain an entry for each wheel listed as an active wheel in axleDescription. + \note If antiRollTorque is returned as a null pointer then zero anti-roll torque will be applied to the rigid body. + */ + virtual void getDataForRigidBodyComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleRigidBodyParams*& rigidBodyParams, + PxVehicleArrayData& suspensionForces, + PxVehicleArrayData& tireForces, + const PxVehicleAntiRollTorque*& antiRollTorque, + PxVehicleRigidBodyState*& rigidBodyState) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_PROFILE_ZONE("PxVehicleRigidBodyComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleRigidBodyParams* rigidBodyParams; + PxVehicleArrayData suspensionForces; + PxVehicleArrayData tireForces; + const PxVehicleAntiRollTorque* antiRollTorque; + PxVehicleRigidBodyState* rigidBodyState; + + getDataForRigidBodyComponent(axleDescription, rigidBodyParams, + suspensionForces, tireForces, antiRollTorque, + rigidBodyState); + + PxVehicleRigidBodyUpdate( + *axleDescription, *rigidBodyParams, + suspensionForces, tireForces, antiRollTorque, + dt, context.gravity, + *rigidBodyState); + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyFunctions.h new file mode 100644 index 000000000..119600968 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyFunctions.h @@ -0,0 +1,76 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxVec3.h" +#include "foundation/PxSimpleTypes.h" +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleRigidBodyParams; +struct PxVehicleSuspensionForce; +struct PxVehicleTireForce; +struct PxVehicleAntiRollTorque; +struct PxVehicleRigidBodyState; + +/** +\brief Forward integrate rigid body state. +\param[in] axleDescription is a description of the axles of the vehicle and the wheels on each axle. +\param[in] rigidBodyParams is a description of rigid body mass and moment of inertia. +\param[in] suspensionForces is an array of suspension forces and torques in the world frame to be applied to the rigid body. +\param[in] tireForces is an array of tire forces and torques in the world frame to be applied to the rigid body. +\param[in] antiRollTorque is an optional pointer to a single PxVehicleAntiRollTorque instance that contains the accumulated anti-roll +torque to apply to the rigid body. +\param[in] dt is the timestep of the forward integration. +\param[in] gravity is gravitational acceleration. +\param[in,out] rigidBodyState is the rigid body state that is to be updated. +\note The suspensionForces array must contain an entry for each wheel listed as an active wheel in axleDescription. +\note The tireForces array must contain an entry for each wheel listed as an active wheel in axleDescription. +\note If antiRollTorque is a null pointer then zero anti-roll torque will be applied to the rigid body. +*/ +void PxVehicleRigidBodyUpdate + (const PxVehicleAxleDescription& axleDescription, const PxVehicleRigidBodyParams& rigidBodyParams, + const PxVehicleArrayData& suspensionForces, + const PxVehicleArrayData& tireForces, + const PxVehicleAntiRollTorque* antiRollTorque, + const PxReal dt, const PxVec3& gravity, + PxVehicleRigidBodyState& rigidBodyState); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyParams.h new file mode 100644 index 000000000..2ff210736 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyParams.h @@ -0,0 +1,87 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleFunctions.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief The properties of the rigid body. +*/ +struct PxVehicleRigidBodyParams +{ + /** + \brief The mass of the rigid body. + + Range: (0, inf)
+ Unit: mass + */ + PxReal mass; + + /** + \brief The moment of inertia of the rigid body. + + Range: (0, inf)
+ Unit: mass * (length^2) + */ + PxVec3 moi; + + PX_FORCE_INLINE PxVehicleRigidBodyParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PxVehicleRigidBodyParams r = *this; + r.moi = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, moi).abs(); + const PxReal scale = trgScale.scale/srcScale.scale; + r.moi *= (scale*scale); + return r; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(mass > 0.0f, "PxVehicleRigidBodyParams.mass must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(moi.x > 0.0f && moi.y > 0.0f && moi.z> 0.0f, "PxVehicleRigidBodyParams.moi must be greater than zero", false); + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyStates.h new file mode 100644 index 000000000..1e30aa40f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/rigidBody/PxVehicleRigidBodyStates.h @@ -0,0 +1,94 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxTransform.h" +#include "foundation/PxVec3.h" +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleRigidBodyState +{ + PxTransform pose; //!< the body's pose (in world space) + PxVec3 linearVelocity; //!< the body's linear velocity (in world space) + PxVec3 angularVelocity; //!< the body's angular velocity (in world space) + PxVec3 previousLinearVelocity; //!< the previous linear velocity of the body (in world space) + PxVec3 previousAngularVelocity; //!< the previous angular velocity of the body (in world space) + PxVec3 externalForce; //!< external force (in world space) affecting the rigid body (usually excluding gravitational force) + PxVec3 externalTorque; //!< external torque (in world space) affecting the rigid body + + PX_FORCE_INLINE void setToDefault() + { + pose = PxTransform(PxIdentity); + linearVelocity = PxVec3(PxZero); + angularVelocity = PxVec3(PxZero); + externalForce = PxVec3(PxZero); + externalTorque = PxVec3(PxZero); + } + + /** + \brief Compute the vertical speed of the rigid body transformed to the world frame. + \param[in] frame describes the axes of the vehicle + */ + PX_FORCE_INLINE PxReal getVerticalSpeed(const PxVehicleFrame& frame) const + { + return linearVelocity.dot(pose.q.rotate(frame.getVrtAxis())); + } + + /** + \param[in] frame describes the axes of the vehicle + \brief Compute the lateral speed of the rigid body transformed to the world frame. + */ + PX_FORCE_INLINE PxReal getLateralSpeed(const PxVehicleFrame& frame) const + { + return linearVelocity.dot(pose.q.rotate(frame.getLatAxis())); + } + + /** + \brief Compute the longitudinal speed of the rigid body transformed to the world frame. + \param[in] frame describes the axes of the vehicle + */ + PX_FORCE_INLINE PxReal getLongitudinalSpeed(const PxVehicleFrame& frame) const + { + return linearVelocity.dot(pose.q.rotate(frame.getLngAxis())); + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/roadGeometry/PxVehicleRoadGeometryState.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/roadGeometry/PxVehicleRoadGeometryState.h new file mode 100644 index 000000000..e17870f01 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/roadGeometry/PxVehicleRoadGeometryState.h @@ -0,0 +1,59 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxPlane.h" +#include "foundation/PxMemory.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleRoadGeometryState +{ + PxPlane plane; //!< the plane under the wheel + PxReal friction; //!< the friction to be used by the tire model + PxVec3 velocity; //!< the velocity of the road geometry + bool hitState; //!< true if a plane is found, false if there is no plane. + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleRoadGeometryState)); + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/steering/PxVehicleSteeringFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/steering/PxVehicleSteeringFunctions.h new file mode 100644 index 000000000..5b6c78115 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/steering/PxVehicleSteeringFunctions.h @@ -0,0 +1,76 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxSimpleTypes.h" + +#include "vehicle2/PxVehicleParams.h" +#include "PxVehicleSteeringParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleCommandState; + +/** +\brief Compute the yaw angle response to a steer command. +\param[in] steer is the input steer command value. +\param[in] longitudinalSpeed is the longitudinal speed of the vehicle. +\param[in] wheelId specifies the wheel to have its steer response computed. +\param[in] steerResponseParams specifies the per wheel yaw angle response to the steer command as a nonlinear function of steer command and longitudinal speed. +\param[out] steerResponseState is the yaw angle response to the input steer command. +*/ +void PxVehicleSteerCommandResponseUpdate +(const PxReal steer, const PxReal longitudinalSpeed, + const PxU32 wheelId, const PxVehicleSteerCommandResponseParams& steerResponseParams, + PxReal& steerResponseState); + +/** +\brief Account for Ackermann correction by modifying the per wheel steer response multipliers to engineer an asymmetric steer response across axles. +\param[in] steer is the input steer command value. +\param[in] steerResponseParams describes the maximum response and a response multiplier per axle. +\param[in] ackermannParams is an array that describes the wheels affected by Ackermann steer correction. +\param[in,out] steerResponseStates contains the corrected per wheel steer response multipliers that take account of Ackermann steer correction. +*/ +void PxVehicleAckermannSteerUpdate +(const PxReal steer, const PxVehicleSteerCommandResponseParams& steerResponseParams, + const PxVehicleSizedArrayData& ackermannParams, + PxVehicleArrayData& steerResponseStates); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/steering/PxVehicleSteeringParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/steering/PxVehicleSteeringParams.h new file mode 100644 index 000000000..cfc9c4d28 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/steering/PxVehicleSteeringParams.h @@ -0,0 +1,118 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxFoundation.h" + +#include "vehicle2/PxVehicleParams.h" + +#include "vehicle2/commands/PxVehicleCommandParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleFrame; +struct PxVehicleScale; + +/** +\brief Distribute a steer response to the wheels of a vehicle. +\note The steer angle applied to each wheel on the ith wheel is steerCommand * maxResponse * wheelResponseMultipliers[i]. +\note A typical use case is to set maxResponse to be the vehicle's maximum achievable steer angle +that occurs when the steer command is equal to 1.0. The array wheelResponseMultipliers[i] would then be used +to specify the maximum achievable steer angle per wheel as a fractional multiplier of the vehicle's maximum achievable steer angle. +*/ +struct PxVehicleSteerCommandResponseParams : public PxVehicleCommandResponseParams +{ + PX_FORCE_INLINE PxVehicleSteerCommandResponseParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + if (!axleDesc.isValid()) + return false; + for (PxU32 i = 0; i < axleDesc.nbWheels; i++) + { + PX_CHECK_AND_RETURN_VAL(PxAbs(maxResponse*wheelResponseMultipliers[axleDesc.wheelIdsInAxleOrder[i]]) <= PxPi, + "PxVehicleSteerCommandResponseParams.maxResponse*PxVehicleSteerCommandResponseParams.wheelResponseMultipliers[i] must be in range [-Pi, Pi]", false); + } + return true; + } +}; + +/** +\brief A description of a single axle that is to be affected by Ackermann steer correction. +*/ +struct PxVehicleAckermannParams +{ + PxU32 wheelIds[2]; //!< wheelIds[0] is the id of the wheel that is negative along the lateral axis, wheelIds[1] is the wheel id that is positive along the lateral axis. + PxReal wheelBase; //!< wheelBase is the longitudinal distance between the axle that is affected by Ackermann correction and a reference axle. + PxReal trackWidth; //!< trackWidth is the width of the axle specified by #wheelIds + PxReal strength; //!< is the strength of the correction with 0 denoting no correction and 1 denoting perfect correction. + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelIds[0] < axleDesc.getNbWheels(), "PxVehicleAckermannParams.wheelIds[0] must be valid wheel", false); + PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelIds[1] < axleDesc.getNbWheels(), "PxVehicleAckermannParams.wheelIds[1] must be a valid wheel", false); + PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelIds[0] != wheelIds[1], "PxVehicleAckermannParams.wheelIds[0] and PxVehicleAckermannParams.wheelIds[1] must reference two different wheels", false); + PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelBase > 0.0f, "PxVehicleAckermannParams.wheelBase must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(0.0f == strength || trackWidth > 0.0f, "PxVehicleAckermannParams.trackWidth must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(strength >= 0.0f && strength <= 1.0f, "PxVehicleAckermannParams.strength must be in range [0,1]", false); + PX_UNUSED(axleDesc); + return true; + } + + PX_FORCE_INLINE PxVehicleAckermannParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleAckermannParams r = *this; + const PxReal scale = trgScale.scale / srcScale.scale; + r.wheelBase *= scale; + r.trackWidth *= scale; + return r; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionComponents.h new file mode 100644 index 000000000..1961ecea1 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionComponents.h @@ -0,0 +1,324 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "vehicle2/commands/PxVehicleCommandStates.h" +#include "vehicle2/commands/PxVehicleCommandHelpers.h" +#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h" +#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h" +#include "vehicle2/wheel/PxVehicleWheelParams.h" + +#include "PxVehicleSuspensionParams.h" +#include "PxVehicleSuspensionStates.h" +#include "PxVehicleSuspensionFunctions.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + + +class PxVehicleSuspensionComponent : public PxVehicleComponent +{ +public: + + PxVehicleSuspensionComponent() : PxVehicleComponent() {} + virtual ~PxVehicleSuspensionComponent() {} + + /** + \brief Retrieve pointers to the parameter and state data required to compute the suspension state and the forces/torques that arise from the suspension state. + \param[out] axleDescription must be returned as a non-null pointer to a single PxVehicleAxleDescription instance that describes the wheels and axles + of the vehicle. + \param[out] rigidBodyParams must be returned as a a non-null pointer to a single PxVehicleRigidBodyParams instance that describes the mass and moment + of inertia of the vehicle's rigid body. + \param[out] suspensionStateCalculationParams must be returned as a non-null pointer to a single PxVehicleSuspensionStateCalculationParams instance + that describes the jounce computation type etc. + \param[out] steerResponseStates must be returned as a non-null pointer to a single PxVehicleSteerCommandResponseStates instance that describes the steer + state of the wheels. + \param[out] rigidBodyState must be returned as a non-null pointer to a single PxVehicleRigidBodyState instance that describes the pose and momentum of + the vehicle's rigid body. + \param[out] wheelParams must be set to a non-null pointer to an array of PxVehicleWheelParams containing per-wheel parameters for each wheel + referenced by axleDescription. + \param[out] suspensionParams must be set to a non-null pointer to an array of PxVehicleSuspensionParams containing per-wheel parameters for each + wheel referenced by axleDescription. + \param[out] suspensionComplianceParams must be set to a non-null pointer to an array of PxVehicleSuspensionComplianceParams containing per-wheel + parameters for each wheel referenced by axleDescription. + \param[out] suspensionForceParams must be set to a non-null pointer to an array of PxVehicleSuspensionForceParams containing per-wheel parameters + for each wheel referenced by axleDescription. + \param[out] antiRollForceParams is optionally returned as a non-null pointer to an array of PxVehicleAntiRollForceParams with each element in the array + describing a unique anti-roll bar connecting a pair of wheels. + \param[out] wheelRoadGeomStates must be set to non-null pointer to an array of PxVehicleRoadGeometryState containing per-wheel road geometry for + each wheel referenced by axleDescription. + \param[out] suspensionStates must be set to a non-null pointer to an array of PxVehicleSuspensionState containing per-wheel suspension state for each + wheel referenced by axleDescription. + \param[out] suspensionComplianceStates must be set to a non-null pointer to an array of PxVehicleSuspensionComplianceState containing per-wheel suspension + compliance state for each wheel referenced by axleDescription. + \param[out] suspensionForces must be set to a non-null pointer to an array of PxVehicleSuspensionForce containing per-wheel suspension forces for each + wheel referenced by axleDescription. + \param[out] antiRollTorque is optionally returned as a non-null pointer to a single PxVehicleAntiRollTorque instance that will store the accumulated anti-roll + torque to be applied to the vheicle's rigid body. + \note antiRollForceParams and antiRollTorque should be returned either both non-NULL or both NULL. + */ + virtual void getDataForSuspensionComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleRigidBodyParams*& rigidBodyParams, + const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, + PxVehicleArrayData& steerResponseStates, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& suspensionParams, + PxVehicleArrayData& suspensionComplianceParams, + PxVehicleArrayData& suspensionForceParams, + PxVehicleSizedArrayData& antiRollForceParams, + PxVehicleArrayData& wheelRoadGeomStates, + PxVehicleArrayData& suspensionStates, + PxVehicleArrayData& suspensionComplianceStates, + PxVehicleArrayData& suspensionForces, + PxVehicleAntiRollTorque*& antiRollTorque) = 0; + + /** + \brief Update the suspension state and suspension compliance state and use those updated states to compute suspension and anti-roll forces/torques + to apply to the vehicle's rigid body. + \param[in] dt is the simulation time that has passed since the last call to PxVehicleSuspensionComponent::update() + \param[in] context describes a variety of global simulation constants such as frame and scale of the simulation and the gravitational acceleration + of the simulated environment. + \note The suspension and anti-roll forces/torques are computed in the world frame. + */ + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_PROFILE_ZONE("PxVehicleSuspensionComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleRigidBodyParams* rigidBodyParams; + const PxVehicleSuspensionStateCalculationParams* suspensionStateCalculationParams; + PxVehicleArrayData steerResponseStates; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData wheelParams; + PxVehicleArrayData suspensionParams; + PxVehicleArrayData suspensionComplianceParams; + PxVehicleArrayData suspensionForceParams; + PxVehicleSizedArrayData antiRollForceParams; + PxVehicleArrayData wheelRoadGeomStates; + PxVehicleArrayData suspensionStates; + PxVehicleArrayData suspensionComplianceStates; + PxVehicleArrayData suspensionForces; + PxVehicleAntiRollTorque* antiRollTorque; + + getDataForSuspensionComponent(axleDescription, rigidBodyParams, suspensionStateCalculationParams, + steerResponseStates, rigidBodyState, + wheelParams, suspensionParams, + suspensionComplianceParams, suspensionForceParams, antiRollForceParams, + wheelRoadGeomStates, suspensionStates, suspensionComplianceStates, + suspensionForces, antiRollTorque); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + //Update the suspension state (jounce, jounce speed) + PxVehicleSuspensionStateUpdate( + wheelParams[wheelId], suspensionParams[wheelId], *suspensionStateCalculationParams, + suspensionForceParams[wheelId].stiffness, suspensionForceParams[wheelId].damping, + steerResponseStates[wheelId], wheelRoadGeomStates[wheelId], + *rigidBodyState, + dt, context.frame, context.gravity, + suspensionStates[wheelId]); + + //Update the compliance from the suspension state. + PxVehicleSuspensionComplianceUpdate( + suspensionParams[wheelId], suspensionComplianceParams[wheelId], + suspensionStates[wheelId], + suspensionComplianceStates[wheelId]); + + //Compute the suspension force from the suspension and compliance states. + PxVehicleSuspensionForceUpdate( + suspensionParams[wheelId], suspensionForceParams[wheelId], + wheelRoadGeomStates[wheelId], suspensionStates[wheelId], + suspensionComplianceStates[wheelId], *rigidBodyState, + context.gravity, rigidBodyParams->mass, + suspensionForces[wheelId]); + } + + if (antiRollForceParams.size>0 && antiRollTorque) + { + PxVehicleAntiRollForceUpdate( + suspensionParams, antiRollForceParams, + suspensionStates.getConst(), suspensionComplianceStates.getConst(), *rigidBodyState, + *antiRollTorque); + } + + return true; + } +}; + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. +*/ +class PX_DEPRECATED PxVehicleLegacySuspensionComponent : public PxVehicleComponent +{ +public: + + PxVehicleLegacySuspensionComponent() : PxVehicleComponent() {} + virtual ~PxVehicleLegacySuspensionComponent() {} + + /** + \brief Retrieve pointers to the parameter and state data required to compute the suspension state and the forces/torques that arise from the suspension state. + \param[out] axleDescription must be returned as a non-null pointer to a single PxVehicleAxleDescription instance that describes the wheels and axles + of the vehicle. + \param[out] suspensionStateCalculationParams must be returned as a non-null pointer to a single PxVehicleSuspensionStateCalculationParams instance + that describes the jounce computation type etc. + \param[out] steerResponseStates must be returned as a non-null pointer to a single PxVehicleSteerCommandResponseStates instance that describes the steer + state of the wheels. + \param[out] rigidBodyState must be returned as a non-null pointer to a single PxVehicleRigidBodyState instance that describes the pose and momentum of + the vehicle's rigid body. + \param[out] wheelParams must be set to a non-null pointer to an array of PxVehicleWheelParams containing per-wheel parameters for each wheel + referenced by axleDescription. + \param[out] suspensionParams must be set to a non-null pointer to an array of PxVehicleSuspensionParams containing per-wheel parameters for each + wheel referenced by axleDescription. + \param[out] suspensionComplianceParams must be set to a non-null pointer to an array of PxVehicleSuspensionComplianceParams containing per-wheel + parameters for each wheel referenced by axleDescription. + \param[out] suspensionForceParams must be set to a non-null pointer to an array of PxVehicleSuspensionForceLegacyParams containing per-wheel parameters + for each wheel referenced by axleDescription. + \param[out] antiRollForceParams is optionally returned as a non-null pointer to an array of PxVehicleAntiRollForceParams with each element in the array + describing a unique anti-roll bar connecting a pair of wheels. + \param[out] wheelRoadGeomStates must be set to non-null pointer to an array of PxVehicleRoadGeometryState containing per-wheel road geometry for + each wheel referenced by axleDescription. + \param[out] suspensionStates must be set to a non-null pointer to an array of PxVehicleSuspensionState containing per-wheel suspension state for each + wheel referenced by axleDescription. + \param[out] suspensionComplianceStates must be set to a non-null pointer to an array of PxVehicleSuspensionComplianceState containing per-wheel suspension + compliance state for each wheel referenced by axleDescription. + \param[out] suspensionForces must be set to a non-null pointer to an array of PxVehicleSuspensionForce containing per-wheel suspension forces for each + wheel referenced by axleDescription. + \param[out] antiRollTorque is optionally returned as a non-null pointer to a single PxVehicleAntiRollTorque instance that will store the accumulated anti-roll + torque to be applied to the vheicle's rigid body. + \note antiRollForceParams and antiRollTorque should be returned either both non-NULL or both NULL. + */ + virtual void getDataForLegacySuspensionComponent( + const PxVehicleAxleDescription*& axleDescription, + const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, + PxVehicleArrayData& steerResponseStates, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& suspensionParams, + PxVehicleArrayData& suspensionComplianceParams, + PxVehicleArrayData& suspensionForceParams, + PxVehicleSizedArrayData& antiRollForceParams, + PxVehicleArrayData& wheelRoadGeomStates, + PxVehicleArrayData& suspensionStates, + PxVehicleArrayData& suspensionComplianceStates, + PxVehicleArrayData& suspensionForces, + PxVehicleAntiRollTorque*& antiRollTorque) = 0; + + /** + \brief Update the suspension state and suspension compliance state and use those updated states to compute suspension and anti-roll forces/torques + to apply to the vehicle's rigid body. + \param[in] dt is the simulation time that has passed since the last call to PxVehicleSuspensionComponent::update() + \param[in] context describes a variety of global simulation constants such as frame and scale of the simulation and the gravitational acceleration + of the simulated environment. + \note The suspension and anti-roll forces are computed in the world frame. + \note PxVehicleLegacySuspensionComponent::update() implements legacy suspension behaviour. + */ + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_PROFILE_ZONE("PxVehicleLegacySuspensionComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + const PxVehicleSuspensionStateCalculationParams* suspensionStateCalculationParams; + PxVehicleArrayData steerResponseStates; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData wheelParams; + PxVehicleArrayData suspensionParams; + PxVehicleArrayData suspensionComplianceParams; + PxVehicleArrayData suspensionForceParams; + PxVehicleSizedArrayData antiRollForceParams; + PxVehicleArrayData wheelRoadGeomStates; + PxVehicleArrayData suspensionStates; + PxVehicleArrayData suspensionComplianceStates; + PxVehicleArrayData suspensionForces; + PxVehicleAntiRollTorque* antiRollTorque; + + getDataForLegacySuspensionComponent(axleDescription, suspensionStateCalculationParams, + steerResponseStates, rigidBodyState, wheelParams, + suspensionParams, suspensionComplianceParams, + suspensionForceParams, antiRollForceParams, + wheelRoadGeomStates, suspensionStates, suspensionComplianceStates, + suspensionForces, antiRollTorque); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + //Update the suspension state (jounce, jounce speed) + PxVehicleSuspensionStateUpdate( + wheelParams[wheelId], suspensionParams[wheelId], *suspensionStateCalculationParams, + suspensionForceParams[wheelId].stiffness, suspensionForceParams[wheelId].damping, + steerResponseStates[wheelId], wheelRoadGeomStates[wheelId], *rigidBodyState, + dt, context.frame, context.gravity, + suspensionStates[wheelId]); + + //Update the compliance from the suspension state. + PxVehicleSuspensionComplianceUpdate( + suspensionParams[wheelId], suspensionComplianceParams[wheelId], + suspensionStates[wheelId], + suspensionComplianceStates[wheelId]); + + //Compute the suspension force from the suspension and compliance states. + PxVehicleSuspensionLegacyForceUpdate( + suspensionParams[wheelId], suspensionForceParams[wheelId], + wheelRoadGeomStates[wheelId], suspensionStates[wheelId], + suspensionComplianceStates[wheelId], *rigidBodyState, + context.gravity, + suspensionForces[wheelId]); + } + + if (antiRollForceParams.size>0 && antiRollTorque) + { + PxVehicleAntiRollForceUpdate( + suspensionParams, antiRollForceParams, + suspensionStates.getConst(), suspensionComplianceStates.getConst(), *rigidBodyState, + *antiRollTorque); + } + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionFunctions.h new file mode 100644 index 000000000..cf40bdeef --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionFunctions.h @@ -0,0 +1,163 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxVec3.h" +#include "foundation/PxSimpleTypes.h" +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleWheelParams; +struct PxVehicleSuspensionParams; +struct PxVehicleSuspensionStateCalculationParams; +struct PxVehicleRoadGeometryState; +struct PxVehicleRigidBodyState; +struct PxVehicleSuspensionState; +struct PxVehicleSuspensionComplianceParams; +struct PxVehicleSuspensionComplianceState; +struct PxVehicleSuspensionForceParams; +struct PxVehicleSuspensionForce; +struct PxVehicleSuspensionForceLegacyParams; +struct PxVehicleAntiRollForceParams; +struct PxVehicleAntiRollTorque; + +/** +\brief Compute the suspension compression and compression speed for a single suspension. +\param[in] wheelParams is a description of the radius and half-width of the wheel on the suspension. +\param[in] suspensionParams is a description of the suspension and wheel frames. +\param[in] suspensionStateCalcParams specifies whether to compute the suspension compression by either +raycasting or sweeping against the plane of the road geometry under the wheel. +\param[in] suspensionStiffness is the stiffness of the suspension +\param[in] suspensionDamping is the damping rate of the suspension. +or whether to apply a limit to the expansion speed so that the wheel may not reach the ground. +\param[in] steerAngle is the yaw angle (in radians) of the wheel. +\param[in] roadGeometryState describes the plane under the wheel. +\param[in] rigidBodyState describes the pose of the rigid body. +\param[in] dt is the simulation time that has lapsed since the last call to PxVehicleSuspensionStateUpdate +\param[in] frame describes the longitudinal, lateral and vertical axes of the vehicle. +\param[in] gravity is the gravitational acceleration that acts on the suspension sprung mass. +\param[in,out] suspState is the compression (jounce) and compression speed of the suspension. +*/ +void PxVehicleSuspensionStateUpdate +(const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspensionParams, const PxVehicleSuspensionStateCalculationParams& suspensionStateCalcParams, + const PxReal suspensionStiffness, const PxReal suspensionDamping, + const PxReal steerAngle, const PxVehicleRoadGeometryState& roadGeometryState, const PxVehicleRigidBodyState& rigidBodyState, + const PxReal dt, const PxVehicleFrame& frame, const PxVec3& gravity, + PxVehicleSuspensionState& suspState); + +/** +\brief Compute the toe, camber and force application points that are affected by suspension compression. +\param[in] suspensionParams is a description of the suspension and wheel frames. +\param[in] complianceParams describes how toe, camber and force application points are affected by suspension compression. +\param[in] suspensionState describes the current suspension compression. +\param[in] complianceState is the computed toe, camber and force application points. +*/ +void PxVehicleSuspensionComplianceUpdate +(const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleSuspensionComplianceParams& complianceParams, + const PxVehicleSuspensionState& suspensionState, + PxVehicleSuspensionComplianceState& complianceState); + +/** +\brief Compute the suspension force and torque arising from suspension compression and speed. +\param[in] suspensionParams is a description of the suspension and wheel frames. +\param[in] suspensionForceParams describes the conversion of suspension state to suspension force. +\param[in] roadGeometryState describes the plane under the wheel of the suspension. +\param[in] suspensionState is the current compression state of the suspension. +\param[in] complianceState is the current compliance state of the suspension. +\param[in] rigidBodyState describes the current pose of the rigid body. +\param[in] gravity is the gravitational acceleration. +\param[in] vehicleMass is the rigid body mass. +\param[out] suspensionForce is the force and torque to apply to the rigid body arising from the suspension state. +*/ +void PxVehicleSuspensionForceUpdate +(const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleSuspensionForceParams& suspensionForceParams, + const PxVehicleRoadGeometryState& roadGeometryState, const PxVehicleSuspensionState& suspensionState, + const PxVehicleSuspensionComplianceState& complianceState, const PxVehicleRigidBodyState& rigidBodyState, + const PxVec3& gravity, const PxReal vehicleMass, + PxVehicleSuspensionForce& suspensionForce); + + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Compute the suspension force and torque arising from suspension compression and speed. +\param[in] suspensionParams is a description of the suspension and wheel frames. +\param[in] suspensionForceParams describes the conversion of suspension state to suspension force. +\param[in] roadGeometryState describes the plane under the wheel of the suspension. +\param[in] suspensionState is the current compression state of the suspension. +\param[in] complianceState is the current compliance state of the suspension. +\param[in] rigidBodyState describes the current pose of the rigid body. +\param[in] gravity is the gravitational acceleration. +\param[out] suspensionForce is the force and torque to apply to the rigid body arising from the suspension state. +\note PxVehicleSuspensionLegacyForceUpdate implements the legacy force computation of PhysX 5.0 and earlier. +*/ +PX_DEPRECATED void PxVehicleSuspensionLegacyForceUpdate +(const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleSuspensionForceLegacyParams& suspensionForceParams, + const PxVehicleRoadGeometryState& roadGeometryState, const PxVehicleSuspensionState& suspensionState, + const PxVehicleSuspensionComplianceState& complianceState, const PxVehicleRigidBodyState& rigidBodyState, + const PxVec3& gravity, + PxVehicleSuspensionForce& suspensionForce); + +/** +\brief Compute the accumulated anti-roll torque to apply to the vehicle's rigid body. +\param[in] suspensionParams The suspension parameters for each wheel. +\param[in] antiRollParams describes the wheel pairs connected by anti-roll bars and the strength of each anti-roll bar. +\param[in] suspensionStates The suspension states for each wheel. +\param[in] complianceStates The suspension compliance states for each wheel. +\param[in] rigidBodyState describes the pose and momentum of the vehicle's rigid body in the world frame. +\param[in] antiRollTorque is the accumulated anti-roll torque that is computed by iterating over all anti-roll bars +describes in *antiRollParams*. +\note suspensionParams must contain an entry for each wheel index referenced by *antiRollParams*. +\note suspensionStates must contain an entry for each wheel index referenced by *antiRollParams*. +\note complianceStates must contain an entry for each wheel index referenced by *antiRollParams*. +\note antiRollTorque is expressed in the world frame. +*/ +void PxVehicleAntiRollForceUpdate +(const PxVehicleArrayData& suspensionParams, + const PxVehicleSizedArrayData& antiRollParams, + const PxVehicleArrayData& suspensionStates, + const PxVehicleArrayData& complianceStates, + const PxVehicleRigidBodyState& rigidBodyState, + PxVehicleAntiRollTorque& antiRollTorque); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionHelpers.h new file mode 100644 index 000000000..dcd8e919a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionHelpers.h @@ -0,0 +1,149 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxTransform.h" + +#include "vehicle2/wheel/PxVehicleWheelParams.h" +#include "vehicle2/wheel/PxVehicleWheelHelpers.h" + +#include "PxVehicleSuspensionParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Compute suspension travel direction in the world frame. +\param[in] suspensionParams is a description of the suspension frame. +\param[in] rigidBodyPose is the current pose of the vehicle's rigid body. +\return The return value is the suspension travel direction in the world frame. +\note The suspension travel direction is used to perform queries against the road geometry. +*/ +PX_FORCE_INLINE PxVec3 PxVehicleComputeSuspensionDirection(const PxVehicleSuspensionParams& suspensionParams, const PxTransform& rigidBodyPose) +{ + const PxVec3 suspDir = rigidBodyPose.rotate(suspensionParams.suspensionTravelDir); + return suspDir; +} + +/** +\brief Compute the start pose of a suspension query. +\param[in] frame is a description of the longitudinal, lateral and vertical axes. +\param[in] suspensionParams is a description of the suspension frame. +\param[in] steerAngle is the yaw angle of the wheel in radians. +\param[in] rigidBodyPose is the pose of the rigid body in the world frame. +*/ +PX_FORCE_INLINE PxTransform PxVehicleComputeWheelPoseForSuspensionQuery(const PxVehicleFrame& frame, const PxVehicleSuspensionParams& suspensionParams, + const PxReal steerAngle, const PxTransform& rigidBodyPose) +{ + //Compute the wheel pose with zero travel from attachment point, zero compliance, + //zero wheel pitch (ignore due to radial symmetry). + //Zero travel from attachment point (we want the wheel pose at the top of the suspension, i.e., at max compression) + PxVehicleSuspensionState suspState; + suspState.setToDefault(); + //Compute the wheel pose. + const PxTransform wheelPose = PxVehicleComputeWheelPose(frame, suspensionParams, suspState, 0.0f, 0.0f, steerAngle, rigidBodyPose, + 0.0f); + + return wheelPose; +} + +/** +\brief Compute the start point, direction and length of a suspension scene raycast. +\param[in] frame is a description of the longitudinal, lateral and vertical axes. +\param[in] wheelParams describes the radius and halfwidth of the wheel. +\param[in] suspensionParams describes the suspension frame and the maximum suspension travel. +\param[in] steerAngle is the yaw angle of the wheel in radians. +\param[in] rigidBodyPose is the pose of the rigid body in the world frame. +\param[out] start is the starting point of the raycast in the world frame. +\param[out] dir is the direction of the raycast in the world frame. +\param[out] dist is the length of the raycast. +\note start, dir and dist together describe a raycast that begins at the top of wheel at maximum compression +and ends at the bottom of wheel at maximum droop. +*/ +PX_FORCE_INLINE void PxVehicleComputeSuspensionRaycast +(const PxVehicleFrame& frame, const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspensionParams, + const PxF32 steerAngle, const PxTransform& rigidBodyPose, + PxVec3& start, PxVec3& dir, PxReal& dist) +{ + const PxTransform wheelPose = PxVehicleComputeWheelPoseForSuspensionQuery(frame, suspensionParams, steerAngle, rigidBodyPose); + + //Raycast from top of wheel at max compression to bottom of wheel at max droop. + dir = PxVehicleComputeSuspensionDirection(suspensionParams, rigidBodyPose); + start = wheelPose.p - dir * wheelParams.radius; + dist = suspensionParams.suspensionTravelDist + 2.0f*wheelParams.radius; +} + +/** +\brief Compute the start pose, direction and length of a suspension scene sweep. +\param[in] frame is a description of the longitudinal, lateral and vertical axes. +\param[in] suspensionParams describes the suspension frame and the maximum suspension travel. +\param[in] steerAngle is the yaw angle of the wheel in radians. +\param[in] rigidBodyPose is the pose of the rigid body in the world frame. +\param[out] start is the start pose of the sweep in the world frame. +\param[out] dir is the direction of the sweep in the world frame. +\param[out] dist is the length of the sweep. +\note start, dir and dist together describe a sweep that begins with the wheel placed at maximum +compression and ends at the maximum droop pose. +*/ +PX_FORCE_INLINE void PxVehicleComputeSuspensionSweep +(const PxVehicleFrame& frame, const PxVehicleSuspensionParams& suspensionParams, + const PxReal steerAngle, const PxTransform& rigidBodyPose, + PxTransform& start, PxVec3& dir, PxReal& dist) +{ + start = PxVehicleComputeWheelPoseForSuspensionQuery(frame, suspensionParams, steerAngle, rigidBodyPose); + dir = PxVehicleComputeSuspensionDirection(suspensionParams, rigidBodyPose); + dist = suspensionParams.suspensionTravelDist; +} + + +/** +\brief Compute the sprung masses of the suspension springs given (i) the number of sprung masses, +(ii) coordinates of the sprung masses in the rigid body frame, (iii) the center of mass offset of the rigid body, (iv) the +total mass of the rigid body, and (v) the direction of gravity +\param[in] nbSprungMasses is the number of sprung masses of the vehicle. This value corresponds to the number of wheels on the vehicle. +\param[in] sprungMassCoordinates are the coordinates of the sprung masses in the rigid body frame. The array sprungMassCoordinates must be of +length nbSprungMasses or greater. +\param[in] totalMass is the total mass of all the sprung masses. +\param[in] gravityDirection describes the direction of gravitational acceleration. +\param[out] sprungMasses are the masses to set in the associated suspension data with PxVehicleSuspensionData::mSprungMass. The sprungMasses array must be of length +nbSprungMasses or greater. Each element in the sprungMasses array corresponds to the suspension located at the same array element in sprungMassCoordinates. +The center of mass of the masses in sprungMasses with the coordinates in sprungMassCoordinates satisfy the specified centerOfMass. +\return True if the sprung masses were successfully computed, false if the sprung masses were not successfully computed. +*/ +bool PxVehicleComputeSprungMasses(const PxU32 nbSprungMasses, const PxVec3* sprungMassCoordinates, const PxReal totalMass, const PxVehicleAxes::Enum gravityDirection, PxReal* sprungMasses); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionParams.h new file mode 100644 index 000000000..28dab468f --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionParams.h @@ -0,0 +1,411 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxTransform.h" +#include "foundation/PxFoundation.h" + +#include "common/PxCoreUtilityTypes.h" + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleFunctions.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleSuspensionParams +{ + /** + \brief suspensionAttachment specifies the wheel pose at maximum compression. + \note suspensionAttachment is specified in the frame of the rigid body. + \note camber, steer and toe angles are all applied in the suspension frame. + */ + PxTransform suspensionAttachment; + + /** + \brief suspensionTravelDir specifies the direction of suspension travel. + \note suspensionTravelDir is specified in the frame of the rigid body. + */ + PxVec3 suspensionTravelDir; + + /** + \brief suspensionTravelDist is the maximum distance that the suspenson can elongate along #suspensionTravelDir + from the pose specified by #suspensionAttachment. + \note The position suspensionAttachment.p + #suspensionTravelDir*#suspensionTravelDist corresponds to the + the suspension at maximum droop in the rigid body frame. + */ + PxReal suspensionTravelDist; + + /** + \brief wheelAttachment is the pose of the wheel in the suspension frame. + \note The rotation angle around the wheel's lateral axis is applied in the wheel attachment frame. + */ + PxTransform wheelAttachment; + + + PX_FORCE_INLINE PxVehicleSuspensionParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PxVehicleSuspensionParams r = *this; + r.suspensionAttachment = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, suspensionAttachment); + r.suspensionTravelDir = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, suspensionTravelDir); + r.suspensionTravelDist *= (trgScale.scale/srcScale.scale); + r.wheelAttachment = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, wheelAttachment); + return r; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(suspensionAttachment.isValid(), "PxVehicleSuspensionParams.suspensionAttachment must be a valid transform", false); + PX_CHECK_AND_RETURN_VAL(suspensionTravelDir.isFinite(), "PxVehicleSuspensionParams.suspensionTravelDir must be a valid vector", false); + PX_CHECK_AND_RETURN_VAL(suspensionTravelDir.isNormalized(), "PxVehicleSuspensionParams.suspensionTravelDir must be a unit vector", false); + PX_CHECK_AND_RETURN_VAL(suspensionTravelDist > 0.0f, "PxVehicleSuspensionParams.suspensionTravelDist must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(wheelAttachment.isValid(), "PxVehicleSuspensionParams.wheelAttachment must be a valid transform", false); + return true; + } +}; + +struct PxVehicleSuspensionJounceCalculationType +{ + enum Enum + { + eRAYCAST, //!< The jounce is calculated using a raycast against the plane of the road geometry state + eSWEEP, //!< The jounce is calculated by sweeping a cylinder against the plane of the road geometry state + eMAX_NB + }; +}; + +struct PxVehicleSuspensionStateCalculationParams +{ + PxVehicleSuspensionJounceCalculationType::Enum suspensionJounceCalculationType; + + /** + \brief Limit the suspension expansion dynamics. + + If a hit with the ground is detected, the suspension jounce will be set such that the wheel + is placed on the ground. This can result in large changes to jounce within a single + simulation frame, if the ground surface has high frequency or if the simulation time step + is large. As a result, large damping forces can evolve and cause undesired behavior. If this + parameter is set to true, the suspension expansion speed will be limited to what can be + achieved given the time step, suspension stiffness etc. As a consequence, handling of the + vehicle will be affected as the wheel might loose contact with the ground more easily. + */ + bool limitSuspensionExpansionVelocity; + + PX_FORCE_INLINE PxVehicleSuspensionStateCalculationParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid() const + { + return true; + } +}; + +/** +\brief Compliance describes how toe and camber angle and force application points are affected by suspension compression. +\note Each compliance term is in the form of a graph with up to 3 points. +\note Each point in the graph has form (jounce/suspensionTravelDist, complianceValue). +\note The sequence of points must respresent monotonically increasing values of jounce. +\note The compliance value can be computed by linear interpolation. +\note If any graph has zero points in it, a value of 0.0 is used for the compliance value. +\note If any graph has 1 point in it, the compliance value of that point is used directly. +*/ +struct PxVehicleSuspensionComplianceParams +{ + /** + \brief A graph of toe angle against jounce/suspensionTravelDist with the toe angle expressed in radians. + \note The toe angle is applied in the suspension frame. + */ + PxVehicleFixedSizeLookupTable wheelToeAngle; + + /** + \brief A graph of camber angle against jounce/suspensionTravelDist with the camber angle expressed in radians. + \note The camber angle is applied in the suspension frame. + */ + PxVehicleFixedSizeLookupTable wheelCamberAngle; + + /** + \brief Suspension forces are applied at an offset from the suspension frame. suspForceAppPoint + specifies the (X, Y, Z) components of that offset as a function of jounce/suspensionTravelDist. + */ + PxVehicleFixedSizeLookupTable suspForceAppPoint; + + /** + \brief Tire forces are applied at an offset from the suspension frame. tireForceAppPoint + specifies the (X, Y, Z) components of that offset as a function of jounce/suspensionTravelDist. + */ + PxVehicleFixedSizeLookupTable tireForceAppPoint; + + PX_FORCE_INLINE PxVehicleSuspensionComplianceParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleSuspensionComplianceParams r = *this; + + const PxReal scale = trgScale.scale / srcScale.scale; + for (PxU32 i = 0; i < r.suspForceAppPoint.nbDataPairs; i++) + { + r.suspForceAppPoint.yVals[i] = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, suspForceAppPoint.yVals[i]); + r.suspForceAppPoint.yVals[i] *= scale; + } + for (PxU32 i = 0; i < r.tireForceAppPoint.nbDataPairs; i++) + { + r.tireForceAppPoint.yVals[i] = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, tireForceAppPoint.yVals[i]); + r.tireForceAppPoint.yVals[i] *= scale; + } + return r; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(wheelToeAngle.isValid(), "PxVehicleSuspensionComplianceParams.wheelToeAngle is invalid", false); + PX_CHECK_AND_RETURN_VAL(wheelCamberAngle.isValid(), "PxVehicleSuspensionComplianceParams.wheelCamberAngle is invalid", false); + PX_CHECK_AND_RETURN_VAL(suspForceAppPoint.isValid(), "PxVehicleSuspensionComplianceParams.wheelToeAngle is invalid", false); + PX_CHECK_AND_RETURN_VAL(tireForceAppPoint.isValid(), "PxVehicleSuspensionComplianceParams.wheelCamberAngle is invalid", false); + + for (PxU32 i = 0; i < wheelToeAngle.nbDataPairs; i++) + { + PX_CHECK_AND_RETURN_VAL(wheelToeAngle.xVals[i] >= 0.0f && wheelToeAngle.xVals[i] <= 1.0f, "PxVehicleSuspensionComplianceParams.wheelToeAngle must be an array of points (x,y) with x in range [0, 1]", false); + PX_CHECK_AND_RETURN_VAL(wheelToeAngle.yVals[i] >= -PxPi && wheelToeAngle.yVals[i] <= PxPi, "PxVehicleSuspensionComplianceParams.wheelToeAngle must be an array of points (x,y) with y in range [-Pi, Pi]", false); + } + for (PxU32 i = 0; i < wheelCamberAngle.nbDataPairs; i++) + { + PX_CHECK_AND_RETURN_VAL(wheelCamberAngle.xVals[i] >= 0.0f && wheelCamberAngle.xVals[i] <= 1.0f, "PxVehicleSuspensionComplianceParams.wheelCamberAngle must be an array of points (x,y) with x in range [0, 1]", false); + PX_CHECK_AND_RETURN_VAL(wheelCamberAngle.yVals[i] >= -PxPi && wheelCamberAngle.yVals[i] <= PxPi, "PxVehicleSuspensionComplianceParams.wheelCamberAngle must be an array of points (x,y) with y in range [-Pi, Pi]", false); + } + + for (PxU32 i = 0; i < suspForceAppPoint.nbDataPairs; i++) + { + PX_CHECK_AND_RETURN_VAL(suspForceAppPoint.xVals[i] >= 0.0f && suspForceAppPoint.xVals[i] <= 1.0f, "PxVehicleSuspensionComplianceParams.suspForceAppPoint[0] must be an array of points (x,y) with x in range [0, 1]", false); + } + for (PxU32 i = 0; i < tireForceAppPoint.nbDataPairs; i++) + { + PX_CHECK_AND_RETURN_VAL(tireForceAppPoint.xVals[i] >= 0.0f && tireForceAppPoint.xVals[i] <= 1.0f, "PxVehicleSuspensionComplianceParams.tireForceAppPoint[0] must be an array of points (x,y) with x in range [0, 1]", false); + } + return true; + } +}; + +/** +\brief Suspension force is computed by converting suspenson state to suspension force under the assumption of a linear spring. +\see PxVehicleSuspensionForceUpdate +*/ +struct PxVehicleSuspensionForceParams +{ + /** + \brief Spring strength of suspension. + + Range: (0, inf)
+ Unit: mass / (time^2) + */ + PxReal stiffness; + + /** + \brief Spring damper rate of suspension. + + Range: [0, inf)
+ Unit: mass / time + */ + PxReal damping; + + /** + \brief Part of the vehicle mass that is supported by the suspension spring. + + Range: (0, inf)
+ Unit: mass + */ + PxReal sprungMass; + + PX_FORCE_INLINE PxVehicleSuspensionForceParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(stiffness > 0.0f, "PxVehicleSuspensionForceParams.stiffness must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(damping >= 0.0f, "PxVehicleSuspensionForceParams.damping must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(sprungMass > 0.0f, "PxVehicleSuspensionForceParams.sprungMass must be greater than zero", false); + return true; + } +}; + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Suspension force is computed by converting suspenson state to suspension force under the assumption of a linear spring. +\see PxVehicleSuspensionLegacyForceUpdate +*/ +struct PX_DEPRECATED PxVehicleSuspensionForceLegacyParams +{ + /** + \brief Spring strength of suspension. + + Range: (0, inf)
+ Unit: mass / (time^2) + */ + PxReal stiffness; + + /** + \brief Spring damper rate of suspension. + + Range: [0, inf)
+ Unit: mass / time + */ + PxReal damping; + + /** + \brief The suspension compression that balances the gravitational force acting on the sprung mass. + + Range: (0, inf)
+ Unit: length + */ + PxReal restDistance; + + /** + \brief The mass supported by the suspension spring. + + Range: (0, inf)
+ Unit: mass + */ + PxReal sprungMass; + + PX_FORCE_INLINE PxVehicleSuspensionForceLegacyParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleSuspensionForceLegacyParams r = *this; + r.restDistance *= (trgScale.scale / srcScale.scale); + return *this; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(stiffness > 0.0f, "PxVehicleSuspensionForceLegacyParams.stiffness must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(damping >= 0.0f, "PxVehicleSuspensionForceLegacyParams.damping must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(restDistance > 0.0f, "PxVehicleSuspensionForceLegacyParams.restDistance must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(sprungMass > 0.0f, "PxVehicleSuspensionForceLegacyParams.sprungMass must be greater than zero", false); + return true; + } + +}; + +/** +\brief The purpose of the anti-roll bar is to generate a torque to apply to the vehicle's rigid body that will reduce the jounce difference arising +between any pair of chosen wheels. If the chosen wheels share an axle, the anti-roll bar will attempt to reduce the roll angle of the vehicle's rigid body. +Alternatively, if the chosen wheels are the front and rear wheels along one side of the vehicle, the anti-roll bar will attempt to reduce the pitch angle of the +vehicle's rigid body. +*/ +struct PxVehicleAntiRollForceParams +{ + /* + \brief The anti-roll bar connects two wheels with indices wheel0 and wheel1 + \note wheel0 and wheel1 may be chosen to have the effect of an anti-dive bar or to have the effect of an anti-roll bar. + */ + PxU32 wheel0; + + /* + \brief The anti-roll bar connects two wheels with indices wheel0 and wheel1 + \note wheel0 and wheel1 may be chosen to have the effect of an anti-dive bar or to have the effect of an anti-roll bar. + */ + PxU32 wheel1; + + /* + \brief The linear stiffness of the anti-roll bar. + \note A positive stiffness will work to reduce the discrepancy in jounce between wheel0 and wheel1. + \note A negative stiffness will work to increase the discrepancy in jounce between wheel0 and wheel1. + + Unit: mass / (time^2) + */ + PxReal stiffness; + + PX_FORCE_INLINE PxVehicleAntiRollForceParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PX_UNUSED(srcScale); + PX_UNUSED(trgScale); + return *this; + } + + PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const + { + if (!PxIsFinite(stiffness)) + return false; + if (wheel0 == wheel1) + return false; + + //Check that each wheel id is a valid wheel. + const PxU32 wheelIds[2] = { wheel0, wheel1 }; + for (PxU32 k = 0; k < 2; k++) + { + const PxU32 wheelToFind = wheelIds[k]; + bool foundWheelInAxleDescription = false; + for (PxU32 i = 0; i < axleDesc.nbWheels; i++) + { + const PxU32 wheel = axleDesc.wheelIdsInAxleOrder[i]; + if (wheel == wheelToFind) + { + foundWheelInAxleDescription = true; + } + } + if (!foundWheelInAxleDescription) + return false; + } + + return true; + } +}; + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionStates.h new file mode 100644 index 000000000..e540e7fd8 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/suspension/PxVehicleSuspensionStates.h @@ -0,0 +1,185 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxVec3.h" +#include "foundation/PxMemory.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +#define PX_VEHICLE_UNSPECIFIED_JOUNCE PX_MAX_F32 +#define PX_VEHICLE_UNSPECIFIED_SEPARATION PX_MAX_F32 + +/** + +*/ +struct PxVehicleSuspensionState +{ + /** + \brief jounce is the distance from maximum droop. + \note jounce is positive semi-definite + \note A value of 0.0 represents the suspension at maximum droop and zero suspension force. + \note A value of suspensionTravelDist represents the suspension at maximum compression. + \note jounce is clamped in range [0, suspensionTravelDist]. + */ + PxReal jounce; + + /** + \brief jounceSpeed is the rate of change of jounce. + */ + PxReal jounceSpeed; + + /** + \brief separation holds extra information about the contact state of the wheel with the ground. + + If the suspension travel range is enough to place the wheel on the ground, then separation will be 0. + If separation holds a negative value, then the wheel penetrates into the ground at maximum compression + as well as maximum droop. The suspension would need to go beyond maximum compression (ground normal + pointing in opposite direction of suspension) or beyond maximum droop (ground normal pointing in same + direction as suspension) to place the wheel on the ground. In that case the separation value defines + how much the wheel penetrates into the ground along the ground plane normal. This penetration may be + resolved by using a constraint that simulates the effect of a bump stop. + If separation holds a positive value, then the wheel does not penetrate the ground at maximum droop + but can not touch the ground because the suspension would need to expand beyond max droop to reach it + or because the suspension could not expand fast enough to reach the ground. + */ + PxReal separation; + + PX_FORCE_INLINE void setToDefault(const PxReal _jounce = PX_VEHICLE_UNSPECIFIED_JOUNCE, + const PxReal _separation = PX_VEHICLE_UNSPECIFIED_SEPARATION) + { + jounce = _jounce; + jounceSpeed = 0; + separation = _separation; + } +}; + +/** +\brief The effect of suspension compliance on toe and camber angle and on the tire and suspension force application points. +*/ +struct PxVehicleSuspensionComplianceState +{ + /** + \brief The toe angle in radians that arises from suspension compliance. + \note toe is expressed in the suspension frame. + */ + PxReal toe; + + /** + \brief The camber angle in radians that arises from suspension compliance. + \note camber is expressed in the suspension frame. + */ + PxReal camber; + + /** + \brief The tire force application point that arises from suspension compliance. + \note tireForceAppPoint is expressed in the suspension frame. + */ + PxVec3 tireForceAppPoint; + + /** + \brief The suspension force application point that arises from suspension compliance. + \note suspForceAppPoint is expressed in the suspension frame. + */ + PxVec3 suspForceAppPoint; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleSuspensionComplianceState)); + } +}; + +/** +\brief The force and torque for a single suspension to apply to the vehicle's rigid body. +*/ +struct PxVehicleSuspensionForce +{ + /** + \brief The force to apply to the rigid body. + \note force is expressed in the world frame. + + Unit: mass * length / (time^2) + */ + PxVec3 force; + + /** + \brief The torque to apply to the rigid body. + \note torque is expressed in the world frame. + + Unit: mass * (length^2) / (time^2) + */ + PxVec3 torque; + + /** + \brief The component of force that lies along the normal of the plane under the wheel. + \note normalForce may be used by the tire model as the tire load. + + Unit: mass * length / (time^2) + */ + PxReal normalForce; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleSuspensionForce)); + } +}; + +/** +\brief The anti-roll torque of all anti-roll bars accumulates in a single torque to apply +to the vehicle's rigid body. +*/ +struct PxVehicleAntiRollTorque +{ + /** + \brief The accumulated torque to apply to the rigid body. + \note antiRollTorque is expressed in the world frame. + + Unit: mass * (length^2) / (time^2) + */ + PxVec3 antiRollTorque; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleAntiRollTorque)); + } +}; + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireComponents.h new file mode 100644 index 000000000..63fb09296 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireComponents.h @@ -0,0 +1,341 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "vehicle2/commands/PxVehicleCommandHelpers.h" +#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h" +#include "vehicle2/suspension/PxVehicleSuspensionParams.h" +#include "vehicle2/suspension/PxVehicleSuspensionStates.h" +#include "vehicle2/wheel/PxVehicleWheelStates.h" +#include "vehicle2/wheel/PxVehicleWheelParams.h" +#include "vehicle2/wheel/PxVehicleWheelHelpers.h" + +#include "PxVehicleTireFunctions.h" +#include "PxVehicleTireParams.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +class PxVehicleTireComponent : public PxVehicleComponent +{ +public: + + PxVehicleTireComponent() : PxVehicleComponent() {} + virtual ~PxVehicleTireComponent() {} + + virtual void getDataForTireComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleArrayData& steerResponseStates, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& actuationStates, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& suspensionParams, + PxVehicleArrayData& tireForceParams, + PxVehicleArrayData& roadGeomStates, + PxVehicleArrayData& suspensionStates, + PxVehicleArrayData& suspensionComplianceStates, + PxVehicleArrayData& suspensionForces, + PxVehicleArrayData& wheelRigidBody1DStates, + PxVehicleArrayData& tireGripStates, + PxVehicleArrayData& tireDirectionStates, + PxVehicleArrayData& tireSpeedStates, + PxVehicleArrayData& tireSlipStates, + PxVehicleArrayData& tireCamberAngleStates, + PxVehicleArrayData& tireStickyStates, + PxVehicleArrayData& tireForces) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_PROFILE_ZONE("PxVehicleTireComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleArrayData steerResponseStates; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData actuationStates; + PxVehicleArrayData wheelParams; + PxVehicleArrayData suspensionParams; + PxVehicleArrayData tireForceParams; + PxVehicleArrayData roadGeomStates; + PxVehicleArrayData suspensionStates; + PxVehicleArrayData suspensionComplianceStates; + PxVehicleArrayData suspensionForces; + PxVehicleArrayData wheelRigidBody1DStates; + PxVehicleArrayData tireGripStates; + PxVehicleArrayData tireDirectionStates; + PxVehicleArrayData tireSpeedStates; + PxVehicleArrayData tireSlipStates; + PxVehicleArrayData tireCamberAngleStates; + PxVehicleArrayData tireStickyStates; + PxVehicleArrayData tireForces; + + getDataForTireComponent(axleDescription, steerResponseStates, + rigidBodyState, actuationStates, wheelParams, suspensionParams, tireForceParams, + roadGeomStates, suspensionStates, suspensionComplianceStates, suspensionForces, + wheelRigidBody1DStates, tireGripStates, tireDirectionStates, tireSpeedStates, + tireSlipStates, tireCamberAngleStates, tireStickyStates, tireForces); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + const bool isWheelOnGround = PxVehicleIsWheelOnGround(suspensionStates[wheelId]); + + //Compute the tire slip directions + PxVehicleTireDirsUpdate( + suspensionParams[wheelId], + steerResponseStates[wheelId], + roadGeomStates[wheelId].plane.n, isWheelOnGround, + suspensionComplianceStates[wheelId], + *rigidBodyState, + context.frame, + tireDirectionStates[wheelId]); + + //Compute the rigid body speeds along the tire slip directions. + PxVehicleTireSlipSpeedsUpdate( + wheelParams[wheelId], suspensionParams[wheelId], + steerResponseStates[wheelId], suspensionStates[wheelId], tireDirectionStates[wheelId], + *rigidBodyState, roadGeomStates[wheelId], + context.frame, + tireSpeedStates[wheelId]); + + //Compute the tire slip angles. + PxVehicleTireSlipsUpdate( + wheelParams[wheelId], context.tireSlipParams, + actuationStates[wheelId], tireSpeedStates[wheelId], + wheelRigidBody1DStates[wheelId], + tireSlipStates[wheelId]); + + //Update the camber angle + PxVehicleTireCamberAnglesUpdate( + suspensionParams[wheelId], steerResponseStates[wheelId], + roadGeomStates[wheelId].plane.n, isWheelOnGround, + suspensionComplianceStates[wheelId], *rigidBodyState, + context.frame, + tireCamberAngleStates[wheelId]); + + //Compute the friction + PxVehicleTireGripUpdate( + tireForceParams[wheelId], roadGeomStates[wheelId].friction, + isWheelOnGround, suspensionForces[wheelId], + tireSlipStates[wheelId], tireGripStates[wheelId]); + + //Update the tire sticky state + // + //Note: this should be skipped if tires do not use the sticky feature + PxVehicleTireStickyStateUpdate( + *axleDescription, + wheelParams[wheelId], + context.tireStickyParams, + actuationStates, tireGripStates[wheelId], + tireSpeedStates[wheelId], wheelRigidBody1DStates[wheelId], + dt, + tireStickyStates[wheelId]); + + //If sticky tire is active set the slip angle to zero. + // + //Note: this should be skipped if tires do not use the sticky feature + PxVehicleTireSlipsAccountingForStickyStatesUpdate( + tireStickyStates[wheelId], + tireSlipStates[wheelId]); + + //Compute the tire forces + PxVehicleTireForcesUpdate( + wheelParams[wheelId], suspensionParams[wheelId], + tireForceParams[wheelId], + suspensionComplianceStates[wheelId], + tireGripStates[wheelId], tireDirectionStates[wheelId], + tireSlipStates[wheelId], tireCamberAngleStates[wheelId], + *rigidBodyState, + tireForces[wheelId]); + } + + return true; + } +}; + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. +*/ +class PX_DEPRECATED PxVehicleLegacyTireComponent : public PxVehicleComponent +{ +public: + + PxVehicleLegacyTireComponent() : PxVehicleComponent() {} + virtual ~PxVehicleLegacyTireComponent() {} + + virtual void getDataForLegacyTireComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleArrayData& steerResponseStates, + const PxVehicleRigidBodyState*& rigidBodyState, + PxVehicleArrayData& actuationStates, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& suspensionParams, + PxVehicleArrayData& tireForceParams, + PxVehicleArrayData& roadGeomStates, + PxVehicleArrayData& suspensionStates, + PxVehicleArrayData& suspensionComplianceStates, + PxVehicleArrayData& suspensionForces, + PxVehicleArrayData& wheelRigidBody1DStates, + PxVehicleArrayData& tireGripStates, + PxVehicleArrayData& tireDirectionStates, + PxVehicleArrayData& tireSpeedStates, + PxVehicleArrayData& tireSlipStates, + PxVehicleArrayData& tireCamberAngleStates, + PxVehicleArrayData& tireStickyStates, + PxVehicleArrayData& tireForces) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_PROFILE_ZONE("PxVehicleLegacyTireComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleArrayData steerResponseStates; + const PxVehicleRigidBodyState* rigidBodyState; + PxVehicleArrayData actuationStates; + PxVehicleArrayData wheelParams; + PxVehicleArrayData suspensionParams; + PxVehicleArrayData tireForceParams; + PxVehicleArrayData roadGeomStates; + PxVehicleArrayData suspensionStates; + PxVehicleArrayData suspensionComplianceStates; + PxVehicleArrayData suspensionForces; + PxVehicleArrayData wheelRigidBody1DStates; + PxVehicleArrayData tireGripStates; + PxVehicleArrayData tireDirectionStates; + PxVehicleArrayData tireSpeedStates; + PxVehicleArrayData tireSlipStates; + PxVehicleArrayData tireCamberAngleStates; + PxVehicleArrayData tireStickyStates; + PxVehicleArrayData tireForces; + + getDataForLegacyTireComponent(axleDescription, steerResponseStates, + rigidBodyState, actuationStates, + wheelParams, suspensionParams, tireForceParams, + roadGeomStates, suspensionStates, suspensionComplianceStates, + suspensionForces, wheelRigidBody1DStates, + tireGripStates, tireDirectionStates, tireSpeedStates, tireSlipStates, + tireCamberAngleStates, tireStickyStates, tireForces); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + const bool isWheelOnGround = roadGeomStates[wheelId].hitState; + // note: since this is the legacy component, PxVehicleIsWheelOnGround() is not used + // here + + //Compute the tire slip directions + PxVehicleTireDirsLegacyUpdate( + suspensionParams[wheelId], + steerResponseStates[wheelId], + roadGeomStates[wheelId], *rigidBodyState, + context.frame, + tireDirectionStates[wheelId]); + + //Compute the rigid body speeds along the tire slip directions. + PxVehicleTireSlipSpeedsUpdate( + wheelParams[wheelId], suspensionParams[wheelId], + steerResponseStates[wheelId], suspensionStates[wheelId], tireDirectionStates[wheelId], + *rigidBodyState, roadGeomStates[wheelId], + context.frame, + tireSpeedStates[wheelId]); + + //Compute the tire slip angles. + PxVehicleTireSlipsLegacyUpdate( + wheelParams[wheelId], context.tireSlipParams, + actuationStates[wheelId], tireSpeedStates[wheelId], + wheelRigidBody1DStates[wheelId], + tireSlipStates[wheelId]); + + //Update the camber angle + PxVehicleTireCamberAnglesUpdate( + suspensionParams[wheelId], steerResponseStates[wheelId], + roadGeomStates[wheelId].plane.n, isWheelOnGround, + suspensionComplianceStates[wheelId], *rigidBodyState, + context.frame, + tireCamberAngleStates[wheelId]); + + //Compute the friction + PxVehicleTireGripUpdate( + tireForceParams[wheelId], roadGeomStates[wheelId].friction, + PxVehicleIsWheelOnGround(suspensionStates[wheelId]), suspensionForces[wheelId], + tireSlipStates[wheelId], tireGripStates[wheelId]); + // note: PxVehicleIsWheelOnGround() used here to reflect previous behavior since this is + // the legacy component after all + + //Update the tire sticky state + // + //Note: this should be skipped if tires do not use the sticky feature + PxVehicleTireStickyStateUpdate( + *axleDescription, + wheelParams[wheelId], + context.tireStickyParams, + actuationStates, tireGripStates[wheelId], + tireSpeedStates[wheelId], wheelRigidBody1DStates[wheelId], + dt, + tireStickyStates[wheelId]); + + //If sticky tire is active set the slip angle to zero. + // + //Note: this should be skipped if tires do not use the sticky feature + PxVehicleTireSlipsAccountingForStickyStatesUpdate( + tireStickyStates[wheelId], + tireSlipStates[wheelId]); + + //Compute the tire forces + PxVehicleTireForcesUpdate( + wheelParams[wheelId], suspensionParams[wheelId], + tireForceParams[wheelId], + suspensionComplianceStates[wheelId], + tireGripStates[wheelId], tireDirectionStates[wheelId], + tireSlipStates[wheelId], tireCamberAngleStates[wheelId], + *rigidBodyState, + tireForces[wheelId]); + } + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireFunctions.h new file mode 100644 index 000000000..1d1060b14 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireFunctions.h @@ -0,0 +1,270 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxSimpleTypes.h" +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleSuspensionParams; +struct PxVehicleRoadGeometryState; +struct PxVehicleRigidBodyState; +struct PxVehicleTireDirectionState; +struct PxVehicleSuspensionComplianceState; +struct PxVehicleWheelParams; +struct PxVehicleTireSpeedState; +struct PxVehicleWheelActuationState; +struct PxVehicleWheelRigidBody1dState; +struct PxVehicleTireSlipState; +struct PxVehicleSuspensionState; +struct PxVehicleTireCamberAngleState; +struct PxVehicleTireGripState; +struct PxVehicleTireForceParams; +struct PxVehicleSuspensionForce; +struct PxVehicleTireForce; +struct PxVehicleTireStickyState; + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Compute the longitudinal and lateral tire directions in the ground plane. +\param[in] suspensionParams describes the frame of the suspension and wheel. +\param[in] steerAngle is the steer angle in radians to be applied to the wheel. +\param[in] roadGeometryState describes the plane of the road geometry under the wheel +\param[in] rigidBodyState describes the current pose of the vehicle's rigid body in the world frame. +\param[in] frame is a description of the vehicle's lateral and longitudinal axes. +\param[out] tireDirectionState is the computed tire longitudinal and lateral directions in the world frame. +\note PxVehicleTireDirsLegacyUpdate replicates the tire direction calculation of PhysX 5.0 and earlier. +*/ +PX_DEPRECATED void PxVehicleTireDirsLegacyUpdate +(const PxVehicleSuspensionParams& suspensionParams, + const PxReal steerAngle, const PxVehicleRoadGeometryState& roadGeometryState, const PxVehicleRigidBodyState& rigidBodyState, + const PxVehicleFrame& frame, + PxVehicleTireDirectionState& tireDirectionState); + +/** +\brief Compute the longitudinal and lateral tire directions in the ground plane. +\param[in] suspensionParams describes the frame of the suspension and wheel. +\param[in] steerAngle is the steer angle in radians to be applied to the wheel. +\param[in] groundNormal describes the plane normal of the road geometry under the wheel. +\param[in] isWheelOnGround defines whether the wheel touches the road geometry. +\param[in] complianceState is a description of the camber and toe angle that arise from suspension compliance. +\param[in] rigidBodyState describes the current pose of the vehicle's rigid body in the world frame. +\param[in] frame is a description of the vehicle's lateral and longitudinal axes. +\param[out] tireDirectionState is the computed tire longitudinal and lateral directions in the world frame. +\note The difference between PxVehicleTireDirsUpdate and PxVehicleTireDirsLegacyUpdate is that +PxVehicleTireDirsUpdate accounts for suspension compliance while PxVehicleTireDirsLegacyUpdate does not. +*/ +void PxVehicleTireDirsUpdate +(const PxVehicleSuspensionParams& suspensionParams, + const PxReal steerAngle, const PxVec3& groundNormal, bool isWheelOnGround, + const PxVehicleSuspensionComplianceState& complianceState, + const PxVehicleRigidBodyState& rigidBodyState, + const PxVehicleFrame& frame, + PxVehicleTireDirectionState& tireDirectionState); + +/** +\brief Project the rigid body velocity at the tire contact point along the tire longitudinal directions. +\param[in] wheelParams is a description of the wheel's radius and half-width. +\param[in] suspensionParams describes the frame of the suspension and wheel. +\param[in] steerAngle is the steer angle in radians to be applied to the wheel. +\param[in] suspensionStates is the current suspension compression state. +\param[in] tireDirectionState is the tire's longitudinal and lateral directions in the ground plane. +\param[in] rigidBodyState describes the current pose and velocity of the vehicle's rigid body in the world frame. +\param[in] roadGeometryState describes the current velocity of the road geometry under each wheel. +\param[in] frame is a description of the vehicle's lateral and longitudinal axes. +\param[out] tireSpeedState is the components of rigid body velocity at the tire contact point along the +tire's longitudinal and lateral axes. +\see PxVehicleTireDirsUpdate +\see PxVehicleTireDirsLegacyUpdate +*/ +void PxVehicleTireSlipSpeedsUpdate +(const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspensionParams, + const PxF32 steerAngle, const PxVehicleSuspensionState& suspensionStates, const PxVehicleTireDirectionState& tireDirectionState, + const PxVehicleRigidBodyState& rigidBodyState, const PxVehicleRoadGeometryState& roadGeometryState, + const PxVehicleFrame& frame, + PxVehicleTireSpeedState& tireSpeedState); + +/** +\brief Compute a tire's longitudinal and lateral slip angles. +\param[in] wheelParams describes the radius of the wheel. +\param[in] tireSlipParams describes how to manage small longitudinal speeds by setting minimum values on the +denominator of the quotients used to calculate lateral and longitudinal slip. +\param[in] actuationState describes whether a wheel is to be driven by a drive torque or not. +\param[in] tireSpeedState is the component of rigid body velocity at the tire contact point projected along the +tire's longitudinal and lateral axes. +\param[in] wheelRigidBody1dState is the wheel rotation speed. +\param[out] tireSlipState is the computed tire longitudinal and lateral slips. +\note Longitudinal slip angle has the following theoretical form: (wheelRotationSpeed*wheelRadius - longitudinalSpeed)/|longitudinalSpeed| +\note Lateral slip angle has the following theoretical form: atan(lateralSpeed/|longitudinalSpeed|) +\note The calculation of both longitudinal and lateral slip angles avoid a zero denominator using minimum values for the denominator set in +tireSlipParams. +*/ +void PxVehicleTireSlipsUpdate +(const PxVehicleWheelParams& wheelParams, + const PxVehicleTireSlipParams& tireSlipParams, + const PxVehicleWheelActuationState& actuationState, PxVehicleTireSpeedState& tireSpeedState, const PxVehicleWheelRigidBody1dState& wheelRigidBody1dState, + PxVehicleTireSlipState& tireSlipState); + +/** +\deprecated This API was introduced with the new Vehicle API for transition purposes but will be removed in a future version. + +\brief Compute a tire's longitudinal and lateral slip angles. +\param[in] wheelParams describes the radius of the wheel. +\param[in] tireSlipParams describes how to manage small longitudinal speeds by setting minimum values on the +denominator of the quotients used to calculate lateral and longitudinal slip. +\param[in] actuationState describes whether a wheel is to be driven by a drive torque or not. +\param[in] tireSpeedState is the component of rigid body velocity at the tire contact point projected along the +tire's longitudinal and lateral axes. +\param[in] wheelRigidBody1dState is the wheel rotation speed. +\param[out] tireSlipState is the computed tire longitudinal and lateral slips. +\note Longitudinal slip angle has the following theoretical form: (wheelRotationSpeed*wheelRadius - longitudinalSpeed)/|longitudinalSpeed| +\note Lateral slip angle has the following theoretical form: atan(lateralSpeed/|longitudinalSpeed|) +\note The calculation of both longitudinal and lateral slip angles avoid a zero denominator using minimum values for the denominator set in +tireSlipParams. +*/ +void PX_DEPRECATED PxVehicleTireSlipsLegacyUpdate +(const PxVehicleWheelParams& wheelParams, + const PxVehicleTireSlipParams& tireSlipParams, + const PxVehicleWheelActuationState& actuationState, PxVehicleTireSpeedState& tireSpeedState, const PxVehicleWheelRigidBody1dState& wheelRigidBody1dState, + PxVehicleTireSlipState& tireSlipState); + + +/** +\brief Compute the camber angle of the wheel +\param[in] suspensionParams describes the frame of the suspension and wheel. +\param[in] steerAngle is the steer angle in radians to be applied to the wheel. +\param[in] groundNormal describes the plane normal of the road geometry under the wheel. +\param[in] isWheelOnGround defines whether the wheel touches the road geometry. +\param[in] complianceState is a description of the camber and toe angle that arise from suspension compliance. +\param[in] rigidBodyState describes the current pose of the vehicle's rigid body in the world frame. +\param[in] frame is a description of the vehicle's lateral and longitudinal axes. +\param[out] tireCamberAngleState is the computed camber angle of the tire expressed in radians. +*/ +void PxVehicleTireCamberAnglesUpdate +(const PxVehicleSuspensionParams& suspensionParams, + const PxReal steerAngle, const PxVec3& groundNormal, bool isWheelOnGround, + const PxVehicleSuspensionComplianceState& complianceState, + const PxVehicleRigidBodyState& rigidBodyState, + const PxVehicleFrame& frame, + PxVehicleTireCamberAngleState& tireCamberAngleState); + +/** +\brief Compute the load and friction experienced by the tire. +\param[in] tireForceParams describes the tire's friction response to longitudinal lip angle and its load response. +\param[in] frictionCoefficient describes the friction coefficient for the tire and road geometry pair. +\param[in] isWheelOnGround defines whether the wheel touches the road geometry. +\param[in] suspensionForce is the force that the suspension exerts on the sprung mass of the suspension. +\param[in] tireSlipState is the tire longitudinal and lateral slip angles. +\param[out] tireGripState is the computed load and friction experienced by the tire. +\note If the suspension cannot place the wheel on the ground the tire load and friction will be 0.0. +*/ +void PxVehicleTireGripUpdate +(const PxVehicleTireForceParams& tireForceParams, + PxReal frictionCoefficient, bool isWheelOnGround, const PxVehicleSuspensionForce& suspensionForce, + const PxVehicleTireSlipState& tireSlipState, + PxVehicleTireGripState& tireGripState); + +/** +\brief When a tire has been at a very low speed for a threshold time without application of drive torque, a +secondary tire model is applied to bring the tire to rest using velocity constraints that asymptotically approach zero speed +along the tire's lateral and longitudinal directions. This secondary tire model is referred to as the sticky tire model and the +tire is considered to be in the sticky tire state when the speed and time conditions are satisfied. The purpose of +PxVehicleTireStickyStateUpdate is to compute the target speeds of the sticky state and to record whether sticky state is +active or not. +\param[in] axleDescription is the axles of the vehicle and the wheels on each axle. +\param[in] wheelParams describes the radius of the wheel +\param[in] tireStickyParams describe the threshold speeds and times for the lateral and longitudinal sticky states. +\param[in] actuationStates describes whether each wheel experiences a drive torque. +\param[in] tireGripState is the load and friction experienced by the tire. +\param[in] tireSpeedState is the component of rigid body velocity at the tire contact point projected along the +tire's longitudinal and lateral axes. +\param[in] wheelRigidBody1dState is the wheel rotation speed. +\param[in] dt is the simulation time that has lapsed since the last call to PxVehicleTireStickyStateUpdate +\param[out] tireStickyState is a description of the sticky state of the tire in the longitudinal and lateral directions. +\note The velocity constraints are maintained through integration with the PhysX scene using the function +PxVehiclePhysXConstraintStatesUpdate. Alternative implementations independent of PhysX are possible. +\see PxVehiclePhysXConstraintStatesUpdate +\see PxVehicleTireSlipsAccountingForStickyStatesUpdate +*/ +void PxVehicleTireStickyStateUpdate +(const PxVehicleAxleDescription& axleDescription, const PxVehicleWheelParams& wheelParams, + const PxVehicleTireStickyParams& tireStickyParams, + const PxVehicleArrayData& actuationStates, + const PxVehicleTireGripState& tireGripState, const PxVehicleTireSpeedState& tireSpeedState, const PxVehicleWheelRigidBody1dState& wheelRigidBody1dState, + const PxReal dt, + PxVehicleTireStickyState& tireStickyState); + +/** +\brief Set the tire longitudinal and lateral slip values to 0.0 in the event that the tire has entred tire sticky state. This is +necessary to avoid both tire models being simultaneously active and interfering with each other. +\param[in] tireStickyState is a description of the sticky state of the tire in the longitudinal and lateral directions. +\param[out] tireSlipState is the updated lateral and longudinal slip with either set to 0.0 in the event that the correspoinding +sticky state is active. +\note This function should not be invoked if there is no subsequent component to implement the sticky tire model. +*/ +void PxVehicleTireSlipsAccountingForStickyStatesUpdate +(const PxVehicleTireStickyState& tireStickyState, + PxVehicleTireSlipState& tireSlipState); + +/** +\brief Compute the longitudinal and lateral forces in the world frame that develop on the tire as a consequence of +the tire's slip angles, friction and load. +\param[in] wheelParams describes the radius and half-width of the wheel. +\param[in] suspensionParams describes the frame of the suspension and wheel. +\param[in] tireForceParams describes the conversion of slip angle, friction and load to a force along the longitudinal +and lateral directions of the tire. +\param[in] complianceState is a description of the camber and toe angle that arise from suspension compliance. +\param[out] tireGripState is the load and friction experienced by the tire. +\param[in] tireDirectionState is the tire's longitudinal and lateral directions in the ground plane. +\param[in] tireSlipState is the longitudinal and lateral slip angles. +\param[in] tireCamberAngleState is the camber angle of the tire expressed in radians. +\param[in] rigidBodyState describes the current pose of the vehicle's rigid body in the world frame. +\param[out] tireForce is the computed tire forces in the world frame. +*/ +void PxVehicleTireForcesUpdate +(const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleTireForceParams& tireForceParams, + const PxVehicleSuspensionComplianceState& complianceState, + const PxVehicleTireGripState& tireGripState, const PxVehicleTireDirectionState& tireDirectionState, + const PxVehicleTireSlipState& tireSlipState, const PxVehicleTireCamberAngleState& tireCamberAngleState, + const PxVehicleRigidBodyState& rigidBodyState, + PxVehicleTireForce& tireForce); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireHelpers.h new file mode 100644 index 000000000..c0a99f57a --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireHelpers.h @@ -0,0 +1,69 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/wheel/PxVehicleWheelStates.h" +#include "PxVehicleTireStates.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Compute the intention to accelerate by inspecting the actuation states of the wheels of a powered vehicle. +\param[in] poweredVehicleAxleDesc describes the axles and wheels of a powered vehicle in a jointed ensemble of vehicles. +\param[in] poweredVehicleActuationStates describes the drive state of each wheel of the powered vehicle. +\see PxVehicleTireStickyStateReset +*/ +bool PxVehicleAccelerationIntentCompute +(const PxVehicleAxleDescription& poweredVehicleAxleDesc, const PxVehicleArrayData& poweredVehicleActuationStates); + +/** +\brief Reset the sticky tire states of an unpowered vehicle if it is in a jointed ensemble of vehicles with at least one powered vehicle. +\param[in] poweredVehicleIntentionToAccelerate describes the state of the powered vehicle in an ensemble of jointed vehicles. +\param[in] unpoweredVehicleAxleDesc describes the axles and wheels of an unpowered vehicle towed by a powered vehicle. +\param[out] unpoweredVehicleStickyState is the sticky state of the wheels of an unpowered vehicle towed by a powered vehicle. +\note If any wheel on the powered vehicle is to receive a drive torque, the sticky tire states of the towed vehicle will be reset to the deactivated state. +\note poweredVehicleIntentionToAccelerate may be computed using PxVehicleAccelerationIntentCompute(). +\see PxVehicleAccelerationIntentCompute +*/ +void PxVehicleTireStickyStateReset +(const bool poweredVehicleIntentionToAccelerate, + const PxVehicleAxleDescription& unpoweredVehicleAxleDesc, + PxVehicleArrayData& unpoweredVehicleStickyState); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireParams.h new file mode 100644 index 000000000..579f7bd17 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireParams.h @@ -0,0 +1,162 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" + +#include "vehicle2/PxVehicleParams.h" + +#include "PxVehicleTireStates.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleTireForceParams +{ + /** + \brief Tire lateral stiffness is a graph of tire load that has linear behavior near zero load and + flattens at large loads. latStiffX describes the minimum normalized load (load/restLoad) that gives a + flat lateral stiffness response to load. + \note A value of 0.0 indicates that the tire lateral stiffness is independent of load and will adopt + the value #latStiffY for all values of tire load. + */ + PxReal latStiffX; + + /** + \brief Tire lateral stiffness is a graph of tire load that has linear behavior near zero load and + flattens at large loads. latStiffY describes the maximum possible value of lateral stiffness that occurs + when (load/restLoad) >= #latStiffX. + + Unit: force per lateral slip = mass * length / (time^2) + */ + PxReal latStiffY; + + /** + \brief Tire Longitudinal stiffness + \note Longitudinal force can be approximated as longStiff*longitudinalSlip. + + Unit: force per longitudinal slip = mass * length / (time^2) + */ + PxReal longStiff; + + /** + \brief Tire camber stiffness + \note Camber force can be approximated as camberStiff*camberAngle. + + Unit: force per radian = mass * length / (time^2) + */ + PxReal camberStiff; + + /** + \brief Graph of friction vs longitudinal slip with 3 points. + \note frictionVsSlip[0][0] is always zero. + \note frictionVsSlip[0][1] is the friction available at zero longitudinal slip. + \note frictionVsSlip[1][0] is the value of longitudinal slip with maximum friction. + \note frictionVsSlip[1][1] is the maximum friction. + \note frictionVsSlip[2][0] is the end point of the graph. + \note frictionVsSlip[2][1] is the value of friction for slips greater than frictionVsSlip[2][0]. + \note The friction value is computed from the friction vs longitudinal slip graph using linear interpolation. + \note The friction value computed from the friction vs longitudinal slip graph is used to scale the friction + value of the road geometry. + \note frictionVsSlip[2][0] > frictionVsSlip[1][0] > frictionVsSlip[0][0] + \note frictionVsSlip[1][1] is typically greater than frictionVsSlip[0][1] + \note frictionVsSlip[2][1] is typically smaller than frictionVsSlip[1][1] + \note longitudinal slips > frictionVsSlip[2][0] use friction multiplier frictionVsSlip[2][1] + */ + PxReal frictionVsSlip[3][2]; //3 (x,y) points + + /** + \brief The rest load is the load that develops on the tire when the vehicle is at rest on a flat plane. + \note The rest load is approximately the product of gravitational acceleration and (sprungMass + wheelMass). + + Unit: force = mass * length / (time^2) + */ + PxReal restLoad; + + /** + \brief Tire load variation can be strongly dependent on the time-step so it is a good idea to filter it + to give less jerky handling behavior. + \note Tire load filtering is implemented by linear interpolating a graph containing just two points. + The x-axis of the graph is normalized tire load, while the y-axis is the filtered normalized tire load that is + to be applied during the tire force calculation. + \note The normalized load is the force acting downwards on the tire divided by restLoad. + \note The minimum possible normalized load is zero. + \note There are two points on the graph: (minNormalisedLoad, minNormalisedFilteredLoad) and (maxNormalisedLoad, maxFilteredNormalisedLoad). + \note Normalized loads less than minNormalisedLoad have filtered normalized load = minNormalisedFilteredLoad. + \note Normalized loads greater than maxNormalisedLoad have filtered normalized load = maxFilteredNormalisedLoad. + \note Normalized loads in-between are linearly interpolated between minNormalisedFilteredLoad and maxFilteredNormalisedLoad. + \note The tire load applied as input to the tire force computation is the filtered normalized load multiplied by the rest load. + \note loadFilter[0][0] is minNormalisedLoad + \note loadFilter[0][1] is minFilteredNormalisedLoad + \note loadFilter[1][0] is maxNormalisedLoad + \note loadFilter[1][1] is maxFilteredNormalisedLoad + */ + PxReal loadFilter[2][2]; //2 (x,y) points + + PX_FORCE_INLINE PxVehicleTireForceParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleTireForceParams r = *this; + const PxReal scale = trgScale.scale / srcScale.scale; + r.latStiffY *= scale; + r.longStiff *= scale; + r.camberStiff *= scale; + r.restLoad *= scale; + return r; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(latStiffX >= 0, "PxVehicleTireForceParams.latStiffX must be greater than or equal to zero", false); + PX_CHECK_AND_RETURN_VAL(latStiffY > 0, "PxVehicleTireForceParams.latStiffY must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(longStiff > 0, "PxVehicleTireForceParams.longStiff must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(camberStiff >= 0, "PxVehicleTireForceParams.camberStiff must be greater than or equal zero", false); + PX_CHECK_AND_RETURN_VAL(restLoad > 0, "PxVehicleTireForceParams.restLoad must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(loadFilter[1][0] >= loadFilter[0][0], "PxVehicleTireForceParams.loadFilter[1][0] must be greater than or equal to PxVehicleTireForceParams.loadFilter[0][0]", false); + PX_CHECK_AND_RETURN_VAL(loadFilter[1][1] > 0, "PxVehicleTireLoadFilterData.loadFilter[1][1] must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(0.0f == loadFilter[0][0], "PxVehicleTireLoadFilterData.loadFilter[0][0] must be equal to zero", false); + PX_CHECK_AND_RETURN_VAL(frictionVsSlip[0][0] >= 0.0f && frictionVsSlip[0][1] >= 0.0f, "Illegal values for frictionVsSlip[0]", false); + PX_CHECK_AND_RETURN_VAL(frictionVsSlip[1][0] >= 0.0f && frictionVsSlip[1][1] >= 0.0f, "Illegal values for frictionVsSlip[1]", false); + PX_CHECK_AND_RETURN_VAL(frictionVsSlip[2][0] >= 0.0f && frictionVsSlip[2][1] >= 0.0f, "Illegal values for frictionVsSlip[2]", false); + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireStates.h new file mode 100644 index 000000000..2acbd2977 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/tire/PxVehicleTireStates.h @@ -0,0 +1,177 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + +#include "foundation/PxVec3.h" +#include "foundation/PxMemory.h" + +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + + +/** +\brief PxVehicleTireDirectionState stores the world frame lateral and longtidinal axes of the tire after +projecting the wheel pose in the world frame onto the road geometry plane (also in the world frame). +*/ +struct PxVehicleTireDirectionState +{ + PxVec3 directions[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTireDirectionState)); + } +}; + + +/** +\brief PxVehicleTireSpeedState stores the components of the instantaneous velocity of the rigid body at the tire contact point projected +along the lateral and longitudinal axes of the tire. +\see PxVehicleTireDirectionState +*/ +struct PxVehicleTireSpeedState +{ + PxReal speedStates[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTireSpeedState)); + } +}; + +/** +\brief The lateral and longitudinal tire slips. +\see PxVehicleTireSpeedState +*/ +struct PxVehicleTireSlipState +{ + PxReal slips[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTireSlipState)); + } +}; + +/** +\brief The load and friction experienced by a tire. +*/ +struct PxVehicleTireGripState +{ + /** + \brief The tire load + + Unit: force = mass * length / (time^2) + */ + PxReal load; + + /** + \brief The tire friction is the product of the road geometry friction and a friction response multiplier. + */ + PxReal friction; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTireGripState)); + } +}; + +/** +\brief Camber angle of the tire relative to the ground plane. +*/ +struct PxVehicleTireCamberAngleState +{ + PxReal camberAngle; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTireCamberAngleState)); + } +}; + +/** +\brief Prolonged low speeds in the lateral and longitudinal directions may be handled with "sticky" velocity constraints that activate after +a speed below a threshold has been recorded for a threshold time. +\see PxVehicleTireStickyParams +\see PxVehicleTireSpeedState +*/ +struct PxVehicleTireStickyState +{ + PxReal lowSpeedTime[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + bool activeStatus[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTireStickyState)); + } +}; + +/** +\brief The longitudinal/lateral forces/torques that develop on the tire. +*/ +struct PxVehicleTireForce +{ + /* + \brief The tire forces that develop along the tire's longitudinal and lateral directions. Specified in the world frame. + */ + PxVec3 forces[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + /* + \brief The tire torques that develop around the tire's longitudinal and lateral directions. Specified in the world frame. + */ + PxVec3 torques[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; + + /** + \brief The aligning moment may be propagated to a torque-driven steering controller. + */ + PxReal aligningMoment; + + /** + \brief The torque to apply to the wheel's 1d rigid body. + */ + PxReal wheelTorque; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleTireForce)); + } +}; + + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelComponents.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelComponents.h new file mode 100644 index 000000000..a82bcefd6 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelComponents.h @@ -0,0 +1,116 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleParams.h" +#include "vehicle2/PxVehicleComponent.h" + +#include "vehicle2/commands/PxVehicleCommandHelpers.h" +#include "vehicle2/tire/PxVehicleTireStates.h" + +#include "PxVehicleWheelFunctions.h" +#include "PxVehicleWheelHelpers.h" + +#include "common/PxProfileZone.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +class PxVehicleWheelComponent : public PxVehicleComponent +{ +public: + + PxVehicleWheelComponent() : PxVehicleComponent() {} + virtual ~PxVehicleWheelComponent() {} + + virtual void getDataForWheelComponent( + const PxVehicleAxleDescription*& axleDescription, + PxVehicleArrayData& steerResponseStates, + PxVehicleArrayData& wheelParams, + PxVehicleArrayData& suspensionParams, + PxVehicleArrayData& actuationStates, + PxVehicleArrayData& suspensionStates, + PxVehicleArrayData& suspensionComplianceStates, + PxVehicleArrayData& tireSpeedStates, + PxVehicleArrayData& wheelRigidBody1dStates, + PxVehicleArrayData& wheelLocalPoses) = 0; + + virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) + { + PX_PROFILE_ZONE("PxVehicleWheelComponent::update", 0); + + const PxVehicleAxleDescription* axleDescription; + PxVehicleArrayData steerResponseStates; + PxVehicleArrayData wheelParams; + PxVehicleArrayData suspensionParams; + PxVehicleArrayData actuationStates; + PxVehicleArrayData suspensionStates; + PxVehicleArrayData suspensionComplianceStates; + PxVehicleArrayData tireSpeedStates; + PxVehicleArrayData wheelRigidBody1dStates; + PxVehicleArrayData wheelLocalPoses; + + getDataForWheelComponent(axleDescription, steerResponseStates, + wheelParams, suspensionParams, actuationStates, suspensionStates, + suspensionComplianceStates, tireSpeedStates, wheelRigidBody1dStates, + wheelLocalPoses); + + for (PxU32 i = 0; i < axleDescription->nbWheels; i++) + { + const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; + + PxVehicleWheelRotationAngleUpdate( + wheelParams[wheelId], + actuationStates[wheelId], suspensionStates[wheelId], + tireSpeedStates[wheelId], + context.thresholdForwardSpeedForWheelAngleIntegration, dt, + wheelRigidBody1dStates[wheelId]); + + wheelLocalPoses[wheelId].localPose = PxVehicleComputeWheelLocalPose(context.frame, + suspensionParams[wheelId], + suspensionStates[wheelId], + suspensionComplianceStates[wheelId], + steerResponseStates[wheelId], + wheelRigidBody1dStates[wheelId]); + } + + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelFunctions.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelFunctions.h new file mode 100644 index 000000000..6e122f446 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelFunctions.h @@ -0,0 +1,77 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxSimpleTypes.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleWheelParams; +struct PxVehicleWheelActuationState; +struct PxVehicleSuspensionState; +struct PxVehicleTireSpeedState; +struct PxVehicleScale; +struct PxVehicleWheelRigidBody1dState; + +/** +\brief Forward integrate the rotation angle of a wheel +\note The rotation angle of the wheel plays no role in simulation but is important to compute the pose of the wheel for rendering. +\param[in] wheelParams describes the radius and half-width of the wheel +\param[in] actuationState describes whether the wheel has drive or brake torque applied to it. +\param[in] suspensionState describes whether the wheel touches the ground. +\param[in] tireSpeedState describes the components of rigid body velocity at the ground contact point along the tire's lateral and longitudinal directions. +\param[in] thresholdForwardSpeedForWheelAngleIntegration Forward wheel speed below which the wheel rotation speed gets blended with the rolling + speed (based on the forward wheel speed) which is then used to integrate the wheel rotation angle. At low forward wheel speed, the wheel + rotation speed can get unstable (depending on the tire model used) and, for example, oscillate. If brake or throttle is applied, there + will be no blending. +\param[in] dt is the simulation time that has lapsed since the last call to PxVehicleWheelRotationAngleUpdate +\param[in,out] wheelRigidBody1dState describes the current angular speed and angle of the wheel. +\note At low speeds and large timesteps, wheel rotation speed can become noisy due to singularities in the tire slip computations. +At low speeds, therefore, the wheel speed used for integrating the angle is a blend of current angular speed and rolling angular speed if the +wheel experiences neither brake nor drive torque and can be placed on the ground. The blended rotation speed gets stored in +PxVehicleWheelRigidBody1dState::correctedRotationSpeed. +*/ +void PxVehicleWheelRotationAngleUpdate +(const PxVehicleWheelParams& wheelParams, + const PxVehicleWheelActuationState& actuationState, const PxVehicleSuspensionState& suspensionState, const PxVehicleTireSpeedState& tireSpeedState, + const PxReal thresholdForwardSpeedForWheelAngleIntegration, const PxReal dt, + PxVehicleWheelRigidBody1dState& wheelRigidBody1dState); + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelHelpers.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelHelpers.h new file mode 100644 index 000000000..831442d71 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelHelpers.h @@ -0,0 +1,217 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "vehicle2/PxVehicleFunctions.h" + +#include "vehicle2/suspension/PxVehicleSuspensionParams.h" +#include "vehicle2/suspension/PxVehicleSuspensionStates.h" + +#include "PxVehicleWheelParams.h" +#include "PxVehicleWheelStates.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief Compute the quaternion of a wheel in the rigid body frame. +\param[in] frame describes the longitudinal and lateral axes of the vehicle. +\param[in] suspensionParams describes the suspension and wheel frames. +\param[in] camberAngle is the camber angle in radian sinduced by suspension compliance. +\param[in] toeAngle is the toe angle in radians induced by suspension compliance. +\param[in] steerAngle is the steer angle in radians applied to the wheel. +\param[in] rotationAngle is the angle around the wheel's lateral axis. +\return The quaterion of the wheel in the rigid body frame. +\see PxVehicleComputeWheelOrientation +*/ +PX_FORCE_INLINE PxQuat PxVehicleComputeWheelLocalOrientation +(const PxVehicleFrame& frame, + const PxVehicleSuspensionParams& suspensionParams, + const PxReal camberAngle, const PxReal toeAngle, const PxReal steerAngle, + const PxReal rotationAngle) +{ + const PxQuat wheelLocalOrientation = + (suspensionParams.suspensionAttachment.q * PxVehicleComputeRotation(frame, camberAngle, 0.0f, steerAngle + toeAngle))* + (suspensionParams.wheelAttachment.q * PxVehicleComputeRotation(frame, 0.0f, rotationAngle, 0.0f)); + return wheelLocalOrientation; +} + +/** +\brief Compute the quaternion of a wheel in the world frame. +\param[in] frame describes the longitudinal and lateral axes of the vehicle. +\param[in] suspensionParams describes the suspension and wheel frames. +\param[in] camberAngle is the camber angle in radian induced by suspension compliance. +\param[in] toeAngle is the toe angle in radians induced by suspension compliance. +\param[in] steerAngle is the steer angle in radians applied to the wheel. +\param[in] rigidBodyOrientation is the quaterion of the rigid body in the world frame. +\param[in] rotationAngle is the angle around the wheel's lateral axis. +\return The quaterion of the wheel in the world frame. +\see PxVehicleComputeWheelLocalOrientation +*/ +PX_FORCE_INLINE PxQuat PxVehicleComputeWheelOrientation +(const PxVehicleFrame& frame, + const PxVehicleSuspensionParams& suspensionParams, + const PxReal camberAngle, const PxReal toeAngle, const PxReal steerAngle, + const PxQuat& rigidBodyOrientation, const PxReal rotationAngle) +{ + const PxQuat wheelOrientation = rigidBodyOrientation * PxVehicleComputeWheelLocalOrientation(frame, suspensionParams, + camberAngle, toeAngle, steerAngle, rotationAngle); + return wheelOrientation; +} + +/** +\brief Compute the pose of the wheel in the rigid body frame. +\param[in] frame describes the longitudinal and lateral axes of the vehicle. +\param[in] suspensionParams describes the suspension and wheel frames. +\param[in] suspensionState is the compression state of the suspenson. +\param[in] camberAngle is the camber angle in radian induced by suspension compliance. +\param[in] toeAngle is the toe angle in radians induced by suspension compliance. +\param[in] steerAngle is the steer angle in radians applied to the wheel. +\param[in] rotationAngle is the angle around the wheel's lateral axis. +\return The pose of the wheel in the rigid body frame. +*/ +PX_FORCE_INLINE PxTransform PxVehicleComputeWheelLocalPose +(const PxVehicleFrame& frame, + const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleSuspensionState& suspensionState, + const PxReal camberAngle, const PxReal toeAngle, const PxReal steerAngle, + const PxReal rotationAngle) +{ + //Full equation: + //PxTransform(suspAttachment.p + suspParams.suspensionTravelDir*suspDist, suspAttachment.q) * + //PxTransform(PxVec3(0), PxQuat(camber, 0, steer+toe)) * + //wheelAttachment * + //PxTransform(PxVec3(0), PxQuat(0, rotation, 0)) + //Reduces to: + //PxTransform(suspAttachment.p + suspParams.suspensionTravelDir*suspDist, suspAttachment.q * PxQuat(camber, 0, steer+toe)) * + //PxTranfsorm(wheelAttachment.p, wheelAttachment.q * PxQuat(0, rotation, 0)) + const PxF32 suspDist = (suspensionState.jounce != PX_VEHICLE_UNSPECIFIED_JOUNCE) ? (suspensionParams.suspensionTravelDist - suspensionState.jounce) : 0.0f; + const PxTransform wheelLocalPose = + PxTransform( + suspensionParams.suspensionAttachment.p + suspensionParams.suspensionTravelDir*suspDist, + suspensionParams.suspensionAttachment.q*PxVehicleComputeRotation(frame, camberAngle, 0.0f, steerAngle + toeAngle))* + PxTransform( + suspensionParams.wheelAttachment.p, + suspensionParams.wheelAttachment.q*PxVehicleComputeRotation(frame, 0.0f, rotationAngle, 0.0f)); + return wheelLocalPose; +} + + +/** +\brief Compute the pose of the wheel in the rigid body frame. +\param[in] frame describes the longitudinal and lateral axes of the vehicle. +\param[in] suspensionParams describes the suspension and wheel frames. +\param[in] suspensionState is the compression state of the suspenson. +\param[in] suspensionComplianceState is the camber and toe angles induced by suspension compliance. +\param[in] steerAngle is the steer angle in radians applied to the wheel. +\param[in] wheelState is angle around the wheel's lateral axis. +\return The pose of the wheel in the rigid body frame. +*/ +PX_FORCE_INLINE PxTransform PxVehicleComputeWheelLocalPose +(const PxVehicleFrame& frame, + const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleSuspensionState& suspensionState, const PxVehicleSuspensionComplianceState& suspensionComplianceState, + const PxReal steerAngle, + const PxVehicleWheelRigidBody1dState& wheelState) +{ + return PxVehicleComputeWheelLocalPose(frame, suspensionParams, suspensionState, + suspensionComplianceState.camber, suspensionComplianceState.toe, steerAngle, + wheelState.rotationAngle); +} + +/** +\brief Compute the pose of the wheel in the world frame. +\param[in] frame describes the longitudinal and lateral axes of the vehicle. +\param[in] suspensionParams describes the suspension and wheel frames. +\param[in] suspensionState is the compression state of the suspenson. +\param[in] camberAngle is the camber angle in radian induced by suspension compliance. +\param[in] toeAngle is the toe angle in radians induced by suspension compliance. +\param[in] steerAngle is the steer angle in radians applied to the wheel. +\param[in] rigidBodyPose is the pose of the rigid body in the world frame. +\param[in] rotationAngle is the angle around the wheel's lateral axis. +\return The pose of the wheel in the world frame. +*/ +PX_FORCE_INLINE PxTransform PxVehicleComputeWheelPose +(const PxVehicleFrame& frame, + const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleSuspensionState& suspensionState, + const PxReal camberAngle, const PxReal toeAngle, const PxReal steerAngle, + const PxTransform& rigidBodyPose, const PxReal rotationAngle) +{ + const PxTransform wheelPose = rigidBodyPose * PxVehicleComputeWheelLocalPose(frame, suspensionParams, suspensionState, + camberAngle, toeAngle, steerAngle, rotationAngle); + return wheelPose; +} + +/** +\brief Compute the pose of the wheel in the world frame. +\param[in] frame describes the longitudinal and lateral axes of the vehicle. +\param[in] suspensionParams describes the suspension and wheel frames. +\param[in] suspensionState is the compression state of the suspenson. +\param[in] suspensionComplianceState is the camber and toe angles induced by suspension compliance. +\param[in] steerAngle is the steer angle in radians applied to the wheel. +\param[in] rigidBodyPose is the pose of the rigid body in the world frame. +\param[in] wheelState is angle around the wheel's lateral axis. +\return The pose of the wheel in the world frame. +*/ + +PX_FORCE_INLINE PxTransform PxVehicleComputeWheelPose +(const PxVehicleFrame& frame, + const PxVehicleSuspensionParams& suspensionParams, + const PxVehicleSuspensionState& suspensionState, const PxVehicleSuspensionComplianceState& suspensionComplianceState, const PxReal steerAngle, + const PxTransform& rigidBodyPose, const PxVehicleWheelRigidBody1dState& wheelState) +{ + return PxVehicleComputeWheelPose(frame, suspensionParams, suspensionState, + suspensionComplianceState.camber, suspensionComplianceState.toe, steerAngle, + rigidBodyPose, wheelState.rotationAngle); +} + +/** +\brief Check if the suspension could place the wheel on the ground or not. + +\param[in] suspState The state of the suspension to check. +\return True if the wheel connects to the ground, else false. + +\see PxVehicleSuspensionState +*/ +PX_FORCE_INLINE bool PxVehicleIsWheelOnGround(const PxVehicleSuspensionState& suspState) +{ + return (suspState.separation <= 0.0f); +} + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelParams.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelParams.h new file mode 100644 index 000000000..4bd313009 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelParams.h @@ -0,0 +1,115 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxFoundation.h" + +#include "vehicle2/PxVehicleParams.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +struct PxVehicleWheelParams +{ + /** + \brief Radius of unit that includes metal wheel plus rubber tire. + + Range: (0, inf)
+ Unit: length + */ + PxReal radius; + + /** + \brief Half-width of unit that includes wheel plus tire. + + Range: (0, inf)
+ Unit: length + */ + PxReal halfWidth; + + /** + \brief Mass of unit that includes wheel plus tire. + + Range: (0, inf)
+ Unit: mass + */ + PxReal mass; + + /** + \brief Moment of inertia of unit that includes wheel plus tire about the rolling axis. + + Range: (0, inf)
+ Unit: mass * (length^2) + */ + PxReal moi; + + /** + \brief Damping rate applied to wheel. + + Range: [0, inf)
+ Unit: torque * time = mass * (length^2) / time + */ + PxReal dampingRate; + + PX_FORCE_INLINE PxVehicleWheelParams transformAndScale( + const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const + { + PX_UNUSED(srcFrame); + PX_UNUSED(trgFrame); + PxVehicleWheelParams r = *this; + const PxReal scale = trgScale.scale/srcScale.scale; + r.radius *= scale; + r.halfWidth *= scale; + r.moi *= (scale*scale); + r.dampingRate *= (scale*scale); + return r; + } + + PX_FORCE_INLINE bool isValid() const + { + PX_CHECK_AND_RETURN_VAL(radius > 0.0f, "PxVehicleWheelParams.radius must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(halfWidth > 0.0f, "PxVehicleWheelParams.halfWidth must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(mass > 0.0f, "PxVehicleWheelParams.mass must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(moi > 0.0f, "PxVehicleWheelParams.moi must be greater than zero", false); + PX_CHECK_AND_RETURN_VAL(dampingRate >= 0.0f, "PxVehicleWheelParams.dampingRate must be greater than or equal to zero", false); + return true; + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + + diff --git a/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelStates.h b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelStates.h new file mode 100644 index 000000000..e133a3f04 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX/vehicle2/wheel/PxVehicleWheelStates.h @@ -0,0 +1,104 @@ +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#pragma once + + +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxTransform.h" +#include "foundation/PxMemory.h" + +#if !PX_DOXYGEN +namespace physx +{ +namespace vehicle2 +{ +#endif + +/** +\brief It is useful to know if a brake or drive torque is to be applied to a wheel. +*/ +struct PxVehicleWheelActuationState +{ + bool isBrakeApplied; //!< True if a brake torque is applied, false if not. + bool isDriveApplied; //!< True if a drive torque is applied, false if not. + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleWheelActuationState)); + } +}; + +struct PxVehicleWheelRigidBody1dState +{ + /** + \brief The rotation speed of the wheel around the lateral axis. + + Unit: radians / time + */ + PxReal rotationSpeed; + + /** + \brief The corrected rotation speed of the wheel around the lateral axis in radians per second. + + At low forward wheel speed, the wheel rotation speed can get unstable (depending on the tire + model used) and, for example, oscillate. To integrate the wheel rotation angle, a (potentially) + blended rotation speed is used which gets stored in #correctedRotationSpeed. + + Unit: radians / time + + \see PxVehicleSimulationContext::thresholdForwardSpeedForWheelAngleIntegration + */ + PxReal correctedRotationSpeed; + + /** + \brief The accumulated angle of the wheel around the lateral axis in radians in range (-2*Pi,2*Pi) + */ + PxReal rotationAngle; + + PX_FORCE_INLINE void setToDefault() + { + PxMemZero(this, sizeof(PxVehicleWheelRigidBody1dState)); + } +}; + +struct PxVehicleWheelLocalPose +{ + PxTransform localPose; //!< The pose of the wheel in the rigid body frame. + + PX_FORCE_INLINE void setToDefault() + { + localPose = PxTransform(PxIdentity); + } +}; + +#if !PX_DOXYGEN +} // namespace vehicle2 +} // namespace physx +#endif + diff --git a/Jusin154_Team3D/Engine/Public/PhysX_Manager.h b/Jusin154_Team3D/Engine/Public/PhysX_Manager.h new file mode 100644 index 000000000..04a3d2322 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/PhysX_Manager.h @@ -0,0 +1,85 @@ +#pragma once + +#include "Base.h" + +NS_BEGIN(Engine) +class CRigidBody; +class CTransform; +class CMesh; + +class CPhysX_Manager final : public CBase +{ +private: + CPhysX_Manager(ID3D11Device* pDevice, ID3D11DeviceContext* pContext); + virtual ~CPhysX_Manager() = default; + +#pragma region RIGID_BODY + +public: + /* dev-treadmill.tistory.com/155 */ +// HRESULT Update_RegionOfInterest(); ( 충돌 컬링, 필터링도 검색해야함 ) +// Aggregate ( 충돌 그룹, 이 그룹끼리는 서로 충돌검사를 하지 않음, 지형, 레그돌 등 ) + + const PSX::PxRigidDynamic* Add_DynamicActor(CRigidBody& RigidBody); + const PSX::PxRigidStatic* Add_StaticActor(CRigidBody& RigidBody); + + PSX::PxMaterial* Get_Material(_float3& vMatInfo); + PSX::PxShape* Create_Shape(ACTOR eType, _float3& vhalfGeometryInfo, PSX::PxMaterial& pxMaterial, _bool bExclusive, PSX::PxShapeFlags ePxShapeFlag); + + HRESULT Create_TriangleMesh(const _wstring& wstrMeshKey, CMesh* pMesh); + PSX::PxTriangleMesh* Find_TriangleMesh(const _wstring& wstrFilePath); + + void Update(_float fTimeDelta); + void ClearScene(); + +#pragma endregion + +#pragma region CHARACTER_CONTROLLER + /* https://dev-treadmill.tistory.com/158 */ + +public: + PSX::PxController* Add_CapsuleController(PSX::PxCapsuleControllerDesc& Desc); + PSX::PxController* Add_BoxController(PSX::PxBoxControllerDesc& Desc); + + PSX::PxController* Get_Controller(_uint iControllerIndex); + void ReleaseController(_uint iControllerIndex); + _uint Get_NumCurrentController(); + HRESULT PurgeAllController(); + +#pragma endregion + + +private: + class CGameInstance* m_pGameInstance = { nullptr }; + ID3D11Device* m_pDevice = { nullptr }; + ID3D11DeviceContext* m_pContext = { nullptr }; + + PSX::PxDefaultAllocator m_AllocatorCallBack = { }; // 피직스 동적할당자 + PSX::PxDefaultErrorCallback m_ErrorCallBack = { }; // 피직스 오류처리자 + PSX::PxDefaultCpuDispatcher* m_pDispatcher = { nullptr }; // 피직스 CPU디스패쳐 ( 현재 피직스는 CPU only ) + PSX::PxTolerancesScale m_ToleranceScale = PSX::PxTolerancesScale(); // 피직스 공차의 집합 ( 기본 단위 집합 ) + PSX::PxFoundation* m_pFoundation = { nullptr }; // 피직스 초기화 종료 담당자 + PSX::PxPhysics* m_pPhysics = { nullptr }; // 피직스 객체의 생성, 초기화, 조작 담당 (싱글톤) + + PSX::PxScene* m_pScene = { nullptr }; // 피직스 시뮬레이션의 공간 + PSX::PxControllerManager* m_pCCTManager = { nullptr }; // 피직스 캐릭터 컨트롤러를 전부 추적하고 매니징함 + PSX::PxPvd* m_pPvd = { nullptr }; // 피직스 시뮬레이션 디버깅을 위한 도구 + PSX::PxCookingParams* m_pCookingParam = { nullptr }; + + + list> m_RigidBodys = { }; + map<_wstring, PSX::PxTriangleMesh*> m_TriangleMeshes = {}; + map<_wstring, PSX::PxTriangleMeshGeometry*> m_TriangleMeshGeometry = {}; + _uint m_iNumLevel = {}; +private: + HRESULT Initialize(); + HRESULT Connect_DebugServer(); + void Update_Kinematic(); + void Update_Dynamic(); + +public: + static CPhysX_Manager* Create(ID3D11Device* pDevice, ID3D11DeviceContext* pContext); + virtual void Free() override; +}; + +NS_END \ No newline at end of file diff --git a/Jusin154_Team3D/Engine/Public/Prototype_Manager.h b/Jusin154_Team3D/Engine/Public/Prototype_Manager.h index 58520d55a..5789a7f2a 100644 --- a/Jusin154_Team3D/Engine/Public/Prototype_Manager.h +++ b/Jusin154_Team3D/Engine/Public/Prototype_Manager.h @@ -5,6 +5,7 @@ #include "VIBuffer_Cell.h" #include "Shader.h" #include "Navigation.h" +#include "RigidBody.h" #include "Texture.h" #include "Cell.h" #include "Model.h" diff --git a/Jusin154_Team3D/Engine/Public/RigidBody.h b/Jusin154_Team3D/Engine/Public/RigidBody.h new file mode 100644 index 000000000..81fcb3941 --- /dev/null +++ b/Jusin154_Team3D/Engine/Public/RigidBody.h @@ -0,0 +1,99 @@ +#pragma once +#include "Component.h" + +NS_BEGIN(PSX) +class PxActor; +class PxMaterial; +NS_END + +NS_BEGIN(Engine) +class CTransform; +class CMesh; + +class ENGINE_DLL CRigidBody final : public CComponent +{ +public: + typedef struct tagRigidStatic_PrototypeDesc + { + _float3 vMatInfo; + const _tchar* pMeshKey = { nullptr }; + CMesh* pMesh = { nullptr }; + }RIGID_STATIC_PROTOTYPEDESC; + typedef struct tagRigidDynamic_PrototypeDesc + { + _float3 vMatInfo; + _float3 vhalfGeometryInfo; + _bool bExclusive = { false }; + PSX::PxShapeFlags ePxShapeFlag = { PSX::PxShapeFlag::eVISUALIZATION | PSX::PxShapeFlag::eSCENE_QUERY_SHAPE | PSX::PxShapeFlag::eSIMULATION_SHAPE }; + }RIGID_DYNAMIC_PROTOTYPEDESC; + + typedef struct tagRigidBody_PrototypeDesc + { + ACTOR eType; + union + { + RIGID_STATIC_PROTOTYPEDESC tRigidStaticDesc; + RIGID_DYNAMIC_PROTOTYPEDESC tRigidDynamicDesc; + }; + }RIGIDBODY_PROTOTYPEDESC; + typedef struct tagRigidStatic_Desc { + const _tchar* pMeshKey = { nullptr }; + }RIGID_STATIC_DESC; + typedef struct tagRigidDynamic_Desc { + _float fDensity = { 1000.f }; + _bool bIsKinematic = { false }; + }RIGID_DYNAMIC_DESC; + typedef struct tagRigidBody_Desc + { + ACTOR eType; + union + { + RIGID_STATIC_DESC tRigidStaticDesc; + RIGID_DYNAMIC_DESC tRigidDynamicDesc; + }; + // 키네마틱을 켜면, + // 프레임 별 직접 위치 지정이 가능하다. + // 물리엔진의 힘, 중력 등의 영향을 받지 않는다. + // 단, 다른 물리엔진 오브젝트와의 충돌은 발생한다. + // 즉, 강제로 움직이지만, 충돌은 시뮬레이션 한다. + // 그러므로 키네마틱 오브젝트는 다른 오브젝트에 영향을 주지만, 다른 오브젝트의 힘에 영향을 받지 않는다. + // 주로 움직이는 플랫폼, 문 등에 사용된다. + // 스태틱 리지드바디와 달리 움직일 수 있다 !!! + }RIGIDBODY_DESC; + +private: + CRigidBody(ID3D11Device* pDevice, ID3D11DeviceContext* pContext); + CRigidBody(const CRigidBody& rhs); + virtual ~CRigidBody() = default; +public: + PSX::PxShape* Get_ShapePtr() const { return m_pShape; } + CTransform* Get_PxTransformPtr() const { return m_pTransform; } + const _tchar* Get_PxMeshKey() const { return m_pMeshKey; } + const PSX::PxMaterial* Get_PxMaterial() const { return m_pMaterial; } + + _float Get_Density() const { return m_fDensity; } + _bool Is_Kinematic() const { return m_bKenematic; } + +private: + ACTOR m_eActorType = ACTOR::END; + const PSX::PxActor* m_pRigidBody = { nullptr }; // 실제 시뮬레이션을 도는 본체 + PSX::PxMaterial* m_pMaterial = { nullptr }; // 피직스 객체의 속성 등 + PSX::PxShape* m_pShape = { nullptr }; // 피직스 객체의 모양 ( 머테리얼로 만들어짐 ) + _float3 m_vhalfGeometryInfo = {}; + CTransform* m_pTransform = { nullptr }; + _bool m_bKenematic = { false }; + _float m_fDensity = { 1000.f }; + const _tchar* m_pMeshKey = { nullptr }; + +private: + HRESULT Initialize_Prototype(RIGIDBODY_PROTOTYPEDESC& Desc); + HRESULT Initialize(void* pArg); + +public: + static CRigidBody* Create(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, RIGIDBODY_PROTOTYPEDESC& Desc); + virtual CComponent* Clone(void* pArg, class CGameObject* pOwner = nullptr) override; + virtual void Free() override; + virtual void Describe_Entity() override; +}; + +NS_END \ No newline at end of file diff --git a/Jusin154_Team3D/Engine/Public/pch.h b/Jusin154_Team3D/Engine/Public/pch.h index 7a345ef28..83fef3926 100644 --- a/Jusin154_Team3D/Engine/Public/pch.h +++ b/Jusin154_Team3D/Engine/Public/pch.h @@ -67,6 +67,15 @@ using namespace std; using namespace FMOD; +// PhysX +#pragma warning(push) +#pragma warning(disable: 26495) +#pragma warning(disable: 33010) + +#include "PhysX/PxPhysics.h" +#include "PhysX/PxPhysicsAPI.h" + +#pragma warning(pop) #ifdef _DEBUG diff --git a/Jusin154_Team3D/Jusin154_Team3D.sln b/Jusin154_Team3D/Jusin154_Team3D.sln index 8a2f8f78f..78e5e4dca 100644 --- a/Jusin154_Team3D/Jusin154_Team3D.sln +++ b/Jusin154_Team3D/Jusin154_Team3D.sln @@ -1,7 +1,7 @@ 癤� Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 18 -VisualStudioVersion = 18.0.11201.2 d18.0 +VisualStudioVersion = 18.0.11201.2 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "00.Client", "00.Client", "{8C01FFE2-C92D-4226-B772-6D7F6F315996}" EndProject @@ -31,7 +31,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SOLUTION", "SOLUTION", "{3F EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ASSIMP", "ASSIMP", "{E6463257-6A19-46F5-9436-5E447F4702B8}" ProjectSection(SolutionItems) = preProject - EngineSDK\Inc\Assimp\.editorconfig = EngineSDK\Inc\Assimp\.editorconfig + Engine\Public\Assimp\.editorconfig = Engine\Public\Assimp\.editorconfig EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Client", "Client\Default\Client.vcxproj", "{AC297B17-64C9-4CD6-8986-EC121672D125}" @@ -48,14 +48,6 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x64.ActiveCfg = Debug|x64 - {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x64.Build.0 = Debug|x64 - {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x86.ActiveCfg = Debug|Win32 - {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x86.Build.0 = Debug|Win32 - {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x64.ActiveCfg = Release|x64 - {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x64.Build.0 = Release|x64 - {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x86.ActiveCfg = Release|Win32 - {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x86.Build.0 = Release|Win32 {AC297B17-64C9-4CD6-8986-EC121672D125}.Debug|x64.ActiveCfg = Debug|x64 {AC297B17-64C9-4CD6-8986-EC121672D125}.Debug|x64.Build.0 = Debug|x64 {AC297B17-64C9-4CD6-8986-EC121672D125}.Debug|x86.ActiveCfg = Debug|Win32 @@ -72,6 +64,14 @@ Global {F91AD988-A0C8-4169-AA7D-A7596A403CFF}.Release|x64.Build.0 = Release|x64 {F91AD988-A0C8-4169-AA7D-A7596A403CFF}.Release|x86.ActiveCfg = Release|Win32 {F91AD988-A0C8-4169-AA7D-A7596A403CFF}.Release|x86.Build.0 = Release|Win32 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x64.ActiveCfg = Debug|x64 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x64.Build.0 = Debug|x64 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x86.ActiveCfg = Debug|Win32 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Debug|x86.Build.0 = Debug|Win32 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x64.ActiveCfg = Release|x64 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x64.Build.0 = Release|x64 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x86.ActiveCfg = Release|Win32 + {2133313A-E5E1-41CD-B976-21753FBCD083}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -80,9 +80,9 @@ Global {593936C7-9E24-43FC-B5E2-03F0CD04E748} = {E9E01406-59AE-4A37-818D-D1967C717E2C} {3F425FBE-7D37-445C-9917-5FD87463390D} = {E9E01406-59AE-4A37-818D-D1967C717E2C} {E6463257-6A19-46F5-9436-5E447F4702B8} = {E9E01406-59AE-4A37-818D-D1967C717E2C} - {2133313A-E5E1-41CD-B976-21753FBCD083} = {C8D5274F-AC00-46C7-1F8D-E88E81087A52} {AC297B17-64C9-4CD6-8986-EC121672D125} = {8C01FFE2-C92D-4226-B772-6D7F6F315996} {F91AD988-A0C8-4169-AA7D-A7596A403CFF} = {8F2ABBAF-8EC5-4CF8-8AD2-B09FB2AC9B14} + {2133313A-E5E1-41CD-B976-21753FBCD083} = {C8D5274F-AC00-46C7-1F8D-E88E81087A52} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {40231FDE-C82F-496F-B27F-38258EBDC83D}