file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionSphereBox.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_SPHERE_BOX_H
#define GU_INTERSECTION_SPHERE_BOX_H
namespace physx
{
namespace Gu
{
class Sphere;
class Box;
/**
Checks if a sphere intersects a box. Based on: Jim Arvo, A Simple Method for Box-Sphere Intersection Testing, Graphics Gems, pp. 247-250.
\param sphere [in] sphere
\param box [in] box
\return true if sphere overlaps box (or exactly touches it)
*/
bool intersectSphereBox(const Gu::Sphere& sphere, const Gu::Box& box);
} // namespace Gu
}
#endif
| 2,196 |
C
| 39.685184 | 138 | 0.756375 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRaySphere.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxVec3.h"
#include "GuIntersectionRaySphere.h"
#include "GuIntersectionRay.h"
using namespace physx;
// Based on GD Mag code, but now works correctly when origin is inside the sphere.
// This version has limited accuracy.
bool Gu::intersectRaySphereBasic(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos)
{
// get the offset vector
const PxVec3 offset = center - origin;
// get the distance along the ray to the center point of the sphere
const PxReal ray_dist = dir.dot(offset);
// get the squared distances
const PxReal off2 = offset.dot(offset);
const PxReal rad_2 = radius * radius;
if(off2 <= rad_2)
{
// we're in the sphere
if(hit_pos)
*hit_pos = origin;
dist = 0.0f;
return true;
}
if(ray_dist <= 0 || (ray_dist - length) > radius)
{
// moving away from object or too far away
return false;
}
// find hit distance squared
const PxReal d = rad_2 - (off2 - ray_dist * ray_dist);
if(d<0.0f)
{
// ray passes by sphere without hitting
return false;
}
// get the distance along the ray
dist = ray_dist - PxSqrt(d);
if(dist > length)
{
// hit point beyond length
return false;
}
// sort out the details
if(hit_pos)
*hit_pos = origin + dir * dist;
return true;
}
// PT: modified version calls the previous function, but moves the ray origin closer to the sphere. The test accuracy is
// greatly improved as a result. This is an idea proposed on the GD-Algorithms list by Eddie Edwards.
// See: http://www.codercorner.com/blog/?p=321
bool Gu::intersectRaySphere(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos)
{
const PxVec3 x = origin - center;
PxReal l = PxSqrt(x.dot(x)) - radius - GU_RAY_SURFACE_OFFSET;
// if(l<0.0f)
// l=0.0f;
l = physx::intrinsics::selectMax(l, 0.0f);
bool status = intersectRaySphereBasic(origin + l*dir, dir, length - l, center, radius, dist, hit_pos);
if(status)
{
// dist += l/length;
dist += l;
}
return status;
}
| 3,784 |
C++
| 35.047619 | 156 | 0.724366 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionTetrahedronBox.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionTetrahedronBox.h"
#include "foundation/PxBasicTemplates.h"
#include "GuIntersectionTriangleBox.h"
#include "GuBox.h"
using namespace physx;
namespace physx
{
namespace Gu
{
bool intersectTetrahedronBox(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxBounds3& box)
{
if (box.contains(a) || box.contains(b) || box.contains(c) || box.contains(d))
return true;
PxBounds3 tetBox = PxBounds3::empty();
tetBox.include(a);
tetBox.include(b);
tetBox.include(c);
tetBox.include(d);
tetBox.fattenFast(1e-6f);
if (!box.intersects(tetBox))
return false;
Gu::BoxPadded boxP;
boxP.center = box.getCenter();
boxP.extents = box.getExtents();
boxP.rot = PxMat33(PxIdentity);
return intersectTriangleBox(boxP, a, b, c) || intersectTriangleBox(boxP, a, b, d) || intersectTriangleBox(boxP, a, c, d) || intersectTriangleBox(boxP, b, c, d);
}
}
}
| 2,614 |
C++
| 40.507936 | 162 | 0.745601 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayCapsule.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_CAPSULE_H
#define GU_INTERSECTION_RAY_CAPSULE_H
#include "GuCapsule.h"
#include "GuDistancePointSegment.h"
#include "GuIntersectionRay.h"
namespace physx
{
namespace Gu
{
PxU32 intersectRayCapsuleInternal(const PxVec3& origin, const PxVec3& dir, const PxVec3& p0, const PxVec3& p1, float radius, PxReal s[2]);
PX_FORCE_INLINE bool intersectRayCapsule(const PxVec3& origin, const PxVec3& dir, const PxVec3& p0, const PxVec3& p1, float radius, PxReal& t)
{
// PT: move ray origin close to capsule, to solve accuracy issues.
// We compute the distance D between the ray origin and the capsule's segment.
// Then E = D - radius = distance between the ray origin and the capsule.
// We can move the origin freely along 'dir' up to E units before touching the capsule.
PxReal l = distancePointSegmentSquaredInternal(p0, p1 - p0, origin);
l = PxSqrt(l) - radius;
// PT: if this becomes negative or null, the ray starts inside the capsule and we can early exit
if(l<=0.0f)
{
t = 0.0f;
return true;
}
// PT: we remove an arbitrary GU_RAY_SURFACE_OFFSET units to E, to make sure we don't go close to the surface.
// If we're moving in the direction of the capsule, the origin is now about GU_RAY_SURFACE_OFFSET units from it.
// If we're moving away from the capsule, the ray won't hit the capsule anyway.
// If l is smaller than GU_RAY_SURFACE_OFFSET we're close enough, accuracy is good, there is nothing to do.
if(l>GU_RAY_SURFACE_OFFSET)
l -= GU_RAY_SURFACE_OFFSET;
else
l = 0.0f;
// PT: move origin closer to capsule and do the raycast
PxReal s[2];
const PxU32 nbHits = Gu::intersectRayCapsuleInternal(origin + l*dir, dir, p0, p1, radius, s);
if(!nbHits)
return false;
// PT: keep closest hit only
if(nbHits == 1)
t = s[0];
else
t = (s[0] < s[1]) ? s[0] : s[1];
// PT: fix distance (smaller than expected after moving ray close to capsule)
t += l;
return true;
}
PX_FORCE_INLINE bool intersectRayCapsule(const PxVec3& origin, const PxVec3& dir, const Gu::Capsule& capsule, PxReal& t)
{
return Gu::intersectRayCapsule(origin, dir, capsule.p0, capsule.p1, capsule.radius, t);
}
}
}
#endif
| 3,900 |
C
| 41.402173 | 143 | 0.730513 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionEdgeEdge.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionEdgeEdge.h"
#include "GuInternal.h"
using namespace physx;
bool Gu::intersectEdgeEdge(const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip)
{
const PxVec3 v1 = p2 - p1;
// Build plane P based on edge (p1, p2) and direction (dir)
PxPlane plane;
plane.n = v1.cross(dir);
plane.d = -(plane.n.dot(p1));
// if colliding edge (p3,p4) does not cross plane return no collision
// same as if p3 and p4 on same side of plane return 0
//
// Derivation:
// d3 = d(p3, P) = (p3 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated.
// d4 = d(p4, P) = (p4 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated.
// if d3 and d4 have the same sign, they're on the same side of the plane => no collision
// We test both sides at the same time by only testing Sign(d3 * d4).
// ### put that in the Plane class
// ### also check that code in the triangle class that might be similar
const PxReal d3 = plane.distance(p3);
PxReal temp = d3 * plane.distance(p4);
if(temp>0.0f) return false;
// if colliding edge (p3,p4) and plane are parallel return no collision
PxVec3 v2 = p4 - p3;
temp = plane.n.dot(v2);
if(temp==0.0f) return false; // ### epsilon would be better
// compute intersection point of plane and colliding edge (p3,p4)
ip = p3-v2*(d3/temp);
// find largest 2D plane projection
PxU32 i,j;
closestAxis(plane.n, i, j);
// compute distance of intersection from line (ip, -dir) to line (p1,p2)
dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i]))/(v1[i]*dir[j]-v1[j]*dir[i]);
if(dist<0.0f) return false;
// compute intersection point on edge (p1,p2) line
ip -= dist*dir;
// check if intersection point (ip) is between edge (p1,p2) vertices
temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z);
if(temp<1e-3f) return true; // collision found
return false; // no collision
}
| 3,697 |
C++
| 43.554216 | 143 | 0.713552 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionCapsuleTriangle.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionCapsuleTriangle.h"
#include "GuDistancePointSegment.h"
using namespace physx;
using namespace Gu;
bool Gu::intersectCapsuleTriangle(const PxVec3& N, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Gu::Capsule& capsule, const CapsuleTriangleOverlapData& params)
{
PX_ASSERT(capsule.p0!=capsule.p1);
{
const PxReal d2 = distancePointSegmentSquaredInternal(capsule.p0, params.mCapsuleDir, p0);
if(d2<=capsule.radius*capsule.radius)
return true;
}
// const PxVec3 N = (p0 - p1).cross(p0 - p2);
if(!testAxis(p0, p1, p2, capsule, N))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p0, p1 - p0, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p1, p2 - p1, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p2, p0 - p2, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
return true;
}
| 2,767 |
C++
| 44.377048 | 174 | 0.755331 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionBoxBox.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionBoxBox.h"
using namespace physx;
bool Gu::intersectOBBOBB(const PxVec3& e0, const PxVec3& c0, const PxMat33& r0, const PxVec3& e1, const PxVec3& c1, const PxMat33& r1, bool full_test)
{
// Translation, in parent frame
const PxVec3 v = c1 - c0;
// Translation, in A's frame
const PxVec3 T(v.dot(r0[0]), v.dot(r0[1]), v.dot(r0[2]));
// B's basis with respect to A's local frame
PxReal R[3][3];
PxReal FR[3][3];
PxReal ra, rb, t;
// Calculate rotation matrix
for(PxU32 i=0;i<3;i++)
{
for(PxU32 k=0;k<3;k++)
{
R[i][k] = r0[i].dot(r1[k]);
FR[i][k] = 1e-6f + PxAbs(R[i][k]); // Precompute fabs matrix
}
}
// A's basis vectors
for(PxU32 i=0;i<3;i++)
{
ra = e0[i];
rb = e1[0]*FR[i][0] + e1[1]*FR[i][1] + e1[2]*FR[i][2];
t = PxAbs(T[i]);
if(t > ra + rb) return false;
}
// B's basis vectors
for(PxU32 k=0;k<3;k++)
{
ra = e0[0]*FR[0][k] + e0[1]*FR[1][k] + e0[2]*FR[2][k];
rb = e1[k];
t = PxAbs(T[0]*R[0][k] + T[1]*R[1][k] + T[2]*R[2][k]);
if( t > ra + rb ) return false;
}
if(full_test)
{
//9 cross products
//L = A0 x B0
ra = e0[1]*FR[2][0] + e0[2]*FR[1][0];
rb = e1[1]*FR[0][2] + e1[2]*FR[0][1];
t = PxAbs(T[2]*R[1][0] - T[1]*R[2][0]);
if(t > ra + rb) return false;
//L = A0 x B1
ra = e0[1]*FR[2][1] + e0[2]*FR[1][1];
rb = e1[0]*FR[0][2] + e1[2]*FR[0][0];
t = PxAbs(T[2]*R[1][1] - T[1]*R[2][1]);
if(t > ra + rb) return false;
//L = A0 x B2
ra = e0[1]*FR[2][2] + e0[2]*FR[1][2];
rb = e1[0]*FR[0][1] + e1[1]*FR[0][0];
t = PxAbs(T[2]*R[1][2] - T[1]*R[2][2]);
if(t > ra + rb) return false;
//L = A1 x B0
ra = e0[0]*FR[2][0] + e0[2]*FR[0][0];
rb = e1[1]*FR[1][2] + e1[2]*FR[1][1];
t = PxAbs(T[0]*R[2][0] - T[2]*R[0][0]);
if(t > ra + rb) return false;
//L = A1 x B1
ra = e0[0]*FR[2][1] + e0[2]*FR[0][1];
rb = e1[0]*FR[1][2] + e1[2]*FR[1][0];
t = PxAbs(T[0]*R[2][1] - T[2]*R[0][1]);
if(t > ra + rb) return false;
//L = A1 x B2
ra = e0[0]*FR[2][2] + e0[2]*FR[0][2];
rb = e1[0]*FR[1][1] + e1[1]*FR[1][0];
t = PxAbs(T[0]*R[2][2] - T[2]*R[0][2]);
if(t > ra + rb) return false;
//L = A2 x B0
ra = e0[0]*FR[1][0] + e0[1]*FR[0][0];
rb = e1[1]*FR[2][2] + e1[2]*FR[2][1];
t = PxAbs(T[1]*R[0][0] - T[0]*R[1][0]);
if(t > ra + rb) return false;
//L = A2 x B1
ra = e0[0]*FR[1][1] + e0[1]*FR[0][1];
rb = e1[0] *FR[2][2] + e1[2]*FR[2][0];
t = PxAbs(T[1]*R[0][1] - T[0]*R[1][1]);
if(t > ra + rb) return false;
//L = A2 x B2
ra = e0[0]*FR[1][2] + e0[1]*FR[0][2];
rb = e1[0]*FR[2][1] + e1[1]*FR[2][0];
t = PxAbs(T[1]*R[0][2] - T[0]*R[1][2]);
if(t > ra + rb) return false;
}
return true;
}
| 4,345 |
C++
| 30.266187 | 150 | 0.591484 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionTriangleTriangle.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionTriangleTriangle.h"
#include "foundation/PxPlane.h"
using namespace physx;
using namespace Gu;
namespace
{
//Based on the paper A Fast Triangle-Triangle Intersection Test by T. Moeller
//http://web.stanford.edu/class/cs277/resources/papers/Moller1997b.pdf
struct Interval
{
PxReal min;
PxReal max;
PxVec3 minPoint;
PxVec3 maxPoint;
PX_FORCE_INLINE Interval() : min(FLT_MAX), max(-FLT_MAX), minPoint(PxVec3(NAN)), maxPoint(PxVec3(NAN)) { }
PX_FORCE_INLINE static bool overlapOrTouch(const Interval& a, const Interval& b)
{
return !(a.min > b.max || b.min > a.max);
}
PX_FORCE_INLINE static Interval intersection(const Interval& a, const Interval& b)
{
Interval result;
if (!overlapOrTouch(a, b))
return result;
if (a.min > b.min)
{
result.min = a.min;
result.minPoint = a.minPoint;
}
else
{
result.min = b.min;
result.minPoint = b.minPoint;
}
if (a.max < b.max)
{
result.max = a.max;
result.maxPoint = a.maxPoint;
}
else
{
result.max = b.max;
result.maxPoint = b.maxPoint;
}
return result;
}
PX_FORCE_INLINE void include(PxReal d, const PxVec3& p)
{
if (d < min) { min = d; minPoint = p; }
if (d > max) { max = d; maxPoint = p; }
}
};
PX_FORCE_INLINE static Interval computeInterval(PxReal distanceA, PxReal distanceB, PxReal distanceC, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& dir)
{
Interval i;
const bool bA = distanceA > 0;
const bool bB = distanceB > 0;
const bool bC = distanceC > 0;
distanceA = PxAbs(distanceA);
distanceB = PxAbs(distanceB);
distanceC = PxAbs(distanceC);
if (bA != bB)
{
const PxVec3 p = (distanceA / (distanceA + distanceB)) * b + (distanceB / (distanceA + distanceB)) * a;
i.include(dir.dot(p), p);
}
if (bA != bC)
{
const PxVec3 p = (distanceA / (distanceA + distanceC)) * c + (distanceC / (distanceA + distanceC)) * a;
i.include(dir.dot(p), p);
}
if (bB != bC)
{
const PxVec3 p = (distanceB / (distanceB + distanceC)) * c + (distanceC / (distanceB + distanceC)) * b;
i.include(dir.dot(p), p);
}
return i;
}
PX_FORCE_INLINE PxReal orient2d(const PxVec3& a, const PxVec3& b, const PxVec3& c, PxU32 x, PxU32 y)
{
return (a[y] - c[y]) * (b[x] - c[x]) - (a[x] - c[x]) * (b[y] - c[y]);
}
PX_FORCE_INLINE PxReal pointInTriangle(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& point, PxU32 x, PxU32 y)
{
const PxReal ab = orient2d(a, b, point, x, y);
const PxReal bc = orient2d(b, c, point, x, y);
const PxReal ca = orient2d(c, a, point, x, y);
if ((ab >= 0) == (bc >= 0) && (ab >= 0) == (ca >= 0))
return true;
return false;
}
PX_FORCE_INLINE PxReal linesIntersect(const PxVec3& startA, const PxVec3& endA, const PxVec3& startB, const PxVec3& endB, PxU32 x, PxU32 y)
{
const PxReal aaS = orient2d(startA, endA, startB, x, y);
const PxReal aaE = orient2d(startA, endA, endB, x, y);
if ((aaS >= 0) == (aaE >= 0))
return false;
const PxReal bbS = orient2d(startB, endB, startA, x, y);
const PxReal bbE = orient2d(startB, endB, endA, x, y);
if ((bbS >= 0) == (bbE >= 0))
return false;
return true;
}
PX_FORCE_INLINE void getProjectionIndices(PxVec3 normal, PxU32& x, PxU32& y)
{
normal.x = PxAbs(normal.x);
normal.y = PxAbs(normal.y);
normal.z = PxAbs(normal.z);
if (normal.x >= normal.y && normal.x >= normal.z)
{
//x is the dominant normal direction
x = 1;
y = 2;
}
else if (normal.y >= normal.x && normal.y >= normal.z)
{
//y is the dominant normal direction
x = 2;
y = 0;
}
else
{
//z is the dominant normal direction
x = 0;
y = 1;
}
}
PX_FORCE_INLINE bool trianglesIntersectCoplanar(const PxPlane& p1, const PxVec3& a1, const PxVec3& b1, const PxVec3& c1, const PxVec3& a2, const PxVec3& b2, const PxVec3& c2)
{
PxU32 x = 0;
PxU32 y = 0;
getProjectionIndices(p1.n, x, y);
const PxReal third = (1.0f / 3.0f);
//A bit of the computations done inside the following functions could be shared but it's kept simple since the
//difference is not very big and the coplanar case is not expected to be the most common case
if (linesIntersect(a1, b1, a2, b2, x, y) || linesIntersect(a1, b1, b2, c2, x, y) || linesIntersect(a1, b1, c2, a2, x, y) ||
linesIntersect(b1, c1, a2, b2, x, y) || linesIntersect(b1, c1, b2, c2, x, y) || linesIntersect(b1, c1, c2, a2, x, y) ||
linesIntersect(c1, a1, a2, b2, x, y) || linesIntersect(c1, a1, b2, c2, x, y) || linesIntersect(c1, a1, c2, a2, x, y) ||
pointInTriangle(a1, b1, c1, third * (a2 + b2 + c2), x, y) || pointInTriangle(a2, b2, c2, third * (a1 + b1 + c1), x, y))
return true;
return false;
}
}
bool Gu::trianglesIntersect(const PxVec3& a1, const PxVec3& b1, const PxVec3& c1, const PxVec3& a2, const PxVec3& b2, const PxVec3& c2/*, Segment* intersection*/, bool ignoreCoplanar)
{
const PxReal tolerance = 1e-8f;
const PxPlane p1(a1, b1, c1);
const PxReal p1ToA = p1.distance(a2);
const PxReal p1ToB = p1.distance(b2);
const PxReal p1ToC = p1.distance(c2);
if(PxAbs(p1ToA) < tolerance && PxAbs(p1ToB) < tolerance &&PxAbs(p1ToC) < tolerance)
return ignoreCoplanar ? false : trianglesIntersectCoplanar(p1, a1, b1, c1, a2, b2, c2); //Coplanar triangles
if ((p1ToA > 0) == (p1ToB > 0) && (p1ToA > 0) == (p1ToC > 0))
return false; //All points of triangle 2 on same side of triangle 1 -> no intersection
const PxPlane p2(a2, b2, c2);
const PxReal p2ToA = p2.distance(a1);
const PxReal p2ToB = p2.distance(b1);
const PxReal p2ToC = p2.distance(c1);
if ((p2ToA > 0) == (p2ToB > 0) && (p2ToA > 0) == (p2ToC > 0))
return false; //All points of triangle 1 on same side of triangle 2 -> no intersection
PxVec3 intersectionDirection = p1.n.cross(p2.n);
const PxReal l2 = intersectionDirection.magnitudeSquared();
intersectionDirection *= 1.0f / PxSqrt(l2);
const Interval i1 = computeInterval(p2ToA, p2ToB, p2ToC, a1, b1, c1, intersectionDirection);
const Interval i2 = computeInterval(p1ToA, p1ToB, p1ToC, a2, b2, c2, intersectionDirection);
if (Interval::overlapOrTouch(i1, i2))
{
/*if (intersection)
{
const Interval i = Interval::intersection(i1, i2);
intersection->p0 = i.minPoint;
intersection->p1 = i.maxPoint;
}*/
return true;
}
return false;
}
| 8,051 |
C++
| 32.272727 | 183 | 0.667371 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionSphereBox.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionSphereBox.h"
#include "GuSphere.h"
#include "GuBox.h"
using namespace physx;
bool Gu::intersectSphereBox(const Sphere& sphere, const Box& box)
{
const PxVec3 delta = sphere.center - box.center;
PxVec3 dRot = box.rot.transformTranspose(delta); //transform delta into OBB body coords. (use method call!)
//check if delta is outside AABB - and clip the vector to the AABB.
bool outside = false;
if(dRot.x < -box.extents.x)
{
outside = true;
dRot.x = -box.extents.x;
}
else if(dRot.x > box.extents.x)
{
outside = true;
dRot.x = box.extents.x;
}
if(dRot.y < -box.extents.y)
{
outside = true;
dRot.y = -box.extents.y;
}
else if(dRot.y > box.extents.y)
{
outside = true;
dRot.y = box.extents.y;
}
if(dRot.z < -box.extents.z)
{
outside = true;
dRot.z = -box.extents.z;
}
else if(dRot.z > box.extents.z)
{
outside = true;
dRot.z = box.extents.z;
}
if(outside) //if clipping was done, sphere center is outside of box.
{
const PxVec3 clippedDelta = box.rot.transform(dRot); //get clipped delta back in world coords.
const PxVec3 clippedVec = delta - clippedDelta; //what we clipped away.
const PxReal lenSquared = clippedVec.magnitudeSquared();
const PxReal radius = sphere.radius;
if(lenSquared > radius * radius) // PT: objects are defined as closed, so we return 'true' in case of equality
return false; //disjoint
}
return true;
}
| 3,137 |
C++
| 34.659091 | 112 | 0.722665 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayBox.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxVec3.h"
#include "foundation/PxMathIntrinsics.h"
#include "foundation/PxFPU.h"
#include "GuIntersectionRayBox.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Computes a ray-AABB intersection.
* Original code by Andrew Woo, from "Graphics Gems", Academic Press, 1990
* Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
* Epsilon value added by Klaus Hartmann. (discarding it saves a few cycles only)
*
* Hence this version is faster as well as more robust than the original one.
*
* Should work provided:
* 1) the integer representation of 0.0f is 0x00000000
* 2) the sign bit of the float is the most significant one
*
* Report bugs: [email protected]
*
* \param aabb [in] the axis-aligned bounding box
* \param origin [in] ray origin
* \param dir [in] ray direction
* \param coord [out] impact coordinates
* \return true if ray intersects AABB
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define RAYAABB_EPSILON 0.00001f
bool Gu::rayAABBIntersect(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord)
{
PxIntBool Inside = PxIntTrue;
PxVec3 MaxT(-1.0f, -1.0f, -1.0f);
const PxReal* dir = &_dir.x;
const PxU32* idir = reinterpret_cast<const PxU32*>(dir);
// Find candidate planes.
for(PxU32 i=0;i<3;i++)
{
if(origin[i] < minimum[i])
{
coord[i] = minimum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (minimum[i] - origin[i]) / dir[i];
}
else if(origin[i] > maximum[i])
{
coord[i] = maximum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (maximum[i] - origin[i]) / dir[i];
}
}
// Ray origin inside bounding box
if(Inside)
{
coord = origin;
return true;
}
// Get largest of the maxT's for final choice of intersection
PxU32 WhichPlane = 0;
if(MaxT[1] > MaxT[WhichPlane]) WhichPlane = 1;
if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
// Check final candidate actually inside box
const PxU32* tmp = reinterpret_cast<const PxU32*>(&MaxT[WhichPlane]);
if((*tmp)&PX_SIGN_BITMASK)
// if(PX_IR(MaxT[WhichPlane])&PX_SIGN_BITMASK)
return false;
for(PxU32 i=0;i<3;i++)
{
if(i!=WhichPlane)
{
coord[i] = origin[i] + MaxT[WhichPlane] * dir[i];
#ifdef RAYAABB_EPSILON
if(coord[i] < minimum[i] - RAYAABB_EPSILON || coord[i] > maximum[i] + RAYAABB_EPSILON)
#else
if(coord[i] < minimum[i] || coord[i] > maximum[i])
#endif
return false;
}
}
return true; // ray hits box
}
/**
* Computes a ray-AABB intersection.
* Original code by Andrew Woo, from "Graphics Gems", Academic Press, 1990
* Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
* Epsilon value added by Klaus Hartmann. (discarding it saves a few cycles only)
* Return of intersected face code and parameter by Adam! Also modified behavior for ray starts inside AABB. 2004 :-p
*
* Hence this version is faster as well as more robust than the original one.
*
* Should work provided:
* 1) the integer representation of 0.0f is 0x00000000
* 2) the sign bit of the float is the most significant one
*
* Report bugs: [email protected]
*
* \param minimum [in] the smaller corner of the bounding box
* \param maximum [in] the larger corner of the bounding box
* \param origin [in] ray origin
* \param _dir [in] ray direction
* \param coord [out] impact coordinates
* \param t [out] t such that coord = origin + dir * t
* \return false if ray does not intersect AABB, or ray origin is inside AABB. Else:
1 + coordinate index of box axis that was hit
Note: sign bit that determines if the minimum (0) or maximum (1) of the axis was hit is equal to sign(coord[returnVal-1]).
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxU32 Gu::rayAABBIntersect2(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord, PxReal & t)
{
PxIntBool Inside = PxIntTrue;
PxVec3 MaxT(-1.0f, -1.0f, -1.0f);
const PxReal* dir = &_dir.x;
const PxU32* idir = reinterpret_cast<const PxU32*>(dir);
// Find candidate planes.
for(PxU32 i=0;i<3;i++)
{
if(origin[i] < minimum[i])
{
coord[i] = minimum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (minimum[i] - origin[i]) / dir[i];
}
else if(origin[i] > maximum[i])
{
coord[i] = maximum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (maximum[i] - origin[i]) / dir[i];
}
}
// Ray origin inside bounding box
if(Inside)
{
coord = origin;
t = 0;
return 1;
}
// Get largest of the maxT's for final choice of intersection
PxU32 WhichPlane = 0;
if(MaxT[1] > MaxT[WhichPlane]) WhichPlane = 1;
if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
// Check final candidate actually inside box
const PxU32* tmp = reinterpret_cast<const PxU32*>(&MaxT[WhichPlane]);
if((*tmp)&PX_SIGN_BITMASK)
// if(PX_IR(MaxT[WhichPlane])&PX_SIGN_BITMASK)
return 0;
for(PxU32 i=0;i<3;i++)
{
if(i!=WhichPlane)
{
coord[i] = origin[i] + MaxT[WhichPlane] * dir[i];
#ifdef RAYAABB_EPSILON
if(coord[i] < minimum[i] - RAYAABB_EPSILON || coord[i] > maximum[i] + RAYAABB_EPSILON) return 0;
#else
if(coord[i] < minimum[i] || coord[i] > maximum[i]) return 0;
#endif
}
}
t = MaxT[WhichPlane];
return 1 + WhichPlane; // ray hits box
}
// Collide ray defined by ray origin (ro) and ray direction (rd)
// with the bounding box. Returns -1 on no collision and the face index
// for first intersection if a collision is found together with
// the distance to the collision points (tnear and tfar)
// ptchernev:
// Should we use an enum, or should we keep the anonymous ints?
// Should we increment the return code by one (return 0 for non intersection)?
int Gu::intersectRayAABB(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float& tnear, float& tfar)
{
// Refactor
int ret=-1;
tnear = -PX_MAX_F32;
tfar = PX_MAX_F32;
// PT: why did we change the initial epsilon value?
#define LOCAL_EPSILON PX_EPS_F32
//#define LOCAL_EPSILON 0.0001f
for(unsigned int a=0;a<3;a++)
{
if(rd[a]>-LOCAL_EPSILON && rd[a]<LOCAL_EPSILON)
{
if(ro[a]<minimum[a] || ro[a]>maximum[a])
return -1;
}
else
{
const PxReal OneOverDir = 1.0f / rd[a];
PxReal t1 = (minimum[a]-ro[a]) * OneOverDir;
PxReal t2 = (maximum[a]-ro[a]) * OneOverDir;
unsigned int b = a;
if(t1>t2)
{
PxReal t=t1;
t1=t2;
t2=t;
b += 3;
}
if(t1>tnear)
{
tnear = t1;
ret = int(b);
}
if(t2<tfar)
tfar=t2;
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
}
}
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
return ret;
}
// PT: specialized version where oneOverDir is available
int Gu::intersectRayAABB(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, const PxVec3& oneOverDir, float& tnear, float& tfar)
{
// PT: why did we change the initial epsilon value?
#define LOCAL_EPSILON PX_EPS_F32
//#define LOCAL_EPSILON 0.0001f
if(physx::intrinsics::abs(rd.x)<LOCAL_EPSILON)
// if(rd.x>-LOCAL_EPSILON && rd.x<LOCAL_EPSILON)
if(ro.x<minimum.x || ro.x>maximum.x)
return -1;
if(physx::intrinsics::abs(rd.y)<LOCAL_EPSILON)
// if(rd.y>-LOCAL_EPSILON && rd.y<LOCAL_EPSILON)
if(ro.y<minimum.y || ro.y>maximum.y)
return -1;
if(physx::intrinsics::abs(rd.z)<LOCAL_EPSILON)
// if(rd.z>-LOCAL_EPSILON && rd.z<LOCAL_EPSILON)
if(ro.z<minimum.z || ro.z>maximum.z)
return -1;
PxReal t1x = (minimum.x - ro.x) * oneOverDir.x;
PxReal t2x = (maximum.x - ro.x) * oneOverDir.x;
PxReal t1y = (minimum.y - ro.y) * oneOverDir.y;
PxReal t2y = (maximum.y - ro.y) * oneOverDir.y;
PxReal t1z = (minimum.z - ro.z) * oneOverDir.z;
PxReal t2z = (maximum.z - ro.z) * oneOverDir.z;
int bx;
int by;
int bz;
if(t1x>t2x)
{
PxReal t=t1x; t1x=t2x; t2x=t;
bx = 3;
}
else
{
bx = 0;
}
if(t1y>t2y)
{
PxReal t=t1y; t1y=t2y; t2y=t;
by = 4;
}
else
{
by = 1;
}
if(t1z>t2z)
{
PxReal t=t1z; t1z=t2z; t2z=t;
bz = 5;
}
else
{
bz = 2;
}
int ret;
// if(t1x>tnear) // PT: no need to test for the first value
{
tnear = t1x;
ret = bx;
}
// tfar = PxMin(tfar, t2x);
tfar = t2x; // PT: no need to test for the first value
if(t1y>tnear)
{
tnear = t1y;
ret = by;
}
tfar = PxMin(tfar, t2y);
if(t1z>tnear)
{
tnear = t1z;
ret = bz;
}
tfar = PxMin(tfar, t2z);
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
return ret;
}
bool Gu::intersectRayAABB2(
const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float maxDist, float& tnear, float& tfar)
{
PX_ASSERT(maximum.x-minimum.x >= GU_MIN_AABB_EXTENT*0.5f);
PX_ASSERT(maximum.y-minimum.y >= GU_MIN_AABB_EXTENT*0.5f);
PX_ASSERT(maximum.z-minimum.z >= GU_MIN_AABB_EXTENT*0.5f);
// not using vector math due to vector to integer pipeline penalties. TODO: verify that it's indeed faster
namespace i = physx::intrinsics;
// P+tD=a; t=(a-P)/D
// t=(a - p.x)*1/d.x = a/d.x +(- p.x/d.x)
const PxF32 dEpsilon = 1e-9f;
// using recipFast fails height field unit tests case where a ray cast from y=10000 to 0 gets clipped to 0.27 in y
PxF32 invDx = i::recip(i::selectMax(i::abs(rd.x), dEpsilon) * i::sign(rd.x));
#ifdef RAYAABB_EPSILON
PxF32 tx0 = (minimum.x - RAYAABB_EPSILON - ro.x) * invDx;
PxF32 tx1 = (maximum.x + RAYAABB_EPSILON - ro.x) * invDx;
#else
PxF32 tx0 = (minimum.x - ro.x) * invDx;
PxF32 tx1 = (maximum.x - ro.x) * invDx;
#endif
PxF32 txMin = i::selectMin(tx0, tx1);
PxF32 txMax = i::selectMax(tx0, tx1);
PxF32 invDy = i::recip(i::selectMax(i::abs(rd.y), dEpsilon) * i::sign(rd.y));
#ifdef RAYAABB_EPSILON
PxF32 ty0 = (minimum.y - RAYAABB_EPSILON - ro.y) * invDy;
PxF32 ty1 = (maximum.y + RAYAABB_EPSILON - ro.y) * invDy;
#else
PxF32 ty0 = (minimum.y - ro.y) * invDy;
PxF32 ty1 = (maximum.y - ro.y) * invDy;
#endif
PxF32 tyMin = i::selectMin(ty0, ty1);
PxF32 tyMax = i::selectMax(ty0, ty1);
PxF32 invDz = i::recip(i::selectMax(i::abs(rd.z), dEpsilon) * i::sign(rd.z));
#ifdef RAYAABB_EPSILON
PxF32 tz0 = (minimum.z - RAYAABB_EPSILON - ro.z) * invDz;
PxF32 tz1 = (maximum.z + RAYAABB_EPSILON - ro.z) * invDz;
#else
PxF32 tz0 = (minimum.z - ro.z) * invDz;
PxF32 tz1 = (maximum.z - ro.z) * invDz;
#endif
PxF32 tzMin = i::selectMin(tz0, tz1);
PxF32 tzMax = i::selectMax(tz0, tz1);
PxF32 maxOfNears = i::selectMax(i::selectMax(txMin, tyMin), tzMin);
PxF32 minOfFars = i::selectMin(i::selectMin(txMax, tyMax), tzMax);
tnear = i::selectMax(maxOfNears, 0.0f);
tfar = i::selectMin(minOfFars, maxDist);
return (tnear<tfar);
}
bool Gu::intersectRayAABB2(const aos::Vec3VArg minimum, const aos::Vec3VArg maximum,
const aos::Vec3VArg ro, const aos::Vec3VArg rd, const aos::FloatVArg maxDist,
aos::FloatV& tnear, aos::FloatV& tfar)
{
using namespace aos;
const FloatV zero = FZero();
const Vec3V eps = V3Load(1e-9f);
const Vec3V absRD = V3Max(V3Abs(rd), eps);
const Vec3V signRD = V3Sign(rd);
const Vec3V rdV = V3Mul(absRD, signRD);
const Vec3V rdVRecip = V3Recip(rdV);
const Vec3V _min = V3Mul(V3Sub(minimum, ro), rdVRecip);
const Vec3V _max = V3Mul(V3Sub(maximum, ro), rdVRecip);
const Vec3V min = V3Min(_max, _min);
const Vec3V max = V3Max(_max, _min);
const FloatV maxOfNears = FMax(V3GetX(min), FMax(V3GetY(min), V3GetZ(min)));
const FloatV minOfFars = FMin(V3GetX(max), FMin(V3GetY(max), V3GetZ(max)));
tnear = FMax(maxOfNears, zero);
tfar = FMin(minOfFars, maxDist);
//tfar = FAdd(FMin(minOfFars, maxDist), V3GetX(eps)); // AP: + epsilon because a test vs empty box should return true
return FAllGrtr(tfar, tnear) != 0;
}
| 14,037 |
C++
| 30.334821 | 199 | 0.644725 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayCapsule.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionRayCapsule.h"
#include "foundation/PxBasicTemplates.h"
using namespace physx;
static bool intersectRaySphere(const PxVec3& rayOrigin, const PxVec3& rayDir, const PxVec3& sphereCenter, float radius2, float& tmin, float& tmax)
{
const PxVec3 CO = rayOrigin - sphereCenter;
const float a = rayDir.dot(rayDir);
const float b = 2.0f * CO.dot(rayDir);
const float c = CO.dot(CO) - radius2;
const float discriminant = b * b - 4.0f * a * c;
if(discriminant < 0.0f)
return false;
const float OneOver2A = 1.0f / (2.0f * a);
const float sqrtDet = sqrtf(discriminant);
tmin = (-b - sqrtDet) * OneOver2A;
tmax = (-b + sqrtDet) * OneOver2A;
if(tmin > tmax)
PxSwap(tmin, tmax);
return true;
}
PxU32 Gu::intersectRayCapsuleInternal(const PxVec3& rayOrigin, const PxVec3& rayDir, const PxVec3& capsuleP0, const PxVec3& capsuleP1, float radius, PxReal s[2])
{
const float radius2 = radius * radius;
const PxVec3 AB = capsuleP1 - capsuleP0;
const PxVec3 AO = rayOrigin - capsuleP0;
const float AB_dot_d = AB.dot(rayDir);
const float AB_dot_AO = AB.dot(AO);
const float AB_dot_AB = AB.dot(AB);
const float OneOverABDotAB = AB_dot_AB!=0.0f ? 1.0f / AB_dot_AB : 0.0f;
const float m = AB_dot_d * OneOverABDotAB;
const float n = AB_dot_AO * OneOverABDotAB;
const PxVec3 Q = rayDir - (AB * m);
const PxVec3 R = AO - (AB * n);
const float a = Q.dot(Q);
const float b = 2.0f * Q.dot(R);
const float c = R.dot(R) - radius2;
if(a == 0.0f)
{
float atmin, atmax, btmin, btmax;
if( !intersectRaySphere(rayOrigin, rayDir, capsuleP0, radius2, atmin, atmax)
|| !intersectRaySphere(rayOrigin, rayDir, capsuleP1, radius2, btmin, btmax))
return 0;
s[0] = atmin < btmin ? atmin : btmin;
return 1;
}
const float discriminant = b * b - 4.0f * a * c;
if(discriminant < 0.0f)
return 0;
const float OneOver2A = 1.0f / (2.0f * a);
const float sqrtDet = sqrtf(discriminant);
float tmin = (-b - sqrtDet) * OneOver2A;
float tmax = (-b + sqrtDet) * OneOver2A;
if(tmin > tmax)
PxSwap(tmin, tmax);
const float t_k1 = tmin * m + n;
if(t_k1 < 0.0f)
{
float stmin, stmax;
if(intersectRaySphere(rayOrigin, rayDir, capsuleP0, radius2, stmin, stmax))
s[0] = stmin;
else
return 0;
}
else if(t_k1 > 1.0f)
{
float stmin, stmax;
if(intersectRaySphere(rayOrigin, rayDir, capsuleP1, radius2, stmin, stmax))
s[0] = stmin;
else
return 0;
}
else
s[0] = tmin;
return 1;
}
| 4,142 |
C++
| 32.959016 | 161 | 0.707146 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayBox.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_BOX_H
#define GU_INTERSECTION_RAY_BOX_H
#include "foundation/PxMathIntrinsics.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
bool rayAABBIntersect(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord);
PxU32 rayAABBIntersect2(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord, PxReal & t);
// Collide ray defined by ray origin (rayOrigin) and ray direction (rayDirection)
// with the bounding box. Returns -1 on no collision and the face index
// for first intersection if a collision is found together with
// the distance to the collision points (tnear and tfar)
//
// ptchernev:
// Even though the above is the original comment by Pierre I am quite confident
// that the tnear and tfar parameters are parameters along rayDirection of the
// intersection points:
//
// ip0 = rayOrigin + (rayDirection * tnear)
// ip1 = rayOrigin + (rayDirection * tfar)
//
// The return code is:
// -1 no intersection
// 0 the ray first hits the plane at aabbMin.x
// 1 the ray first hits the plane at aabbMin.y
// 2 the ray first hits the plane at aabbMin.z
// 3 the ray first hits the plane at aabbMax.x
// 4 the ray first hits the plane at aabbMax.y
// 5 the ray first hits the plane at aabbMax.z
//
// The return code will be -1 if the RAY does not intersect the AABB.
// The tnear and tfar values will give the parameters of the intersection
// points between the INFINITE LINE and the AABB.
int PX_PHYSX_COMMON_API intersectRayAABB( const PxVec3& minimum, const PxVec3& maximum,
const PxVec3& rayOrigin, const PxVec3& rayDirection,
float& tnear, float& tfar);
// Faster version when one-over-dir is available
int intersectRayAABB( const PxVec3& minimum, const PxVec3& maximum,
const PxVec3& rayOrigin, const PxVec3& rayDirection, const PxVec3& invDirection,
float& tnear, float& tfar);
// minimum extent length required for intersectRayAABB2 to return true for a zero-extent box
// this can happen when inflating the raycast by a 2-d square
#define GU_MIN_AABB_EXTENT 1e-3f
// a much faster version that doesn't return face codes
bool PX_PHYSX_COMMON_API intersectRayAABB2(
const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float maxDist, float& tnear, float& tfar);
bool PX_PHYSX_COMMON_API intersectRayAABB2( const aos::Vec3VArg minimum, const aos::Vec3VArg maximum,
const aos::Vec3VArg ro, const aos::Vec3VArg rd, const aos::FloatVArg maxDist,
aos::FloatV& tnear, aos::FloatV& tfar);
} // namespace Gu
}
#endif
| 4,446 |
C
| 46.817204 | 140 | 0.74269 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionTriangleBox.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuIntersectionTriangleBox.h"
#include "GuIntersectionTriangleBoxRef.h"
#include "GuBox.h"
#include "foundation/PxVecMath.h"
using namespace physx;
PxIntBool Gu::intersectTriangleBox_ReferenceCode(const PxVec3& boxcenter, const PxVec3& extents, const PxVec3& tp0, const PxVec3& tp1, const PxVec3& tp2)
{
return intersectTriangleBox_RefImpl(boxcenter, extents, tp0, tp1, tp2);
}
using namespace aos;
static PX_FORCE_INLINE int testClassIIIAxes(const Vec4V& e0V, const Vec4V v0V, const Vec4V v1V, const Vec4V v2V, const PxVec3& extents)
{
const Vec4V e0XZY_V = V4PermYZXW(e0V);
const Vec4V v0XZY_V = V4PermYZXW(v0V);
const Vec4V p0V = V4NegMulSub(v0XZY_V, e0V, V4Mul(v0V, e0XZY_V));
const Vec4V v1XZY_V = V4PermYZXW(v1V);
const Vec4V p1V = V4NegMulSub(v1XZY_V, e0V, V4Mul(v1V, e0XZY_V));
const Vec4V v2XZY_V = V4PermYZXW(v2V);
const Vec4V p2V = V4NegMulSub(v2XZY_V, e0V, V4Mul(v2V, e0XZY_V));
Vec4V minV = V4Min(p0V, p1V);
minV = V4Min(minV, p2V);
const Vec4V extentsV = V4LoadU(&extents.x);
const Vec4V fe0ZYX_V = V4Abs(e0V);
const Vec4V fe0XZY_V = V4PermYZXW(fe0ZYX_V);
const Vec4V extentsXZY_V = V4PermYZXW(extentsV);
Vec4V radV = V4MulAdd(extentsV, fe0XZY_V, V4Mul(extentsXZY_V, fe0ZYX_V));
if(V4AnyGrtr3(minV, radV))
return 0;
Vec4V maxV = V4Max(p0V, p1V);
maxV = V4Max(maxV, p2V);
radV = V4Sub(V4Zero(), radV);
if(V4AnyGrtr3(radV, maxV))
return 0;
return 1;
}
static const VecU32V signV = U4LoadXYZW(0x80000000, 0x80000000, 0x80000000, 0x80000000);
static PX_FORCE_INLINE PxIntBool intersectTriangleBoxInternal(const Vec4V v0V, const Vec4V v1V, const Vec4V v2V, const PxVec3& extents)
{
// Test box axes
{
Vec4V extentsV = V4LoadU(&extents.x);
{
const Vec4V cV = V4Abs(v0V);
if(V4AllGrtrOrEq3(extentsV, cV))
return 1;
}
Vec4V minV = V4Min(v0V, v1V);
minV = V4Min(minV, v2V);
if(V4AnyGrtr3(minV, extentsV))
return 0;
Vec4V maxV = V4Max(v0V, v1V);
maxV = V4Max(maxV, v2V);
extentsV = V4Sub(V4Zero(), extentsV);
if(V4AnyGrtr3(extentsV, maxV))
return 0;
}
// Test if the box intersects the plane of the triangle
const Vec4V e0V = V4Sub(v1V, v0V);
const Vec4V e1V = V4Sub(v2V, v1V);
{
const Vec4V normalV = V4Cross(e0V, e1V);
const Vec4V dV = Vec4V_From_FloatV(V4Dot3(normalV, v0V));
const Vec4V extentsV = V4LoadU(&extents.x);
VecU32V normalSignsV = V4U32and(VecU32V_ReinterpretFrom_Vec4V(normalV), signV);
const Vec4V maxV = Vec4V_ReinterpretFrom_VecU32V(V4U32or(VecU32V_ReinterpretFrom_Vec4V(extentsV), normalSignsV));
Vec4V tmpV = Vec4V_From_FloatV(V4Dot3(normalV, maxV));
if(V4AnyGrtr3(dV, tmpV))
return 0;
normalSignsV = V4U32xor(normalSignsV, signV);
const Vec4V minV = Vec4V_ReinterpretFrom_VecU32V(V4U32or(VecU32V_ReinterpretFrom_Vec4V(extentsV), normalSignsV));
tmpV = Vec4V_From_FloatV(V4Dot3(normalV, minV));
if(V4AnyGrtr3(tmpV, dV))
return 0;
}
// Edge-edge tests
{
if(!testClassIIIAxes(e0V, v0V, v1V, v2V, extents))
return 0;
if(!testClassIIIAxes(e1V, v0V, v1V, v2V, extents))
return 0;
const Vec4V e2V = V4Sub(v0V, v2V);
if(!testClassIIIAxes(e2V, v0V, v1V, v2V, extents))
return 0;
}
return 1;
}
// PT: a SIMD version of Tomas Moller's triangle-box SAT code
PxIntBool Gu::intersectTriangleBox_Unsafe(const PxVec3& center, const PxVec3& extents, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2)
{
// Move everything so that the boxcenter is in (0,0,0)
const Vec4V BoxCenterV = V4LoadU(¢er.x);
const Vec4V v0V = V4Sub(V4LoadU(&p0.x), BoxCenterV);
const Vec4V v1V = V4Sub(V4LoadU(&p1.x), BoxCenterV);
const Vec4V v2V = V4Sub(V4LoadU(&p2.x), BoxCenterV);
return intersectTriangleBoxInternal(v0V, v1V, v2V, extents);
}
PxIntBool Gu::intersectTriangleBox(const BoxPadded& box, const PxVec3& p0_, const PxVec3& p1_, const PxVec3& p2_)
{
// PT: TODO: SIMDify this part
// PxVec3p ensures we can safely V4LoadU the data
const PxVec3p p0 = box.rotateInv(p0_ - box.center);
const PxVec3p p1 = box.rotateInv(p1_ - box.center);
const PxVec3p p2 = box.rotateInv(p2_ - box.center);
const Vec4V v0V = V4LoadU(&p0.x);
const Vec4V v1V = V4LoadU(&p1.x);
const Vec4V v2V = V4LoadU(&p2.x);
return intersectTriangleBoxInternal(v0V, v1V, v2V, box.extents);
}
static PX_FORCE_INLINE Vec4V multiply3x3V(const Vec4V p, const PxMat33& mat)
{
const FloatV xxxV = V4GetX(p);
const FloatV yyyV = V4GetY(p);
const FloatV zzzV = V4GetZ(p);
Vec4V ResV = V4Scale(V4LoadU(&mat.column0.x), xxxV);
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.column1.x), yyyV));
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.column2.x), zzzV));
return ResV;
}
// PT: warning: all params must be safe to V4LoadU
PxIntBool intersectTriangleBoxBV4( const PxVec3& p0, const PxVec3& p1, const PxVec3& p2,
const PxMat33& rotModelToBox, const PxVec3& transModelToBox, const PxVec3& extents)
{
const Vec4V transModelToBoxV = V4LoadU(&transModelToBox.x);
const Vec4V v0V = V4Add(multiply3x3V(V4LoadU(&p0.x), rotModelToBox), transModelToBoxV);
const Vec4V v1V = V4Add(multiply3x3V(V4LoadU(&p1.x), rotModelToBox), transModelToBoxV);
const Vec4V v2V = V4Add(multiply3x3V(V4LoadU(&p2.x), rotModelToBox), transModelToBoxV);
return intersectTriangleBoxInternal(v0V, v1V, v2V, extents);
}
| 6,931 |
C++
| 34.731959 | 153 | 0.732939 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionCapsuleTriangle.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_CAPSULE_TRIANGLE_H
#define GU_INTERSECTION_CAPSULE_TRIANGLE_H
#include "GuCapsule.h"
#include "foundation/PxUtilities.h"
namespace physx
{
namespace Gu
{
// PT: precomputed data for capsule-triangle test. Useful when testing the same capsule vs several triangles.
struct CapsuleTriangleOverlapData
{
PxVec3 mCapsuleDir;
float mBDotB;
float mOneOverBDotB;
void init(const Capsule& capsule)
{
const PxVec3 dir = capsule.p1 - capsule.p0;
const float BDotB = dir.dot(dir);
mCapsuleDir = dir;
mBDotB = BDotB;
mOneOverBDotB = BDotB!=0.0f ? 1.0f/BDotB : 0.0f;
}
};
// PT: tests if projections of capsule & triangle overlap on given axis
PX_FORCE_INLINE PxU32 testAxis(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Capsule& capsule, const PxVec3& axis)
{
// Project capsule
float min0 = capsule.p0.dot(axis);
float max0 = capsule.p1.dot(axis);
if(min0>max0)
PxSwap(min0, max0);
const float MR = axis.magnitude()*capsule.radius;
min0 -= MR;
max0 += MR;
// Project triangle
float min1, max1;
{
min1 = max1 = p0.dot(axis);
float dp = p1.dot(axis);
if(dp<min1) min1 = dp;
if(dp>max1) max1 = dp;
dp = p2.dot(axis);
if(dp<min1) min1 = dp;
if(dp>max1) max1 = dp;
}
// Test projections
if(max0<min1 || max1<min0)
return 0;
return 1;
}
// PT: computes shortest vector going from capsule axis to triangle edge
PX_FORCE_INLINE PxVec3 computeEdgeAxis( const PxVec3& p, const PxVec3& a,
const PxVec3& q, const PxVec3& b,
float BDotB, float oneOverBDotB)
{
const PxVec3 T = q - p;
const float ADotA = a.dot(a);
const float ADotB = a.dot(b);
const float ADotT = a.dot(T);
const float BDotT = b.dot(T);
const float denom = ADotA*BDotB - ADotB*ADotB;
float t = denom!=0.0f ? (ADotT*BDotB - BDotT*ADotB) / denom : 0.0f;
t = PxClamp(t, 0.0f, 1.0f);
float u = (t*ADotB - BDotT) * oneOverBDotB;
if(u<0.0f)
{
u = 0.0f;
t = ADotT / ADotA;
t = PxClamp(t, 0.0f, 1.0f);
}
else if(u>1.0f)
{
u = 1.0f;
t = (ADotB + ADotT) / ADotA;
t = PxClamp(t, 0.0f, 1.0f);
}
return T + b*u - a*t;
}
/**
* Checks if a capsule intersects a triangle.
*
* \param normal [in] triangle normal (orientation does not matter)
* \param p0 [in] triangle's first point
* \param p1 [in] triangle's second point
* \param p2 [in] triangle's third point
* \param capsule [in] capsule
* \param params [in] precomputed capsule params
* \return true if capsule overlaps triangle
*/
bool intersectCapsuleTriangle(const PxVec3& normal, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Gu::Capsule& capsule, const CapsuleTriangleOverlapData& params);
}
}
#endif
| 4,447 |
C
| 31.705882 | 177 | 0.697549 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuCooking.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_COOKING_H
#define GU_COOKING_H
/** \addtogroup geomutils
@{
*/
// PT: TODO: the SDK always had this questionable design decision that all APIs can include all high-level public headers,
// regardless of where they fit in the header hierarchy. For example PhysXCommon can include headers from the higher-level
// PhysX DLL. We take advantage of that here by including PxCooking from PhysXCommon. That way we can reuse the same code
// as before without decoupling it from high-level classes like PxConvexMeshDesc/etc. A cleaner solution would be to decouple
// the two and only use PxConvexMeshDesc/etc in the higher level cooking DLL. The lower-level Gu functions below would then
// operate either on Gu-level types (see e.g. PxBVH / GuBVH which was done this way), or on basic types like float and ints
// to pass vertex & triangle data around. We could also split the kitchen-sink PxCookingParams structure into separate classes
// for convex / triangle mesh / etc. Overall there might be some more refactoring to do here, and that's why these functions
// have been put in the "semi public" Gu API for now, instead of the Px API (which is more strict in terms of backward
// compatibility and how we deal with deprecated functions).
#include "cooking/PxCooking.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxMemory.h"
namespace physx
{
class PxInsertionCallback;
class PxOutputStream;
class PxBVHDesc;
class PxBVH;
class PxHeightField;
struct PxCookingParams;
namespace immediateCooking
{
PX_FORCE_INLINE static void gatherStrided(const void* src, void* dst, PxU32 nbElem, PxU32 elemSize, PxU32 stride)
{
const PxU8* s = reinterpret_cast<const PxU8*>(src);
PxU8* d = reinterpret_cast<PxU8*>(dst);
while(nbElem--)
{
PxMemCopy(d, s, elemSize);
d += elemSize;
s += stride;
}
}
PX_INLINE static bool platformMismatch()
{
// Get current endianness (the one for the platform where cooking is performed)
const PxI8 currentEndian = PxLittleEndian();
const bool mismatch = currentEndian!=1; // The files must be little endian - we don't have big endian platforms anymore.
return mismatch;
}
PX_C_EXPORT PX_PHYSX_COMMON_API PxInsertionCallback* getInsertionCallback(); // PT: should be a reference but using a pointer for C
// BVH
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookBVH(const PxBVHDesc& desc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxBVH* createBVH(const PxBVHDesc& desc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxBVH* createBVH(const PxBVHDesc& desc)
{
return createBVH(desc, *getInsertionCallback());
}
// Heightfield
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookHeightField(const PxHeightFieldDesc& desc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxHeightField* createHeightField(const PxHeightFieldDesc& desc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxHeightField* createHeightField(const PxHeightFieldDesc& desc)
{
return createHeightField(desc, *getInsertionCallback());
}
// Convex meshes
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc, PxOutputStream& stream, PxConvexMeshCookingResult::Enum* condition=NULL);
PX_C_EXPORT PX_PHYSX_COMMON_API PxConvexMesh* createConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc, PxInsertionCallback& insertionCallback, PxConvexMeshCookingResult::Enum* condition=NULL);
PX_FORCE_INLINE PxConvexMesh* createConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc)
{
return createConvexMesh(params, desc, *getInsertionCallback());
}
PX_C_EXPORT PX_PHYSX_COMMON_API bool validateConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc);
PX_C_EXPORT PX_PHYSX_COMMON_API bool computeHullPolygons(const PxCookingParams& params, const PxSimpleTriangleMesh& mesh, PxAllocatorCallback& inCallback, PxU32& nbVerts, PxVec3*& vertices,
PxU32& nbIndices, PxU32*& indices, PxU32& nbPolygons, PxHullPolygon*& hullPolygons);
// Triangle meshes
PX_C_EXPORT PX_PHYSX_COMMON_API bool validateTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc);
PX_C_EXPORT PX_PHYSX_COMMON_API PxTriangleMesh* createTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc, PxInsertionCallback& insertionCallback, PxTriangleMeshCookingResult::Enum* condition=NULL);
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc, PxOutputStream& stream, PxTriangleMeshCookingResult::Enum* condition=NULL);
PX_FORCE_INLINE PxTriangleMesh* createTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc)
{
return createTriangleMesh(params, desc, *getInsertionCallback());
}
// Tetrahedron & soft body meshes
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookTetrahedronMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& meshDesc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxTetrahedronMesh* createTetrahedronMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& meshDesc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxTetrahedronMesh* createTetrahedronMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& meshDesc)
{
return createTetrahedronMesh(params, meshDesc, *getInsertionCallback());
}
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSoftBodyMesh* createSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxSoftBodyMesh* createSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc)
{
return createSoftBodyMesh(params, simulationMeshDesc, collisionMeshDesc, softbodyDataDesc, *getInsertionCallback());
}
PX_C_EXPORT PX_PHYSX_COMMON_API PxCollisionMeshMappingData* computeModelsMapping(const PxCookingParams& params, PxTetrahedronMeshData& simulationMesh, const PxTetrahedronMeshData& collisionMesh,
const PxSoftBodyCollisionData& collisionData, const PxBoundedData* vertexToTet = NULL);
PX_C_EXPORT PX_PHYSX_COMMON_API PxCollisionTetrahedronMeshData* computeCollisionData(const PxCookingParams& params, const PxTetrahedronMeshDesc& collisionMeshDesc);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSimulationTetrahedronMeshData* computeSimulationData(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSoftBodyMesh* assembleSoftBodyMesh(PxTetrahedronMeshData& simulationMesh, PxSoftBodySimulationData& simulationData, PxTetrahedronMeshData& collisionMesh,
PxSoftBodyCollisionData& collisionData, PxCollisionMeshMappingData& mappingData, PxInsertionCallback& insertionCallback);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSoftBodyMesh* assembleSoftBodyMesh_Sim(PxSimulationTetrahedronMeshData& simulationMesh, PxCollisionTetrahedronMeshData& collisionMesh,
PxCollisionMeshMappingData& mappingData, PxInsertionCallback& insertionCallback);
}
}
/** @} */
#endif
| 9,422 |
C
| 56.457317 | 223 | 0.786351 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuOverlapTests.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_OVERLAP_TESTS_H
#define GU_OVERLAP_TESTS_H
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxAssert.h"
#include "foundation/PxErrors.h"
#include "foundation/PxFoundation.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
namespace physx
{
namespace Gu
{
class Capsule;
class Sphere;
// PT: this is just a shadow of what it used to be. We currently don't use TRIGGER_INSIDE anymore, but I leave it for now,
// since I really want to put this back the way it was before.
enum TriggerStatus
{
TRIGGER_DISJOINT,
TRIGGER_INSIDE,
TRIGGER_OVERLAP
};
// PT: currently only used for convex triggers
struct TriggerCache
{
PxVec3 dir;
PxU16 state;
PxU16 gjkState; //gjk succeed or fail
};
#define UNUSED_OVERLAP_THREAD_CONTEXT NULL
// PT: we use a define to be able to quickly change the signature of all overlap functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] geom0 first geometry object
// \param[in] pose0 pose of first geometry object
// \param[in] geom1 second geometry object
// \param[in] pose1 pose of second geometry object
// \param[in] cache optional cached data for triggers
// \param[in] threadContext optional per-thread context
#define GU_OVERLAP_FUNC_PARAMS const PxGeometry& geom0, const PxTransform& pose0, \
const PxGeometry& geom1, const PxTransform& pose1, \
Gu::TriggerCache* cache, PxOverlapThreadContext* threadContext
// PT: function pointer for Geom-indexed overlap functions
// See GU_OVERLAP_FUNC_PARAMS for function parameters details.
// \return true if an overlap was found, false otherwise
typedef bool (*GeomOverlapFunc) (GU_OVERLAP_FUNC_PARAMS);
// PT: typedef for a bundle of all overlap functions, i.e. the function table itself (indexed by geom-type).
typedef GeomOverlapFunc GeomOverlapTable[PxGeometryType::eGEOMETRY_COUNT];
// PT: retrieves the overlap function table (for access by external non-Gu modules)
PX_PHYSX_COMMON_API const GeomOverlapTable* getOverlapFuncTable();
PX_FORCE_INLINE bool overlap( const PxGeometry& geom0, const PxTransform& pose0,
const PxGeometry& geom1, const PxTransform& pose1,
const GeomOverlapTable* PX_RESTRICT overlapFuncs, PxOverlapThreadContext* threadContext)
{
PX_CHECK_AND_RETURN_VAL(pose0.isValid(), "Gu::overlap(): pose0 is not valid.", false);
PX_CHECK_AND_RETURN_VAL(pose1.isValid(), "Gu::overlap(): pose1 is not valid.", false);
if(geom0.getType() > geom1.getType())
{
GeomOverlapFunc overlapFunc = overlapFuncs[geom1.getType()][geom0.getType()];
PX_ASSERT(overlapFunc);
return overlapFunc(geom1, pose1, geom0, pose0, NULL, threadContext);
}
else
{
GeomOverlapFunc overlapFunc = overlapFuncs[geom0.getType()][geom1.getType()];
PX_ASSERT(overlapFunc);
return overlapFunc(geom0, pose0, geom1, pose1, NULL, threadContext);
}
}
} // namespace Gu
}
#endif
| 4,733 |
C
| 39.810344 | 123 | 0.747517 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuSweepTests.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_TESTS_H
#define GU_SWEEP_TESTS_H
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
namespace physx
{
class PxConvexMeshGeometry;
class PxCapsuleGeometry;
class PxTriangle;
class PxBoxGeometry;
#define UNUSED_SWEEP_THREAD_CONTEXT NULL
// PT: TODO: unify this with raycast calls (names and order of params)
// PT: we use defines to be able to quickly change the signature of all sweep functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] geom geometry object to sweep against
// \param[in] pose pose of geometry object
// \param[in] unitDir sweep's unit dir
// \param[in] distance sweep's length/max distance
// \param[out] sweepHit hit result
// \param[in] hitFlags query behavior flags
// \param[in] inflation optional inflation value for swept shape
// \param[in] threadContext optional per-thread context
// PT: sweep parameters for capsule
#define GU_CAPSULE_SWEEP_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxCapsuleGeometry& capsuleGeom_, const PxTransform& capsulePose_, const Gu::Capsule& lss, \
const PxVec3& unitDir, PxReal distance, \
PxGeomSweepHit& sweepHit, const PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* threadContext
// PT: sweep parameters for box
#define GU_BOX_SWEEP_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxBoxGeometry& boxGeom_, const PxTransform& boxPose_, const Gu::Box& box, \
const PxVec3& unitDir, PxReal distance, \
PxGeomSweepHit& sweepHit, const PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* threadContext
// PT: sweep parameters for convex
#define GU_CONVEX_SWEEP_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxConvexMeshGeometry& convexGeom, const PxTransform& convexPose, \
const PxVec3& unitDir, PxReal distance, \
PxGeomSweepHit& sweepHit, const PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* threadContext
namespace Gu
{
class Capsule;
class Box;
// PT: function pointer for Geom-indexed capsule sweep functions
// See GU_CAPSULE_SWEEP_FUNC_PARAMS for function parameters details.
// \return true if a hit was found, false otherwise
typedef bool (*SweepCapsuleFunc) (GU_CAPSULE_SWEEP_FUNC_PARAMS);
// PT: function pointer for Geom-indexed box sweep functions
// See GU_BOX_SWEEP_FUNC_PARAMS for function parameters details.
// \return true if a hit was found, false otherwise
typedef bool (*SweepBoxFunc) (GU_BOX_SWEEP_FUNC_PARAMS);
// PT: function pointer for Geom-indexed box sweep functions
// See GU_CONVEX_SWEEP_FUNC_PARAMS for function parameters details.
// \return true if a hit was found, false otherwise
typedef bool (*SweepConvexFunc) (GU_CONVEX_SWEEP_FUNC_PARAMS);
// PT: typedef for bundles of all sweep functions, i.e. the function tables themselves (indexed by geom-type).
typedef SweepCapsuleFunc GeomSweepCapsuleTable [PxGeometryType::eGEOMETRY_COUNT];
typedef SweepBoxFunc GeomSweepBoxTable [PxGeometryType::eGEOMETRY_COUNT];
typedef SweepConvexFunc GeomSweepConvexTable [PxGeometryType::eGEOMETRY_COUNT];
struct GeomSweepFuncs
{
GeomSweepCapsuleTable capsuleMap;
GeomSweepCapsuleTable preciseCapsuleMap;
GeomSweepBoxTable boxMap;
GeomSweepBoxTable preciseBoxMap;
GeomSweepConvexTable convexMap;
};
// PT: grabs all sweep function tables at once (for access by external non-Gu modules)
PX_PHYSX_COMMON_API const GeomSweepFuncs& getSweepFuncTable();
// PT: signature for sweep-vs-triangles functions.
// We use defines to be able to quickly change the signature of all sweep functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] nbTris number of triangles in input array
// \param[in] triangles array of triangles to sweep the shape against
// \param[in] doubleSided true if input triangles are double-sided
// \param[in] x geom to sweep against input triangles
// \param[in] pose pose of geom x
// \param[in] unitDir sweep's unit dir
// \param[in] distance sweep's length/max distance
// \param[out] hit hit result
// \param[in] cachedIndex optional initial triangle index (must be <nbTris)
// \param[in] inflation optional inflation value for swept shape
// \param[in] hitFlags query behavior flags
#define GU_SWEEP_TRIANGLES_FUNC_PARAMS(x) PxU32 nbTris, const PxTriangle* triangles, bool doubleSided, \
const x& geom, const PxTransform& pose, \
const PxVec3& unitDir, const PxReal distance, \
PxGeomSweepHit& hit, const PxU32* cachedIndex, \
const PxReal inflation, PxHitFlags hitFlags
bool sweepCapsuleTriangles (GU_SWEEP_TRIANGLES_FUNC_PARAMS(PxCapsuleGeometry));
bool sweepBoxTriangles (GU_SWEEP_TRIANGLES_FUNC_PARAMS(PxBoxGeometry));
bool sweepBoxTriangles_Precise (GU_SWEEP_TRIANGLES_FUNC_PARAMS(PxBoxGeometry));
} // namespace Gu
}
#endif
| 6,901 |
C
| 48.654676 | 117 | 0.737864 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuPrunerPayload.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_PRUNER_PAYLOAD_H
#define GU_PRUNER_PAYLOAD_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/Px.h"
namespace physx
{
class PxBounds3;
namespace Gu
{
// PT: anonymous payload structure used by the pruners. This is similar in spirit to a userData pointer.
struct PrunerPayload
{
size_t data[2]; // Enough space for two arbitrary pointers
PX_FORCE_INLINE bool operator == (const PrunerPayload& other) const
{
return (data[0] == other.data[0]) && (data[1] == other.data[1]);
}
};
// PT: pointers to internal data associated with a pruner payload. The lifetime of these pointers
// is usually limited and they should be used immediately after retrieval.
struct PrunerPayloadData
{
PxBounds3* mBounds; // Pointer to internal bounds.
PxTransform* mTransform; // Pointer to internal transform, or NULL.
};
// PT: called for each removed payload. Gives users a chance to cleanup their data
// structures without duplicating the pruner-data to payload mapping on their side.
struct PrunerPayloadRemovalCallback
{
PrunerPayloadRemovalCallback() {}
virtual ~PrunerPayloadRemovalCallback() {}
virtual void invoke(PxU32 nbRemoved, const PrunerPayload* removed) = 0;
};
}
}
#endif
| 2,939 |
C
| 39.273972 | 105 | 0.752977 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuBox.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BOX_H
#define GU_BOX_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxTransform.h"
#include "foundation/PxMat33.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
class Capsule;
PX_PHYSX_COMMON_API void computeOBBPoints(PxVec3* PX_RESTRICT pts, const PxVec3& center, const PxVec3& extents, const PxVec3& base0, const PxVec3& base1, const PxVec3& base2);
/**
\brief Represents an oriented bounding box.
As a center point, extents(radii) and a rotation. i.e. the center of the box is at the center point,
the box is rotated around this point with the rotation and it is 2*extents in width, height and depth.
*/
/**
Box geometry
The rot member describes the world space orientation of the box.
The center member gives the world space position of the box.
The extents give the local space coordinates of the box corner in the positive octant.
Dimensions of the box are: 2*extent.
Transformation to world space is: worldPoint = rot * localPoint + center
Transformation to local space is: localPoint = T(rot) * (worldPoint - center)
Where T(M) denotes the transpose of M.
*/
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class
#endif
class PX_PHYSX_COMMON_API Box
{
public:
/**
\brief Constructor
*/
PX_FORCE_INLINE Box()
{
}
/**
\brief Constructor
\param origin Center of the OBB
\param extent Extents/radii of the obb.
\param base rotation to apply to the obb.
*/
//! Construct from center, extent and rotation
PX_FORCE_INLINE Box(const PxVec3& origin, const PxVec3& extent, const PxMat33& base) : rot(base), center(origin), extents(extent)
{}
//! Copy constructor
PX_FORCE_INLINE Box(const Box& other) : rot(other.rot), center(other.center), extents(other.extents)
{}
/**
\brief Destructor
*/
PX_FORCE_INLINE ~Box()
{
}
//! Assignment operator
PX_FORCE_INLINE const Box& operator=(const Box& other)
{
rot = other.rot;
center = other.center;
extents = other.extents;
return *this;
}
/**
\brief Setups an empty box.
*/
PX_INLINE void setEmpty()
{
center = PxVec3(0);
extents = PxVec3(-PX_MAX_REAL, -PX_MAX_REAL, -PX_MAX_REAL);
rot = PxMat33(PxIdentity);
}
/**
\brief Checks the box is valid.
\return true if the box is valid
*/
PX_INLINE bool isValid() const
{
// Consistency condition for (Center, Extents) boxes: Extents >= 0.0f
if(extents.x < 0.0f) return false;
if(extents.y < 0.0f) return false;
if(extents.z < 0.0f) return false;
return true;
}
/////////////
PX_FORCE_INLINE void setAxes(const PxVec3& axis0, const PxVec3& axis1, const PxVec3& axis2)
{
rot.column0 = axis0;
rot.column1 = axis1;
rot.column2 = axis2;
}
PX_FORCE_INLINE PxVec3 rotate(const PxVec3& src) const
{
return rot * src;
}
PX_FORCE_INLINE PxVec3 rotateInv(const PxVec3& src) const
{
return rot.transformTranspose(src);
}
PX_FORCE_INLINE PxVec3 transform(const PxVec3& src) const
{
return rot * src + center;
}
PX_FORCE_INLINE PxTransform getTransform() const
{
return PxTransform(center, PxQuat(rot));
}
PX_INLINE PxVec3 computeAABBExtent() const
{
const PxReal a00 = PxAbs(rot[0][0]);
const PxReal a01 = PxAbs(rot[0][1]);
const PxReal a02 = PxAbs(rot[0][2]);
const PxReal a10 = PxAbs(rot[1][0]);
const PxReal a11 = PxAbs(rot[1][1]);
const PxReal a12 = PxAbs(rot[1][2]);
const PxReal a20 = PxAbs(rot[2][0]);
const PxReal a21 = PxAbs(rot[2][1]);
const PxReal a22 = PxAbs(rot[2][2]);
const PxReal ex = extents.x;
const PxReal ey = extents.y;
const PxReal ez = extents.z;
return PxVec3( a00 * ex + a10 * ey + a20 * ez,
a01 * ex + a11 * ey + a21 * ez,
a02 * ex + a12 * ey + a22 * ez);
}
/**
Computes the obb points.
\param pts [out] 8 box points
*/
PX_FORCE_INLINE void computeBoxPoints(PxVec3* PX_RESTRICT pts) const
{
Gu::computeOBBPoints(pts, center, extents, rot.column0, rot.column1, rot.column2);
}
void create(const Gu::Capsule& capsule);
PxMat33 rot;
PxVec3 center;
PxVec3 extents;
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::Box) == 60);
//! A padded version of Gu::Box, to safely load its data using SIMD
class BoxPadded : public Box
{
public:
PX_FORCE_INLINE BoxPadded() {}
PX_FORCE_INLINE ~BoxPadded() {}
PxU32 padding;
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::BoxPadded) == 64);
#if PX_VC
#pragma warning(pop)
#endif
}
}
/** @} */
#endif
| 6,273 |
C
| 27.008928 | 176 | 0.692013 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuIntersectionTriangleBox.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_TRIANGLE_BOX_H
#define GU_INTERSECTION_TRIANGLE_BOX_H
#include "foundation/PxMat33.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
class Box;
class BoxPadded;
/**
Tests if a triangle overlaps a box (AABB). This is the reference non-SIMD code.
\param center [in] the box center
\param extents [in] the box extents
\param p0 [in] triangle's first point
\param p1 [in] triangle's second point
\param p2 [in] triangle's third point
\return true if triangle overlaps box
*/
PX_PHYSX_COMMON_API PxIntBool intersectTriangleBox_ReferenceCode(const PxVec3& center, const PxVec3& extents, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2);
/**
Tests if a triangle overlaps a box (AABB). This is the optimized SIMD code.
WARNING: the function has various SIMD requirements, left to the calling code:
- function will load 4 bytes after 'center'. Make sure it's safe to load from there.
- function will load 4 bytes after 'extents'. Make sure it's safe to load from there.
- function will load 4 bytes after 'p0'. Make sure it's safe to load from there.
- function will load 4 bytes after 'p1'. Make sure it's safe to load from there.
- function will load 4 bytes after 'p2'. Make sure it's safe to load from there.
If you can't guarantee these requirements, please use the non-SIMD reference code instead.
\param center [in] the box center.
\param extents [in] the box extents
\param p0 [in] triangle's first point
\param p1 [in] triangle's second point
\param p2 [in] triangle's third point
\return true if triangle overlaps box
*/
PX_PHYSX_COMMON_API PxIntBool intersectTriangleBox_Unsafe(const PxVec3& center, const PxVec3& extents, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2);
/**
Tests if a triangle overlaps a box (OBB).
There are currently no SIMD-related requirements for p0, p1, p2.
\param box [in] the box
\param p0 [in] triangle's first point
\param p1 [in] triangle's second point
\param p2 [in] triangle's third point
\return true if triangle overlaps box
*/
PX_PHYSX_COMMON_API PxIntBool intersectTriangleBox(const BoxPadded& box, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2);
} // namespace Gu
}
#endif
| 3,940 |
C
| 42.788888 | 165 | 0.75 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuActorShapeMap.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_ACTOR_SHAPE_MAP_H
#define GU_ACTOR_SHAPE_MAP_H
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxHashMap.h"
namespace physx
{
namespace Gu
{
typedef PxU64 ActorShapeData;
#define PX_INVALID_INDEX 0xffffffff
class ActorShapeMap
{
public:
PX_PHYSX_COMMON_API ActorShapeMap();
PX_PHYSX_COMMON_API ~ActorShapeMap();
PX_PHYSX_COMMON_API bool add(PxU32 actorIndex, const void* actor, const void* shape, ActorShapeData actorShapeData);
PX_PHYSX_COMMON_API bool remove(PxU32 actorIndex, const void* actor, const void* shape, ActorShapeData* removed);
PX_PHYSX_COMMON_API ActorShapeData find(PxU32 actorIndex, const void* actor, const void* shape) const;
struct ActorShape
{
PX_FORCE_INLINE ActorShape() {}
PX_FORCE_INLINE ActorShape(const void* actor, const void* shape) : mActor(actor), mShape(shape) {}
const void* mActor;
const void* mShape;
PX_FORCE_INLINE bool operator==(const ActorShape& p) const
{
return mActor == p.mActor && mShape == p.mShape;
}
};
private:
PxHashMap<ActorShape, ActorShapeData> mDatabase;
struct Cache
{
// const void* mActor;
const void* mShape;
ActorShapeData mData;
};
PxU32 mCacheSize;
Cache* mCache;
void resizeCache(PxU32 index);
};
}
}
#endif
| 3,073 |
C
| 35.164705 | 120 | 0.732184 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuSqInternal.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SQ_INTERNAL_H
#define GU_SQ_INTERNAL_H
#include "foundation/PxSimpleTypes.h"
#include "common/PxPhysXCommonConfig.h"
#define SQ_DEBUG_VIZ_STATIC_COLOR PxU32(PxDebugColor::eARGB_BLUE)
#define SQ_DEBUG_VIZ_DYNAMIC_COLOR PxU32(PxDebugColor::eARGB_RED)
#define SQ_DEBUG_VIZ_STATIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKBLUE)
#define SQ_DEBUG_VIZ_DYNAMIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKRED)
#define SQ_DEBUG_VIZ_COMPOUND_COLOR PxU32(PxDebugColor::eARGB_MAGENTA)
namespace physx
{
class PxRenderOutput;
class PxBounds3;
namespace Gu
{
class BVH;
class AABBTree;
class IncrementalAABBTree;
class IncrementalAABBTreeNode;
}
class DebugVizCallback
{
public:
DebugVizCallback() {}
virtual ~DebugVizCallback() {}
virtual bool visualizeNode(const physx::Gu::IncrementalAABBTreeNode& node, const physx::PxBounds3& bounds) = 0;
};
}
PX_PHYSX_COMMON_API void visualizeTree(physx::PxRenderOutput& out, physx::PxU32 color, const physx::Gu::BVH* tree);
PX_PHYSX_COMMON_API void visualizeTree(physx::PxRenderOutput& out, physx::PxU32 color, const physx::Gu::AABBTree* tree);
PX_PHYSX_COMMON_API void visualizeTree(physx::PxRenderOutput& out, physx::PxU32 color, const physx::Gu::IncrementalAABBTree* tree, physx::DebugVizCallback* cb=NULL);
// PT: macros to try limiting the code duplication in headers. Mostly it just redefines the
// SqPruner API in implementation classes, and you shouldn't have to worry about it.
// Note that this assumes pool-based pruners with an mPool class member (for now).
#define DECLARE_BASE_PRUNER_API \
virtual void shiftOrigin(const PxVec3& shift); \
virtual void visualize(PxRenderOutput& out, PxU32 primaryColor, PxU32 secondaryColor) const;
#define DECLARE_PRUNER_API_COMMON \
virtual bool addObjects(PrunerHandle* results, const PxBounds3* bounds, const PrunerPayload* data, const PxTransform* transforms, PxU32 count, bool hasPruningStructure); \
virtual void removeObjects(const PrunerHandle* handles, PxU32 count, PrunerPayloadRemovalCallback* removalCallback); \
virtual void updateObjects(const PrunerHandle* handles, PxU32 count, float inflation, const PxU32* boundsIndices, const PxBounds3* newBounds, const PxTransform32* newTransforms); \
virtual void purge(); \
virtual void commit(); \
virtual void merge(const void* mergeParams); \
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal& inOutDistance, Gu::PrunerRaycastCallback&) const; \
virtual bool overlap(const Gu::ShapeData& queryVolume, Gu::PrunerOverlapCallback&) const; \
virtual bool sweep(const Gu::ShapeData& queryVolume, const PxVec3& unitDir, PxReal& inOutDistance, Gu::PrunerRaycastCallback&) const; \
virtual const PrunerPayload& getPayloadData(PrunerHandle handle, PrunerPayloadData* data) const { return mPool.getPayloadData(handle, data); } \
virtual void preallocate(PxU32 entries) { mPool.preallocate(entries); } \
virtual bool setTransform(PrunerHandle handle, const PxTransform& transform) { return mPool.setTransform(handle, transform); } \
virtual void getGlobalBounds(PxBounds3&) const;
#endif
| 5,221 |
C
| 56.384615 | 187 | 0.712507 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuRaycastTests.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_RAYCAST_TESTS_H
#define GU_RAYCAST_TESTS_H
#include "foundation/PxSimpleTypes.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
namespace physx
{
#define UNUSED_RAYCAST_THREAD_CONTEXT NULL
// PT: we use a define to be able to quickly change the signature of all raycast functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] geom geometry object to raycast against
// \param[in] pose pose of geometry object
// \param[in] rayOrigin ray's origin
// \param[in] rayDir ray's unit dir
// \param[in] maxDist ray's length/max distance
// \param[in] hitFlags query behavior flags
// \param[in] maxHits max number of hits = size of 'hits' buffer
// \param[out] hits result buffer where to write raycast hits
// \param[in] stride size of hit structure
// \param[in] threadContext optional per-thread context
#define GU_RAY_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, \
PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride, PxRaycastThreadContext* threadContext
namespace Gu
{
// PT: function pointer for Geom-indexed raycast functions
// See GU_RAY_FUNC_PARAMS for function parameters details.
// \return number of hits written to 'hits' result buffer
// \note there's no mechanism to report overflow. Returned number of hits is just clamped to maxHits.
typedef PxU32 (*RaycastFunc) (GU_RAY_FUNC_PARAMS);
// PT: typedef for a bundle of all raycast functions, i.e. the function table itself (indexed by geom-type).
typedef RaycastFunc GeomRaycastTable[PxGeometryType::eGEOMETRY_COUNT];
// PT: retrieves the raycast function table (for access by external non-Gu modules)
PX_PHYSX_COMMON_API const GeomRaycastTable& getRaycastFuncTable();
} // namespace Gu
}
#endif
| 3,674 |
C
| 47.999999 | 131 | 0.752041 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuQuerySystem.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_QUERY_SYSTEM_H
#define GU_QUERY_SYSTEM_H
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
#include "foundation/PxBounds3.h"
#include "GuPruner.h"
#include "GuActorShapeMap.h"
namespace physx
{
class PxGeometry;
namespace Gu
{
class BVH;
class Adapter
{
public:
Adapter() {}
virtual ~Adapter() {}
virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const = 0;
};
class PrunerFilter
{
public:
PrunerFilter() {}
virtual ~PrunerFilter() {}
virtual bool processPruner(PxU32 prunerIndex/*, const PxQueryThreadContext* context*/) const = 0;
};
typedef PxU32 PrunerInfo;
PX_FORCE_INLINE PrunerInfo createPrunerInfo(PxU32 prunerIndex, bool isDynamic) { return (prunerIndex << 1) | PxU32(isDynamic); }
PX_FORCE_INLINE PxU32 getPrunerIndex(PrunerInfo info) { return PxU32(info)>>1; }
PX_FORCE_INLINE PxU32 getDynamic(PrunerInfo info) { return PxU32(info) & 1; }
PX_FORCE_INLINE ActorShapeData createActorShapeData(PrunerInfo info, PrunerHandle h) { return (ActorShapeData(h) << 32) | ActorShapeData(info); }
PX_FORCE_INLINE PrunerInfo getPrunerInfo(ActorShapeData data) { return PrunerInfo(data); }
PX_FORCE_INLINE PrunerHandle getPrunerHandle(ActorShapeData data) { return PrunerHandle(data >> 32); }
#define INVALID_ACTOR_SHAPE_DATA PxU64(-1)
class QuerySystem : public PxUserAllocated
{
public: // PT: TODO: public only to implement checkPrunerIndex easily, revisit this
struct PrunerExt : public PxUserAllocated
{
PrunerExt(Pruner* pruner, PxU32 preallocated);
~PrunerExt();
void flushMemory();
void addToDirtyList(PrunerHandle handle, PxU32 dynamic, const PxTransform& transform, const PxBounds3* userBounds=NULL);
void removeFromDirtyList(PrunerHandle handle);
bool processDirtyList(const Adapter& adapter, float inflation);
Pruner* mPruner;
PxBitMap mDirtyMap;
PxArray<PrunerHandle> mDirtyList;
PxU32 mNbStatic; // nb static objects in pruner
PxU32 mNbDynamic; // nb dynamic objects in pruner
bool mDirtyStatic; // true if dirty list contains a static
struct Data
{
PxTransform mPose;
PxBounds3 mBounds;
};
PxArray<Data> mDirtyData;
PX_NOCOPY(PrunerExt)
};
public:
PX_PHYSX_COMMON_API QuerySystem(PxU64 contextID, float inflation, const Adapter& adapter, bool usesTreeOfPruners=false);
PX_PHYSX_COMMON_API ~QuerySystem();
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
PX_FORCE_INLINE const Adapter& getAdapter() const { return mAdapter; }
PX_FORCE_INLINE PxU32 getStaticTimestamp() const { return mStaticTimestamp; }
PX_PHYSX_COMMON_API PxU32 addPruner(Pruner* pruner, PxU32 preallocated);
PX_PHYSX_COMMON_API void removePruner(PxU32 prunerIndex);
PX_FORCE_INLINE PxU32 getNbPruners() const { return mPrunerExt.size(); }
PX_FORCE_INLINE const Pruner* getPruner(PxU32 index) const { return mPrunerExt[index]->mPruner; }
PX_FORCE_INLINE Pruner* getPruner(PxU32 index) { return mPrunerExt[index]->mPruner; }
PX_PHYSX_COMMON_API ActorShapeData addPrunerShape(const PrunerPayload& payload, PxU32 prunerIndex, bool dynamic, const PxTransform& transform, const PxBounds3* userBounds=NULL);
PX_PHYSX_COMMON_API void removePrunerShape(ActorShapeData data, PrunerPayloadRemovalCallback* removalCallback);
PX_PHYSX_COMMON_API void updatePrunerShape(ActorShapeData data, bool immediately, const PxTransform& transform, const PxBounds3* userBounds=NULL);
PX_PHYSX_COMMON_API const PrunerPayload& getPayloadData(ActorShapeData data, PrunerPayloadData* ppd=NULL) const;
PX_PHYSX_COMMON_API void commitUpdates();
PX_PHYSX_COMMON_API void update(bool buildStep, bool commit);
PX_PHYSX_COMMON_API void sync(PxU32 prunerIndex, const PrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count);
PX_PHYSX_COMMON_API void flushMemory();
PX_PHYSX_COMMON_API void raycast(const PxVec3& origin, const PxVec3& unitDir, float& inOutDistance, PrunerRaycastCallback& cb, const PrunerFilter* prunerFilter) const;
PX_PHYSX_COMMON_API void overlap(const ShapeData& queryVolume, PrunerOverlapCallback& cb, const PrunerFilter* prunerFilter) const;
PX_PHYSX_COMMON_API void sweep(const ShapeData& queryVolume, const PxVec3& unitDir, float& inOutDistance, PrunerRaycastCallback& cb, const PrunerFilter* prunerFilter) const;
PxU32 startCustomBuildstep();
void customBuildstep(PxU32 index);
void finishCustomBuildstep();
void createTreeOfPruners();
private:
const Adapter& mAdapter;
PxArray<PrunerExt*> mPrunerExt;
PxArray<PxU32> mDirtyPruners;
PxArray<PxU32> mFreePruners;
Gu::BVH* mTreeOfPruners;
const PxU64 mContextID;
PxU32 mStaticTimestamp;
const float mInflation; // SQ_PRUNER_EPSILON
PxMutex mSQLock; // to make sure only one query updates the dirty pruner structure if multiple queries run in parallel
volatile bool mPrunerNeedsUpdating;
volatile bool mTimestampNeedsUpdating;
const bool mUsesTreeOfPruners;
void processDirtyLists();
PX_FORCE_INLINE void invalidateStaticTimestamp() { mStaticTimestamp++; }
PX_NOCOPY(QuerySystem)
};
}
}
#include "geometry/PxGeometryHit.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "GuCachedFuncs.h"
#include "GuCapsule.h"
#include "GuBounds.h"
#if PX_VC
#pragma warning(disable: 4355 ) // "this" used in base member initializer list
#endif
namespace physx
{
namespace Gu
{
// PT: TODO: use templates instead of v-calls?
// PT: we decouple the filter callback from the rest, so that the same filter callback can easily be reused for all pruner queries.
// This combines the pre-filter callback and fetching the payload's geometry in a single call. Return null to ignore that object.
struct PrunerFilterCallback
{
virtual ~PrunerFilterCallback() {}
// Query's hit flags can be tweaked per object. (Note that 'hitFlags' is unused for overlaps though)
virtual const PxGeometry* validatePayload(const PrunerPayload& payload, PxHitFlags& hitFlags) = 0;
};
struct DefaultPrunerRaycastCallback : public PrunerRaycastCallback, public PxRaycastThreadContext
{
PxRaycastThreadContext* mContext;
PrunerFilterCallback& mFilterCB;
const GeomRaycastTable& mCachedRaycastFuncs;
const PxVec3& mOrigin;
const PxVec3& mDir;
PxGeomRaycastHit* mLocalHits;
const PxU32 mMaxLocalHits;
const PxHitFlags mHitFlags;
PxGeomRaycastHit mClosestHit;
PrunerPayload mClosestPayload;
bool mFoundHit;
const bool mAnyHit;
DefaultPrunerRaycastCallback(PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance, PxU32 maxLocalHits, PxGeomRaycastHit* localHits, PxHitFlags hitFlags, bool anyHit, PxRaycastThreadContext* context=NULL) :
mContext (context ? context : this),
mFilterCB (filterCB),
mCachedRaycastFuncs (funcs),
mOrigin (origin),
mDir (dir),
mLocalHits (localHits),
mMaxLocalHits (maxLocalHits),
mHitFlags (hitFlags),
mFoundHit (false),
mAnyHit (anyHit)
{
mClosestHit.distance = distance;
}
virtual bool reportHits(const PrunerPayload& /*payload*/, PxU32 /*nbHits*/, PxGeomRaycastHit* /*hits*/)
{
return true;
}
virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
PX_ASSERT(payloads && transforms);
const PrunerPayload& payload = payloads[primIndex];
PxHitFlags filteredHitFlags = mHitFlags;
const PxGeometry* shapeGeom = mFilterCB.validatePayload(payload, filteredHitFlags);
if(!shapeGeom)
return true;
const RaycastFunc func = mCachedRaycastFuncs[shapeGeom->getType()];
const PxU32 nbHits = func(*shapeGeom, transforms[primIndex], mOrigin, mDir, aDist, filteredHitFlags, mMaxLocalHits, mLocalHits, sizeof(PxGeomRaycastHit), mContext);
if(!nbHits || !reportHits(payload, nbHits, mLocalHits))
return true;
const PxGeomRaycastHit& localHit = mLocalHits[0];
if(localHit.distance < mClosestHit.distance)
{
mFoundHit = true;
if(mAnyHit)
return false;
aDist = localHit.distance;
mClosestHit = localHit;
mClosestPayload = payload;
}
return true;
}
PX_NOCOPY(DefaultPrunerRaycastCallback)
};
struct DefaultPrunerRaycastAnyCallback : public DefaultPrunerRaycastCallback
{
PxGeomRaycastHit mLocalHit;
DefaultPrunerRaycastAnyCallback(PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance) :
DefaultPrunerRaycastCallback (filterCB, funcs, origin, dir, distance, 1, &mLocalHit, PxHitFlag::eANY_HIT, true) {}
};
struct DefaultPrunerRaycastClosestCallback : public DefaultPrunerRaycastCallback
{
PxGeomRaycastHit mLocalHit;
DefaultPrunerRaycastClosestCallback(PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance, PxHitFlags hitFlags) :
DefaultPrunerRaycastCallback (filterCB, funcs, origin, dir, distance, 1, &mLocalHit, hitFlags, false) {}
};
struct DefaultPrunerOverlapCallback : public PrunerOverlapCallback, public PxOverlapThreadContext
{
PxOverlapThreadContext* mContext;
PrunerFilterCallback& mFilterCB;
const GeomOverlapTable* mCachedFuncs;
const PxGeometry& mGeometry;
const PxTransform& mPose;
PxHitFlags mUnused;
DefaultPrunerOverlapCallback(PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose, PxOverlapThreadContext* context=NULL) :
mContext (context ? context : this),
mFilterCB (filterCB),
mCachedFuncs (funcs),
mGeometry (geometry),
mPose (pose)
{
}
virtual bool reportHit(const PrunerPayload& /*payload*/)
{
return true;
}
virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
PX_ASSERT(payloads && transforms);
const PrunerPayload& payload = payloads[primIndex];
const PxGeometry* shapeGeom = mFilterCB.validatePayload(payload, mUnused);
if(!shapeGeom || !Gu::overlap(mGeometry, mPose, *shapeGeom, transforms[primIndex], mCachedFuncs, mContext))
return true;
return reportHit(payload);
}
PX_NOCOPY(DefaultPrunerOverlapCallback)
};
struct BoxShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& queryVolume,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eBOX);
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepBoxFunc func = precise ? sf.preciseBoxMap[geom.getType()] : sf.boxMap[geom.getType()];
return PxU32(func(geom, pose, static_cast<const PxBoxGeometry&>(queryGeom), queryPose, queryVolume.getGuBox(), unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct SphereShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& /*queryVolume*/,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eSPHERE);
// PT: we don't use sd.getGuSphere() here because PhysX doesn't expose a set of 'SweepSphereFunc' functions,
// we have to go through a capsule (which is then seen as a sphere internally when the half-length is zero).
const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(queryGeom);
const PxCapsuleGeometry capsuleGeom(sphereGeom.radius, 0.0f);
const Capsule worldCapsule(queryPose.p, queryPose.p, sphereGeom.radius); // AP: precompute?
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom.getType()] : sf.capsuleMap[geom.getType()];
return PxU32(func(geom, pose, capsuleGeom, queryPose, worldCapsule, unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct CapsuleShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& queryVolume,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eCAPSULE);
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom.getType()] : sf.capsuleMap[geom.getType()];
return PxU32(func(geom, pose, static_cast<const PxCapsuleGeometry&>(queryGeom), queryPose, queryVolume.getGuCapsule(), unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct ConvexShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& /*queryVolume*/,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eCONVEXMESH);
const SweepConvexFunc func = sf.convexMap[geom.getType()];
return PxU32(func(geom, pose, static_cast<const PxConvexMeshGeometry&>(queryGeom), queryPose, unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct DefaultPrunerSweepCallback : public PrunerRaycastCallback, public PxSweepThreadContext
{
virtual bool reportHit(const PrunerPayload& /*payload*/, PxGeomSweepHit& /*hit*/)
{
return true;
}
};
template<class ShapeCast>
struct DefaultPrunerSweepCallbackT : public DefaultPrunerSweepCallback
{
PxSweepThreadContext* mContext;
PrunerFilterCallback& mFilterCB;
const GeomSweepFuncs& mCachedFuncs;
const PxGeometry& mGeometry;
const PxTransform& mPose;
const ShapeData& mQueryVolume;
const PxVec3& mDir;
PxGeomSweepHit mLocalHit;
const PxHitFlags mHitFlags;
PxGeomSweepHit mClosestHit;
PrunerPayload mClosestPayload;
bool mFoundHit;
const bool mAnyHit;
DefaultPrunerSweepCallbackT(PrunerFilterCallback& filterCB, const GeomSweepFuncs& funcs,
const PxGeometry& geometry, const PxTransform& pose, const ShapeData& queryVolume,
const PxVec3& dir, float distance, PxHitFlags hitFlags, bool anyHit, PxSweepThreadContext* context=NULL) :
mContext (context ? context : this),
mFilterCB (filterCB),
mCachedFuncs (funcs),
mGeometry (geometry),
mPose (pose),
mQueryVolume (queryVolume),
mDir (dir),
mHitFlags (hitFlags),
mFoundHit (false),
mAnyHit (anyHit)
{
mClosestHit.distance = distance;
}
virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
PX_ASSERT(payloads && transforms);
const PrunerPayload& payload = payloads[primIndex];
PxHitFlags filteredHitFlags = mHitFlags;
const PxGeometry* shapeGeom = mFilterCB.validatePayload(payload, filteredHitFlags);
if(!shapeGeom)
return true;
// PT: ### TODO: missing bit from PhysX version here
const float inflation = 0.0f; // ####
const PxU32 retVal = ShapeCast::sweep(mCachedFuncs, *shapeGeom, transforms[primIndex], mGeometry, mPose, mQueryVolume, mDir, aDist, mLocalHit, filteredHitFlags, inflation, mContext);
if(!retVal || !reportHit(payload, mLocalHit))
return true;
if(mLocalHit.distance < mClosestHit.distance)
{
mFoundHit = true;
if(mAnyHit)
return false;
aDist = mLocalHit.distance;
mClosestHit = mLocalHit;
mClosestPayload = payload;
}
return true;
}
PX_NOCOPY(DefaultPrunerSweepCallbackT)
};
typedef DefaultPrunerSweepCallbackT<SphereShapeCast> DefaultPrunerSphereSweepCallback;
typedef DefaultPrunerSweepCallbackT<BoxShapeCast> DefaultPrunerBoxSweepCallback;
typedef DefaultPrunerSweepCallbackT<CapsuleShapeCast> DefaultPrunerCapsuleSweepCallback;
typedef DefaultPrunerSweepCallbackT<ConvexShapeCast> DefaultPrunerConvexSweepCallback;
}
}
#endif
| 18,786 |
C
| 39.489224 | 273 | 0.741243 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuSegment.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SEGMENT_H
#define GU_SEGMENT_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxVec3.h"
namespace physx
{
namespace Gu
{
/**
\brief Represents a line segment.
Line segment geometry
In some cases this structure will be used to represent the infinite line that passes point0 and point1.
*/
class Segment
{
public:
/**
\brief Constructor
*/
PX_INLINE Segment()
{
}
/**
\brief Constructor
*/
PX_INLINE Segment(const PxVec3& _p0, const PxVec3& _p1) : p0(_p0), p1(_p1)
{
}
/**
\brief Copy constructor
*/
PX_INLINE Segment(const Segment& seg) : p0(seg.p0), p1(seg.p1)
{
}
/**
\brief Destructor
*/
PX_INLINE ~Segment()
{
}
//! Assignment operator
PX_INLINE Segment& operator=(const Segment& other)
{
p0 = other.p0;
p1 = other.p1;
return *this;
}
//! Equality operator
PX_INLINE bool operator==(const Segment& other) const
{
return (p0==other.p0 && p1==other.p1);
}
//! Inequality operator
PX_INLINE bool operator!=(const Segment& other) const
{
return (p0!=other.p0 || p1!=other.p1);
}
PX_INLINE const PxVec3& getOrigin() const
{
return p0;
}
//! Return the vector from point0 to point1
PX_INLINE PxVec3 computeDirection() const
{
return p1 - p0;
}
//! Return the vector from point0 to point1
PX_INLINE void computeDirection(PxVec3& dir) const
{
dir = p1 - p0;
}
//! Return the center of the segment segment
PX_INLINE PxVec3 computeCenter() const
{
return (p0 + p1)*0.5f;
}
PX_INLINE PxF32 computeLength() const
{
return (p1-p0).magnitude();
}
PX_INLINE PxF32 computeSquareLength() const
{
return (p1-p0).magnitudeSquared();
}
// PT: TODO: remove this one
//! Return the square of the length of vector from point0 to point1
PX_INLINE PxReal lengthSquared() const
{
return ((p1 - p0).magnitudeSquared());
}
// PT: TODO: remove this one
//! Return the length of vector from point0 to point1
PX_INLINE PxReal length() const
{
return ((p1 - p0).magnitude());
}
/* PX_INLINE void setOriginDirection(const PxVec3& origin, const PxVec3& direction)
{
p0 = p1 = origin;
p1 += direction;
}*/
/**
\brief Computes a point on the segment
\param[out] pt point on segment
\param[in] t point's parameter [t=0 => pt = mP0, t=1 => pt = mP1]
*/
PX_INLINE void computePoint(PxVec3& pt, PxF32 t) const
{
pt = p0 + t * (p1 - p0);
}
// PT: TODO: remove this one
//! Return the point at parameter t along the line: point0 + t*(point1-point0)
PX_INLINE PxVec3 getPointAt(PxReal t) const
{
return (p1 - p0)*t + p0;
}
PxVec3 p0; //!< Start of segment
PxVec3 p1; //!< End of segment
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::Segment) == 24);
}
}
/** @} */
#endif
| 4,496 |
C
| 23.983333 | 104 | 0.68016 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuPruner.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_PRUNER_H
#define GU_PRUNER_H
#include "foundation/PxUserAllocated.h"
#include "foundation/PxTransform.h"
#include "GuPrunerPayload.h"
#include "GuPrunerTypedef.h"
namespace physx
{
class PxRenderOutput;
class PxBounds3;
namespace Gu
{
class ShapeData;
struct PrunerRaycastCallback
{
PrunerRaycastCallback() {}
virtual ~PrunerRaycastCallback() {}
virtual bool invoke(PxReal& distance, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) = 0;
};
struct PrunerOverlapCallback
{
PrunerOverlapCallback() {}
virtual ~PrunerOverlapCallback() {}
virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) = 0;
};
class BasePruner : public PxUserAllocated
{
public:
BasePruner() {}
virtual ~BasePruner() {}
// shift the origin of the pruner objects
virtual void shiftOrigin(const PxVec3& shift) = 0;
// additional 'internal' interface
virtual void visualize(PxRenderOutput&, PxU32, PxU32) const {}
};
class Pruner : public BasePruner
{
public:
Pruner() {}
virtual ~Pruner() {}
/**
\brief Adds objects to the pruner.
\param[out] results Returned handles for added objects
\param[in] bounds Bounds of added objects. These bounds are used as-is so they should be pre-inflated if inflation is needed.
\param[in] data Payloads for added objects.
\param[in] transforms Transforms of added objects.
\param[in] count Number of objects in the arrays
\param[in] hasPruningStructure True if added objects have pruning structure. The structure will be merged later, adding the objects will not invalidate the pruner.
\return true if success, false if internal allocation failed. The first failing add results in a INVALID_PRUNERHANDLE.
@see PxPruningStructure
*/
virtual bool addObjects(PrunerHandle* results, const PxBounds3* bounds, const PrunerPayload* data, const PxTransform* transforms, PxU32 count, bool hasPruningStructure) = 0;
/**
\brief Removes objects from the pruner.
\param[in] handles The objects to remove
\param[in] count The number of objects to remove
\param[in] removalCallback Optional callback, called for each removed object (giving access to its payload for keeping external structures in sync)
*/
virtual void removeObjects(const PrunerHandle* handles, PxU32 count, PrunerPayloadRemovalCallback* removalCallback) = 0;
/**
\brief Updates objects with new bounds & transforms.
There are two ways to use this function:
1) manual bounds update: you can manually update the bounds via "getPayloadData" calls prior to calling "updateObjects".
In this case "updateObjects" only notifies the system that the data for these objects has changed. In this mode the
"inflation", "boundsIndices", "newBounds" and "newTransforms" parameters should remain null.
2) synchronization mode: in this case the new bounds (and optionally the new transforms) have been computed by an
external source and "updateObjects" tells the system to update its data from passed buffers. The new bounds are
always inflated by the "inflation" parameter while being copied. "boundsIndices" is an optional remap table, allowing
this call to only update a subset of the existing bounds (i.e. the updated bounds don't have to be first copied to a
separate contiguous buffer).
\param[in] handles The objects to update
\param[in] count The number of objects to update
\param[in] inflation Bounds inflation value
\param[in] boundsIndices The indices of the bounds in the bounds array (or NULL)
\param[in] newBounds Updated bounds array (or NULL)
\param[in] newTransforms Updated transforms array (or NULL)
*/
virtual void updateObjects(const PrunerHandle* handles, PxU32 count, float inflation=0.0f, const PxU32* boundsIndices=NULL, const PxBounds3* newBounds=NULL, const PxTransform32* newTransforms=NULL) = 0;
/**
\brief Gets rid of internal accel struct.
*/
virtual void purge() = 0;
/**
\brief Makes the queries consistent with previous changes.
This function must be called before starting queries on an updated Pruner and assert otherwise.
*/
virtual void commit() = 0;
/**
\brief Merges pruning structure to current pruner, parameters may differ for each pruner implementation.
\param[in] mergeParams Implementation-dependent merge data
*/
virtual void merge(const void* mergeParams) = 0;
/**
* Query functions
*
* Note: return value may disappear if PrunerCallback contains the necessary information
* currently it is still used for the dynamic pruner internally (to decide if added objects must be queried)
*/
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal& inOutDistance, PrunerRaycastCallback&) const = 0;
virtual bool overlap(const Gu::ShapeData& queryVolume, PrunerOverlapCallback&) const = 0;
virtual bool sweep(const Gu::ShapeData& queryVolume, const PxVec3& unitDir, PxReal& inOutDistance, PrunerRaycastCallback&) const = 0;
/**
\brief Retrieves the object's payload and data associated with the handle.
This function returns the payload associated with a given handle. Additionally it can return the
destination addresses for the object's bounds & transform. The user can then write the new bounds
and transform there, before eventually calling updateObjects().
\param[in] handle Object handle (initially returned by addObjects())
\param[out] data Optional location where to store the internal data associated with the payload.
\return The payload associated with the given handle.
*/
virtual const PrunerPayload& getPayloadData(PrunerHandle handle, PrunerPayloadData* data=NULL) const = 0;
/**
\brief Preallocate space
\param[in] nbEntries The number of entries to preallocate space for
*/
virtual void preallocate(PxU32 nbEntries) = 0;
/**
\brief Sets object's transform
\note This is equivalent to retrieving the transform's address with "getPayloadData" and writing
the transform there.
\param[in] handle Object handle (initially returned by addObjects())
\param[in] transform New transform
\return True if success
*/
virtual bool setTransform(PrunerHandle handle, const PxTransform& transform) = 0;
// PT: from the SQ branch, maybe temporary, unclear if a getType() function would be better etc
virtual bool isDynamic() const { return false; }
virtual void getGlobalBounds(PxBounds3&) const = 0;
};
/**
* Pruner building accel structure over time base class
*/
class DynamicPruner : public Pruner
{
public:
/**
* sets the rebuild hint rate used for step building the accel structure.
*/
virtual void setRebuildRateHint(PxU32 nbStepsForRebuild) = 0;
/**
* Steps the accel structure build.
* synchronousCall specifies if initialization can happen. It should not initialize build when called from a different thread
* returns true if finished
*/
virtual bool buildStep(bool synchronousCall = true) = 0;
/**
* Prepares new tree build
* returns true if new tree is needed
*/
virtual bool prepareBuild() = 0;
};
}
}
#endif
| 8,983 |
C
| 38.403509 | 208 | 0.740176 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuCenterExtents.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_CENTER_EXTENTS_H
#define GU_CENTER_EXTENTS_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBounds3.h"
namespace physx
{
namespace Gu
{
class CenterExtents : public physx::PxUserAllocated
{
public:
PX_FORCE_INLINE CenterExtents() {}
PX_FORCE_INLINE CenterExtents(const PxBounds3& b) { mCenter = b.getCenter(); mExtents = b.getExtents(); }
PX_FORCE_INLINE ~CenterExtents() {}
PX_FORCE_INLINE void getMin(PxVec3& min) const { min = mCenter - mExtents; }
PX_FORCE_INLINE void getMax(PxVec3& max) const { max = mCenter + mExtents; }
PX_FORCE_INLINE float getMin(PxU32 axis) const { return mCenter[axis] - mExtents[axis]; }
PX_FORCE_INLINE float getMax(PxU32 axis) const { return mCenter[axis] + mExtents[axis]; }
PX_FORCE_INLINE PxVec3 getMin() const { return mCenter - mExtents; }
PX_FORCE_INLINE PxVec3 getMax() const { return mCenter + mExtents; }
PX_FORCE_INLINE void setMinMax(const PxVec3& min, const PxVec3& max)
{
mCenter = (max + min)*0.5f;
mExtents = (max - min)*0.5f;
}
PX_FORCE_INLINE PxU32 isInside(const CenterExtents& box) const
{
if(box.getMin(0)>getMin(0)) return 0;
if(box.getMin(1)>getMin(1)) return 0;
if(box.getMin(2)>getMin(2)) return 0;
if(box.getMax(0)<getMax(0)) return 0;
if(box.getMax(1)<getMax(1)) return 0;
if(box.getMax(2)<getMax(2)) return 0;
return 1;
}
PX_FORCE_INLINE void setEmpty()
{
mExtents = PxVec3(-PX_MAX_BOUNDS_EXTENTS);
}
PX_FORCE_INLINE bool isEmpty() const
{
PX_ASSERT(isValid());
return mExtents.x<0.0f;
}
PX_FORCE_INLINE bool isFinite() const
{
return mCenter.isFinite() && mExtents.isFinite();
}
PX_FORCE_INLINE bool isValid() const
{
const PxVec3& c = mCenter;
const PxVec3& e = mExtents;
return (c.isFinite() && e.isFinite() && (((e.x >= 0.0f) && (e.y >= 0.0f) && (e.z >= 0.0f)) ||
((e.x == -PX_MAX_BOUNDS_EXTENTS) &&
(e.y == -PX_MAX_BOUNDS_EXTENTS) &&
(e.z == -PX_MAX_BOUNDS_EXTENTS))));
}
PX_FORCE_INLINE PxBounds3 transformFast(const PxMat33& matrix) const
{
PX_ASSERT(isValid());
return PxBounds3::basisExtent(matrix * mCenter, matrix, mExtents);
}
PxVec3 mCenter;
PxVec3 mExtents;
};
//! A padded version of CenterExtents, to safely load its data using SIMD
class CenterExtentsPadded : public CenterExtents
{
public:
PX_FORCE_INLINE CenterExtentsPadded() {}
PX_FORCE_INLINE ~CenterExtentsPadded() {}
PxU32 padding;
};
PX_COMPILE_TIME_ASSERT(sizeof(CenterExtentsPadded) == 7*4);
}
}
/** @} */
#endif
| 4,614 |
C
| 35.054687 | 110 | 0.653446 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuDistanceSegmentSegment.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_DISTANCE_SEGMENT_SEGMENT_H
#define GU_DISTANCE_SEGMENT_SEGMENT_H
#include "common/PxPhysXCommonConfig.h"
#include "GuSegment.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
// This version fixes accuracy issues (e.g. TTP 4617), but needs to do 2 square roots in order
// to find the normalized direction and length of the segments, and then
// a division in order to renormalize the output
PX_PHYSX_COMMON_API PxReal distanceSegmentSegmentSquared( const PxVec3& origin0, const PxVec3& dir0, PxReal extent0,
const PxVec3& origin1, const PxVec3& dir1, PxReal extent1,
PxReal* s=NULL, PxReal* t=NULL);
PX_PHYSX_COMMON_API PxReal distanceSegmentSegmentSquared( const PxVec3& origin0, const PxVec3& extent0,
const PxVec3& origin1, const PxVec3& extent1,
PxReal* s=NULL, PxReal* t=NULL);
PX_FORCE_INLINE PxReal distanceSegmentSegmentSquared( const Gu::Segment& segment0,
const Gu::Segment& segment1,
PxReal* s=NULL, PxReal* t=NULL)
{
return distanceSegmentSegmentSquared( segment0.p0, segment0.computeDirection(),
segment1.p0, segment1.computeDirection(),
s, t);
}
PX_PHYSX_COMMON_API aos::FloatV distanceSegmentSegmentSquared( const aos::Vec3VArg p1, const aos::Vec3VArg d1, const aos::Vec3VArg p2, const aos::Vec3VArg d2,
aos::FloatV& param0,
aos::FloatV& param1);
// This function do four segment segment closest point test in one go
aos::Vec4V distanceSegmentSegmentSquared4( const aos::Vec3VArg p, const aos::Vec3VArg d,
const aos::Vec3VArg p02, const aos::Vec3VArg d02,
const aos::Vec3VArg p12, const aos::Vec3VArg d12,
const aos::Vec3VArg p22, const aos::Vec3VArg d22,
const aos::Vec3VArg p32, const aos::Vec3VArg d32,
aos::Vec4V& s, aos::Vec4V& t);
} // namespace Gu
}
#endif
| 3,643 |
C
| 46.324675 | 159 | 0.721383 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuIntersectionTriangleBoxRef.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_TRIANGLE_BOX_REF_H
#define GU_INTERSECTION_TRIANGLE_BOX_REF_H
#include "foundation/PxVec3.h"
/********************************************************/
/* AABB-triangle overlap test code */
/* by Tomas Akenine-M?r */
/* Function: int triBoxOverlap(float boxcenter[3], */
/* float boxhalfsize[3],float triverts[3][3]); */
/* History: */
/* 2001-03-05: released the code in its first version */
/* 2001-06-18: changed the order of the tests, faster */
/* */
/* Acknowledgement: Many thanks to Pierre Terdiman for */
/* suggestions and discussions on how to optimize code. */
/* Thanks to David Hunt for finding a ">="-bug! */
/********************************************************/
namespace physx
{
#define CROSS(dest,v1,v2) \
dest.x=v1.y*v2.z-v1.z*v2.y; \
dest.y=v1.z*v2.x-v1.x*v2.z; \
dest.z=v1.x*v2.y-v1.y*v2.x;
#define DOT(v1,v2) (v1.x*v2.x+v1.y*v2.y+v1.z*v2.z)
#define FINDMINMAX(x0, x1, x2, minimum, maximum) \
minimum = physx::intrinsics::selectMin(x0, x1); \
maximum = physx::intrinsics::selectMax(x0, x1); \
minimum = physx::intrinsics::selectMin(minimum, x2); \
maximum = physx::intrinsics::selectMax(maximum, x2);
static PX_CUDA_CALLABLE PX_FORCE_INLINE PxIntBool planeBoxOverlap(const PxVec3& normal, PxReal d, const PxVec3& maxbox)
{
PxVec3 vmin, vmax;
if (normal.x>0.0f)
{
vmin.x = -maxbox.x;
vmax.x = maxbox.x;
}
else
{
vmin.x = maxbox.x;
vmax.x = -maxbox.x;
}
if (normal.y>0.0f)
{
vmin.y = -maxbox.y;
vmax.y = maxbox.y;
}
else
{
vmin.y = maxbox.y;
vmax.y = -maxbox.y;
}
if (normal.z>0.0f)
{
vmin.z = -maxbox.z;
vmax.z = maxbox.z;
}
else
{
vmin.z = maxbox.z;
vmax.z = -maxbox.z;
}
if(normal.dot(vmin) + d > 0.0f)
return PxIntFalse;
if(normal.dot(vmax) + d >= 0.0f)
return PxIntTrue;
return PxIntFalse;
}
/*======================== X-tests ========================*/
#define AXISTEST_X01(a, b, fa, fb) \
p0 = a*v0.y - b*v0.z; \
p2 = a*v2.y - b*v2.z; \
minimum = physx::intrinsics::selectMin(p0, p2); \
maximum = physx::intrinsics::selectMax(p0, p2); \
rad = fa * extents.y + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
#define AXISTEST_X2(a, b, fa, fb) \
p0 = a*v0.y - b*v0.z; \
p1 = a*v1.y - b*v1.z; \
minimum = physx::intrinsics::selectMin(p0, p1); \
maximum = physx::intrinsics::selectMax(p0, p1); \
rad = fa * extents.y + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
/*======================== Y-tests ========================*/
#define AXISTEST_Y02(a, b, fa, fb) \
p0 = -a*v0.x + b*v0.z; \
p2 = -a*v2.x + b*v2.z; \
minimum = physx::intrinsics::selectMin(p0, p2); \
maximum = physx::intrinsics::selectMax(p0, p2); \
rad = fa * extents.x + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
#define AXISTEST_Y1(a, b, fa, fb) \
p0 = -a*v0.x + b*v0.z; \
p1 = -a*v1.x + b*v1.z; \
minimum = physx::intrinsics::selectMin(p0, p1); \
maximum = physx::intrinsics::selectMax(p0, p1); \
rad = fa * extents.x + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
/*======================== Z-tests ========================*/
#define AXISTEST_Z12(a, b, fa, fb) \
p1 = a*v1.x - b*v1.y; \
p2 = a*v2.x - b*v2.y; \
minimum = physx::intrinsics::selectMin(p1, p2); \
maximum = physx::intrinsics::selectMax(p1, p2); \
rad = fa * extents.x + fb * extents.y; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
#define AXISTEST_Z0(a, b, fa, fb) \
p0 = a*v0.x - b*v0.y; \
p1 = a*v1.x - b*v1.y; \
minimum = physx::intrinsics::selectMin(p0, p1); \
maximum = physx::intrinsics::selectMax(p0, p1); \
rad = fa * extents.x + fb * extents.y; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
namespace Gu
{
template <const bool bDoVertexChecks = false>
static PX_CUDA_CALLABLE PX_FORCE_INLINE PxIntBool intersectTriangleBox_RefImpl(const PxVec3& boxcenter, const PxVec3& extents, const PxVec3& tp0, const PxVec3& tp1, const PxVec3& tp2)
{
/* use separating axis theorem to test overlap between triangle and box */
/* need to test for overlap in these directions: */
/* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
/* we do not even need to test these) */
/* 2) normal of the triangle */
/* 3) crossproduct(edge from tri, {x,y,z}-directin) */
/* this gives 3x3=9 more tests */
// This is the fastest branch on Sun - move everything so that the boxcenter is in (0,0,0)
const PxVec3 v0 = tp0 - boxcenter;
const PxVec3 v1 = tp1 - boxcenter;
const PxVec3 v2 = tp2 - boxcenter;
if (bDoVertexChecks)
{
if (PxAbs(v0.x) <= extents.x && PxAbs(v0.y) <= extents.y && PxAbs(v0.z) <= extents.z)
return PxIntTrue;
if (PxAbs(v1.x) <= extents.x && PxAbs(v1.y) <= extents.y && PxAbs(v1.z) <= extents.z)
return PxIntTrue;
if (PxAbs(v2.x) <= extents.x && PxAbs(v2.y) <= extents.y && PxAbs(v2.z) <= extents.z)
return PxIntTrue;
}
// compute triangle edges
const PxVec3 e0 = v1 - v0; // tri edge 0
const PxVec3 e1 = v2 - v1; // tri edge 1
const PxVec3 e2 = v0 - v2; // tri edge 2
float minimum, maximum, rad, p0, p1, p2;
// Bullet 3: test the 9 tests first (this was faster)
float fex = PxAbs(e0.x);
float fey = PxAbs(e0.y);
float fez = PxAbs(e0.z);
AXISTEST_X01(e0.z, e0.y, fez, fey);
AXISTEST_Y02(e0.z, e0.x, fez, fex);
AXISTEST_Z12(e0.y, e0.x, fey, fex);
fex = PxAbs(e1.x);
fey = PxAbs(e1.y);
fez = PxAbs(e1.z);
AXISTEST_X01(e1.z, e1.y, fez, fey);
AXISTEST_Y02(e1.z, e1.x, fez, fex);
AXISTEST_Z0(e1.y, e1.x, fey, fex);
fex = PxAbs(e2.x);
fey = PxAbs(e2.y);
fez = PxAbs(e2.z);
AXISTEST_X2(e2.z, e2.y, fez, fey);
AXISTEST_Y1(e2.z, e2.x, fez, fex);
AXISTEST_Z12(e2.y, e2.x, fey, fex);
// Bullet 1:
// first test overlap in the {x,y,z}-directions
// find minimum, maximum of the triangle each direction, and test for overlap in
// that direction -- this is equivalent to testing a minimal AABB around
// the triangle against the AABB
// test in X-direction
FINDMINMAX(v0.x, v1.x, v2.x, minimum, maximum);
if(minimum>extents.x || maximum<-extents.x)
return PxIntFalse;
// test in Y-direction
FINDMINMAX(v0.y, v1.y, v2.y, minimum, maximum);
if(minimum>extents.y || maximum<-extents.y)
return PxIntFalse;
// test in Z-direction
FINDMINMAX(v0.z, v1.z, v2.z, minimum, maximum);
if(minimum>extents.z || maximum<-extents.z)
return PxIntFalse;
// Bullet 2:
// test if the box intersects the plane of the triangle
// compute plane equation of triangle: normal*x+d=0
PxVec3 normal;
CROSS(normal, e0, e1);
const float d = -DOT(normal, v0); // plane eq: normal.x+d=0
if(!planeBoxOverlap(normal, d, extents))
return PxIntFalse;
return PxIntTrue; // box and triangle overlaps
}
}
#undef CROSS
#undef DOT
#undef FINDMINMAX
#undef AXISTEST_X01
#undef AXISTEST_X2
#undef AXISTEST_Y02
#undef AXISTEST_Y1
#undef AXISTEST_Z12
#undef AXISTEST_Z0
}
#endif
| 9,123 |
C
| 33.560606 | 185 | 0.612737 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuDistancePointTriangle.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_DISTANCE_POINT_TRIANGLE_H
#define GU_DISTANCE_POINT_TRIANGLE_H
#include "foundation/PxVec3.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
// PT: special version:
// - inlined
// - doesn't compute (s,t) output params
// - expects precomputed edges in input
PX_FORCE_INLINE PX_CUDA_CALLABLE PxVec3 closestPtPointTriangle2(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& ab, const PxVec3& ac)
{
// Check if P in vertex region outside A
//const PxVec3 ab = b - a;
//const PxVec3 ac = c - a;
const PxVec3 ap = p - a;
const float d1 = ab.dot(ap);
const float d2 = ac.dot(ap);
if(d1<=0.0f && d2<=0.0f)
return a; // Barycentric coords 1,0,0
// Check if P in vertex region outside B
const PxVec3 bp = p - b;
const float d3 = ab.dot(bp);
const float d4 = ac.dot(bp);
if(d3>=0.0f && d4<=d3)
return b; // Barycentric coords 0,1,0
// Check if P in edge region of AB, if so return projection of P onto AB
const float vc = d1*d4 - d3*d2;
if(vc<=0.0f && d1>=0.0f && d3<=0.0f)
{
const float v = d1 / (d1 - d3);
return a + v * ab; // barycentric coords (1-v, v, 0)
}
// Check if P in vertex region outside C
const PxVec3 cp = p - c;
const float d5 = ab.dot(cp);
const float d6 = ac.dot(cp);
if(d6>=0.0f && d5<=d6)
return c; // Barycentric coords 0,0,1
// Check if P in edge region of AC, if so return projection of P onto AC
const float vb = d5*d2 - d1*d6;
if(vb<=0.0f && d2>=0.0f && d6<=0.0f)
{
const float w = d2 / (d2 - d6);
return a + w * ac; // barycentric coords (1-w, 0, w)
}
// Check if P in edge region of BC, if so return projection of P onto BC
const float va = d3*d6 - d5*d4;
if(va<=0.0f && (d4-d3)>=0.0f && (d5-d6)>=0.0f)
{
const float w = (d4-d3) / ((d4 - d3) + (d5-d6));
return b + w * (c-b); // barycentric coords (0, 1-w, w)
}
// P inside face region. Compute Q through its barycentric coords (u,v,w)
const float denom = 1.0f / (va + vb + vc);
const float v = vb * denom;
const float w = vc * denom;
return a + ab*v + ac*w;
}
//Scales and translates triangle and query points to fit into the unit box to make calculations less prone to numerical cancellation.
//The returned point will still be in the same space as the input points.
PX_FORCE_INLINE PX_CUDA_CALLABLE PxVec3 closestPtPointTriangle2UnitBox(const PxVec3& queryPoint, const PxVec3& triA, const PxVec3& triB, const PxVec3& triC)
{
const PxVec3 min = queryPoint.minimum(triA.minimum(triB.minimum(triC)));
const PxVec3 max = queryPoint.maximum(triA.maximum(triB.maximum(triC)));
const PxVec3 size = max - min;
PxReal invScaling = PxMax(PxMax(size.x, size.y), PxMax(1e-12f, size.z));
PxReal scaling = 1.0f / invScaling;
PxVec3 p = (queryPoint - min) * scaling;
PxVec3 a = (triA - min) * scaling;
PxVec3 b = (triB - min) * scaling;
PxVec3 c = (triC - min) * scaling;
PxVec3 result = closestPtPointTriangle2(p, a, b, c, b - a, c - a);
return result * invScaling + min;
}
PX_PHYSX_COMMON_API PxVec3 closestPtPointTriangle(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, float& s, float& t);
PX_FORCE_INLINE PxReal distancePointTriangleSquared(const PxVec3& point,
const PxVec3& triangleOrigin, const PxVec3& triangleEdge0, const PxVec3& triangleEdge1,
PxReal* param0=NULL, PxReal* param1=NULL)
{
const PxVec3 pt0 = triangleEdge0 + triangleOrigin;
const PxVec3 pt1 = triangleEdge1 + triangleOrigin;
float s,t;
const PxVec3 cp = closestPtPointTriangle(point, triangleOrigin, pt0, pt1, s, t);
if(param0)
*param0 = s;
if(param1)
*param1 = t;
return (cp - point).magnitudeSquared();
}
PX_PHYSX_COMMON_API aos::FloatV distancePointTriangleSquared( const aos::Vec3VArg point,
const aos::Vec3VArg a,
const aos::Vec3VArg b,
const aos::Vec3VArg c,
aos::FloatV& u,
aos::FloatV& v,
aos::Vec3V& closestP);
//Scales and translates triangle and query points to fit into the unit box to make calculations less prone to numerical cancellation.
//The returned point and squared distance will still be in the same space as the input points.
PX_PHYSX_COMMON_API aos::FloatV distancePointTriangleSquared2UnitBox(
const aos::Vec3VArg point,
const aos::Vec3VArg a,
const aos::Vec3VArg b,
const aos::Vec3VArg c,
aos::FloatV& u,
aos::FloatV& v,
aos::Vec3V& closestP);
} // namespace Gu
}
#endif
| 6,285 |
C
| 38.043478 | 168 | 0.684964 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuBounds.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BOUNDS_H
#define GU_BOUNDS_H
#include "foundation/PxBounds3.h"
#include "foundation/PxFlags.h"
#include "foundation/PxVecMath.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include <stddef.h>
#include "GuBox.h"
#include "GuCenterExtents.h"
#include "GuSphere.h"
#include "GuCapsule.h"
// PT: the PX_MAX_BOUNDS_EXTENTS value is too large and produces INF floats when the box values are squared in
// some collision routines. Thus, for the SQ subsystem we use this alternative (smaller) value to mark empty bounds.
// See PX-954 for details.
#define GU_EMPTY_BOUNDS_EXTENTS PxSqrt(0.25f * 1e33f)
namespace physx
{
class PxMeshScale;
namespace Gu
{
PX_FORCE_INLINE void computeCapsuleBounds(PxBounds3& bounds, const PxCapsuleGeometry& capsuleGeom, const PxTransform& pose, float contactOffset=0.0f, float inflation=1.0f)
{
const PxVec3 d = pose.q.getBasisVector0();
PxVec3 extents;
for(PxU32 ax = 0; ax<3; ax++)
extents[ax] = (PxAbs(d[ax]) * capsuleGeom.halfHeight + capsuleGeom.radius + contactOffset)*inflation;
bounds.minimum = pose.p - extents;
bounds.maximum = pose.p + extents;
}
//'contactOffset' and 'inflation' should not be used at the same time, i.e. either contactOffset==0.0f, or inflation==1.0f
PX_PHYSX_COMMON_API void computeBounds(PxBounds3& bounds, const PxGeometry& geometry, const PxTransform& transform, float contactOffset, float inflation); //AABB in world space.
PX_FORCE_INLINE PxBounds3 computeBounds(const PxGeometry& geometry, const PxTransform& pose)
{
PxBounds3 bounds;
computeBounds(bounds, geometry, pose, 0.0f, 1.0f);
return bounds;
}
void computeGlobalBox(PxBounds3& bounds, PxU32 nbPrims, const PxBounds3* PX_RESTRICT boxes, const PxU32* PX_RESTRICT primitives);
PX_PHYSX_COMMON_API void computeBoundsAroundVertices(PxBounds3& bounds, PxU32 nbVerts, const PxVec3* PX_RESTRICT verts);
PX_PHYSX_COMMON_API void computeTightBounds(PxBounds3& bounds, PxU32 nbVerts, const PxVec3* PX_RESTRICT verts, const PxTransform& pose, const PxMeshScale& scale, float contactOffset, float inflation);
PX_PHYSX_COMMON_API void computeLocalBoundsAndGeomEpsilon(const PxVec3* vertices, PxU32 nbVerties, PxBounds3& localBounds, PxReal& geomEpsilon);
#define StoreBounds(bounds, minV, maxV) \
V4StoreU(minV, &bounds.minimum.x); \
PX_ALIGN(16, PxVec4) max4; \
V4StoreA(maxV, &max4.x); \
bounds.maximum = PxVec3(max4.x, max4.y, max4.z);
// PT: TODO: - refactor with "inflateBounds" in GuBounds.cpp if possible
template<const bool useSIMD>
PX_FORCE_INLINE void inflateBounds(PxBounds3& dst, const PxBounds3& src, float enlargement)
{
const float coeff = 0.5f * enlargement;
if(useSIMD)
{
using namespace physx::aos;
Vec4V minV = V4LoadU(&src.minimum.x);
Vec4V maxV = V4LoadU(&src.maximum.x);
const Vec4V eV = V4Scale(V4Sub(maxV, minV), FLoad(coeff));
minV = V4Sub(minV, eV);
maxV = V4Add(maxV, eV);
StoreBounds(dst, minV, maxV);
}
else
{
// PT: this clumsy but necessary second codepath is used to read the last bound of the array
// (making sure we don't V4LoadU invalid memory). Implementation must stay in sync with the
// main codepath above. No, this is not very nice.
const PxVec3& minV = src.minimum;
const PxVec3& maxV = src.maximum;
const PxVec3 eV = (maxV - minV) * coeff;
dst.minimum = minV - eV;
dst.maximum = maxV + eV;
}
}
class ShapeData
{
public:
PX_PHYSX_COMMON_API ShapeData(const PxGeometry& g, const PxTransform& t, PxReal inflation);
// PT: used by overlaps (box, capsule, convex)
PX_FORCE_INLINE const PxVec3& getPrunerBoxGeomExtentsInflated() const { return mPrunerBoxGeomExtents; }
// PT: used by overlaps (box, capsule, convex)
PX_FORCE_INLINE const PxVec3& getPrunerWorldPos() const { return mGuBox.center; }
PX_FORCE_INLINE const PxBounds3& getPrunerInflatedWorldAABB() const { return mPrunerInflatedAABB; }
// PT: used by overlaps (box, capsule, convex)
PX_FORCE_INLINE const PxMat33& getPrunerWorldRot33() const { return mGuBox.rot; }
// PT: this one only used by overlaps so far (for sphere shape, pruner level)
PX_FORCE_INLINE const Gu::Sphere& getGuSphere() const
{
PX_ASSERT(mType == PxGeometryType::eSPHERE);
return reinterpret_cast<const Gu::Sphere&>(mGuSphere);
}
// PT: this one only used by sweeps so far (for box shape, NP level)
PX_FORCE_INLINE const Gu::Box& getGuBox() const
{
PX_ASSERT(mType == PxGeometryType::eBOX);
return mGuBox;
}
// PT: this one used by sweeps (NP level) and overlaps (pruner level) - for capsule shape
PX_FORCE_INLINE const Gu::Capsule& getGuCapsule() const
{
PX_ASSERT(mType == PxGeometryType::eCAPSULE);
return reinterpret_cast<const Gu::Capsule&>(mGuCapsule);
}
PX_FORCE_INLINE float getCapsuleHalfHeight() const
{
PX_ASSERT(mType == PxGeometryType::eCAPSULE);
return mGuBox.extents.x;
}
PX_FORCE_INLINE PxU32 isOBB() const { return PxU32(mIsOBB); }
PX_FORCE_INLINE PxGeometryType::Enum getType() const { return PxGeometryType::Enum(mType); }
PX_NOCOPY(ShapeData)
private:
// PT: box: pre-inflated box extents
// capsule: pre-inflated extents of box-around-capsule
// convex: pre-inflated extents of box-around-convex
// sphere: not used
PxVec3 mPrunerBoxGeomExtents; // used for pruners. This volume encloses but can differ from the original shape
// PT:
//
// box center = unchanged copy of initial shape's position, except for convex (position of box around convex)
// SIMD code will load it as a V4 (safe because member is not last of Gu structure)
//
// box rot = precomputed PxMat33 version of initial shape's rotation, except for convex (rotation of box around convex)
// SIMD code will load it as V4s (safe because member is not last of Gu structure)
//
// box extents = non-inflated initial box extents for box shape, half-height for capsule, otherwise not used
Gu::Box mGuBox;
PxBounds3 mPrunerInflatedAABB; // precomputed AABB for the pruner shape
PxU16 mIsOBB; // true for OBB, false for AABB. Also used as padding for mPrunerInflatedAABB, don't move.
PxU16 mType; // shape's type
// these union Gu shapes are only precomputed for narrow phase (not pruners), can be different from mPrunerVolume
// so need separate storage
union
{
PxU8 mGuCapsule[sizeof(Gu::Capsule)]; // 28
PxU8 mGuSphere[sizeof(Gu::Sphere)]; // 16
};
};
// PT: please make sure it fits in "one" cache line
PX_COMPILE_TIME_ASSERT(sizeof(ShapeData)==128);
} // namespace Gu
}
#endif
| 8,329 |
C
| 39.833333 | 201 | 0.728419 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleDriveNW.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleDriveNW.h"
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleSDK.h"
#include "PxRigidDynamic.h"
#include "PxShape.h"
#include "PxScene.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "foundation/PxUtilities.h"
#include "CmUtils.h"
namespace physx
{
extern PxF32 gToleranceScaleLength;
void PxVehicleDriveSimDataNW::setDiffData(const PxVehicleDifferentialNWData& diff)
{
PX_CHECK_AND_RETURN(diff.isValid(), "Invalid PxVehicleCoreSimulationData.mDiff");
mDiff=diff;
}
bool PxVehicleDriveSimDataNW::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mDiff.isValid(), "Invalid PxVehicleDifferentialNWData", false);
PX_CHECK_AND_RETURN_VAL(PxVehicleDriveSimData::isValid(), "Invalid PxVehicleDriveSimDataNW", false);
return true;
}
///////////////////////////////////
bool PxVehicleDriveNW::isValid() const
{
PX_CHECK_AND_RETURN_VAL(PxVehicleDrive::isValid(), "invalid PxVehicleDrive", false);
PX_CHECK_AND_RETURN_VAL(mDriveSimData.isValid(), "Invalid PxVehicleNW.mCoreSimData", false);
return true;
}
PxVehicleDriveNW* PxVehicleDriveNW::allocate(const PxU32 numWheels)
{
PX_CHECK_AND_RETURN_NULL(numWheels>0, "Cars with zero wheels are illegal");
PX_CHECK_AND_RETURN_NULL(gToleranceScaleLength > 0, "PxVehicleDriveNW::allocate - need to call PxInitVehicleSDK");
//Compute the bytes needed.
const PxU32 byteSize = sizeof(PxVehicleDriveNW) + PxVehicleDrive::computeByteSize(numWheels);
//Allocate the memory.
PxVehicleDriveNW* veh = static_cast<PxVehicleDriveNW*>(PX_ALLOC(byteSize, "PxVehicleDriveNW"));
PxMarkSerializedMemory(veh, byteSize);
PX_PLACEMENT_NEW(veh, PxVehicleDriveNW());
//Patch up the pointers.
PxU8* ptr = reinterpret_cast<PxU8*>(veh) + sizeof(PxVehicleDriveNW);
ptr=PxVehicleDrive::patchupPointers(numWheels, veh, ptr);
//Initialise
veh->init(numWheels);
//Set the vehicle type.
veh->mType = PxVehicleTypes::eDRIVENW;
return veh;
}
void PxVehicleDriveNW::free()
{
PxVehicleDrive::free();
}
void PxVehicleDriveNW::setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
const PxU32 numWheels)
{
PX_CHECK_AND_RETURN(driveData.isValid(), "PxVehicleDriveNW::setup - invalid driveData");
//Set up the wheels.
PxVehicleDrive::setup(physics,vehActor,wheelsData,numWheels,0);
//Start setting up the drive.
PX_CHECK_MSG(driveData.isValid(), "PxVehicleNWDrive - invalid driveData");
//Copy the simulation data.
mDriveSimData = driveData;
}
PxVehicleDriveNW* PxVehicleDriveNW::create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
const PxU32 numWheels)
{
PxVehicleDriveNW* vehNW=PxVehicleDriveNW::allocate(numWheels);
vehNW->setup(physics,vehActor,wheelsData,driveData,numWheels);
return vehNW;
}
void PxVehicleDriveNW::setToRestState()
{
//Set core to rest state.
PxVehicleDrive::setToRestState();
}
} //namespace physx
| 4,743 |
C++
| 31.49315 | 115 | 0.767236 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleUpdate.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxQuat.h"
#include "foundation/PxBitMap.h"
#include "common/PxProfileZone.h"
#include "common/PxTolerancesScale.h"
#include "vehicle/PxVehicleUpdate.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveNW.h"
#include "vehicle/PxVehicleDriveTank.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleUtil.h"
#include "vehicle/PxVehicleUtilTelemetry.h"
#include "extensions/PxRigidBodyExt.h"
#include "extensions/PxSceneQueryExt.h"
#include "PxShape.h"
#include "PxRigidDynamic.h"
#include "PxMaterial.h"
#include "PxContactModifyCallback.h"
#include "PxScene.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleLinearMath.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxFPU.h"
#include "CmUtils.h"
using namespace physx;
using namespace Cm;
//TODO: lsd - handle case where wheels are spinning in different directions.
//TODO: ackermann - use faster approximate functions for PxTan/PxATan because the results don't need to be too accurate here.
//TODO: tire lat slip - do we really use PxAbs(vz) as denominator, that's not in the paper?
//TODO: toe vs jounce table.
//TODO: pneumatic trail.
//TODO: we probably need to have a graphics jounce and a physics jounce and
//TODO: expose sticky friction values in api.
//TODO: blend the graphics jounce towards the physics jounce to avoid graphical pops at kerbs etc.
//TODO: better graph of friction vs slip. Need to account for negative slip and positive slip differences.
namespace physx
{
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetBasisVectors
////////////////////////////////////////////////////////////////////////////
static PxVehicleContext gVehicleContextDefault;
void PxVehicleSetBasisVectors(const PxVec3& up, const PxVec3& forward)
{
gVehicleContextDefault.upAxis = up;
gVehicleContextDefault.forwardAxis = forward;
gVehicleContextDefault.computeSideAxis();
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetUpdateMode
////////////////////////////////////////////////////////////////////////////
void PxVehicleSetUpdateMode(PxVehicleUpdateMode::Enum vehicleUpdateMode)
{
gVehicleContextDefault.updateMode = vehicleUpdateMode;
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetSweepHitRejectionAngles
////////////////////////////////////////////////////////////////////////////
void PxVehicleSetSweepHitRejectionAngles(const PxF32 pointRejectAngle, const PxF32 normalRejectAngle)
{
PX_CHECK_AND_RETURN(pointRejectAngle > 0.0f && pointRejectAngle < PxPi, "PxVehicleSetSweepHitRejectionAngles - pointRejectAngle must be in range (0, Pi)");
PX_CHECK_AND_RETURN(normalRejectAngle > 0.0f && normalRejectAngle < PxPi, "PxVehicleSetSweepHitRejectionAngles - normalRejectAngle must be in range (0, Pi)");
gVehicleContextDefault.pointRejectAngleThresholdCosine = PxCos(pointRejectAngle);
gVehicleContextDefault.normalRejectAngleThresholdCosine = PxCos(normalRejectAngle);
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetSweepHitRejectionAngles
////////////////////////////////////////////////////////////////////////////
void PxVehicleSetMaxHitActorAcceleration(const PxF32 maxHitActorAcceleration)
{
PX_CHECK_AND_RETURN(maxHitActorAcceleration >= 0.0f, "PxVehicleSetMaxHitActorAcceleration - maxHitActorAcceleration must be greater than or equal to zero");
gVehicleContextDefault.maxHitActorAcceleration = maxHitActorAcceleration;
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleGetDefaultContext
////////////////////////////////////////////////////////////////////////////
const PxVehicleContext& PxVehicleGetDefaultContext()
{
return gVehicleContextDefault;
}
////////////////////////////////////////////////////////////////////////////
//Set all defaults from PxVehicleInitSDK
////////////////////////////////////////////////////////////////////////////
void setVehicleDefaults()
{
gVehicleContextDefault.setToDefault();
}
////////////////////////////////////////////////////////////////////////////
//Called from PxVehicleInitSDK/PxCloseVehicleSDK
////////////////////////////////////////////////////////////////////////////
//***********************
PxF32 gThresholdForwardSpeedForWheelAngleIntegration=0;
PxF32 gRecipThresholdForwardSpeedForWheelAngleIntegration=0;
PxF32 gMinLatSpeedForTireModel=0;
PxF32 gStickyTireFrictionThresholdSpeed=0;
PxF32 gToleranceScaleLength=0;
PxF32 gMinimumSlipThreshold=0;
void setVehicleToleranceScale(const PxTolerancesScale& ts)
{
gThresholdForwardSpeedForWheelAngleIntegration=5.0f*ts.length;
gRecipThresholdForwardSpeedForWheelAngleIntegration=1.0f/gThresholdForwardSpeedForWheelAngleIntegration;
gMinLatSpeedForTireModel=1.0f*ts.length;
gStickyTireFrictionThresholdSpeed=0.2f*ts.length;
gToleranceScaleLength=ts.length;
gMinimumSlipThreshold = 1e-5f;
}
void resetVehicleToleranceScale()
{
gThresholdForwardSpeedForWheelAngleIntegration=0;
gRecipThresholdForwardSpeedForWheelAngleIntegration=0;
gMinLatSpeedForTireModel=0;
gStickyTireFrictionThresholdSpeed=0;
gToleranceScaleLength=0;
gMinimumSlipThreshold=0;
}
//***********************
const PxSerializationRegistry* gSerializationRegistry=NULL;
void setSerializationRegistryPtr(const PxSerializationRegistry* sr)
{
gSerializationRegistry = sr;
}
const PxSerializationRegistry* resetSerializationRegistryPtr()
{
const PxSerializationRegistry* tmp = gSerializationRegistry;
gSerializationRegistry = NULL;
return tmp;
}
////////////////////////////////////////////////////////////////////////////
//Global values used to trigger and control sticky tire friction constraints.
////////////////////////////////////////////////////////////////////////////
const PxF32 gStickyTireFrictionForwardDamping=0.01f;
const PxF32 gStickyTireFrictionSideDamping=0.1f;
const PxF32 gLowForwardSpeedThresholdTime=1.0f;
const PxF32 gLowSideSpeedThresholdTime=1.0f;
////////////////////////////////////////////////////////////////////////////
//Global values used to control max iteration count if estimate mode is chosen
////////////////////////////////////////////////////////////////////////////
const PxF32 gSolverTolerance = 1e-10f;
////////////////////////////////////////////////////////////////////////////
//Compute the sprung masses that satisfy the centre of mass and sprung mass coords.
////////////////////////////////////////////////////////////////////////////
#define DETERMINANT_THRESHOLD (1e-6f)
void computeSprungMasses(const PxU32 numSprungMasses, const PxVec3* sprungMassCoordinates, const PxVec3& centreOfMass, const PxReal totalMass, const PxU32 gravityDirection, PxReal* sprungMasses)
{
#if PX_CHECKED
PX_CHECK_AND_RETURN(numSprungMasses > 0, "PxVehicleComputeSprungMasses: numSprungMasses must be greater than zero");
PX_CHECK_AND_RETURN(numSprungMasses <= PX_MAX_NB_WHEELS, "PxVehicleComputeSprungMasses: numSprungMasses must be less than or equal to 20");
for(PxU32 i=0;i<numSprungMasses;i++)
{
PX_CHECK_AND_RETURN(sprungMassCoordinates[i].isFinite(), "PxVehicleComputeSprungMasses: sprungMassCoordinates must all be valid coordinates");
}
PX_CHECK_AND_RETURN(totalMass > 0.0f, "PxVehicleComputeSprungMasses: totalMass must be greater than zero");
PX_CHECK_AND_RETURN(gravityDirection<=2, "PxVehicleComputeSprungMasses: gravityDirection must be 0 or 1 or 2");
PX_CHECK_AND_RETURN(sprungMasses, "PxVehicleComputeSprungMasses: sprungMasses must be a non-null pointer");
#endif
if(1==numSprungMasses)
{
sprungMasses[0]=totalMass;
}
else if(2==numSprungMasses)
{
PxVec3 v=sprungMassCoordinates[0];
v[gravityDirection]=0;
PxVec3 w=sprungMassCoordinates[1]-sprungMassCoordinates[0];
w[gravityDirection]=0;
w.normalize();
PxVec3 cm=centreOfMass;
cm[gravityDirection]=0;
PxF32 t=w.dot(cm-v);
PxVec3 p=v+w*t;
PxVec3 x0=sprungMassCoordinates[0];
x0[gravityDirection]=0;
PxVec3 x1=sprungMassCoordinates[1];
x1[gravityDirection]=0;
const PxF32 r0=(x0-p).dot(w);
const PxF32 r1=(x1-p).dot(w);
PX_CHECK_AND_RETURN(PxAbs(r0-r1) > DETERMINANT_THRESHOLD, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
const PxF32 m0=totalMass*r1/(r1-r0);
const PxF32 m1=totalMass-m0;
sprungMasses[0]=m0;
sprungMasses[1]=m1;
}
else if(3==numSprungMasses)
{
const PxU32 d0=(gravityDirection+1)%3;
const PxU32 d1=(gravityDirection+2)%3;
MatrixNN A(3);
VectorN b(3);
A.set(0,0,sprungMassCoordinates[0][d0]);
A.set(0,1,sprungMassCoordinates[1][d0]);
A.set(0,2,sprungMassCoordinates[2][d0]);
A.set(1,0,sprungMassCoordinates[0][d1]);
A.set(1,1,sprungMassCoordinates[1][d1]);
A.set(1,2,sprungMassCoordinates[2][d1]);
A.set(2,0,1.f);
A.set(2,1,1.f);
A.set(2,2,1.f);
b[0]=totalMass*centreOfMass[d0];
b[1]=totalMass*centreOfMass[d1];
b[2]=totalMass;
VectorN result(3);
MatrixNNLUSolver solver;
solver.decomposeLU(A);
PX_CHECK_AND_RETURN(PxAbs(solver.getDet()) > DETERMINANT_THRESHOLD, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
solver.solve(b,result);
sprungMasses[0]=result[0];
sprungMasses[1]=result[1];
sprungMasses[2]=result[2];
}
else if(numSprungMasses>=4)
{
const PxU32 d0=(gravityDirection+1)%3;
const PxU32 d1=(gravityDirection+2)%3;
const PxF32 mbar = totalMass/(numSprungMasses*1.0f);
//See http://en.wikipedia.org/wiki/Lagrange_multiplier
//particularly the section on multiple constraints.
//3 Constraint equations.
//g0 = sum_ xi*mi=xcm
//g1 = sum_ zi*mi=zcm
//g2 = sum_ mi = totalMass
//Minimisation function to achieve solution with minimum mass variance.
//f = sum_ (mi - mave)^2
//Lagrange terms (N equations, N+3 unknowns)
//2*mi - xi*lambda0 - zi*lambda1 - 1*lambda2 = 2*mave
MatrixNN A(numSprungMasses+3);
VectorN b(numSprungMasses+3);
//g0, g1, g2
for(PxU32 i=0;i<numSprungMasses;i++)
{
A.set(0,i,sprungMassCoordinates[i][d0]); //g0
A.set(1,i,sprungMassCoordinates[i][d1]); //g1
A.set(2,i,1.0f); //g2
}
for(PxU32 i=numSprungMasses;i<numSprungMasses+3;i++)
{
A.set(0,i,0); //g0 independent of lambda0,lambda1,lambda2
A.set(1,i,0); //g1 independent of lambda0,lambda1,lambda2
A.set(2,i,0); //g2 independent of lambda0,lambda1,lambda2
}
b[0] = totalMass*(centreOfMass[d0]); //g0
b[1] = totalMass*(centreOfMass[d1]); //g1
b[2] = totalMass; //g2
//Lagrange terms.
for(PxU32 i=0;i<numSprungMasses;i++)
{
//Off-diagonal terms from the derivative of f
for(PxU32 j=0;j<numSprungMasses;j++)
{
A.set(i+3,j,0);
}
//Diagonal term from the derivative of f
A.set(i+3,i,2.f);
//Derivative of g
A.set(i+3,numSprungMasses+0,sprungMassCoordinates[i][d0]);
A.set(i+3,numSprungMasses+1,sprungMassCoordinates[i][d1]);
A.set(i+3,numSprungMasses+2,1.0f);
//rhs.
b[i+3] = 2*mbar;
}
//Solve Ax=b
VectorN result(numSprungMasses+3);
MatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b,result);
PX_CHECK_AND_RETURN(PxAbs(solver.getDet()) > DETERMINANT_THRESHOLD, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
for(PxU32 i=0;i<numSprungMasses;i++)
{
sprungMasses[i]=result[i];
}
}
#if PX_CHECKED
PxVec3 cm(0,0,0);
PxF32 m = 0;
for(PxU32 i=0;i<numSprungMasses;i++)
{
PX_CHECK_AND_RETURN(sprungMasses[i] >= 0, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
cm += sprungMassCoordinates[i]*sprungMasses[i];
m += sprungMasses[i];
}
cm *= (1.0f/totalMass);
PX_CHECK_AND_RETURN((PxAbs(totalMass - m)/totalMass) < 1e-3f, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
PxVec3 diff = cm - centreOfMass;
diff[gravityDirection]=0;
const PxF32 diffMag = diff.magnitude();
PX_CHECK_AND_RETURN(numSprungMasses <=2 || diffMag < 1e-3f, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
#endif
}
////////////////////////////////////////////////////////////////////////////
//Work out if all wheels are in the air.
////////////////////////////////////////////////////////////////////////////
bool PxVehicleIsInAir(const PxVehicleWheelQueryResult& vehWheelQueryResults)
{
if(!vehWheelQueryResults.wheelQueryResults)
{
return true;
}
for(PxU32 i=0;i<vehWheelQueryResults.nbWheelQueryResults;i++)
{
if(!vehWheelQueryResults.wheelQueryResults[i].isInAir)
{
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////
//Reject wheel contact points
////////////////////////////////////////////////////////////////////////////
PxU32 PxVehicleModifyWheelContacts
(const PxVehicleWheels& vehicle, const PxU32 wheelId,
const PxF32 wheelTangentVelocityMultiplier, const PxReal maxImpulse,
PxContactModifyPair& contactModifyPair, const PxVehicleContext& context)
{
const bool rejectPoints = true;
const bool rejectNormals = true;
PxU32 numIgnoredContacts = 0;
const PxRigidDynamic* vehActor = vehicle.getRigidDynamicActor();
//Is the vehicle represented by actor[0] or actor[1]?
PxTransform vehActorTransform;
PxTransform vehWheelTransform;
PxF32 normalMultiplier;
PxF32 targetVelMultiplier;
bool isOtherDynamic = false;
if(contactModifyPair.actor[0] == vehActor)
{
normalMultiplier = 1.0f;
targetVelMultiplier = 1.0f;
vehActorTransform = contactModifyPair.actor[0]->getGlobalPose();
vehWheelTransform = contactModifyPair.transform[0];
isOtherDynamic = contactModifyPair.actor[1] && contactModifyPair.actor[1]->is<PxRigidDynamic>();
}
else
{
PX_ASSERT(contactModifyPair.actor[1] == vehActor);
normalMultiplier = -1.0f;
targetVelMultiplier = -1.0f;
vehActorTransform = contactModifyPair.actor[1]->getGlobalPose();
vehWheelTransform = contactModifyPair.transform[1];
isOtherDynamic = contactModifyPair.actor[0] && contactModifyPair.actor[0]->is<PxRigidDynamic>();
}
//Compute the "right" vector of the transform.
const PxVec3 right = vehWheelTransform.q.rotate(context.sideAxis);
//The wheel transform includes rotation about the rolling axis.
//We want to compute the wheel transform at zero wheel rotation angle.
PxTransform correctedWheelShapeTransform;
{
const PxF32 wheelRotationAngle = vehicle.mWheelsDynData.getWheelRotationAngle(wheelId);
const PxQuat wheelRotateQuat(-wheelRotationAngle, right);
correctedWheelShapeTransform = PxTransform(vehWheelTransform.p, wheelRotateQuat*vehWheelTransform.q);
}
//Construct a plane for the wheel
const PxPlane wheelPlane(correctedWheelShapeTransform.p, right);
//Compute the suspension travel vector.
const PxVec3 suspTravelDir = correctedWheelShapeTransform.rotate(vehicle.mWheelsSimData.getSuspTravelDirection(wheelId));
//Get the wheel centre.
const PxVec3 wheelCentre = correctedWheelShapeTransform.p;
//Test each point.
PxContactSet& contactSet = contactModifyPair.contacts;
const PxU32 numContacts = contactSet.size();
for(PxU32 i = 0; i < numContacts; i++)
{
//Get the next contact point to analyse.
const PxVec3& contactPoint = contactSet.getPoint(i);
bool ignorePoint = false;
//Project the contact point on to the wheel plane.
const PxF32 distanceToPlane = wheelPlane.n.dot(contactPoint) + wheelPlane.d;
const PxVec3 contactPointOnPlane = contactPoint - wheelPlane.n*distanceToPlane;
//Construct a vector from the wheel centre to the contact point on the plane.
PxVec3 dir = contactPointOnPlane - wheelCentre;
const PxF32 effectiveRadius = dir.normalize();
if(!ignorePoint && rejectPoints)
{
//Work out the dot product of the suspension direction and the direction from wheel centre to contact point.
const PxF32 dotProduct = dir.dot(suspTravelDir);
if (dotProduct > context.pointRejectAngleThresholdCosine)
{
ignorePoint = true;
numIgnoredContacts++;
contactSet.ignore(i);
}
}
//Ignore contact normals that are near the raycast direction.
if(!ignorePoint && rejectNormals)
{
const PxVec3& contactNormal = contactSet.getNormal(i) * normalMultiplier;
const PxF32 dotProduct = -(contactNormal.dot(suspTravelDir));
if(dotProduct > context.normalRejectAngleThresholdCosine)
{
ignorePoint = true;
numIgnoredContacts++;
contactSet.ignore(i);
}
}
//For points that remain we want to modify the contact speed to account for the spinning wheel.
//We also want the applied impulse to go through the suspension geometry so we set the contact point to be the suspension force
//application point.
if(!ignorePoint)
{
//Compute the tangent velocity.
//Retain only the component that lies perpendicular to the contact normal.
const PxF32 wheelRotationSpeed = vehicle.mWheelsDynData.getWheelRotationSpeed(wheelId);
const PxVec3 tangentVelocityDir = right.cross(dir);
PxVec3 tangentVelocity = tangentVelocityDir*(effectiveRadius*wheelRotationSpeed);
tangentVelocity -= contactSet.getNormal(i)*(tangentVelocity.dot(contactSet.getNormal(i)));
//We want to add velocity in the opposite direction to the tangent velocity.
const PxVec3 targetTangentVelocity = -wheelTangentVelocityMultiplier*tangentVelocity;
//Relative velocity is computed from actor0 - actor1
//If vehicle is actor 0 we want to add to the target velocity: targetVelocity = [(vel0 + targetTangentVelocity) - vel1] = vel0 - vel1 + targetTangentVelocity
//If vehicle is actor 1 we want to subtract from the target velocity: targetVelocity = [vel0 - (vel1 + targetTangentVelocity)] = vel0 - vel1 - targetTangentVelocity
const PxVec3 targetVelocity = targetTangentVelocity*targetVelMultiplier;
//Add the target velocity.
contactSet.setTargetVelocity(i, targetVelocity);
//Set the max impulse that can be applied.
//Only apply this if the wheel has hit a dynamic.
if (isOtherDynamic)
{
contactSet.setMaxImpulse(i, maxImpulse);
}
//Set the contact point to be the suspension force application point because all forces applied through the wheel go through the suspension geometry.
const PxVec3 suspAppPoint = vehActorTransform.transform(vehActor->getCMassLocalPose().p + vehicle.mWheelsSimData.getSuspForceAppPointOffset(wheelId));
contactSet.setPoint(i, suspAppPoint);
}
}
return numIgnoredContacts;
}
////////////////////////////////////////////////////////////////////////////
//Enable a 4W vehicle in either tadpole or delta configuration.
////////////////////////////////////////////////////////////////////////////
void computeDirection(const PxVec3& up, const PxVec3& right,
PxU32& rightDirection, PxU32& upDirection)
{
//Work out the up and right vectors.
rightDirection = 0xffffffff;
if(right == PxVec3(1.f,0,0) || right == PxVec3(-1.f,0,0))
{
rightDirection = 0;
}
else if(right == PxVec3(0,1.f,0) || right == PxVec3(0,-1.f,0))
{
rightDirection = 1;
}
else if(right == PxVec3(0,0,1.f) || right == PxVec3(0,0,-1.f))
{
rightDirection = 2;
}
upDirection = 0xffffffff;
if(up == PxVec3(1.f,0,0) || up == PxVec3(-1.f,0,0))
{
upDirection = 0;
}
else if(up == PxVec3(0,1.f,0) || up == PxVec3(0,-1.f,0))
{
upDirection = 1;
}
else if(up == PxVec3(0,0,1.f) || up == PxVec3(0,0,-1.f))
{
upDirection = 2;
}
}
void enable3WMode(const PxU32 rightDirection, const PxU32 upDirection, const bool removeFrontWheel, PxVehicleWheelsSimData& wheelsSimData, PxVehicleWheelsDynData& wheelsDynData, PxVehicleDriveSimData4W& driveSimData)
{
PX_ASSERT(rightDirection < 3);
PX_ASSERT(upDirection < 3);
const PxU32 wheelToRemove = removeFrontWheel ? PxVehicleDrive4WWheelOrder::eFRONT_LEFT : PxVehicleDrive4WWheelOrder::eREAR_LEFT;
const PxU32 wheelToModify = removeFrontWheel ? PxVehicleDrive4WWheelOrder::eFRONT_RIGHT : PxVehicleDrive4WWheelOrder::eREAR_RIGHT;
//Disable the wheel.
wheelsSimData.disableWheel(wheelToRemove);
//Make sure the wheel's corresponding PxShape does not get posed again.
wheelsSimData.setWheelShapeMapping(wheelToRemove, -1);
//Set the angular speed to 0.0f
wheelsDynData.setWheelRotationSpeed(wheelToRemove, 0.0f);
//Disable Ackermann steering.
//If the front wheel is to be removed and the front wheels can steer then disable Ackermann correction.
//If the rear wheel is to be removed and the rear wheels can steer then disable Ackermann correction.
if(removeFrontWheel &&
(wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT).mMaxSteer!=0.0f ||
wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_LEFT).mMaxSteer!=0.0f))
{
PxVehicleAckermannGeometryData ackermannData=driveSimData.getAckermannGeometryData();
ackermannData.mAccuracy=0.0f;
driveSimData.setAckermannGeometryData(ackermannData);
}
if(!removeFrontWheel &&
(wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_RIGHT).mMaxSteer!=0.0f ||
wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_LEFT).mMaxSteer!=0.0f))
{
PxVehicleAckermannGeometryData ackermannData=driveSimData.getAckermannGeometryData();
ackermannData.mAccuracy=0.0f;
driveSimData.setAckermannGeometryData(ackermannData);
}
//We need to set up the differential to make sure that no drive torque is delivered to the disabled wheel.
PxVehicleDifferential4WData diffData =driveSimData.getDiffData();
if(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT==wheelToModify)
{
diffData.mFrontBias=PX_MAX_F32;
diffData.mFrontLeftRightSplit=0.0f;
}
else
{
diffData.mRearBias=PX_MAX_F32;
diffData.mRearLeftRightSplit=0.0f;
}
driveSimData.setDiffData(diffData);
//Now reposition the disabled wheel so that it lies at the center of its axle.
//The following assumes that the front and rear axles lie along the x-axis.
{
PxVec3 wheelCentreOffset=wheelsSimData.getWheelCentreOffset(wheelToModify);
wheelCentreOffset[rightDirection]=0.0f;
wheelsSimData.setWheelCentreOffset(wheelToModify,wheelCentreOffset);
PxVec3 suspOffset=wheelsSimData.getSuspForceAppPointOffset(wheelToModify);
suspOffset[rightDirection]=0;
wheelsSimData.setSuspForceAppPointOffset(wheelToModify,suspOffset);
PxVec3 tireOffset=wheelsSimData.getTireForceAppPointOffset(wheelToModify);
tireOffset[rightDirection]=0;
wheelsSimData.setTireForceAppPointOffset(wheelToModify,tireOffset);
}
//Redistribute the mass supported by 4 wheels among the 3 remaining enabled wheels.
//Compute the total mass supported by all 4 wheels.
const PxF32 totalMass =
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eFRONT_LEFT).mSprungMass +
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT).mSprungMass +
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eREAR_LEFT).mSprungMass +
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eREAR_RIGHT).mSprungMass;
//Get the wheel cm offsets of the 3 enabled wheels.
PxVec3 cmOffsets[3]=
{
wheelsSimData.getWheelCentreOffset((wheelToRemove+1) % 4),
wheelsSimData.getWheelCentreOffset((wheelToRemove+2) % 4),
wheelsSimData.getWheelCentreOffset((wheelToRemove+3) % 4),
};
//Re-compute the sprung masses.
PxF32 sprungMasses[3];
computeSprungMasses(3, cmOffsets, PxVec3(0,0,0), totalMass, upDirection, sprungMasses);
//Now set the new sprung masses.
//Do this in a way that preserves the natural frequency and damping ratio of the spring.
for(PxU32 i=0;i<3;i++)
{
PxVehicleSuspensionData suspData = wheelsSimData.getSuspensionData((wheelToRemove+1+i) % 4);
const PxF32 oldSprungMass = suspData.mSprungMass;
const PxF32 oldStrength = suspData.mSpringStrength;
const PxF32 oldDampingRate = suspData.mSpringDamperRate;
const PxF32 oldNaturalFrequency = PxSqrt(oldStrength/oldSprungMass);
const PxF32 newSprungMass = sprungMasses[i];
const PxF32 newStrength = oldNaturalFrequency*oldNaturalFrequency*newSprungMass;
const PxF32 newDampingRate = oldDampingRate;
suspData.mSprungMass = newSprungMass;
suspData.mSpringStrength = newStrength;
suspData.mSpringDamperRate = newDampingRate;
wheelsSimData.setSuspensionData((wheelToRemove+1+i) % 4, suspData);
}
}
////////////////////////////////////////////////////////////////////////////
//Maximum number of allowed blocks of 4 wheels
////////////////////////////////////////////////////////////////////////////
#define PX_MAX_NB_SUSPWHEELTIRE4 (PX_MAX_NB_WHEELS >>2)
////////////////////////////////////////////////////////////////////////////
//Pointers to telemetry data.
//Set to NULL if no telemetry data is to be recorded during a vehicle update.
//Functions used throughout vehicle update to record specific vehicle data.
////////////////////////////////////////////////////////////////////////////
#if PX_DEBUG_VEHICLE_ON
struct VehicleTelemetryDataContext
{
PxF32 wheelGraphData[PX_MAX_NB_WHEELS][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS];
PxF32 engineGraphData[PxVehicleDriveGraphChannel::eMAX_NB_DRIVE_CHANNELS];
PxVec3 suspForceAppPoints[PX_MAX_NB_WHEELS];
PxVec3 tireForceAppPoints[PX_MAX_NB_WHEELS];
};
PX_FORCE_INLINE void updateGraphDataInternalWheelDynamics(const PxU32 startIndex, const PxF32* carWheelSpeeds,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
//Grab the internal rotation speeds for graphing before we update them.
for(PxU32 i=0;i<4;i++)
{
PX_ASSERT((startIndex+i) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+i]);
carWheelGraphData[startIndex+i][PxVehicleWheelGraphChannel::eWHEEL_OMEGA]=carWheelSpeeds[i];
}
}
PX_FORCE_INLINE void updateGraphDataInternalEngineDynamics(const PxF32 carEngineSpeed, PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eENGINE_REVS]=carEngineSpeed;
}
PX_FORCE_INLINE void updateGraphDataControlInputs(const PxF32 accel, const PxF32 brake, const PxF32 handbrake, const PxF32 steerLeft, const PxF32 steerRight,
PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eACCEL_CONTROL]=accel;
carEngineGraphData[PxVehicleDriveGraphChannel::eBRAKE_CONTROL]=brake;
carEngineGraphData[PxVehicleDriveGraphChannel::eHANDBRAKE_CONTROL]=handbrake;
carEngineGraphData[PxVehicleDriveGraphChannel::eSTEER_LEFT_CONTROL]=steerLeft;
carEngineGraphData[PxVehicleDriveGraphChannel::eSTEER_RIGHT_CONTROL]=steerRight;
}
PX_FORCE_INLINE void updateGraphDataGearRatio(const PxF32 G, PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eGEAR_RATIO]=G;
}
PX_FORCE_INLINE void updateGraphDataEngineDriveTorque(const PxF32 engineDriveTorque, PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eENGINE_DRIVE_TORQUE]=engineDriveTorque;
}
PX_FORCE_INLINE void updateGraphDataClutchSlip(const PxF32* wheelSpeeds, const PxF32* aveWheelSpeedContributions, const PxF32 engineSpeed, const PxF32 G,
PxF32* carEngineGraphData)
{
PxF32 averageWheelSpeed=0;
for(PxU32 i=0;i<4;i++)
{
averageWheelSpeed+=wheelSpeeds[i]*aveWheelSpeedContributions[i];
}
averageWheelSpeed*=G;
carEngineGraphData[PxVehicleDriveGraphChannel::eCLUTCH_SLIP]=averageWheelSpeed-engineSpeed;
}
PX_FORCE_INLINE void updateGraphDataClutchSlipNW(const PxU32 numWheels4, const PxVehicleWheels4DynData* wheelsDynData, const PxF32* aveWheelSpeedContributions, const PxF32 engineSpeed, const PxF32 G,
PxF32* carEngineGraphData)
{
PxF32 averageWheelSpeed=0;
for(PxU32 i=0;i<numWheels4;i++)
{
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[0]*aveWheelSpeedContributions[4*i+0];
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[1]*aveWheelSpeedContributions[4*i+1];
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[2]*aveWheelSpeedContributions[4*i+2];
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[3]*aveWheelSpeedContributions[4*i+3];
}
averageWheelSpeed*=G;
carEngineGraphData[PxVehicleDriveGraphChannel::eCLUTCH_SLIP]=averageWheelSpeed-engineSpeed;
}
PX_FORCE_INLINE void zeroGraphDataWheels(const PxU32 startIndex, const PxU32 type,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
for(PxU32 i=0;i<4;i++)
{
PX_ASSERT((startIndex+i) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+i]);
carWheelGraphData[startIndex+i][type]=0.0f;
}
}
PX_FORCE_INLINE void updateGraphDataSuspJounce(const PxU32 startIndex, const PxU32 wheel, const PxF32 jounce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eJOUNCE]=jounce;
}
PX_FORCE_INLINE void updateGraphDataSuspForce(const PxU32 startIndex, const PxU32 wheel, const PxF32 springForce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eSUSPFORCE]=springForce;
}
PX_FORCE_INLINE void updateGraphDataTireLoad(const PxU32 startIndex, const PxU32 wheel, const PxF32 filteredTireLoad,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRELOAD]=filteredTireLoad;
}
PX_FORCE_INLINE void updateGraphDataNormTireLoad(const PxU32 startIndex, const PxU32 wheel, const PxF32 filteredNormalisedTireLoad,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORMALIZED_TIRELOAD]=filteredNormalisedTireLoad;
}
PX_FORCE_INLINE void updateGraphDataNormLongTireForce(const PxU32 startIndex, const PxU32 wheel, const PxF32 normForce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORM_TIRE_LONG_FORCE]=normForce;
}
PX_FORCE_INLINE void updateGraphDataNormLatTireForce(const PxU32 startIndex, const PxU32 wheel, const PxF32 normForce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORM_TIRE_LAT_FORCE]=normForce;
}
PX_FORCE_INLINE void updateGraphDataLatTireSlip(const PxU32 startIndex, const PxU32 wheel, const PxF32 latSlip,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRE_LAT_SLIP]=latSlip;
}
PX_FORCE_INLINE void updateGraphDataLongTireSlip(const PxU32 startIndex, const PxU32 wheel, const PxF32 longSlip,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRE_LONG_SLIP]=longSlip;
}
PX_FORCE_INLINE void updateGraphDataTireFriction(const PxU32 startIndex, const PxU32 wheel, const PxF32 friction,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRE_FRICTION]=friction;
}
PX_FORCE_INLINE void updateGraphDataNormTireAligningMoment(const PxU32 startIndex, const PxU32 wheel, const PxF32 normAlignMoment,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORM_TIRE_ALIGNING_MOMENT]=normAlignMoment;
}
#else
struct VehicleTelemetryDataContext;
#endif //DEBUG_VEHICLE_ON
////////////////////////////////////////////////////////////////////////////
//Profile data structures.
////////////////////////////////////////////////////////////////////////////
#define PX_VEHICLE_PROFILE 0
enum
{
TIMER_ADMIN=0,
TIMER_GRAPHS,
TIMER_COMPONENTS_UPDATE,
TIMER_WHEELS,
TIMER_INTERNAL_DYNAMICS_SOLVER,
TIMER_POSTUPDATE1,
TIMER_POSTUPDATE2,
TIMER_POSTUPDATE3,
TIMER_ALL,
TIMER_RAYCASTS,
TIMER_SWEEPS,
MAX_NB_TIMERS
};
#if PX_VEHICLE_PROFILE
bool gTimerStates[MAX_NB_TIMERS]={false,false,false,false,false,false,false,false,false,false,false};
PxU64 gTimers[MAX_NB_TIMERS]={0,0,0,0,0,0,0,0,0,0,0};
PxU64 gStartTimers[MAX_NB_TIMERS]={0,0,0,0,0,0,0,0,0,0,0};
PxU64 gEndTimers[MAX_NB_TIMERS]={0,0,0,0,0,0,0,0,0,0,0};
PxU32 gTimerCount=0;
physx::PxTime gTimer;
PX_FORCE_INLINE void START_TIMER(const PxU32 id)
{
PX_ASSERT(!gTimerStates[id]);
gStartTimers[id]=gTimer.getCurrentCounterValue();
gTimerStates[id]=true;
}
PX_FORCE_INLINE void END_TIMER(const PxU32 id)
{
PX_ASSERT(gTimerStates[id]);
gTimerStates[id]=false;
gEndTimers[id]=gTimer.getCurrentCounterValue();
gTimers[id]+=(gEndTimers[id]-gStartTimers[id]);
}
PX_FORCE_INLINE PxF32 getTimerFraction(const PxU32 id)
{
return gTimers[id]/(1.0f*gTimers[TIMER_ALL]);
}
PX_FORCE_INLINE PxReal getTimerInMilliseconds(const PxU32 id)
{
const PxU64 time=gTimers[id];
const PxU64 timein10sOfNs = gTimer.getBootCounterFrequency().toTensOfNanos(time);
return (timein10sOfNs/(gTimerCount*100*1.0f));
}
#else
PX_FORCE_INLINE void START_TIMER(const PxU32)
{
}
PX_FORCE_INLINE void END_TIMER(const PxU32)
{
}
#endif
////////////////////////////////////////////////////////////////////////////
//Functions used to integrate rigid body transform and velocity.
//The sub-step system divides a specified timestep into N equal sub-steps
//and integrates the velocity and transform each sub-step.
//After all sub-steps are complete the velocity required to move the
//associated PxRigidBody from the start transform to the transform at the end
//of the timestep is computed and set. If the update mode is chosen to be
//acceleration then the acceleration is computed/set that will move the rigid body
//from the start to end transform. The PxRigidBody never actually has its transform
//updated and only has its velocity or acceleration set at the very end of the timestep.
////////////////////////////////////////////////////////////////////////////
PX_INLINE void integrateBody
(const PxF32 inverseMass, const PxVec3& invInertia, const PxVec3& force, const PxVec3& torque, const PxF32 dt,
PxVec3& v, PxVec3& w, PxTransform& t)
{
//Integrate linear velocity.
v+=force*(inverseMass*dt);
//Integrate angular velocity.
PxMat33 inverseInertia;
transformInertiaTensor(invInertia, PxMat33(t.q), inverseInertia);
w+=inverseInertia*(torque*dt);
//Integrate position.
t.p+=v*dt;
//Integrate quaternion.
PxQuat wq(w.x,w.y,w.z,0.0f);
PxQuat q=t.q;
PxQuat qdot=wq*q*(dt*0.5f);
q+=qdot;
q.normalize();
t.q=q;
}
/*
PX_INLINE void computeVelocity(const PxTransform& t1, const PxTransform& t2, const PxF32 invDT, PxVec3& v, PxVec3& w)
{
//Linear velocity.
v = (t2.p - t1.p)*invDT;
//Angular velocity.
PxQuat qw = (t2.q - t1.q)*t1.q.getConjugate()*(2.0f*invDT);
w.x=qw.x;
w.y=qw.y;
w.z=qw.z;
}
*/
/////////////////////////////////////////////////////////////////////////////////////////
//Use fsel to compute the sign of a float: +1 for positive values, -1 for negative values
/////////////////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 computeSign(const PxF32 f)
{
return physx::intrinsics::fsel(f, physx::intrinsics::fsel(-f, 0.0f, 1.0f), -1.0f);
}
/////////////////////////////////////////////////////////////////////////////////////////
//Get the accel/brake/handbrake as floats in range (0,1) from the inputs stored in the vehicle.
//Equivalent for tank involving thrustleft/thrustright and brakeleft/brakeright.
/////////////////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void getVehicle4WControlValues(const PxVehicleDriveDynData& driveDynData, PxF32& accel, PxF32& brake, PxF32& handbrake, PxF32& steerLeft, PxF32& steerRight)
{
accel=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];
brake=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE];
handbrake=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE];
steerLeft=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT];
steerRight=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT];
}
PX_FORCE_INLINE void getVehicleNWControlValues(const PxVehicleDriveDynData& driveDynData, PxF32& accel, PxF32& brake, PxF32& handbrake, PxF32& steerLeft, PxF32& steerRight)
{
accel=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL];
brake=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_BRAKE];
handbrake=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_HANDBRAKE];
steerLeft=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT];
steerRight=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT];
}
PX_FORCE_INLINE void getTankControlValues(const PxVehicleDriveDynData& driveDynData, PxF32& accel, PxF32& brakeLeft, PxF32& brakeRight, PxF32& thrustLeft, PxF32& thrustRight)
{
accel=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL];
brakeLeft=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT];
brakeRight=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT];
thrustLeft=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];
thrustRight=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];
}
////////////////////////////////////////////////////////////////////////////
//Process autobox to initiate automatic gear changes.
//The autobox can be turned off and simulated externally by setting
//the target gear as required prior to calling PxVehicleUpdates.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 processAutoBox(const PxU32 accelIndex, const PxF32 timestep, const PxVehicleDriveSimData& vehCoreSimData, PxVehicleDriveDynData& vehDynData)
{
PX_ASSERT(vehDynData.getUseAutoGears());
PxF32 autoboxCompensatedAnalogAccel = vehDynData.mControlAnalogVals[accelIndex];
//If still undergoing a gear change triggered by the autobox
//then turn off the accelerator pedal. This happens in autoboxes
//to stop the driver revving the engine crazily then damaging the
//clutch when the clutch re-engages at the end of the gear change.
const PxU32 currentGear=vehDynData.getCurrentGear();
const PxU32 targetGear=vehDynData.getTargetGear();
if(targetGear!=currentGear && PxVehicleGearsData::eNEUTRAL==currentGear)
{
autoboxCompensatedAnalogAccel = 0;
}
//Only process the autobox if no gear change is underway and the time passed since the last autobox
//gear change is greater than the autobox latency.
PxF32 autoBoxSwitchTime=vehDynData.getAutoBoxSwitchTime();
const PxF32 autoBoxLatencyTime=vehCoreSimData.getAutoBoxData().mDownRatios[PxVehicleGearsData::eREVERSE];
if(targetGear==currentGear && autoBoxSwitchTime > autoBoxLatencyTime)
{
//Work out if the autobox wants to switch up or down.
const PxF32 normalisedEngineOmega=vehDynData.getEngineRotationSpeed()*vehCoreSimData.getEngineData().getRecipMaxOmega();
const PxVehicleAutoBoxData& autoBoxData=vehCoreSimData.getAutoBoxData();
bool gearUp=false;
if(normalisedEngineOmega > autoBoxData.mUpRatios[currentGear] && PxVehicleGearsData::eREVERSE!=currentGear)
{
//If revs too high and not in reverse and not undergoing a gear change then switch up.
gearUp=true;
}
bool gearDown=false;
if(normalisedEngineOmega < autoBoxData.mDownRatios[currentGear] && currentGear > PxVehicleGearsData::eFIRST)
{
//If revs too low and in gear greater than first and not undergoing a gear change then change down.
gearDown=true;
}
//Start the gear change and reset the time since the last autobox gear change.
if(gearUp || gearDown)
{
vehDynData.setGearUp(gearUp);
vehDynData.setGearDown(gearDown);
vehDynData.setAutoBoxSwitchTime(0.f);
}
}
else
{
autoBoxSwitchTime+=timestep;
vehDynData.setAutoBoxSwitchTime(autoBoxSwitchTime);
}
return autoboxCompensatedAnalogAccel;
}
////////////////////////////////////////////////////////////////////////////
//Process gear changes.
//If target gear not equal to current gear then a gear change needs to start.
//The gear change process begins by switching immediately in neutral and
//staying there for a specified time. The process ends by setting current
//gear equal to target gear when the gear switch time has passed.
//This can be bypassed by always forcing target gear = current gear and then
//externally managing gear changes prior to calling PxVehicleUpdates.
////////////////////////////////////////////////////////////////////////////
void processGears(const PxF32 timestep, const PxVehicleGearsData& gears, PxVehicleDriveDynData& car)
{
//const PxVehicleGearsData& gears=car.mVehicleSimData.getGearsData();
//Process the gears.
if(car.getGearUp() && gears.mNbRatios-1!=car.getCurrentGear() && car.getCurrentGear()==car.getTargetGear())
{
//Car wants to go up a gear and can go up a gear and not already undergoing a gear change.
if(PxVehicleGearsData::eREVERSE==car.getCurrentGear())
{
//In reverse so switch to first through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eFIRST);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else if(PxVehicleGearsData::eNEUTRAL==car.getCurrentGear())
{
//In neutral so switch to first and stay in neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eFIRST);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else
{
//Switch up a gear through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(car.getCurrentGear() + 1);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
}
if(car.getGearDown() && PxVehicleGearsData::eREVERSE!=car.getCurrentGear() && car.getCurrentGear()==car.getTargetGear())
{
//Car wants to go down a gear and can go down a gear and not already undergoing a gear change
if(PxVehicleGearsData::eFIRST==car.getCurrentGear())
{
//In first so switch to reverse through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eREVERSE);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else if(PxVehicleGearsData::eNEUTRAL==car.getCurrentGear())
{
//In neutral so switch to reverse and stay in neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eREVERSE);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else
{
//Switch down a gear through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(car.getCurrentGear() - 1);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
}
if(car.getCurrentGear()!=car.getTargetGear())
{
if(car.getGearSwitchTime()>gears.mSwitchTime)
{
car.setCurrentGear(car.getTargetGear());
car.setGearSwitchTime(0);
car.setGearDown(false);
car.setGearUp(false);
}
else
{
car.setGearSwitchTime(car.getGearSwitchTime() + timestep);
}
}
}
////////////////////////////////////////////////////////////////////////////
//Helper functions to compute
//1. the gear ratio from the current gear.
//2. the drive torque from the state of the accelerator pedal and torque curve of available torque against engine speed.
//3. engine damping rate (a blend between a rate when not accelerating and a rate when fully accelerating).
//4. clutch strength (rate at which clutch will regulate difference between engine and averaged wheel speed).
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 computeGearRatio(const PxVehicleGearsData& gearsData, const PxU32 currentGear)
{
const PxF32 gearRatio=gearsData.mRatios[currentGear]*gearsData.mFinalRatio;
return gearRatio;
}
PX_FORCE_INLINE PxF32 computeEngineDriveTorque(const PxVehicleEngineData& engineData, const PxF32 omega, const PxF32 accel)
{
const PxF32 engineDriveTorque=accel*engineData.mPeakTorque*engineData.mTorqueCurve.getYVal(omega*engineData.getRecipMaxOmega());
return engineDriveTorque;
}
PX_FORCE_INLINE PxF32 computeEngineDampingRate(const PxVehicleEngineData& engineData, const PxU32 gear, const PxF32 accel)
{
const PxF32 fullThrottleDamping = engineData.mDampingRateFullThrottle;
const PxF32 zeroThrottleDamping = (PxVehicleGearsData::eNEUTRAL!=gear) ? engineData.mDampingRateZeroThrottleClutchEngaged : engineData.mDampingRateZeroThrottleClutchDisengaged;
const PxF32 engineDamping = zeroThrottleDamping + (fullThrottleDamping-zeroThrottleDamping)*accel;
return engineDamping;
}
PX_FORCE_INLINE PxF32 computeClutchStrength(const PxVehicleClutchData& clutchData, const PxU32 currentGear)
{
return ((PxVehicleGearsData::eNEUTRAL!=currentGear) ? clutchData.mStrength : 0.0f);
}
////////////////////////////////////////////////////////////////////////////
//Limited slip differential.
//Split the available drive torque as a fraction of the total between up to 4 driven wheels.
//Compute the fraction that each wheel contributes to the averages wheel speed at the clutch.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void splitTorque
(const PxF32 w1, const PxF32 w2, const PxF32 diffBias, const PxF32 defaultSplitRatio,
PxF32* t1, PxF32* t2)
{
PX_ASSERT(computeSign(w1)==computeSign(w2) && 0.0f!=computeSign(w1));
const PxF32 w1Abs=PxAbs(w1);
const PxF32 w2Abs=PxAbs(w2);
const PxF32 omegaMax=PxMax(w1Abs,w2Abs);
const PxF32 omegaMin=PxMin(w1Abs,w2Abs);
const PxF32 delta=omegaMax-diffBias*omegaMin;
const PxF32 deltaTorque=physx::intrinsics::fsel(delta, delta/omegaMax , 0.0f);
const PxF32 f1=physx::intrinsics::fsel(w1Abs-w2Abs, defaultSplitRatio*(1.0f-deltaTorque), defaultSplitRatio*(1.0f+deltaTorque));
const PxF32 f2=physx::intrinsics::fsel(w1Abs-w2Abs, (1.0f-defaultSplitRatio)*(1.0f+deltaTorque), (1.0f-defaultSplitRatio)*(1.0f-deltaTorque));
const PxF32 denom=1.0f/(f1+f2);
*t1=f1*denom;
*t2=f2*denom;
PX_ASSERT((*t1 + *t2) >=0.999f && (*t1 + *t2) <=1.001f);
}
PX_FORCE_INLINE void computeDiffTorqueRatios
(const PxVehicleDifferential4WData& diffData, const PxF32 handbrake, const PxF32* PX_RESTRICT wheelOmegas, PxF32* PX_RESTRICT diffTorqueRatios)
{
//If the handbrake is on only deliver torque to the front wheels.
PxU32 type=diffData.mType;
if(handbrake>0)
{
switch(diffData.mType)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
case PxVehicleDifferential4WData::eMAX_NB_DIFF_TYPES:
break;
}
}
const PxF32 wfl=wheelOmegas[PxVehicleDrive4WWheelOrder::eFRONT_LEFT];
const PxF32 wfr=wheelOmegas[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT];
const PxF32 wrl=wheelOmegas[PxVehicleDrive4WWheelOrder::eREAR_LEFT];
const PxF32 wrr=wheelOmegas[PxVehicleDrive4WWheelOrder::eREAR_RIGHT];
const PxF32 centreBias=diffData.mCentreBias;
const PxF32 frontBias=diffData.mFrontBias;
const PxF32 rearBias=diffData.mRearBias;
const PxF32 frontRearSplit=diffData.mFrontRearSplit;
const PxF32 frontLeftRightSplit=diffData.mFrontLeftRightSplit;
const PxF32 rearLeftRightSplit=diffData.mRearLeftRightSplit;
const PxF32 oneMinusFrontRearSplit=1.0f-diffData.mFrontRearSplit;
const PxF32 oneMinusFrontLeftRightSplit=1.0f-diffData.mFrontLeftRightSplit;
const PxF32 oneMinusRearLeftRightSplit=1.0f-diffData.mRearLeftRightSplit;
const PxF32 swfl=computeSign(wfl);
//Split a torque of 1 between front and rear.
//Then split that torque between left and right.
PxF32 torqueFrontLeft=0;
PxF32 torqueFrontRight=0;
PxF32 torqueRearLeft=0;
PxF32 torqueRearRight=0;
switch(type)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
if(0.0f!=swfl && swfl==computeSign(wfr) && swfl==computeSign(wrl) && swfl==computeSign(wrr))
{
PxF32 torqueFront,torqueRear;
const PxF32 omegaFront=PxAbs(wfl+wfr);
const PxF32 omegaRear=PxAbs(wrl+wrr);
splitTorque(omegaFront,omegaRear,centreBias,frontRearSplit,&torqueFront,&torqueRear);
splitTorque(wfl,wfr,frontBias,frontLeftRightSplit,&torqueFrontLeft,&torqueFrontRight);
splitTorque(wrl,wrr,rearBias,rearLeftRightSplit,&torqueRearLeft,&torqueRearRight);
torqueFrontLeft*=torqueFront;
torqueFrontRight*=torqueFront;
torqueRearLeft*=torqueRear;
torqueRearRight*=torqueRear;
}
else
{
//TODO: need to handle this case.
torqueFrontLeft=frontRearSplit*frontLeftRightSplit;
torqueFrontRight=frontRearSplit*oneMinusFrontLeftRightSplit;
torqueRearLeft=oneMinusFrontRearSplit*rearLeftRightSplit;
torqueRearRight=oneMinusFrontRearSplit*oneMinusRearLeftRightSplit;
}
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
if(0.0f!=swfl && swfl==computeSign(wfr))
{
splitTorque(wfl,wfr,frontBias,frontLeftRightSplit,&torqueFrontLeft,&torqueFrontRight);
}
else
{
torqueFrontLeft=frontLeftRightSplit;
torqueFrontRight=oneMinusFrontLeftRightSplit;
}
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
if(0.0f!=computeSign(wrl) && computeSign(wrl)==computeSign(wrr))
{
splitTorque(wrl,wrr,rearBias,rearLeftRightSplit,&torqueRearLeft,&torqueRearRight);
}
else
{
torqueRearLeft=rearLeftRightSplit;
torqueRearRight=oneMinusRearLeftRightSplit;
}
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
torqueFrontLeft=frontRearSplit*frontLeftRightSplit;
torqueFrontRight=frontRearSplit*oneMinusFrontLeftRightSplit;
torqueRearLeft=oneMinusFrontRearSplit*rearLeftRightSplit;
torqueRearRight=oneMinusFrontRearSplit*oneMinusRearLeftRightSplit;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
torqueFrontLeft=frontLeftRightSplit;
torqueFrontRight=oneMinusFrontLeftRightSplit;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
torqueRearLeft=rearLeftRightSplit;
torqueRearRight=oneMinusRearLeftRightSplit;
break;
default:
PX_ASSERT(false);
break;
}
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=torqueFrontLeft;
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=torqueFrontRight;
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=torqueRearLeft;
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=torqueRearRight;
PX_ASSERT(((torqueFrontLeft+torqueFrontRight+torqueRearLeft+torqueRearRight) >= 0.999f) && ((torqueFrontLeft+torqueFrontRight+torqueRearLeft+torqueRearRight) <= 1.001f));
}
PX_FORCE_INLINE void computeDiffAveWheelSpeedContributions
(const PxVehicleDifferential4WData& diffData, const PxF32 handbrake, PxF32* PX_RESTRICT diffAveWheelSpeedContributions)
{
PxU32 type=diffData.mType;
//If the handbrake is on only deliver torque to the front wheels.
if(handbrake>0)
{
switch(diffData.mType)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
case PxVehicleDifferential4WData::eMAX_NB_DIFF_TYPES:
break;
}
}
const PxF32 frontRearSplit=diffData.mFrontRearSplit;
const PxF32 frontLeftRightSplit=diffData.mFrontLeftRightSplit;
const PxF32 rearLeftRightSplit=diffData.mRearLeftRightSplit;
const PxF32 oneMinusFrontRearSplit=1.0f-diffData.mFrontRearSplit;
const PxF32 oneMinusFrontLeftRightSplit=1.0f-diffData.mFrontLeftRightSplit;
const PxF32 oneMinusRearLeftRightSplit=1.0f-diffData.mRearLeftRightSplit;
switch(type)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=frontRearSplit*frontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=frontRearSplit*oneMinusFrontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=oneMinusFrontRearSplit*rearLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=oneMinusFrontRearSplit*oneMinusRearLeftRightSplit;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=frontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=oneMinusFrontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=0.0f;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=0.0f;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=0.0f;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=0.0f;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=rearLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=oneMinusRearLeftRightSplit;
break;
default:
PX_ASSERT(false);
break;
}
PX_ASSERT((diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]) >= 0.999f &&
(diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]) <= 1.001f);
}
///////////////////////////////////////////////////////
//Tank differential
///////////////////////////////////////////////////////
void computeTankDiff
(const PxF32 thrustLeft, const PxF32 thrustRight,
const PxU32 numActiveWheels, const bool* activeWheelStates,
PxF32* aveWheelSpeedContributions, PxF32* diffTorqueRatios, PxF32* wheelGearings)
{
const PxF32 thrustLeftAbs=PxAbs(thrustLeft);
const PxF32 thrustRightAbs=PxAbs(thrustRight);
//Work out now many left wheels are enabled.
PxF32 numLeftWheels=0.0f;
for(PxU32 i=0;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
numLeftWheels+=1.0f;
}
}
const PxF32 invNumEnabledWheelsLeft = numLeftWheels > 0 ? 1.0f/numLeftWheels : 0.0f;
//Work out now many right wheels are enabled.
PxF32 numRightWheels=0.0f;
for(PxU32 i=1;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
numRightWheels+=1.0f;
}
}
const PxF32 invNumEnabledWheelsRight = numRightWheels > 0 ? 1.0f/numRightWheels : 0.0f;
//Split the diff torque between left and right.
PxF32 diffTorqueRatioLeft=0.5f;
PxF32 diffTorqueRatioRight=0.5f;
if((thrustLeftAbs + thrustRightAbs) > 1e-3f)
{
const PxF32 thrustDiff = 0.5f*(thrustLeftAbs - thrustRightAbs)/(thrustLeftAbs + thrustRightAbs);
diffTorqueRatioLeft += thrustDiff;
diffTorqueRatioRight -= thrustDiff;
}
diffTorqueRatioLeft *= invNumEnabledWheelsLeft;
diffTorqueRatioRight *= invNumEnabledWheelsRight;
//Compute the per wheel gearing.
PxF32 wheelGearingLeft=1.0f;
PxF32 wheelGearingRight=1.0f;
if((thrustLeftAbs + thrustRightAbs) > 1e-3f)
{
wheelGearingLeft=computeSign(thrustLeft);
wheelGearingRight=computeSign(thrustRight);
}
//Compute the contribution of each wheel to the average speed at the clutch.
const PxF32 aveWheelSpeedContributionLeft = 0.5f*invNumEnabledWheelsLeft;
const PxF32 aveWheelSpeedContributionRight = 0.5f*invNumEnabledWheelsRight;
//Set all the left wheels.
for(PxU32 i=0;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
aveWheelSpeedContributions[i]=aveWheelSpeedContributionLeft;
diffTorqueRatios[i]=diffTorqueRatioLeft;
wheelGearings[i]=wheelGearingLeft;
}
}
//Set all the right wheels.
for(PxU32 i=1;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
aveWheelSpeedContributions[i]=aveWheelSpeedContributionRight;
diffTorqueRatios[i]=diffTorqueRatioRight;
wheelGearings[i]=wheelGearingRight;
}
}
}
////////////////////////////////////////////////////////////////////////////
//Compute a per-wheel accelerator pedal value.
//These values are to blend the denominator normalised longitudinal slip at low speed
//between a low value for wheels under drive torque and a high value for wheels with no
//drive torque.
//Using a high value allows the vehicle to come to rest smoothly.
//Using a low value gives better thrust.
////////////////////////////////////////////////////////////////////////////
void computeIsAccelApplied(const PxF32* aveWheelSpeedContributions, bool* isAccelApplied)
{
isAccelApplied[0] = aveWheelSpeedContributions[0] != 0.0f ? true : false;
isAccelApplied[1] = aveWheelSpeedContributions[1] != 0.0f ? true : false;
isAccelApplied[2] = aveWheelSpeedContributions[2] != 0.0f ? true : false;
isAccelApplied[3] = aveWheelSpeedContributions[3] != 0.0f ? true : false;
}
////////////////////////////////////////////////////////////////////////////
//Ackermann correction to steer angles.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void computeAckermannSteerAngles
(const PxF32 steer, const PxF32 steerGain,
const PxF32 ackermannAccuracy, const PxF32 width, const PxF32 axleSeparation,
PxF32* PX_RESTRICT leftAckermannSteerAngle, PxF32* PX_RESTRICT rightAckermannSteerAngle)
{
PX_ASSERT(steer>=-1.01f && steer<=1.01f);
PX_ASSERT(steerGain<PxPi);
const PxF32 steerAngle=steer*steerGain;
if(0==steerAngle)
{
*leftAckermannSteerAngle=0;
*rightAckermannSteerAngle=0;
return;
}
//Work out the ackermann steer for +ve steer then swap and negate the steer angles if the steer is -ve.
//TODO: use faster approximate functions for PxTan/PxATan because the results don't need to be too accurate here.
const PxF32 rightSteerAngle=PxAbs(steerAngle);
const PxF32 dz=axleSeparation;
const PxF32 dx=width + dz/PxTan(rightSteerAngle);
const PxF32 leftSteerAnglePerfect=PxAtan(dz/dx);
const PxF32 leftSteerAngle=rightSteerAngle + ackermannAccuracy*(leftSteerAnglePerfect-rightSteerAngle);
*rightAckermannSteerAngle=physx::intrinsics::fsel(steerAngle, rightSteerAngle, -leftSteerAngle);
*leftAckermannSteerAngle=physx::intrinsics::fsel(steerAngle, leftSteerAngle, -rightSteerAngle);
}
PX_FORCE_INLINE void computeAckermannCorrectedSteerAngles
(const PxVehicleDriveSimData4W& driveSimData, const PxVehicleWheels4SimData& wheelsSimData, const PxF32 steer,
PxF32* PX_RESTRICT steerAngles)
{
const PxVehicleAckermannGeometryData& ackermannData=driveSimData.getAckermannGeometryData();
const PxF32 ackermannAccuracy=ackermannData.mAccuracy;
const PxF32 axleSeparation=ackermannData.mAxleSeparation;
{
const PxVehicleWheelData& wheelDataFL=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_LEFT);
const PxVehicleWheelData& wheelDataFR=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT);
const PxF32 steerGainFront=PxMax(wheelDataFL.mMaxSteer,wheelDataFR.mMaxSteer);
const PxF32 frontWidth=ackermannData.mFrontWidth;
PxF32 frontLeftSteer,frontRightSteer;
computeAckermannSteerAngles(steer,steerGainFront,ackermannAccuracy,frontWidth,axleSeparation,&frontLeftSteer,&frontRightSteer);
steerAngles[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=wheelDataFL.mToeAngle+frontLeftSteer;
steerAngles[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=wheelDataFR.mToeAngle+frontRightSteer;
}
{
const PxVehicleWheelData& wheelDataRL=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_LEFT);
const PxVehicleWheelData& wheelDataRR=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_RIGHT);
const PxF32 steerGainRear=PxMax(wheelDataRL.mMaxSteer,wheelDataRR.mMaxSteer);
const PxF32 rearWidth=ackermannData.mRearWidth;
PxF32 rearLeftSteer,rearRightSteer;
computeAckermannSteerAngles(steer,steerGainRear,ackermannAccuracy,rearWidth,axleSeparation,&rearLeftSteer,&rearRightSteer);
steerAngles[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=wheelDataRL.mToeAngle-rearLeftSteer;
steerAngles[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=wheelDataRR.mToeAngle-rearRightSteer;
}
}
////////////////////////////////////////////////////////////////////////////
//Compute the wheel active states
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void computeWheelActiveStates(const PxU32 startId, PxU32* bitmapBuffer, bool* activeStates)
{
PX_ASSERT(!activeStates[0] && !activeStates[1] && !activeStates[2] && !activeStates[3]);
PxBitMap bm;
bm.setWords(bitmapBuffer, ((PX_MAX_NB_WHEELS + 31) & ~31) >> 5);
if(bm.test(startId + 0))
{
activeStates[0]=true;
}
if(bm.test(startId + 1))
{
activeStates[1]=true;
}
if(bm.test(startId + 2))
{
activeStates[2]=true;
}
if(bm.test(startId + 3))
{
activeStates[3]=true;
}
}
////////////////////////////////////////////////////////////////////////////
//Compute the brake and handbrake torques for different vehicle types.
//Also compute a boolean for each tire to know if the brake is applied or not.
//Can't use a single function for all types because not all vehicle types have
//handbrakes and the brake control mechanism is different for different vehicle
//types.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void computeNoDriveBrakeTorques
(const PxVehicleWheelData* PX_RESTRICT wheelDatas, const PxF32* PX_RESTRICT wheelOmegas, const PxF32* PX_RESTRICT rawBrakeTroques,
PxF32* PX_RESTRICT brakeTorques, bool* PX_RESTRICT isBrakeApplied)
{
PX_UNUSED(wheelDatas);
const PxF32 sign0=computeSign(wheelOmegas[0]);
brakeTorques[0]=(-sign0*rawBrakeTroques[0]);
isBrakeApplied[0]=(rawBrakeTroques[0]!=0);
const PxF32 sign1=computeSign(wheelOmegas[1]);
brakeTorques[1]=(-sign1*rawBrakeTroques[1]);
isBrakeApplied[1]=(rawBrakeTroques[1]!=0);
const PxF32 sign2=computeSign(wheelOmegas[2]);
brakeTorques[2]=(-sign2*rawBrakeTroques[2]);
isBrakeApplied[2]=(rawBrakeTroques[2]!=0);
const PxF32 sign3=computeSign(wheelOmegas[3]);
brakeTorques[3]=(-sign3*rawBrakeTroques[3]);
isBrakeApplied[3]=(rawBrakeTroques[3]!=0);
}
PX_FORCE_INLINE void computeBrakeAndHandBrakeTorques
(const PxVehicleWheelData* PX_RESTRICT wheelDatas, const PxF32* PX_RESTRICT wheelOmegas, const PxF32 brake, const PxF32 handbrake,
PxF32* PX_RESTRICT brakeTorques, bool* isBrakeApplied)
{
//At zero speed offer no brake torque allowed.
const PxF32 sign0=computeSign(wheelOmegas[0]);
brakeTorques[0]=(-brake*sign0*wheelDatas[0].mMaxBrakeTorque-handbrake*sign0*wheelDatas[0].mMaxHandBrakeTorque);
isBrakeApplied[0]=((brake*wheelDatas[0].mMaxBrakeTorque+handbrake*wheelDatas[0].mMaxHandBrakeTorque)!=0);
const PxF32 sign1=computeSign(wheelOmegas[1]);
brakeTorques[1]=(-brake*sign1*wheelDatas[1].mMaxBrakeTorque-handbrake*sign1*wheelDatas[1].mMaxHandBrakeTorque);
isBrakeApplied[1]=((brake*wheelDatas[1].mMaxBrakeTorque+handbrake*wheelDatas[1].mMaxHandBrakeTorque)!=0);
const PxF32 sign2=computeSign(wheelOmegas[2]);
brakeTorques[2]=(-brake*sign2*wheelDatas[2].mMaxBrakeTorque-handbrake*sign2*wheelDatas[2].mMaxHandBrakeTorque);
isBrakeApplied[2]=((brake*wheelDatas[2].mMaxBrakeTorque+handbrake*wheelDatas[2].mMaxHandBrakeTorque)!=0);
const PxF32 sign3=computeSign(wheelOmegas[3]);
brakeTorques[3]=(-brake*sign3*wheelDatas[3].mMaxBrakeTorque-handbrake*sign3*wheelDatas[3].mMaxHandBrakeTorque);
isBrakeApplied[3]=((brake*wheelDatas[3].mMaxBrakeTorque+handbrake*wheelDatas[3].mMaxHandBrakeTorque)!=0);
}
PX_FORCE_INLINE void computeTankBrakeTorques
(const PxVehicleWheelData* PX_RESTRICT wheelDatas, const PxF32* PX_RESTRICT wheelOmegas, const PxF32 brakeLeft, const PxF32 brakeRight,
PxF32* PX_RESTRICT brakeTorques, bool* isBrakeApplied)
{
//At zero speed offer no brake torque allowed.
const PxF32 sign0=computeSign(wheelOmegas[0]);
brakeTorques[0]=(-brakeLeft*sign0*wheelDatas[0].mMaxBrakeTorque);
isBrakeApplied[0]=((brakeLeft*wheelDatas[0].mMaxBrakeTorque)!=0);
const PxF32 sign1=computeSign(wheelOmegas[1]);
brakeTorques[1]=(-brakeRight*sign1*wheelDatas[1].mMaxBrakeTorque);
isBrakeApplied[1]=((brakeRight*wheelDatas[1].mMaxBrakeTorque)!=0);
const PxF32 sign2=computeSign(wheelOmegas[2]);
brakeTorques[2]=(-brakeLeft*sign2*wheelDatas[2].mMaxBrakeTorque);
isBrakeApplied[2]=((brakeLeft*wheelDatas[2].mMaxBrakeTorque)!=0);
const PxF32 sign3=computeSign(wheelOmegas[3]);
brakeTorques[3]=(-brakeRight*sign3*wheelDatas[3].mMaxBrakeTorque);
isBrakeApplied[3]=((brakeRight*wheelDatas[3].mMaxBrakeTorque)!=0);
}
////////////////////////////////////////////////////////////////////////////
//Functions to compute inputs to tire force calculation.
//1. Filter the normalised tire load to smooth any spikes in load.
//2. Compute the tire lat and long directions in the ground plane.
//3. Compute the tire lat and long slips.
//4. Compute the friction from a graph of friction vs slip.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 computeFilteredNormalisedTireLoad(const PxVehicleTireLoadFilterData& filterData, const PxF32 normalisedLoad)
{
if(normalisedLoad <= filterData.mMinNormalisedLoad)
{
return filterData.mMinFilteredNormalisedLoad;
}
else if(normalisedLoad >= filterData.mMaxNormalisedLoad)
{
return filterData.mMaxFilteredNormalisedLoad;
}
else
{
const PxF32 x=normalisedLoad;
const PxF32 xmin=filterData.mMinNormalisedLoad;
const PxF32 ymin=filterData.mMinFilteredNormalisedLoad;
const PxF32 ymax=filterData.mMaxFilteredNormalisedLoad;
const PxF32 recipXmaxMinusXMin=filterData.getDenominator();
return (ymin + (x-xmin)*(ymax-ymin)*recipXmaxMinusXMin);
}
}
PX_FORCE_INLINE void computeTireDirs(const PxVec3& chassisLatDir, const PxVec3& hitNorm, const PxF32 wheelSteerAngle, PxVec3& tireLongDir, PxVec3& tireLatDir)
{
PX_ASSERT(chassisLatDir.magnitude()>0.999f && chassisLatDir.magnitude()<1.001f);
PX_ASSERT(hitNorm.magnitude()>0.999f && hitNorm.magnitude()<1.001f);
//Compute the tire axes in the ground plane.
PxVec3 tzRaw=chassisLatDir.cross(hitNorm);
PxVec3 txRaw=hitNorm.cross(tzRaw);
tzRaw.normalize();
txRaw.normalize();
//Rotate the tire using the steer angle.
const PxF32 cosWheelSteer=PxCos(wheelSteerAngle);
const PxF32 sinWheelSteer=PxSin(wheelSteerAngle);
const PxVec3 tz=tzRaw*cosWheelSteer + txRaw*sinWheelSteer;
const PxVec3 tx=txRaw*cosWheelSteer - tzRaw*sinWheelSteer;
tireLongDir=tz;
tireLatDir=tx;
}
PX_FORCE_INLINE void computeTireSlips
(const PxF32 longSpeed, const PxF32 latSpeed, const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 maxDenominator,
const bool isAccelApplied, const bool isBrakeApplied,
const bool isTank,
PxF32& longSlip, PxF32& latSlip)
{
PX_ASSERT(maxDenominator>=0.0f);
const PxF32 longSpeedAbs=PxAbs(longSpeed);
const PxF32 wheelSpeed=wheelOmega*wheelRadius;
const PxF32 wheelSpeedAbs=PxAbs(wheelSpeed);
//Lateral slip is easy.
latSlip = PxAtan(latSpeed/(longSpeedAbs+gMinLatSpeedForTireModel));//TODO: do we really use PxAbs(vz) as denominator?
//If nothing is moving just avoid a divide by zero and set the long slip to zero.
if(longSpeed==0 && wheelOmega==0)
{
longSlip=0.0f;
return;
}
//Longitudinal slip is a bit harder because we can end up wtih zero on the denominator.
if(isTank)
{
if(isBrakeApplied || isAccelApplied)
{
//Wheel experiencing an applied torque.
//Use the raw denominator value plus an offset to avoid anything approaching a divide by zero.
//When accelerating from rest the small denominator will generate really quite large
//slip values, which will, in turn, generate large longitudinal forces. With large
//time-steps this might lead to a temporary oscillation in longSlip direction and an
//oscillation in wheel speed direction. The amplitude of the oscillation should be low
//unless the timestep is really large.
//There's not really an obvious solution to this without setting the denominator offset higher
//(or decreasing the timestep). Setting the denominator higher affects handling everywhere so
//settling for a potential temporary oscillation is probably the least worst compromise.
//Note that we always use longSpeedAbs as denominator because in order to turn on the spot the
//tank needs to get strong longitudinal force when it isn't moving but the wheels are slipping.
longSlip = (wheelSpeed - longSpeed)/(longSpeedAbs + 0.1f*gToleranceScaleLength);
}
else
{
//Wheel not experiencing an applied torque.
//If the denominator becomes too small then the longSlip becomes large and the longitudinal force
//can overshoot zero at large timesteps. This can be really noticeable so it's harder to justify
//not taking action. Further, the car isn't being actually driven so there is a strong case to fiddle
//with the denominator because it doesn't really affect active handling.
//Don't let the denominator fall below a user-specified value. This can be tuned upwards until the
//oscillation in the sign of longSlip disappears.
longSlip = (wheelSpeed - longSpeed)/(PxMax(maxDenominator, PxMax(longSpeedAbs,wheelSpeedAbs)));
}
}
else
{
if(isBrakeApplied || isAccelApplied)
{
//Wheel experiencing an applied torque.
//Use the raw denominator value plus an offset to avoid anything approaching a divide by zero.
//When accelerating from rest the small denominator will generate really quite large
//slip values, which will, in turn, generate large longitudinal forces. With large
//time-steps this might lead to a temporary oscillation in longSlip direction and an
//oscillation in wheel speed direction. The amplitude of the oscillation should be low
//unless the timestep is really large.
//There's not really an obvious solution to this without setting the denominator offset higher
//(or decreasing the timestep). Setting the denominator higher affects handling everywhere so
//settling for a potential temporary oscillation is probably the least worst compromise.
longSlip = (wheelSpeed - longSpeed)/(PxMax(longSpeedAbs,wheelSpeedAbs)+0.1f*gToleranceScaleLength);
}
else
{
//Wheel not experiencing an applied torque.
//If the denominator becomes too small then the longSlip becomes large and the longitudinal force
//can overshoot zero at large timesteps. This can be really noticeable so it's harder to justify
//not taking action. Further, the car isn't being actually driven so there is a strong case to fiddle
//with the denominator because it doesn't really affect active handling.
//Don't let the denominator fall below a user-specified value. This can be tuned upwards until the
//oscillation in the sign of longSlip disappears.
longSlip = (wheelSpeed - longSpeed)/(PxMax(maxDenominator,PxMax(longSpeedAbs,wheelSpeedAbs)));
}
}
}
PX_FORCE_INLINE void computeTireFriction(const PxVehicleTireData& tireData, const PxF32 longSlip, const PxF32 frictionMultiplier, PxF32& friction)
{
const PxF32 x0=tireData.mFrictionVsSlipGraph[0][0];
const PxF32 y0=tireData.mFrictionVsSlipGraph[0][1];
const PxF32 x1=tireData.mFrictionVsSlipGraph[1][0];
const PxF32 y1=tireData.mFrictionVsSlipGraph[1][1];
const PxF32 x2=tireData.mFrictionVsSlipGraph[2][0];
const PxF32 y2=tireData.mFrictionVsSlipGraph[2][1];
const PxF32 recipx1Minusx0=tireData.getFrictionVsSlipGraphRecipx1Minusx0();
const PxF32 recipx2Minusx1=tireData.getFrictionVsSlipGraphRecipx2Minusx1();
const PxF32 longSlipAbs=PxAbs(longSlip);
PxF32 mu;
if(longSlipAbs<x1)
{
mu=y0 + (y1-y0)*(longSlipAbs-x0)*recipx1Minusx0;
}
else if(longSlipAbs<x2)
{
mu=y1 + (y2-y1)*(longSlipAbs-x1)*recipx2Minusx1;
}
else
{
mu=y2;
}
PX_ASSERT(mu>=0);
friction=mu*frictionMultiplier;
}
////////////////////////////////////////////////////////////////////////////
//Sticky tire constraints.
//Increment a timer each update that a tire has a very low longitudinal speed.
//Activate a sticky constraint when the tire has had an unbroken low long speed
//for at least a threshold time.
//The longer the sticky constraint is active, the slower the target constraint speed
//along the long dir. Quickly tends towards zero.
//When the sticky constraint is activated set the long slip to zero and let
//the sticky constraint take over.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void updateLowForwardSpeedTimer
(const PxF32 longSpeed, const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 recipWheelRadius, const bool isIntentionToAccelerate,
const PxF32 timestep, PxF32& lowForwardSpeedTime)
{
PX_UNUSED(wheelRadius);
PX_UNUSED(recipWheelRadius);
//If the tire is rotating slowly and the forward speed is slow then increment the slow forward speed timer.
//If the intention of the driver is to accelerate the vehicle then reset the timer because the intention has been signalled NOT to bring
//the wheel to rest.
PxF32 longSpeedAbs=PxAbs(longSpeed);
if((longSpeedAbs<gStickyTireFrictionThresholdSpeed) && (PxAbs(wheelOmega)< gStickyTireFrictionThresholdSpeed*recipWheelRadius) && !isIntentionToAccelerate)
{
lowForwardSpeedTime+=timestep;
}
else
{
lowForwardSpeedTime=0;
}
}
PX_FORCE_INLINE void updateLowSideSpeedTimer
(const PxF32 latSpeed, const bool isIntentionToAccelerate, const PxF32 timestep, PxF32& lowSideSpeedTime)
{
//If the side speed is slow then increment the slow side speed timer.
//If the intention of the driver is to accelerate the vehicle then reset the timer because the intention has been signalled NOT to bring
//the wheel to rest.
PxF32 latSpeedAbs=PxAbs(latSpeed);
if((latSpeedAbs<gStickyTireFrictionThresholdSpeed) && !isIntentionToAccelerate)
{
lowSideSpeedTime+=timestep;
}
else
{
lowSideSpeedTime=0;
}
}
PX_FORCE_INLINE void activateStickyFrictionForwardConstraint
(const PxF32 longSpeed, const PxF32 wheelOmega, const PxF32 lowForwardSpeedTime, const bool isIntentionToAccelerate,
bool& stickyTireActiveFlag, PxF32& stickyTireTargetSpeed)
{
//Setup the sticky friction constraint to bring the vehicle to rest at the tire contact point.
//The idea here is to resolve the singularity of the tire long slip at low vz by replacing the long force with a velocity constraint.
//Only do this if we can guarantee that the intention is to bring the car to rest (no accel pedal applied).
//Smoothly reduce error to zero to avoid bringing car immediately to rest. This avoids graphical glitchiness.
//We're going to replace the longitudinal tire force with the sticky friction so set the long slip to zero to ensure zero long force.
//Apply sticky friction to this tire if
//(1) the wheel is locked (this means the brake/handbrake must be on) and the forward speed at the tire contact point is vanishingly small and
// the drive of vehicle has no intention to accelerate the vehicle.
//(2) the accumulated time of low forward speed is greater than a threshold.
PxF32 longSpeedAbs=PxAbs(longSpeed);
stickyTireActiveFlag=false;
stickyTireTargetSpeed=0.0f;
if((longSpeedAbs < gStickyTireFrictionThresholdSpeed && 0.0f==wheelOmega && !isIntentionToAccelerate) || lowForwardSpeedTime>gLowForwardSpeedThresholdTime)
{
stickyTireActiveFlag=true;
stickyTireTargetSpeed=longSpeed*gStickyTireFrictionForwardDamping;
}
}
PX_FORCE_INLINE void activateStickyFrictionSideConstraint
(const PxF32 latSpeed, const PxF32 lowSpeedForwardTimer, const PxF32 lowSideSpeedTimer, const bool isIntentionToAccelerate,
bool& stickyTireActiveFlag, PxF32& stickyTireTargetSpeed)
{
PX_UNUSED(latSpeed);
PX_UNUSED(isIntentionToAccelerate);
//Setup the sticky friction constraint to bring the vehicle to rest at the tire contact point.
//Only do this if we can guarantee that the intention is to bring the car to rest (no accel pedal applied).
//Smoothly reduce error to zero to avoid bringing car immediately to rest. This avoids graphical glitchiness.
//We're going to replace the lateral tire force with the sticky friction so set the lat slip to zero to ensure zero lat force.
//Apply sticky friction to this tire if
//(1) the low forward speed timer is > 0.
//(2) the accumulated time of low forward speed is greater than a threshold.
stickyTireActiveFlag=false;
stickyTireTargetSpeed=0.0f;
if((lowSpeedForwardTimer > 0) && lowSideSpeedTimer>gLowSideSpeedThresholdTime)
{
stickyTireActiveFlag=true;
stickyTireTargetSpeed=latSpeed*gStickyTireFrictionSideDamping;
}
}
////////////////////////////////////////////////////////////////////////////
//Default tire force shader function.
//Taken from Michigan tire model.
//Computes tire long and lat forces plus the aligning moment arising from
//the lat force and the torque to apply back to the wheel arising from the
//long force (application of Newton's 3rd law).
////////////////////////////////////////////////////////////////////////////
#define ONE_TWENTYSEVENTH 0.037037f
#define ONE_THIRD 0.33333f
PX_FORCE_INLINE PxF32 smoothingFunction1(const PxF32 K)
{
//Equation 20 in CarSimEd manual Appendix F.
//Looks a bit like a curve of sqrt(x) for 0<x<1 but reaching 1.0 on y-axis at K=3.
PX_ASSERT(K>=0.0f);
return PxMin(1.0f, K - ONE_THIRD*K*K + ONE_TWENTYSEVENTH*K*K*K);
}
PX_FORCE_INLINE PxF32 smoothingFunction2(const PxF32 K)
{
//Equation 21 in CarSimEd manual Appendix F.
//Rises to a peak at K=0.75 and falls back to zero by K=3
PX_ASSERT(K>=0.0f);
return (K - K*K + ONE_THIRD*K*K*K - ONE_TWENTYSEVENTH*K*K*K*K);
}
void PxVehicleComputeTireForceDefault
(const void* tireShaderData,
const PxF32 tireFriction,
const PxF32 longSlipUnClamped, const PxF32 latSlipUnClamped, const PxF32 camberUnclamped,
const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 recipWheelRadius,
const PxF32 restTireLoad, const PxF32 normalisedTireLoad, const PxF32 tireLoad,
const PxF32 gravity, const PxF32 recipGravity,
PxF32& wheelTorque, PxF32& tireLongForceMag, PxF32& tireLatForceMag, PxF32& tireAlignMoment)
{
PX_UNUSED(wheelOmega);
PX_UNUSED(recipWheelRadius);
const PxVehicleTireData& tireData=*reinterpret_cast<const PxVehicleTireData*>(tireShaderData);
PX_ASSERT(tireFriction>0);
PX_ASSERT(tireLoad>0);
wheelTorque=0.0f;
tireLongForceMag=0.0f;
tireLatForceMag=0.0f;
tireAlignMoment=0.0f;
//Clamp the slips to a minimum value.
const PxF32 latSlip = PxAbs(latSlipUnClamped) >= gMinimumSlipThreshold ? latSlipUnClamped : 0.0f;
const PxF32 longSlip = PxAbs(longSlipUnClamped) >= gMinimumSlipThreshold ? longSlipUnClamped : 0.0f;
const PxF32 camber = PxAbs(camberUnclamped) >= gMinimumSlipThreshold ? camberUnclamped : 0.0f;
//If long slip/lat slip/camber are all zero than there will be zero tire force.
if((0==latSlip)&&(0==longSlip)&&(0==camber))
{
return;
}
//Compute the lateral stiffness
const PxF32 latStiff=restTireLoad*tireData.mLatStiffY*smoothingFunction1(normalisedTireLoad*3.0f/tireData.mLatStiffX);
//Get the longitudinal stiffness
const PxF32 longStiff=tireData.mLongitudinalStiffnessPerUnitGravity*gravity;
const PxF32 recipLongStiff=tireData.getRecipLongitudinalStiffnessPerUnitGravity()*recipGravity;
//Get the camber stiffness.
const PxF32 camberStiff=tireData.mCamberStiffnessPerUnitGravity*gravity;
//Carry on and compute the forces.
const PxF32 TEff = PxTan(latSlip - camber*camberStiff/latStiff);
const PxF32 K = PxSqrt(latStiff*TEff*latStiff*TEff + longStiff*longSlip*longStiff*longSlip) /(tireFriction*tireLoad);
//const PxF32 KAbs=PxAbs(K);
PxF32 FBar = smoothingFunction1(K);//K - ONE_THIRD*PxAbs(K)*K + ONE_TWENTYSEVENTH*K*K*K;
PxF32 MBar = smoothingFunction2(K); //K - KAbs*K + ONE_THIRD*K*K*K - ONE_TWENTYSEVENTH*KAbs*K*K*K;
//Mbar = PxMin(Mbar, 1.0f);
PxF32 nu=1;
if(K <= 2.0f*PxPi)
{
const PxF32 latOverlLong=latStiff*recipLongStiff;
nu = 0.5f*(1.0f + latOverlLong - (1.0f - latOverlLong)*PxCos(K*0.5f));
}
const PxF32 FZero = tireFriction*tireLoad / (PxSqrt(longSlip*longSlip + nu*TEff*nu*TEff));
const PxF32 fz = longSlip*FBar*FZero;
const PxF32 fx = -nu*TEff*FBar*FZero;
//TODO: pneumatic trail.
const PxF32 pneumaticTrail=1.0f;
const PxF32 fMy= nu * pneumaticTrail * TEff * MBar * FZero;
//We can add the torque to the wheel.
wheelTorque=-fz*wheelRadius;
tireLongForceMag=fz;
tireLatForceMag=fx;
tireAlignMoment=fMy;
}
////////////////////////////////////////////////////////////////////////////
//Compute the suspension line raycast start point and direction.
////////////////////////////////////////////////////////////////////////////
static PX_INLINE void computeSuspensionRaycast
(const PxTransform& carChassisTrnsfm, const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir, const PxF32 radius, const PxF32 maxBounce,
PxVec3& suspLineStart, PxVec3& suspLineDir)
{
//Direction of raycast.
suspLineDir=carChassisTrnsfm.rotate(bodySpaceSuspTravelDir);
//Position at top of wheel at maximum compression.
suspLineStart=carChassisTrnsfm.transform(bodySpaceWheelCentreOffset);
suspLineStart-=suspLineDir*(radius+maxBounce);
}
static PX_INLINE void computeSuspensionSweep
(const PxTransform& carChassisTrnsfm,
const PxQuat& wheelLocalPoseRotation,
const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir, const PxF32 radius, const PxF32 maxBounce,
PxTransform& suspStartPose, PxVec3& suspLineDir)
{
//Direction of raycast.
suspLineDir=carChassisTrnsfm.rotate(bodySpaceSuspTravelDir);
//Position of wheel at maximum compression.
suspStartPose.p = carChassisTrnsfm.transform(bodySpaceWheelCentreOffset);
suspStartPose.p -= suspLineDir*(radius + maxBounce);
//Rotation in world frame.
suspStartPose.q = carChassisTrnsfm.q*wheelLocalPoseRotation;
}
////////////////////////////////////////////////////////////////////////////
//Functions required to intersect the wheel with the hit plane
//We support raycasts and sweeps.
////////////////////////////////////////////////////////////////////////////
static bool intersectRayPlane
(const PxTransform& carChassisTrnsfm,
const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir,
const PxF32 width, const PxF32 radius, const PxF32 maxCompression,
const PxPlane& hitPlane,
PxF32& jounce, PxVec3& wheelBottomPos)
{
PX_UNUSED(width);
//Compute the raycast start pos and direction.
PxVec3 v, w;
computeSuspensionRaycast(carChassisTrnsfm, bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, radius, maxCompression, v, w);
//If the raycast starts inside the hit plane then return false
if((hitPlane.n.dot(v) + hitPlane.d) < 0.0f)
{
return false;
}
//Store a point through the centre of the wheel.
//We'll use this later to compute a position at the bottom of the wheel.
const PxVec3 pos = v;
//Remove this code because we handle tire width with sweeps now.
//Work out if the inner or outer disc is deeper in the plane.
//const PxVec3 latDir = carChassisTrnsfm.rotate(gRight);
//const PxF32 signDot = computeSign(hitNorm.dot(latDir));
//v -= latDir*(signDot*0.5f*width);
//Work out the point on the susp line that touches the intersection plane.
//n.(v+wt)+d=0 where n,d describe the plane; v,w describe the susp ray; t is the point on the susp line.
//t=-(n.v + d)/n.w
const PxF32 hitD = hitPlane.d;
const PxVec3 n = hitPlane.n;
const PxF32 d = hitD;
const PxF32 T=-(n.dot(v) + d)/(n.dot(w));
//The rest pos of the susp line is 2*radius + maxBounce.
const PxF32 restT = 2.0f*radius+maxCompression;
//Compute the spring compression ie the difference between T and restT.
//+ve means that the spring is compressed
//-ve means that the spring is elongated.
jounce = restT-T;
//Compute the bottom of the wheel.
//Always choose a point through the centre of the wheel.
wheelBottomPos = pos + w*(restT - jounce);
return true;
}
static bool intersectPlanes(const PxPlane& a, const PxPlane& b, PxVec3& v, PxVec3& w)
{
const PxF32 n1x = a.n.x;
const PxF32 n1y = a.n.y;
const PxF32 n1z = a.n.z;
const PxF32 n1d = a.d;
const PxF32 n2x = b.n.x;
const PxF32 n2y = b.n.y;
const PxF32 n2z = b.n.z;
const PxF32 n2d = b.d;
PxF32 dx = (n1y * n2z) - (n1z * n2y);
PxF32 dy = (n1z * n2x) - (n1x * n2z);
PxF32 dz = (n1x * n2y) - (n1y * n2x);
const PxF32 dx2 = dx * dx;
const PxF32 dy2 = dy * dy;
const PxF32 dz2 = dz * dz;
PxF32 px, py, pz;
bool success = true;
if ((dz2 > dy2) && (dz2 > dx2) && (dz2 > 0))
{
px = ((n1y * n2d) - (n2y * n1d)) / dz;
py = ((n2x * n1d) - (n1x * n2d)) / dz;
pz = 0;
}
else if ((dy2 > dx2) && (dy2 > 0))
{
px = -((n1z * n2d) - (n2z * n1d)) / dy;
py = 0;
pz = -((n2x * n1d) - (n1x * n2d)) / dy;
}
else if (dx2 > 0)
{
px = 0;
py = ((n1z * n2d) - (n2z * n1d)) / dx;
pz = ((n2y * n1d) - (n1y * n2d)) / dx;
}
else
{
px=0;
py=0;
pz=0;
success=false;
}
const PxF32 ld = PxSqrt(dx2 + dy2 + dz2);
dx /= ld;
dy /= ld;
dz /= ld;
w = PxVec3(dx,dy,dz);
v = PxVec3(px,py,pz);
return success;
}
static bool intersectCylinderPlane
(const PxTransform& wheelPoseAtZeroJounce, const PxVec3 suspDir,
const PxF32 width, const PxF32 radius, const PxF32 maxCompression,
const PxPlane& hitPlane,
const PxVec3& sideAxis,
const bool rejectFromThresholds,
const PxF32 pointRejectAngleThresholdCosine,
const PxF32 normalRejectAngleThresholdCosine,
PxF32& jounce, PxVec3& wheelBottomPos,
const PxVec3& contactPt, float hitDist, bool useDirectSweepResults)
{
//Reject based on the contact normal.
if(rejectFromThresholds)
{
if(suspDir.dot(-hitPlane.n) < normalRejectAngleThresholdCosine)
return false;
}
//Construct the wheel plane that contains the wheel disc.
const PxPlane wheelPlane(wheelPoseAtZeroJounce.p, wheelPoseAtZeroJounce.rotate(sideAxis));
if(useDirectSweepResults)
{
// PT: this codepath fixes PX-2184 / PX-2170 / PX-2297
// We start from the results we want to obtain, i.e. the data provided by the sweeps:
jounce = maxCompression + radius - hitDist;
wheelBottomPos = wheelPlane.project(contactPt);
// PT: and then we re-derive other variables from them, to do the culling.
// This is only needed for touching hits.
if(rejectFromThresholds)
{
// Derive t & pos from above data
const PxF32 t = -jounce; // From "jounce = -t;" in original codepath
const PxVec3 pos = wheelBottomPos - suspDir*t; // From "wheelBottomPos = pos + suspDir*t;" in original codepath
//If the sweep started inside the hit plane then return false
const PxVec3 startPos = pos - suspDir*(radius + maxCompression);
if(hitPlane.n.dot(startPos) + hitPlane.d < 0.0f)
return false;
// PT: derive dir from "const PxVec3 pos = wheelPoseAtZeroJounce.p + dir*radius;" in original codepath.
// We need a normalized dir though so we skip the division by radius.
PxVec3 dir = (pos - wheelPoseAtZeroJounce.p);
dir.normalize();
//Now work out if we accept the hit.
//Compare dir with the suspension direction.
if(suspDir.dot(dir) < pointRejectAngleThresholdCosine)
return false;
}
}
else
{
//Intersect the plane of the wheel with the hit plane.
//This generates an intersection edge.
PxVec3 intersectionEdgeV, intersectionEdgeW;
const bool intersectPlaneSuccess = intersectPlanes(wheelPlane, hitPlane, intersectionEdgeV, intersectionEdgeW);
if(!intersectPlaneSuccess)
{
jounce = 0.0f;
wheelBottomPos = PxVec3(0,0,0);
return false;
}
//Compute the position on the intersection edge that is closest to the wheel centre.
PxVec3 closestPointOnIntersectionEdge;
{
const PxVec3& p = wheelPoseAtZeroJounce.p;
const PxVec3& w = intersectionEdgeW;
const PxVec3& v = intersectionEdgeV;
const PxF32 t = (p - v).dot(w);
closestPointOnIntersectionEdge = v + w*t;
}
//Compute the vector that joins the wheel centre to the intersection edge;
PxVec3 dir;
{
const PxF32 wheelCentreD = hitPlane.n.dot(wheelPoseAtZeroJounce.p) + hitPlane.d;
dir = ((wheelCentreD >= 0) ? closestPointOnIntersectionEdge - wheelPoseAtZeroJounce.p : wheelPoseAtZeroJounce.p - closestPointOnIntersectionEdge);
dir.normalize();
}
//Now work out if we accept the hit.
//Compare dir with the suspension direction.
if(rejectFromThresholds)
{
if(suspDir.dot(dir) < pointRejectAngleThresholdCosine)
return false;
}
//Compute the point on the disc diameter that will be the closest to the hit plane or the deepest inside the hit plane.
const PxVec3 pos = wheelPoseAtZeroJounce.p + dir*radius;
//If the sweep started inside the hit plane then return false
const PxVec3 startPos = pos - suspDir*(radius + maxCompression);
if(hitPlane.n.dot(startPos) + hitPlane.d < 0.0f)
return false;
//Now compute the maximum depth of the inside and outside discs against the plane.
PxF32 depth;
{
const PxVec3 latDir = wheelPoseAtZeroJounce.rotate(sideAxis);
const PxF32 signDot = computeSign(hitPlane.n.dot(latDir));
const PxVec3 deepestPos = pos - latDir*(signDot*0.5f*width);
depth = hitPlane.n.dot(deepestPos) + hitPlane.d;
}
//How far along the susp dir do we have to move to place the wheel exactly on the plane.
const PxF32 t = -depth/(hitPlane.n.dot(suspDir));
//+ve means that the spring is compressed
//-ve means that the spring is elongated.
jounce = -t;
//Compute a point at the bottom of the wheel that is at the centre.
wheelBottomPos = pos + suspDir*t;
}
return true;
}
static bool intersectCylinderPlane
(const PxTransform& carChassisTrnsfm,
const PxQuat& wheelLocalPoseRotation,
const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir, const PxF32 width, const PxF32 radius, const PxF32 maxCompression,
const PxPlane& hitPlane,
const PxVec3& sideAxis,
const bool rejectFromThresholds,
const PxF32 pointRejectAngleThresholdCosine,
const PxF32 normalRejectAngleThresholdCosine,
PxF32& jounce, PxVec3& wheelBottomPos,
const PxVec3& contactPt, float hitDist, bool useDirectSweepResults)
{
//Compute the pose of the wheel
PxTransform wheelPostsAtZeroJounce;
PxVec3 suspDir;
computeSuspensionSweep(
carChassisTrnsfm,
wheelLocalPoseRotation,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, 0.0f, 0.0f,
wheelPostsAtZeroJounce, suspDir);
//Perform the intersection.
return intersectCylinderPlane
(wheelPostsAtZeroJounce, suspDir,
width, radius, maxCompression,
hitPlane,
sideAxis,
rejectFromThresholds, pointRejectAngleThresholdCosine, normalRejectAngleThresholdCosine,
jounce, wheelBottomPos, contactPt, hitDist, useDirectSweepResults);
}
////////////////////////////////////////////////////////////////////////////
//Structures used to process blocks of 4 wheels: process the raycast result,
//compute the suspension and tire force, store a number of report variables
//such as tire slip, hit shape, hit material, friction etc.
////////////////////////////////////////////////////////////////////////////
class PxVehicleTireForceCalculator4
{
public:
const void* mShaderData[4];
PxVehicleComputeTireForce mShader;
private:
};
//This data structure is passed to processSuspTireWheels
//and represents the data that is logically constant across all sub-steps of each dt update.
struct ProcessSuspWheelTireConstData
{
//We are integrating dt over N sub-steps.
//timeFraction is 1/N.
PxF32 timeFraction;
//We are integrating dt over N sub-steps.
//subTimeStep is dt/N.
PxF32 subTimeStep;
PxF32 recipSubTimeStep;
//Gravitational acceleration vector
PxVec3 gravity;
//Length of gravitational acceleration vector (saves a square root each time we need it)
PxF32 gravityMagnitude;
//Reciprocal length of gravitational acceleration vector (saves a square root and divide each time we need it).
PxF32 recipGravityMagnitude;
//True for tanks, false for all other vehicle types.
//Used when computing the longitudinal and lateral slips.
bool isTank;
//Minimum denominator allowed in longitudinal slip computation.
PxF32 minLongSlipDenominator;
//Pointer to physx actor that represents the vehicle.
const PxRigidDynamic* vehActor;
//Pointer to table of friction values for each combination of material and tire type.
const PxVehicleDrivableSurfaceToTireFrictionPairs* frictionPairs;
//Flags related to wheel simulation (see PxVehicleWheelsSimFlags)
PxU32 wheelsSimFlags;
};
//This data structure is passed to processSuspTireWheels
//and represents the data that is physically constant across each sub-steps of each dt update.
struct ProcessSuspWheelTireInputData
{
public:
//True if the driver intends to pass drive torque to any wheel of the vehicle,
//even if none of the wheels in the block of 4 wheels processed in processSuspTireWheels are given drive torque.
//False if the driver does not intend the vehicle to accelerate.
//If the player intends to accelerate then no wheel will be given a sticky tire constraint.
//This data is actually logically constant.
bool isIntentionToAccelerate;
//True if a wheel has a non-zero diff torque, false if a wheel has zero diff torque.
//This data is actually logically constant.
const bool* isAccelApplied;
//True if a wheel has a non-zero brake torque, false if a wheel has zero brake torque.
//This data is actually logically constant.
const bool* isBrakeApplied;
//Steer angles of each wheel in radians.
//This data is actually logically constant.
const PxF32* steerAngles;
//True if the wheel is not disabled, false if wheel is disabled.
//This data is actually logically constant.
bool* activeWheelStates;
//Properties of the rigid body - transform.
//This data is actually logically constant.
PxTransform carChassisTrnsfm;
//Properties of the rigid body - linear velocity.
//This data is actually logically constant.
PxVec3 carChassisLinVel;
//Properties of the rigid body - angular velocity
//This data is actually logically constant.
PxVec3 carChassisAngVel;
//Properties of the wheel shapes at the last sweep.
const PxQuat* wheelLocalPoseRotations;
//Simulation data for the 4 wheels being processed in processSuspTireWheels
//This data is actually logically constant.
const PxVehicleWheels4SimData* vehWheels4SimData;
//Dynamics data for the 4 wheels being processed in processSuspTireWheels
//This data is a mixture of logically and physically constant.
//We could update some of the data in vehWheels4DynData in processSuspTireWheels
//but we choose to do it after. By specifying the non-constant data members explicitly
//in ProcessSuspWheelTireOutputData we are able to more easily keep a track of the
//constant and non-constant data members. After processSuspTireWheels is complete
//we explicitly transfer the updated data in ProcessSuspWheelTireOutputData to vehWheels4DynData.
//Examples are low long and lat forward speed timers.
const PxVehicleWheels4DynData* vehWheels4DynData;
//Shaders to calculate the tire forces.
//This data is actually logically constant.
const PxVehicleTireForceCalculator4* vehWheels4TireForceCalculator;
//Filter function to filter tire load.
//This data is actually logically constant.
const PxVehicleTireLoadFilterData* vehWheels4TireLoadFilterData;
//How many of the 4 wheels are real wheels (eg a 6-wheeled car has a
//block of 4 wheels then a 2nd block of 4 wheels with only 2 active wheels)
//This data is actually logically constant.
PxU32 numActiveWheels;
};
struct ProcessSuspWheelTireOutputData
{
public:
ProcessSuspWheelTireOutputData()
{
PxMemZero(this, sizeof(ProcessSuspWheelTireOutputData));
for(PxU32 i=0;i<4;i++)
{
isInAir[i]=true;
tireSurfaceTypes[i]=PxU32(PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN);
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//The following data is stored so that it may be later passed to PxVehicleWheelQueryResult
/////////////////////////////////////////////////////////////////////////////////////////////
//Raycast start [most recent raycast start coord or (0,0,0) if using a cached raycast]
PxVec3 suspLineStarts[4];
//Raycast start [most recent raycast direction or (0,0,0) if using a cached raycast]
PxVec3 suspLineDirs[4];
//Raycast start [most recent raycast length or 0 if using a cached raycast]
PxF32 suspLineLengths[4];
//False if wheel cannot touch the ground.
bool isInAir[4];
//Actor hit by most recent raycast, NULL if using a cached raycast.
PxActor* tireContactActors[4];
//Shape hit by most recent raycast, NULL if using a cached raycast.
PxShape* tireContactShapes[4];
//Material hit by most recent raycast, NULL if using a cached raycast.
PxMaterial* tireSurfaceMaterials[4];
//Surface type of material hit by most recent raycast, eSURFACE_TYPE_UNKNOWN if using a cached raycast.
PxU32 tireSurfaceTypes[4];
//Contact point of raycast against either fresh contact plane from fresh raycast or cached contact plane.
PxVec3 tireContactPoints[4];
//Contact normal of raycast against either fresh contact plane from fresh raycast or cached contact plane.
PxVec3 tireContactNormals[4];
//Friction experienced by tire (value from friction table for surface/tire type combos multiplied by friction vs slip graph)
PxF32 frictions[4];
//Jounce experienced by suspension against fresh or cached contact plane.
PxF32 jounces[4];
//Suspension force to be applied to rigid body.
PxF32 suspensionSpringForces[4];
//Longitudinal direction of tire in the ground contact plane.
PxVec3 tireLongitudinalDirs[4];
//Lateral direction of tire in the ground contact plane.
PxVec3 tireLateralDirs[4];
//Longitudinal slip.
PxF32 longSlips[4];
//Lateral slip.
PxF32 latSlips[4];
//Forward speed of rigid body along tire longitudinal direction at tire base.
//Used later to blend the integrated wheel rotation angle between rolling speed and computed speed
//when the wheel rotation speeds become unreliable at low forward speeds.
PxF32 forwardSpeeds[4];
//Torque to be applied to wheel as 1d rigid body. Taken from the longitudinal tire force.
//(Newton's 3rd law means the longitudinal tire force must have an equal and opposite force).
//(The lateral tire force is assumed to be absorbed by the suspension geometry).
PxF32 tireTorques[4];
//Force to be applied to rigid body (accumulated across all 4 wheels/tires/suspensions).
PxVec3 chassisForce;
//Torque to be applied to rigid body (accumulated across all 4 wheels/tires/suspensions).
PxVec3 chassisTorque;
//Updated time spend at low forward speed.
//Needs copied back to vehWheels4DynData
PxF32 newLowForwardSpeedTimers[4];
//Updated time spend at low lateral speed.
//Needs copied back to vehWheels4DynData
PxF32 newLowSideSpeedTimers[4];
//Constraint data for sticky tire constraints and suspension limit constraints.
//Needs copied back to vehWheels4DynData
PxVehicleConstraintShader::VehicleConstraintData vehConstraintData;
//Store the details of the raycast hit results so that they may be re-used
//next update in the event that no raycast is performed.
//If no raycast was performed then the cached values are just re-copied here
//so that they can be recycled without having to do further tests on whether
//raycasts were performed or not.
//Needs copied back to vehWheels4DynData after the last call to processSuspTireWheels.
//The union of cached hit data and susp raycast data means we don't want to overwrite the
//raycast data until we don't need it any more.
PxU32 cachedHitCounts[4];
PxPlane cachedHitPlanes[4];
PxF32 cachedHitDistances[4];
PxF32 cachedFrictionMultipliers[4];
PxU16 cachedHitQueryTypes[4];
//Store the details of the force applied to any dynamic actor hit by wheel raycasts.
PxRigidDynamic* hitActors[4];
PxVec3 hitActorForces[4];
PxVec3 hitActorForcePositions[4];
};
////////////////////////////////////////////////////////////////////////////
//Monster function to
//1. compute the tire/susp forces
//2. compute the torque to apply to the 1D rigid body wheel arising from the long tire force
//3. process the sticky tire friction constraints
// (monitor and increment the low long + lat speed timers, compute data for the sticky tire constraint if necessary)
//4. process the suspension limit constraints
// (monitor the suspension jounce versus the suspension travel limit, compute the data for the suspension limit constraint if necessary).
//5. record the contact plane so that it may be re-used in future updates in the absence of fresh raycasts.
//6. record telemetry data (if necessary) and record data for reporting such as hit material, hit normal etc.
////////////////////////////////////////////////////////////////////////////
namespace
{
struct LocalHitData
{
template<class T>
void setFrom(const T& hit)
{
actor = hit.actor;
shape = hit.shape;
position = hit.position;
normal = hit.normal;
distance = hit.distance;
faceIndex = hit.faceIndex;
}
PxRigidActor* actor;
PxShape* shape;
PxVec3 position;
PxVec3 normal;
PxF32 distance;
PxU32 faceIndex;
};
}
static void storeHit
(const ProcessSuspWheelTireConstData& constData, const ProcessSuspWheelTireInputData& inputData,
const PxU16 hitQueryType,
const LocalHitData& hit, const PxPlane& hitPlane,
const PxU32 i,
PxU32* hitCounts4,
PxF32* hitDistances4,
PxPlane* hitPlanes4,
PxF32* hitFrictionMultipliers4,
PxU16* hitQueryTypes4,
PxShape** hitContactShapes4,
PxRigidActor** hitContactActors4,
PxMaterial** hitContactMaterials4,
PxU32* hitSurfaceTypes4,
PxVec3* hitContactPoints4,
PxVec3* hitContactNormals4,
PxU32* cachedHitCounts,
PxPlane* cachedHitPlanes,
PxF32* cachedHitDistances,
PxF32* cachedFrictionMultipliers,
PxU16* cachedHitQueryTypes)
{
//Hit count.
hitCounts4[i] = 1;
//Hit distance.
hitDistances4[i] = hit.distance;
//Hit plane.
hitPlanes4[i] = hitPlane;
//Hit friction.
PxMaterial* material = NULL;
{
//Only get the material if the raycast started outside the hit shape.
PxBaseMaterial* baseMaterial = (hit.distance != 0.0f) ? hit.shape->getMaterialFromInternalFaceIndex(hit.faceIndex) : NULL;
PX_ASSERT(!baseMaterial || baseMaterial->getConcreteType()==PxConcreteType::eMATERIAL);
material = static_cast<PxMaterial*>(baseMaterial);
}
const PxVehicleDrivableSurfaceToTireFrictionPairs* PX_RESTRICT frictionPairs = constData.frictionPairs;
const PxU32 surfaceType = material ? frictionPairs->getSurfaceType(*material) : 0;
const PxVehicleTireData& tire = inputData.vehWheels4SimData->getTireData(i);
const PxU32 tireType = tire.mType;
const PxF32 frictionMultiplier = frictionPairs->getTypePairFriction(surfaceType, tireType);
PX_ASSERT(frictionMultiplier >= 0);
hitFrictionMultipliers4[i] = frictionMultiplier;
//Hit type.
hitQueryTypes4[i] = hitQueryType;
//Hit report.
hitContactShapes4[i] = hit.shape;
hitContactActors4[i] = hit.actor;
hitContactMaterials4[i] = material;
hitSurfaceTypes4[i] = surfaceType;
hitContactPoints4[i] = hit.position;
hitContactNormals4[i] = hit.normal;
//When we're finished here we need to copy this back to the vehicle.
cachedHitCounts[i] = 1;
cachedHitPlanes[i] = hitPlane;
cachedHitDistances[i] = hit.distance;
cachedFrictionMultipliers[i] = frictionMultiplier;
cachedHitQueryTypes[i] = hitQueryType;
}
static void processSuspTireWheels
(const PxU32 startWheelIndex,
const ProcessSuspWheelTireConstData& constData, const ProcessSuspWheelTireInputData& inputData,
const PxVec3& sideAxis,
const PxF32 pointRejectAngleThresholdCosine,
const PxF32 normalRejectAngleThresholdCosine,
const PxF32 maxHitActorAcceleration,
ProcessSuspWheelTireOutputData& outputData,
VehicleTelemetryDataContext* vehTelemetryDataContext)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(startWheelIndex);
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; //tzRaw.normalize(); in computeTireDirs threw a denorm exception on osx
#if PX_DEBUG_VEHICLE_ON
PX_ASSERT(0==(startWheelIndex & 3));
#endif
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eJOUNCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eSUSPFORCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRELOAD, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eNORMALIZED_TIRELOAD, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eNORM_TIRE_LONG_FORCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eNORM_TIRE_LAT_FORCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRE_LONG_SLIP, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRE_LAT_SLIP, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRE_FRICTION, vehTelemetryDataContext->wheelGraphData);
}
#endif
//Unpack the logically constant data.
const PxVec3& gravity=constData.gravity;
const PxF32 timeFraction=constData.timeFraction;
const PxF32 timeStep=constData.subTimeStep;
const PxF32 recipTimeStep=constData.recipSubTimeStep;
const PxF32 recipGravityMagnitude=constData.recipGravityMagnitude;
const PxF32 gravityMagnitude=constData.gravityMagnitude;
const bool isTank=constData.isTank;
const PxF32 minLongSlipDenominator=constData.minLongSlipDenominator;
const PxU32 wheelsSimFlags = constData.wheelsSimFlags;
//Unpack the input data (physically constant data).
const PxVehicleWheels4SimData& wheelsSimData=*inputData.vehWheels4SimData;
const PxVehicleWheels4DynData& wheelsDynData=*inputData.vehWheels4DynData;
const PxVehicleTireForceCalculator4& tireForceCalculator=*inputData.vehWheels4TireForceCalculator;
const PxVehicleTireLoadFilterData& tireLoadFilterData=*inputData.vehWheels4TireLoadFilterData;
//More constant data describing the 4 wheels under consideration.
const PxF32* PX_RESTRICT tireRestLoads=wheelsSimData.getTireRestLoadsArray();
const PxF32* PX_RESTRICT recipTireRestLoads=wheelsSimData.getRecipTireRestLoadsArray();
//Compute the right direction for later.
const PxTransform& carChassisTrnsfm=inputData.carChassisTrnsfm;
const PxVec3 latDir=inputData.carChassisTrnsfm.rotate(sideAxis);
//Unpack the linear and angular velocity of the rigid body.
const PxVec3& carChassisLinVel=inputData.carChassisLinVel;
const PxVec3& carChassisAngVel=inputData.carChassisAngVel;
//Wheel local poses
const PxQuat* PX_RESTRICT wheelLocalPoseRotations = inputData.wheelLocalPoseRotations;
//Inputs (accel, steer, brake).
const bool isIntentionToAccelerate=inputData.isIntentionToAccelerate;
const PxF32* steerAngles=inputData.steerAngles;
const bool* isBrakeApplied=inputData.isBrakeApplied;
const bool* isAccelApplied=inputData.isAccelApplied;
//Disabled/enabled wheel states.
const bool* activeWheelStates=inputData.activeWheelStates;
//Current low forward/side speed timers. Note that the updated timers
//are stored in newLowForwardSpeedTimers and newLowSideSpeedTimers.
const PxF32* PX_RESTRICT lowForwardSpeedTimers=wheelsDynData.mTireLowForwardSpeedTimers;
const PxF32* PX_RESTRICT lowSideSpeedTimers=wheelsDynData.mTireLowSideSpeedTimers;
//Susp jounces and speeds from previous call to processSuspTireWheels.
const PxF32* PX_RESTRICT prevJounces=wheelsDynData.mJounces;
//Unpack the output data (the data we are going to compute).
//Start with the data stored for reporting to PxVehicleWheelQueryResult.
//PxVec3* suspLineStarts=outputData.suspLineStarts;
//PxVec3* suspLineDirs=outputData.suspLineDirs;
//PxF32* suspLineLengths=outputData.suspLineLengths;
bool* isInAirs=outputData.isInAir;
PxActor** tireContactActors=outputData.tireContactActors;
PxShape** tireContactShapes=outputData.tireContactShapes;
PxMaterial** tireSurfaceMaterials=outputData.tireSurfaceMaterials;
PxU32* tireSurfaceTypes=outputData.tireSurfaceTypes;
PxVec3* tireContactPoints=outputData.tireContactPoints;
PxVec3* tireContactNormals=outputData.tireContactNormals;
PxF32* frictions=outputData.frictions;
PxF32* jounces=outputData.jounces;
PxF32* suspensionSpringForces=outputData.suspensionSpringForces;
PxVec3* tireLongitudinalDirs=outputData.tireLongitudinalDirs;
PxVec3* tireLateralDirs=outputData.tireLateralDirs;
PxF32* longSlips=outputData.longSlips;
PxF32* latSlips=outputData.latSlips;
//Now unpack the forward speeds that are used later to blend the integrated wheel
//rotation angle between rolling speed and computed speed when the wheel rotation
//speeds become unreliable at low forward speeds.
PxF32* forwardSpeeds=outputData.forwardSpeeds;
//Unpack the real outputs of this function (wheel torques to apply to 1d rigid body wheel and forces/torques
//to apply to 3d rigid body chassis).
PxF32* tireTorques=outputData.tireTorques;
PxVec3& chassisForce=outputData.chassisForce;
PxVec3& chassisTorque=outputData.chassisTorque;
//Unpack the low speed timers that will be computed.
PxF32* newLowForwardSpeedTimers=outputData.newLowForwardSpeedTimers;
PxF32* newLowSideSpeedTimers=outputData.newLowSideSpeedTimers;
//Unpack the constraint data for suspensions limit and sticky tire constraints.
//Susp limits.
bool* suspLimitActiveFlags=outputData.vehConstraintData.mSuspLimitData.mActiveFlags;
PxVec3* suspLimitDirs=outputData.vehConstraintData.mSuspLimitData.mDirs;
PxVec3* suspLimitCMOffsets=outputData.vehConstraintData.mSuspLimitData.mCMOffsets;
PxF32* suspLimitErrors=outputData.vehConstraintData.mSuspLimitData.mErrors;
//Longitudinal sticky tires.
bool* stickyTireForwardActiveFlags=outputData.vehConstraintData.mStickyTireForwardData.mActiveFlags;
PxVec3* stickyTireForwardDirs=outputData.vehConstraintData.mStickyTireForwardData.mDirs;
PxVec3* stickyTireForwardCMOffsets=outputData.vehConstraintData.mStickyTireForwardData.mCMOffsets;
PxF32* stickyTireForwardTargetSpeeds=outputData.vehConstraintData.mStickyTireForwardData.mTargetSpeeds;
//Lateral sticky tires.
bool* stickyTireSideActiveFlags=outputData.vehConstraintData.mStickyTireSideData.mActiveFlags;
PxVec3* stickyTireSideDirs=outputData.vehConstraintData.mStickyTireSideData.mDirs;
PxVec3* stickyTireSideCMOffsets=outputData.vehConstraintData.mStickyTireSideData.mCMOffsets;
PxF32* stickyTireSideTargetSpeeds=outputData.vehConstraintData.mStickyTireSideData.mTargetSpeeds;
//Hit data. Store the contact data so it can be reused.
PxU32* cachedHitCounts=outputData.cachedHitCounts;
PxPlane* cachedHitPlanes=outputData.cachedHitPlanes;
PxF32* cachedHitDistances=outputData.cachedHitDistances;
PxF32* cachedFrictionMultipliers=outputData.cachedFrictionMultipliers;
PxU16* cachedHitQueryTypes=outputData.cachedHitQueryTypes;
//Hit actor data.
PxRigidDynamic** hitActors=outputData.hitActors;
PxVec3* hitActorForces=outputData.hitActorForces;
PxVec3* hitActorForcePositions=outputData.hitActorForcePositions;
//Set the cmass rotation straight away (we might need this, we might not but we don't know that yet so just set it).
outputData.vehConstraintData.mCMassRotation = constData.vehActor->getCMassLocalPose().q;
//Compute all the hit data (counts, distances, planes, frictions, actors, shapes, materials etc etc).
//If we just did a raycast/sweep then we need to compute all this from the hit reports.
//If we are using cached raycast/sweep results then just copy the cached hit result data.
PxU32 hitCounts4[4];
PxF32 hitDistances4[4];
PxPlane hitPlanes4[4];
PxF32 hitFrictionMultipliers4[4];
PxU16 hitQueryTypes4[4];
PxShape* hitContactShapes4[4];
PxRigidActor* hitContactActors4[4];
PxMaterial* hitContactMaterials4[4];
PxU32 hitSurfaceTypes4[4];
PxVec3 hitContactPoints4[4];
PxVec3 hitContactNormals4[4];
const PxRaycastBuffer* PX_RESTRICT raycastResults=inputData.vehWheels4DynData->mRaycastResults;
const PxSweepBuffer* PX_RESTRICT sweepResults=inputData.vehWheels4DynData->mSweepResults;
if(raycastResults || sweepResults)
{
const PxU16 queryType = raycastResults ? 0u : 1u;
//If we have a blocking hit then always take that.
//If we don't have a blocking hit then search for the "best" hit from all the touches.
for(PxU32 i=0;i<inputData.numActiveWheels;i++)
{
//Test that raycasts issue blocking hits.
PX_CHECK_AND_RETURN(!raycastResults || (0 == raycastResults[i].nbTouches), "Raycasts must generate blocking hits");
PX_CHECK_MSG(!sweepResults || (PxBatchQueryStatus::getStatus(sweepResults[i]) != PxBatchQueryStatus::eOVERFLOW), "PxVehicleUpdate::suspensionSweeps - batched sweep touch array not large enough to perform sweep.");
PxU32 hitCount = 0;
if ((raycastResults && raycastResults[i].hasBlock) || (sweepResults && sweepResults[i].hasBlock))
{
//We have a blocking hit so use that.
LocalHitData hit;
if(raycastResults)
hit.setFrom(raycastResults[i].block);
else
hit.setFrom(sweepResults[i].block);
//Test that the hit actor isn't the vehicle itself.
PX_CHECK_AND_RETURN(constData.vehActor != hit.actor, "Vehicle raycast has hit itself. Please check the filter data to avoid this.");
//Reject if the sweep started inside the hit shape.
if (hit.distance != 0)
{
//Compute the plane of the hit.
const PxPlane hitPlane(hit.position, hit.normal);
//Store the hit data in the various arrays.
storeHit(constData, inputData,
queryType,
hit, hitPlane,
i,
hitCounts4,
hitDistances4,
hitPlanes4,
hitFrictionMultipliers4,
hitQueryTypes4,
hitContactShapes4,
hitContactActors4,
hitContactMaterials4,
hitSurfaceTypes4,
hitContactPoints4,
hitContactNormals4,
cachedHitCounts,
cachedHitPlanes,
cachedHitDistances,
cachedFrictionMultipliers,
cachedHitQueryTypes);
hitCount = 1;
}
}
else if (sweepResults && sweepResults[i].nbTouches)
{
//We need wheel info so that we can analyse the hit and reject/accept it.
//Get what we need now.
const PxVehicleWheelData& wheel = wheelsSimData.getWheelData(i);
const PxVehicleSuspensionData& susp = wheelsSimData.getSuspensionData(i);
const PxVec3& bodySpaceWheelCentreOffset = wheelsSimData.getWheelCentreOffset(i);
const PxVec3& bodySpaceSuspTravelDir = wheelsSimData.getSuspTravelDirection(i);
const PxQuat& wheelLocalPoseRotation = wheelLocalPoseRotations[i];
const PxF32 width = wheel.mWidth;
const PxF32 radius = wheel.mRadius;
const PxF32 maxBounce = susp.mMaxCompression;
//Compute the global pose of the wheel at zero jounce.
PxTransform suspPose;
PxVec3 suspDir;
computeSuspensionSweep(
carChassisTrnsfm,
wheelLocalPoseRotation,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, 0.0f, 0.0f,
suspPose, suspDir);
//Iterate over all touches and cache the deepest hit that we accept.
PxF32 bestTouchDistance = -PX_MAX_F32;
for (PxU32 j = 0; j < sweepResults[i].nbTouches; j++)
{
//Get the next candidate hit.
LocalHitData hit;
hit.setFrom(sweepResults[i].touches[j]);
//Test that the hit actor isn't the vehicle itself.
PX_CHECK_AND_RETURN(constData.vehActor != hit.actor, "Vehicle raycast has hit itself. Please check the filter data to avoid this.");
//Reject if the sweep started inside the hit shape.
if (hit.distance != 0.0f)
{
//Compute the plane of the hit.
const PxPlane hitPlane(hit.position, hit.normal);
const bool useDirectSweepResults = (wheelsSimFlags & PxVehicleWheelsSimFlag::eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST)!=0;
//Intersect the wheel disc with the hit plane and compute the jounce required to move the wheel free of the hit plane.
PxF32 dx;
PxVec3 wheelBottomPos;
const bool successIntersection =
intersectCylinderPlane
(suspPose, suspDir,
width, radius, maxBounce,
hitPlane,
sideAxis,
true, pointRejectAngleThresholdCosine, normalRejectAngleThresholdCosine,
dx, wheelBottomPos, hit.position, hit.distance, useDirectSweepResults);
//If we accept the intersection and it requires more jounce than previously encountered then
//store the hit.
if (successIntersection && dx > bestTouchDistance)
{
storeHit(constData, inputData,
queryType,
hit, hitPlane,
i,
hitCounts4,
hitDistances4,
hitPlanes4,
hitFrictionMultipliers4,
hitQueryTypes4,
hitContactShapes4,
hitContactActors4,
hitContactMaterials4,
hitSurfaceTypes4,
hitContactPoints4,
hitContactNormals4,
cachedHitCounts,
cachedHitPlanes,
cachedHitDistances,
cachedFrictionMultipliers,
cachedHitQueryTypes);
bestTouchDistance = dx;
hitCount = 1;
}
}
}
}
if(0 == hitCount)
{
hitCounts4[i]=0;
hitDistances4[i]=0;
hitPlanes4[i]=PxPlane(PxVec3(0,0,0),0);
hitFrictionMultipliers4[i]=0;
hitQueryTypes4[i]=0u;
hitContactShapes4[i]=NULL;
hitContactActors4[i]=NULL;
hitContactMaterials4[i]=NULL;
hitSurfaceTypes4[i]=PxU32(PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN);
hitContactPoints4[i]=PxVec3(0,0,0);
hitContactNormals4[i]=PxVec3(0,0,0);
//When we're finished here we need to copy this back to the vehicle.
cachedHitCounts[i]=0;
cachedHitPlanes[i]= PxPlane(PxVec3(0,0,0),0);
cachedHitDistances[i]=0;
cachedFrictionMultipliers[i]=0;
cachedHitQueryTypes[i] = 0u;
}
}
}
else
{
//If we have no sq results then we must have a cached raycast hit result.
const PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult& cachedHitResult =
reinterpret_cast<const PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult&>(inputData.vehWheels4DynData->mQueryOrCachedHitResults);
for(PxU32 i=0;i<inputData.numActiveWheels;i++)
{
hitCounts4[i]=cachedHitResult.mCounts[i];
hitDistances4[i]=cachedHitResult.mDistances[i];
hitPlanes4[i]=cachedHitResult.mPlanes[i];
hitFrictionMultipliers4[i]=cachedHitResult.mFrictionMultipliers[i];
hitQueryTypes4[i] = cachedHitResult.mQueryTypes[i];
hitContactShapes4[i]=NULL;
hitContactActors4[i]=NULL;
hitContactMaterials4[i]=NULL;
hitSurfaceTypes4[i]=PxU32(PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN);
hitContactPoints4[i]=PxVec3(0,0,0);
hitContactNormals4[i]=PxVec3(0,0,0);
//When we're finished here we need to copy this back to the vehicle.
cachedHitCounts[i]=cachedHitResult.mCounts[i];
cachedHitPlanes[i]=cachedHitResult.mPlanes[i];
cachedHitDistances[i]=cachedHitResult.mDistances[i];
cachedFrictionMultipliers[i]=cachedHitResult.mFrictionMultipliers[i];
cachedHitQueryTypes[i]=cachedHitResult.mQueryTypes[i];
}
}
//Iterate over all 4 wheels.
for(PxU32 i=0;i<4;i++)
{
//Constant data of the ith wheel.
const PxVehicleWheelData& wheel=wheelsSimData.getWheelData(i);
const PxVehicleSuspensionData& susp=wheelsSimData.getSuspensionData(i);
const PxVehicleTireData& tire=wheelsSimData.getTireData(i);
const PxVec3& bodySpaceWheelCentreOffset=wheelsSimData.getWheelCentreOffset(i);
const PxVec3& bodySpaceSuspTravelDir=wheelsSimData.getSuspTravelDirection(i);
//Take a copy of the low forward/side speed timer of the ith wheel (time spent at low forward/side speed)
//Do this so we can quickly tell if the low/side forward speed timer changes.
newLowForwardSpeedTimers[i]=lowForwardSpeedTimers[i];
newLowSideSpeedTimers[i]=lowSideSpeedTimers[i];
//Reset the graph of the jounce to max droop.
//This will get updated as we learn more about the suspension.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataSuspJounce(startWheelIndex, i,-susp.mMaxDroop, vehTelemetryDataContext->wheelGraphData);
#endif
//Reset the jounce to max droop.
//This will get updated as we learn more about the suspension and tire.
PxF32 jounce=-susp.mMaxDroop;
jounces[i]=jounce;
//Deactivate the sticky tire and susp limit constraint.
//These will get updated as we learn more about the suspension and tire.
suspLimitActiveFlags[i]=false;
suspLimitErrors[i]=0.0f;
stickyTireForwardActiveFlags[i]=false;
stickyTireForwardTargetSpeeds[i]=0;
stickyTireSideActiveFlags[i]=false;
stickyTireSideTargetSpeeds[i]=0;
//The vehicle is in the air until we know otherwise.
isInAirs[i]=true;
//If there has been a hit then compute the suspension force and tire load.
//Ignore the hit if the raycast starts inside the hit shape (eg wheel completely underneath surface of a heightfield).
const bool activeWheelState=activeWheelStates[i];
const PxU32 numHits=hitCounts4[i];
const PxVec3 hitNorm(hitPlanes4[i].n);
const PxVec3 w = carChassisTrnsfm.q.rotate(bodySpaceSuspTravelDir);
if(activeWheelState && numHits > 0 && hitDistances4[i] != 0.0f && hitNorm.dot(w) < 0.0f)
{
//Get the friction multiplier from the combination of surface type and tire type.
const PxF32 frictionMultiplier=hitFrictionMultipliers4[i];
PX_ASSERT(frictionMultiplier>=0);
PxF32 dx;
PxVec3 wheelBottomPos;
bool successIntersection = true;
if(0 == hitQueryTypes4[i])
{
successIntersection = intersectRayPlane
(carChassisTrnsfm,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, wheel.mWidth, wheel.mRadius, susp.mMaxCompression,
hitPlanes4[i],
dx, wheelBottomPos);
}
else
{
const bool useDirectSweepResults = (wheelsSimFlags & PxVehicleWheelsSimFlag::eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST)!=0;
PX_ASSERT(1 == hitQueryTypes4[i]);
successIntersection = intersectCylinderPlane
(carChassisTrnsfm,
wheelLocalPoseRotations[i],
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, wheel.mWidth, wheel.mRadius, susp.mMaxCompression,
hitPlanes4[i],
sideAxis,
false, 0.0f, 0.0f,
dx, wheelBottomPos, hitContactPoints4[i], hitDistances4[i], useDirectSweepResults);
}
//If the spring is elongated past its max droop then the wheel isn't touching the ground.
//In this case the spring offers zero force and provides no support for the chassis/sprung mass.
//Only carry on computing the spring force if the wheel is touching the ground.
PX_ASSERT(susp.mMaxCompression>=0);
PX_ASSERT(susp.mMaxDroop>=0);
if(dx > -susp.mMaxDroop && successIntersection)
{
//We can record the hit shape, hit actor, hit material, hit surface type, hit point, and hit normal now because we've got a hit.
tireContactShapes[i]=hitContactShapes4[i];
tireContactActors[i]=hitContactActors4[i];
tireSurfaceMaterials[i]=hitContactMaterials4[i];
tireSurfaceTypes[i]=hitSurfaceTypes4[i];
tireContactPoints[i]=hitContactPoints4[i];
tireContactNormals[i]=hitContactNormals4[i];
//Clamp the spring compression so that it is never greater than the max bounce.
//Apply the susp limit constraint if the spring compression is greater than the max bounce.
suspLimitErrors[i] = (w.dot(hitNorm))*(-dx + susp.mMaxCompression);
suspLimitActiveFlags[i] = (dx > susp.mMaxCompression);
suspLimitCMOffsets[i] = bodySpaceWheelCentreOffset;
suspLimitDirs[i] = bodySpaceSuspTravelDir;
jounce=PxMin(dx,susp.mMaxCompression);
//Store the jounce (having a local copy avoids lhs).
jounces[i]=jounce;
//Store the jounce in the graph.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataSuspJounce(startWheelIndex, i,jounce, vehTelemetryDataContext->wheelGraphData);
#endif
//Compute the speed of the rigid body along the suspension travel dir at the
//bottom of the wheel.
const PxVec3 r=wheelBottomPos-carChassisTrnsfm.p;
PxVec3 wheelBottomVel=carChassisLinVel;
wheelBottomVel+=carChassisAngVel.cross(r);
//Modify the relative velocity at the wheel contact point if the hit actor is a dynamic.
PxRigidDynamic* dynamicHitActor=NULL;
PxVec3 hitActorVelocity(0,0,0);
if(hitContactActors4[i] && ((dynamicHitActor = hitContactActors4[i]->is<PxRigidDynamic>()) != NULL))
{
hitActorVelocity = PxRigidBodyExt::getVelocityAtPos(*dynamicHitActor,wheelBottomPos);
wheelBottomVel -= hitActorVelocity;
}
//Get the speed of the jounce.
PxF32 jounceSpeed;
PxF32 previousJounce;
if (PX_MAX_F32 != prevJounces[i])
{
jounceSpeed = (jounce - prevJounces[i])*recipTimeStep;
previousJounce = prevJounces[i];
}
else
{
jounceSpeed = 0.0f;
previousJounce = jounce;
}
const PxF32 gravitySuspDir = gravity.dot(w);
bool computeSuspensionForce = true;
if ((wheelsSimFlags & PxVehicleWheelsSimFlag::eLIMIT_SUSPENSION_EXPANSION_VELOCITY) && (jounceSpeed < 0.0f) && (jounce <= 0.0f))
{
//Suspension is expanding and not compressed (the latter helps to avoid the suspension not being able to carry the sprung mass
//when many substeps are used because the expected velocity from the suspension spring might always be slightly below the velocity
//needed to reach the new jounce).
//Check if the suspension can expand fast enough to keep pushing the wheel to the ground.
const PxF32 distToMaxDroop = previousJounce + susp.mMaxDroop; // signs chosen to point along the suspension travel direction
//The vehicle is considered to be in air until the suspension expands to the ground, thus the max droop is used
//as the rest length of the spring.
//Without the suspension elongating, the wheel would end up in the air. Compute the force that pushes the
//wheel towards the ground. Note that gravity is ignored here as it applies to chassis and wheel equally.
//Furthermore, the suspension start point (sprung mass) and the wheel are assumed to move with roughly the
//same velocity, hence, damping is ignored too.
const PxF32 springForceAlongSuspDir = distToMaxDroop * susp.mSpringStrength;
const PxF32 suspDirVelWheel = ((springForceAlongSuspDir / wheel.mMass) + gravitySuspDir) * timeStep;
if (jounceSpeed < (-suspDirVelWheel))
{
//The suspension can not push the wheel fast enough onto the ground, so the vehicle will leave the ground.
//Hence, no spring forces should get applied.
//note: could consider applying -springForceAlongSuspDir to the chassis but this is not done in the other
// scenarios where the vehicle is in the air either.
computeSuspensionForce = false;
jounce = PxMin(previousJounce - (suspDirVelWheel * timeStep), susp.mMaxCompression);
}
}
if (computeSuspensionForce)
{
//We know that the vehicle is not in the air.
isInAirs[i]=false;
//Decompose gravity into a term along w and a term perpendicular to w
//gravity = w*alpha + T*beta
//where T is a unit vector perpendicular to w; alpha and beta are scalars.
//The vector w*alpha*mass is the component of gravitational force that acts along the spring direction.
//The vector T*beta*mass is the component of gravitational force that will be resisted by the spring
//because the spring only supports a single degree of freedom along w.
//We only really need to know T*beta so don't bother calculating T or beta.
const PxF32 alpha = PxMax(0.0f, gravitySuspDir);
const PxVec3 TTimesBeta = (0.0f != alpha) ? gravity - w*alpha : PxVec3(0,0,0);
//Compute the magnitude of the force along w.
PxF32 suspensionForceW =
PxMax(0.0f,
susp.mSprungMass*alpha + //force to support sprung mass at zero jounce
susp.mSpringStrength*jounce); //linear spring
suspensionForceW += jounceSpeed * susp.mSpringDamperRate; //damping
//Compute the total force acting on the suspension.
//Remember that the spring force acts along -w.
//Remember to account for the term perpendicular to w and that it acts along -TTimesBeta
PxF32 suspensionForceMag;
if(wheelsSimFlags & PxVehicleWheelsSimFlag::eDISABLE_SUSPENSION_FORCE_PROJECTION)
suspensionForceMag = suspensionForceW - hitNorm.dot(TTimesBeta*susp.mSprungMass);
else
suspensionForceMag = hitNorm.dot(-w*suspensionForceW - TTimesBeta*susp.mSprungMass);
//Apply the opposite force to the hit object.
//Clamp suspensionForceMag if required.
if (dynamicHitActor && !(dynamicHitActor->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC))
{
const PxF32 dynamicActorInvMass = dynamicHitActor->getInvMass();
const PxF32 dynamicActorMass = dynamicHitActor->getMass();
const PxF32 forceSign = computeSign(suspensionForceMag);
const PxF32 forceMag = PxAbs(suspensionForceMag);
const PxF32 clampedAccelMag = PxMin(forceMag*dynamicActorInvMass, maxHitActorAcceleration);
const PxF32 clampedForceMag = clampedAccelMag*dynamicActorMass*forceSign;
PX_ASSERT(clampedForceMag*suspensionForceMag >= 0.0f);
suspensionForceMag = clampedForceMag;
hitActors[i] = dynamicHitActor;
hitActorForces[i] = hitNorm*(-clampedForceMag*timeFraction);
hitActorForcePositions[i] = hitContactPoints4[i];
}
//Store the spring force now (having a local copy avoids lhs).
suspensionSpringForces[i] = suspensionForceMag;
//Store the spring force in the graph.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataSuspForce(startWheelIndex, i, suspensionForceMag, vehTelemetryDataContext->wheelGraphData);
#endif
//Suspension force can be computed now.
const PxVec3 suspensionForce = hitNorm*suspensionForceMag;
//Torque from spring force.
const PxVec3 suspForceCMOffset = carChassisTrnsfm.rotate(wheelsSimData.getSuspForceAppPointOffset(i));
const PxVec3 suspensionTorque = suspForceCMOffset.cross(suspensionForce);
//Add the suspension force/torque to the chassis force/torque.
chassisForce+=suspensionForce;
chassisTorque+=suspensionTorque;
//Now compute the tire load.
const PxF32 tireLoad = suspensionForceMag;
//Normalize the tire load
//Now work out the normalized tire load.
const PxF32 normalisedTireLoad=tireLoad*recipGravityMagnitude*recipTireRestLoads[i];
//Filter the normalized tire load and compute the filtered tire load too.
const PxF32 filteredNormalisedTireLoad=computeFilteredNormalisedTireLoad(tireLoadFilterData,normalisedTireLoad);
const PxF32 filteredTireLoad=filteredNormalisedTireLoad*gravityMagnitude*tireRestLoads[i];
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
updateGraphDataTireLoad(startWheelIndex,i,filteredTireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataNormTireLoad(startWheelIndex,i,filteredNormalisedTireLoad, vehTelemetryDataContext->wheelGraphData);
}
#endif
//Compute the lateral and longitudinal tire axes in the ground plane.
PxVec3 tireLongDir;
PxVec3 tireLatDir;
computeTireDirs(latDir,hitNorm,steerAngles[i],tireLongDir,tireLatDir);
//Store the tire long and lat dirs now (having a local copy avoids lhs).
tireLongitudinalDirs[i]= tireLongDir;
tireLateralDirs[i]=tireLatDir;
//Now compute the speeds along each of the tire axes.
const PxF32 tireLongSpeed=wheelBottomVel.dot(tireLongDir);
const PxF32 tireLatSpeed=wheelBottomVel.dot(tireLatDir);
//Store the forward speed (having a local copy avoids lhs).
forwardSpeeds[i]=tireLongSpeed;
//Now compute the slips along each axes.
const bool hasAccel=isAccelApplied[i];
const bool hasBrake=isBrakeApplied[i];
const PxF32 wheelOmega=wheelsDynData.mWheelSpeeds[i];
const PxF32 wheelRadius=wheel.mRadius;
PxF32 longSlip;
PxF32 latSlip;
computeTireSlips
(tireLongSpeed,tireLatSpeed,wheelOmega,wheelRadius,minLongSlipDenominator,
hasAccel,hasBrake,
isTank,
longSlip,latSlip);
//Store the lat and long slip (having local copies avoids lhs).
longSlips[i]=longSlip;
latSlips[i]=latSlip;
//Camber angle.
PxF32 camber=susp.mCamberAtRest;
if(jounce>0)
{
camber += jounce*susp.mCamberAtMaxCompression*susp.getRecipMaxCompression();
}
else
{
camber -= jounce*susp.mCamberAtMaxDroop*susp.getRecipMaxDroop();
}
//Compute the friction that will be experienced by the tire.
PxF32 friction;
computeTireFriction(tire,longSlip,frictionMultiplier,friction);
//Store the friction (having a local copy avoids lhs).
frictions[i]=friction;
if(filteredTireLoad*frictionMultiplier>0)
{
//Either tire forces or sticky tire friction constraint will be applied here.
const PxVec3 tireForceCMOffset = carChassisTrnsfm.rotate(wheelsSimData.getTireForceAppPointOffset(i));
PxF32 newLowForwardSpeedTimer;
{
//check the accel value here
//Update low forward speed timer.
const PxF32 recipWheelRadius=wheel.getRecipRadius();
newLowForwardSpeedTimer=newLowForwardSpeedTimers[i];
updateLowForwardSpeedTimer(tireLongSpeed,wheelOmega,wheelRadius,recipWheelRadius,isIntentionToAccelerate,timeStep,newLowForwardSpeedTimer);
//Activate sticky tire forward friction constraint if required.
//If sticky tire friction is active then set the longitudinal slip to zero because
//the sticky tire constraint will take care of the longitudinal component of motion.
bool stickyTireForwardActiveFlag=false;
PxF32 stickyTireForwardTargetSpeed=0.0f;
activateStickyFrictionForwardConstraint(tireLongSpeed,wheelOmega,newLowForwardSpeedTimer,isIntentionToAccelerate,stickyTireForwardActiveFlag,stickyTireForwardTargetSpeed);
stickyTireForwardTargetSpeed += hitActorVelocity.dot(tireLongDir);
//Store the sticky tire data (having local copies avoids lhs).
newLowForwardSpeedTimers[i] = newLowForwardSpeedTimer;
stickyTireForwardActiveFlags[i]=stickyTireForwardActiveFlag;
stickyTireForwardTargetSpeeds[i]=stickyTireForwardTargetSpeed;
stickyTireForwardDirs[i]=tireLongDir;
stickyTireForwardCMOffsets[i]=tireForceCMOffset;
//Deactivate the long slip if sticky tire constraint is active.
longSlip=(!stickyTireForwardActiveFlag ? longSlip : 0.0f);
//Store the long slip (having local copies avoids lhs).
longSlips[i]=longSlip;
}
PxF32 newLowSideSpeedTimer;
{
//check the accel value here
//Update low side speed timer.
newLowSideSpeedTimer=newLowSideSpeedTimers[i];
updateLowSideSpeedTimer(tireLatSpeed,isIntentionToAccelerate,timeStep,newLowSideSpeedTimer);
//Activate sticky tire side friction constraint if required.
//If sticky tire friction is active then set the lateral slip to zero because
//the sticky tire constraint will take care of the lateral component of motion.
bool stickyTireSideActiveFlag=false;
PxF32 stickyTireSideTargetSpeed=0.0f;
activateStickyFrictionSideConstraint(tireLatSpeed,newLowForwardSpeedTimer,newLowSideSpeedTimer,isIntentionToAccelerate,stickyTireSideActiveFlag,stickyTireSideTargetSpeed);
stickyTireSideTargetSpeed += hitActorVelocity.dot(tireLatDir);
//Store the sticky tire data (having local copies avoids lhs).
newLowSideSpeedTimers[i] = newLowSideSpeedTimer;
stickyTireSideActiveFlags[i]=stickyTireSideActiveFlag;
stickyTireSideTargetSpeeds[i]=stickyTireSideTargetSpeed;
stickyTireSideDirs[i]=tireLatDir;
stickyTireSideCMOffsets[i]=tireForceCMOffset;
//Deactivate the lat slip if sticky tire constraint is active.
latSlip=(!stickyTireSideActiveFlag ? latSlip : 0.0f);
//Store the long slip (having local copies avoids lhs).
latSlips[i]=latSlip;
}
//Compute the various tire torques.
PxF32 wheelTorque=0;
PxF32 tireLongForceMag=0;
PxF32 tireLatForceMag=0;
PxF32 tireAlignMoment=0;
const PxF32 restTireLoad=gravityMagnitude*tireRestLoads[i];
const PxF32 recipWheelRadius=wheel.getRecipRadius();
tireForceCalculator.mShader(
tireForceCalculator.mShaderData[i],
friction,
longSlip,latSlip,camber,
wheelOmega,wheelRadius,recipWheelRadius,
restTireLoad,filteredNormalisedTireLoad,filteredTireLoad,
gravityMagnitude, recipGravityMagnitude,
wheelTorque,tireLongForceMag,tireLatForceMag,tireAlignMoment);
//Store the tire torque ((having a local copy avoids lhs).
tireTorques[i]=wheelTorque;
//Apply the torque to the chassis.
//Compute the tire force to apply to the chassis.
const PxVec3 tireLongForce=tireLongDir*tireLongForceMag;
const PxVec3 tireLatForce=tireLatDir*tireLatForceMag;
const PxVec3 tireForce=tireLongForce+tireLatForce;
//Compute the torque to apply to the chassis.
const PxVec3 tireTorque=tireForceCMOffset.cross(tireForce);
//Add all the forces/torques together.
chassisForce+=tireForce;
chassisTorque+=tireTorque;
//Graph all the data we just computed.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
vehTelemetryDataContext->tireForceAppPoints[i] = carChassisTrnsfm.p + tireForceCMOffset;
vehTelemetryDataContext->suspForceAppPoints[i] = carChassisTrnsfm.p + suspForceCMOffset;
updateGraphDataNormLongTireForce(startWheelIndex, i, PxAbs(tireLongForceMag)*normalisedTireLoad/tireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataNormLatTireForce(startWheelIndex, i, PxAbs(tireLatForceMag)*normalisedTireLoad/tireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataNormTireAligningMoment(startWheelIndex, i, tireAlignMoment*normalisedTireLoad/tireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataLongTireSlip(startWheelIndex, i,longSlips[i], vehTelemetryDataContext->wheelGraphData);
updateGraphDataLatTireSlip(startWheelIndex, i,latSlips[i], vehTelemetryDataContext->wheelGraphData);
updateGraphDataTireFriction(startWheelIndex, i,frictions[i], vehTelemetryDataContext->wheelGraphData);
}
#endif
}//filteredTireLoad*frictionMultiplier>0
}//if(computeSuspensionForce)
}//if(dx > -susp.mMaxCompression)
}//if(numHits>0)
}//i
}
void procesAntiRollSuspension
(const PxVehicleWheelsSimData& wheelsSimData,
const PxTransform& carChassisTransform, const PxWheelQueryResult* wheelQueryResults,
PxVec3& chassisTorque)
{
const PxU32 numAntiRollBars = wheelsSimData.getNbAntiRollBars();
for(PxU32 i = 0; i < numAntiRollBars; i++)
{
const PxVehicleAntiRollBarData& antiRoll = wheelsSimData.getAntiRollBarData(i);
const PxU32 w0 = antiRoll.mWheel0;
const PxU32 w1 = antiRoll.mWheel1;
//At least one wheel must be on the ground for the anti-roll to work.
const bool w0InAir = wheelQueryResults[w0].isInAir;
const bool w1InAir = wheelQueryResults[w1].isInAir;
if(!w0InAir || !w1InAir)
{
//Compute the difference in jounce and compute the force.
const PxF32 w0Jounce = wheelQueryResults[w0].suspJounce;
const PxF32 w1Jounce = wheelQueryResults[w1].suspJounce;
const PxF32 antiRollForceMag = (w0Jounce - w1Jounce)*antiRoll.mStiffness;
//Apply the antiRollForce postiviely to wheel0, negatively to wheel 1
PxU32 wheelIds[2] = {0xffffffff, 0xffffffff};
PxF32 antiRollForceMags[2];
PxU32 numWheelIds = 0;
if(!w0InAir)
{
wheelIds[numWheelIds] = w0;
antiRollForceMags[numWheelIds] = -antiRollForceMag;
numWheelIds++;
}
if(!w1InAir)
{
wheelIds[numWheelIds] = w1;
antiRollForceMags[numWheelIds] = +antiRollForceMag;
numWheelIds++;
}
for(PxU32 j = 0; j < numWheelIds; j++)
{
const PxU32 wheelId = wheelIds[j];
//Force
const PxVec3 suspDir = carChassisTransform.q.rotate(wheelsSimData.getSuspTravelDirection(wheelId));
const PxVec3 antiRollForce = suspDir*antiRollForceMags[j];
//Torque
const PxVec3 r = carChassisTransform.q.rotate(wheelsSimData.getSuspForceAppPointOffset(wheelId));
const PxVec3 antiRollTorque = r.cross(antiRollForce);
chassisTorque += antiRollTorque;
}
}
}
}
////////////////////////////////////////////////////////////////////////////
//Set the low long speed timers computed in processSuspTireWheels
//Call immediately after completing processSuspTireWheels.
////////////////////////////////////////////////////////////////////////////
void updateLowSpeedTimers(const PxF32* PX_RESTRICT newLowSpeedTimers, PxF32* PX_RESTRICT lowSpeedTimers)
{
for(PxU32 i=0;i<4;i++)
{
lowSpeedTimers[i]=(newLowSpeedTimers[i]!=lowSpeedTimers[i] ? newLowSpeedTimers[i] : 0.0f);
}
}
////////////////////////////////////////////////////////////////////////////
//Set the jounce values computed in processSuspTireWheels
//Call immediately after completing processSuspTireWheels.
////////////////////////////////////////////////////////////////////////////
void updateJounces(const PxF32* PX_RESTRICT jounces, PxF32* PX_RESTRICT prevJounces)
{
for(PxU32 i=0;i<4;i++)
{
prevJounces[i] = jounces[i];
}
}
void updateSteers(const PxF32* PX_RESTRICT steerAngles, PxF32* PX_RESTRICT prevSteers)
{
for (PxU32 i = 0; i < 4; i++)
{
prevSteers[i] = steerAngles[i];
}
}
///////////////////////////////////////////////////////////////////////////////
//Set the hit plane, hit distance and hit friction multplier computed in processSuspTireWheels
//Call immediately after completing processSuspTireWheels.
////////////////////////////////////////////////////////////////////////////
void updateCachedHitData
(const PxU32* PX_RESTRICT cachedHitCounts, const PxPlane* PX_RESTRICT cachedHitPlanes, const PxF32* PX_RESTRICT cachedHitDistances, const PxF32* PX_RESTRICT cachedFrictionMultipliers, const PxU16* cachedQueryTypes,
PxVehicleWheels4DynData* wheels4DynData)
{
if(wheels4DynData->mRaycastResults || wheels4DynData->mSweepResults)
{
wheels4DynData->mHasCachedRaycastHitPlane = true;
}
PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult* cachedRaycastHitResults =
reinterpret_cast<PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult*>(wheels4DynData->mQueryOrCachedHitResults);
for(PxU32 i=0;i<4;i++)
{
cachedRaycastHitResults->mCounts[i]=PxTo16(cachedHitCounts[i]);
cachedRaycastHitResults->mPlanes[i]=cachedHitPlanes[i];
cachedRaycastHitResults->mDistances[i]=cachedHitDistances[i];
cachedRaycastHitResults->mFrictionMultipliers[i]=cachedFrictionMultipliers[i];
cachedRaycastHitResults->mQueryTypes[i] = cachedQueryTypes[i];
}
}
////////////////////////////////////////////////////////////////////////////
//Solve the system of engine speed + wheel rotation speeds using an implicit integrator.
//The following functions only compute the speed of wheels connected to the diff.
//Worth going to the length of the implicit integrator because after gear changes
//the difference in speed at the clutch can be hard to integrate.
//Separate functions for 4W, NW and tank because the differential works in slightly
//different ways. With driveNW we end up with (N+1)*(N+1) problem, with drive4W we end up
//with 5*5 and with tanks we end up with just 3*3. Tanks use the method of least squares
//to apply the rule that all left/right wheels have the same speed.
//Remember that the following functions don't integrate wheels not connected to the diff
//so these need integrated separately.
////////////////////////////////////////////////////////////////////////////
#if PX_CHECKED
bool isValid(const MatrixNN& A, const VectorN& b, const VectorN& result)
{
PX_ASSERT(A.getSize()==b.getSize());
PX_ASSERT(A.getSize()==result.getSize());
const PxU32 size=A.getSize();
//r=A*result-b
VectorN r(size);
for(PxU32 i=0;i<size;i++)
{
r[i]=-b[i];
for(PxU32 j=0;j<size;j++)
{
r[i]+=A.get(i,j)*result[j];
}
}
PxF32 rLength=0;
PxF32 bLength=0;
for(PxU32 i=0;i<size;i++)
{
rLength+=r[i]*r[i];
bLength+=b[i]*b[i];
}
const PxF32 error=PxSqrt(rLength/(bLength+1e-5f));
return (error<1e-5f);
}
#endif
struct ImplicitSolverInput
{
//dt/numSubSteps
PxF32 subTimeStep;
//Brake control value in range (0,1)
PxF32 brake;
//Handbrake control value in range (0,1)
PxF32 handBrake;
//Clutch strength
PxF32 K;
//Gear ratio.
PxF32 G;
PxVehicleClutchAccuracyMode::Enum accuracyMode;
PxU32 maxNumIterations;
//Engine drive torque
PxF32 engineDriveTorque;
//Engine damping rate.
PxF32 engineDampingRate;
//Fraction of available clutch torque to be delivered to each wheel.
const PxF32* diffTorqueRatios;
//Fractional contribution of each wheel to average wheel speed at clutch.
const PxF32* aveWheelSpeedContributions;
//Braking torque at each wheel (inlcudes handbrake torque).
const PxF32* brakeTorques;
//True per wheel brakeTorques[i] > 0, false if brakeTorques[i]==0
const bool* isBrakeApplied;
//Tire torques to apply to each 1d rigid body wheel.
const PxF32* tireTorques;
//Sim and dyn data.
PxU32 numWheels4;
PxU32 numActiveWheels;
const PxVehicleWheels4SimData* wheels4SimData;
const PxVehicleDriveSimData* driveSimData;
};
struct ImplicitSolverOutput
{
PxVehicleWheels4DynData* wheelsDynData;
PxVehicleDriveDynData* driveDynData;
};
void solveDrive4WInternaDynamicsEnginePlusDrivenWheels
(const ImplicitSolverInput& input, ImplicitSolverOutput* output)
{
const PxF32 subTimestep = input.subTimeStep;
const PxF32 K = input.K;
const PxF32 G = input.G;
const PxVehicleClutchAccuracyMode::Enum accuracyMode = input.accuracyMode;
const PxU32 maxIterations = input.maxNumIterations;
const PxF32 engineDriveTorque = input.engineDriveTorque;
const PxF32 engineDampingRate = input.engineDampingRate;
const PxF32* PX_RESTRICT diffTorqueRatios = input.diffTorqueRatios;
const PxF32* PX_RESTRICT aveWheelSpeedContributions = input.aveWheelSpeedContributions;
const PxF32* PX_RESTRICT brakeTorques = input.brakeTorques;
const bool* PX_RESTRICT isBrakeApplied = input.isBrakeApplied;
const PxF32* PX_RESTRICT tireTorques = input.tireTorques;
const PxVehicleWheels4SimData& wheels4SimData = *input.wheels4SimData;
const PxVehicleDriveSimData4W& driveSimData = *static_cast<const PxVehicleDriveSimData4W*>(input.driveSimData);
PxVehicleDriveDynData* driveDynData = output->driveDynData;
PxVehicleWheels4DynData* wheels4DynData = output->wheelsDynData;
const PxF32 KG=K*G;
const PxF32 KGG=K*G*G;
MatrixNN A(4+1);
VectorN b(4+1);
VectorN result(4+1);
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32* PX_RESTRICT wheelSpeeds=wheels4DynData->mWheelSpeeds;
const PxF32 engineOmega=driveDynData->getEngineRotationSpeed();
//
//torque at clutch:
//tc = K*{G*[alpha0*w0 + alpha1*w1 + alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}
//where
//(i) G is the gearing ratio,
//(ii) alphai is the fractional contribution of the ith wheel to the average wheel speed at the clutch (alpha(i) is zero for undriven wheels)
//(iii) wi is the angular speed of the ith wheel
//(iv) K is the clutch strength
//(v) wEng is the angular speed of the engine
//torque applied to ith wheel is
//ti = G*gammai*tc + bt(i) + tt(i)
//where
//gammai is the fractional proportion of the clutch torque that the differential delivers to the ith wheel
//bt(i) is the brake torque applied to the ith wheel
//tt(i) is the tire torque applied to the ith wheel
//acceleration applied to ith wheel is
//ai = G*gammai*K*{G*[alpha0*w0 + alpha1*w1 alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}/Ii + (bt(i) + tt(i))/Ii
//wheer Ii is the moi of the ith wheel
//express ai as
//ai = [wi(t+dt) - wi(t)]/dt
//and rearrange
//wi(t+dt) - wi(t)] = dt*G*gammai*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1)(t+dt)] - wEng(t+dt)}/Ii + dt*(bt(i) + tt(i))/Ii
//Do the same for tEng (torque applied to engine)
//tEng = -tc + engineDriveTorque
//where engineDriveTorque is the drive torque applied to the engine
//Assuming the engine has unit mass then
//wEng(t+dt) -wEng(t) = -dt*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1(t+dt))] - wEng(t+dt)}/Ieng + dt*engineDriveTorque]/IEng
//Introduce the vector w=(w0,w1,w2....w(N-1), wEng)
//and re-express as a matrix after collecting all unknowns at (t+dt) and knowns at time t.
//A*w(t+dt)=b(t);
//Wheels.
{
for(PxU32 i=0;i<4;i++)
{
const PxF32 dt=subTimestep*wheels4SimData.getWheelData(i).getRecipMOI();
const PxF32 R=diffTorqueRatios[i];
const PxF32 dtKGGR=dt*KGG*R;
A.set(i,0,dtKGGR*aveWheelSpeedContributions[0]);
A.set(i,1,dtKGGR*aveWheelSpeedContributions[1]);
A.set(i,2,dtKGGR*aveWheelSpeedContributions[2]);
A.set(i,3,dtKGGR*aveWheelSpeedContributions[3]);
A.set(i,i,1.0f+dtKGGR*aveWheelSpeedContributions[i]+dt*wheels4SimData.getWheelData(i).mDampingRate);
A.set(i,4,-dt*KG*R);
b[i] = wheelSpeeds[i] + dt*(brakeTorques[i]+tireTorques[i]);
result[i] = wheelSpeeds[i];
}
}
//Engine.
{
const PxF32 dt=subTimestep*driveSimData.getEngineData().getRecipMOI();
const PxF32 dtKG=dt*K*G;
A.set(4,0,-dtKG*aveWheelSpeedContributions[0]);
A.set(4,1,-dtKG*aveWheelSpeedContributions[1]);
A.set(4,2,-dtKG*aveWheelSpeedContributions[2]);
A.set(4,3,-dtKG*aveWheelSpeedContributions[3]);
A.set(4,4,1.0f + dt*(K+engineDampingRate));
b[4] = engineOmega + dt*engineDriveTorque;
result[4] = engineOmega;
}
//Solve Aw=b
if(PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == accuracyMode)
{
MatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b,result);
PX_WARN_ONCE_IF(!isValid(A,b,result), "Unable to compute new PxVehicleDrive4W internal rotation speeds. Please check vehicle sim data, especially clutch strength; engine moi and damping; wheel moi and damping");
}
else
{
MatrixNGaussSeidelSolver solver;
solver.solve(maxIterations, gSolverTolerance, A, b, result);
}
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//A consequence of this quick fix is that locked wheels remain locked until the brake is entirely released.
//This isn't strictly mathematically or physically correct - a more accurate solution would either formulate the
//brake as a lcp problem or repeatedly solve with constraints that locked wheels remain at zero rotation speed.
//The physically correct solution will certainly be more expensive so let's live with the restriction that
//locked wheels remain locked until the brake is released.
//newOmega=result[i], oldOmega=wheelSpeeds[i], if newOmega*oldOmega<=0 and isBrakeApplied then lock wheel.
result[0]=(isBrakeApplied[0] && (wheelSpeeds[0]*result[0]<=0)) ? 0.0f : result[0];
result[1]=(isBrakeApplied[1] && (wheelSpeeds[1]*result[1]<=0)) ? 0.0f : result[1];
result[2]=(isBrakeApplied[2] && (wheelSpeeds[2]*result[2]<=0)) ? 0.0f : result[2];
result[3]=(isBrakeApplied[3] && (wheelSpeeds[3]*result[3]<=0)) ? 0.0f : result[3];
//Clamp the engine revs.
//Again, this is not physically or mathematically correct but the loss in behaviour will be hard to notice.
//The alternative would be to add constraints to the solver, which would be much more expensive.
result[4]=PxClamp(result[4],0.0f,engineData.mMaxOmega);
//Copy back to the car's internal rotation speeds.
wheels4DynData->mWheelSpeeds[0]=result[0];
wheels4DynData->mWheelSpeeds[1]=result[1];
wheels4DynData->mWheelSpeeds[2]=result[2];
wheels4DynData->mWheelSpeeds[3]=result[3];
driveDynData->setEngineRotationSpeed(result[4]);
}
void solveDriveNWInternalDynamicsEnginePlusDrivenWheels
(const ImplicitSolverInput& input, ImplicitSolverOutput* output)
{
const PxF32 subTimestep = input.subTimeStep;
//const PxF32 brake = input.brake;
//const PxF32 handbrake = input.handBrake;
const PxF32 K = input.K;
const PxF32 G = input.G;
const PxVehicleClutchAccuracyMode::Enum accuracyMode = input.accuracyMode;
const PxU32 maxIterations = input.maxNumIterations;
const PxF32 engineDriveTorque = input.engineDriveTorque;
const PxF32 engineDampingRate = input.engineDampingRate;
const PxF32* PX_RESTRICT diffTorqueRatios = input.diffTorqueRatios;
const PxF32* PX_RESTRICT aveWheelSpeedContributions = input.aveWheelSpeedContributions;
const PxF32* PX_RESTRICT brakeTorques = input.brakeTorques;
const bool* PX_RESTRICT isBrakeApplied = input.isBrakeApplied;
const PxF32* PX_RESTRICT tireTorques = input.tireTorques;
//const PxU32 numWheels4 = input.numWheels4;
const PxU32 numActiveWheels = input.numActiveWheels;
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimDatas = input.wheels4SimData;
const PxVehicleDriveSimDataNW& driveSimData = *static_cast<const PxVehicleDriveSimDataNW*>(input.driveSimData);
PxVehicleDriveDynData* driveDynData = output->driveDynData;
PxVehicleWheels4DynData* wheels4DynDatas = output->wheelsDynData;
const PxF32 KG=K*G;
const PxF32 KGG=K*G*G;
MatrixNN A(numActiveWheels+1);
VectorN b(numActiveWheels+1);
VectorN result(numActiveWheels+1);
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData->getEngineRotationSpeed();
//
//torque at clutch:
//tc = K*{G*[alpha0*w0 + alpha1*w1 + alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}
//where
//(i) G is the gearing ratio,
//(ii) alphai is the fractional contribution of the ith wheel to the average wheel speed at the clutch (alpha(i) is zero for undriven wheels)
//(iii) wi is the angular speed of the ith wheel
//(iv) K is the clutch strength
//(v) wEng is the angular speed of the engine
//torque applied to ith wheel is
//ti = G*gammai*tc + bt(i) + tt(i)
//where
//gammai is the fractional proportion of the clutch torque that the differential delivers to the ith wheel
//bt(i) is the brake torque applied to the ith wheel
//tt(i) is the tire torque applied to the ith wheel
//acceleration applied to ith wheel is
//ai = G*gammai*K*{G*[alpha0*w0 + alpha1*w1 alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}/Ii + (bt(i) + tt(i))/Ii
//wheer Ii is the moi of the ith wheel.
//express ai as
//ai = [wi(t+dt) - wi(t)]/dt
//and rearrange
//wi(t+dt) - wi(t)] = dt*G*gammai*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1)(t+dt)] - wEng(t+dt)}/Ii + dt*(bt(i) + tt(i))/Ii
//Do the same for tEng (torque applied to engine)
//tEng = -tc + engineDriveTorque
//where engineDriveTorque is the drive torque applied to the engine
//Assuming the engine has unit mass then
//wEng(t+dt) -wEng(t) = -dt*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1(t+dt))] - wEng(t+dt)}/Ieng + dt*engineDriveTorque/Ieng
//Introduce the vector w=(w0,w1,w2....w(N-1), wEng)
//and re-express as a matrix after collecting all unknowns at (t+dt) and knowns at time t.
//A*w(t+dt)=b(t);
//Wheels.
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxF32 dt=subTimestep*wheels4SimDatas[i>>2].getWheelData(i&3).getRecipMOI();
const PxF32 R=diffTorqueRatios[i];
const PxF32 dtKGGR=dt*KGG*R;
for(PxU32 j=0;j<numActiveWheels;j++)
{
A.set(i,j,dtKGGR*aveWheelSpeedContributions[j]);
}
A.set(i,i,1.0f+dtKGGR*aveWheelSpeedContributions[i]+dt*wheels4SimDatas[i>>2].getWheelData(i&3).mDampingRate);
A.set(i,numActiveWheels,-dt*KG*R);
b[i] = wheels4DynDatas[i>>2].mWheelSpeeds[i&3] + dt*(brakeTorques[i]+tireTorques[i]);
result[i] = wheels4DynDatas[i>>2].mWheelSpeeds[i&3];
}
//Engine.
{
const PxF32 dt=subTimestep*driveSimData.getEngineData().getRecipMOI();
const PxF32 dtKG=dt*K*G;
for(PxU32 i=0;i<numActiveWheels;i++)
{
A.set(numActiveWheels,i,-dtKG*aveWheelSpeedContributions[i]);
}
A.set(numActiveWheels,numActiveWheels,1.0f + dt*(K+engineDampingRate));
b[numActiveWheels] = engineOmega + dt*engineDriveTorque;
result[numActiveWheels] = engineOmega;
}
//Solve Aw=b
if(PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == accuracyMode)
{
MatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b,result);
PX_WARN_ONCE_IF(!isValid(A,b,result), "Unable to compute new PxVehicleDriveNW internal rotation speeds. Please check vehicle sim data, especially clutch strength; engine moi and damping; wheel moi and damping");
}
else
{
MatrixNGaussSeidelSolver solver;
solver.solve(maxIterations, gSolverTolerance, A, b, result);
}
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//A consequence of this quick fix is that locked wheels remain locked until the brake is entirely released.
//This isn't strictly mathematically or physically correct - a more accurate solution would either formulate the
//brake as a lcp problem or repeatedly solve with constraints that locked wheels remain at zero rotation speed.
//The physically correct solution will certainly be more expensive so let's live with the restriction that
//locked wheels remain locked until the brake is released.
//newOmega=result[i], oldOmega=wheelSpeeds[i], if newOmega*oldOmega<=0 and isBrakeApplied then lock wheel.
for(PxU32 i=0;i<numActiveWheels;i++)
{
result[i]=(isBrakeApplied[i] && (wheels4DynDatas[i>>2].mWheelSpeeds[i&3]*result[i]<=0)) ? 0.0f : result[i];
}
//Clamp the engine revs.
//Again, this is not physically or mathematically correct but the loss in behaviour will be hard to notice.
result[numActiveWheels]=PxClamp(result[numActiveWheels],0.0f,engineData.mMaxOmega);
//Copy back to the car's internal rotation speeds.
for(PxU32 i=0;i<numActiveWheels;i++)
{
wheels4DynDatas[i>>2].mWheelSpeeds[i&3]=result[i];
}
driveDynData->setEngineRotationSpeed(result[numActiveWheels]);
}
void solveTankInternaDynamicsEnginePlusDrivenWheels
(const ImplicitSolverInput& input, const bool* PX_RESTRICT activeWheelStates, const PxF32* PX_RESTRICT wheelGearings, ImplicitSolverOutput* output)
{
PX_SIMD_GUARD; // denormal exception triggered at oldOmega*newOmega on osx
const PxF32 subTimestep = input.subTimeStep;
const PxF32 K = input.K;
const PxF32 G = input.G;
const PxF32 engineDriveTorque = input.engineDriveTorque;
const PxF32 engineDampingRate = input.engineDampingRate;
const PxF32* PX_RESTRICT diffTorqueRatios = input.diffTorqueRatios;
const PxF32* PX_RESTRICT aveWheelSpeedContributions = input.aveWheelSpeedContributions;
const PxF32* PX_RESTRICT brakeTorques = input.brakeTorques;
const bool* PX_RESTRICT isBrakeApplied = input.isBrakeApplied;
const PxF32* PX_RESTRICT tireTorques = input.tireTorques;
const PxU32 numWheels4 = input.numWheels4;
const PxU32 numActiveWheels = input.numActiveWheels;
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimDatas = input.wheels4SimData;
const PxVehicleDriveSimData& driveSimData = *input.driveSimData;
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynDatas = output->wheelsDynData;
PxVehicleDriveDynData* driveDynData = output->driveDynData;
const PxF32 KG=K*G;
const PxF32 KGG=K*G*G;
//Rearrange data in a single array rather than scattered in blocks of 4.
//This makes it easier later on.
PxF32 recipMOI[PX_MAX_NB_WHEELS];
PxF32 dampingRates[PX_MAX_NB_WHEELS];
PxF32 wheelSpeeds[PX_MAX_NB_WHEELS];
PxF32 wheelRecipRadii[PX_MAX_NB_WHEELS];
for(PxU32 i=0;i<numWheels4-1;i++)
{
const PxVehicleWheelData& wheelData0=wheels4SimDatas[i].getWheelData(0);
const PxVehicleWheelData& wheelData1=wheels4SimDatas[i].getWheelData(1);
const PxVehicleWheelData& wheelData2=wheels4SimDatas[i].getWheelData(2);
const PxVehicleWheelData& wheelData3=wheels4SimDatas[i].getWheelData(3);
recipMOI[4*i+0]=wheelData0.getRecipMOI();
recipMOI[4*i+1]=wheelData1.getRecipMOI();
recipMOI[4*i+2]=wheelData2.getRecipMOI();
recipMOI[4*i+3]=wheelData3.getRecipMOI();
dampingRates[4*i+0]=wheelData0.mDampingRate;
dampingRates[4*i+1]=wheelData1.mDampingRate;
dampingRates[4*i+2]=wheelData2.mDampingRate;
dampingRates[4*i+3]=wheelData3.mDampingRate;
wheelRecipRadii[4*i+0]=wheelData0.getRecipRadius();
wheelRecipRadii[4*i+1]=wheelData1.getRecipRadius();
wheelRecipRadii[4*i+2]=wheelData2.getRecipRadius();
wheelRecipRadii[4*i+3]=wheelData3.getRecipRadius();
const PxVehicleWheels4DynData& suspWheelTire4=wheels4DynDatas[i];
wheelSpeeds[4*i+0]=suspWheelTire4.mWheelSpeeds[0];
wheelSpeeds[4*i+1]=suspWheelTire4.mWheelSpeeds[1];
wheelSpeeds[4*i+2]=suspWheelTire4.mWheelSpeeds[2];
wheelSpeeds[4*i+3]=suspWheelTire4.mWheelSpeeds[3];
}
const PxU32 numInLastBlock = 4 - (4*numWheels4 - numActiveWheels);
for(PxU32 i=0;i<numInLastBlock;i++)
{
const PxVehicleWheelData& wheelData=wheels4SimDatas[numWheels4-1].getWheelData(i);
recipMOI[4*(numWheels4-1)+i]=wheelData.getRecipMOI();
dampingRates[4*(numWheels4-1)+i]=wheelData.mDampingRate;
wheelRecipRadii[4*(numWheels4-1)+i]=wheelData.getRecipRadius();
const PxVehicleWheels4DynData& suspWheelTire4=wheels4DynDatas[numWheels4-1];
wheelSpeeds[4*(numWheels4-1)+i]=suspWheelTire4.mWheelSpeeds[i];
}
const PxF32 wheelRadius0=wheels4SimDatas[0].getWheelData(0).mRadius;
const PxF32 wheelRadius1=wheels4SimDatas[0].getWheelData(1).mRadius;
//
//torque at clutch:
//tc = K*{G*[alpha0*w0 + alpha1*w1 + alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}
//where
//(i) G is the gearing ratio,
//(ii) alphai is the fractional contribution of the ith wheel to the average wheel speed at the clutch (alpha(i) is zero for undriven wheels)
//(iii) wi is the angular speed of the ith wheel
//(iv) K is the clutch strength
//(v) wEng is the angular speed of the engine
//torque applied to ith wheel is
//ti = G*gammai*tc + bt(i) + tt(i)
//where
//gammai is the fractional proportion of the clutch torque that the differential delivers to the ith wheel
//bt(i) is the brake torque applied to the ith wheel
//tt(i) is the tire torque applied to the ith wheel
//acceleration applied to ith wheel is
//ai = G*gammai*K*{G*[alpha0*w0 + alpha1*w1 alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}/Ii + (bt(i) + tt(i))/Ii
//wheer Ii is the moi of the ith wheel.
//express ai as
//ai = [wi(t+dt) - wi(t)]/dt
//and rearrange
//wi(t+dt) - wi(t)] = dt*G*gammai*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1)(t+dt)] - wEng(t+dt)}/Ii + dt*(bt(i) + tt(i))/Ii
//Do the same for tEng (torque applied to engine)
//tEng = -tc + engineDriveTorque
//where engineDriveTorque is the drive torque applied to the engine
//Assuming the engine has unit mass then
//wEng(t+dt) -wEng(t) = -dt*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1(t+dt))] - wEng(t+dt)}/Ieng + dt*engineDriveTorque/Ieng
//Introduce the vector w=(w0,w1,w2....w(N-1), wEng)
//and re-express as a matrix after collecting all unknowns at (t+dt) and knowns at time t.
//M*w(t+dt)=b(t);
//Matrix M and rhs vector b that we use to solve Mw=b.
MatrixNN M(numActiveWheels+1);
VectorN b(numActiveWheels+1);
//Wheels.
{
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxF32 dt=subTimestep*recipMOI[i];
const PxF32 R=diffTorqueRatios[i];
const PxF32 g=wheelGearings[i];
const PxF32 dtKGGRg=dt*KGG*R*g;
for(PxU32 j=0;j<numActiveWheels;j++)
{
M.set(i,j,dtKGGRg*aveWheelSpeedContributions[j]*wheelGearings[j]);
}
M.set(i,i,1.0f+dtKGGRg*aveWheelSpeedContributions[i]*wheelGearings[i]+dt*dampingRates[i]);
M.set(i,numActiveWheels,-dt*KG*R*g);
b[i] = wheelSpeeds[i] + dt*(brakeTorques[i]+tireTorques[i]);
}
}
//Engine.
{
const PxF32 engineOmega=driveDynData->getEngineRotationSpeed();
const PxF32 dt=subTimestep*driveSimData.getEngineData().getRecipMOI();
const PxF32 dtKG=dt*K*G;
for(PxU32 i=0;i<numActiveWheels;i++)
{
M.set(numActiveWheels,i,-dtKG*aveWheelSpeedContributions[i]*wheelGearings[i]);
}
M.set(numActiveWheels,numActiveWheels,1.0f + dt*(K+engineDampingRate));
b[numActiveWheels] = engineOmega + dt*engineDriveTorque;
}
//Now apply the constraints that all the odd numbers are equal and all the even numbers are equal.
//ie w2,w4,w6 are all equal to w0 and w3,w5,w7 are all equal to w1.
//That leaves (4*N+1) equations but only 3 unknowns: two wheels speeds and the engine speed.
//Substitute these extra constraints into the matrix.
MatrixNN A(numActiveWheels+1);
for(PxU32 i=0;i<numActiveWheels+1;i++)
{
PxF32 sum0=M.get(i,0+0);
PxF32 sum1=M.get(i,0+1);
for(PxU32 j=2;j<numActiveWheels;j+=2)
{
sum0+=M.get(i,j+0)*wheelRadius0*wheelRecipRadii[j+0];
sum1+=M.get(i,j+1)*wheelRadius1*wheelRecipRadii[j+1];
}
A.set(i,0,sum0);
A.set(i,1,sum1);
A.set(i,2,M.get(i,numActiveWheels));
}
//We have an over-determined problem because of the extra constraints
//on equal wheel speeds. Solve using the least squares method as in
//http://s-mat-pcs.oulu.fi/~mpa/matreng/ematr5_5.htm
//Compute A^T*A
//No longer using M.
MatrixNN& ATA = M;
ATA.setSize(3);
for(PxU32 i=0;i<3;i++)
{
for(PxU32 j=0;j<3;j++)
{
PxF32 sum=0.0f;
for(PxU32 k=0;k<numActiveWheels+1;k++)
{
//sum+=AT.get(i,k)*A.get(k,j);
sum+=A.get(k,i)*A.get(k,j);
}
ATA.set(i,j,sum);
}
}
//Compute A^T*b;
VectorN ATb(3);
for(PxU32 i=0;i<3;i++)
{
PxF32 sum=0;
for(PxU32 j=0;j<numActiveWheels+1;j++)
{
//sum+=AT.get(i,j)*b[j];
sum+=A.get(j,i)*b[j];
}
ATb[i]=sum;
}
//Solve (A^T*A)*x = A^T*b
VectorN result(3);
Matrix33Solver solver;
bool successfulSolver = solver.solve(ATA, ATb, result);
if(!successfulSolver)
{
PX_WARN_ONCE("Unable to compute new PxVehicleDriveTank internal rotation speeds. Please check vehicle sim data, especially clutch strength; engine moi and damping; wheel moi and damping");
return;
}
//Clamp the engine revs between zero and maxOmega
const PxF32 maxEngineOmega=driveSimData.getEngineData().mMaxOmega;
const PxF32 newEngineOmega=PxClamp(result[2],0.0f,maxEngineOmega);
//Apply the constraints on each of the equal wheel speeds.
PxF32 wheelSpeedResults[PX_MAX_NB_WHEELS];
wheelSpeedResults[0]=result[0];
wheelSpeedResults[1]=result[1];
for(PxU32 i=2;i<numActiveWheels;i+=2)
{
wheelSpeedResults[i+0]=result[0];
wheelSpeedResults[i+1]=result[1];
}
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//A consequence of this quick fix is that locked wheels remain locked until the brake is entirely released.
//This isn't strictly mathematically or physically correct - a more accurate solution would either formulate the
//brake as a lcp problem or repeatedly solve with constraints that locked wheels remain at zero rotation speed.
//The physically correct solution will certainly be more expensive so let's live with the restriction that
//locked wheels remain locked until the brake is released.
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxF32 oldOmega=wheelSpeeds[i];
const PxF32 newOmega=wheelSpeedResults[i];
const bool hasBrake=isBrakeApplied[i];
if(hasBrake && (oldOmega*newOmega <= 0))
{
wheelSpeedResults[i]=0.0f;
}
}
//Copy back to the car's internal rotation speeds.
for(PxU32 i=0;i<numWheels4-1;i++)
{
wheels4DynDatas[i].mWheelSpeeds[0] = activeWheelStates[4*i+0] ? wheelSpeedResults[4*i+0] : 0.0f;
wheels4DynDatas[i].mWheelSpeeds[1] = activeWheelStates[4*i+1] ? wheelSpeedResults[4*i+1] : 0.0f;
wheels4DynDatas[i].mWheelSpeeds[2] = activeWheelStates[4*i+2] ? wheelSpeedResults[4*i+2] : 0.0f;
wheels4DynDatas[i].mWheelSpeeds[3] = activeWheelStates[4*i+3] ? wheelSpeedResults[4*i+3] : 0.0f;
}
for(PxU32 i=0;i<numInLastBlock;i++)
{
wheels4DynDatas[numWheels4-1].mWheelSpeeds[i] = activeWheelStates[4*(numWheels4-1)+i] ? wheelSpeedResults[4*(numWheels4-1)+i] : 0.0f;
}
driveDynData->setEngineRotationSpeed(newEngineOmega);
}
////////////////////////////////////////////////////////////////////////////
//Integrate wheel rotation speeds of wheels not connected to the differential.
//Obviously, no wheels in a PxVehicleNoDrive are connected to a diff so all require
//direct integration.
//Only the first 4 wheels of a PxVehicleDrive4W are connected to the diff so
//any extra wheels need direct integration.
//All tank wheels are connected to the diff so none need integrated in a separate pass.
//What about undriven wheels in a PxVehicleDriveNW? This vehicle type treats all
//wheels as being connected to the diff but sets the diff contribution to zero for
//all undriven wheels. No wheels from a PxVehicleNW need integrated in a separate pass.
////////////////////////////////////////////////////////////////////////////
void integrateNoDriveWheelSpeeds
(const PxF32 subTimestep,
const PxF32* PX_RESTRICT brakeTorques, const bool* PX_RESTRICT isBrakeApplied, const PxF32* driveTorques, const PxF32* PX_RESTRICT tireTorques, const PxF32* PX_RESTRICT dampingRates,
const PxVehicleWheels4SimData& vehSuspWheelTire4SimData, PxVehicleWheels4DynData& vehSuspWheelTire4)
{
//w(t+dt) = w(t) + (1/inertia)*(brakeTorque + driveTorque + tireTorque)*dt - (1/inertia)*damping*w(t)*dt ) (1)
//Apply implicit trick and rearrange.
//w(t+dt)[1 + (1/inertia)*damping*dt] = w(t) + (1/inertia)*(brakeTorque + driveTorque + tireTorque)*dt (2)
//Introduce (1/inertia)*dt to avoid duplication in (2)
PxF32 subTimeSteps[4] =
{
subTimestep*vehSuspWheelTire4SimData.getWheelData(0).getRecipMOI(),
subTimestep*vehSuspWheelTire4SimData.getWheelData(1).getRecipMOI(),
subTimestep*vehSuspWheelTire4SimData.getWheelData(2).getRecipMOI(),
subTimestep*vehSuspWheelTire4SimData.getWheelData(3).getRecipMOI()
};
//Integrate.
//w += torque*dt/inertia - damping*dt*w
//Use implicit integrate trick and rearrange
//w(t+dt) = [w(t) + torque*dt/inertia]/[1 + damping*dt]
const PxF32* PX_RESTRICT wheelSpeeds=vehSuspWheelTire4.mWheelSpeeds;
PxF32 result[4]=
{
(wheelSpeeds[0] + subTimeSteps[0]*(tireTorques[0] + driveTorques[0] + brakeTorques[0]))/(1.0f + dampingRates[0]*subTimeSteps[0]),
(wheelSpeeds[1] + subTimeSteps[1]*(tireTorques[1] + driveTorques[1] + brakeTorques[1]))/(1.0f + dampingRates[1]*subTimeSteps[1]),
(wheelSpeeds[2] + subTimeSteps[2]*(tireTorques[2] + driveTorques[2] + brakeTorques[2]))/(1.0f + dampingRates[2]*subTimeSteps[2]),
(wheelSpeeds[3] + subTimeSteps[3]*(tireTorques[3] + driveTorques[3] + brakeTorques[3]))/(1.0f + dampingRates[3]*subTimeSteps[3]),
};
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//newOmega=result[i], oldOmega=wheelSpeeds[i], if newOmega*oldOmega<=0 and isBrakeApplied then lock wheel.
result[0]=(isBrakeApplied[0] && (wheelSpeeds[0]*result[0]<=0)) ? 0.0f : result[0];
result[1]=(isBrakeApplied[1] && (wheelSpeeds[1]*result[1]<=0)) ? 0.0f : result[1];
result[2]=(isBrakeApplied[2] && (wheelSpeeds[2]*result[2]<=0)) ? 0.0f : result[2];
result[3]=(isBrakeApplied[3] && (wheelSpeeds[3]*result[3]<=0)) ? 0.0f : result[3];
//Copy back to the car's internal rotation speeds.
vehSuspWheelTire4.mWheelSpeeds[0]=result[0];
vehSuspWheelTire4.mWheelSpeeds[1]=result[1];
vehSuspWheelTire4.mWheelSpeeds[2]=result[2];
vehSuspWheelTire4.mWheelSpeeds[3]=result[3];
}
void integrateUndriveWheelRotationSpeeds
(const PxF32 subTimestep,
const PxF32 brake, const PxF32 handbrake, const PxF32* PX_RESTRICT tireTorques, const PxF32* PX_RESTRICT brakeTorques,
const PxVehicleWheels4SimData& vehSuspWheelTire4SimData, PxVehicleWheels4DynData& vehSuspWheelTire4)
{
for(PxU32 i=0;i<4;i++)
{
//Compute the new angular speed of the wheel.
const PxF32 oldOmega=vehSuspWheelTire4.mWheelSpeeds[i];
const PxF32 dtI = subTimestep*vehSuspWheelTire4SimData.getWheelData(i).getRecipMOI();
const PxF32 gamma = vehSuspWheelTire4SimData.getWheelData(i).mDampingRate;
const PxF32 newOmega=(oldOmega+dtI*(tireTorques[i]+brakeTorques[i]))/(1.0f + gamma*dtI);
//Has the brake been applied? It's hard to tell from brakeTorques[j] because that
//will be zero if the wheel is locked. Work it out from the brake and handbrake data.
const PxF32 brakeGain=vehSuspWheelTire4SimData.getWheelData(i).mMaxBrakeTorque;
const PxF32 handbrakeGain=vehSuspWheelTire4SimData.getWheelData(i).mMaxHandBrakeTorque;
//Work out if the wheel should be locked.
const bool brakeApplied=((brake*brakeGain + handbrake*handbrakeGain)!=0.0f);
const bool wheelReversed=(oldOmega*newOmega <=0);
const bool wheelLocked=(brakeApplied && wheelReversed);
//Lock the wheel or apply its new angular speed.
if(!wheelLocked)
{
vehSuspWheelTire4.mWheelSpeeds[i]=newOmega;
}
else
{
vehSuspWheelTire4.mWheelSpeeds[i]=0.0f;
}
}
}
////////////////////////////////////////////////////////////////////////////
//Pose the wheels.
//First integrate the wheel rotation angles and clamp them to a range (-10*pi, 10*pi)
//PxVehicleNoDrive has a different way of telling if a wheel is driven by a drive torque so has a separate function.
//Use the wheel steer/rotation/camber angle and suspension jounce to compute the local transform of each wheel.
////////////////////////////////////////////////////////////////////////////
void integrateWheelRotationAngles
(const PxF32 timestep,
const PxF32 K, const PxF32 G, const PxF32 engineDriveTorque,
const PxF32* PX_RESTRICT jounces, const PxF32* PX_RESTRICT diffTorqueRatios, const PxF32* PX_RESTRICT forwardSpeeds, const bool* isBrakeApplied,
const PxVehicleDriveSimData& vehCoreSimData, const PxVehicleWheels4SimData& vehSuspWheelTire4SimData,
PxVehicleDriveDynData& vehCore, PxVehicleWheels4DynData& vehSuspWheelTire4)
{
PX_SIMD_GUARD; //denorm exception on newRotAngle=wheelRotationAngles[j]+wheelOmega*timestep; on osx
PX_UNUSED(vehCore);
PX_UNUSED(vehCoreSimData);
const PxF32 KG=K*G;
PxF32* PX_RESTRICT wheelSpeeds=vehSuspWheelTire4.mWheelSpeeds;
PxF32* PX_RESTRICT wheelRotationAngles=vehSuspWheelTire4.mWheelRotationAngles;
PxF32* PX_RESTRICT correctedWheelSpeeds = vehSuspWheelTire4.mCorrectedWheelSpeeds;
for(PxU32 j=0;j<4;j++)
{
//At low vehicle forward speeds we have some numerical difficulties getting the
//wheel rotation speeds to be correct due to the tire model's difficulties at low vz.
//The solution is to blend between the rolling speed at the wheel and the wheel's actual rotation speed.
//If the wheel is
//(i) in the air or,
//(ii) under braking torque or,
//(iii) driven by the engine through the gears and diff
//then always use the wheel's actual rotation speed.
//Just to be clear, this means we will blend when the wheel
//(i) is on the ground and
//(ii) has no brake applied and
//(iii) has no drive torque applied from the clutch and
//(iv) is at low forward speed
PxF32 wheelOmega=wheelSpeeds[j];
if(jounces[j] > -vehSuspWheelTire4SimData.getSuspensionData(j).mMaxDroop && //(i) wheel touching ground
false==isBrakeApplied[j] && //(ii) no brake applied
0.0f==diffTorqueRatios[j]*KG*engineDriveTorque && //(iii) no drive torque applied
PxAbs(forwardSpeeds[j])<gThresholdForwardSpeedForWheelAngleIntegration) //(iv) low speed
{
const PxF32 recipWheelRadius=vehSuspWheelTire4SimData.getWheelData(j).getRecipRadius();
const PxF32 alpha=PxAbs(forwardSpeeds[j])*gRecipThresholdForwardSpeedForWheelAngleIntegration;
wheelOmega = (forwardSpeeds[j]*recipWheelRadius)*(1.0f-alpha) + wheelOmega*alpha;
}
PxF32 newRotAngle=wheelRotationAngles[j]+wheelOmega*timestep;
//Clamp the wheel rotation angle to a range (-10*pi,10*pi) to stop it getting crazily big.
newRotAngle=physx::intrinsics::fsel(newRotAngle-10*PxPi, newRotAngle-10*PxPi, physx::intrinsics::fsel(-newRotAngle-10*PxPi, newRotAngle + 10*PxPi, newRotAngle));
wheelRotationAngles[j]=newRotAngle;
correctedWheelSpeeds[j]=wheelOmega;
}
}
void integrateNoDriveWheelRotationAngles
(const PxF32 timestep,
const PxF32* PX_RESTRICT driveTorques,
const PxF32* PX_RESTRICT jounces, const PxF32* PX_RESTRICT forwardSpeeds, const bool* isBrakeApplied,
const PxVehicleWheels4SimData& vehSuspWheelTire4SimData,
PxVehicleWheels4DynData& vehSuspWheelTire4)
{
PxF32* PX_RESTRICT wheelSpeeds=vehSuspWheelTire4.mWheelSpeeds;
PxF32* PX_RESTRICT wheelRotationAngles=vehSuspWheelTire4.mWheelRotationAngles;
PxF32* PX_RESTRICT correctedWheelSpeeds=vehSuspWheelTire4.mCorrectedWheelSpeeds;
for(PxU32 j=0;j<4;j++)
{
//At low vehicle forward speeds we have some numerical difficulties getting the
//wheel rotation speeds to be correct due to the tire model's difficulties at low vz.
//The solution is to blend between the rolling speed at the wheel and the wheel's actual rotation speed.
//If the wheel is
//(i) in the air or,
//(ii) under braking torque or,
//(iii) driven by a drive torque
//then always use the wheel's actual rotation speed.
//Just to be clear, this means we will blend when the wheel
//(i) is on the ground and
//(ii) has no brake applied and
//(iii) has no drive torque and
//(iv) is at low forward speed
PxF32 wheelOmega=wheelSpeeds[j];
if(jounces[j] > -vehSuspWheelTire4SimData.getSuspensionData(j).mMaxDroop && //(i) wheel touching ground
false==isBrakeApplied[j] && //(ii) no brake applied
0.0f==driveTorques[j] && //(iii) no drive torque applied
PxAbs(forwardSpeeds[j])<gThresholdForwardSpeedForWheelAngleIntegration) //(iv) low speed
{
const PxF32 recipWheelRadius=vehSuspWheelTire4SimData.getWheelData(j).getRecipRadius();
const PxF32 alpha=PxAbs(forwardSpeeds[j])*gRecipThresholdForwardSpeedForWheelAngleIntegration;
wheelOmega = (forwardSpeeds[j]*recipWheelRadius)*(1.0f-alpha) + wheelOmega*alpha;
//TODO: maybe just set the car wheel omega to the blended value?
//Not sure about this bit.
//Turned this off because it added energy to the car at very small timesteps.
//wheelSpeeds[j]=wheelOmega;
}
PxF32 newRotAngle=wheelRotationAngles[j]+wheelOmega*timestep;
//Clamp the wheel rotation angle to a range (-10*pi,10*pi) to stop it getting crazily big.
newRotAngle=physx::intrinsics::fsel(newRotAngle-10*PxPi, newRotAngle-10*PxPi, physx::intrinsics::fsel(-newRotAngle-10*PxPi, newRotAngle + 10*PxPi, newRotAngle));
wheelRotationAngles[j]=newRotAngle;
correctedWheelSpeeds[j]=wheelOmega;
}
}
PxQuat computeWheelLocalQuat(
const PxVec3& forwardAxis, const PxVec3& sideAxis, const PxVec3& upAxis,
const float jounce, const PxVehicleSuspensionData& suspData, const PxF32 rotationAngle, const PxF32 steerAngle)
{
PX_ASSERT(jounce != PX_MAX_F32);
//Compute the camber angle.
PxF32 camberAngle = suspData.mCamberAtRest;
if (jounce > 0.0f)
{
camberAngle += jounce*suspData.mCamberAtMaxCompression*suspData.getRecipMaxCompression();
}
else
{
camberAngle -= jounce*suspData.mCamberAtMaxDroop*suspData.getRecipMaxDroop();
}
const PxQuat quat(steerAngle, upAxis);
const PxQuat quat2(camberAngle, quat.rotate(forwardAxis));
const PxQuat quat3 = quat2*quat;
const PxQuat quat4(rotationAngle, quat3.rotate(sideAxis));
const PxQuat result = quat4*quat3;
return result;
}
void computeWheelLocalPoses
(const PxVehicleWheels4SimData& wheelsSimData,
const PxVehicleWheels4DynData& wheelsDynData,
const PxWheelQueryResult* wheelQueryResults,
const PxU32 numWheelsToPose,
const PxTransform& vehChassisCMLocalPose,
const PxVec3& upAxis,
const PxVec3& sideAxis,
const PxVec3& forwardAxis,
PxTransform* localPoses)
{
const PxF32* PX_RESTRICT rotAngles=wheelsDynData.mWheelRotationAngles;
const PxVec3 cmOffset=vehChassisCMLocalPose.p;
for(PxU32 i=0;i<numWheelsToPose;i++)
{
const PxF32 jounce=wheelQueryResults[i].suspJounce;
PX_ASSERT(jounce != PX_MAX_F32);
const PxQuat quat = computeWheelLocalQuat(forwardAxis, sideAxis, upAxis, jounce, wheelsSimData.getSuspensionData(i), rotAngles[i], wheelQueryResults[i].steerAngle);
const PxVec3 pos=cmOffset+wheelsSimData.getWheelCentreOffset(i)-wheelsSimData.getSuspTravelDirection(i)*jounce;
localPoses[i] = PxTransform(pos, quat);
}
}
void computeWheelLocalPoseRotations
(const PxVehicleWheels4DynData* wheels4DynDatas, const PxVehicleWheels4SimData* wheels4SimDatas, const PxU32 numWheels4,
const PxVehicleContext& context,
const float* steerAngles,
PxQuat* wheelLocalPoseRotations)
{
for (PxU32 i = 0; i < numWheels4; i++)
{
for (PxU32 j = 0; j < 4; j++)
{
const PxF32 jounce = (wheels4DynDatas[i].mJounces[j] != PX_MAX_F32) ? wheels4DynDatas[i].mJounces[j] : 0.0f;
const PxVehicleSuspensionData& suspData = wheels4SimDatas[i].getSuspensionData(j);
const PxF32 steerAngle = steerAngles[4 * i + j];
const PxQuat q = computeWheelLocalQuat(context.forwardAxis, context.sideAxis, context.upAxis, jounce, suspData, 0.0f, steerAngle);
wheelLocalPoseRotations[4 * i + j] = q;
}
}
}
void poseWheels
(const PxVehicleWheels4SimData& wheelsSimData,
const PxTransform* localPoses,
const PxU32 numWheelsToPose,
PxRigidDynamic* vehActor)
{
PxShape* shapeBuffer[128];
vehActor->getShapes(shapeBuffer,128,0);
for(PxU32 i=0;i<numWheelsToPose;i++)
{
const PxI32 shapeIndex = wheelsSimData.getWheelShapeMapping(i);
if(shapeIndex != -1)
{
PxShape* currShape = NULL;
if(shapeIndex < 128)
{
currShape = shapeBuffer[shapeIndex];
}
else
{
PxShape* shapeBuffer2[1];
vehActor->getShapes(shapeBuffer2,1,PxU32(shapeIndex));
currShape = shapeBuffer2[0];
}
PX_ASSERT(currShape);
currShape->setLocalPose(localPoses[i]);
}
}
}
////////////////////////////////////////////////////////////////////////////
//Update each vehicle type with a special function
////////////////////////////////////////////////////////////////////////////
class PxVehicleUpdate
{
public:
#if PX_DEBUG_VEHICLE_ON
static void updateSingleVehicleAndStoreTelemetryData(
const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
PxVehicleWheels* focusVehicle, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleTelemetryData& telemetryData,
PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxVehicleContext&);
#endif
static void update(
const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
const PxU32 numVehicles, PxVehicleWheels** vehicles, PxVehicleWheelQueryResult* wheelQueryResults, PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates,
VehicleTelemetryDataContext* vehicleTelemetryDataContext, const PxVehicleContext&);
static void updatePost(
const PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxVehicleContext&);
static void suspensionRaycasts(
PxBatchQueryExt* batchQuery,
const PxU32 numVehicles, PxVehicleWheels** vehicles,
const bool* vehiclesToRaycast, const PxQueryFlags queryFlags);
static void suspensionSweeps(
PxBatchQueryExt* batchQuery,
const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxU16 nbHitsPerQuery,
const bool* vehiclesToRaycast,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation, const PxQueryFlags queryFlags,
const PxVec3& upAxis, const PxVec3& forwardAxis, const PxVec3& sideAxis);
static void updateDrive4W(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDrive4W* vehDrive4W, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static void updateDriveNW(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveNW* vehDriveNW, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static void updateTank(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveTank* vehDriveTank, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static void updateNoDrive(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleNoDrive* vehDriveTank, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static PxU32 computeNumberOfSubsteps(const PxVehicleWheelsSimData& wheelsSimData, const PxVec3& linVel, const PxTransform& globalPose, const PxVec3& forward)
{
const PxVec3 z=globalPose.q.rotate(forward);
const PxF32 vz=PxAbs(linVel.dot(z));
const PxF32 thresholdVz=wheelsSimData.mThresholdLongitudinalSpeed;
const PxU32 lowCount=wheelsSimData.mLowForwardSpeedSubStepCount;
const PxU32 highCount=wheelsSimData.mHighForwardSpeedSubStepCount;
const PxU32 count=(vz<thresholdVz ? lowCount : highCount);
return count;
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleWheelsDynData& wheels)
{
const PxU32 nbWheels4 = (wheels.mNbActiveWheels + 3) >> 2;
PxVehicleWheels4DynData* wheels4 = wheels.getWheel4DynData();
for(PxU32 i = 0; i < nbWheels4; i++)
{
wheels4[i].setInternalDynamicsToZero();
}
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDriveDynData& drive)
{
drive.setEngineRotationSpeed(0.0f);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleNoDrive* veh)
{
setInternalDynamicsToZero(veh->mWheelsDynData);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDrive4W* veh)
{
setInternalDynamicsToZero(veh->mWheelsDynData);
setInternalDynamicsToZero(veh->mDriveDynData);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDriveNW* veh)
{
veh->mDriveDynData.setEngineRotationSpeed(0.0f);
setInternalDynamicsToZero(veh->mWheelsDynData);
setInternalDynamicsToZero(veh->mDriveDynData);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDriveTank* veh)
{
setInternalDynamicsToZero(veh->mWheelsDynData);
setInternalDynamicsToZero(veh->mDriveDynData);
}
PX_INLINE static bool isOnDynamicActor(const PxVehicleWheelsSimData& wheelsSimData, const PxVehicleWheelsDynData& wheelsDynData)
{
const PxU32 numWheels4 = wheelsSimData.mNbWheels4;
const PxVehicleWheels4DynData* PX_RESTRICT wheels4DynDatas = wheelsDynData.mWheels4DynData;
for(PxU32 i=0;i<numWheels4;i++)
{
const PxRaycastBuffer* raycastResults = wheels4DynDatas[i].mRaycastResults;
const PxSweepBuffer* sweepResults = wheels4DynDatas[i].mSweepResults;
for(PxU32 j=0;j<4;j++)
{
if (!wheelsSimData.getIsWheelDisabled(4 * i + j) && (raycastResults || sweepResults))
{
const PxU32 hitCount = PxU32(raycastResults ? raycastResults[j].hasBlock : sweepResults[j].hasBlock);
PxRigidActor* hitActor = raycastResults ? raycastResults[j].block.actor : sweepResults[j].block.actor;
if(hitCount && hitActor && hitActor->is<PxRigidDynamic>())
return true;
}
}
}
return false;
}
PX_INLINE static void storeRaycasts(const PxVehicleWheels4DynData& dynData, PxWheelQueryResult* wheelQueryResults)
{
if(dynData.mRaycastResults)
{
for(PxU32 i=0;i<4;i++)
{
const PxVehicleWheels4DynData::SuspLineRaycast& raycast =
reinterpret_cast<const PxVehicleWheels4DynData::SuspLineRaycast&>(dynData.mQueryOrCachedHitResults);
wheelQueryResults[i].suspLineStart=raycast.mStarts[i];
wheelQueryResults[i].suspLineDir=raycast.mDirs[i];
wheelQueryResults[i].suspLineLength=raycast.mLengths[i];
}
}
else if(dynData.mSweepResults)
{
for(PxU32 i=0;i<4;i++)
{
const PxVehicleWheels4DynData::SuspLineSweep& sweep =
reinterpret_cast<const PxVehicleWheels4DynData::SuspLineSweep&>(dynData.mQueryOrCachedHitResults);
wheelQueryResults[i].suspLineStart=sweep.mStartPose[i].p;
wheelQueryResults[i].suspLineDir=sweep.mDirs[i];
wheelQueryResults[i].suspLineLength=sweep.mLengths[i];
}
}
else
{
for(PxU32 i=0;i<4;i++)
{
wheelQueryResults[i].suspLineStart=PxVec3(0,0,0);
wheelQueryResults[i].suspLineDir=PxVec3(0,0,0);
wheelQueryResults[i].suspLineLength=0;
}
}
}
PX_INLINE static void storeSuspWheelTireResults
(const ProcessSuspWheelTireOutputData& outputData, const PxF32* steerAngles, PxWheelQueryResult* wheelQueryResults, const PxU32 numWheels)
{
for(PxU32 i=0;i<numWheels;i++)
{
wheelQueryResults[i].isInAir=outputData.isInAir[i];
wheelQueryResults[i].tireContactActor=outputData.tireContactActors[i];
wheelQueryResults[i].tireContactShape=outputData.tireContactShapes[i];
wheelQueryResults[i].tireSurfaceMaterial=outputData.tireSurfaceMaterials[i];
wheelQueryResults[i].tireSurfaceType=outputData.tireSurfaceTypes[i];
wheelQueryResults[i].tireContactPoint=outputData.tireContactPoints[i];
wheelQueryResults[i].tireContactNormal=outputData.tireContactNormals[i];
wheelQueryResults[i].tireFriction=outputData.frictions[i];
wheelQueryResults[i].suspJounce=outputData.jounces[i];
wheelQueryResults[i].suspSpringForce=outputData.suspensionSpringForces[i];
wheelQueryResults[i].tireLongitudinalDir=outputData.tireLongitudinalDirs[i];
wheelQueryResults[i].tireLateralDir=outputData.tireLateralDirs[i];
wheelQueryResults[i].longitudinalSlip=outputData.longSlips[i];
wheelQueryResults[i].lateralSlip=outputData.latSlips[i];
wheelQueryResults[i].steerAngle=steerAngles[i];
}
}
PX_INLINE static void storeHitActorForces(const ProcessSuspWheelTireOutputData& outputData, PxVehicleWheelConcurrentUpdateData* wheelConcurrentUpdates, const PxU32 numWheels)
{
for(PxU32 i=0;i<numWheels;i++)
{
wheelConcurrentUpdates[i].hitActor=outputData.hitActors[i];
wheelConcurrentUpdates[i].hitActorForce+=outputData.hitActorForces[i];
wheelConcurrentUpdates[i].hitActorForcePosition=outputData.hitActorForcePositions[i];
}
}
static void shiftOrigin(const PxVec3& shift, const PxU32 numVehicles, PxVehicleWheels** vehicles);
};
void PxVehicleUpdate::updateDrive4W(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDrive4W* vehDrive4W, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception in transformInertiaTensor() on osx
START_TIMER(TIMER_ADMIN);
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL]>-0.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL]<1.01f,
"Illegal vehicle control value - accel must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE]>-0.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE]<1.01f,
"Illegal vehicle control value - brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE]>-0.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE]<1.01f,
"Illegal vehicle control value - handbrake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT]>-1.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT]<1.01f,
"Illegal vehicle control value - left steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]>-1.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]<1.01f,
"Illegal vehicle control value - right steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxAbs(vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]-
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT])<1.01f,
"Illegal vehicle control value - right steer value minus left steer value must be in range (-1,1)");
PX_CHECK_AND_RETURN(
!(vehDrive4W->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a drive4W with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehDrive4W->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
PX_CHECK_AND_RETURN(
NULL==vehConcurrentUpdates || vehConcurrentUpdates->nbConcurrentWheelUpdates >= vehDrive4W->mWheelsSimData.getNbWheels(),
"vehConcurrentUpdates->nbConcurrentWheelUpdates must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
{
//Check that the sense of left/right and forward/rear is true.
const PxVec3 fl=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eFRONT_LEFT);
const PxVec3 fr=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT);
const PxVec3 rl=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eREAR_LEFT);
const PxVec3 rr=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eREAR_RIGHT);
const PxVec3 right=context.sideAxis;
const PxF32 s0=computeSign((fr-fl).dot(right));
const PxF32 s1=computeSign((rr-rl).dot(right));
PX_CHECK_AND_RETURN(0==s0 || 0==s1 || s0==s1, "PxVehicle4W does not obey the rule that the eFRONT_RIGHT/eREAR_RIGHT wheels are to the right of the eFRONT_LEFT/eREAR_LEFT wheels");
}
#endif
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_GRAPHS);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehDrive4W->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehDrive4W->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
updateGraphDataInternalEngineDynamics(vehDrive4W->mDriveDynData.getEngineRotationSpeed(), vehTelemetryDataContext->engineGraphData);
}
#endif
END_TIMER(TIMER_GRAPHS);
START_TIMER(TIMER_ADMIN);
//Unpack the vehicle.
//Unpack the 4W simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehDrive4W->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehDrive4W->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehDrive4W->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehDrive4W->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehDrive4W->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4 - numActiveWheels);
const PxVehicleDriveSimData4W driveSimData=vehDrive4W->mDriveSimData;
PxVehicleDriveDynData& driveDynData=vehDrive4W->mDriveDynData;
PxRigidDynamic* vehActor=vehDrive4W->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
if(0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL) ||
driveDynData.getGearDown() || driveDynData.getGearUp())
{
finiteInputApplied=true;
}
//Awake or sleep.
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehDrive4W->mWheelsSimData, vehDrive4W->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to zero.
setInternalDynamicsToZero(vehDrive4W);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//We need to store data to pose the wheels at the end.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_COMPONENTS_UPDATE);
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Update the auto-box and decide whether to change gear up or down.
PxF32 autoboxCompensatedAnalogAccel = driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];
if(driveDynData.getUseAutoGears())
{
autoboxCompensatedAnalogAccel = processAutoBox(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL,timestep,driveSimData,driveDynData);
}
//Process gear-up/gear-down commands.
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
processGears(timestep,gearsData,driveDynData);
}
//Clutch strength;
PxF32 K;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
const PxU32 currentGear=driveDynData.getCurrentGear();
K=computeClutchStrength(clutchData, currentGear);
}
//Clutch accuracy
PxVehicleClutchAccuracyMode::Enum clutchAccuracyMode;
PxU32 clutchMaxIterations;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
clutchAccuracyMode = clutchData.mAccuracyMode;
clutchMaxIterations = clutchData.mEstimateIterations;
}
//Gear ratio.
PxF32 G;
PxU32 currentGear;
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
currentGear=driveDynData.getCurrentGear();
G=computeGearRatio(gearsData,currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataGearRatio(G, vehTelemetryDataContext->engineGraphData);
#endif
}
//Retrieve control values from vehicle controls.
PxF32 accel,brake,handbrake,steerLeft,steerRight;
PxF32 steer;
bool isIntentionToAccelerate;
{
getVehicle4WControlValues(driveDynData,accel,brake,handbrake,steerLeft,steerRight);
steer=steerRight-steerLeft;
accel=autoboxCompensatedAnalogAccel;
isIntentionToAccelerate = (accel>0.0f && 0.0f==brake && 0.0f==handbrake && PxVehicleGearsData::eNEUTRAL != currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataControlInputs(accel,brake,handbrake,steerLeft,steerRight, vehTelemetryDataContext->engineGraphData);
#endif
}
//Active wheels (wheels which have not been disabled).
bool activeWheelStates[4]={false,false,false,false};
{
computeWheelActiveStates(4*0, vehDrive4W->mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
}
//Get the drive wheels (the first 4 wheels are the drive wheels).
const PxVehicleWheels4SimData& wheels4SimData=wheels4SimDatas[0];
PxVehicleWheels4DynData& wheels4DynData=wheels4DynDatas[0];
const PxVehicleTireForceCalculator4& tires4ForceCalculator=tires4ForceCalculators[0];
//Contribution of each driven wheel to average wheel speed at clutch.
//With 4 driven wheels the average wheel speed at clutch is
//wAve = alpha0*w0 + alpha1*w1 + alpha2*w2 + alpha3*w3.
//This next bit of code computes alpha0,alpha1,alpha2,alpha3.
//For rear wheel drive alpha0=alpha1=0
//For front wheel drive alpha2=alpha3=0
PxF32 aveWheelSpeedContributions[4]={0.0f,0.0f,0.0f,0.0f};
{
const PxVehicleDifferential4WData& diffData=driveSimData.getDiffData();
computeDiffAveWheelSpeedContributions(diffData,handbrake,aveWheelSpeedContributions);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataClutchSlip(wheels4DynData.mWheelSpeeds,aveWheelSpeedContributions,driveDynData.getEngineRotationSpeed(),G, vehTelemetryDataContext->engineGraphData);
#endif
PX_CHECK_AND_RETURN(
(activeWheelStates[0] || 0.0f==aveWheelSpeedContributions[0]) &&
(activeWheelStates[1] || 0.0f==aveWheelSpeedContributions[1]) &&
(activeWheelStates[2] || 0.0f==aveWheelSpeedContributions[2]) &&
(activeWheelStates[3] || 0.0f==aveWheelSpeedContributions[3]),
"PxVehicleDifferential4WData must be configured so that no torque is delivered to a disabled wheel");
}
//Compute a per-wheel accelerator pedal value.
bool isAccelApplied[4]={false,false,false,false};
if(isIntentionToAccelerate)
{
PX_ASSERT(accel>0);
computeIsAccelApplied(aveWheelSpeedContributions, isAccelApplied);
}
//Ackermann-corrected steering angles for 1st block of 4 wheels.
//http://en.wikipedia.org/wiki/Ackermann_steering_geometry
PxF32 steerAngles[PX_MAX_NB_WHEELS];
PxMemZero(steerAngles, sizeof(steerAngles));
{
computeAckermannCorrectedSteerAngles(driveSimData,wheels4SimData,steer,steerAngles);
}
//All other wheels need a steer angle too.
for(PxU32 i = 1; i < numWheels4; i++)
{
for(PxU32 j = 0; j < 4; j++)
{
const PxF32 steerAngle = wheels4SimDatas[i].getWheelData(j).mToeAngle;
steerAngles[4*i + j] = steerAngle;
}
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, steerAngles, wheelLocalPoseRotations);
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_ADMIN);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehDrive4W->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehDrive4W->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, false, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehDrive4W->mWheelsSimData.mFlags};
END_TIMER(TIMER_ADMIN);
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
START_TIMER(TIMER_COMPONENTS_UPDATE);
//Update the drive/steer wheels and engine.
{
//Compute the brake torques.
PxF32 brakeTorques[4]={0.0f,0.0f,0.0f,0.0f};
bool isBrakeApplied[4]={false,false,false,false};
computeBrakeAndHandBrakeTorques
(&wheels4SimData.getWheelData(0),wheels4DynData.mWheelSpeeds,brake,handbrake,
brakeTorques,isBrakeApplied);
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_WHEELS);
//Compute jounces, slips, tire forces, suspension forces etc.
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, isAccelApplied, isBrakeApplied, steerAngles, activeWheelStates,
carChassisTransform, carChassisLinVel, carChassisAngVel,
wheelLocalPoseRotations, &wheels4SimData, &wheels4DynData, &tires4ForceCalculator, &tireLoadFilterData, numActiveWheelsPerBlock4[0]
};
ProcessSuspWheelTireOutputData outputData;
processSuspTireWheels(0, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData, vehTelemetryDataContext);
updateLowSpeedTimers(outputData.newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData.newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData.jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(steerAngles, const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData.cachedHitCounts, outputData.cachedHitPlanes, outputData.cachedHitDistances, outputData.cachedFrictionMultipliers, outputData.cachedHitQueryTypes, &wheels4DynData);
}
chassisForce+=outputData.chassisForce;
chassisTorque+=outputData.chassisTorque;
if(0 == k)
{
wheels4DynData.mVehicleConstraints->mData=outputData.vehConstraintData;
}
storeSuspWheelTireResults(outputData, inputData.steerAngles, &wheelQueryResults[4*0], numActiveWheelsPerBlock4[0]);
storeHitActorForces(outputData, &vehicleConcurrentUpdates.concurrentWheelUpdates[4*0], numActiveWheelsPerBlock4[0]);
END_TIMER(TIMER_WHEELS);
START_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
//Diff torque ratios needed (how we split the torque between the drive wheels).
//The sum of the torque ratios is always 1.0f.
//The drive torque delivered to each wheel is the total available drive torque multiplied by the
//diff torque ratio for each wheel.
PxF32 diffTorqueRatios[4]={0.0f,0.0f,0.0f,0.0f};
computeDiffTorqueRatios(driveSimData.getDiffData(),handbrake,wheels4DynData.mWheelSpeeds,diffTorqueRatios);
PX_CHECK_AND_RETURN(
(activeWheelStates[0] || 0.0f==diffTorqueRatios[0]) &&
(activeWheelStates[1] || 0.0f==diffTorqueRatios[1]) &&
(activeWheelStates[2] || 0.0f==diffTorqueRatios[2]) &&
(activeWheelStates[3] || 0.0f==diffTorqueRatios[3]),
"PxVehicleDifferential4WData must be configured so that no torque is delivered to a disabled wheel");
PxF32 engineDriveTorque;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData.getEngineRotationSpeed();
engineDriveTorque=computeEngineDriveTorque(engineData,engineOmega,accel);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataEngineDriveTorque(engineDriveTorque, vehTelemetryDataContext->engineGraphData);
#endif
}
PxF32 engineDampingRate;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
engineDampingRate=computeEngineDampingRate(engineData,currentGear,accel);
}
//Update the wheel and engine speeds - 5x5 matrix coupling engine and wheels.
ImplicitSolverInput implicitSolverInput=
{
subTimestep,
brake, handbrake,
K, G,
clutchAccuracyMode, clutchMaxIterations,
engineDriveTorque, engineDampingRate,
diffTorqueRatios, aveWheelSpeedContributions,
brakeTorques, isBrakeApplied, outputData.tireTorques,
1, 4,
&wheels4SimData, &driveSimData
};
ImplicitSolverOutput implicitSolverOutput=
{
&wheels4DynData, &driveDynData
};
solveDrive4WInternaDynamicsEnginePlusDrivenWheels(implicitSolverInput, &implicitSolverOutput);
END_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
START_TIMER(TIMER_POSTUPDATE1);
//Integrate wheel rotation angle (theta += omega*dt)
integrateWheelRotationAngles
(subTimestep,
K,G,engineDriveTorque,
outputData.jounces,diffTorqueRatios,outputData.forwardSpeeds,isBrakeApplied,
driveSimData,wheels4SimData,
driveDynData,wheels4DynData);
}
END_TIMER(TIMER_POSTUPDATE1);
//////////////////////////////////////////////////////////////////////////
//susp and tire forces from extra wheels (non-driven wheels)
//////////////////////////////////////////////////////////////////////////
for(PxU32 j=1;j<numWheels4;j++)
{
//We already computed the steer angles above.
PxF32* extraWheelSteerAngles= steerAngles + 4*j;
//Only the driven wheels are connected to the diff.
PxF32 extraWheelsDiffTorqueRatios[4]={0.0f,0.0f,0.0f,0.0f};
bool extraIsAccelApplied[4]={false,false,false,false};
//The extra wheels do have brakes.
PxF32 extraWheelBrakeTorques[4]={0.0f,0.0f,0.0f,0.0f};
bool extraIsBrakeApplied[4]={false,false,false,false};
computeBrakeAndHandBrakeTorques
(&wheels4SimDatas[j].getWheelData(0),wheels4DynDatas[j].mWheelSpeeds,brake,handbrake,
extraWheelBrakeTorques,extraIsBrakeApplied);
//The extra wheels can be disabled or enabled.
bool extraWheelActiveStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, vehDrive4W->mWheelsSimData.mActiveWheelsBitmapBuffer, extraWheelActiveStates);
ProcessSuspWheelTireInputData extraInputData=
{
isIntentionToAccelerate, extraIsAccelApplied, extraIsBrakeApplied, extraWheelSteerAngles, extraWheelActiveStates,
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[j], &wheels4SimDatas[j], &wheels4DynDatas[j], &tires4ForceCalculators[j], &tireLoadFilterData, numActiveWheelsPerBlock4[j],
};
ProcessSuspWheelTireOutputData extraOutputData;
processSuspTireWheels(4*j, constData, extraInputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
extraOutputData, vehTelemetryDataContext);
updateLowSpeedTimers(extraOutputData.newLowForwardSpeedTimers, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(extraOutputData.newLowSideSpeedTimers, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(extraOutputData.jounces, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mJounces));
updateSteers(extraWheelSteerAngles, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(extraOutputData.cachedHitCounts, extraOutputData.cachedHitPlanes, extraOutputData.cachedHitDistances, extraOutputData.cachedFrictionMultipliers, extraOutputData.cachedHitQueryTypes, &wheels4DynDatas[j]);
}
chassisForce+=extraOutputData.chassisForce;
chassisTorque+=extraOutputData.chassisTorque;
if(0 == k)
{
wheels4DynDatas[j].mVehicleConstraints->mData=extraOutputData.vehConstraintData;
}
storeSuspWheelTireResults(extraOutputData, extraInputData.steerAngles, &wheelQueryResults[4*j], numActiveWheelsPerBlock4[j]);
storeHitActorForces(extraOutputData, &vehicleConcurrentUpdates.concurrentWheelUpdates[4*j], numActiveWheelsPerBlock4[j]);
//Integrate the tire torques (omega += (tireTorque + brakeTorque)*dt)
integrateUndriveWheelRotationSpeeds(subTimestep, brake, handbrake, extraOutputData.tireTorques, extraWheelBrakeTorques, wheels4SimDatas[j], wheels4DynDatas[j]);
//Integrate wheel rotation angle (theta += omega*dt)
integrateWheelRotationAngles
(subTimestep,
0,0,0,
extraOutputData.jounces,extraWheelsDiffTorqueRatios,extraOutputData.forwardSpeeds,extraIsBrakeApplied,
driveSimData,wheels4SimDatas[j],
driveDynData,wheels4DynDatas[j]);
}
START_TIMER(TIMER_POSTUPDATE2);
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehDrive4W->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate one sustep.
integrateBody(inverseChassisMass, inverseInertia ,chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
END_TIMER(TIMER_POSTUPDATE2);
}
START_TIMER(TIMER_POSTUPDATE3);
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;;
}
//Compute and pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
//Copy the poses to the wheelQueryResults
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
//Copy the poses to the concurrent update data.
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
//Copy the poses to the wheelQueryResults
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
//Copy the poses to the concurrent update data.
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehDrive4W};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
END_TIMER(TIMER_POSTUPDATE3);
}
void PxVehicleUpdate::updateDriveNW
(const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveNW* vehDriveNW, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception triggered in transformInertiaTensor() on osx
START_TIMER(TIMER_ADMIN);
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL]>-0.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL]<1.01f,
"Illegal vehicle control value - accel must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_BRAKE]>-0.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_BRAKE]<1.01f,
"Illegal vehicle control value - brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_HANDBRAKE]>-0.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_HANDBRAKE]<1.01f,
"Illegal vehicle control value - handbrake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT]>-1.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT]<1.01f,
"Illegal vehicle control value - left steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT]>-1.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT]<1.01f,
"Illegal vehicle control value - right steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxAbs(vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT]-
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT])<1.01f,
"Illegal vehicle control value - right steer value minus left steer value must be in range (-1,1)");
PX_CHECK_AND_RETURN(
!(vehDriveNW->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a drive4W with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehDriveNW->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
for(PxU32 i=0;i<vehDriveNW->mWheelsSimData.getNbWheels();i++)
{
PX_CHECK_AND_RETURN(!vehDriveNW->mWheelsSimData.getIsWheelDisabled(i) || !vehDriveNW->mDriveSimData.getDiffData().getIsDrivenWheel(i),
"PxVehicleDifferentialNWData must be configured so that no torque is delivered to a disabled wheel");
}
#endif
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_GRAPHS);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehDriveNW->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehDriveNW->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
updateGraphDataInternalEngineDynamics(vehDriveNW->mDriveDynData.getEngineRotationSpeed(), vehTelemetryDataContext->engineGraphData);
}
#endif
END_TIMER(TIMER_GRAPHS);
START_TIMER(TIMER_ADMIN);
//Unpack the vehicle.
//Unpack the NW simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehDriveNW->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehDriveNW->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehDriveNW->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehDriveNW->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehDriveNW->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4 - numActiveWheels);
const PxVehicleDriveSimDataNW driveSimData=vehDriveNW->mDriveSimData;
PxVehicleDriveDynData& driveDynData=vehDriveNW->mDriveDynData;
PxRigidDynamic* vehActor=vehDriveNW->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
if(0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL) ||
driveDynData.getGearDown() || driveDynData.getGearUp())
{
finiteInputApplied=true;
}
//Awake or sleep.
{
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehDriveNW->mWheelsSimData, vehDriveNW->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to sleep.
setInternalDynamicsToZero(vehDriveNW);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
}
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//Need to store report data to pose the wheels.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_COMPONENTS_UPDATE);
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Update the auto-box and decide whether to change gear up or down.
PxF32 autoboxCompensatedAnalogAccel = driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL];
if(driveDynData.getUseAutoGears())
{
autoboxCompensatedAnalogAccel = processAutoBox(PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL,timestep,driveSimData,driveDynData);
}
//Process gear-up/gear-down commands.
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
processGears(timestep,gearsData,driveDynData);
}
//Clutch strength.
PxF32 K;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
const PxU32 currentGear=driveDynData.getCurrentGear();
K=computeClutchStrength(clutchData, currentGear);
}
//Clutch accuracy.
PxVehicleClutchAccuracyMode::Enum clutchAccuracyMode;
PxU32 clutchMaxIterations;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
clutchAccuracyMode=clutchData.mAccuracyMode;
clutchMaxIterations=clutchData.mEstimateIterations;
}
//Gear ratio.
PxF32 G;
PxU32 currentGear;
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
currentGear=driveDynData.getCurrentGear();
G=computeGearRatio(gearsData,currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataGearRatio(G, vehTelemetryDataContext->engineGraphData);
#endif
}
//Retrieve control values from vehicle controls.
PxF32 accel,brake,handbrake,steerLeft,steerRight;
PxF32 steer;
bool isIntentionToAccelerate;
{
getVehicleNWControlValues(driveDynData,accel,brake,handbrake,steerLeft,steerRight);
steer=steerRight-steerLeft;
accel=autoboxCompensatedAnalogAccel;
isIntentionToAccelerate = (accel>0.0f && 0.0f==brake && 0.0f==handbrake && PxVehicleGearsData::eNEUTRAL != currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataControlInputs(accel,brake,handbrake,steerLeft,steerRight, vehTelemetryDataContext->engineGraphData);
#endif
}
//Compute the wheels that are disabled or enabled.
bool activeWheelStates[PX_MAX_NB_WHEELS];
PxMemSet(activeWheelStates, 0, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeWheelActiveStates(4*i, vehDriveNW->mWheelsSimData.mActiveWheelsBitmapBuffer, &activeWheelStates[4*i]);
}
//Contribution of each driven wheel to average wheel speed at clutch.
//For NW drive equal torque split is supported.
const PxVehicleDifferentialNWData diffData=driveSimData.getDiffData();
const PxF32 invNumDrivenWheels=diffData.mInvNbDrivenWheels;
PxF32 aveWheelSpeedContributions[PX_MAX_NB_WHEELS];
PxMemSet(aveWheelSpeedContributions, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numActiveWheels;i++)
{
aveWheelSpeedContributions[i] = diffData.getIsDrivenWheel(i) ? invNumDrivenWheels : 0;
}
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataClutchSlipNW(numWheels4,wheels4DynDatas,aveWheelSpeedContributions,driveDynData.getEngineRotationSpeed(),G, vehTelemetryDataContext->engineGraphData);
#endif
//Compute a per-wheel accelerator pedal value.
bool isAccelApplied[PX_MAX_NB_WHEELS];
PxMemSet(isAccelApplied, 0, sizeof(bool)*PX_MAX_NB_WHEELS);
if(isIntentionToAccelerate)
{
PX_ASSERT(accel>0);
for(PxU32 i=0;i<numWheels4;i++)
{
computeIsAccelApplied(&aveWheelSpeedContributions[4*i],&isAccelApplied[4*i]);
}
}
//Steer angles.
PxF32 steerAngles[PX_MAX_NB_WHEELS];
PxMemSet(steerAngles, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxVehicleWheelData& wheelData=vehDriveNW->mWheelsSimData.getWheelData(i);
const PxF32 steerGain=wheelData.mMaxSteer;
const PxF32 toe=wheelData.mToeAngle;
steerAngles[i]=steerGain*steer + toe;
}
//Diff torque ratios needed (how we split the torque between the drive wheels).
//The sum of the torque ratios is always 1.0f.
//The drive torque delivered to each wheel is the total available drive torque multiplied by the
//diff torque ratio for each wheel.
PxF32 diffTorqueRatios[PX_MAX_NB_WHEELS];
PxMemSet(diffTorqueRatios, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numActiveWheels;i++)
{
diffTorqueRatios[i] = diffData.getIsDrivenWheel(i) ? invNumDrivenWheels : 0.0f;
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, steerAngles, wheelLocalPoseRotations);
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_ADMIN);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehDriveNW->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehDriveNW->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, false, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehDriveNW->mWheelsSimData.mFlags};
END_TIMER(TIMER_ADMIN);
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
START_TIMER(TIMER_COMPONENTS_UPDATE);
PxF32 brakeTorques[PX_MAX_NB_WHEELS];
bool isBrakeApplied[PX_MAX_NB_WHEELS];
PxMemSet(brakeTorques, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemSet(isBrakeApplied, false, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeBrakeAndHandBrakeTorques(&wheels4SimDatas[i].getWheelData(0),wheels4DynDatas[i].mWheelSpeeds,brake,handbrake,&brakeTorques[4*i],&isBrakeApplied[4*i]);
}
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_WHEELS);
ProcessSuspWheelTireOutputData outputData[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, &isAccelApplied[4*i], &isBrakeApplied[4*i], &steerAngles[4*i], &activeWheelStates[4*i],
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[i], &wheels4SimDatas[i], &wheels4DynDatas[i], &tires4ForceCalculators[i], &tireLoadFilterData, numActiveWheelsPerBlock4[i]
};
processSuspTireWheels(4*i, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData[i], vehTelemetryDataContext);
updateLowSpeedTimers(outputData[i].newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData[i].newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData[i].jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(&steerAngles[4*i], const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData[i].cachedHitCounts, outputData[i].cachedHitPlanes, outputData[i].cachedHitDistances, outputData[i].cachedFrictionMultipliers, outputData[i].cachedHitQueryTypes, &wheels4DynDatas[i]);
}
chassisForce+=outputData[i].chassisForce;
chassisTorque+=outputData[i].chassisTorque;
if(0 == k)
{
wheels4DynDatas[i].mVehicleConstraints->mData=outputData[i].vehConstraintData;
}
storeSuspWheelTireResults(outputData[i], inputData.steerAngles, &wheelQueryResults[4*i], numActiveWheelsPerBlock4[i]);
storeHitActorForces(outputData[i], &vehicleConcurrentUpdates.concurrentWheelUpdates[4*i], numActiveWheelsPerBlock4[i]);
}
//Store the tire torques in a single array.
PxF32 tireTorques[PX_MAX_NB_WHEELS];
for(PxU32 i=0;i<numWheels4;i++)
{
tireTorques[4*i+0]=outputData[i].tireTorques[0];
tireTorques[4*i+1]=outputData[i].tireTorques[1];
tireTorques[4*i+2]=outputData[i].tireTorques[2];
tireTorques[4*i+3]=outputData[i].tireTorques[3];
}
END_TIMER(TIMER_WHEELS);
START_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
PxF32 engineDriveTorque;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData.getEngineRotationSpeed();
engineDriveTorque=computeEngineDriveTorque(engineData,engineOmega,accel);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataEngineDriveTorque(engineDriveTorque, vehTelemetryDataContext->engineGraphData);
#endif
}
PxF32 engineDampingRate;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
engineDampingRate=computeEngineDampingRate(engineData,currentGear,accel);
}
//Update the wheel and engine speeds - (N+1)*(N+1) matrix coupling engine and wheels.
ImplicitSolverInput implicitSolverInput=
{
subTimestep,
brake, handbrake,
K, G,
clutchAccuracyMode, clutchMaxIterations,
engineDriveTorque, engineDampingRate,
diffTorqueRatios, aveWheelSpeedContributions,
brakeTorques, isBrakeApplied, tireTorques,
numWheels4, numActiveWheels,
wheels4SimDatas, &driveSimData
};
ImplicitSolverOutput implicitSolverOutput=
{
wheels4DynDatas, &driveDynData
};
solveDriveNWInternalDynamicsEnginePlusDrivenWheels(implicitSolverInput, &implicitSolverOutput);
END_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
START_TIMER(TIMER_POSTUPDATE1);
//Integrate wheel rotation angle (theta += omega*dt)
for(PxU32 i=0;i<numWheels4;i++)
{
integrateWheelRotationAngles
(subTimestep,
K,G,engineDriveTorque,
outputData[i].jounces,&diffTorqueRatios[4*i],outputData[i].forwardSpeeds,&isBrakeApplied[4*i],
driveSimData,wheels4SimDatas[i],
driveDynData,wheels4DynDatas[i]);
}
END_TIMER(TIMER_POSTUPDATE1);
START_TIMER(TIMER_POSTUPDATE2);
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehDriveNW->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate the chassis velocity by applying the accumulated force and torque.
integrateBody(inverseChassisMass, inverseInertia, chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
END_TIMER(TIMER_POSTUPDATE2);
}
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;
}
START_TIMER(TIMER_POSTUPDATE3);
//Pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehDriveNW};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
END_TIMER(TIMER_POSTUPDATE3);
}
void PxVehicleUpdate::updateTank
(const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveTank* vehDriveTank, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception in transformInertiaTensor()
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL]<1.01f,
"Illegal tank control value - accel must be in range (0,1)" );
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT]<1.01f,
"Illegal tank control value - left brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT]<1.01f,
"Illegal tank control right value - right brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]>-1.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]<1.01f,
"Illegal tank control value - left thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]>-1.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]<1.01f,
"Illegal tank control value - right thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
(vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]<1.01f),
"Illegal tank control value - left thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
(vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]<1.01f),
"Illegal tank control value - right thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
0.0f==
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]*
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT],
"Illegal tank control value - thrust left and brake left simultaneously non-zero in standard drive mode");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
0.0f==
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]*
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT],
"Illegal tank control value - thrust right and brake right simultaneously non-zero in standard drive mode");
PX_CHECK_AND_RETURN(
!(vehDriveTank->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a tank with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehDriveTank->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
{
PxVec3 fl=vehDriveTank->mWheelsSimData.getWheelCentreOffset(PxVehicleDriveTankWheelOrder::eFRONT_LEFT);
PxVec3 fr=vehDriveTank->mWheelsSimData.getWheelCentreOffset(PxVehicleDriveTankWheelOrder::eFRONT_RIGHT);
const PxVec3 right=context.sideAxis;
const PxF32 s0=computeSign((fr-fl).dot(right));
for(PxU32 i=PxVehicleDriveTankWheelOrder::e1ST_FROM_FRONT_LEFT;i<vehDriveTank->mWheelsSimData.getNbWheels();i+=2)
{
PxVec3 rl=vehDriveTank->mWheelsSimData.getWheelCentreOffset(i);
PxVec3 rr=vehDriveTank->mWheelsSimData.getWheelCentreOffset(i+1);
const PxF32 t0=computeSign((rr-rl).dot(right));
PX_CHECK_AND_RETURN(s0==t0 || 0==s0 || 0==t0, "Tank wheels must be ordered with odd wheels on one side and even wheels on the other side");
}
}
#endif
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehDriveTank->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehDriveTank->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
updateGraphDataInternalEngineDynamics(vehDriveTank->mDriveDynData.getEngineRotationSpeed(), vehTelemetryDataContext->engineGraphData);
}
#endif
//Unpack the tank simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehDriveTank->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehDriveTank->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehDriveTank->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehDriveTank->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehDriveTank->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4-numActiveWheels);
const PxVehicleDriveSimData driveSimData=vehDriveTank->mDriveSimData;
PxVehicleDriveDynData& driveDynData=vehDriveTank->mDriveDynData;
PxRigidDynamic* vehActor=vehDriveTank->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
if(0!=driveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT) ||
0!=driveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT) ||
0!=driveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL) ||
driveDynData.getGearDown() || driveDynData.getGearUp())
{
finiteInputApplied=true;
}
//Awake or sleep.
{
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehDriveTank->mWheelsSimData, vehDriveTank->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to sleep.
setInternalDynamicsToZero(vehDriveTank);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
}
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the suspension/tire constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//Need to store report data to pose the wheels.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Retrieve control values from vehicle controls.
PxF32 accel,brakeLeft,brakeRight,thrustLeft,thrustRight;
{
getTankControlValues(driveDynData,accel,brakeLeft,brakeRight,thrustLeft,thrustRight);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataControlInputs(accel,brakeLeft,brakeRight,thrustLeft,thrustRight, vehTelemetryDataContext->engineGraphData);
#endif
}
//Update the auto-box and decide whether to change gear up or down.
//If the tank is supposed to turn sharply don't process the auto-box.
bool useAutoGears;
if(vehDriveTank->getDriveModel()==PxVehicleDriveTankControlModel::eSPECIAL)
{
useAutoGears = driveDynData.getUseAutoGears() ? ((((thrustRight*thrustLeft) >= 0.0f) || (0.0f==thrustLeft && 0.0f==thrustRight)) ? true : false) : false;
}
else
{
useAutoGears = driveDynData.getUseAutoGears() ? (thrustRight*brakeLeft>0 || thrustLeft*brakeRight>0 ? false : true) : false;
}
if(useAutoGears)
{
processAutoBox(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL,timestep,driveSimData,driveDynData);
}
//Process gear-up/gear-down commands.
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
processGears(timestep,gearsData,driveDynData);
}
//Clutch strength;
PxF32 K;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
const PxU32 currentGear=driveDynData.getCurrentGear();
K=computeClutchStrength(clutchData, currentGear);
}
//Gear ratio.
PxF32 G;
PxU32 currentGear;
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
currentGear=driveDynData.getCurrentGear();
G=computeGearRatio(gearsData,currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataGearRatio(G, vehTelemetryDataContext->engineGraphData);
#endif
}
bool isIntentionToAccelerate;
{
const PxF32 thrustLeftAbs=PxAbs(thrustLeft);
const PxF32 thrustRightAbs=PxAbs(thrustRight);
isIntentionToAccelerate = (accel*(thrustLeftAbs+thrustRightAbs)>0 && PxVehicleGearsData::eNEUTRAL != currentGear);
}
//Compute the wheels that are enabled/disabled.
bool activeWheelStates[PX_MAX_NB_WHEELS];
PxMemZero(activeWheelStates, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeWheelActiveStates(4*i, vehDriveTank->mWheelsSimData.mActiveWheelsBitmapBuffer, &activeWheelStates[4*i]);
}
//Set up contribution of each wheel to the average wheel speed at the clutch
//Set up the torque ratio delivered by the diff to each wheel.
//Set the sign of the gearing applied to the left and right wheels.
PxF32 aveWheelSpeedContributions[PX_MAX_NB_WHEELS];
PxF32 diffTorqueRatios[PX_MAX_NB_WHEELS];
PxF32 wheelGearings[PX_MAX_NB_WHEELS];
PxMemZero(aveWheelSpeedContributions, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemZero(diffTorqueRatios, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemZero(wheelGearings, sizeof(PxF32)*PX_MAX_NB_WHEELS);
computeTankDiff
(thrustLeft, thrustRight,
numActiveWheels, activeWheelStates,
aveWheelSpeedContributions, diffTorqueRatios, wheelGearings);
//Compute an accelerator pedal value per wheel.
bool isAccelApplied[PX_MAX_NB_WHEELS];
PxMemZero(isAccelApplied, sizeof(bool)*PX_MAX_NB_WHEELS);
if(isIntentionToAccelerate)
{
PX_ASSERT(accel>0);
for(PxU32 i=0;i<numWheels4;i++)
{
computeIsAccelApplied(&aveWheelSpeedContributions[4*i], &isAccelApplied[4*i]);
}
}
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataClutchSlip(wheels4DynDatas[0].mWheelSpeeds,aveWheelSpeedContributions,driveDynData.getEngineRotationSpeed(),G, vehTelemetryDataContext->engineGraphData);
#endif
//Ackermann-corrected steer angles
//For tanks this is always zero because they turn by torque delivery rather than a steering mechanism.
PxF32 steerAngles[PX_MAX_NB_WHEELS];
PxMemZero(steerAngles, sizeof(PxF32)*PX_MAX_NB_WHEELS);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, steerAngles, wheelLocalPoseRotations);
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehDriveTank->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehDriveTank->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, true, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehDriveTank->mWheelsSimData.mFlags};
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
//Compute the brake torques.
PxF32 brakeTorques[PX_MAX_NB_WHEELS];
bool isBrakeApplied[PX_MAX_NB_WHEELS];
PxMemZero(brakeTorques, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemZero(isBrakeApplied, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeTankBrakeTorques
(&wheels4SimDatas[i].getWheelData(0),wheels4DynDatas[i].mWheelSpeeds,brakeLeft,brakeRight,
&brakeTorques[i*4],&isBrakeApplied[i*4]);
}
//Compute jounces, slips, tire forces, suspension forces etc.
ProcessSuspWheelTireOutputData outputData[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, &isAccelApplied[i*4], &isBrakeApplied[i*4], &steerAngles[i*4], &activeWheelStates[4*i],
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[i], &wheels4SimDatas[i], &wheels4DynDatas[i], &tires4ForceCalculators[i], &tireLoadFilterData, numActiveWheelsPerBlock4[i],
};
processSuspTireWheels(i*4, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData[i], vehTelemetryDataContext);
updateLowSpeedTimers(outputData[i].newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData[i].newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData[i].jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(&steerAngles[i*4], const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData[i].cachedHitCounts, outputData[i].cachedHitPlanes, outputData[i].cachedHitDistances, outputData[i].cachedFrictionMultipliers, outputData[i].cachedHitQueryTypes, &wheels4DynDatas[i]);
}
chassisForce+=outputData[i].chassisForce;
chassisTorque+=outputData[i].chassisTorque;
if(0 == k)
{
wheels4DynDatas[i].mVehicleConstraints->mData=outputData[i].vehConstraintData;
}
storeSuspWheelTireResults(outputData[i], inputData.steerAngles, &wheelQueryResults[4*i], numActiveWheelsPerBlock4[i]);
storeHitActorForces(outputData[i], &vehicleConcurrentUpdates.concurrentWheelUpdates[4*i], numActiveWheelsPerBlock4[i]);
}
//Copy the tire torques to a single array.
PxF32 tireTorques[PX_MAX_NB_WHEELS];
for(PxU32 i=0;i<numWheels4;i++)
{
tireTorques[4*i+0]=outputData[i].tireTorques[0];
tireTorques[4*i+1]=outputData[i].tireTorques[1];
tireTorques[4*i+2]=outputData[i].tireTorques[2];
tireTorques[4*i+3]=outputData[i].tireTorques[3];
}
PxF32 engineDriveTorque;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData.getEngineRotationSpeed();
engineDriveTorque=computeEngineDriveTorque(engineData,engineOmega,accel);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataEngineDriveTorque(engineDriveTorque, vehTelemetryDataContext->engineGraphData);
#endif
}
PxF32 engineDampingRate;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
engineDampingRate=computeEngineDampingRate(engineData,currentGear,accel);
}
//Update the wheel and engine speeds - 5x5 matrix coupling engine and wheels.
ImplicitSolverInput implicitSolverInput =
{
subTimestep,
0.0f, 0.0f,
K, G,
PxVehicleClutchAccuracyMode::eBEST_POSSIBLE, 0,
engineDriveTorque, engineDampingRate,
diffTorqueRatios, aveWheelSpeedContributions,
brakeTorques, isBrakeApplied, tireTorques,
numWheels4, numActiveWheels,
wheels4SimDatas, &driveSimData
};
ImplicitSolverOutput implicitSolverOutput =
{
wheels4DynDatas, &driveDynData
};
solveTankInternaDynamicsEnginePlusDrivenWheels(implicitSolverInput, activeWheelStates, wheelGearings, &implicitSolverOutput);
//Integrate wheel rotation angle (theta += omega*dt)
for(PxU32 i=0;i<numWheels4;i++)
{
integrateWheelRotationAngles
(subTimestep,
K,G,engineDriveTorque,
outputData[i].jounces,diffTorqueRatios,outputData[i].forwardSpeeds,isBrakeApplied,
driveSimData,wheels4SimDatas[i],
driveDynData,wheels4DynDatas[i]);
}
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehDriveTank->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate the chassis velocity by applying the accumulated force and torque.
integrateBody(inverseChassisMass, inverseInertia, chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
}
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;
}
//Pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehDriveTank};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
}
void PxVehicleUpdate::updateNoDrive
(const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleNoDrive* vehNoDrive, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception in transformInertiaTensor() on osx
PX_CHECK_AND_RETURN(
!(vehNoDrive->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a PxVehicleNoDrive with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehNoDrive->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
for(PxU32 i=0;i<vehNoDrive->mWheelsSimData.getNbWheels();i++)
{
PX_CHECK_AND_RETURN(
!vehNoDrive->mWheelsSimData.getIsWheelDisabled(i) || 0==vehNoDrive->getDriveTorque(i),
"Disabled wheels should have zero drive torque applied to them.");
}
#endif
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehNoDrive->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehNoDrive->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
}
#endif
//Unpack the tank simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehNoDrive->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehNoDrive->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehNoDrive->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehNoDrive->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehNoDrive->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4-numActiveWheels);
PxRigidDynamic* vehActor=vehNoDrive->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
for(PxU32 i=0;i<numActiveWheels;i++)
{
if(vehNoDrive->getDriveTorque(i) != 0.0f)
{
finiteInputApplied=true;
break;
}
if(vehNoDrive->getSteerAngle(i)!=0.0f)
{
finiteInputApplied=true;
break;
}
}
//Wake or sleep.
{
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehNoDrive->mWheelsSimData, vehNoDrive->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to sleep.
setInternalDynamicsToZero(vehNoDrive);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
}
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the suspension/tire constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//Need to store report data to pose the wheels.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, vehNoDrive->mSteerAngles, wheelLocalPoseRotations);
PxF32 maxAccel=0;
PxF32 maxBrake=0;
for(PxU32 i=0;i<numActiveWheels;i++)
{
maxAccel = PxMax(PxAbs(vehNoDrive->mDriveTorques[i]), maxAccel);
maxBrake = PxMax(PxAbs(vehNoDrive->mBrakeTorques[i]), maxBrake);
}
const bool isIntentionToAccelerate = (maxAccel>0.0f && 0.0f==maxBrake);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehNoDrive->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehNoDrive->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, false, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehNoDrive->mWheelsSimData.mFlags};
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
for(PxU32 i=0;i<numWheels4;i++)
{
//Get the raw input torques.
const PxF32* PX_RESTRICT rawBrakeTorques=&vehNoDrive->mBrakeTorques[4*i];
const PxF32* PX_RESTRICT rawSteerAngles=&vehNoDrive->mSteerAngles[4*i];
const PxF32* PX_RESTRICT rawDriveTorques=&vehNoDrive->mDriveTorques[4*i];
//Work out which wheels are enabled.
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*i, vehNoDrive->mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
const PxVehicleWheels4SimData& wheels4SimData=wheels4SimDatas[i];
PxVehicleWheels4DynData& wheels4DynData=wheels4DynDatas[i];
//Compute the brake torques.
PxF32 brakeTorques[4]={0.0f,0.0f,0.0f,0.0f};
bool isBrakeApplied[4]={false,false,false,false};
computeNoDriveBrakeTorques
(wheels4SimData.mWheels,wheels4DynData.mWheelSpeeds,rawBrakeTorques,
brakeTorques,isBrakeApplied);
//Compute the per wheel accel pedal values.
bool isAccelApplied[4]={false,false,false,false};
if(isIntentionToAccelerate)
{
computeIsAccelApplied(rawDriveTorques, isAccelApplied);
}
//Compute jounces, slips, tire forces, suspension forces etc.
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, isAccelApplied, isBrakeApplied, rawSteerAngles, activeWheelStates,
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[i], &wheels4SimData, &wheels4DynData, &tires4ForceCalculators[i], &tireLoadFilterData, numActiveWheelsPerBlock4[i]
};
ProcessSuspWheelTireOutputData outputData;
processSuspTireWheels(4*i, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData, vehTelemetryDataContext);
updateLowSpeedTimers(outputData.newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData.newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData.jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(rawSteerAngles, const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData.cachedHitCounts, outputData.cachedHitPlanes, outputData.cachedHitDistances, outputData.cachedFrictionMultipliers, outputData.cachedHitQueryTypes, &wheels4DynData);
}
chassisForce+=outputData.chassisForce;
chassisTorque+=outputData.chassisTorque;
if(0 == k)
{
wheels4DynDatas[i].mVehicleConstraints->mData=outputData.vehConstraintData;
}
storeSuspWheelTireResults(outputData, inputData.steerAngles, &wheelQueryResults[4*i], numActiveWheelsPerBlock4[i]);
storeHitActorForces(outputData, &vehicleConcurrentUpdates.concurrentWheelUpdates[4*i], numActiveWheelsPerBlock4[i]);
//Integrate wheel speeds.
const PxF32 wheelDampingRates[4]=
{
wheels4SimData.getWheelData(0).mDampingRate,
wheels4SimData.getWheelData(1).mDampingRate,
wheels4SimData.getWheelData(2).mDampingRate,
wheels4SimData.getWheelData(3).mDampingRate
};
integrateNoDriveWheelSpeeds(
subTimestep,
brakeTorques,isBrakeApplied,rawDriveTorques,outputData.tireTorques,wheelDampingRates,
wheels4SimData,wheels4DynData);
integrateNoDriveWheelRotationAngles(
subTimestep,
rawDriveTorques,
outputData.jounces, outputData.forwardSpeeds, isBrakeApplied,
wheels4SimData,
wheels4DynData);
}
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehNoDrive->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate the chassis velocity by applying the accumulated force and torque.
integrateBody(inverseChassisMass, inverseInertia, chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
}
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;
}
//Pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehNoDrive};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
}
void PxVehicleUpdate::shiftOrigin(const PxVec3& shift, const PxU32 numVehicles, PxVehicleWheels** vehicles)
{
for(PxU32 i=0; i < numVehicles; i++)
{
//Get the current car.
PxVehicleWheels& veh = *vehicles[i];
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynData=veh.mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=veh.mWheelsSimData.mNbWheels4;
//Blocks of 4 wheels.
for(PxU32 j=0; j < numWheels4; j++)
{
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
if (wheels4DynData[j].mRaycastResults) // this is set when a query has been scheduled
{
PxVehicleWheels4DynData::SuspLineRaycast& raycast =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineRaycast&>(wheels4DynData[j].mQueryOrCachedHitResults);
for(PxU32 k=0; k < 4; k++)
{
if (activeWheelStates[k])
{
raycast.mStarts[k] -= shift;
if (wheels4DynData[j].mRaycastResults[k].hasBlock)
const_cast<PxVec3&>(wheels4DynData[j].mRaycastResults[k].block.position) -= shift;
}
}
}
else if(wheels4DynData[i].mSweepResults)
{
PxVehicleWheels4DynData::SuspLineSweep& sweep =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineSweep&>(wheels4DynData[j].mQueryOrCachedHitResults);
for(PxU32 k=0; k < 4; k++)
{
if (activeWheelStates[k])
{
sweep.mStartPose[k].p -= shift;
if (wheels4DynData[j].mSweepResults[k].hasBlock)
const_cast<PxVec3&>(wheels4DynData[j].mSweepResults[k].block.position) -= shift;
}
}
}
}
}
}
}//namespace physx
#if PX_DEBUG_VEHICLE_ON
/////////////////////////////////////////////////////////////////////////////////
//Update a single vehicle of any type and record the associated telemetry data.
/////////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void PxVehicleUpdate::updateSingleVehicleAndStoreTelemetryData
(const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
PxVehicleWheels* vehWheels, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleTelemetryData& telemetryData,
PxVehicleConcurrentUpdateData* vehConcurrentUpdates, const PxVehicleContext& context)
{
START_TIMER(TIMER_ALL);
PX_CHECK_MSG(vehWheels->mWheelsSimData.getNbWheels()==telemetryData.getNbWheelGraphs(), "vehicle and telemetry data need to have the same number of wheels");
VehicleTelemetryDataContext vehicleTelemetryDataContext;
PxMemZero(vehicleTelemetryDataContext.wheelGraphData, sizeof(vehicleTelemetryDataContext.wheelGraphData));
PxMemZero(vehicleTelemetryDataContext.engineGraphData, sizeof(vehicleTelemetryDataContext.engineGraphData));
PxMemZero(vehicleTelemetryDataContext.suspForceAppPoints, sizeof(vehicleTelemetryDataContext.suspForceAppPoints));
PxMemZero(vehicleTelemetryDataContext.tireForceAppPoints, sizeof(vehicleTelemetryDataContext.tireForceAppPoints));
update(timestep, gravity, vehicleDrivableSurfaceToTireFrictionPairs, 1, &vehWheels, vehWheelQueryResults, vehConcurrentUpdates,
&vehicleTelemetryDataContext, context);
for(PxU32 i=0;i<vehWheels->mWheelsSimData.mNbActiveWheels;i++)
{
telemetryData.mWheelGraphs[i].updateTimeSlice(vehicleTelemetryDataContext.wheelGraphData[i]);
telemetryData.mSuspforceAppPoints[i]=vehicleTelemetryDataContext.suspForceAppPoints[i];
telemetryData.mTireforceAppPoints[i]=vehicleTelemetryDataContext.tireForceAppPoints[i];
}
telemetryData.mEngineGraph->updateTimeSlice(vehicleTelemetryDataContext.engineGraphData);
END_TIMER(TIMER_ALL);
#if PX_VEHICLE_PROFILE
gTimerCount++;
if(10==gTimerCount)
{
/*
printf("%f %f %f %f %f %f %f %f %f\n",
localTimers[TIMER_ADMIN]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_GRAPHS]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_COMPONENTS_UPDATE]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_WHEELS]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_INTERNAL_DYNAMICS_SOLVER]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_POSTUPDATE1]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_POSTUPDATE2]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_POSTUPDATE3]/(1.0f*localTimers[TIMER_ALL]),
floatTimeIn10sOfNs);
*/
printf("%f %f %f %f %f %f \n",
getTimerFraction(TIMER_WHEELS),
getTimerFraction(TIMER_INTERNAL_DYNAMICS_SOLVER),
getTimerFraction(TIMER_POSTUPDATE2),
getTimerFraction(TIMER_POSTUPDATE3),
getTimerInMilliseconds(TIMER_ALL),
getTimerInMilliseconds(TIMER_RAYCASTS));
gTimerCount=0;
for(PxU32 i=0;i<MAX_NB_TIMERS;i++)
{
gTimers[i]=0;
}
}
#endif
}
void physx::PxVehicleUpdateSingleVehicleAndStoreTelemetryData
(const PxReal timestep, const PxVec3& gravity, const physx::PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
PxVehicleWheels* focusVehicle, PxVehicleWheelQueryResult* wheelQueryResults, PxVehicleTelemetryData& telemetryData,
PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicleUpdateSingleVehicleAndStoreTelemetryData: provided PxVehicleContext is not valid");
PxVehicleUpdate::updateSingleVehicleAndStoreTelemetryData
(timestep, gravity, vehicleDrivableSurfaceToTireFrictionPairs, focusVehicle, wheelQueryResults, telemetryData,
vehicleConcurrentUpdates, context);
}
#endif
////////////////////////////////////////////////////////////
//Update an array of vehicles of any type
////////////////////////////////////////////////////////////
void PxVehicleUpdate::update
(const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
const PxU32 numVehicles, PxVehicleWheels** vehicles, PxVehicleWheelQueryResult* vehicleWheelQueryResults, PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates,
VehicleTelemetryDataContext* vehicleTelemetryDataContext, const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN(gravity.magnitude()>0, "gravity vector must have non-zero length");
PX_CHECK_AND_RETURN(timestep>0, "timestep must be greater than zero");
PX_CHECK_AND_RETURN(gThresholdForwardSpeedForWheelAngleIntegration>0, "PxInitVehicleSDK needs to be called before ever calling PxVehicleUpdates or PxVehicleUpdateSingleVehicleAndStoreTelemetryData");
#if PX_CHECKED
for(PxU32 i=0;i<numVehicles;i++)
{
const PxVehicleWheels* const vehWheels=vehicles[i];
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbWheels4;j++)
{
PX_CHECK_MSG(
vehWheels->mWheelsDynData.mWheels4DynData[j].mRaycastResults ||
vehWheels->mWheelsDynData.mWheels4DynData[j].mSweepResults ||
vehWheels->mWheelsDynData.mWheels4DynData[0].mHasCachedRaycastHitPlane ||
(vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+0) &&
vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+1) &&
vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+2) &&
vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+3)),
"Need to call PxVehicleSuspensionRaycasts or PxVehicleSuspensionSweeps at least once before trying to update");
}
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbActiveWheels;j++)
{
PX_CHECK_MSG(vehWheels->mWheelsDynData.mTireForceCalculators->mShaderData[j], "Need to set non-null tire force shader data ptr");
}
PX_CHECK_MSG(vehWheels->mWheelsDynData.mTireForceCalculators->mShader, "Need to set non-null tire force shader function");
PX_CHECK_AND_RETURN(NULL==vehicleWheelQueryResults || vehicleWheelQueryResults[i].nbWheelQueryResults >= vehicles[i]->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbActiveWheels;j++)
{
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || -1==vehWheels->mWheelsSimData.getWheelShapeMapping(j),
"Disabled wheels must not be associated with a PxShape: use setWheelShapeMapping to remove the association");
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || 0==vehWheels->mWheelsDynData.getWheelRotationSpeed(j),
"Disabled wheels must have zero rotation speed: use setWheelRotationSpeed to set the wheel to zero rotation speed");
}
PX_CHECK_AND_RETURN(!vehicleConcurrentUpdates || (vehicleConcurrentUpdates[i].concurrentWheelUpdates && vehicleConcurrentUpdates[i].nbConcurrentWheelUpdates >= vehicles[i]->mWheelsSimData.getNbWheels()),
"vehicleConcurrentUpdates is illegally configured with either null pointers or with insufficient memory for successful concurrent updates.");
for(PxU32 j=0; j < vehWheels->mWheelsSimData.mNbActiveAntiRollBars; j++)
{
const PxVehicleAntiRollBarData antiRoll = vehWheels->mWheelsSimData.getAntiRollBarData(j);
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(antiRoll.mWheel0), "Wheel0 of antiroll bar is disabled. This is not supported.");
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(antiRoll.mWheel1), "Wheel1 of antiroll bar is disabled. This is not supported.");
}
}
#endif
const PxF32 gravityMagnitude=gravity.magnitude();
const PxF32 recipGravityMagnitude=1.0f/gravityMagnitude;
for(PxU32 i=0;i<numVehicles;i++)
{
PxVehicleWheels* vehWheels=vehicles[i];
PxVehicleWheelQueryResult* vehWheelQueryResults = vehicleWheelQueryResults ? &vehicleWheelQueryResults[i] : NULL;
PxVehicleConcurrentUpdateData* vehConcurrentUpdateData = vehicleConcurrentUpdates ? &vehicleConcurrentUpdates[i] : NULL;
switch(vehWheels->mType)
{
case PxVehicleTypes::eDRIVE4W:
{
PxVehicleDrive4W* vehDrive4W=static_cast<PxVehicleDrive4W*>(vehWheels);
PxVehicleUpdate::updateDrive4W(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDrive4W, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
case PxVehicleTypes::eDRIVENW:
{
PxVehicleDriveNW* vehDriveNW=static_cast<PxVehicleDriveNW*>(vehWheels);
PxVehicleUpdate::updateDriveNW(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDriveNW, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
case PxVehicleTypes::eDRIVETANK:
{
PxVehicleDriveTank* vehDriveTank=static_cast<PxVehicleDriveTank*>(vehWheels);
PxVehicleUpdate::updateTank(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDriveTank, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
case PxVehicleTypes::eNODRIVE:
{
PxVehicleNoDrive* vehDriveNoDrive=static_cast<PxVehicleNoDrive*>(vehWheels);
PxVehicleUpdate::updateNoDrive(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDriveNoDrive, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
default:
PX_CHECK_MSG(false, "update - unsupported vehicle type");
break;
}
}
}
void PxVehicleUpdate::updatePost
(const PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxVehicleContext& context)
{
PX_PROFILE_ZONE("PxVehicleUpdates::ePROFILE_POSTUPDATES",0);
PX_CHECK_AND_RETURN(vehicleConcurrentUpdates, "vehicleConcurrentUpdates must be non-null.");
#if PX_CHECKED
for(PxU32 i=0;i<numVehicles;i++)
{
PxVehicleWheels* vehWheels=vehicles[i];
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbActiveWheels;j++)
{
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || -1==vehWheels->mWheelsSimData.getWheelShapeMapping(j),
"Disabled wheels must not be associated with a PxShape: use setWheelShapeMapping to remove the association");
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || 0==vehWheels->mWheelsDynData.getWheelRotationSpeed(j),
"Disabled wheels must have zero rotation speed: use setWheelRotationSpeed to set the wheel to zero rotation speed");
PX_CHECK_AND_RETURN(vehicleConcurrentUpdates[i].concurrentWheelUpdates && vehicleConcurrentUpdates[i].nbConcurrentWheelUpdates >= vehWheels->mWheelsSimData.getNbWheels(),
"vehicleConcurrentUpdates is illegally configured with either null pointers or insufficient memory for successful concurrent vehicle updates.");
}
}
#endif
for(PxU32 i=0;i<numVehicles;i++)
{
//Get the ith vehicle and its actor.
PxVehicleWheels* vehWheels=vehicles[i];
PxRigidDynamic* vehActor = vehWheels->getRigidDynamicActor();
//Get the concurrent update data for the ith vehicle.
//This contains the data that couldn't get updated concurrently and now must be
//set sequentially.
const PxVehicleConcurrentUpdateData& vehicleConcurrentUpdate = vehicleConcurrentUpdates[i];
//Test if the actor is to remain sleeping.
//If the actor is to remain sleeping then do nothing.
if(!vehicleConcurrentUpdate.staySleeping)
{
//Wake the vehicle's actor up as required.
if(vehicleConcurrentUpdate.wakeup && vehActor->getScene()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
vehActor->wakeUp();
}
//Apply momentum changes to vehicle's actor
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehActor->setLinearVelocity(vehicleConcurrentUpdate.linearMomentumChange, false);
vehActor->setAngularVelocity(vehicleConcurrentUpdate.angularMomentumChange, false);
}
else
{
vehActor->addForce(vehicleConcurrentUpdate.linearMomentumChange, PxForceMode::eACCELERATION, false);
vehActor->addTorque(vehicleConcurrentUpdate.angularMomentumChange, PxForceMode::eACCELERATION, false);
}
//In each block of 4 wheels record how many wheels are active.
const PxU32 numActiveWheels=vehWheels->mWheelsSimData.mNbActiveWheels;
const PxU32 numWheels4 = vehWheels->mWheelsSimData.getNbWheels4();
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4 - numActiveWheels);
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 j=1;j<numWheels4-1;j++)
{
numActiveWheelsPerBlock4[j]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Apply the local poses to the shapes of the vehicle's actor that represent wheels.
for(PxU32 j=0;j<numWheels4;j++)
{
PxTransform localPoses[4]=
{
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 0].localPose,
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 1].localPose,
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 2].localPose,
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 3].localPose
};
poseWheels(vehWheels->mWheelsSimData.mWheels4SimData[j],localPoses,numActiveWheelsPerBlock4[j],vehActor);
}
//Apply forces to dynamic actors hit by the wheels.
for(PxU32 j=0;j<numActiveWheels;j++)
{
PxRigidDynamic* hitActor=vehicleConcurrentUpdate.concurrentWheelUpdates[j].hitActor;
if(hitActor)
{
const PxVec3& hitForce=vehicleConcurrentUpdate.concurrentWheelUpdates[j].hitActorForce;
const PxVec3& hitForcePosition=vehicleConcurrentUpdate.concurrentWheelUpdates[j].hitActorForcePosition;
PxRigidBodyExt::addForceAtPos(*hitActor,hitForce,hitForcePosition);
}
}
}
}
}
void physx::PxVehicleUpdates
(const PxReal timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
const PxU32 numVehicles, PxVehicleWheels** vehicles, PxVehicleWheelQueryResult* vehicleWheelQueryResults, PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates,
const PxVehicleContext& context)
{
PX_PROFILE_ZONE("PxVehicleUpdates::ePROFILE_UPDATES",0);
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicleUpdates: provided PxVehicleContext is not valid");
PxVehicleUpdate::update(timestep, gravity, vehicleDrivableSurfaceToTireFrictionPairs, numVehicles, vehicles, vehicleWheelQueryResults, vehicleConcurrentUpdates,
NULL, context);
}
void physx::PxVehiclePostUpdates
(const PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN(context.isValid(), "PxVehiclePostUpdates: provided PxVehicleContext is not valid");
PxVehicleUpdate::updatePost(vehicleConcurrentUpdates, numVehicles, vehicles, context);
}
void physx::PxVehicleShiftOrigin(const PxVec3& shift, const PxU32 numVehicles, PxVehicleWheels** vehicles)
{
PxVehicleUpdate::shiftOrigin(shift, numVehicles, vehicles);
}
///////////////////////////////////////////////////////////////////////////////////
//The following functions issue a single batch of suspension raycasts for an array of vehicles of any type.
//The buffer of sceneQueryResults is distributed among the vehicles in the array
//for use in the next PxVehicleUpdates call.
///////////////////////////////////////////////////////////////////////////////////
static const PxRaycastBuffer* vehicleWheels4SuspensionRaycasts
(PxBatchQueryExt* batchQuery,
const PxVehicleWheels4SimData& wheels4SimData, PxVehicleWheels4DynData& wheels4DynData,
const PxQueryFilterData* carFilterData, const bool* activeWheelStates, const PxU32 numActiveWheels,
PxRigidDynamic* vehActor)
{
const PxRaycastBuffer* buffer4 = NULL;
//Get the transform of the chassis.
PxTransform massXform = vehActor->getCMassLocalPose();
massXform.q = PxQuat(PxIdentity);
PxTransform carChassisTrnsfm = vehActor->getGlobalPose().transform(massXform);
//Add a raycast for each wheel.
for(PxU32 j=0;j<numActiveWheels;j++)
{
const PxVehicleSuspensionData& susp=wheels4SimData.getSuspensionData(j);
const PxVehicleWheelData& wheel=wheels4SimData.getWheelData(j);
const PxVec3& bodySpaceSuspTravelDir=wheels4SimData.getSuspTravelDirection(j);
PxVec3 bodySpaceWheelCentreOffset=wheels4SimData.getWheelCentreOffset(j);
PxF32 maxDroop=susp.mMaxDroop;
PxF32 maxBounce=susp.mMaxCompression;
PxF32 radius=wheel.mRadius;
PX_ASSERT(maxBounce>=0);
PX_ASSERT(maxDroop>=0);
if(!activeWheelStates[j])
{
//For disabled wheels just issue a raycast of almost zero length.
//This should be very cheap and ought to hit nothing.
bodySpaceWheelCentreOffset=PxVec3(0,0,0);
maxDroop=1e-5f*gToleranceScaleLength;
maxBounce=1e-5f*gToleranceScaleLength;
radius=1e-5f*gToleranceScaleLength;
}
PxVec3 suspLineStart;
PxVec3 suspLineDir;
computeSuspensionRaycast(carChassisTrnsfm,bodySpaceWheelCentreOffset,bodySpaceSuspTravelDir,radius,maxBounce,suspLineStart,suspLineDir);
//Total length from top of wheel at max compression to bottom of wheel at max droop.
PxF32 suspLineLength=radius + maxBounce + maxDroop + radius;
//Add another radius on for good measure.
suspLineLength+=radius;
//Store the susp line ray for later use.
PxVehicleWheels4DynData::SuspLineRaycast& raycast =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineRaycast&>(wheels4DynData.mQueryOrCachedHitResults);
raycast.mStarts[j]=suspLineStart;
raycast.mDirs[j]=suspLineDir;
raycast.mLengths[j]=suspLineLength;
//Add the raycast to the scene query.
const PxRaycastBuffer* raycastBuffer = batchQuery->raycast(
suspLineStart, suspLineDir, suspLineLength, 0,
PxHitFlag::ePOSITION|PxHitFlag::eNORMAL|PxHitFlag::eUV, carFilterData[j]);
if(0 == j)
buffer4 = raycastBuffer;
if (!raycastBuffer)
return buffer4 = NULL;
}
return buffer4;
}
void PxVehicleUpdate::suspensionRaycasts(PxBatchQueryExt* batchQuery, const PxU32 numVehicles, PxVehicleWheels** vehicles, const bool* vehiclesToRaycast, const PxQueryFlags queryFlags)
{
START_TIMER(TIMER_RAYCASTS);
//Work out the rays for the suspension line raycasts and perform all the raycasts.
for(PxU32 i=0;i<numVehicles;i++)
{
//Get the current car.
PxVehicleWheels& veh=*vehicles[i];
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimData=veh.mWheelsSimData.mWheels4SimData;
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynData=veh.mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=((veh.mWheelsSimData.mNbActiveWheels & ~3) >> 2);
const PxU32 numActiveWheels=veh.mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=numActiveWheels-4*numWheels4;
PxRigidDynamic* vehActor=veh.mActor;
//Set the results pointer and start the raycasts.
PX_ASSERT(numActiveWheelsInLast4<4);
//Blocks of 4 wheels.
for(PxU32 j=0;j<numWheels4;j++)
{
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if(!vehiclesToRaycast || vehiclesToRaycast[i])
{
const PxQueryFilterData carFilterData[4] =
{
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(3), queryFlags)
};
const PxRaycastBuffer* buffer = vehicleWheels4SuspensionRaycasts(batchQuery, wheels4SimData[j], wheels4DynData[j], carFilterData, activeWheelStates, 4, vehActor);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionRaycasts - PxVehicleBatchUpdate raycast buffers not large enough to perform raycast.");
wheels4DynData[j].mRaycastResults = buffer;
}
}
//Remainder that don't make up a block of 4.
if(numActiveWheelsInLast4>0)
{
const PxU32 j=numWheels4;
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if(!vehiclesToRaycast || vehiclesToRaycast[i])
{
PxQueryFilterData carFilterData[4];
if (0 < numActiveWheelsInLast4)
carFilterData[0] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags);
if (1 < numActiveWheelsInLast4)
carFilterData[1] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags);
if (2 < numActiveWheelsInLast4)
carFilterData[2] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags);
const PxRaycastBuffer* buffer = vehicleWheels4SuspensionRaycasts(batchQuery,wheels4SimData[j],wheels4DynData[j],carFilterData,activeWheelStates,numActiveWheelsInLast4,vehActor);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionRaycasts - PxVehicleBatchUpdate raycast buffers not large enough to perform raycast.");
wheels4DynData[j].mRaycastResults = buffer;
}
}
}
batchQuery->execute();
END_TIMER(TIMER_RAYCASTS);
}
void physx::PxVehicleSuspensionRaycasts(PxBatchQueryExt* batchQuery, const PxU32 numVehicles, PxVehicleWheels** vehicles, const bool* vehiclesToRaycast, const PxQueryFlags queryFlags)
{
PX_PROFILE_ZONE("PxVehicleSuspensionRaycasts::ePROFILE_RAYCASTS",0);
PxVehicleUpdate::suspensionRaycasts(batchQuery, numVehicles, vehicles, vehiclesToRaycast, queryFlags);
}
static const PxSweepBuffer* vehicleWheels4SuspensionSweeps
(PxBatchQueryExt* batchQuery,
const PxVehicleWheels4SimData& wheels4SimData, PxVehicleWheels4DynData& wheels4DynData,
const PxQueryFilterData* carFilterData, const bool* activeWheelStates, const PxU32 numActiveWheels,
const PxU16 nbHitsPerQuery,
const PxI32* wheelShapeIds,
PxRigidDynamic* vehActor,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation,
const PxVec3& upAxis, const PxVec3& forwardAxis, const PxVec3& sideAxis)
{
PX_UNUSED(sweepWidthScale);
PX_UNUSED(sweepRadiusScale);
//Get the transform of the chassis.
PxTransform carChassisTrnsfm=vehActor->getGlobalPose().transform(vehActor->getCMassLocalPose());
const PxSweepBuffer* buffer4 = NULL;
//Add a raycast for each wheel.
for(PxU32 j=0;j<numActiveWheels;j++)
{
const PxVehicleSuspensionData& susp = wheels4SimData.getSuspensionData(j);
const PxVehicleWheelData& wheel = wheels4SimData.getWheelData(j);
PxShape* wheelShape;
vehActor->getShapes(&wheelShape, 1, PxU32(wheelShapeIds[j]));
PxGeometryHolder suspGeometry;
const PxGeometry& geom = wheelShape->getGeometry();
const PxGeometryType::Enum geomType = geom.getType();
if (PxGeometryType::eCONVEXMESH == geomType)
{
PxConvexMeshGeometry convMeshGeom = static_cast<const PxConvexMeshGeometry&>(geom);
convMeshGeom.scale.scale = convMeshGeom.scale.scale.multiply(
PxVec3(
PxAbs(sideAxis.x*sweepWidthScale + (upAxis.x + forwardAxis.x)*sweepRadiusScale),
PxAbs(sideAxis.y*sweepWidthScale + (upAxis.y + forwardAxis.y)*sweepRadiusScale),
PxAbs(sideAxis.z*sweepWidthScale + (upAxis.z + forwardAxis.z)*sweepRadiusScale))
);
suspGeometry.storeAny(convMeshGeom);
}
else if (PxGeometryType::eCAPSULE == geomType)
{
PxCapsuleGeometry capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom);
capsuleGeom.halfHeight *= sweepWidthScale;
capsuleGeom.radius *= sweepRadiusScale;
suspGeometry.storeAny(capsuleGeom);
}
else
{
PX_ASSERT(PxGeometryType::eSPHERE == geomType);
PxSphereGeometry sphereGeom = static_cast<const PxSphereGeometry&>(geom);
sphereGeom.radius *= sweepRadiusScale;
suspGeometry.storeAny(sphereGeom);
}
const float jounce = wheels4DynData.mJounces[j] != PX_MAX_F32 ? wheels4DynData.mJounces[j] : 0.0f;
const float steerAngle = wheels4DynData.mSteerAngles[j];
const PxVehicleSuspensionData& suspData = wheels4SimData.getSuspensionData(j);
const PxQuat wheelLocalPoseRotation = computeWheelLocalQuat(forwardAxis, sideAxis, upAxis, jounce, suspData, 0.0f, steerAngle);
const PxVec3& bodySpaceSuspTravelDir = wheels4SimData.getSuspTravelDirection(j);
PxVec3 bodySpaceWheelCentreOffset = wheels4SimData.getWheelCentreOffset(j);
PxF32 maxDroop = susp.mMaxDroop;
PxF32 maxBounce = susp.mMaxCompression;
PxF32 radius = wheel.mRadius;
PX_ASSERT(maxBounce >= 0);
PX_ASSERT(maxDroop >= 0);
if(!activeWheelStates[j])
{
//For disabled wheels just issue a raycast of almost zero length.
//This should be very cheap and ought to hit nothing.
bodySpaceWheelCentreOffset = PxVec3(0,0,0);
maxDroop = 1e-5f*gToleranceScaleLength;
maxBounce = 1e-5f*gToleranceScaleLength;
radius = 1e-5f*gToleranceScaleLength;
}
PxTransform suspPoseStart;
PxVec3 suspLineDir;
computeSuspensionSweep(
carChassisTrnsfm,
wheelLocalPoseRotation,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, radius, maxBounce,
suspPoseStart, suspLineDir);
const PxF32 suspLineLength = radius + maxBounce + maxDroop + radius;
//Store the susp line ray for later use.
PxVehicleWheels4DynData::SuspLineSweep& sweep =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineSweep&>(wheels4DynData.mQueryOrCachedHitResults);
sweep.mStartPose[j] = suspPoseStart;
sweep.mDirs[j] = suspLineDir;
sweep.mLengths[j] = suspLineLength;
sweep.mGometries[j] = suspGeometry;
//Add the raycast to the scene query.
const PxSweepBuffer* buffer = batchQuery->sweep(sweep.mGometries[j].any(),
suspPoseStart, suspLineDir, suspLineLength, nbHitsPerQuery,
PxHitFlag::ePOSITION|PxHitFlag::eNORMAL|PxHitFlag::eUV,
carFilterData[j], NULL, sweepInflation);
if(0 == j)
buffer4 = buffer;
if(!buffer)
buffer4 = NULL;
}
return buffer4;
}
void PxVehicleUpdate::suspensionSweeps
(PxBatchQueryExt* batchQuery,
const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxU16 nbHitsPerQuery,
const bool* vehiclesToSweep,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation, const PxQueryFlags queryFlags,
const PxVec3& upAxis, const PxVec3& forwardAxis, const PxVec3& sideAxis)
{
PX_CHECK_MSG(sweepWidthScale > 0.0f, "PxVehicleUpdate::suspensionSweeps - sweepWidthScale must be greater than 0.0");
PX_CHECK_MSG(sweepRadiusScale > 0.0f, "PxVehicleUpdate::suspensionSweeps - sweepRadiusScale must be greater than 0.0");
START_TIMER(TIMER_SWEEPS);
//Work out the rays for the suspension line raycasts and perform all the raycasts.
for(PxU32 i=0;i<numVehicles;i++)
{
//Get the current car.
PxVehicleWheels& veh=*vehicles[i];
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimData=veh.mWheelsSimData.mWheels4SimData;
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynData=veh.mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=((veh.mWheelsSimData.mNbActiveWheels & ~3) >> 2);
const PxU32 numActiveWheels=veh.mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=numActiveWheels-4*numWheels4;
PxRigidDynamic* vehActor=veh.mActor;
//Set the results pointer and start the raycasts.
PX_ASSERT(numActiveWheelsInLast4<4);
//Get the shape ids for the wheels.
PxI32 wheelShapeIds[PX_MAX_NB_WHEELS];
PxMemSet(wheelShapeIds, 0xff, sizeof(PxI32)*PX_MAX_NB_WHEELS);
for(PxU32 j = 0; j < veh.mWheelsSimData.getNbWheels(); j++)
{
PX_CHECK_AND_RETURN(veh.mWheelsSimData.getWheelShapeMapping(j) != -1, "PxVehicleUpdate::suspensionSweeps - trying to sweep a shape that doesn't exist.");
wheelShapeIds[j] = veh.mWheelsSimData.getWheelShapeMapping(j);
}
//Blocks of 4 wheels.
for(PxU32 j=0;j<numWheels4;j++)
{
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
const PxI32* wheelShapeIds4 = wheelShapeIds + 4*j;
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if (!vehiclesToSweep || vehiclesToSweep[i])
{
const PxQueryFilterData carFilterData[4] =
{
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(3), queryFlags)
};
const PxSweepBuffer* buffer = vehicleWheels4SuspensionSweeps(
batchQuery,
wheels4SimData[j], wheels4DynData[j],
carFilterData, activeWheelStates, 4,
nbHitsPerQuery,
wheelShapeIds4,
vehActor,
sweepWidthScale, sweepRadiusScale, sweepInflation,
upAxis, forwardAxis, sideAxis);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionSweeps - batched sweep result array not large enough to perform sweep.");
wheels4DynData[j].mSweepResults = buffer;
}
}
//Remainder that don't make up a block of 4.
if(numActiveWheelsInLast4>0)
{
const PxU32 j=numWheels4;
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
const PxI32* wheelShapeIds4 = wheelShapeIds + 4*j;
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if(!vehiclesToSweep || vehiclesToSweep[i])
{
PxQueryFilterData carFilterData[4];
if(0<numActiveWheelsInLast4)
carFilterData[0] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags);
if(1<numActiveWheelsInLast4)
carFilterData[1] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags);
if(2<numActiveWheelsInLast4)
carFilterData[2] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags);
const PxSweepBuffer* buffer = vehicleWheels4SuspensionSweeps(
batchQuery,
wheels4SimData[j], wheels4DynData[j],
carFilterData, activeWheelStates, numActiveWheelsInLast4,
nbHitsPerQuery,
wheelShapeIds4,
vehActor,
sweepWidthScale, sweepRadiusScale, sweepInflation,
upAxis, forwardAxis, sideAxis);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionSweeps - batched sweep result array not large enough to perform sweep.");
wheels4DynData[j].mSweepResults = buffer;
}
}
}
batchQuery->execute();
END_TIMER(TIMER_SWEEPS);
}
namespace physx
{
void PxVehicleSuspensionSweeps
(PxBatchQueryExt* batchQuery,
const PxU32 nbVehicles, PxVehicleWheels** vehicles,
const PxU16 nbHitsPerQuery,
const bool* vehiclesToSweep,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation,
const PxQueryFlags queryFlags, const PxVehicleContext& context)
{
PX_PROFILE_ZONE("PxVehicleSuspensionSweeps::ePROFILE_SWEEPS",0);
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicleSuspensionSweeps: provided PxVehicleContext is not valid");
PxVehicleUpdate::suspensionSweeps(batchQuery, nbVehicles, vehicles, nbHitsPerQuery, vehiclesToSweep,
sweepWidthScale, sweepRadiusScale, sweepInflation, queryFlags, context.upAxis, context.forwardAxis, context.sideAxis);
}
}
| 318,845 |
C++
| 41.450539 | 227 | 0.757525 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleSerialization.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "common/PxBase.h"
#include "common/PxCollection.h"
#include "extensions/PxRepXSimpleType.h"
#include "PxVehicleMetaDataObjects.h"
#include "PxVehicleSerialization.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "SnRepXSerializerImpl.h"
#include "foundation/PxFPU.h"
namespace physx
{
using namespace Sn;
template<typename TVehicleType>
inline void* createVehicle( PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData, const PxVehicleDriveSimDataNW& driveDataNW,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PX_UNUSED(physics);
PX_UNUSED(vehActor);
PX_UNUSED(wheelsData);
PX_UNUSED(driveData);
PX_UNUSED(driveDataNW);
PX_UNUSED(numWheels);
PX_UNUSED(numNonDrivenWheels);
return NULL;
}
template<>
inline void* createVehicle<PxVehicleDrive4W>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData, const PxVehicleDriveSimDataNW& /*driveDataNW*/,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PxVehicleDrive4W* vehDrive4W = PxVehicleDrive4W::allocate(numWheels);
vehDrive4W->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData, driveData, numNonDrivenWheels);
return vehDrive4W;
}
template<>
inline void* createVehicle<PxVehicleDriveTank>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData, const PxVehicleDriveSimDataNW& /*driveDataNW*/,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PxVehicleDriveTank* tank = PxVehicleDriveTank::allocate(numWheels);
tank->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData, driveData, numWheels - numNonDrivenWheels);
return tank;
}
template<>
inline void* createVehicle<PxVehicleDriveNW>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& /*driveData*/, const PxVehicleDriveSimDataNW& driveDataNW,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PxVehicleDriveNW* vehDriveNW = PxVehicleDriveNW::allocate(numWheels);
vehDriveNW->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData, driveDataNW, numWheels - numNonDrivenWheels);
return vehDriveNW;
}
template<>
inline void* createVehicle<PxVehicleNoDrive>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& /*driveData*/, const PxVehicleDriveSimDataNW& /*driveDataNW*/,
const PxU32 numWheels, const PxU32 /*numNonDrivenWheels*/)
{
PxVehicleNoDrive* vehNoDrive = PxVehicleNoDrive::allocate(numWheels);
vehNoDrive->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData);
return vehNoDrive;
}
template<typename TVehicleType>
PxRepXObject PxVehicleRepXSerializer<TVehicleType>::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection )
{
PxRigidActor* vehActor = NULL;
readReference<PxRigidActor>( inReader, *inCollection, "PxRigidDynamicRef", vehActor );
if ( vehActor == NULL )
return PxRepXObject();
PxU32 numWheels = 0;
readProperty( inReader, "NumWheels", numWheels );
if( numWheels == 0)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::createCollectionFromXml: PxVehicleRepXSerializer: Xml field NumWheels is zero!");
return PxRepXObject();
}
PxU32 numNonDrivenWheels = 0;
readProperty( inReader, "NumNonDrivenWheels", numNonDrivenWheels );
//change to numwheel
PxVehicleWheelsSimData* wheelsSimData=PxVehicleWheelsSimData::allocate(numWheels);
{
inReader.pushCurrentContext();
if ( inReader.gotoChild( "MWheelsSimData" ) )
{
readAllProperties( inArgs, inReader, wheelsSimData, inAllocator, *inCollection );
}
inReader.popCurrentContext();
}
PxVehicleDriveSimData4W driveSimData;
{
inReader.pushCurrentContext();
if ( inReader.gotoChild( "MDriveSimData" ) )
{
readAllProperties( inArgs, inReader, &driveSimData, inAllocator, *inCollection );
}
inReader.popCurrentContext();
}
PxVehicleDriveSimDataNW nmSimData;
{
inReader.pushCurrentContext();
if ( inReader.gotoChild( "MDriveSimDataNW" ) )
{
readAllProperties( inArgs, inReader, &driveSimData, inAllocator, *inCollection );
}
inReader.popCurrentContext();
}
TVehicleType* drive = static_cast<TVehicleType*>(createVehicle<TVehicleType>(inArgs.physics, vehActor->is<PxRigidDynamic>(), *wheelsSimData, driveSimData, nmSimData, numWheels, numNonDrivenWheels));
readAllProperties( inArgs, inReader, drive, inAllocator, *inCollection );
PxVehicleWheels4DynData* wheel4DynData = drive->mWheelsDynData.getWheel4DynData();
PX_ASSERT( wheel4DynData );
for(PxU32 i=0;i<wheelsSimData->getNbWheels4();i++)
{
PxConstraint* constraint = wheel4DynData[i].getVehicletConstraintShader().getPxConstraint();
if( constraint )
inCollection->add(*constraint);
}
if( wheelsSimData )
wheelsSimData->free();
return PxCreateRepXObject(drive);
}
template<typename TVehicleType>
void PxVehicleRepXSerializer<TVehicleType>::objectToFileImpl( const TVehicleType* drive, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& /*inArgs*/ )
{
PX_SIMD_GUARD; // denorm exception triggered in PxVehicleGearsDataGeneratedInfo::visitInstanceProperties on osx
writeReference( inWriter, *inCollection, "PxRigidDynamicRef", drive->getRigidDynamicActor() );
writeProperty( inWriter, *inCollection, inTempBuffer, "NumWheels", drive->mWheelsSimData.getNbWheels() );
writeProperty( inWriter, *inCollection, inTempBuffer, "NumNonDrivenWheels", drive->getNbNonDrivenWheels());
writeAllProperties( drive, inWriter, inTempBuffer, *inCollection );
}
PxVehicleNoDrive::PxVehicleNoDrive()
: PxVehicleWheels(PxVehicleConcreteType::eVehicleNoDrive, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
{}
PxVehicleDrive4W::PxVehicleDrive4W()
: PxVehicleDrive(PxVehicleConcreteType::eVehicleDrive4W, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
{}
PxVehicleDriveNW::PxVehicleDriveNW()
: PxVehicleDrive(PxVehicleConcreteType::eVehicleDriveNW, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
{}
PxVehicleDriveTank::PxVehicleDriveTank()
: PxVehicleDrive(PxVehicleConcreteType::eVehicleDriveTank, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
, mDriveModel(PxVehicleDriveTankControlModel::eSTANDARD)
{}
// explicit template instantiations
template struct PxVehicleRepXSerializer<PxVehicleDrive4W>;
template struct PxVehicleRepXSerializer<PxVehicleDriveTank>;
template struct PxVehicleRepXSerializer<PxVehicleDriveNW>;
template struct PxVehicleRepXSerializer<PxVehicleNoDrive>;
}
| 8,733 |
C++
| 41.813725 | 204 | 0.770068 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleSuspLimitConstraintShader.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_VEHICLE_SUSP_LIMIT_CONSTRAINT_SHADER_H
#define PX_VEHICLE_SUSP_LIMIT_CONSTRAINT_SHADER_H
/** \addtogroup vehicle
@{
*/
#include "foundation/PxTransform.h"
#include "extensions/PxConstraintExt.h"
#include "PxConstraintDesc.h"
#include "PxConstraint.h"
#include "vehicle/PxVehicleWheels.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxVehicleConstraintShader : public PxConstraintConnector
{
public:
friend class PxVehicleWheels;
PxVehicleConstraintShader(PxVehicleWheels* vehicle, PxConstraint* constraint = NULL)
: mConstraint(constraint),
mVehicle(vehicle)
{
}
PxVehicleConstraintShader(){}
~PxVehicleConstraintShader()
{
}
static void getBinaryMetaData(PxOutputStream& stream);
void release()
{
if(mConstraint)
{
mConstraint->release();
}
}
virtual void onComShift(PxU32 actor) { PX_UNUSED(actor); }
virtual void onOriginShift(const PxVec3& shift) { PX_UNUSED(shift); }
virtual void* prepareData()
{
return &mData;
}
virtual bool updatePvdProperties(pvdsdk::PvdDataStream& pvdConnection,
const PxConstraint* c,
PxPvdUpdateType::Enum updateType) const { PX_UNUSED(c); PX_UNUSED(updateType); PX_UNUSED(&pvdConnection); return true;}
virtual void updateOmniPvdProperties() const { }
virtual void onConstraintRelease()
{
mVehicle->onConstraintRelease();
}
virtual void* getExternalReference(PxU32& typeID) { typeID = PxConstraintExtIDs::eVEHICLE_SUSP_LIMIT_DEPRECATED; return this; }
virtual PxBase* getSerializable() { return NULL; }
//TAG:solverprepshader
static PxU32 vehicleSuspLimitConstraintSolverPrep(
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 VehicleConstraintData* data = static_cast<const VehicleConstraintData*>(constantBlock);
PxU32 numActive=0;
const PxQuat bodyRotation = bodyAToWorld.q * data->mCMassRotation.getConjugate();
//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;
//Susp limit constraints.
for(PxU32 i=0;i<4;i++)
{
if(data->mSuspLimitData.mActiveFlags[i])
{
Px1DConstraint& p=constraints[numActive];
p.linear0 = bodyRotation.rotate(data->mSuspLimitData.mDirs[i]);
p.angular0 = bodyRotation.rotate(data->mSuspLimitData.mCMOffsets[i].cross(data->mSuspLimitData.mDirs[i]));
p.geometricError=data->mSuspLimitData.mErrors[i];
p.linear1=PxVec3(0);
p.angular1=PxVec3(0);
p.minImpulse=-FLT_MAX;
p.maxImpulse=0;
p.velocityTarget=0;
p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT;
numActive++;
}
}
//Sticky tire friction constraints.
for(PxU32 i=0;i<4;i++)
{
if(data->mStickyTireForwardData.mActiveFlags[i])
{
Px1DConstraint& p=constraints[numActive];
p.linear0=data->mStickyTireForwardData.mDirs[i];
p.angular0=data->mStickyTireForwardData.mCMOffsets[i].cross(data->mStickyTireForwardData.mDirs[i]);
p.geometricError=0.0f;
p.linear1=PxVec3(0);
p.angular1=PxVec3(0);
p.minImpulse=-FLT_MAX;
p.maxImpulse=FLT_MAX;
p.velocityTarget=data->mStickyTireForwardData.mTargetSpeeds[i];
p.mods.spring.damping = 1000.0f;
p.flags = Px1DConstraintFlag::eSPRING | Px1DConstraintFlag::eACCELERATION_SPRING;
p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT;
numActive++;
}
}
//Sticky tire friction constraints.
for(PxU32 i=0;i<4;i++)
{
if(data->mStickyTireSideData.mActiveFlags[i])
{
Px1DConstraint& p=constraints[numActive];
p.linear0=data->mStickyTireSideData.mDirs[i];
p.angular0=data->mStickyTireSideData.mCMOffsets[i].cross(data->mStickyTireSideData.mDirs[i]);
p.geometricError=0.0f;
p.linear1=PxVec3(0);
p.angular1=PxVec3(0);
p.minImpulse=-FLT_MAX;
p.maxImpulse=FLT_MAX;
p.velocityTarget=data->mStickyTireSideData.mTargetSpeeds[i];
p.mods.spring.damping = 1000.0f;
p.flags = Px1DConstraintFlag::eSPRING | Px1DConstraintFlag::eACCELERATION_SPRING;
p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT;
numActive++;
}
}
return numActive;
}
static void visualiseConstraint(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()); }
public:
struct SuspLimitConstraintData
{
PxVec3 mCMOffsets[4];
PxVec3 mDirs[4];
PxReal mErrors[4];
bool mActiveFlags[4];
};
struct StickyTireConstraintData
{
PxVec3 mCMOffsets[4];
PxVec3 mDirs[4];
PxReal mTargetSpeeds[4];
bool mActiveFlags[4];
};
struct VehicleConstraintData
{
SuspLimitConstraintData mSuspLimitData;
StickyTireConstraintData mStickyTireForwardData;
StickyTireConstraintData mStickyTireSideData;
PxQuat mCMassRotation;
};
VehicleConstraintData mData;
PxConstraint* mConstraint;
PX_INLINE void setPxConstraint(PxConstraint* pxConstraint)
{
mConstraint = pxConstraint;
}
PX_INLINE PxConstraint* getPxConstraint()
{
return mConstraint;
}
PxConstraintConnector* getConnector()
{
return this;
}
virtual PxConstraintSolverPrep getPrep() const { return vehicleSuspLimitConstraintSolverPrep; }
virtual const void* getConstantBlock() const { return &mData; }
private:
PxVehicleWheels* mVehicle;
#if !PX_P64_FAMILY
PxU32 mPad[2];
#else
PxU32 mPad[1];
#endif
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleConstraintShader)& 0x0f));
/**
\brief Default implementation of PxVehicleComputeTireForce
@see PxVehicleComputeTireForce, PxVehicleTireForceCalculator
*/
void PxVehicleComputeTireForceDefault
(const void* shaderData,
const PxF32 tireFriction,
const PxF32 longSlip, const PxF32 latSlip, const PxF32 camber,
const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 recipWheelRadius,
const PxF32 restTireLoad, const PxF32 normalisedTireLoad, const PxF32 tireLoad,
const PxF32 gravity, const PxF32 recipGravity,
PxF32& wheelTorque, PxF32& tireLongForceMag, PxF32& tireLatForceMag, PxF32& tireAlignMoment);
/**
\brief Structure containing shader data for each tire of a vehicle and a shader function that computes individual tire forces
*/
class PxVehicleTireForceCalculator
{
public:
PxVehicleTireForceCalculator()
: mShader(PxVehicleComputeTireForceDefault)
{
}
/**
\brief Array of shader data - one data entry per tire.
Default values are pointers to PxVehicleTireData (stored in PxVehicleWheelsSimData) and are set in PxVehicleDriveTank::setup or PxVehicleDrive4W::setup
@see PxVehicleComputeTireForce, PxVehicleComputeTireForceDefault, PxVehicleWheelsSimData, PxVehicleDriveTank::setup, PxVehicleDrive4W::setup
*/
const void** mShaderData;
/**
\brief Shader function.
Default value is PxVehicleComputeTireForceDefault and is set in PxVehicleDriveTank::setup or PxVehicleDrive4W::setup
@see PxVehicleComputeTireForce, PxVehicleComputeTireForceDefault, PxVehicleWheelsSimData, PxVehicleDriveTank::setup, PxVehicleDrive4W::setup
*/
PxVehicleComputeTireForce mShader;
#if !PX_P64_FAMILY
PxU32 mPad[2];
#endif
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleTireForceCalculator) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,453 |
C
| 29.595469 | 152 | 0.754258 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/VehicleUtilTelemetry.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleUtilTelemetry.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxErrors.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxAllocator.h"
#include "stdio.h"
namespace physx
{
#if PX_DEBUG_VEHICLE_ON
PxVehicleGraphDesc::PxVehicleGraphDesc()
: mPosX(PX_MAX_F32),
mPosY(PX_MAX_F32),
mSizeX(PX_MAX_F32),
mSizeY(PX_MAX_F32),
mBackgroundColor(PxVec3(PX_MAX_F32,PX_MAX_F32,PX_MAX_F32)),
mAlpha(PX_MAX_F32)
{
}
bool PxVehicleGraphDesc::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mPosX != PX_MAX_F32, "PxVehicleGraphDesc.mPosX must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mPosY != PX_MAX_F32, "PxVehicleGraphDesc.mPosY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mSizeX != PX_MAX_F32, "PxVehicleGraphDesc.mSizeX must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mSizeY != PX_MAX_F32, "PxVehicleGraphDesc.mSizeY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mBackgroundColor.x != PX_MAX_F32 && mBackgroundColor.y != PX_MAX_F32 && mBackgroundColor.z != PX_MAX_F32, "PxVehicleGraphDesc.mBackgroundColor must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mAlpha != PX_MAX_F32, "PxVehicleGraphDesc.mAlpha must be initialised", false);
return true;
}
PxVehicleGraphChannelDesc::PxVehicleGraphChannelDesc()
: mMinY(PX_MAX_F32),
mMaxY(PX_MAX_F32),
mMidY(PX_MAX_F32),
mColorLow(PxVec3(PX_MAX_F32,PX_MAX_F32,PX_MAX_F32)),
mColorHigh(PxVec3(PX_MAX_F32,PX_MAX_F32,PX_MAX_F32)),
mTitle(NULL)
{
}
bool PxVehicleGraphChannelDesc::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mMinY != PX_MAX_F32, "PxVehicleGraphChannelDesc.mMinY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mMaxY != PX_MAX_F32, "PxVehicleGraphChannelDesc.mMaxY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mMidY != PX_MAX_F32, "PxVehicleGraphChannelDesc.mMidY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mColorLow.x != PX_MAX_F32 && mColorLow.y != PX_MAX_F32 && mColorLow.z != PX_MAX_F32, "PxVehicleGraphChannelDesc.mColorLow must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mColorHigh.x != PX_MAX_F32 && mColorHigh.y != PX_MAX_F32 && mColorHigh.z != PX_MAX_F32, "PxVehicleGraphChannelDesc.mColorHigh must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mTitle, "PxVehicleGraphChannelDesc.mTitle must be initialised", false);
return true;
}
PxVehicleGraph::PxVehicleGraph()
{
mBackgroundMinX=0;
mBackgroundMaxX=0;
mBackgroundMinY=0;
mBackgroundMaxY=0;
mSampleTide=0;
mBackgroundColor=PxVec3(255.f,255.f,255.f);
mBackgroundAlpha=1.0f;
for(PxU32 i=0;i<eMAX_NB_CHANNELS;i++)
{
mChannelMinY[i]=0;
mChannelMaxY[i]=0;
mChannelMidY[i]=0;
mChannelColorLow[i]=PxVec3(0,0,255.f);
mChannelColorHigh[i]=PxVec3(255.f,0,0);
memset(mChannelSamples[i], 0, sizeof(PxReal)*eMAX_NB_SAMPLES);
}
mNbChannels = 0;
PX_COMPILE_TIME_ASSERT(size_t(PxVehicleGraph::eMAX_NB_CHANNELS) >= size_t(PxVehicleDriveGraphChannel::eMAX_NB_DRIVE_CHANNELS) && size_t(PxVehicleGraph::eMAX_NB_CHANNELS) >= size_t(PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS));
}
PxVehicleGraph::~PxVehicleGraph()
{
}
void PxVehicleGraph::setup(const PxVehicleGraphDesc& desc, const PxVehicleGraphType::Enum graphType)
{
mBackgroundMinX = (desc.mPosX - 0.5f*desc.mSizeX);
mBackgroundMaxX = (desc.mPosX + 0.5f*desc.mSizeX);
mBackgroundMinY = (desc.mPosY - 0.5f*desc.mSizeY);
mBackgroundMaxY = (desc.mPosY + 0.5f*desc.mSizeY);
mBackgroundColor=desc.mBackgroundColor;
mBackgroundAlpha=desc.mAlpha;
mNbChannels = (PxVehicleGraphType::eWHEEL==graphType) ? PxU32(PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS) : PxU32(PxVehicleDriveGraphChannel::eMAX_NB_DRIVE_CHANNELS);
}
void PxVehicleGraph::setChannel(PxVehicleGraphChannelDesc& desc, const PxU32 channel)
{
PX_ASSERT(channel<eMAX_NB_CHANNELS);
mChannelMinY[channel]=desc.mMinY;
mChannelMaxY[channel]=desc.mMaxY;
mChannelMidY[channel]=desc.mMidY;
PX_CHECK_MSG(mChannelMinY[channel]<=mChannelMidY[channel], "mChannelMinY must be less than or equal to mChannelMidY");
PX_CHECK_MSG(mChannelMidY[channel]<=mChannelMaxY[channel], "mChannelMidY must be less than or equal to mChannelMaxY");
mChannelColorLow[channel]=desc.mColorLow;
mChannelColorHigh[channel]=desc.mColorHigh;
strcpy(mChannelTitle[channel], desc.mTitle);
}
void PxVehicleGraph::clearRecordedChannelData()
{
mSampleTide=0;
for(PxU32 i=0;i<eMAX_NB_CHANNELS;i++)
{
memset(mChannelSamples[i], 0, sizeof(PxReal)*eMAX_NB_SAMPLES);
}
}
void PxVehicleGraph::updateTimeSlice(const PxReal* const samples)
{
mSampleTide++;
mSampleTide=mSampleTide%eMAX_NB_SAMPLES;
for(PxU32 i=0;i<mNbChannels;i++)
{
mChannelSamples[i][mSampleTide]=samples[i];
}
}
void PxVehicleGraph::computeGraphChannel(const PxU32 channel, PxReal* xy, PxVec3* colors, char* title) const
{
PX_ASSERT(channel<mNbChannels);
const PxReal sizeX=mBackgroundMaxX-mBackgroundMinX;
const PxReal sizeY=mBackgroundMaxY-mBackgroundMinY;
const PxF32 minVal=mChannelMinY[channel];
const PxF32 maxVal=mChannelMaxY[channel];
const PxF32 midVal=mChannelMidY[channel];
const PxVec3 colorLow=mChannelColorLow[channel];
const PxVec3 colorHigh=mChannelColorHigh[channel];
for(PxU32 i=0;i<PxVehicleGraph::eMAX_NB_SAMPLES;i++)
{
const PxU32 index = (mSampleTide+1+i)%PxVehicleGraph::eMAX_NB_SAMPLES;
xy[2*i+0] = mBackgroundMinX+sizeX*i/(1.0f * PxVehicleGraph::eMAX_NB_SAMPLES);
const PxF32 sampleVal = PxClamp(mChannelSamples[channel][index],minVal,maxVal);
const PxReal y = (sampleVal-minVal)/(maxVal-minVal);
xy[2*i+1] = mBackgroundMinY+sizeY*y;
colors[i] = sampleVal < midVal ? colorLow : colorHigh;
}
strcpy(title,mChannelTitle[channel]);
}
PxF32 PxVehicleGraph::getLatestValue(const PxU32 channel) const
{
PX_CHECK_AND_RETURN_VAL(channel < mNbChannels, "PxVehicleGraph::getLatestValue: Illegal channel", 0.0f);
return mChannelSamples[channel][mSampleTide];
}
void PxVehicleGraph::getRawData(const PxU32 channel, PxReal* values) const
{
PX_ASSERT(channel<mNbChannels);
for (PxU32 i = 0; i < PxVehicleGraph::eMAX_NB_SAMPLES; i++)
{
const PxU32 index = (mSampleTide+1+i) % PxVehicleGraph::eMAX_NB_SAMPLES;
values[i] = mChannelSamples[channel][index];
}
}
void PxVehicleGraph::setupEngineGraph
(const PxF32 sizeX, const PxF32 sizeY, const PxF32 posX, const PxF32 posY,
const PxVec3& backgoundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow)
{
PxVehicleGraphDesc desc;
desc.mSizeX=sizeX;
desc.mSizeY=sizeY;
desc.mPosX=posX;
desc.mPosY=posY;
desc.mBackgroundColor=backgoundColor;
desc.mAlpha=0.5f;
setup(desc,PxVehicleGraphType::eDRIVE);
//Engine revs
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=800.0f;
desc2.mMidY=400.0f;
char title[64];
sprintf(title, "engineRevs");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eENGINE_REVS);
}
//Engine torque
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1000.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "engineDriveTorque");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eENGINE_DRIVE_TORQUE);
}
//Clutch slip
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-200.0f;
desc2.mMaxY=200.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "clutchSlip");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eCLUTCH_SLIP);
}
//Accel control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "accel");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eACCEL_CONTROL);
}
//Brake control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "brake/tank brake left");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eBRAKE_CONTROL);
}
//HandBrake control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "handbrake/tank brake right");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eHANDBRAKE_CONTROL);
}
//Steer control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-1.1f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "steerLeft/tank thrust left");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eSTEER_LEFT_CONTROL);
}
//Steer control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-1.1f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "steerRight/tank thrust right");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eSTEER_RIGHT_CONTROL);
}
//Gear
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-4.f;
desc2.mMaxY=20.f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "gearRatio");
desc2.mTitle=title;
setChannel(desc2,PxVehicleDriveGraphChannel::eGEAR_RATIO);
}
}
void PxVehicleGraph::setupWheelGraph
(const PxF32 sizeX, const PxF32 sizeY, const PxF32 posX, const PxF32 posY,
const PxVec3& backgoundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow)
{
PxVehicleGraphDesc desc;
desc.mSizeX=sizeX;
desc.mSizeY=sizeY;
desc.mPosX=posX;
desc.mPosY=posY;
desc.mBackgroundColor=backgoundColor;
desc.mAlpha=0.5f;
setup(desc,PxVehicleGraphType::eWHEEL);
//Jounce data channel
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-0.2f;
desc2.mMaxY=0.4f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "suspJounce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eJOUNCE);
}
//Jounce susp force channel
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=20000.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "suspForce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eSUSPFORCE);
}
//Tire load channel.
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=20000.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "tireLoad");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eTIRELOAD);
}
//Normalised tire load channel.
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=3.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireLoad");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eNORMALIZED_TIRELOAD);
}
//Wheel omega channel
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-50.0f;
desc2.mMaxY=250.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "wheelOmega");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eWHEEL_OMEGA);
}
//Tire friction
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "friction");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eTIRE_FRICTION);
}
//Tire long slip
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-0.2f;
desc2.mMaxY=0.2f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "tireLongSlip");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eTIRE_LONG_SLIP);
}
//Normalised tire long force
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=2.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireLongForce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eNORM_TIRE_LONG_FORCE);
}
//Tire lat slip
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-1.0f;
desc2.mMaxY=1.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "tireLatSlip");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eTIRE_LAT_SLIP);
}
//Normalised tire lat force
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=2.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireLatForce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eNORM_TIRE_LAT_FORCE);
}
//Normalized aligning moment
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=2.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireAlignMoment");
desc2.mTitle=title;
setChannel(desc2,PxVehicleWheelGraphChannel::eNORM_TIRE_ALIGNING_MOMENT);
}
}
PxVehicleTelemetryData* physx::PxVehicleTelemetryData::allocate(const PxU32 numWheels)
{
//Work out the byte size required.
PxU32 size = sizeof(PxVehicleTelemetryData);
size += sizeof(PxVehicleGraph); //engine graph
size += sizeof(PxVehicleGraph)*numWheels; //wheel graphs
size += sizeof(PxVec3)*numWheels; //tire force app points
size += sizeof(PxVec3)*numWheels; //susp force app points
//Allocate the memory.
PxVehicleTelemetryData* vehTelData=static_cast<PxVehicleTelemetryData*>(PX_ALLOC(size, "PxVehicleNWTelemetryData"));
//Patch up the pointers.
PxU8* ptr = reinterpret_cast<PxU8*>(vehTelData) + sizeof(PxVehicleTelemetryData);
vehTelData->mEngineGraph = reinterpret_cast<PxVehicleGraph*>(ptr);
PX_PLACEMENT_NEW(vehTelData->mEngineGraph, PxVehicleGraph());
ptr += sizeof(PxVehicleGraph);
vehTelData->mWheelGraphs = reinterpret_cast<PxVehicleGraph*>(ptr);
for(PxU32 i=0;i<numWheels;i++)
{
PX_PLACEMENT_NEW(&vehTelData->mWheelGraphs[i], PxVehicleGraph());
}
ptr += sizeof(PxVehicleGraph)*numWheels;
vehTelData->mSuspforceAppPoints = reinterpret_cast<PxVec3*>(ptr);
ptr += sizeof(PxVec3)*numWheels;
vehTelData->mTireforceAppPoints = reinterpret_cast<PxVec3*>(ptr);
ptr += sizeof(PxVec3)*numWheels;
//Set the number of wheels in each structure that needs it.
vehTelData->mNbActiveWheels=numWheels;
//Finished.
return vehTelData;
}
void PxVehicleTelemetryData::free()
{
PX_FREE_THIS;
}
void physx::PxVehicleTelemetryData::setup
(const PxF32 graphSizeX, const PxF32 graphSizeY,
const PxF32 engineGraphPosX, const PxF32 engineGraphPosY,
const PxF32* const wheelGraphPosX, const PxF32* const wheelGraphPosY,
const PxVec3& backgroundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow)
{
mEngineGraph->setupEngineGraph
(graphSizeX, graphSizeY, engineGraphPosX, engineGraphPosY,
backgroundColor, lineColorHigh, lineColorLow);
const PxU32 numActiveWheels=mNbActiveWheels;
for(PxU32 k=0;k<numActiveWheels;k++)
{
mWheelGraphs[k].setupWheelGraph
(graphSizeX, graphSizeY, wheelGraphPosX[k], wheelGraphPosY[k],
backgroundColor, lineColorHigh, lineColorLow);
mTireforceAppPoints[k]=PxVec3(0,0,0);
mSuspforceAppPoints[k]=PxVec3(0,0,0);
}
}
void physx::PxVehicleTelemetryData::clear()
{
mEngineGraph->clearRecordedChannelData();
const PxU32 numActiveWheels=mNbActiveWheels;
for(PxU32 k=0;k<numActiveWheels;k++)
{
mWheelGraphs[k].clearRecordedChannelData();
mTireforceAppPoints[k]=PxVec3(0,0,0);
mSuspforceAppPoints[k]=PxVec3(0,0,0);
}
}
#endif //PX_DEBUG_VEHICLE_ON
} //physx
| 17,869 |
C++
| 29.339559 | 234 | 0.755666 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleTireFriction.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleTireFriction.h"
#include "foundation/PxMemory.h"
#include "foundation/PxErrors.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxIO.h"
#include "foundation/PxBitMap.h"
#include "common/PxCollection.h"
#include "PxMaterial.h"
namespace physx
{
PX_FORCE_INLINE PxU32 computeByteSize(const PxU32 maxNbTireTypes, const PxU32 maxNbSurfaceTypes)
{
PxU32 byteSize = ((sizeof(PxU32)*(maxNbTireTypes*maxNbSurfaceTypes) + 15) & ~15);
byteSize += ((sizeof(PxMaterial*)*maxNbSurfaceTypes + 15) & ~15);
byteSize += ((sizeof(PxVehicleDrivableSurfaceType)*maxNbSurfaceTypes + 15) & ~15);
byteSize += ((sizeof(PxSerialObjectId)*maxNbSurfaceTypes + 15) & ~15);
byteSize += ((sizeof(PxVehicleDrivableSurfaceToTireFrictionPairs) + 15) & ~ 15);
return byteSize;
}
PxVehicleDrivableSurfaceToTireFrictionPairs* PxVehicleDrivableSurfaceToTireFrictionPairs::allocate
(const PxU32 maxNbTireTypes, const PxU32 maxNbSurfaceTypes)
{
PX_CHECK_AND_RETURN_VAL(maxNbSurfaceTypes <= eMAX_NB_SURFACE_TYPES, "maxNbSurfaceTypes must be less than eMAX_NB_SURFACE_TYPES", NULL);
PxU32 byteSize = computeByteSize(maxNbTireTypes, maxNbSurfaceTypes);
PxU8* ptr = static_cast<PxU8*>(PX_ALLOC(byteSize, "PxVehicleDrivableSurfaceToTireFrictionPairs"));
PxMemSet(ptr, 0, byteSize);
PxVehicleDrivableSurfaceToTireFrictionPairs* pairs = reinterpret_cast<PxVehicleDrivableSurfaceToTireFrictionPairs*>(ptr);
pairs->mPairs = NULL;
pairs->mDrivableSurfaceMaterials = NULL;
pairs->mDrivableSurfaceTypes = NULL;
pairs->mMaterialSerialIds = NULL;
pairs->mNbTireTypes = 0;
pairs->mMaxNbTireTypes = maxNbTireTypes;
pairs->mNbSurfaceTypes = 0;
pairs->mMaxNbSurfaceTypes = maxNbSurfaceTypes;
return pairs;
}
void PxVehicleDrivableSurfaceToTireFrictionPairs::setup
(const PxU32 numTireTypes, const PxU32 numSurfaceTypes, const PxMaterial** drivableSurfaceMaterials, const PxVehicleDrivableSurfaceType* drivableSurfaceTypes)
{
PX_CHECK_AND_RETURN(numTireTypes <= mMaxNbTireTypes, "numTireTypes must be less than mMaxNumSurfaceTypes");
PX_CHECK_AND_RETURN(numSurfaceTypes <= mMaxNbSurfaceTypes, "numSurfaceTypes must be less than mMaxNumSurfaceTypes");
PxU8* ptr = reinterpret_cast<PxU8*>(this);
const PxU32 maxNbTireTypes = mMaxNbTireTypes;
const PxU32 maxNbSurfaceTypes = mMaxNbSurfaceTypes;
PxU32 byteSize = computeByteSize(mMaxNbTireTypes, mMaxNbSurfaceTypes);
PxMemSet(ptr, 0, byteSize);
mMaxNbTireTypes = maxNbTireTypes;
mMaxNbSurfaceTypes = maxNbSurfaceTypes;
PxVehicleDrivableSurfaceToTireFrictionPairs* pairs = reinterpret_cast<PxVehicleDrivableSurfaceToTireFrictionPairs*>(ptr);
ptr += ((sizeof(PxVehicleDrivableSurfaceToTireFrictionPairs) + 15) & ~ 15);
mPairs = reinterpret_cast<PxReal*>(ptr);
ptr += ((sizeof(PxU32)*(numTireTypes*numSurfaceTypes) + 15) & ~15);
mDrivableSurfaceMaterials = reinterpret_cast<const PxMaterial**>(ptr);
ptr += ((sizeof(PxMaterial*)*numSurfaceTypes + 15) & ~15);
mDrivableSurfaceTypes = reinterpret_cast<PxVehicleDrivableSurfaceType*>(ptr);
ptr += ((sizeof(PxVehicleDrivableSurfaceType)*numSurfaceTypes +15) & ~15);
mMaterialSerialIds = reinterpret_cast<PxSerialObjectId*>(ptr);
ptr += ((sizeof(PxSerialObjectId)*numSurfaceTypes + 15) & ~15);
for(PxU32 i=0;i<numSurfaceTypes;i++)
{
mDrivableSurfaceTypes[i] = drivableSurfaceTypes[i];
mDrivableSurfaceMaterials[i] = drivableSurfaceMaterials[i];
mMaterialSerialIds[i] = 0;
}
for(PxU32 i=0;i<numTireTypes*numSurfaceTypes;i++)
{
mPairs[i]=1.0f;
}
pairs->mNbTireTypes=numTireTypes;
pairs->mNbSurfaceTypes=numSurfaceTypes;
}
void PxVehicleDrivableSurfaceToTireFrictionPairs::release()
{
PX_FREE_THIS;
}
void PxVehicleDrivableSurfaceToTireFrictionPairs::setTypePairFriction(const PxU32 surfaceType, const PxU32 tireType, const PxReal value)
{
PX_CHECK_AND_RETURN(tireType<mNbTireTypes, "Invalid tireType");
PX_CHECK_AND_RETURN(surfaceType<mNbSurfaceTypes, "Invalid surfaceType");
*(mPairs + mNbTireTypes*surfaceType + tireType) = value;
}
PxReal PxVehicleDrivableSurfaceToTireFrictionPairs::getTypePairFriction(const PxU32 surfaceType, const PxU32 tireType) const
{
PX_CHECK_AND_RETURN_VAL(tireType<mNbTireTypes, "Invalid tireType", 0.0f);
PX_CHECK_AND_RETURN_VAL(surfaceType<mNbSurfaceTypes, "Invalid surfaceType", 0.0f);
return *(mPairs + mNbTireTypes*surfaceType + tireType);
}
////////////////////////////////////////////////////////////////////////////
//Hash table of PxMaterial pointers used to associate each PxMaterial pointer
//with a unique PxDrivableSurfaceType. PxDrivableSurfaceType is just an integer
//representing an id but introducing this type allows different PxMaterial pointers
//to be associated with the same surface type. The friction of a specific tire
//touching a specific PxMaterial is found from a 2D table using the integers for
//the tire type (stored in the tire) and drivable surface type (from the hash table).
//It would be great to use PsHashSet for the hash table of PxMaterials but
//PsHashSet will never, ever work on spu so this will need to do instead.
//Perf isn't really critical so this will do in the meantime.
//It is probably wasteful to compute the hash table each update
//but this is really not an expensive operation so keeping the api as
//simple as possible wins out at the cost of a relatively very small number of wasted cycles.
////////////////////////////////////////////////////////////////////////////
class VehicleSurfaceTypeHashTable
{
public:
VehicleSurfaceTypeHashTable(const PxVehicleDrivableSurfaceToTireFrictionPairs& pairs)
: mNbEntries(pairs.mNbSurfaceTypes),
mMaterials(pairs.mDrivableSurfaceMaterials),
mDrivableSurfaceTypes(pairs.mDrivableSurfaceTypes)
{
for (PxU32 i = 0; i < eHASH_SIZE; i++)
{
mHeadIds[i] = PX_MAX_U32;
}
for (PxU32 i = 0; i < eMAX_NB_KEYS; i++)
{
mNextIds[i] = PX_MAX_U32;
}
if (mNbEntries > 0)
{
//Compute the number of bits to right-shift that gives the maximum number of unique hashes.
//Keep searching until we find either a set of completely unique hashes or a peak count of unique hashes.
PxU32 prevShift = 0;
PxU32 shift = 2;
PxU32 prevNumUniqueHashes = 0;
PxU32 currNumUniqueHashes = 0;
while (((currNumUniqueHashes = computeNumUniqueHashes(shift)) > prevNumUniqueHashes) && currNumUniqueHashes != mNbEntries)
{
prevNumUniqueHashes = currNumUniqueHashes;
prevShift = shift;
shift = (shift << 1);
}
if (currNumUniqueHashes != mNbEntries)
{
//Stopped searching because we have gone past the peak number of unqiue hashes.
mShift = prevShift;
}
else
{
//Stopped searching because we found a unique hash for each key.
mShift = shift;
}
//Compute the hash values with the optimum shift.
for (PxU32 i = 0; i < mNbEntries; i++)
{
const PxMaterial* const material = mMaterials[i];
const PxU32 hash = computeHash(material, mShift);
if (PX_MAX_U32 == mHeadIds[hash])
{
mNextIds[i] = PX_MAX_U32;
mHeadIds[hash] = i;
}
else
{
mNextIds[i] = mHeadIds[hash];
mHeadIds[hash] = i;
}
}
}
}
~VehicleSurfaceTypeHashTable()
{
}
PX_FORCE_INLINE PxU32 get(const PxMaterial* const key) const
{
PX_ASSERT(key);
const PxU32 hash = computeHash(key, mShift);
PxU32 id = mHeadIds[hash];
while (PX_MAX_U32 != id)
{
const PxMaterial* const mat = mMaterials[id];
if (key == mat)
{
return mDrivableSurfaceTypes[id].mType;
}
id = mNextIds[id];
}
return 0;
}
private:
PxU32 mNbEntries;
const PxMaterial* const* mMaterials;
const PxVehicleDrivableSurfaceType* mDrivableSurfaceTypes;
static PX_FORCE_INLINE PxU32 computeHash(const PxMaterial* const key, const PxU32 shift)
{
const uintptr_t ptr = ((uintptr_t(key)) >> shift);
const uintptr_t hash = (ptr & (eHASH_SIZE - 1));
return PxU32(hash);
}
PxU32 computeNumUniqueHashes(const PxU32 shift) const
{
PxU32 words[eHASH_SIZE >> 5];
PxU8* bitmapBuffer[sizeof(PxBitMap)];
PxBitMap* bitmap = reinterpret_cast<PxBitMap*>(bitmapBuffer);
bitmap->setWords(words, eHASH_SIZE >> 5);
PxU32 numUniqueHashes = 0;
PxMemZero(words, sizeof(PxU32)*(eHASH_SIZE >> 5));
for (PxU32 i = 0; i < mNbEntries; i++)
{
const PxMaterial* const material = mMaterials[i];
const PxU32 hash = computeHash(material, shift);
if (!bitmap->test(hash))
{
bitmap->set(hash);
numUniqueHashes++;
}
}
return numUniqueHashes;
}
enum
{
eHASH_SIZE = PxVehicleDrivableSurfaceToTireFrictionPairs::eMAX_NB_SURFACE_TYPES
};
PxU32 mHeadIds[eHASH_SIZE];
enum
{
eMAX_NB_KEYS = PxVehicleDrivableSurfaceToTireFrictionPairs::eMAX_NB_SURFACE_TYPES
};
PxU32 mNextIds[eMAX_NB_KEYS];
PxU32 mShift;
};
PxU32 PxVehicleDrivableSurfaceToTireFrictionPairs::getSurfaceType(const PxMaterial& surfaceMaterial) const
{
const VehicleSurfaceTypeHashTable surfaceTypeHashTable(*this);
const PxU32 surfaceType = surfaceTypeHashTable.get(&surfaceMaterial);
return surfaceType;
}
PxReal PxVehicleDrivableSurfaceToTireFrictionPairs::getTypePairFriction(const PxMaterial& surfaceMaterial, const PxU32 tireType) const
{
const PxU32 surfaceType = getSurfaceType(surfaceMaterial);
return getTypePairFriction(surfaceType, tireType);
}
#if PX_CHECKED
bool isLegalCollectionWithNullArray(PxCollection* collection, const PxSerialObjectId* materialIds, const PxMaterial** materials, const PxU32 nbMaterials)
{
if (!materialIds)
{
for (PxU32 i = 0; i < nbMaterials; i++)
{
const PxMaterial* material = materials[i];
if (0 == collection->getId(*material))
{
return false;
}
}
}
return true;
}
bool isLegalCollection(PxCollection* collection, const PxSerialObjectId* materialIds, const PxMaterial** materials, const PxU32 nbMaterials)
{
if(materialIds)
{
for (PxU32 i = 0; i < nbMaterials; i++)
{
const PxMaterial* material = materials[i];
if (0 == collection->getId(*material))
{
//Material has not yet been assigned an id.
//Make sure materialId is free.
if(collection->find(materialIds[i]))
{
return false;
}
}
}
}
return true;
}
#endif
void PxVehicleDrivableSurfaceToTireFrictionPairs::serializeToBinary
(const PxVehicleDrivableSurfaceToTireFrictionPairs& frictionTable,
const PxSerialObjectId* materialIds, const PxU32 nbMaterialIds,
PxCollection* collection, PxOutputStream& stream)
{
PX_CHECK_AND_RETURN(!materialIds || nbMaterialIds >= frictionTable.mNbSurfaceTypes, "PxVehicleDrivableSurfaceToTireFrictionPairs::serializeToBinary - insufficient nbMaterialIds");
PX_CHECK_AND_RETURN(isLegalCollectionWithNullArray(collection, materialIds, frictionTable.mDrivableSurfaceMaterials, frictionTable.mNbSurfaceTypes), "PxVehicleDrivableSurfaceToTireFrictionPairs::serializeToBinary - material ids not configured");
PX_CHECK_AND_RETURN(isLegalCollection(collection, materialIds, frictionTable.mDrivableSurfaceMaterials, frictionTable.mNbSurfaceTypes), "PxVehicleDrivableSurfaceToTireFrictionPairs::serializeToBinary - material id already in use");
PX_UNUSED(nbMaterialIds);
for (PxU32 i = 0; i < frictionTable.mNbSurfaceTypes; i++)
{
const PxMaterial* material = frictionTable.mDrivableSurfaceMaterials[i];
const PxSerialObjectId id = collection->getId(*material);
if(0 == id)
{
collection->add(*const_cast<PxMaterial*>(material), materialIds[i]);
const_cast<PxVehicleDrivableSurfaceToTireFrictionPairs&>(frictionTable).mMaterialSerialIds[i] = materialIds[i];
}
else
{
const_cast<PxVehicleDrivableSurfaceToTireFrictionPairs&>(frictionTable).mMaterialSerialIds[i] = collection->getId(*material);
}
}
stream.write(&frictionTable, computeByteSize(frictionTable.mMaxNbTireTypes, frictionTable.mMaxNbSurfaceTypes));
for (PxU32 i = 0; i < frictionTable.mNbSurfaceTypes; i++)
{
const_cast<PxVehicleDrivableSurfaceToTireFrictionPairs&>(frictionTable).mMaterialSerialIds[i] = 0;
}
}
PxVehicleDrivableSurfaceToTireFrictionPairs* PxVehicleDrivableSurfaceToTireFrictionPairs::deserializeFromBinary(const PxCollection& collection, void* buffer)
{
PxVehicleDrivableSurfaceToTireFrictionPairs* fricTable = reinterpret_cast<PxVehicleDrivableSurfaceToTireFrictionPairs*>(buffer);
//Patch up pointers.
{
PxU8* ptr = reinterpret_cast<PxU8*>(fricTable);
ptr += ((sizeof(PxVehicleDrivableSurfaceToTireFrictionPairs) + 15) & ~15);
fricTable->mPairs = reinterpret_cast<PxReal*>(ptr);
ptr += ((sizeof(PxU32) * (fricTable->mNbTireTypes * fricTable->mNbSurfaceTypes) + 15) & ~15);
fricTable->mDrivableSurfaceMaterials = reinterpret_cast<const PxMaterial**>(ptr);
ptr += ((sizeof(PxMaterial*) * fricTable->mNbSurfaceTypes + 15) & ~15);
fricTable->mDrivableSurfaceTypes = reinterpret_cast<PxVehicleDrivableSurfaceType*>(ptr);
ptr += ((sizeof(PxVehicleDrivableSurfaceType) * fricTable->mNbSurfaceTypes + 15) & ~15);
fricTable->mMaterialSerialIds = reinterpret_cast<PxSerialObjectId*>(ptr);
ptr += ((sizeof(PxSerialObjectId) * fricTable->mNbSurfaceTypes + 15) & ~15);
}
//Set the material pointers in order.
for (PxU32 i = 0; i < fricTable->mNbSurfaceTypes; i++)
{
const PxSerialObjectId id = fricTable->mMaterialSerialIds[i];
const PxBase* base = collection.find(id);
const PxMaterial* material = base->is<PxMaterial>();
fricTable->mDrivableSurfaceMaterials[i] = material;
}
return fricTable;
}
}//physx
| 15,054 |
C++
| 36.35732 | 246 | 0.74897 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleWheels.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleWheels.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxIntrinsics.h"
#include "PxRigidDynamic.h"
#include "PxShape.h"
#include "PxPhysics.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "foundation/PxUtilities.h"
namespace physx
{
PxF32 gThresholdLongSpeed=5.0f;
PxU32 gLowLongSpeedSubstepCount=3;
PxU32 gHighLongSpeedSubstepCount=1;
PxF32 gMinLongSlipDenominator=4.0f;
extern PxF32 gToleranceScaleLength;
PxU32 PxVehicleWheelsSimData::computeByteSize(const PxU32 numWheels)
{
const PxU32 numWheels4 =(((numWheels + 3) & ~3) >> 2);
const PxU32 byteSize = sizeof(PxVehicleWheels4SimData)*numWheels4 + sizeof(PxVehicleAntiRollBarData)*2*numWheels4;
return byteSize;
}
PxU8* PxVehicleWheelsSimData::patchUpPointers(const PxU32 numWheels, PxVehicleWheelsSimData* simData, PxU8* ptrIn)
{
const PxU32 numWheels4 =(((numWheels + 3) & ~3) >> 2);
PxU8* ptr = ptrIn;
simData->mWheels4SimData = reinterpret_cast<PxVehicleWheels4SimData*>(ptr);
ptr += sizeof(PxVehicleWheels4SimData)*numWheels4;
simData->mAntiRollBars = reinterpret_cast<PxVehicleAntiRollBarData*>(ptr);
ptr += sizeof(PxVehicleAntiRollBarData)*numWheels4*2;
PX_ASSERT((ptrIn + computeByteSize(numWheels)) == ptr);
return ptr;
}
PxVehicleWheelsSimData::PxVehicleWheelsSimData(const PxU32 numWheels)
{
const PxU32 numWheels4 =(((numWheels + 3) & ~3) >> 2);
//Set numWheels
mNbWheels4 = numWheels4;
mNbActiveWheels = numWheels;
//Set numAntiRollBars to zero.
mNbAntiRollBars4 = 2*numWheels4;
mNbActiveAntiRollBars = 0;
//Placement new for wheels4
for(PxU32 i=0;i<numWheels4;i++)
{
PX_PLACEMENT_NEW(&mWheels4SimData[i], PxVehicleWheels4SimData());
}
//Placement new for anti-roll bars
for(PxU32 i=0;i<numWheels4*2;i++)
{
PX_PLACEMENT_NEW(&mAntiRollBars[i], PxVehicleAntiRollBarData());
}
//Placement new for tire load filter data.
PX_PLACEMENT_NEW(&mNormalisedLoadFilter, PxVehicleTireLoadFilterData());
//Enable used wheels, disabled unused wheels.
PxMemZero(mActiveWheelsBitmapBuffer, sizeof(PxU32) * (((PX_MAX_NB_WHEELS + 31) & ~31) >> 5));
for(PxU32 i=0;i<numWheels;i++)
{
//Enabled used wheel.
enableWheel(i);
setWheelShapeMapping(i,PxI32(i));
setSceneQueryFilterData(i, PxFilterData());
}
for(PxU32 i=numWheels;i<numWheels4*4;i++)
{
//Disable unused wheel.
disableWheel(i);
setWheelShapeMapping(i,-1);
setSceneQueryFilterData(i, PxFilterData());
}
//Default values for substep count computation.
mThresholdLongitudinalSpeed = gThresholdLongSpeed*gToleranceScaleLength;
mLowForwardSpeedSubStepCount = gLowLongSpeedSubstepCount;
mHighForwardSpeedSubStepCount = gHighLongSpeedSubstepCount;
mMinLongSlipDenominator = gMinLongSlipDenominator*gToleranceScaleLength;
mFlags = 0;
}
PxVehicleWheelsSimData* PxVehicleWheelsSimData::allocate(const PxU32 numWheels)
{
//Byte size
const PxU32 byteSize = sizeof(PxVehicleWheelsSimData) + computeByteSize(numWheels);
//Allocate
PxU8* ptrStart = static_cast<PxU8*>(PX_ALLOC(byteSize, "PxVehicleWheelsSimData"));
//Patchup pointers
PxU8* ptr = ptrStart;
PxVehicleWheelsSimData* simData = reinterpret_cast<PxVehicleWheelsSimData*>(ptr);
ptr += sizeof(PxVehicleWheelsSimData);
ptr = patchUpPointers(numWheels, simData, ptr);
PX_ASSERT((ptrStart+ byteSize) == ptr);
//Constructor.
PX_PLACEMENT_NEW(simData, PxVehicleWheelsSimData(numWheels));
//Finished.
return simData;
}
void PxVehicleWheelsSimData::setChassisMass(const PxF32 chassisMass)
{
//Target spring natural frequency = 9.66
//Target spring damping ratio = 0.62
const PxF32 mult=1.0f/(1.0f*mNbActiveWheels);
const PxF32 sprungMass=chassisMass*mult;
const PxF32 w0=9.66f;
const PxF32 r=0.62f;
for(PxU32 i=0;i<mNbActiveWheels;i++)
{
PxVehicleSuspensionData susp=getSuspensionData(i);
susp.mSprungMass=sprungMass;
susp.mSpringStrength=w0*w0*sprungMass;
susp.mSpringDamperRate=r*2*sprungMass*w0;
setSuspensionData(i,susp);
}
}
void PxVehicleWheelsSimData::free()
{
for(PxU32 i=0;i<mNbWheels4;i++)
{
mWheels4SimData[i].~PxVehicleWheels4SimData();
}
PX_FREE_THIS;
}
PxVehicleWheelsSimData& PxVehicleWheelsSimData::operator=(const PxVehicleWheelsSimData& src)
{
PX_CHECK_MSG(mNbActiveWheels == src.mNbActiveWheels, "target PxVehicleSuspWheelTireNSimData must match the number of wheels in src");
for(PxU32 i=0;i<src.mNbWheels4;i++)
{
mWheels4SimData[i] = src.mWheels4SimData[i];
}
mNbActiveAntiRollBars = src.mNbActiveAntiRollBars;
for(PxU32 i=0; i<src.mNbActiveAntiRollBars; i++)
{
mAntiRollBars[i] = src.mAntiRollBars[i];
}
mNormalisedLoadFilter = src.mNormalisedLoadFilter;
mThresholdLongitudinalSpeed = src.mThresholdLongitudinalSpeed;
mLowForwardSpeedSubStepCount = src.mLowForwardSpeedSubStepCount;
mHighForwardSpeedSubStepCount = src.mHighForwardSpeedSubStepCount;
mMinLongSlipDenominator = src.mMinLongSlipDenominator;
mFlags = src.mFlags;
PxMemCopy(mActiveWheelsBitmapBuffer, src.mActiveWheelsBitmapBuffer, sizeof(PxU32)* (((PX_MAX_NB_WHEELS + 31) & ~31) >> 5));
return *this;
}
void PxVehicleWheelsSimData::copy(const PxVehicleWheelsSimData& src, const PxU32 srcWheel, const PxU32 wheel)
{
PX_CHECK_AND_RETURN(srcWheel < src.mNbActiveWheels, "Illegal src wheel");
PX_CHECK_AND_RETURN(wheel < mNbActiveWheels, "Illegal target wheel");
setSuspensionData(wheel,src.getSuspensionData(srcWheel));
setWheelData(wheel,src.getWheelData(srcWheel));
setTireData(wheel,src.getTireData(srcWheel));
setSuspTravelDirection(wheel,src.getSuspTravelDirection(srcWheel));
setSuspForceAppPointOffset(wheel,src.getSuspForceAppPointOffset(srcWheel));
setTireForceAppPointOffset(wheel,src.getTireForceAppPointOffset(srcWheel));
setWheelCentreOffset(wheel,src.getWheelCentreOffset(srcWheel));
setWheelShapeMapping(wheel, src.getWheelShapeMapping(srcWheel));
setSceneQueryFilterData(wheel, src.getSceneQueryFilterData(srcWheel));
if(src.getIsWheelDisabled(srcWheel))
disableWheel(wheel);
else
enableWheel(wheel);
}
bool PxVehicleWheelsSimData::isValid() const
{
for(PxU32 i=0;i<mNbWheels4-1;i++)
{
mWheels4SimData[i].isValid(0);
mWheels4SimData[i].isValid(1);
mWheels4SimData[i].isValid(2);
mWheels4SimData[i].isValid(3);
}
const PxU32 numInLastBlock = 4 - (4*mNbWheels4 - mNbActiveWheels);
for(PxU32 i=0;i<numInLastBlock;i++)
{
mWheels4SimData[mNbWheels4-1].isValid(i);
}
PX_CHECK_AND_RETURN_VAL(mNormalisedLoadFilter.isValid(), "Invalid PxVehicleWheelsSimData.mNormalisedLoadFilter", false);
return true;
}
void PxVehicleWheelsSimData::disableWheel(const PxU32 wheel)
{
PX_CHECK_AND_RETURN(wheel < 4*mNbWheels4, "PxVehicleWheelsSimData::disableWheel - Illegal wheel");
PxBitMap bm;
bm.setWords(mActiveWheelsBitmapBuffer, ((PX_MAX_NB_WHEELS + 31) & ~31) >> 5);
bm.reset(wheel);
}
void PxVehicleWheelsSimData::enableWheel(const PxU32 wheel)
{
PX_CHECK_AND_RETURN(wheel < 4*mNbWheels4, "PxVehicleWheelsSimData::disableWheel - Illegal wheel");
PxBitMap bm;
bm.setWords(mActiveWheelsBitmapBuffer, ((PX_MAX_NB_WHEELS + 31) & ~31) >> 5);
bm.set(wheel);
}
bool PxVehicleWheelsSimData::getIsWheelDisabled(const PxU32 wheel) const
{
PX_CHECK_AND_RETURN_VAL(wheel < 4*mNbWheels4, "PxVehicleWheelsSimData::getIsWheelDisabled - Illegal wheel", false);
PxBitMap bm;
bm.setWords(const_cast<PxU32*>(mActiveWheelsBitmapBuffer), ((PX_MAX_NB_WHEELS + 31) & ~31) >> 5);
return (bm.test(wheel) ? false : true);
}
const PxVehicleSuspensionData& PxVehicleWheelsSimData::getSuspensionData(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getSuspensionData - Illegal wheel");
return mWheels4SimData[id>>2].getSuspensionData(id & 3);
}
const PxVehicleWheelData& PxVehicleWheelsSimData::getWheelData(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getWheelData - Illegal wheel");
return mWheels4SimData[id>>2].getWheelData(id & 3);
}
const PxVehicleTireData& PxVehicleWheelsSimData::getTireData(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getTireData - Illegal wheel");
return mWheels4SimData[id>>2].getTireData(id & 3);
}
const PxVec3& PxVehicleWheelsSimData::getSuspTravelDirection(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getSuspTravelDirection - Illegal wheel");
return mWheels4SimData[id>>2].getSuspTravelDirection(id & 3);
}
const PxVec3& PxVehicleWheelsSimData::getSuspForceAppPointOffset(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getSuspForceAppPointOffset - Illegal wheel");
return mWheels4SimData[id>>2].getSuspForceAppPointOffset(id & 3);
}
const PxVec3& PxVehicleWheelsSimData::getTireForceAppPointOffset(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getTireForceAppPointOffset - Illegal wheel");
return mWheels4SimData[id>>2].getTireForceAppPointOffset(id & 3);
}
const PxVec3& PxVehicleWheelsSimData::getWheelCentreOffset(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getWheelCentreOffset - Illegal wheel");
return mWheels4SimData[id>>2].getWheelCentreOffset(id & 3);
}
PxI32 PxVehicleWheelsSimData::getWheelShapeMapping(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getWheelShapeMapping - Illegal wheel");
return mWheels4SimData[id>>2].getWheelShapeMapping(id & 3);
}
const PxFilterData& PxVehicleWheelsSimData::getSceneQueryFilterData(const PxU32 id) const
{
PX_CHECK_MSG(id < 4*mNbWheels4, "PxVehicleWheelsSimData::getSceneQueryFilterData - Illegal wheel");
return mWheels4SimData[id>>2].getSceneQueryFilterData(id & 3);
}
const PxVehicleAntiRollBarData& PxVehicleWheelsSimData::getAntiRollBarData(const PxU32 antiRollId) const
{
PX_CHECK_MSG(antiRollId < mNbActiveAntiRollBars, "PxVehicleWheelsSimData::getAntiRollBarData - Illegal anti-roll bar");
return mAntiRollBars[antiRollId];
}
void PxVehicleWheelsSimData::setSuspensionData(const PxU32 id, const PxVehicleSuspensionData& susp)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setSuspensionData - Illegal wheel");
mWheels4SimData[id>>2].setSuspensionData(id & 3, susp);
}
void PxVehicleWheelsSimData::setWheelData(const PxU32 id, const PxVehicleWheelData& wheel)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setWheelData - Illegal wheel");
mWheels4SimData[id>>2].setWheelData(id & 3, wheel);
}
void PxVehicleWheelsSimData::setTireData(const PxU32 id, const PxVehicleTireData& tire)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setTireData - Illegal wheel");
mWheels4SimData[id>>2].setTireData(id & 3, tire);
}
void PxVehicleWheelsSimData::setSuspTravelDirection(const PxU32 id, const PxVec3& dir)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setSuspTravelDirection - Illegal wheel");
mWheels4SimData[id>>2].setSuspTravelDirection(id & 3, dir);
}
void PxVehicleWheelsSimData::setSuspForceAppPointOffset(const PxU32 id, const PxVec3& offset)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setSuspForceAppPointOffset - Illegal wheel");
mWheels4SimData[id>>2].setSuspForceAppPointOffset(id & 3, offset);
}
void PxVehicleWheelsSimData::setTireForceAppPointOffset(const PxU32 id, const PxVec3& offset)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setTireForceAppPointOffset - Illegal wheel");
mWheels4SimData[id>>2].setTireForceAppPointOffset(id & 3, offset);
}
void PxVehicleWheelsSimData::setWheelCentreOffset(const PxU32 id, const PxVec3& offset)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setWheelCentreOffset - Illegal wheel");
mWheels4SimData[id>>2].setWheelCentreOffset(id & 3, offset);
}
void PxVehicleWheelsSimData::setWheelShapeMapping(const PxU32 id, const PxI32 shapeId)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setWheelShapeMapping - Illegal wheel");
mWheels4SimData[id>>2].setWheelShapeMapping(id & 3, shapeId);
}
void PxVehicleWheelsSimData::setSceneQueryFilterData(const PxU32 id, const PxFilterData& sqFilterData)
{
PX_CHECK_AND_RETURN(id < 4*mNbWheels4, "PxVehicleWheelsSimData::setSceneQueryFilterData - Illegal wheel");
mWheels4SimData[id>>2].setSceneQueryFilterData(id & 3, sqFilterData);
}
void PxVehicleWheelsSimData::setTireLoadFilterData(const PxVehicleTireLoadFilterData& tireLoadFilter)
{
PX_CHECK_AND_RETURN(tireLoadFilter.mMaxNormalisedLoad>tireLoadFilter.mMinNormalisedLoad, "Illegal graph points");
PX_CHECK_AND_RETURN(tireLoadFilter.mMaxFilteredNormalisedLoad>0, "Max filtered load must be greater than zero");
mNormalisedLoadFilter=tireLoadFilter;
mNormalisedLoadFilter.mDenominator=1.0f/(mNormalisedLoadFilter.mMaxNormalisedLoad-mNormalisedLoadFilter.mMinNormalisedLoad);
}
PxU32 PxVehicleWheelsSimData::addAntiRollBarData(const PxVehicleAntiRollBarData& antiRollBar)
{
PX_CHECK_AND_RETURN_VAL(antiRollBar.isValid(), "Illegal antiRollBar", 0xffffffff)
PX_CHECK_AND_RETURN_VAL(antiRollBar.mWheel0 < mNbActiveWheels, "Illegal wheel0", 0xffffffff);
PX_CHECK_AND_RETURN_VAL(antiRollBar.mWheel1 < mNbActiveWheels, "Illegal wheel1", 0xffffffff);
//If the anti-roll pair already exists then modify it.
for(PxU32 i = 0; i < mNbActiveAntiRollBars; i++)
{
if( ((mAntiRollBars[i].mWheel0 == antiRollBar.mWheel0) && (mAntiRollBars[i].mWheel1 == antiRollBar.mWheel1)) ||
((mAntiRollBars[i].mWheel1 == antiRollBar.mWheel0) && (mAntiRollBars[i].mWheel0 == antiRollBar.mWheel1)) )
{
mAntiRollBars[i].mStiffness = antiRollBar.mStiffness;
return i;
}
}
//Check we have space for an extra anti-roll bar.
PX_CHECK_AND_RETURN_VAL(mNbActiveAntiRollBars < 2*mNbWheels4, "The buffer of anti-roll bars is full", 0xffffffff);
//Add a new anti-roll bar.
const PxU32 id = mNbActiveAntiRollBars;
mAntiRollBars[mNbActiveAntiRollBars] = antiRollBar;
mNbActiveAntiRollBars++;
//Finished.
return id;
}
//Only used for serialization.
void PxVehicleWheelsSimData::setAntiRollBarData(const PxU32 id, const PxVehicleAntiRollBarData& antiRoll)
{
PX_UNUSED(id);
addAntiRollBarData(antiRoll);
}
void PxVehicleWheelsSimData::setSubStepCount(const PxReal thresholdLongitudinalSpeed, const PxU32 lowForwardSpeedSubStepCount, const PxU32 highForwardSpeedSubStepCount)
{
PX_CHECK_AND_RETURN(thresholdLongitudinalSpeed>=0, "thresholdLongitudinalSpeed must be greater than or equal to zero.");
PX_CHECK_AND_RETURN(lowForwardSpeedSubStepCount>0, "lowForwardSpeedSubStepCount must be greater than zero.");
PX_CHECK_AND_RETURN(highForwardSpeedSubStepCount>0, "highForwardSpeedSubStepCount must be greater than zero.");
mThresholdLongitudinalSpeed=thresholdLongitudinalSpeed;
mLowForwardSpeedSubStepCount=lowForwardSpeedSubStepCount;
mHighForwardSpeedSubStepCount=highForwardSpeedSubStepCount;
}
void PxVehicleWheelsSimData::setMinLongSlipDenominator(const PxReal minLongSlipDenominator)
{
PX_CHECK_AND_RETURN(minLongSlipDenominator>0, "minLongSlipDenominator must be greater than or equal to zero.");
mMinLongSlipDenominator=minLongSlipDenominator;
}
void PxVehicleWheelsSimData::setFlags(PxVehicleWheelsSimFlags flags)
{
mFlags = flags;
}
PxVehicleWheelsSimFlags PxVehicleWheelsSimData::getFlags() const
{
return PxVehicleWheelsSimFlags(mFlags);
}
/////////////////////////////
PxU32 PxVehicleWheelsDynData::computeByteSize(const PxU32 numWheels)
{
const PxU32 numWheels4 =(((numWheels + 3) & ~3) >> 2);
const PxU32 byteSize =
sizeof(PxVehicleWheels4DynData)*numWheels4 +
sizeof(PxVehicleTireForceCalculator) + sizeof(void*)*4*numWheels4 +
sizeof(void*)*4*numWheels4 +
sizeof(PxVehicleConstraintShader)*numWheels4;
return byteSize;
}
PxU8* PxVehicleWheelsDynData::patchUpPointers(const PxU32 numWheels, PxVehicleWheelsDynData* dynData, PxU8* ptrIn)
{
const PxU32 numWheels4 =(((numWheels + 3) & ~3) >> 2);
PxU8* ptr = ptrIn;
dynData->mWheels4DynData = reinterpret_cast<PxVehicleWheels4DynData*>(ptr);
ptr += sizeof(PxVehicleWheels4DynData)*numWheels4;
dynData->mTireForceCalculators = reinterpret_cast<PxVehicleTireForceCalculator*>(ptr);
ptr += sizeof(PxVehicleTireForceCalculator);
dynData->mTireForceCalculators->mShaderData = reinterpret_cast<const void**>(ptr);
ptr += sizeof(void*)*4*numWheels4;
dynData->mUserDatas = reinterpret_cast<void**>(ptr);
ptr += sizeof(void*)*4*numWheels4;
for(PxU32 i=0;i<numWheels4;i++)
{
PxVehicleConstraintShader* shader = PX_PLACEMENT_NEW(ptr, PxVehicleConstraintShader());
dynData->mWheels4DynData[i].setVehicleConstraintShader(shader);
ptr += sizeof(PxVehicleConstraintShader);
}
PX_ASSERT((ptrIn + computeByteSize(numWheels)) == ptr);
return ptr;
}
PxVehicleWheelsDynData::PxVehicleWheelsDynData(const PxU32 numWheels)
{
const PxU32 numWheels4 =(((numWheels + 3) & ~3) >> 2);
mNbWheels4=numWheels4;
mNbActiveWheels=numWheels;
//Placement new for wheels4
for(PxU32 i=0;i<numWheels4;i++)
{
PX_PLACEMENT_NEW(&mWheels4DynData[i], PxVehicleWheels4DynData());
}
//Initialise tire calculator
for(PxU32 i=0;i<4*numWheels4;i++)
{
mTireForceCalculators->mShaderData[i]=NULL;
}
PX_PLACEMENT_NEW(mTireForceCalculators, PxVehicleTireForceCalculator);
//Initialise user data
for(PxU32 i=0;i<4*numWheels4;i++)
{
mUserDatas[i]=NULL;
}
}
bool PxVehicleWheelsDynData::isValid() const
{
for(PxU32 i=0;i<mNbWheels4;i++)
{
PX_CHECK_AND_RETURN_VAL(mWheels4DynData[i].isValid(), "Invalid PxVehicleSuspWheelTireNDynData.mSuspWheelTire4DynData[i]", false);
}
return true;
}
void PxVehicleWheelsDynData::setToRestState()
{
//Set susp/wheel/tires to rest state.
const PxU32 numSuspWheelTire4=mNbWheels4;
for(PxU32 i=0;i<numSuspWheelTire4;i++)
{
mWheels4DynData[i].setToRestState();
}
}
void PxVehicleWheelsDynData::setTireForceShaderFunction(PxVehicleComputeTireForce tireForceShaderFn)
{
mTireForceCalculators->mShader=tireForceShaderFn;
}
void PxVehicleWheelsDynData::setTireForceShaderData(const PxU32 tireId, const void* tireForceShaderData)
{
PX_CHECK_AND_RETURN(tireId < mNbActiveWheels, "PxVehicleWheelsDynData::setTireForceShaderData - Illegal tire");
mTireForceCalculators->mShaderData[tireId]=tireForceShaderData;
}
const void* PxVehicleWheelsDynData::getTireForceShaderData(const PxU32 tireId) const
{
PX_CHECK_AND_RETURN_VAL(tireId < mNbActiveWheels, "PxVehicleWheelsDynData::getTireForceShaderData - Illegal tire", NULL);
return mTireForceCalculators->mShaderData[tireId];
}
void PxVehicleWheelsDynData::setWheelRotationSpeed(const PxU32 wheelIdx, const PxReal speed)
{
PX_CHECK_AND_RETURN(wheelIdx < mNbActiveWheels, "PxVehicleWheelsDynData::setWheelRotationSpeed - Illegal wheel");
PxVehicleWheels4DynData& suspWheelTire4=mWheels4DynData[(wheelIdx>>2)];
suspWheelTire4.mWheelSpeeds[wheelIdx & 3] = speed;
suspWheelTire4.mCorrectedWheelSpeeds[wheelIdx & 3] = speed;
}
PxReal PxVehicleWheelsDynData::getWheelRotationSpeed(const PxU32 wheelIdx) const
{
PX_CHECK_AND_RETURN_VAL(wheelIdx < mNbActiveWheels, "PxVehicleWheelsDynData::getWheelRotationSpeed - Illegal wheel", 0.0f);
const PxVehicleWheels4DynData& suspWheelTire4=mWheels4DynData[(wheelIdx>>2)];
return suspWheelTire4.mCorrectedWheelSpeeds[wheelIdx & 3];
}
void PxVehicleWheelsDynData::setWheelRotationAngle(const PxU32 wheelIdx, const PxReal angle)
{
PX_CHECK_AND_RETURN(wheelIdx < mNbActiveWheels, "PxVehicleWheelsDynData::setWheelRotationAngle - Illegal wheel");
PxVehicleWheels4DynData& suspWheelTire4=mWheels4DynData[(wheelIdx>>2)];
suspWheelTire4.mWheelRotationAngles[wheelIdx & 3] = angle;
}
PxReal PxVehicleWheelsDynData::getWheelRotationAngle(const PxU32 wheelIdx) const
{
PX_CHECK_AND_RETURN_VAL(wheelIdx < mNbActiveWheels, "PxVehicleWheelsDynData::getWheelRotationAngle - Illegal wheel", 0.0f);
const PxVehicleWheels4DynData& suspWheelTire4=mWheels4DynData[(wheelIdx>>2)];
return suspWheelTire4.mWheelRotationAngles[wheelIdx & 3];
}
#if PX_CHECKED
bool legalNumHits(const PxU32* nbHits, const PxU32 nbWheels)
{
for(PxU32 i = 0; i < nbWheels; i++)
{
if(nbHits[i] !=0 && nbHits[i] != 1)
return false;
}
return true;
}
bool legalHitPlanes(const PxPlane* hitPlanes, const PxU32 nbWheels)
{
for (PxU32 i = 0; i < nbWheels; i++)
{
if(PxAbs(1.0f - hitPlanes[i].n.magnitude()) >= 1e-3f)
return false;
}
return true;
}
bool legalHitFrictions(const PxReal* hitFrictions, const PxU32 nbWheels)
{
for (PxU32 i = 0; i < nbWheels; i++)
{
if(hitFrictions[i] < 0.0f)
return false;
}
return true;
}
#endif
void PxVehicleWheelsDynData::setTireContacts(const PxU32* nbHits, const PxPlane* hitPlanes, const PxReal* hitFrictions, const PxTireContactIntersectionMethod::Enum* queryTypes, const PxU32 nbWheels)
{
PX_CHECK_AND_RETURN(nbWheels <= PX_MAX_NB_WHEELS, "PxVehicleWheelsDynData::setTireContacts - nbWheels must be <= PX_MAX_NB_WHEELS");
PX_CHECK_AND_RETURN(nbWheels >= mNbActiveWheels, "PxVehicleWheelsDynData::setTireContacts - nbWheels must be >= nbWheels");
PX_CHECK_AND_RETURN(legalNumHits(nbHits, nbWheels), "PxVehicleWheelsDynData::setTireContacts - nbHits[i] must be 0 or 1");
PX_CHECK_AND_RETURN(legalHitPlanes(hitPlanes, nbWheels), "PxVehicleWheelsDynData::setTireContacts - hitPlanes[i] must have a unit normal");
PX_CHECK_AND_RETURN(legalHitFrictions(hitFrictions, nbWheels), "PxVehicleWheelsDynData::setTireContacts - hitFrictions[i] must be >= 0.0f");
PxU32 hits[PX_MAX_NB_WHEELS];
PxPlane planes[PX_MAX_NB_WHEELS];
PxReal frictions[PX_MAX_NB_WHEELS];
PxTireContactIntersectionMethod types[PX_MAX_NB_WHEELS];
PxMemCopy(hits, nbHits, sizeof(PxU32)*nbWheels);
PxMemCopy(planes, hitPlanes, sizeof(PxPlane)*nbWheels);
PxMemCopy(frictions, hitFrictions, sizeof(PxReal)*nbWheels);
PxMemCopy(types, queryTypes, sizeof(PxTireContactIntersectionMethod)*nbWheels);
for (PxU32 i = 0; i < mNbWheels4; i++)
{
mWheels4DynData[i].setTireContacts(hits + 4 * i, planes + 4 * i, frictions + 4 * i, queryTypes + 4 * i);
}
}
void PxVehicleWheels::setToRestState()
{
//Set the rigid body to rest and clear all the accumulated forces and impulses.
if(!(mActor->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC))
{
mActor->setLinearVelocity(PxVec3(0,0,0));
mActor->setAngularVelocity(PxVec3(0,0,0));
//Support case where actor is not in a scene and constraints get solved via immediate mode
if (mActor->getScene())
{
mActor->clearForce(PxForceMode::eACCELERATION);
mActor->clearForce(PxForceMode::eVELOCITY_CHANGE);
mActor->clearTorque(PxForceMode::eACCELERATION);
mActor->clearTorque(PxForceMode::eVELOCITY_CHANGE);
}
}
//Set the wheels to rest state.
mWheelsDynData.setToRestState();
}
bool PxVehicleWheels::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mWheelsSimData.isValid(), "invalid mWheelsSimData", false);
PX_CHECK_AND_RETURN_VAL(mWheelsDynData.isValid(), "invalid mWheelsDynData", false);
return true;
}
PxU32 PxVehicleWheels::computeByteSize(const PxU32 numWheels)
{
const PxU32 byteSize =
PxVehicleWheelsSimData::computeByteSize(numWheels) +
PxVehicleWheelsDynData::computeByteSize(numWheels);
return byteSize;
}
PxU8* PxVehicleWheels::patchupPointers(const PxU32 numWheels, PxVehicleWheels* vehWheels, PxU8* ptrIn)
{
PxU8* ptr = ptrIn;
ptr = PxVehicleWheelsSimData::patchUpPointers(numWheels, &vehWheels->mWheelsSimData, ptr);
ptr = PxVehicleWheelsDynData::patchUpPointers(numWheels, &vehWheels->mWheelsDynData, ptr);
PX_ASSERT((ptrIn + computeByteSize(numWheels)) == ptr);
return ptr;
}
void PxVehicleWheels::init(const PxU32 numWheels)
{
PX_PLACEMENT_NEW(&mWheelsSimData, PxVehicleWheelsSimData(numWheels));
PX_PLACEMENT_NEW(&mWheelsDynData, PxVehicleWheelsDynData(numWheels));
for(PxU32 i = 0; i < mWheelsSimData.mNbWheels4; i++)
{
PX_PLACEMENT_NEW(&mWheelsDynData.mWheels4DynData[i].getVehicletConstraintShader(), PxVehicleConstraintShader(this));
}
mOnConstraintReleaseCounter = PxTo8(mWheelsSimData.mNbWheels4);
}
void PxVehicleWheels::free()
{
PX_CHECK_AND_RETURN(mWheelsSimData.mNbWheels4>0, "Cars with zero wheels are illegal");
const PxU32 numSuspWheelTire4 = mWheelsSimData.mNbWheels4;
for(PxU32 i=0;i<numSuspWheelTire4;i++)
{
mWheelsDynData.mWheels4DynData[i].getVehicletConstraintShader().release();
}
}
void PxVehicleWheels::onConstraintRelease()
{
mOnConstraintReleaseCounter--;
if (0 == mOnConstraintReleaseCounter)
{
PX_FREE_THIS;
}
}
static PxConstraintShaderTable table =
{
PxVehicleConstraintShader::vehicleSuspLimitConstraintSolverPrep,
PxVehicleConstraintShader::visualiseConstraint,
PxConstraintFlag::Enum(0)
};
void PxVehicleWheels::setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData,
const PxU32 numDrivenWheels, const PxU32 numNonDrivenWheels)
{
mNbNonDrivenWheels = numNonDrivenWheels;
PX_CHECK_AND_RETURN(wheelsData.getNbWheels() == mWheelsSimData.getNbWheels(), "PxVehicleWheels::setup - vehicle must be setup with same number of wheels as wheelsData");
PX_CHECK_AND_RETURN(vehActor, "PxVehicleWheels::setup - vehActor is null ptr : you need to instantiate an empty PxRigidDynamic for the vehicle");
PX_CHECK_AND_RETURN(wheelsData.isValid(), "PxVehicleWheels::setup -invalid wheelsData");
PX_UNUSED(numDrivenWheels);
#if PX_CHECKED
if (!(wheelsData.mFlags & PxVehicleWheelsSimFlag::eDISABLE_SPRUNG_MASS_SUM_CHECK))
{
PxF32 totalSprungMass=0.0f;
for(PxU32 i=0;i<(numDrivenWheels+numNonDrivenWheels);i++)
{
totalSprungMass+=wheelsData.getSuspensionData(i).mSprungMass;
}
PX_CHECK_MSG(PxAbs((vehActor->getMass()-totalSprungMass)/vehActor->getMass()) < 0.01f, "Sum of suspension sprung masses doesn't match actor mass");
}
#endif
//Copy the simulation data.
mWheelsSimData=wheelsData;
//Set the actor pointer.
mActor=vehActor;
//Set all the sq result ptrs to null.
const PxU32 numSuspWheelTire4=wheelsData.mNbWheels4;
for(PxU32 i=0;i<numSuspWheelTire4;i++)
{
mWheelsDynData.mWheels4DynData[i].mRaycastResults=NULL;
mWheelsDynData.mWheels4DynData[i].mSweepResults=NULL;
}
//Set up the suspension limits constraints.
for(PxU32 i=0;i<numSuspWheelTire4;i++)
{
PxVehicleConstraintShader& shader=mWheelsDynData.mWheels4DynData[i].getVehicletConstraintShader();
for(PxU32 j=0;j<4;j++)
{
shader.mData.mSuspLimitData.mCMOffsets[j]=wheelsData.mWheels4SimData[i].getSuspForceAppPointOffset(j);
shader.mData.mSuspLimitData.mDirs[j]=wheelsData.mWheels4SimData[i].getSuspTravelDirection(j);
shader.mData.mSuspLimitData.mErrors[j]=0.0f;
shader.mData.mSuspLimitData.mActiveFlags[j]=false;
shader.mData.mStickyTireForwardData.mCMOffsets[j]=PxVec3(0,0,0);
shader.mData.mStickyTireForwardData.mDirs[j]=PxVec3(0,0,0);
shader.mData.mStickyTireForwardData.mTargetSpeeds[j]=0.0f;
shader.mData.mStickyTireForwardData.mActiveFlags[j]=false;
shader.mData.mStickyTireSideData.mCMOffsets[j]=PxVec3(0,0,0);
shader.mData.mStickyTireSideData.mDirs[j]=PxVec3(0,0,0);
shader.mData.mStickyTireSideData.mTargetSpeeds[j]=0.0f;
shader.mData.mStickyTireSideData.mActiveFlags[j]=false;
}
shader.mConstraint=physics->createConstraint(vehActor, NULL, shader, table, sizeof(PxVehicleConstraintShader::VehicleConstraintData));
shader.mConstraint->markDirty();
}
//Set up the shader data ptrs.
for(PxU32 i=0;i<wheelsData.mNbActiveWheels;i++)
{
mWheelsDynData.setTireForceShaderData(i,&mWheelsSimData.getTireData(i));
}
//Disable the unused wheels.
for(PxU32 i=wheelsData.mNbActiveWheels;i<4*mWheelsSimData.mNbWheels4;i++)
{
mWheelsSimData.disableWheel(i);
}
//Pose the wheels that are mapped to shapes so that all shapes are at the rest pose.
for(PxU32 i=0;i<wheelsData.mNbActiveWheels;i++)
{
const PxI32 shapeId = mWheelsSimData.getWheelShapeMapping(i);
if(-1!=shapeId)
{
PX_CHECK_AND_RETURN(PxU32(shapeId) < mActor->getNbShapes(), "Illegal wheel shape mapping, shape does not exist on actor");
//Compute the shape local pose
const PxTransform chassisCMOffset=mActor->getCMassLocalPose();
PxTransform wheelOffset=chassisCMOffset;
wheelOffset.p+=mWheelsSimData.getWheelCentreOffset(i);
//Pose the shape.
PxShape* shapeBuffer[1];
mActor->getShapes(shapeBuffer,1,PxU32(shapeId));
shapeBuffer[0]->setLocalPose(wheelOffset);
}
}
}
void PxVehicleWheels::requiresObjects(PxProcessPxBaseCallback& c)
{
c.process(*mActor);
for(PxU32 i=0;i<mWheelsSimData.mNbWheels4;i++)
{
c.process(*mWheelsDynData.mWheels4DynData[i].getVehicletConstraintShader().getPxConstraint());
}
}
static PxConstraint* resolveConstraintPtr(PxDeserializationContext& context,
PxConstraint* old,
PxConstraintConnector* connector,
PxConstraintShaderTable &shaders)
{
context.translatePxBase(old);
PxConstraint* new_nx = static_cast<PxConstraint*>(old);
new_nx->setConstraintFunctions(*connector, shaders);
return new_nx;
}
void PxVehicleWheels::resolveReferences(PxDeserializationContext& context)
{
context.translatePxBase(mActor);
for(PxU32 i=0;i<mWheelsSimData.mNbWheels4;i++)
{
PxVehicleConstraintShader& shader=mWheelsDynData.mWheels4DynData[i].getVehicletConstraintShader();
shader.setPxConstraint(resolveConstraintPtr(context,shader.getPxConstraint(), shader.getConnector(), table));
}
//Set up the shader data ptrs.
for(PxU32 i=0;i<mWheelsSimData.mNbActiveWheels;i++)
{
mWheelsDynData.setTireForceShaderData(i,&mWheelsSimData.getTireData(i));
}
}
PxReal PxVehicleWheels::computeForwardSpeed(const PxVec3& forwardAxis) const
{
const PxTransform vehicleChassisTrnsfm=mActor->getGlobalPose().transform(mActor->getCMassLocalPose());
return mActor->getLinearVelocity().dot(vehicleChassisTrnsfm.q.rotate(forwardAxis));
}
PxReal PxVehicleWheels::computeSidewaysSpeed(const PxVec3& sideAxis) const
{
const PxTransform vehicleChassisTrnsfm=mActor->getGlobalPose().transform(mActor->getCMassLocalPose());
return mActor->getLinearVelocity().dot(vehicleChassisTrnsfm.q.rotate(sideAxis));
}
////////////////////////////////////////////////////////////////////////////
void PxVehicleWheelsDynData::setUserData(const PxU32 tireIdx, void* userData)
{
PX_CHECK_AND_RETURN(tireIdx < mNbActiveWheels, "PxVehicleWheelsDynData::setUserData - Illegal wheel");
mUserDatas[tireIdx]=userData;
}
void* PxVehicleWheelsDynData::getUserData(const PxU32 tireIdx) const
{
PX_CHECK_AND_RETURN_VAL(tireIdx < mNbActiveWheels, "PxVehicleWheelsDynData::setUserData - Illegal wheel", NULL);
return mUserDatas[tireIdx];
}
////////////////////////////////////////////////////////////////////////////
void PxVehicleWheelsDynData::copy(const PxVehicleWheelsDynData& src, const PxU32 srcWheel, const PxU32 trgWheel)
{
PX_CHECK_AND_RETURN(srcWheel < src.mNbActiveWheels, "PxVehicleWheelsDynData::copy - Illegal src wheel");
PX_CHECK_AND_RETURN(trgWheel < mNbActiveWheels, "PxVehicleWheelsDynData::copy - Illegal trg wheel");
const PxVehicleWheels4DynData& src4 = src.mWheels4DynData[(srcWheel>>2)];
PxVehicleWheels4DynData& trg4 = mWheels4DynData[(trgWheel>>2)];
trg4.mWheelSpeeds[trgWheel & 3] = src4.mWheelSpeeds[srcWheel & 3];
trg4.mCorrectedWheelSpeeds[trgWheel & 3] = src4.mCorrectedWheelSpeeds[srcWheel & 3];
trg4.mTireLowForwardSpeedTimers[trgWheel & 3] = src4.mTireLowForwardSpeedTimers[srcWheel & 3];
trg4.mTireLowSideSpeedTimers[trgWheel & 3] = src4.mTireLowSideSpeedTimers[srcWheel & 3];
trg4.mWheelRotationAngles[trgWheel & 3] = src4.mWheelRotationAngles[srcWheel & 3];
if(src4.mRaycastResults)
{
const PxVehicleWheels4DynData::SuspLineRaycast& suspLineRaycastSrc = reinterpret_cast<const PxVehicleWheels4DynData::SuspLineRaycast&>(src4.mQueryOrCachedHitResults);
PxVehicleWheels4DynData::SuspLineRaycast& suspLineRaycastTrg = reinterpret_cast<PxVehicleWheels4DynData::SuspLineRaycast&>(trg4.mQueryOrCachedHitResults);
suspLineRaycastTrg.mStarts[trgWheel & 3] = suspLineRaycastSrc.mStarts[srcWheel & 3];
suspLineRaycastTrg.mDirs[trgWheel & 3] = suspLineRaycastSrc.mDirs[srcWheel & 3];
suspLineRaycastTrg.mLengths[trgWheel & 3] = suspLineRaycastSrc.mLengths[srcWheel & 3];
}
else if(src4.mSweepResults)
{
const PxVehicleWheels4DynData::SuspLineSweep& suspLineSweepSrc = reinterpret_cast<const PxVehicleWheels4DynData::SuspLineSweep&>(src4.mQueryOrCachedHitResults);
PxVehicleWheels4DynData::SuspLineSweep& suspLineSweepTrg = reinterpret_cast<PxVehicleWheels4DynData::SuspLineSweep&>(trg4.mQueryOrCachedHitResults);
suspLineSweepTrg.mStartPose[trgWheel & 3] = suspLineSweepSrc.mStartPose[srcWheel & 3];
suspLineSweepTrg.mDirs[trgWheel & 3] = suspLineSweepSrc.mDirs[srcWheel & 3];
suspLineSweepTrg.mLengths[trgWheel & 3] = suspLineSweepSrc.mLengths[srcWheel & 3];
}
else
{
const PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult& cachedHitResultSrc = reinterpret_cast<const PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult&>(src4.mQueryOrCachedHitResults);
PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult& cachedHitResultTrg = reinterpret_cast<PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult&>(trg4.mQueryOrCachedHitResults);
cachedHitResultTrg.mPlanes[trgWheel & 3] = cachedHitResultSrc.mPlanes[srcWheel & 3];
cachedHitResultTrg.mFrictionMultipliers[trgWheel & 3] = cachedHitResultSrc.mFrictionMultipliers[srcWheel & 3];
cachedHitResultTrg.mCounts[trgWheel & 3] = cachedHitResultSrc.mCounts[srcWheel & 3];
cachedHitResultTrg.mDistances[trgWheel & 3] = cachedHitResultSrc.mDistances[srcWheel & 3];
}
}
PxU32 PxVehicleWheelsDynData::getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex) const
{
const PxU32 remainder = PxU32(PxMax<PxI32>(PxI32(mNbWheels4 - startIndex), 0));
const PxU32 writeCount = PxMin(remainder, bufferSize);
PxVehicleWheels4DynData* wheels4DynData = mWheels4DynData + startIndex;
for (PxU32 i = 0; i < writeCount; i++)
{
userBuffer[i] = wheels4DynData->getVehicletConstraintShader().getPxConstraint();
wheels4DynData++;
}
return writeCount;
}
} //namespace physx
| 35,627 |
C++
| 36.542676 | 206 | 0.777023 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleMetaData.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "common/PxMetaData.h"
#include "vehicle/PxVehicleComponents.h"
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveNW.h"
#include "vehicle/PxVehicleDriveTank.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "foundation/PxAllocator.h"
using namespace physx;
namespace
{
typedef PxFixedSizeLookupTable<PxVehicleEngineData::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES> PxVehicleEngineTable;
class ShadowLookupTable : public PxVehicleEngineTable
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowLookupTable)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream_, PxVehicleEngineTable, PxReal, mDataPairs, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, PxVehicleEngineTable, PxU32, mNbDataPairs, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream_, PxVehicleEngineTable, PxU32, mPad, PxMetaDataFlag::ePADDING)
}
};
}
static void getBinaryMetaData_PxFixedSizeLookupTable(PxOutputStream& stream)
{
ShadowLookupTable::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxFixedSizeLookupTable<PxVehicleEngineData::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>, ShadowLookupTable)
}
void PxVehicleDriveSimData::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_PxFixedSizeLookupTable(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxVehicleClutchAccuracyMode::Enum, PxU32)
//PxVehicleEngineData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleEngineData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, ShadowLookupTable, mTorqueCurve, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mMOI, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mPeakTorque, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mMaxOmega, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mDampingRateFullThrottle, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mDampingRateZeroThrottleClutchEngaged, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mDampingRateZeroThrottleClutchDisengaged, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mRecipMOI, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleEngineData, PxReal, mRecipMaxOmega, 0)
//PxVehicleGearsData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleGearsData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleGearsData, PxReal, mRatios, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleGearsData, PxReal, mFinalRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleGearsData, PxU32, mNbRatios, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleGearsData, PxReal, mSwitchTime, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleGearsData, PxReal, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleClutchData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleClutchData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleClutchData, PxReal, mStrength, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleClutchData, PxVehicleClutchAccuracyMode::Enum, mAccuracyMode, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleClutchData, PxU32, mEstimateIterations, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleClutchData, PxU8, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleAutoBoxData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleAutoBoxData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleAutoBoxData, PxReal, mUpRatios, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleAutoBoxData, PxReal, mDownRatios, 0)
//PxVehicleDriveSimData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleDriveSimData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveSimData, PxVehicleEngineData, mEngine, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveSimData, PxVehicleGearsData, mGears, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveSimData, PxVehicleClutchData, mClutch, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveSimData, PxVehicleAutoBoxData, mAutoBox, 0)
}
void PxVehicleDrive::getBinaryMetaData(PxOutputStream& stream)
{
//PxVehicleDriveDynData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleDriveDynData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleDriveDynData, PxReal, mControlAnalogVals, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, bool, mUseAutoGears, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, bool, mGearUpPressed, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, bool, mGearDownPressed, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, PxU32, mCurrentGear, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, PxU32, mTargetGear, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, PxReal, mEnginespeed, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, PxReal, mGearSwitchTime, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveDynData, PxReal, mAutoBoxSwitchTime, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleDriveDynData, PxU32, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleDrive
PX_DEF_BIN_METADATA_VCLASS(stream, PxVehicleDrive)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleDrive, PxVehicleWheels)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDrive, PxVehicleDriveDynData, mDriveDynData, 0)
}
void PxVehicleDriveSimData4W::getBinaryMetaData(PxOutputStream& stream)
{
//PxVehicleDifferential4WData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleDifferential4WData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferential4WData, PxReal, mFrontRearSplit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferential4WData, PxReal, mFrontLeftRightSplit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferential4WData, PxReal, mRearLeftRightSplit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferential4WData, PxReal, mCentreBias, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferential4WData, PxReal, mFrontBias, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferential4WData, PxReal, mRearBias, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferential4WData, PxU32, mType, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleDifferential4WData, PxReal, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleAckermannGeometryData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleAckermannGeometryData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleAckermannGeometryData, PxReal, mAccuracy, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleAckermannGeometryData, PxReal, mFrontWidth, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleAckermannGeometryData, PxReal, mRearWidth, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleAckermannGeometryData, PxReal, mAxleSeparation, 0)
//PxVehicleDriveSimData4W
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleDriveSimData4W)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleDriveSimData4W, PxVehicleDriveSimData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveSimData4W, PxVehicleDifferential4WData, mDiff, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveSimData4W, PxVehicleAckermannGeometryData, mAckermannGeometry, 0)
}
void PxVehicleDriveSimDataNW::getBinaryMetaData(PxOutputStream& stream)
{
//PxVehicleDifferentialWData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleDifferentialNWData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleDifferentialNWData, PxU32, mBitmapBuffer, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferentialNWData, PxU32, mNbDrivenWheels, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferentialNWData, PxReal, mInvNbDrivenWheels, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDifferentialNWData, PxU32, mPad, 0)
//PxVehicleDriveSimDataNW
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleDriveSimDataNW)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleDriveSimDataNW, PxVehicleDriveSimData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveSimDataNW, PxVehicleDifferentialNWData, mDiff, 0)
}
void PxVehicleNoDrive::getBinaryMetaData(PxOutputStream& stream)
{
PxVehicleDrive::getBinaryMetaData(stream);
PxVehicleWheels::getBinaryMetaData(stream);
PxVehicleDriveSimData::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, PxVehicleNoDrive)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleNoDrive, PxVehicleWheels)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleNoDrive, PxReal, mSteerAngles, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleNoDrive, PxReal, mDriveTorques, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleNoDrive, PxReal, mBrakeTorques, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleNoDrive, PxU32, mPad, PxMetaDataFlag::ePADDING)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mSteerAngles, mWheelsSimData.mNbWheels4, 0, PX_SERIAL_ALIGN)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mSteerAngles, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mSteerAngles, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mSteerAngles, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mDriveTorques, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mDriveTorques, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mDriveTorques, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mDriveTorques, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mBrakeTorques, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mBrakeTorques, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mBrakeTorques, mWheelsSimData.mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleNoDrive, PxReal, mBrakeTorques, mWheelsSimData.mNbWheels4, 0, 0)
}
void PxVehicleNoDrive::exportExtraData(PxSerializationContext& stream)
{
PxVehicleWheels::exportExtraData(stream);
PxU32 size = sizeof(PxReal)*4*mWheelsSimData.mNbWheels4;
stream.alignData();
stream.writeData(mSteerAngles, size);
stream.writeData(mDriveTorques, size);
stream.writeData(mBrakeTorques, size);
}
void PxVehicleNoDrive::importExtraData(PxDeserializationContext& context)
{
PxVehicleWheels::importExtraData(context);
context.alignExtraData();
mSteerAngles = context.readExtraData<PxReal>(4*mWheelsSimData.mNbWheels4);
mDriveTorques = context.readExtraData<PxReal>(4*mWheelsSimData.mNbWheels4);
mBrakeTorques = context.readExtraData<PxReal>(4*mWheelsSimData.mNbWheels4);
}
PxVehicleNoDrive* PxVehicleNoDrive::createObject(PxU8*& address, PxDeserializationContext& context)
{
PxVehicleNoDrive* obj = PX_PLACEMENT_NEW(address, PxVehicleNoDrive(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(PxVehicleNoDrive);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
void PxVehicleDrive4W::getBinaryMetaData(PxOutputStream& stream)
{
PxVehicleDrive::getBinaryMetaData(stream);
PxVehicleWheels::getBinaryMetaData(stream);
PxVehicleDriveSimData::getBinaryMetaData(stream);
PxVehicleDriveSimData4W::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, PxVehicleDrive4W)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleDrive4W, PxVehicleDrive)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDrive4W, PxVehicleDriveSimData4W, mDriveSimData, 0)
}
PxVehicleDrive4W* PxVehicleDrive4W::createObject(PxU8*& address, PxDeserializationContext& context)
{
PxVehicleDrive4W* obj = PX_PLACEMENT_NEW(address, PxVehicleDrive4W(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(PxVehicleDrive4W);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
void PxVehicleDriveNW::getBinaryMetaData(PxOutputStream& stream)
{
PxVehicleDriveSimDataNW::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, PxVehicleDriveNW)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleDriveNW, PxVehicleDrive)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveNW, PxVehicleDriveSimDataNW, mDriveSimData, 0)
}
PxVehicleDriveNW* PxVehicleDriveNW::createObject(PxU8*& address, PxDeserializationContext& context)
{
PxVehicleDriveNW* obj = PX_PLACEMENT_NEW(address, PxVehicleDriveNW(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(PxVehicleDriveNW);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
void PxVehicleDriveTank::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_VCLASS(stream, PxVehicleDriveTank)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleDriveTank, PxVehicleDrive)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveTank, PxVehicleDriveSimData, mDriveSimData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleDriveTank, PxU32, mDriveModel, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleDriveTank, PxU32, mPad, PxMetaDataFlag::ePADDING)
}
PxVehicleDriveTank* PxVehicleDriveTank::createObject(PxU8*& address, PxDeserializationContext& context)
{
PxVehicleDriveTank* obj = PX_PLACEMENT_NEW(address, PxVehicleDriveTank(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(PxVehicleDriveTank);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
void PxVehicleWheelsSimData::getBinaryMetaData(PxOutputStream& stream)
{
PxVehicleWheels4SimData::getBinaryMetaData(stream);
//PxVehicleTireLoadFilterData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleTireLoadFilterData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireLoadFilterData, PxReal, mMinNormalisedLoad, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireLoadFilterData, PxReal, mMinFilteredNormalisedLoad, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireLoadFilterData, PxReal, mMaxNormalisedLoad, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireLoadFilterData, PxReal, mMaxFilteredNormalisedLoad, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireLoadFilterData, PxReal, mDenominator, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleTireLoadFilterData, PxU32, mPad, PxMetaDataFlag::ePADDING)
//Add anti-roll here to save us having to add an extra function.
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleAntiRollBarData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleAntiRollBarData, PxU32, mWheel0, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleAntiRollBarData, PxU32, mWheel1, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleAntiRollBarData, PxReal, mStiffness, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleAntiRollBarData, PxU32, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleWheelsSimData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleWheelsSimData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxVehicleTireLoadFilterData, mNormalisedLoadFilter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxVehicleWheels4SimData, mWheels4SimData, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mNbWheels4, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mNbActiveWheels, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxVehicleAntiRollBarData, mAntiRollBars, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mNbAntiRollBars4, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mNbActiveAntiRollBars, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mActiveWheelsBitmapBuffer, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxReal, mThresholdLongitudinalSpeed, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mLowForwardSpeedSubStepCount, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mHighForwardSpeedSubStepCount, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mMinLongSlipDenominator, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsSimData, PxU32, mFlags, 0)
#if PX_P64_FAMILY
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheelsSimData, PxU32, mPad, PxMetaDataFlag::ePADDING)
#endif
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsSimData, PxVehicleWheels4SimData, mWheels4SimData, mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsSimData, PxVehicleAntiRollBarData, mAntiRollBars, mNbAntiRollBars4, 0, 0)
}
void PxVehicleWheelsDynData::getBinaryMetaData(PxOutputStream& stream)
{
PxVehicleWheels4DynData::getBinaryMetaData(stream);
PxVehicleConstraintShader::getBinaryMetaData(stream);
//PxVehicleTireForceCalculator
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleTireForceCalculator)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireForceCalculator, void*, mShaderData, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireForceCalculator, PxU32, mShader, PxMetaDataFlag::ePTR)
#if !PX_P64_FAMILY
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleTireForceCalculator, PxU32, mPad, PxMetaDataFlag::ePADDING)
#endif
//PxVehicleWheelsDynData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleWheelsDynData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsDynData, PxVehicleWheels4DynData, mWheels4DynData, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsDynData, PxVehicleTireForceCalculator, mTireForceCalculators, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsDynData, PxU32, mUserDatas, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsDynData, PxU32, mNbWheels4, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelsDynData, PxU32, mNbActiveWheels, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheelsDynData, PxU32, mPad, PxMetaDataFlag::ePADDING)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, PxVehicleWheels4DynData, mWheels4DynData, mNbWheels4, 0, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, PxVehicleWheelsDynData, PxVehicleTireForceCalculator, mTireForceCalculators, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mTireForceCalculators, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mTireForceCalculators, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mTireForceCalculators, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mTireForceCalculators, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mUserDatas, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mUserDatas, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mUserDatas, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, void, mUserDatas, mNbWheels4, PxMetaDataFlag::ePTR, 0)
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PxVehicleWheelsDynData, PxVehicleConstraintShader, mWheels4DynData, mNbWheels4, 0, 0)
}
void PxVehicleWheels::exportExtraData(PxSerializationContext& stream)
{
PxU32 size = computeByteSize(mWheelsSimData.mNbActiveWheels);
stream.alignData();
stream.writeData(mWheelsSimData.mWheels4SimData, size);
}
void PxVehicleWheels::importExtraData(PxDeserializationContext& context)
{
PxU32 size = computeByteSize(mWheelsSimData.mNbActiveWheels);
PxU8* ptr = context.readExtraData<PxU8, PX_SERIAL_ALIGN>(size);
patchupPointers(mWheelsSimData.mNbActiveWheels, this, ptr);
}
void PxVehicleWheels::getBinaryMetaData(PxOutputStream& stream)
{
PxVehicleWheelsSimData::getBinaryMetaData(stream);
PxVehicleWheelsDynData::getBinaryMetaData(stream);
//PxVehicleWheels
PX_DEF_BIN_METADATA_VCLASS(stream, PxVehicleWheels)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleWheels, PxBase)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels, PxVehicleWheelsSimData, mWheelsSimData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels, PxVehicleWheelsDynData, mWheelsDynData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels, PxRigidDynamic, mActor, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels, PxU32, mNbNonDrivenWheels, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels, PxU8, mOnConstraintReleaseCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels, PxU8, mType, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels, PxU8, mPad0, PxMetaDataFlag::ePADDING)
}
void PxVehicleConstraintShader::getBinaryMetaData(PxOutputStream& stream)
{
//SuspLimitConstraintData
PX_DEF_BIN_METADATA_CLASS(stream, SuspLimitConstraintData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, SuspLimitConstraintData, PxVec3, mCMOffsets, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, SuspLimitConstraintData, PxVec3, mDirs, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, SuspLimitConstraintData, PxReal, mErrors, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, SuspLimitConstraintData, bool, mActiveFlags, 0)
//StickyTireConstraintData
PX_DEF_BIN_METADATA_CLASS(stream, StickyTireConstraintData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, StickyTireConstraintData, PxVec3, mCMOffsets, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, StickyTireConstraintData, PxVec3, mDirs, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, StickyTireConstraintData, PxReal, mTargetSpeeds, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, StickyTireConstraintData, bool, mActiveFlags, 0)
//VehicleConstraintData
PX_DEF_BIN_METADATA_CLASS(stream, VehicleConstraintData)
PX_DEF_BIN_METADATA_ITEM(stream, VehicleConstraintData, SuspLimitConstraintData, mSuspLimitData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, VehicleConstraintData, StickyTireConstraintData, mStickyTireForwardData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, VehicleConstraintData, StickyTireConstraintData, mStickyTireSideData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, VehicleConstraintData, PxQuat, mCMassRotation, 0)
//PxVehicleConstraintShader
PX_DEF_BIN_METADATA_VCLASS(stream, PxVehicleConstraintShader)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxVehicleConstraintShader, PxConstraintConnector)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleConstraintShader, VehicleConstraintData, mData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleConstraintShader, PxConstraint, mConstraint, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleConstraintShader, PxVehicleWheels, mVehicle, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleConstraintShader, PxU32, mPad, PxMetaDataFlag::ePADDING)
}
void PxVehicleWheels4SimData::getBinaryMetaData(PxOutputStream& stream)
{
//PxVehicleSuspensionData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleSuspensionData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mSpringStrength, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mSpringDamperRate, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mMaxCompression, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mMaxDroop, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mSprungMass, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mCamberAtRest, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mCamberAtMaxCompression, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mCamberAtMaxDroop, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mRecipMaxCompression, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleSuspensionData, PxReal, mRecipMaxDroop, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleSuspensionData, PxU32, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleWheelData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleWheelData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mRadius, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mWidth, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mMass, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mMOI, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mDampingRate, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mMaxBrakeTorque, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mMaxHandBrakeTorque, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mMaxSteer, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mToeAngle, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mRecipRadius, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheelData, PxReal, mRecipMOI, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheelData, PxReal, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleTireData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleTireData)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxReal, mLatStiffX, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxReal, mLatStiffY, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxReal, mLongitudinalStiffnessPerUnitGravity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxReal, mCamberStiffnessPerUnitGravity, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleTireData, PxReal, mFrictionVsSlipGraph, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxU32, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxReal, mRecipLongitudinalStiffnessPerUnitGravity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxReal, mFrictionVsSlipGraphRecipx1Minusx0, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleTireData, PxReal, mFrictionVsSlipGraphRecipx2Minusx1, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleTireData, PxReal, mPad, PxMetaDataFlag::ePADDING)
//PxVehicleWheels4SimData
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleWheels4SimData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxVehicleSuspensionData, mSuspensions, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxVehicleWheelData, mWheels, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxVehicleTireData, mTires, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxVec3, mSuspDownwardTravelDirections, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxVec3, mSuspForceAppPointOffsets, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxVec3, mTireForceAppPointOffsets, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxVec3, mWheelCentreOffsets, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxReal, mTireRestLoads, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxReal, mRecipTireRestLoads, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxFilterData, mSqFilterData, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxU8, mWheelShapeMap, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4SimData, PxU32, mPad, PxMetaDataFlag::ePADDING)
}
/*
void PxVehicleAntiRollBar::getBinaryMetaData(PxOutputStream& stream)
{
}
*/
void PxVehicleWheels4DynData::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxVehicleWheels4DynData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxReal, mWheelSpeeds, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxReal, mCorrectedWheelSpeeds, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxReal, mWheelRotationAngles, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxReal, mTireLowForwardSpeedTimers, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxReal, mTireLowSideSpeedTimers, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxU8, mQueryOrCachedHitResults, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxReal, mJounces, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxReal, mSteerAngles, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels4DynData, PxVehicleConstraintShader, mVehicleConstraints, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels4DynData, PxRaycastQueryResult, mRaycastResults, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels4DynData, PxSweepQueryResult, mSweepResults, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxVehicleWheels4DynData, bool, mHasCachedRaycastHitPlane, 0)
#if PX_P64_FAMILY
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PxVehicleWheels4DynData, PxU32, mPad, PxMetaDataFlag::ePADDING)
#endif
}
| 31,869 |
C++
| 57.692449 | 141 | 0.770059 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleComponents.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleComponents.h"
#include "foundation/PxBitMap.h"
namespace physx
{
bool PxVehicleChassisData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mMOI.x>0.0f && mMOI.y>0.0f && mMOI.z>0.0f, "Illegal PxVehicleChassisData.mMOI - each element of the chassis moi needs to non-zero", false);
PX_CHECK_AND_RETURN_VAL(mMass>0.0f, "Illegal PxVehicleChassisData.mMass - chassis mass needs to be non-zero", false);
return true;
}
bool PxVehicleEngineData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mPeakTorque>0.0f, "PxVehicleEngineData.mPeakTorque must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mMaxOmega>0.0f, "PxVehicleEngineData.mMaxOmega must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mDampingRateFullThrottle>0.0f, "PxVehicleEngineData.mDampingRateFullThrottle must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mDampingRateZeroThrottleClutchEngaged>0.0f, "PxVehicleEngineData.mDampingRateZeroThrottleClutchEngaged must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mDampingRateZeroThrottleClutchDisengaged>0.0f, "PxVehicleEngineData.mDampingRateZeroThrottleClutchDisengaged must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mRecipMOI>0.0f, "PxVehicleEngineData.mRecipMOI must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mRecipMaxOmega>0.0f, "PxVehicleEngineData.mRecipMaxOmega must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(PxAbs((1.0f/mMaxOmega)-mRecipMaxOmega) <= 0.001f, "PxVehicleEngineData.mMaxOmega and PxVehicleEngineData.mRecipMaxOmega don't match", false);
return true;
}
bool PxVehicleGearsData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mFinalRatio>0, "PxVehicleGearsData.mFinalRatio must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mNbRatios>=1, "PxVehicleGearsData.mNbRatios must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mSwitchTime>=0.0f, "PxVehicleGearsData.mSwitchTime must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mRatios[PxVehicleGearsData::eREVERSE]<0.0f, "PxVehicleGearsData.mRatios[PxVehicleGearsData::eREVERSE] must be less than zero", false);
PX_CHECK_AND_RETURN_VAL(mRatios[PxVehicleGearsData::eNEUTRAL]==0.0f, "PxVehicleGearsData.mRatios[PxVehicleGearsData::eNEUTRAL] must be zero", false);
for(PxU32 i=PxVehicleGearsData::eFIRST;i<mNbRatios;i++)
{
PX_CHECK_AND_RETURN_VAL(mRatios[i]>0.0f, "Forward gear ratios must be greater than zero", false);
}
for(PxU32 i=PxVehicleGearsData::eSECOND;i<mNbRatios;i++)
{
PX_CHECK_AND_RETURN_VAL(mRatios[i]<mRatios[i-1], "Forward gear ratios must be a descending sequence of gear ratios", false);
}
return true;
}
bool PxVehicleAutoBoxData::isValid() const
{
for(PxU32 i=0;i<PxVehicleGearsData::eGEARSRATIO_COUNT;i++)
{
PX_CHECK_AND_RETURN_VAL(mUpRatios[i]>=0.0f, "PxVehicleAutoBoxData.mUpRatios must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mDownRatios[i]>=0.0f, "PxVehicleAutoBoxData.mDownRatios must be greater than or equal to zero", false);
}
return true;
}
bool PxVehicleDifferential4WData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mFrontRearSplit<=1.0f && mFrontRearSplit>=0.0f, "PxVehicleDifferential4WData.mFrontRearSplit must be in range (0,1)", false);
PX_CHECK_AND_RETURN_VAL(mFrontLeftRightSplit<=1.0f && mFrontLeftRightSplit>=0.0f, "PxVehicleDifferential4WData.mFrontLeftRightSplit must be in range (0,1)", false);
PX_CHECK_AND_RETURN_VAL(mRearLeftRightSplit<=1.0f || mRearLeftRightSplit>=0.0f, "PxVehicleDifferential4WData.mRearLeftRightSplit must be in range (0,1)", false);
PX_CHECK_AND_RETURN_VAL(mCentreBias>=1.0f, "PxVehicleDifferential4WData.mCentreBias must be greater than or equal to 1.0f", false);
PX_CHECK_AND_RETURN_VAL(mFrontBias>=1.0f, "PxVehicleDifferential4WData.mFrontBias must be greater than or equal to 1.0f", false);
PX_CHECK_AND_RETURN_VAL(mRearBias>=1.0f, "PxVehicleDifferential4WData.mRearBias must be greater than or equal to 1.0f", false);
PX_CHECK_AND_RETURN_VAL(mType<PxVehicleDifferential4WData::eMAX_NB_DIFF_TYPES, "PxVehicleDifferential4WData.mType has illegal value", false);
return true;
}
void PxVehicleDifferentialNWData::setDrivenWheel(const PxU32 wheelId, const bool drivenState)
{
PxBitMap bitmap;
bitmap.setWords(mBitmapBuffer,((PX_MAX_NB_WHEELS + 31) & ~31) >> 5);
PxU32 numDrivenWheels=mNbDrivenWheels;
if(drivenState)
{
if(!bitmap.test(wheelId))
{
numDrivenWheels++;
bitmap.set(wheelId);
mInvNbDrivenWheels=1.0f/(1.0f*numDrivenWheels);
}
}
else if(bitmap.test(wheelId))
{
numDrivenWheels--;
bitmap.reset(wheelId);
mInvNbDrivenWheels = numDrivenWheels>0.0f ? 1.0f/(1.0f*numDrivenWheels) : 0.0f;
}
mNbDrivenWheels=numDrivenWheels;
}
bool PxVehicleDifferentialNWData::getIsDrivenWheel(const PxU32 wheelId) const
{
PxBitMap bitmap;
bitmap.setWords(const_cast<PxU32*>(mBitmapBuffer),((PX_MAX_NB_WHEELS + 31) & ~31) >> 5);
return (bitmap.test(wheelId) ? true : false);
}
PxU32 PxVehicleDifferentialNWData::getDrivenWheelStatus() const
{
PX_ASSERT(((PX_MAX_NB_WHEELS + 31) & ~31) >> 5 == 1);
return mBitmapBuffer[0];
}
void PxVehicleDifferentialNWData::setDrivenWheelStatus(PxU32 status)
{
PX_ASSERT(((PX_MAX_NB_WHEELS + 31) & ~31) >> 5 == 1);
PxBitMap bitmap;
bitmap.setWords(&status, 1);
for(PxU32 i = 0; i < PX_MAX_NB_WHEELS; ++i)
{
setDrivenWheel(i, !!bitmap.test(i));
}
}
bool PxVehicleDifferentialNWData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mNbDrivenWheels<=PX_MAX_NB_WHEELS, "PxVehicleDifferentialNWData.mNbDrivenWheels must be in range (0,20)", false);
return true;
}
bool PxVehicleAckermannGeometryData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mAccuracy>=0.0f && mAccuracy<=1.0f, "PxVehicleAckermannGeometryData.mAccuracy must be in range (0,1)", false);
PX_CHECK_AND_RETURN_VAL(mFrontWidth>0.0f, "PxVehicleAckermannGeometryData.mFrontWidth must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mRearWidth>0.0f, "PxVehicleAckermannGeometryData.mRearWidth must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mAxleSeparation>0.0f, "PxVehicleAckermannGeometryData.mAxleSeparation must be greater than zero", false);
return true;
}
bool PxVehicleClutchData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mStrength>0, "PxVehicleClutchData.mStrength must be greater than zero", false);
return true;
}
bool PxVehicleTireLoadFilterData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mMaxNormalisedLoad>=mMinNormalisedLoad, "PxVehicleTireLoadFilterData.mMaxNormalisedLoad must be greater than or equal to PxVehicleTireLoadFilterData.mMinNormalisedLoad", false);
PX_CHECK_AND_RETURN_VAL(mMaxFilteredNormalisedLoad>0, "PxVehicleTireLoadFilterData.mMaxFilteredNormalisedLoad must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(PxAbs((1.0f/(mMaxNormalisedLoad - mMinNormalisedLoad)) - mDenominator) < 0.001f, "PxVehicleTireLoadFilterData.mMaxFilteredNormalisedLoad, PxVehicleTireLoadFilterData.mMinNormalisedLoad, and PxVehicleTireLoadFilterData.mDenominator don't match", false);
return true;
}
bool PxVehicleWheelData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mRadius>0.0f, "PxVehicleWheelData.mRadius must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mWidth>0.0f, "PxVehicleWheelData.mWidth must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mMass>0.0f, "PxVehicleWheelData.mMass must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mMOI>0.0f, "PxVehicleWheelData.mMOI must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mDampingRate>0.0f, "PxVehicleWheelData.mDampingRate must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(mMaxBrakeTorque>=0.0f, "PxVehicleWheelData.mMaxBrakeTorque must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mMaxHandBrakeTorque>=0.0f, "PxVehicleWheelData.mMaxHandBrakeTorque must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mToeAngle<=PxPi, "PxVehicleWheelData.mToeAngle must be less than Pi", false);
PX_CHECK_AND_RETURN_VAL(PxAbs((1.0f/mRadius) - mRecipRadius) < 0.001f, "PxVehicleWheelData.mRadius and PxVehicleWheelData.mRecipRadius don't match", false);
PX_CHECK_AND_RETURN_VAL(PxAbs((1.0f/mMOI) - mRecipMOI) < 0.001f, "PxVehicleWheelData.mMOI and PxVehicleWheelData.mRecipMOI don't match", false);
return true;
}
bool PxVehicleSuspensionData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mSpringStrength>=0.0f, "PxVehicleSuspensionData.mSpringStrength must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mSpringDamperRate>=0.0f, "PxVehicleSuspensionData.mSpringDamperRate must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mMaxCompression>=0.0f, "PxVehicleSuspensionData.mMaxCompression must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mMaxDroop>=0.0f, "PxVehicleSuspensionData.mMaxDroop must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(mSprungMass>=0.0f, "PxVehicleSuspensionData.mSprungMass must be greater than or equal to zero", false);
return true;
}
bool PxVehicleAntiRollBarData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(((mWheel0< PX_MAX_NB_WHEELS) && (mWheel1 < PX_MAX_NB_WHEELS)), "PxVehicleAntiRoll.mWheel0 and PxVehicleAntiRoll.mWheel1 are an illegal pair", false);
PX_CHECK_AND_RETURN_VAL((mWheel0 != mWheel1), "PxVehicleAntiRoll.mWheel0 == PxVehicleAntiRoll.mWheel1", false);
PX_CHECK_AND_RETURN_VAL(mStiffness>=0, "PxVehicleAntiRoll::mStiffness must be greater than or equal to zero", false);
return true;
}
bool PxVehicleTireData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mFrictionVsSlipGraph[0][0]>=0.0f && mFrictionVsSlipGraph[0][1]>=0.0f, "Illegal values for mFrictionVsSlipGraph[0]", false);
PX_CHECK_AND_RETURN_VAL(mFrictionVsSlipGraph[1][0]>=0.0f && mFrictionVsSlipGraph[1][1]>=0.0f, "Illegal values for mFrictionVsSlipGraph[1]", false);
PX_CHECK_AND_RETURN_VAL(mFrictionVsSlipGraph[2][0]>=0.0f && mFrictionVsSlipGraph[2][1]>=0.0f, "Illegal values for mFrictionVsSlipGraph[2]", false);
PX_CHECK_AND_RETURN_VAL(PxAbs((1.0f/(mFrictionVsSlipGraph[1][0]-mFrictionVsSlipGraph[0][0])) - mFrictionVsSlipGraphRecipx1Minusx0) < 0.001f, "PxVehicleTireData.mFrictionVsSlipGraphRecipx1Minusx0 not set up", false);
PX_CHECK_AND_RETURN_VAL(PxAbs((1.0f/(mFrictionVsSlipGraph[2][0]-mFrictionVsSlipGraph[1][0])) - mFrictionVsSlipGraphRecipx2Minusx1) < 0.001f, "PxVehicleTireData.mFrictionVsSlipGraphRecipx2Minusx1 not set up", false);
return true;
}
} //namespace physx
| 12,134 |
C++
| 54.410959 | 277 | 0.774848 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleNoDrive.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleWheels.h"
#include "PxRigidDynamic.h"
#include "CmUtils.h"
namespace physx
{
extern PxF32 gToleranceScaleLength;
bool PxVehicleNoDrive::isValid() const
{
PX_CHECK_AND_RETURN_VAL(PxVehicleWheels::isValid(), "invalid PxVehicleDrive", false);
return true;
}
PxVehicleNoDrive* PxVehicleNoDrive::allocate(const PxU32 numWheels)
{
PX_CHECK_AND_RETURN_NULL(numWheels>0, "Cars with zero wheels are illegal");
PX_CHECK_AND_RETURN_NULL(gToleranceScaleLength > 0, "PxVehicleNoDrive::allocate - need to call PxInitVehicleSDK");
//Compute the bytes needed.
const PxU32 numWheels4 = (((numWheels + 3) & ~3) >> 2);
const PxU32 inputByteSize16 = sizeof(PxReal)*numWheels4*4;
const PxU32 byteSize = sizeof(PxVehicleNoDrive) + 3*inputByteSize16 + PxVehicleWheels::computeByteSize(numWheels);
//Allocate the memory.
PxVehicleNoDrive* veh = static_cast<PxVehicleNoDrive*>(PX_ALLOC(byteSize, "PxVehicleNoDrive"));
PxMarkSerializedMemory(veh, byteSize);
PX_PLACEMENT_NEW(veh, PxVehicleNoDrive());
//Patch up the pointers.
PxU8* ptr = reinterpret_cast<PxU8*>(veh) + sizeof(PxVehicleNoDrive);
veh->mSteerAngles = reinterpret_cast<PxReal*>(ptr);
ptr += inputByteSize16;
veh->mDriveTorques = reinterpret_cast<PxReal*>(ptr);
ptr += inputByteSize16;
veh->mBrakeTorques = reinterpret_cast<PxReal*>(ptr);
ptr += inputByteSize16;
ptr = PxVehicleWheels::patchupPointers(numWheels, veh, ptr);
//Initialise.
PxMemZero(veh->mSteerAngles, inputByteSize16);
PxMemZero(veh->mDriveTorques, inputByteSize16);
PxMemZero(veh->mBrakeTorques, inputByteSize16);
veh->init(numWheels);
//Set the vehicle type.
veh->mType = PxVehicleTypes::eNODRIVE;
return veh;
}
void PxVehicleNoDrive::free()
{
PxVehicleWheels::free();
}
void PxVehicleNoDrive::setup
(PxPhysics* physics, PxRigidDynamic* vehActor, const PxVehicleWheelsSimData& wheelsData)
{
//Set up the wheels.
PxVehicleWheels::setup(physics,vehActor,wheelsData,0,wheelsData.getNbWheels());
}
PxVehicleNoDrive* PxVehicleNoDrive::create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData)
{
PxVehicleNoDrive* veh=PxVehicleNoDrive::allocate(wheelsData.getNbWheels());
veh->setup(physics,vehActor,wheelsData);
return veh;
}
void PxVehicleNoDrive::setToRestState()
{
const PxU32 numWheels4 = (((mWheelsSimData.getNbWheels() + 3) & ~3) >> 2);
const PxU32 inputByteSize = sizeof(PxReal)*numWheels4*4;
const PxU32 inputByteSize16 = (inputByteSize + 15) & ~15;
PxMemZero(mSteerAngles, 3*inputByteSize16);
//Set core to rest state.
PxVehicleWheels::setToRestState();
}
void PxVehicleNoDrive::setBrakeTorque(const PxU32 id, const PxReal brakeTorque)
{
PX_CHECK_AND_RETURN(id < mWheelsSimData.getNbWheels(), "PxVehicleNoDrive::setBrakeTorque - Illegal wheel");
PX_CHECK_AND_RETURN(brakeTorque>=0, "PxVehicleNoDrive::setBrakeTorque - negative brake torques are illegal");
mBrakeTorques[id] = brakeTorque;
}
void PxVehicleNoDrive::setDriveTorque(const PxU32 id, const PxReal driveTorque)
{
PX_CHECK_AND_RETURN(id < mWheelsSimData.getNbWheels(), "PxVehicleNoDrive::setDriveTorque - Illegal wheel");
mDriveTorques[id] = driveTorque;
}
void PxVehicleNoDrive::setSteerAngle(const PxU32 id, const PxReal steerAngle)
{
PX_CHECK_AND_RETURN(id < mWheelsSimData.getNbWheels(), "PxVehicleNoDrive::setSteerAngle - Illegal wheel");
mSteerAngles[id] = steerAngle;
}
PxReal PxVehicleNoDrive::getBrakeTorque(const PxU32 id) const
{
PX_CHECK_AND_RETURN_VAL(id < mWheelsSimData.getNbWheels(), "PxVehicleNoDrive::getBrakeTorque - Illegal wheel", 0);
return mBrakeTorques[id];
}
PxReal PxVehicleNoDrive::getDriveTorque(const PxU32 id) const
{
PX_CHECK_AND_RETURN_VAL(id < mWheelsSimData.getNbWheels(), "PxVehicleNoDrive::getDriveTorque - Illegal wheel",0);
return mDriveTorques[id];
}
PxReal PxVehicleNoDrive::getSteerAngle(const PxU32 id) const
{
PX_CHECK_AND_RETURN_VAL(id < mWheelsSimData.getNbWheels(), "PxVehicleNoDrive::getSteerAngle - Illegal wheel",0);
return mSteerAngles[id];
}
} //namespace physx
| 5,793 |
C++
| 36.623376 | 115 | 0.768514 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleDrive4W.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleSDK.h"
#include "PxRigidDynamic.h"
#include "PxShape.h"
#include "PxScene.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "foundation/PxUtilities.h"
#include "CmUtils.h"
namespace physx
{
extern PxF32 gToleranceScaleLength;
bool PxVehicleDriveSimData4W::isValid() const
{
PX_CHECK_AND_RETURN_VAL(PxVehicleDriveSimData::isValid(), "Invalid PxVehicleDriveSimData4W", false);
PX_CHECK_AND_RETURN_VAL(mDiff.isValid(), "Invalid PxVehicleCoreSimulationData.mDiff", false);
PX_CHECK_AND_RETURN_VAL(mAckermannGeometry.isValid(), "Invalid PxVehicleCoreSimulationData.mAckermannGeometry", false);
return true;
}
void PxVehicleDriveSimData4W::setDiffData(const PxVehicleDifferential4WData& diff)
{
PX_CHECK_AND_RETURN(diff.mType!=PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD || (diff.mFrontRearSplit>=0 && diff.mFrontRearSplit<=1.0f), "Diff torque split between front and rear must be in range (0,1)");
PX_CHECK_AND_RETURN(diff.mType!=PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD || (diff.mCentreBias>=1), "Diff centre bias must be greater than or equal to 1");
PX_CHECK_AND_RETURN((diff.mType!=PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD && diff.mType!=PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD) || (diff.mFrontBias>=1), "Diff front bias must be greater than or equal to 1");
PX_CHECK_AND_RETURN((diff.mType!=PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD && diff.mType!=PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD) || (diff.mRearBias>=1), "Diff rear bias must be greater than or equal to 1");
PX_CHECK_AND_RETURN(diff.mType<PxVehicleDifferential4WData::eMAX_NB_DIFF_TYPES, "Illegal differential type");
mDiff=diff;
}
void PxVehicleDriveSimData4W::setAckermannGeometryData(const PxVehicleAckermannGeometryData& ackermannData)
{
PX_CHECK_AND_RETURN(ackermannData.mFrontWidth > 0, "Illegal ackermannData.mFrontWidth - must be greater than zero");
PX_CHECK_AND_RETURN(ackermannData.mRearWidth > 0, "Illegal ackermannData.mRearWidth - must be greater than zero");
PX_CHECK_AND_RETURN(ackermannData.mAxleSeparation > 0, "Illegal ackermannData.mAxleSeparation - must be greater than zero");
mAckermannGeometry = ackermannData;
}
///////////////////////////////////
bool PxVehicleDrive4W::isValid() const
{
PX_CHECK_AND_RETURN_VAL(PxVehicleDrive::isValid(), "invalid PxVehicleDrive", false);
PX_CHECK_AND_RETURN_VAL(mDriveSimData.isValid(), "Invalid PxVehicleNW.mCoreSimData", false);
return true;
}
PxVehicleDrive4W* PxVehicleDrive4W::allocate(const PxU32 numWheels)
{
PX_CHECK_AND_RETURN_NULL(numWheels>=4, "PxVehicleDrive4W::allocate - needs to have at least 4 wheels");
PX_CHECK_AND_RETURN_NULL(gToleranceScaleLength > 0, "PxVehicleDrive4W::allocate - need to call PxInitVehicleSDK");
//Compute the bytes needed.
const PxU32 byteSize = sizeof(PxVehicleDrive4W) + PxVehicleDrive::computeByteSize(numWheels);
//Allocate the memory.
PxVehicleDrive4W* veh = static_cast<PxVehicleDrive4W*>(PX_ALLOC(byteSize, "PxVehicleDrive4W"));
PxMarkSerializedMemory(veh, byteSize);
PX_PLACEMENT_NEW(veh, PxVehicleDrive4W());
//Patch up the pointers.
PxU8* ptr = reinterpret_cast<PxU8*>(veh) + sizeof(PxVehicleDrive4W);
ptr=PxVehicleDrive::patchupPointers(numWheels, veh, ptr);
//Initialise wheels.
veh->init(numWheels);
//Set the vehicle type.
veh->mType = PxVehicleTypes::eDRIVE4W;
return veh;
}
void PxVehicleDrive4W::free()
{
PxVehicleDrive::free();
}
void PxVehicleDrive4W::setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData,
const PxU32 numNonDrivenWheels)
{
PX_CHECK_AND_RETURN(driveData.isValid(), "PxVehicleDrive4W::setup - invalid driveData");
PX_CHECK_AND_RETURN(wheelsData.getNbWheels() >= 4, "PxVehicleDrive4W::setup - needs to have at least 4 wheels");
//Set up the wheels.
PxVehicleDrive::setup(physics,vehActor,wheelsData,4,numNonDrivenWheels);
//Start setting up the drive.
PX_CHECK_MSG(driveData.isValid(), "PxVehicle4WDrive - invalid driveData");
//Copy the simulation data.
mDriveSimData = driveData;
}
PxVehicleDrive4W* PxVehicleDrive4W::create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData,
const PxU32 numNonDrivenWheels)
{
PxVehicleDrive4W* veh4W=PxVehicleDrive4W::allocate(4+numNonDrivenWheels);
veh4W->setup(physics,vehActor,wheelsData,driveData,numNonDrivenWheels);
return veh4W;
}
void PxVehicleDrive4W::setToRestState()
{
//Set core to rest state.
PxVehicleDrive::setToRestState();
}
} //namespace physx
| 6,418 |
C++
| 41.793333 | 227 | 0.774073 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/VehicleUtilSetup.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMath.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxErrors.h"
#include "vehicle/PxVehicleUtilSetup.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveNW.h"
#include "vehicle/PxVehicleDriveTank.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleUtil.h"
#include "vehicle/PxVehicleUpdate.h"
namespace physx
{
void enable3WMode(const PxU32 rightDirection, const PxU32 upDirection, const bool removeFrontWheel, PxVehicleWheelsSimData& wheelsSimData, PxVehicleWheelsDynData& wheelsDynData, PxVehicleDriveSimData4W& driveSimData);
void computeDirection(const PxVec3& up, const PxVec3& right, PxU32& rightDirection, PxU32& upDirection);
void PxVehicle4WEnable3WTadpoleMode(PxVehicleWheelsSimData& wheelsSimData, PxVehicleWheelsDynData& wheelsDynData, PxVehicleDriveSimData4W& driveSimData,
const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN
(!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eFRONT_LEFT) &&
!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT) &&
!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eREAR_LEFT) &&
!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eREAR_RIGHT), "PxVehicle4WEnable3WTadpoleMode requires no wheels to be disabled");
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicle4WEnable3WTadpoleMode: provided PxVehicleContext is not valid");
PxU32 rightDirection=0xffffffff;
PxU32 upDirection=0xffffffff;
computeDirection(context.upAxis, context.sideAxis, rightDirection, upDirection);
PX_CHECK_AND_RETURN(rightDirection<3 && upDirection<3, "PxVehicle4WEnable3WTadpoleMode requires the vectors set in PxVehicleSetBasisVectors to be axis-aligned");
enable3WMode(rightDirection, upDirection, false, wheelsSimData, wheelsDynData, driveSimData);
}
void PxVehicle4WEnable3WDeltaMode(PxVehicleWheelsSimData& wheelsSimData, PxVehicleWheelsDynData& wheelsDynData, PxVehicleDriveSimData4W& driveSimData,
const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN
(!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eFRONT_LEFT) &&
!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT) &&
!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eREAR_LEFT) &&
!wheelsSimData.getIsWheelDisabled(PxVehicleDrive4WWheelOrder::eREAR_RIGHT), "PxVehicle4WEnable3WDeltaMode requires no wheels to be disabled");
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicle4WEnable3WDeltaMode: provided PxVehicleContext is not valid");
PxU32 rightDirection=0xffffffff;
PxU32 upDirection=0xffffffff;
computeDirection(context.upAxis, context.sideAxis, rightDirection, upDirection);
PX_CHECK_AND_RETURN(rightDirection<3 && upDirection<3, "PxVehicle4WEnable3WTadpoleMode requires the vectors set in PxVehicleSetBasisVectors to be axis-aligned");
enable3WMode(rightDirection, upDirection, true, wheelsSimData, wheelsDynData, driveSimData);
}
void computeSprungMasses(const PxU32 numSprungMasses, const PxVec3* sprungMassCoordinates, const PxVec3& centreOfMass, const PxReal totalMass, const PxU32 gravityDirection, PxReal* sprungMasses);
void PxVehicleComputeSprungMasses(const PxU32 numSprungMasses, const PxVec3* sprungMassCoordinates, const PxVec3& centreOfMass, const PxReal totalMass, const PxU32 gravityDirection, PxReal* sprungMasses)
{
computeSprungMasses(numSprungMasses, sprungMassCoordinates, centreOfMass, totalMass, gravityDirection, sprungMasses);
}
void PxVehicleCopyDynamicsData(const PxVehicleCopyDynamicsMap& wheelMap, const PxVehicleWheels& src, PxVehicleWheels* trg)
{
PX_CHECK_AND_RETURN(trg, "PxVehicleCopyDynamicsData requires that trg is a valid vehicle pointer");
PX_CHECK_AND_RETURN(src.getVehicleType() == trg->getVehicleType(), "PxVehicleCopyDynamicsData requires that both src and trg are the same type of vehicle");
#if PX_CHECKED
{
const PxU32 numWheelsSrc = src.mWheelsSimData.getNbWheels();
const PxU32 numWheelsTrg = trg->mWheelsSimData.getNbWheels();
PxU8 copiedWheelsSrc[PX_MAX_NB_WHEELS];
PxMemZero(copiedWheelsSrc, sizeof(PxU8) * PX_MAX_NB_WHEELS);
PxU8 setWheelsTrg[PX_MAX_NB_WHEELS];
PxMemZero(setWheelsTrg, sizeof(PxU8) * PX_MAX_NB_WHEELS);
for(PxU32 i = 0; i < PxMin(numWheelsSrc, numWheelsTrg); i++)
{
const PxU32 srcWheelId = wheelMap.sourceWheelIds[i];
PX_CHECK_AND_RETURN(srcWheelId < numWheelsSrc, "PxVehicleCopyDynamicsData - wheelMap contains illegal source wheel id");
PX_CHECK_AND_RETURN(0 == copiedWheelsSrc[srcWheelId], "PxVehicleCopyDynamicsData - wheelMap contains illegal source wheel id");
copiedWheelsSrc[srcWheelId] = 1;
const PxU32 trgWheelId = wheelMap.targetWheelIds[i];
PX_CHECK_AND_RETURN(trgWheelId < numWheelsTrg, "PxVehicleCopyDynamicsData - wheelMap contains illegal target wheel id");
PX_CHECK_AND_RETURN(0 == setWheelsTrg[trgWheelId], "PxVehicleCopyDynamicsData - wheelMap contains illegal target wheel id");
setWheelsTrg[trgWheelId]=1;
}
}
#endif
const PxU32 numWheelsSrc = src.mWheelsSimData.getNbWheels();
const PxU32 numWheelsTrg = trg->mWheelsSimData.getNbWheels();
//Set all dynamics data on the target to zero.
//Be aware that setToRestState sets the rigid body to
//rest so set the momentum back after calling setToRestState.
PxRigidDynamic* actorTrg = trg->getRigidDynamicActor();
PxVec3 linVel = actorTrg->getLinearVelocity();
PxVec3 angVel = actorTrg->getAngularVelocity();
switch(src.getVehicleType())
{
case PxVehicleTypes::eDRIVE4W:
static_cast<PxVehicleDrive4W*>(trg)->setToRestState();
break;
case PxVehicleTypes::eDRIVENW:
static_cast<PxVehicleDriveNW*>(trg)->setToRestState();
break;
case PxVehicleTypes::eDRIVETANK:
static_cast<PxVehicleDriveTank*>(trg)->setToRestState();
break;
case PxVehicleTypes::eNODRIVE:
static_cast<PxVehicleNoDrive*>(trg)->setToRestState();
break;
default:
break;
}
actorTrg->setLinearVelocity(linVel);
actorTrg->setAngularVelocity(angVel);
//Keep a track of the wheels on trg that have their dynamics data set as a copy from src.
PxU8 setWheelsTrg[PX_MAX_NB_WHEELS];
PxMemZero(setWheelsTrg, sizeof(PxU8) * PX_MAX_NB_WHEELS);
//Keep a track of the average wheel rotation speed of all enabled wheels on src.
PxU32 numEnabledWheelsSrc = 0;
PxF32 accumulatedWheelRotationSpeedSrc = 0.0f;
//Copy wheel dynamics data from src wheels to trg wheels.
//Track the target wheels that have been given dynamics data from src wheels.
//Compute the accumulated wheel rotation speed of all enabled src wheels.
const PxU32 numMappedWheels = PxMin(numWheelsSrc, numWheelsTrg);
for(PxU32 i = 0; i < numMappedWheels; i++)
{
const PxU32 srcWheelId = wheelMap.sourceWheelIds[i];
const PxU32 trgWheelId = wheelMap.targetWheelIds[i];
trg->mWheelsDynData.copy(src.mWheelsDynData, srcWheelId, trgWheelId);
setWheelsTrg[trgWheelId] = 1;
if(!src.mWheelsSimData.getIsWheelDisabled(srcWheelId))
{
numEnabledWheelsSrc++;
accumulatedWheelRotationSpeedSrc += src.mWheelsDynData.getWheelRotationSpeed(srcWheelId);
}
}
//Compute the average wheel rotation speed of src.
PxF32 averageWheelRotationSpeedSrc = 0;
if(numEnabledWheelsSrc > 0)
{
averageWheelRotationSpeedSrc = (accumulatedWheelRotationSpeedSrc/ (1.0f * numEnabledWheelsSrc));
}
//For wheels on trg that have not had their dynamics data copied from src just set
//their wheel rotation speed to the average wheel rotation speed.
for(PxU32 i = 0; i < numWheelsTrg; i++)
{
if(0 == setWheelsTrg[i] && !trg->mWheelsSimData.getIsWheelDisabled(i))
{
trg->mWheelsDynData.setWheelRotationSpeed(i, averageWheelRotationSpeedSrc);
}
}
//Copy the engine rotation speed/gear states/autobox states/etc.
switch(src.getVehicleType())
{
case PxVehicleTypes::eDRIVE4W:
case PxVehicleTypes::eDRIVENW:
case PxVehicleTypes::eDRIVETANK:
{
const PxVehicleDriveDynData& driveDynDataSrc = static_cast<const PxVehicleDrive&>(src).mDriveDynData;
PxVehicleDriveDynData* driveDynDataTrg = &static_cast<PxVehicleDrive*>(trg)->mDriveDynData;
*driveDynDataTrg = driveDynDataSrc;
}
break;
default:
break;
}
}
bool areEqual(const PxQuat& q0, const PxQuat& q1)
{
return ((q0.x == q1.x) && (q0.y == q1.y) && (q0.z == q1.z) && (q0.w == q1.w));
}
void PxVehicleUpdateCMassLocalPose(const PxTransform& oldCMassLocalPose, const PxTransform& newCMassLocalPose, const PxU32 gravityDirection, PxVehicleWheels* vehicle)
{
PX_CHECK_AND_RETURN(areEqual(PxQuat(PxIdentity), oldCMassLocalPose.q), "Only center of mass poses with identity rotation are supported");
PX_CHECK_AND_RETURN(areEqual(PxQuat(PxIdentity), newCMassLocalPose.q), "Only center of mass poses with identity rotation are supported");
PX_CHECK_AND_RETURN(0==gravityDirection || 1==gravityDirection || 2==gravityDirection, "gravityDirection must be 0 or 1 or 2.");
//Update the offsets from the rigid body center of mass.
PxVec3 wheelCenterCMOffsets[PX_MAX_NB_WHEELS];
const PxU32 nbWheels = vehicle->mWheelsSimData.getNbWheels();
for(PxU32 i = 0; i < nbWheels; i++)
{
wheelCenterCMOffsets[i] = vehicle->mWheelsSimData.getWheelCentreOffset(i) + oldCMassLocalPose.p - newCMassLocalPose.p;
vehicle->mWheelsSimData.setWheelCentreOffset(i, vehicle->mWheelsSimData.getWheelCentreOffset(i) + oldCMassLocalPose.p - newCMassLocalPose.p);
vehicle->mWheelsSimData.setSuspForceAppPointOffset(i, vehicle->mWheelsSimData.getSuspForceAppPointOffset(i) + oldCMassLocalPose.p - newCMassLocalPose.p);
vehicle->mWheelsSimData.setTireForceAppPointOffset(i, vehicle->mWheelsSimData.getTireForceAppPointOffset(i) + oldCMassLocalPose.p - newCMassLocalPose.p);
}
//Now update the sprung masses.
PxF32 sprungMasses[PX_MAX_NB_WHEELS];
PxVehicleComputeSprungMasses(nbWheels, wheelCenterCMOffsets, PxVec3(0,0,0), vehicle->getRigidDynamicActor()->getMass(), gravityDirection, sprungMasses);
for(PxU32 i = 0; i < nbWheels; i++)
{
PxVehicleSuspensionData suspData = vehicle->mWheelsSimData.getSuspensionData(i);
const PxF32 massRatio = sprungMasses[i]/suspData.mSprungMass;
suspData.mSprungMass = sprungMasses[i];
suspData.mSpringStrength *= massRatio;
suspData.mSpringDamperRate *= massRatio;
vehicle->mWheelsSimData.setSuspensionData(i, suspData);
}
}
}//physx
| 11,960 |
C++
| 46.844 | 217 | 0.787375 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleLinearMath.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_VEHICLE_LINEAR_MATH_H
#define PX_VEHICLE_LINEAR_MATH_H
/** \addtogroup vehicle
@{
*/
#include "vehicle/PxVehicleSDK.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#define MAX_VECTORN_SIZE (PX_MAX_NB_WHEELS+3)
class VectorN
{
public:
VectorN(const PxU32 size)
: mSize(size)
{
PX_ASSERT(mSize <= MAX_VECTORN_SIZE);
}
~VectorN()
{
}
VectorN(const VectorN& src)
{
for(PxU32 i = 0; i < src.mSize; i++)
{
mValues[i] = src.mValues[i];
}
mSize = src.mSize;
}
PX_FORCE_INLINE VectorN& operator=(const VectorN& src)
{
for(PxU32 i = 0; i < src.mSize; i++)
{
mValues[i] = src.mValues[i];
}
mSize = src.mSize;
return *this;
}
PX_FORCE_INLINE PxF32& operator[] (const PxU32 i)
{
PX_ASSERT(i < mSize);
return (mValues[i]);
}
PX_FORCE_INLINE const PxF32& operator[] (const PxU32 i) const
{
PX_ASSERT(i < mSize);
return (mValues[i]);
}
PX_FORCE_INLINE PxU32 getSize() const {return mSize;}
private:
PxF32 mValues[MAX_VECTORN_SIZE];
PxU32 mSize;
};
class MatrixNN
{
public:
MatrixNN()
: mSize(0)
{
}
MatrixNN(const PxU32 size)
: mSize(size)
{
PX_ASSERT(mSize <= MAX_VECTORN_SIZE);
}
MatrixNN(const MatrixNN& 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;
}
~MatrixNN()
{
}
PX_FORCE_INLINE MatrixNN& operator=(const MatrixNN& 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 PxF32 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 PxF32 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 <= MAX_VECTORN_SIZE);
mSize = size;
}
public:
PxF32 mValues[MAX_VECTORN_SIZE][MAX_VECTORN_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 MatrixNNLUSolver
{
private:
MatrixNN mLU;
PxU32 mP[MAX_VECTORN_SIZE-1]; // Row permutation
PxU32 mQ[MAX_VECTORN_SIZE-1]; // Column permutation
PxF32 mdetM;
public:
MatrixNNLUSolver(){}
~MatrixNNLUSolver(){}
PxF32 getDet() const {return mdetM;}
void decomposeLU(const MatrixNN& A)
{
const PxU32 D = A.mSize;
mLU = A;
mdetM = 1.0f;
for (PxU32 k = 0; k < D-1; ++k)
{
PxU32 pivot_row = k;
PxU32 pivot_col = k;
float abs_pivot_elem = 0.0f;
for (PxU32 c = k; c < D; ++c)
{
for (PxU32 r = k; r < D; ++r)
{
const PxF32 abs_elem = PxAbs(mLU.get(r,c));
if (abs_elem > abs_pivot_elem)
{
abs_pivot_elem = abs_elem;
pivot_row = r;
pivot_col = c;
}
}
}
mP[k] = pivot_row;
if (pivot_row != k)
{
mdetM = -mdetM;
for (PxU32 c = 0; c < D; ++c)
{
//swap(m_LU(k,c), m_LU(pivot_row,c));
const PxF32 pivotrowc = mLU.get(pivot_row, c);
mLU.set(pivot_row, c, mLU.get(k, c));
mLU.set(k, c, pivotrowc);
}
}
mQ[k] = pivot_col;
if (pivot_col != k)
{
mdetM = -mdetM;
for (PxU32 r = 0; r < D; ++r)
{
//swap(m_LU(r,k), m_LU(r,pivot_col));
const PxF32 rpivotcol = mLU.get(r, pivot_col);
mLU.set(r,pivot_col, mLU.get(r,k));
mLU.set(r, k, rpivotcol);
}
}
mdetM *= mLU.get(k,k);
if (mLU.get(k,k) != 0.0f)
{
for (PxU32 r = k+1; r < D; ++r)
{
mLU.set(r, k, mLU.get(r,k) / mLU.get(k,k));
for (PxU32 c = k+1; c < D; ++c)
{
//m_LU(r,c) -= m_LU(r,k)*m_LU(k,c);
const PxF32 rc = mLU.get(r, c);
const PxF32 rk = mLU.get(r, k);
const PxF32 kc = mLU.get(k, c);
mLU.set(r, c, rc - rk*kc);
}
}
}
}
mdetM *= mLU.get(D-1,D-1);
}
//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 VectorN& b, VectorN& x) const
{
const PxU32 D = x.getSize();
if((b.getSize() != x.getSize()) || (b.getSize() != mLU.getSize()) || (0.0f == mdetM))
{
for(PxU32 i = 0; i < D; i++)
{
x[i] = 0.0f;
}
return false;
}
x = b;
// Perform row permutation to get Pb
for(PxU32 i = 0; i < D-1; ++i)
{
//swap(x(i), x(m_P[i]));
const PxF32 xp = x[mP[i]];
x[mP[i]] = x[i];
x[i] = xp;
}
// Forward substitute to get (L^-1)Pb
for (PxU32 r = 1; r < D; ++r)
{
for (PxU32 i = 0; i < r; ++i)
{
x[r] -= mLU.get(r,i)*x[i];
}
}
// Back substitute to get (U^-1)(L^-1)Pb
for (PxU32 r = D; r-- > 0;)
{
for (PxU32 i = r+1; i < D; ++i)
{
x[r] -= mLU.get(r,i)*x[i];
}
x[r] /= mLU.get(r,r);
}
// Perform column permutation to get the solution (Q^T)(U^-1)(L^-1)Pb
for (PxU32 i = D-1; i-- > 0;)
{
//swap(x(i), x(m_Q[i]));
const PxF32 xq = x[mQ[i]];
x[mQ[i]] = x[i];
x[i] = xq;
}
return true;
}
};
class MatrixNGaussSeidelSolver
{
public:
void solve(const PxU32 maxIterations, const PxF32 tolerance, const MatrixNN& A, const VectorN& b, VectorN& result) const
{
const PxU32 N = A.getSize();
VectorN DInv(N);
PxF32 bLength2 = 0.0f;
for(PxU32 i = 0; i < N; i++)
{
DInv[i] = 1.0f/A.get(i,i);
bLength2 += (b[i] * b[i]);
}
PxU32 iteration = 0;
PxF32 error = PX_MAX_F32;
while(iteration < maxIterations && tolerance < error)
{
for(PxU32 i = 0; i < N; i++)
{
PxF32 l = 0.0f;
for(PxU32 j = 0; j < i; j++)
{
l += A.get(i,j) * result[j];
}
PxF32 u = 0.0f;
for(PxU32 j = i + 1; j < N; j++)
{
u += A.get(i,j) * result[j];
}
result[i] = DInv[i] * (b[i] - l - u);
}
//Compute the error.
PxF32 rLength2 = 0;
for(PxU32 i = 0; i < N; i++)
{
PxF32 e = -b[i];
for(PxU32 j = 0; j < N; j++)
{
e += A.get(i,j) * result[j];
}
rLength2 += e * e;
}
error = (rLength2 / (bLength2 + 1e-10f));
iteration++;
}
}
};
class Matrix33Solver
{
public:
bool solve(const MatrixNN& A_, const VectorN& b_, VectorN& result) const
{
const PxF32 a = A_.get(0,0);
const PxF32 b = A_.get(0,1);
const PxF32 c = A_.get(0,2);
const PxF32 d = A_.get(1,0);
const PxF32 e = A_.get(1,1);
const PxF32 f = A_.get(1,2);
const PxF32 g = A_.get(2,0);
const PxF32 h = A_.get(2,1);
const PxF32 k = A_.get(2,2);
const PxF32 detA = a*(e*k - f*h) - b*(k*d - f*g) + c*(d*h - e*g);
if(0.0f == detA)
{
return false;
}
const PxF32 detAInv = 1.0f/detA;
const PxF32 A = (e*k - f*h);
const PxF32 D = -(b*k - c*h);
const PxF32 G = (b*f - c*e);
const PxF32 B = -(d*k - f*g);
const PxF32 E = (a*k - c*g);
const PxF32 H = -(a*f - c*d);
const PxF32 C = (d*h - e*g);
const PxF32 F = -(a*h - b*g);
const PxF32 K = (a*e - b*d);
result[0] = detAInv*(A*b_[0] + D*b_[1] + G*b_[2]);
result[1] = detAInv*(B*b_[0] + E*b_[1] + H*b_[2]);
result[2] = detAInv*(C*b_[0] + F*b_[1] + K*b_[2]);
return true;
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 9,535 |
C
| 21.023095 | 129 | 0.590771 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleDriveTank.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleDriveTank.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleSDK.h"
#include "PxRigidDynamic.h"
#include "CmUtils.h"
namespace physx
{
extern PxF32 gToleranceScaleLength;
bool PxVehicleDriveTank::isValid() const
{
PX_CHECK_AND_RETURN_VAL(PxVehicleDrive::isValid(), "invalid PxVehicleDrive", false);
PX_CHECK_AND_RETURN_VAL(mDriveSimData.isValid(), "Invalid PxVehicleDriveTank.mCoreSimData", false);
return true;
}
PxVehicleDriveTank* PxVehicleDriveTank::allocate(const PxU32 numWheels)
{
PX_CHECK_AND_RETURN_NULL(numWheels>0, "Cars with zero wheels are illegal");
PX_CHECK_AND_RETURN_NULL(0 == (numWheels % 2), "PxVehicleDriveTank::allocate - needs to have even number of wheels");
PX_CHECK_AND_RETURN_NULL(gToleranceScaleLength > 0, "PxVehicleDriveTank::allocate - need to call PxInitVehicleSDK");
//Compute the bytes needed.
const PxU32 byteSize = sizeof(PxVehicleDriveTank) + PxVehicleDrive::computeByteSize(numWheels);
//Allocate the memory.
PxVehicleDriveTank* veh = static_cast<PxVehicleDriveTank*>(PX_ALLOC(byteSize, "PxVehicleDriveTank"));
PxMarkSerializedMemory(veh, byteSize);
PX_PLACEMENT_NEW(veh, PxVehicleDriveTank());
//Patch up the pointers.
PxU8* ptr = reinterpret_cast<PxU8*>(veh) + sizeof(PxVehicleDriveTank);
PxVehicleDrive::patchupPointers(numWheels, veh, ptr);
//Initialise.
veh->init(numWheels);
//Set the vehicle type.
veh->mType = PxVehicleTypes::eDRIVETANK;
//Set the default drive model.
veh->mDriveModel = PxVehicleDriveTankControlModel::eSTANDARD;
return veh;
}
void PxVehicleDriveTank::free()
{
PxVehicleDrive::free();
}
void PxVehicleDriveTank::setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData& driveData,
const PxU32 numDrivenWheels)
{
PX_CHECK_AND_RETURN(driveData.isValid(), "PxVehicleDriveTank::setup - illegal drive data");
//Set up the wheels.
PxVehicleDrive::setup(physics,vehActor,wheelsData,numDrivenWheels,0);
//Start setting up the drive.
PX_CHECK_MSG(driveData.isValid(), "PxVehicle4WDrive - invalid driveData");
//Copy the simulation data.
mDriveSimData = driveData;
}
PxVehicleDriveTank* PxVehicleDriveTank::create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData& driveData,
const PxU32 numDrivenWheels)
{
PxVehicleDriveTank* tank=PxVehicleDriveTank::allocate(numDrivenWheels);
tank->setup(physics,vehActor,wheelsData,driveData,numDrivenWheels);
return tank;
}
void PxVehicleDriveTank::setToRestState()
{
//Set core to rest state.
PxVehicleDrive::setToRestState();
}
} //namespace physx
| 4,377 |
C++
| 36.101695 | 118 | 0.773818 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/VehicleUtilControl.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleUtilControl.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxErrors.h"
namespace physx
{
#if PX_CHECKED
void testValidAnalogValue(const PxF32 actualValue, const PxF32 minVal, const PxF32 maxVal, const char* errorString)
{
const PxF32 tolerance = 1e-2f;
PX_CHECK_MSG((actualValue > (minVal - tolerance)) && (actualValue < (maxVal + tolerance)), errorString);
}
#endif
PxF32 processDigitalValue
(const PxU32 inputType,
const PxVehicleKeySmoothingData& keySmoothing, const bool digitalValue,
const PxF32 timestep,
const PxF32 analogVal)
{
PxF32 newAnalogVal=analogVal;
if(digitalValue)
{
newAnalogVal+=keySmoothing.mRiseRates[inputType]*timestep;
}
else
{
newAnalogVal-=keySmoothing.mFallRates[inputType]*timestep;
}
return PxClamp(newAnalogVal,0.0f,1.0f);
}
static void PxVehicleDriveSmoothDigitalRawInputsAndSetAnalogInputs
(const PxVehicleKeySmoothingData& keySmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDrive4WRawInputData& rawInputData, const PxF32 timestep, const bool isVehicleInAir,
const PxVehicleWheels& vehicle, PxVehicleDriveDynData& driveDynData, const PxVehicleSteerFilter& steerFilter,
const PxVec3& forwardAxis)
{
const bool gearup=rawInputData.getGearUp();
const bool geardown=rawInputData.getGearDown();
driveDynData.setGearDown(geardown);
driveDynData.setGearUp(gearup);
const PxF32 accel=processDigitalValue(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL,keySmoothing,rawInputData.getDigitalAccel(),timestep,driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL));
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL,accel);
const PxF32 brake=processDigitalValue(PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE,keySmoothing,rawInputData.getDigitalBrake(),timestep,driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE));
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE,brake);
const PxF32 handbrake=processDigitalValue(PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE,keySmoothing,rawInputData.getDigitalHandbrake(),timestep,driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE));
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE,handbrake);
PxF32 steerLeft=processDigitalValue(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT,keySmoothing,rawInputData.getDigitalSteerLeft(),timestep,driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT));
PxF32 steerRight=processDigitalValue(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT,keySmoothing,rawInputData.getDigitalSteerRight(),timestep,driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT));
const PxF32 vz=vehicle.computeForwardSpeed(forwardAxis);
const PxF32 vzAbs=PxAbs(vz);
const PxF32 maxSteer = steerFilter.computeMaxSteer(isVehicleInAir, steerVsForwardSpeedTable, vzAbs, timestep);
const PxF32 steer=PxAbs(steerRight-steerLeft);
if(steer>maxSteer)
{
const PxF32 k=maxSteer/steer;
steerLeft*=k;
steerRight*=k;
}
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT, steerLeft);
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT, steerRight);
}
//////////////////////////////////
//process value in range(0,1)
PX_FORCE_INLINE PxF32 processPositiveAnalogValue
(const PxF32 riseRate, const PxF32 fallRate,
const PxF32 currentVal, const PxF32 targetVal,
const PxF32 timestep)
{
PX_ASSERT(targetVal>=-0.01f && targetVal<=1.01f);
PxF32 val;
if(currentVal<targetVal)
{
val=currentVal + riseRate*timestep;
val=PxMin(val,targetVal);
}
else
{
val=currentVal - fallRate*timestep;
val=PxMax(val,targetVal);
}
return val;
}
//process value in range(-1,1)
PX_FORCE_INLINE PxF32 processAnalogValue
(const PxF32 riseRate, const PxF32 fallRate,
const PxF32 currentVal, const PxF32 targetVal,
const PxF32 timestep)
{
PX_ASSERT(PxAbs(targetVal)<=1.01f);
PxF32 val=0.0f; // PT: the following code could leave that variable uninitialized!!!!!
if(0==targetVal)
{
//Drift slowly back to zero
if(currentVal>0)
{
val=currentVal-fallRate*timestep;
val=PxMax(val,0.0f);
}
else if(currentVal<0)
{
val=currentVal+fallRate*timestep;
val=PxMin(val,0.0f);
}
}
else
{
if(currentVal < targetVal)
{
if(currentVal<0)
{
val=currentVal + fallRate*timestep;
val=PxMin(val,targetVal);
}
else
{
val=currentVal + riseRate*timestep;
val=PxMin(val,targetVal);
}
}
else
{
if(currentVal>0)
{
val=currentVal - fallRate*timestep;
val=PxMax(val,targetVal);
}
else
{
val=currentVal - riseRate*timestep;
val=PxMax(val,targetVal);
}
}
}
return val;
}
static void PxVehicleDriveSmoothAnalogRawInputsAndSetAnalogInputs
(const PxVehiclePadSmoothingData& padSmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDrive4WRawInputData& rawInputData, const PxF32 timestep, const bool isVehicleInAir,
const PxVehicleWheels& vehicle, PxVehicleDriveDynData& driveDynData, const PxVehicleSteerFilter& steerFilter,
const PxVec3& forwardAxis)
{
//gearup/geardown
const bool gearup=rawInputData.getGearUp();
const bool geardown=rawInputData.getGearDown();
driveDynData.setGearUp(gearup);
driveDynData.setGearDown(geardown);
//Update analog inputs for focus vehicle.
//Process the accel.
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];
const PxF32 currentVal=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL);
const PxF32 targetVal=rawInputData.getAnalogAccel();
const PxF32 accel=processPositiveAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL, accel);
}
//Process the brake
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE];
const PxF32 currentVal=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE);
const PxF32 targetVal=rawInputData.getAnalogBrake();
const PxF32 brake=processPositiveAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE, brake);
}
//Process the handbrake.
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE];
const PxF32 currentVal=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE);
const PxF32 targetVal=rawInputData.getAnalogHandbrake();
const PxF32 handbrake=processPositiveAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE, handbrake);
}
//Process the steer
{
const PxF32 vz=vehicle.computeForwardSpeed(forwardAxis);
const PxF32 vzAbs=PxAbs(vz);
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT];
const PxF32 currentVal=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT)-driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT);
const PxF32 maxSteer = steerFilter.computeMaxSteer(isVehicleInAir, steerVsForwardSpeedTable, vzAbs, timestep);
const PxF32 targetVal=rawInputData.getAnalogSteer()*maxSteer;
const PxF32 steer=processAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT, 0.0f);
driveDynData.setAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT, steer);
}
}
////////////////
void PxVehicleDrive4WSmoothDigitalRawInputsAndSetAnalogInputs
(const PxVehicleKeySmoothingData& keySmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDrive4WRawInputData& rawInputData, const PxF32 timestep, const bool isVehicleInAir,
PxVehicleDrive4W& focusVehicle, const PxVehicleSteerFilter& steerFilter, const PxVec3& forwardAxis)
{
PxVehicleDriveSmoothDigitalRawInputsAndSetAnalogInputs
(keySmoothing, steerVsForwardSpeedTable, rawInputData, timestep, isVehicleInAir, focusVehicle, focusVehicle.mDriveDynData, steerFilter,
forwardAxis);
}
void PxVehicleDrive4WSmoothAnalogRawInputsAndSetAnalogInputs
(const PxVehiclePadSmoothingData& padSmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDrive4WRawInputData& rawInputData, const PxF32 timestep, const bool isVehicleInAir,
PxVehicleDrive4W& focusVehicle, const PxVehicleSteerFilter& steerFilter, const PxVec3& forwardAxis)
{
PxVehicleDriveSmoothAnalogRawInputsAndSetAnalogInputs
(padSmoothing,steerVsForwardSpeedTable,rawInputData,timestep,isVehicleInAir,focusVehicle,focusVehicle.mDriveDynData, steerFilter,
forwardAxis);
}
////////////////
void PxVehicleDriveNWSmoothDigitalRawInputsAndSetAnalogInputs
(const PxVehicleKeySmoothingData& keySmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDriveNWRawInputData& rawInputData, const PxReal timestep, const bool isVehicleInAir,
PxVehicleDriveNW& focusVehicle, const PxVehicleSteerFilter& steerFilter, const PxVec3& forwardAxis)
{
PxVehicleDriveSmoothDigitalRawInputsAndSetAnalogInputs
(keySmoothing,steerVsForwardSpeedTable,rawInputData,timestep,isVehicleInAir,focusVehicle,focusVehicle.mDriveDynData, steerFilter,
forwardAxis);
}
void PxVehicleDriveNWSmoothAnalogRawInputsAndSetAnalogInputs
(const PxVehiclePadSmoothingData& padSmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDriveNWRawInputData& rawInputData, const PxReal timestep, const bool isVehicleInAir,
PxVehicleDriveNW& focusVehicle, const PxVehicleSteerFilter& steerFilter, const PxVec3& forwardAxis)
{
PxVehicleDriveSmoothAnalogRawInputsAndSetAnalogInputs
(padSmoothing,steerVsForwardSpeedTable,rawInputData,timestep,isVehicleInAir,focusVehicle,focusVehicle.mDriveDynData, steerFilter,
forwardAxis);
}
////////////////
void PxVehicleDriveTankSmoothAnalogRawInputsAndSetAnalogInputs
(const PxVehiclePadSmoothingData& padSmoothing,
const PxVehicleDriveTankRawInputData& rawInputData,
const PxReal timestep,
PxVehicleDriveTank& focusVehicle)
{
//Process the gearup/geardown buttons.
const bool gearup=rawInputData.getGearUp();
const bool geardown=rawInputData.getGearDown();
focusVehicle.mDriveDynData.setGearUp(gearup);
focusVehicle.mDriveDynData.setGearDown(geardown);
//Process the accel.
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL];
const PxF32 currentVal=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL);
const PxF32 targetVal=rawInputData.getAnalogAccel();
const PxF32 accel=processPositiveAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL, accel);
}
PX_ASSERT(focusVehicle.getDriveModel()==rawInputData.getDriveModel());
switch(rawInputData.getDriveModel())
{
case PxVehicleDriveTankControlModel::eSPECIAL:
{
//Process the left brake.
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT];
const PxF32 currentVal=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT);
const PxF32 targetVal=rawInputData.getAnalogLeftBrake();
const PxF32 accel=processPositiveAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT, accel);
}
//Process the right brake.
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT];
const PxF32 currentVal=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT);
const PxF32 targetVal=rawInputData.getAnalogRightBrake();
const PxF32 accel=processPositiveAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT, accel);
}
//Left thrust
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];
const PxF32 currentVal=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT);
const PxF32 targetVal=rawInputData.getAnalogLeftThrust();
const PxF32 val=processAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT, val);
}
//Right thrust
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];
const PxF32 currentVal=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT);
const PxF32 targetVal=rawInputData.getAnalogRightThrust();
const PxF32 val=processAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT, val);
}
}
break;
case PxVehicleDriveTankControlModel::eSTANDARD:
{
//Right thrust
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];
const PxF32 currentVal=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT)-focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT);
const PxF32 targetVal=rawInputData.getAnalogRightThrust()-rawInputData.getAnalogRightBrake();
const PxF32 val=processAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
if(val>0)
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT, val);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT, 0.0f);
}
else
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT, 0.0f);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT, -val);
}
}
//Left thrust
{
const PxF32 riseRate=padSmoothing.mRiseRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];
const PxF32 fallRate=padSmoothing.mFallRates[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];
const PxF32 currentVal=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT)-focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT);
const PxF32 targetVal=rawInputData.getAnalogLeftThrust()-rawInputData.getAnalogLeftBrake();
const PxF32 val=processAnalogValue(riseRate,fallRate,currentVal,targetVal,timestep);
if(val>0)
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT, val);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT, 0.0f);
}
else
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT, 0.0f);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT, -val);
}
}
}
break;
}
}
void PxVehicleDriveTankSmoothDigitalRawInputsAndSetAnalogInputs
(const PxVehicleKeySmoothingData& keySmoothing,
const PxVehicleDriveTankRawInputData& rawInputData,
const PxF32 timestep,
PxVehicleDriveTank& focusVehicle)
{
PxF32 val;
val=processDigitalValue(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL,keySmoothing,rawInputData.getDigitalAccel(),timestep,focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL));
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL, val);
val=processDigitalValue(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT,keySmoothing,rawInputData.getDigitalLeftThrust(),timestep,focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT));
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT, val);
val=processDigitalValue(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT,keySmoothing,rawInputData.getDigitalRightThrust(),timestep,focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT));
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT, val);
val=processDigitalValue(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT,keySmoothing,rawInputData.getDigitalLeftBrake(),timestep,focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT));
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT, val);
val=processDigitalValue(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT,keySmoothing,rawInputData.getDigitalRightBrake(),timestep,focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT));
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT, val);
//Update digital inputs for focus vehicle.
focusVehicle.mDriveDynData.setGearUp(rawInputData.getGearUp());
focusVehicle.mDriveDynData.setGearDown(rawInputData.getGearDown());
switch(rawInputData.getDriveModel())
{
case PxVehicleDriveTankControlModel::eSPECIAL:
{
const PxF32 thrustL=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT)-focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT, thrustL);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT, 0.0f);
const PxF32 thrustR=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT)-focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT, thrustR);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT, 0.0f);
}
break;
case PxVehicleDriveTankControlModel::eSTANDARD:
{
const PxF32 thrustL=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT)-focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT);
if(thrustL>0)
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT, thrustL);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT, 0.0f);
}
else
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT, 0.0f);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT, -thrustL);
}
const PxF32 thrustR=focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT)-focusVehicle.mDriveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT);
if(thrustR>0)
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT, thrustR);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT, 0.0f);
}
else
{
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT, 0.0f);
focusVehicle.mDriveDynData.setAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT, -thrustR);
}
}
break;
}
}
} //physx
| 22,823 |
C++
| 47.458599 | 236 | 0.816194 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleDrive.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleSDK.h"
#include "PxRigidDynamic.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxErrors.h"
namespace physx
{
bool PxVehicleDriveSimData::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mEngine.isValid(), "Invalid PxVehicleCoreSimulationData.mEngine", false);
PX_CHECK_AND_RETURN_VAL(mGears.isValid(), "Invalid PxVehicleCoreSimulationData.mGears", false);
PX_CHECK_AND_RETURN_VAL(mClutch.isValid(), "Invalid PxVehicleCoreSimulationData.mClutch", false);
PX_CHECK_AND_RETURN_VAL(mAutoBox.isValid(), "Invalid PxVehicleCoreSimulationData.mAutoBox", false);
return true;
}
void PxVehicleDriveSimData::setEngineData(const PxVehicleEngineData& engine)
{
PX_CHECK_AND_RETURN(engine.mTorqueCurve.getNbDataPairs()>0, "Engine torque curve must specify at least one entry");
PX_CHECK_AND_RETURN(engine.mPeakTorque>0, "Engine peak torque must be greater than zero");
PX_CHECK_AND_RETURN(engine.mMaxOmega>0, "Engine max omega must be greater than zero");
PX_CHECK_AND_RETURN(engine.mDampingRateFullThrottle>=0, "Full throttle damping rate must be greater than or equal to zero");
PX_CHECK_AND_RETURN(engine.mDampingRateZeroThrottleClutchEngaged>=0, "Zero throttle clutch engaged damping rate must be greater than or equal to zero");
PX_CHECK_AND_RETURN(engine.mDampingRateZeroThrottleClutchDisengaged>=0, "Zero throttle clutch disengaged damping rate must be greater than or equal to zero");
mEngine=engine;
mEngine.mRecipMOI=1.0f/engine.mMOI;
mEngine.mRecipMaxOmega=1.0f/engine.mMaxOmega;
}
void PxVehicleDriveSimData::setGearsData(const PxVehicleGearsData& gears)
{
PX_CHECK_AND_RETURN(gears.mRatios[PxVehicleGearsData::eREVERSE]<0, "Reverse gear ratio must be negative");
PX_CHECK_AND_RETURN(gears.mRatios[PxVehicleGearsData::eNEUTRAL]==0, "Neutral gear ratio must be zero");
PX_CHECK_AND_RETURN(gears.mRatios[PxVehicleGearsData::eFIRST]>0, "First gear ratio must be positive");
PX_CHECK_AND_RETURN(PxVehicleGearsData::eSECOND>=gears.mNbRatios || (gears.mRatios[PxVehicleGearsData::eSECOND]>0 && gears.mRatios[PxVehicleGearsData::eSECOND] < gears.mRatios[PxVehicleGearsData::eFIRST]), "Second gear ratio must be positive and less than first gear ratio");
PX_CHECK_AND_RETURN(PxVehicleGearsData::eTHIRD>=gears.mNbRatios || (gears.mRatios[PxVehicleGearsData::eTHIRD]>0 && gears.mRatios[PxVehicleGearsData::eTHIRD] < gears.mRatios[PxVehicleGearsData::eSECOND]), "Third gear ratio must be positive and less than second gear ratio");
PX_CHECK_AND_RETURN(PxVehicleGearsData::eFOURTH>=gears.mNbRatios || (gears.mRatios[PxVehicleGearsData::eFOURTH]>0 && gears.mRatios[PxVehicleGearsData::eFOURTH] < gears.mRatios[PxVehicleGearsData::eTHIRD]), "Fourth gear ratio must be positive and less than third gear ratio");
PX_CHECK_AND_RETURN(PxVehicleGearsData::eFIFTH>=gears.mNbRatios || (gears.mRatios[PxVehicleGearsData::eFIFTH]>0 && gears.mRatios[PxVehicleGearsData::eFIFTH] < gears.mRatios[PxVehicleGearsData::eFOURTH]), "Fifth gear ratio must be positive and less than fourth gear ratio");
PX_CHECK_AND_RETURN(PxVehicleGearsData::eSIXTH>=gears.mNbRatios || (gears.mRatios[PxVehicleGearsData::eSIXTH]>0 && gears.mRatios[PxVehicleGearsData::eSIXTH] < gears.mRatios[PxVehicleGearsData::eFIFTH]), "Sixth gear ratio must be positive and less than fifth gear ratio");
PX_CHECK_AND_RETURN(gears.mFinalRatio>0, "Final gear ratio must be greater than zero");
PX_CHECK_AND_RETURN(gears.mNbRatios>=3, "Number of gear ratios must be at least 3 - we need at least reverse, neutral, and a forward gear");
mGears=gears;
}
void PxVehicleDriveSimData::setClutchData(const PxVehicleClutchData& clutch)
{
PX_CHECK_AND_RETURN(clutch.mStrength>0, "Clutch strength must be greater than zero");
PX_CHECK_AND_RETURN(PxVehicleClutchAccuracyMode::eBEST_POSSIBLE==clutch.mAccuracyMode || clutch.mEstimateIterations > 0, "Clutch mEstimateIterations must be greater than zero in eESTIMATE mode.");
mClutch=clutch;
}
void PxVehicleDriveSimData::setAutoBoxData(const PxVehicleAutoBoxData& autobox)
{
PX_CHECK_AND_RETURN(autobox.mUpRatios[PxVehicleGearsData::eREVERSE]>=0, "Autobox gearup ratio in reverse must be greater than or equal to zero");
PX_CHECK_AND_RETURN(autobox.mUpRatios[PxVehicleGearsData::eNEUTRAL]>=0, "Autobox gearup ratio in neutral must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mUpRatios[PxVehicleGearsData::eFIRST]>=0, "Autobox gearup ratio in first must be greater than or equal to zero");
PX_CHECK_AND_RETURN(autobox.mUpRatios[PxVehicleGearsData::eSECOND]>=0, "Autobox gearup ratio in second must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mUpRatios[PxVehicleGearsData::eTHIRD]>=0, "Autobox gearup ratio in third must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mUpRatios[PxVehicleGearsData::eFOURTH]>=0, "Autobox gearup ratio in fourth must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mUpRatios[PxVehicleGearsData::eFIFTH]>=0, "Autobox gearup ratio in fifth must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eREVERSE]>=0, "Autobox geardown ratio in reverse must be greater than or equal to zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eNEUTRAL]>=0, "Autobox geardown ratio in neutral must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eFIRST]>=0, "Autobox geardown ratio in first must be greater than or equal to zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eSECOND]>=0, "Autobox geardown ratio in second must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eTHIRD]>=0, "Autobox geardown ratio in third must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eFOURTH]>=0, "Autobox geardown ratio in fourth must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eFIFTH]>=0, "Autobox geardown ratio in fifth must be greater than zero");
PX_CHECK_AND_RETURN(autobox.mDownRatios[PxVehicleGearsData::eSIXTH]>=0, "Autobox geardown ratio in fifth must be greater than zero");
mAutoBox=autobox;
}
///////////////////////////////////
PxVehicleDriveDynData::PxVehicleDriveDynData()
: mUseAutoGears(false),
mGearUpPressed(false),
mGearDownPressed(false),
mCurrentGear(PxVehicleGearsData::eNEUTRAL),
mTargetGear(PxVehicleGearsData::eNEUTRAL),
mEnginespeed(0.0f),
mGearSwitchTime(0.0f),
mAutoBoxSwitchTime(0.0f)
{
for(PxU32 i=0;i<eMAX_NB_ANALOG_INPUTS;i++)
{
mControlAnalogVals[i]=0.0f;
}
}
void PxVehicleDriveDynData::setToRestState()
{
//Set analog inputs to zero so the vehicle starts completely at rest.
for(PxU32 i=0;i<eMAX_NB_ANALOG_INPUTS;i++)
{
mControlAnalogVals[i]=0.0f;
}
mGearUpPressed=false;
mGearDownPressed=false;
//Set the vehicle to neutral gear.
mCurrentGear=PxVehicleGearsData::eNEUTRAL;
mTargetGear=PxVehicleGearsData::eNEUTRAL;
mGearSwitchTime=0.0f;
mAutoBoxSwitchTime=0.0f;
//Set internal dynamics to zero so the vehicle starts completely at rest.
mEnginespeed=0.0f;
}
bool PxVehicleDriveDynData::isValid() const
{
return true;
}
void PxVehicleDriveDynData::setAnalogInput(const PxU32 type, const PxReal analogVal)
{
PX_CHECK_AND_RETURN(analogVal>=-1.01f && analogVal<=1.01f, "PxVehicleDriveDynData::setAnalogInput - analogVal must be in range (-1,1)");
PX_CHECK_AND_RETURN(type<eMAX_NB_ANALOG_INPUTS, "PxVehicleDriveDynData::setAnalogInput - illegal type");
mControlAnalogVals[type]=analogVal;
}
PxReal PxVehicleDriveDynData::getAnalogInput(const PxU32 type) const
{
PX_CHECK_AND_RETURN_VAL(type<eMAX_NB_ANALOG_INPUTS, "PxVehicleDriveDynData::getAnalogInput - illegal type", 0.0f);
return mControlAnalogVals[type];
}
///////////////////////////////////
bool PxVehicleDrive::isValid() const
{
PX_CHECK_AND_RETURN_VAL(PxVehicleWheels::isValid(), "invalid PxVehicleWheels", false);
PX_CHECK_AND_RETURN_VAL(mDriveDynData.isValid(), "Invalid PxVehicleDrive.mCoreSimData", false);
return true;
}
PxU32 PxVehicleDrive::computeByteSize(const PxU32 numWheels)
{
return PxVehicleWheels::computeByteSize(numWheels);
}
PxU8* PxVehicleDrive::patchupPointers( const PxU32 numWheels, PxVehicleDrive* veh, PxU8* ptr)
{
return PxVehicleWheels::patchupPointers(numWheels, veh, ptr);
}
void PxVehicleDrive::init(const PxU32 numWheels)
{
PxVehicleWheels::init(numWheels);
}
void PxVehicleDrive::free()
{
PxVehicleWheels::free();
}
void PxVehicleDrive::setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData,
const PxU32 numDrivenWheels, const PxU32 numNonDrivenWheels)
{
//Set up the wheels.
PxVehicleWheels::setup(physics,vehActor,wheelsData,numDrivenWheels,numNonDrivenWheels);
}
void PxVehicleDrive::setToRestState()
{
//Set core to rest state.
PxVehicleWheels::setToRestState();
//Set dynamics data to rest state.
mDriveDynData.setToRestState();
}
} //namespace physx
| 10,674 |
C++
| 49.117371 | 276 | 0.777871 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleSuspWheelTire4.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxVehicleSuspWheelTire4.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxErrors.h"
namespace physx
{
PxVehicleWheels4SimData::PxVehicleWheels4SimData()
{
for(PxU32 i=0;i<4;i++)
{
mSuspDownwardTravelDirections[i]=PxVec3(0,0,0); //Must be filled out
mSuspForceAppPointOffsets[i]=PxVec3(0,0,0); //Must be filled out
mTireForceAppPointOffsets[i]=PxVec3(0,0,0); //Must be filled out
mWheelCentreOffsets[i]=PxVec3(0,0,0); //Must be filled out
mTireRestLoads[i]=20.0f + 1500.0f;
mRecipTireRestLoads[i]=1.0f/mTireRestLoads[i];
}
}
bool PxVehicleWheels4SimData::isValid(const PxU32 id) const
{
PX_ASSERT(id<4);
PX_CHECK_AND_RETURN_VAL(mSuspensions[id].isValid(), "Invalid PxVehicleSuspWheelTire4SimulationData.mSuspensions", false);
PX_CHECK_AND_RETURN_VAL(mWheels[id].isValid(), "Invalid PxVehicleSuspWheelTire4SimulationData.mWheels", false);
PX_CHECK_AND_RETURN_VAL(mTires[id].isValid(), "Invalid PxVehicleSuspWheelTire4SimulationData.mTires", false);
PX_CHECK_AND_RETURN_VAL(mSuspDownwardTravelDirections[id].magnitude()>=0.999f && mSuspDownwardTravelDirections[id].magnitude()<=1.001f, "Invalid PxVehicleSuspWheelTire4SimulationData.mSuspDownwardTravelDirections", false);
PX_CHECK_AND_RETURN_VAL(mSuspForceAppPointOffsets[id].magnitude()!=0.0f, "Invalid PxVehicleSuspWheelTire4SimulationData.mSuspForceAppPointOffsets.mSuspForceAppPointOffsets", false);
PX_CHECK_AND_RETURN_VAL(mTireForceAppPointOffsets[id].magnitude()!=0.0f, "Invalid PxVehicleSuspWheelTire4SimulationData.mTireForceAppPointOffsets.mTireForceAppPointOffsets", false);
PX_CHECK_AND_RETURN_VAL(mWheelCentreOffsets[id].magnitude()!=0.0f, "Invalid PxVehicleSuspWheelTire4SimulationData.mWheelCentreOffsets.mWheelCentreOffsets", false);
PX_CHECK_AND_RETURN_VAL(mTireRestLoads[id]>0.0f, "Invalid PxVehicleSuspWheelTire4SimulationData.mTireRestLoads", false);
PX_CHECK_AND_RETURN_VAL(PxAbs((1.0f/mTireRestLoads[id]) - mRecipTireRestLoads[id]) <= 0.001f, "Invalid PxVehicleSuspWheelTire4SimulationData.mRecipTireRestLoads", false);
PX_UNUSED(id);
return true;
}
void PxVehicleWheels4SimData::setSuspensionData(const PxU32 id, const PxVehicleSuspensionData& susp)
{
PX_CHECK_AND_RETURN(id<4, "Illegal suspension id");
PX_CHECK_AND_RETURN(susp.mSpringStrength>0, "Susp spring strength must be greater than zero");
PX_CHECK_AND_RETURN(susp.mSpringDamperRate>=0, "Susp spring damper rate must be greater than or equal to zero");
PX_CHECK_AND_RETURN(susp.mMaxCompression>=0, "Susp max compression must be greater than or equal to zero");
PX_CHECK_AND_RETURN(susp.mMaxDroop>=0, "Susp max droop must be greater than or equal to zero");
PX_CHECK_AND_RETURN(susp.mMaxDroop>0 || susp.mMaxCompression>0, "Either one of max droop or max compression must be greater than zero");
PX_CHECK_AND_RETURN(susp.mSprungMass>0, "Susp spring mass must be greater than zero");
mSuspensions[id]=susp;
mSuspensions[id].mRecipMaxCompression = 1.0f/((susp.mMaxCompression > 0.0f) ? susp.mMaxCompression : 1.0f);
mSuspensions[id].mRecipMaxDroop = 1.0f/((susp.mMaxDroop > 0.0f) ? susp.mMaxDroop : 1.0f);
mTireRestLoads[id]=mWheels[id].mMass+mSuspensions[id].mSprungMass;
mRecipTireRestLoads[id]=1.0f/mTireRestLoads[id];
}
/////////////////////////////
void PxVehicleWheels4SimData::setWheelData(const PxU32 id, const PxVehicleWheelData& wheel)
{
PX_CHECK_AND_RETURN(id<4, "Illegal wheel id");
PX_CHECK_AND_RETURN(wheel.mRadius>0, "Wheel radius must be greater than zero");
PX_CHECK_AND_RETURN(wheel.mMaxBrakeTorque>=0, "Wheel brake torque must be zero or be a positive value");
PX_CHECK_AND_RETURN(wheel.mMaxHandBrakeTorque>=0, "Wheel handbrake torque must be zero or be a positive value");
PX_CHECK_AND_RETURN(PxAbs(wheel.mMaxSteer)<PxHalfPi, "Wheel max steer must be in range (-Pi/2,Pi/2)");
PX_CHECK_AND_RETURN(wheel.mMass>0, "Wheel mass must be greater than zero");
PX_CHECK_AND_RETURN(wheel.mMOI>0, "Wheel moi must be greater than zero");
PX_CHECK_AND_RETURN(wheel.mToeAngle>-PxHalfPi && wheel.mToeAngle<PxHalfPi, "Wheel toe angle must be in range (-Pi/2,Pi/2)");
PX_CHECK_AND_RETURN(wheel.mWidth>0, "Wheel width must be greater than zero");
PX_CHECK_AND_RETURN(wheel.mDampingRate>=0, "Wheel damping rate must be greater than or equal to zero");
mWheels[id]=wheel;
mWheels[id].mRecipRadius=1.0f/mWheels[id].mRadius;
mWheels[id].mRecipMOI=1.0f/mWheels[id].mMOI;
mTireRestLoads[id]=mWheels[id].mMass+mSuspensions[id].mSprungMass;
mRecipTireRestLoads[id]=1.0f/mTireRestLoads[id];
}
/////////////////////////////
void PxVehicleWheels4SimData::setTireData(const PxU32 id, const PxVehicleTireData& tire)
{
PX_CHECK_AND_RETURN(id<4, "Illegal tire id");
PX_CHECK_AND_RETURN(tire.mLatStiffX>0, "Tire mLatStiffX must greater than zero");
PX_CHECK_AND_RETURN(tire.mLatStiffY>0, "Tire mLatStiffY must greater than zero");
PX_CHECK_AND_RETURN(tire.mLongitudinalStiffnessPerUnitGravity>0, "Tire longitudinal stiffness must greater than zero");
PX_CHECK_AND_RETURN(tire.mCamberStiffnessPerUnitGravity>=0, "Tire camber stiffness must greater than or equal to zero");
PX_CHECK_AND_RETURN(tire.mFrictionVsSlipGraph[0][0]==0, "mFrictionVsSlipGraph[0][0] must be zero");
PX_CHECK_AND_RETURN(tire.mFrictionVsSlipGraph[0][1]>0, "mFrictionVsSlipGraph[0][1] must be greater than zero");
PX_CHECK_AND_RETURN(tire.mFrictionVsSlipGraph[1][0]>0, "mFrictionVsSlipGraph[1][0] must be greater than zero");
PX_CHECK_AND_RETURN(tire.mFrictionVsSlipGraph[1][1]>=tire.mFrictionVsSlipGraph[0][1], "mFrictionVsSlipGraph[1][1] must be greater than mFrictionVsSlipGraph[0][1]");
PX_CHECK_AND_RETURN(tire.mFrictionVsSlipGraph[2][0]> tire.mFrictionVsSlipGraph[1][0], "mFrictionVsSlipGraph[2][0] must be greater than mFrictionVsSlipGraph[1][0]");
PX_CHECK_AND_RETURN(tire.mFrictionVsSlipGraph[2][1]<=tire.mFrictionVsSlipGraph[1][1], "mFrictionVsSlipGraph[2][1] must be less than or equal to mFrictionVsSlipGraph[1][1]");
mTires[id]=tire;
mTires[id].mRecipLongitudinalStiffnessPerUnitGravity=1.0f/mTires[id].mLongitudinalStiffnessPerUnitGravity;
mTires[id].mFrictionVsSlipGraphRecipx1Minusx0=1.0f/(mTires[id].mFrictionVsSlipGraph[1][0]-mTires[id].mFrictionVsSlipGraph[0][0]);
mTires[id].mFrictionVsSlipGraphRecipx2Minusx1=1.0f/(mTires[id].mFrictionVsSlipGraph[2][0]-mTires[id].mFrictionVsSlipGraph[1][0]);
}
/////////////////////////////
void PxVehicleWheels4SimData::setSuspTravelDirection(const PxU32 id, const PxVec3& dir)
{
PX_CHECK_AND_RETURN(id<4, "Illegal suspension id");
PX_CHECK_AND_RETURN(dir.magnitude()>0.999f && dir.magnitude()<1.0001f, "Suspension travel dir must be unit vector");
mSuspDownwardTravelDirections[id]=dir;
}
/////////////////////////////
void PxVehicleWheels4SimData::setSuspForceAppPointOffset(const PxU32 id, const PxVec3& offset)
{
PX_CHECK_AND_RETURN(id<4, "Illegal suspension id");
PX_CHECK_AND_RETURN(offset.magnitude()>0, "Susp force app point must be offset from centre of mass");
mSuspForceAppPointOffsets[id]=offset;
}
/////////////////////////////
void PxVehicleWheels4SimData::setTireForceAppPointOffset(const PxU32 id, const PxVec3& offset)
{
PX_CHECK_AND_RETURN(id<4, "Illegal tire id");
PX_CHECK_AND_RETURN(offset.magnitude()>0, "Tire force app point must be offset from centre of mass");
mTireForceAppPointOffsets[id]=offset;
}
/////////////////////////////
void PxVehicleWheels4SimData::setWheelCentreOffset(const PxU32 id, const PxVec3& offset)
{
PX_CHECK_AND_RETURN(id<4, "Illegal wheel id");
PX_CHECK_AND_RETURN(offset.magnitude()>0, "Tire force app point must be offset from centre of mass");
mWheelCentreOffsets[id]=offset;
}
/////////////////////////////
void PxVehicleWheels4SimData::setWheelShapeMapping(const PxU32 id, const PxI32 shapeId)
{
PX_CHECK_AND_RETURN(id<4, "Illegal wheel id");
PX_CHECK_AND_RETURN((-1==shapeId) || (PxU32(shapeId) < PX_MAX_U8), "Illegal shapeId: must be -1 or less than PX_MAX_U8");
mWheelShapeMap[id] = PxTo8(-1!=shapeId ? shapeId : PX_MAX_U8);
}
/////////////////////////////
void PxVehicleWheels4SimData::setSceneQueryFilterData(const PxU32 id, const PxFilterData& sqFilterData)
{
PX_CHECK_AND_RETURN(id<4, "Illegal wheel id");
mSqFilterData[id]=sqFilterData;
}
} //namespace physx
| 9,939 |
C++
| 51.315789 | 223 | 0.754804 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleSuspWheelTire4.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_VEHICLE_SUSP_WHEEL_TIRE4_H
#define PX_VEHICLE_SUSP_WHEEL_TIRE4_H
/** \addtogroup vehicle
@{
*/
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "foundation/PxVec4.h"
#include "foundation/PxTransform.h"
#include "foundation/PxIO.h"
#include "geometry/PxGeometryHelpers.h"
#include "vehicle/PxVehicleComponents.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "extensions/PxSceneQueryExt.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxMaterial;
class PxShape;
class PxVehicleWheels4SimData
{
public:
friend class PxVehicleUpdate;
PxVehicleWheels4SimData();
bool isValid(const PxU32 id) const;
static void getBinaryMetaData(PxOutputStream& stream);
public:
PX_FORCE_INLINE const PxVehicleSuspensionData& getSuspensionData(const PxU32 id) const {return mSuspensions[id];}
PX_FORCE_INLINE const PxVehicleWheelData& getWheelData(const PxU32 id) const {return mWheels[id];}
PX_FORCE_INLINE const PxVehicleTireData& getTireData(const PxU32 id) const {return mTires[id];}
PX_FORCE_INLINE const PxVec3& getSuspTravelDirection(const PxU32 id) const {return mSuspDownwardTravelDirections[id];}
PX_FORCE_INLINE const PxVec3& getSuspForceAppPointOffset(const PxU32 id) const {return mSuspForceAppPointOffsets[id];}
PX_FORCE_INLINE const PxVec3& getTireForceAppPointOffset(const PxU32 id) const {return mTireForceAppPointOffsets[id];}
PX_FORCE_INLINE const PxVec3& getWheelCentreOffset(const PxU32 id) const {return mWheelCentreOffsets[id];}
PX_FORCE_INLINE PxI32 getWheelShapeMapping(const PxU32 id) const {return (PX_MAX_U8 != mWheelShapeMap[id]) ? mWheelShapeMap[id] : -1;}
PX_FORCE_INLINE const PxFilterData& getSceneQueryFilterData(const PxU32 id) const {return mSqFilterData[id];}
PX_FORCE_INLINE const PxReal* getTireRestLoadsArray() const {return mTireRestLoads;}
PX_FORCE_INLINE const PxReal* getRecipTireRestLoadsArray() const {return mRecipTireRestLoads;}
void setSuspensionData (const PxU32 id, const PxVehicleSuspensionData& susp);
void setWheelData (const PxU32 id, const PxVehicleWheelData& susp);
void setTireData (const PxU32 id, const PxVehicleTireData& tire);
void setSuspTravelDirection (const PxU32 id, const PxVec3& dir);
void setSuspForceAppPointOffset (const PxU32 id, const PxVec3& offset);
void setTireForceAppPointOffset (const PxU32 id, const PxVec3& offset);
void setWheelCentreOffset (const PxU32 id, const PxVec3& offset);
void setWheelShapeMapping (const PxU32 id, const PxI32 shapeId);
void setSceneQueryFilterData (const PxU32 id, const PxFilterData& sqFilterData);
private:
/**
\brief Suspension simulation data
@see setSuspensionData, getSuspensionData
*/
PxVehicleSuspensionData mSuspensions[4];
/**
\brief Wheel simulation data
@see setWheelData, getWheelData
*/
PxVehicleWheelData mWheels[4];
/**
\brief Tire simulation data
@see setTireData, getTireData
*/
PxVehicleTireData mTires[4];
/**
\brief Direction of suspension travel, pointing downwards.
*/
PxVec3 mSuspDownwardTravelDirections[4];
/**
\brief Application point of suspension force specified as an offset from the rigid body centre of mass.
*/
PxVec3 mSuspForceAppPointOffsets[4]; //Offset from cm
/**
\brief Application point of tire forces specified as an offset from the rigid body centre of mass.
*/
PxVec3 mTireForceAppPointOffsets[4]; //Offset from cm
/**
\brief Position of wheel center specified as an offset from the rigid body centre of mass.
*/
PxVec3 mWheelCentreOffsets[4]; //Offset from cm
/**
\brief Normalized tire load on each tire (load/rest load) at zero suspension jounce under gravity.
*/
PxReal mTireRestLoads[4];
/**
\brief Reciprocal normalized tire load on each tire at zero suspension jounce under gravity.
*/
PxReal mRecipTireRestLoads[4];
/**
\brief Scene query filter data used by each suspension line.
Anything relating to the actor belongs in PxVehicleWheels.
*/
PxFilterData mSqFilterData[4];
/**
\brief Mapping between wheel id and shape id.
The PxShape that corresponds to the ith wheel can be found with
If mWheelShapeMap[i]<0 then the wheel has no corresponding shape.
Otherwise, the shape corresponds to:
PxShape* shapeBuffer[1];
mActor->getShapes(shapeBuffer,1,mWheelShapeMap[i]);
Anything relating to the actor belongs in PxVehicleWheels.
*/
PxU8 mWheelShapeMap[4];
PxU32 mPad[3];
};
PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxVehicleWheels4SimData) & 15));
class PxVehicleWheels4DynData
{
public:
friend class PxVehicleUpdate;
PxVehicleWheels4DynData()
: mRaycastResults(NULL),
mSweepResults(NULL)
{
setToRestState();
}
~PxVehicleWheels4DynData()
{
}
bool isValid() const {return true;}
static void getBinaryMetaData(PxOutputStream& stream);
void setToRestState()
{
for(PxU32 i=0;i<4;i++)
{
mWheelSpeeds[i] = 0.0f;
mCorrectedWheelSpeeds[i] = 0.0f;
mWheelRotationAngles[i] = 0.0f;
mTireLowForwardSpeedTimers[i] = 0.0f;
mTireLowSideSpeedTimers[i] = 0.0f;
mJounces[i] = PX_MAX_F32;
mSteerAngles[i] = 0.0f;
mVehicleConstraints->mData.mStickyTireForwardData.mActiveFlags[i] = false;
mVehicleConstraints->mData.mStickyTireSideData.mActiveFlags[i] = false;
mVehicleConstraints->mData.mSuspLimitData.mActiveFlags[i] = false;
}
PxMemZero(mQueryOrCachedHitResults, sizeof(SuspLineSweep));
mRaycastResults = NULL;
mSweepResults = NULL;
mHasCachedRaycastHitPlane = false;
}
void setInternalDynamicsToZero()
{
for(PxU32 i=0;i<4;i++)
{
mWheelSpeeds[i] = 0.0f;
mCorrectedWheelSpeeds[i] = 0.0f;
mJounces[i] = PX_MAX_F32; //Ensure that the jounce speed is zero when the car wakes up again.
mSteerAngles[i] = 0.0f;
}
}
void setTireContacts(const PxU32* cachedHitCounts, const PxPlane* cachedHitPlanes, const PxF32* cachedFrictionMultipliers, const PxTireContactIntersectionMethod::Enum* cachedQueryTypes)
{
mHasCachedRaycastHitPlane = true;
mRaycastResults = NULL;
mSweepResults = NULL;
PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult* cachedRaycastHitResults =
reinterpret_cast<PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult*>(mQueryOrCachedHitResults);
for (PxU32 i = 0; i < 4; i++)
{
cachedRaycastHitResults->mCounts[i] = PxU16(cachedHitCounts[i]);
cachedRaycastHitResults->mPlanes[i] = cachedHitPlanes[i];
cachedRaycastHitResults->mDistances[i] = 1.0f;
cachedRaycastHitResults->mFrictionMultipliers[i] = cachedFrictionMultipliers[i];
cachedRaycastHitResults->mQueryTypes[i] = ((cachedQueryTypes[i] == PxTireContactIntersectionMethod::eRAY) ? 0 : 1);
}
}
/**
\brief Rotation speeds of wheels
@see PxVehicle4WSetToRestState, PxVehicle4WGetWheelRotationSpeed, PxVehicle4WGetEngineRotationSpeed
*/
PxReal mWheelSpeeds[4];
/**
\brief Rotation speeds of wheels used to update the wheel rotation angles.
*/
PxReal mCorrectedWheelSpeeds[4];
/**
\brief Reported rotation angle about rolling axis.
@see PxVehicle4WSetToRestState, PxVehicle4WGetWheelRotationAngle
*/
PxReal mWheelRotationAngles[4];
/**
\brief Timers used to trigger sticky friction to hold the car perfectly at rest.
\note Used only internally.
*/
PxReal mTireLowForwardSpeedTimers[4];
/**
\brief Timers used to trigger sticky friction to hold the car perfectly at rest.
\note Used only internally.
*/
PxReal mTireLowSideSpeedTimers[4];
/**
\brief Previous suspension jounce.
\note Used only internally to compute the jounce speed by comparing cached jounce and latest jounce.
*/
PxReal mJounces[4];
/**
\brief Previous steer angle
\note Used only internally to compute the rotation of the sweep pose.
*/
PxReal mSteerAngles[4];
struct SuspLineSweep
{
/**
\brief Geometry suspension line sweep used in most recent scene query.
@see PxVehicleSuspensionSweeps
*/
PxGeometryHolder mGometries[4];
/**
\brief Start poses of suspension line sweep used in most recent scene query.
@see PxVehicleSuspensionSweeps
*/
PxTransform mStartPose[4];
/**
\brief Directions of suspension line sweeps used in most recent scene query.
@see PxVehicleSuspensionSweeps
*/
PxVec3 mDirs[4];
/**
\brief Lengths of suspension line sweeps used in most recent scene query.
@see PxVehicleSuspensionSweeps
*/
PxReal mLengths[4];
};
struct SuspLineRaycast
{
/**
\brief Start point of suspension line raycasts used in most recent scene query.
@see PxVehicleSuspensionRaycasts
*/
PxVec3 mStarts[4];
/**
\brief Directions of suspension line raycasts used in most recent scene query.
@see PxVehicleSuspensionRaycasts
*/
PxVec3 mDirs[4];
/**
\brief Lengths of suspension line raycasts used in most recent scene query.
@see PxVehicleSuspensionRaycasts
*/
PxReal mLengths[4];
PxU32 mPad[16];
};
struct CachedSuspLineSceneQuerytHitResult
{
/**
\brief Cached raycast hit planes. These are the planes found from the last scene queries.
@see PxVehicleSuspensionRaycasts, PxVehicleSuspensionSweeps
*/
PxPlane mPlanes[4];
/**
\brief Cached friction.
@see PxVehicleSuspensionRaycasts, PxVehicleSuspensionSweeps
*/
PxF32 mFrictionMultipliers[4];
/**
\brief Cached raycast hit distance. These are the hit distances found from the last scene queries.
*/
PxF32 mDistances[4];
/**
\brief Cached raycast hit counts. These are the hit counts found from the last scene queries.
@see PxVehicleSuspensionRaycasts, , PxVehicleSuspensionSweeps
*/
PxU16 mCounts[4];
/**
\brief Store 0 if cached results are from raycasts, store 1 if cached results are from sweeps.
*/
PxU16 mQueryTypes[4];
PxU32 mPad1[16];
};
/**
\brief We either have a fresh raycast that was just performed or a cached raycast result that will be used if no raycast was just performed.
*/
PxU8 mQueryOrCachedHitResults[sizeof(SuspLineSweep)];
/**
\brief Used only internally.
*/
void setVehicleConstraintShader(PxVehicleConstraintShader* shader) {mVehicleConstraints=shader;}
PxVehicleConstraintShader& getVehicletConstraintShader() const {return *mVehicleConstraints;}
private:
//Susp limits and sticky tire friction for all wheels.
PxVehicleConstraintShader* mVehicleConstraints;
public:
/**
\brief Set by PxVehicleSuspensionRaycasts
@see PxVehicleSuspensionRaycasts
*/
const PxRaycastBuffer* mRaycastResults;
/**
\brief Set by PxVehicleSuspensionSweeps
@see PxVehicleSuspensionSweeps
*/
const PxSweepBuffer* mSweepResults;
/**
\brief Set true if a raycast hit plane has been recorded and cached.
This requires a raycast to be performed and then followed by PxVehicleUpdates
at least once. Reset to false in setToRestState.
*/
bool mHasCachedRaycastHitPlane;
#if PX_P64_FAMILY
PxU32 mPad[12];
#endif
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleWheels4DynData) & 15));
PX_COMPILE_TIME_ASSERT((0 == (sizeof(PxVehicleWheels4DynData::SuspLineSweep) & 0x0f)));
PX_COMPILE_TIME_ASSERT(sizeof(PxVehicleWheels4DynData::SuspLineRaycast) <= sizeof(PxVehicleWheels4DynData::SuspLineSweep));
PX_COMPILE_TIME_ASSERT(sizeof(PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult) <= sizeof(PxVehicleWheels4DynData::SuspLineSweep));
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 13,105 |
C
| 31.04401 | 186 | 0.751927 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/physxmetadata/src/PxVehicleMetaDataObjects.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxPhysicsAPI.h"
#include "extensions/PxExtensionsAPI.h"
#include "PxVehicleMetaDataObjects.h"
#include "PxExtensionMetaDataObjects.h"
namespace physx
{
inline void SetMFrictionVsSlipGraph( PxVehicleTireData* inTireData, PxU32 idx1, PxU32 idx2, PxReal val ) { inTireData->mFrictionVsSlipGraph[idx1][idx2] = val; }
inline PxReal GetMFrictionVsSlipGraph( const PxVehicleTireData* inTireData, PxU32 idx1, PxU32 idx2 )
{
return inTireData->mFrictionVsSlipGraph[idx1][idx2];
}
PX_PHYSX_CORE_API MFrictionVsSlipGraphProperty::MFrictionVsSlipGraphProperty()
: PxExtendedDualIndexedPropertyInfo<PxVehiclePropertyInfoName::PxVehicleTireData_MFrictionVsSlipGraph
, PxVehicleTireData
, PxU32
, PxU32
, PxReal> ( "MFrictionVsSlipGraph", SetMFrictionVsSlipGraph, GetMFrictionVsSlipGraph, 3, 2 )
{
}
inline PxU32 GetNbWheels( const PxVehicleWheels* inStats ) { return inStats->mWheelsSimData.getNbWheels(); }
inline PxU32 GetNbTorqueCurvePair( const PxVehicleEngineData* inStats ) { return inStats->mTorqueCurve.getNbDataPairs(); }
inline PxReal getXTorqueCurvePair( const PxVehicleEngineData* inStats, PxU32 index)
{
return inStats->mTorqueCurve.getX(index);
}
inline PxReal getYTorqueCurvePair( const PxVehicleEngineData* inStats, PxU32 index)
{
return inStats->mTorqueCurve.getY(index);
}
void addTorqueCurvePair(PxVehicleEngineData* inStats, const PxReal x, const PxReal y)
{
inStats->mTorqueCurve.addPair(x, y);
}
void clearTorqueCurvePair(PxVehicleEngineData* inStats)
{
inStats->mTorqueCurve.clear();
}
PX_PHYSX_CORE_API MTorqueCurveProperty::MTorqueCurveProperty()
: PxFixedSizeLookupTablePropertyInfo<PxVehiclePropertyInfoName::PxVehicleEngineData_MTorqueCurve
, PxVehicleEngineData
, PxU32
, PxReal>("MTorqueCurve", getXTorqueCurvePair, getYTorqueCurvePair, GetNbTorqueCurvePair, addTorqueCurvePair, clearTorqueCurvePair)
{
}
}
| 3,683 |
C++
| 41.837209 | 161 | 0.76378 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/physxmetadata/src/PxVehicleAutoGeneratedMetaDataObjects.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// This code is auto-generated by the PhysX Clang metadata generator. Do not edit or be
// prepared for your edits to be quietly ignored next time the clang metadata generator is
// run. You can find the most recent version of clang metadata generator by contacting
// Chris Nuernberger <[email protected]> or Dilip or Adam.
// The source code for the generate was at one time checked into:
// physx/PhysXMetaDataGenerator/llvm/tools/clang/lib/Frontend/PhysXMetaDataAction.cpp
#include "foundation/PxPreprocessor.h"
#if PX_LINUX && PX_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-identifier"
#endif
#include "PxVehicleMetaDataObjects.h"
#if PX_LINUX && PX_CLANG
#pragma clang diagnostic pop
#endif
#include "PxMetaDataCppPrefix.h"
#include "PxVehicleSuspWheelTire4.h"
using namespace physx;
inline PxVec3 getPxVehicleChassisDataMMOI( const PxVehicleChassisData* inOwner ) { return inOwner->mMOI; }
inline void setPxVehicleChassisDataMMOI( PxVehicleChassisData* inOwner, PxVec3 inData) { inOwner->mMOI = inData; }
inline PxReal getPxVehicleChassisDataMMass( const PxVehicleChassisData* inOwner ) { return inOwner->mMass; }
inline void setPxVehicleChassisDataMMass( PxVehicleChassisData* inOwner, PxReal inData) { inOwner->mMass = inData; }
inline PxVec3 getPxVehicleChassisDataMCMOffset( const PxVehicleChassisData* inOwner ) { return inOwner->mCMOffset; }
inline void setPxVehicleChassisDataMCMOffset( PxVehicleChassisData* inOwner, PxVec3 inData) { inOwner->mCMOffset = inData; }
PxVehicleChassisDataGeneratedInfo::PxVehicleChassisDataGeneratedInfo()
: MMOI( "MMOI", setPxVehicleChassisDataMMOI, getPxVehicleChassisDataMMOI )
, MMass( "MMass", setPxVehicleChassisDataMMass, getPxVehicleChassisDataMMass )
, MCMOffset( "MCMOffset", setPxVehicleChassisDataMCMOffset, getPxVehicleChassisDataMCMOffset )
{}
PxVehicleChassisDataGeneratedValues::PxVehicleChassisDataGeneratedValues( const PxVehicleChassisData* inSource )
:MMOI( inSource->mMOI )
,MMass( inSource->mMass )
,MCMOffset( inSource->mCMOffset )
{
PX_UNUSED(inSource);
}
PxReal getPxVehicleEngineData_RecipMOI( const PxVehicleEngineData* inObj ) { return inObj->getRecipMOI(); }
PxReal getPxVehicleEngineData_RecipMaxOmega( const PxVehicleEngineData* inObj ) { return inObj->getRecipMaxOmega(); }
inline PxReal getPxVehicleEngineDataMMOI( const PxVehicleEngineData* inOwner ) { return inOwner->mMOI; }
inline void setPxVehicleEngineDataMMOI( PxVehicleEngineData* inOwner, PxReal inData) { inOwner->mMOI = inData; }
inline PxReal getPxVehicleEngineDataMPeakTorque( const PxVehicleEngineData* inOwner ) { return inOwner->mPeakTorque; }
inline void setPxVehicleEngineDataMPeakTorque( PxVehicleEngineData* inOwner, PxReal inData) { inOwner->mPeakTorque = inData; }
inline PxReal getPxVehicleEngineDataMMaxOmega( const PxVehicleEngineData* inOwner ) { return inOwner->mMaxOmega; }
inline void setPxVehicleEngineDataMMaxOmega( PxVehicleEngineData* inOwner, PxReal inData) { inOwner->mMaxOmega = inData; }
inline PxReal getPxVehicleEngineDataMDampingRateFullThrottle( const PxVehicleEngineData* inOwner ) { return inOwner->mDampingRateFullThrottle; }
inline void setPxVehicleEngineDataMDampingRateFullThrottle( PxVehicleEngineData* inOwner, PxReal inData) { inOwner->mDampingRateFullThrottle = inData; }
inline PxReal getPxVehicleEngineDataMDampingRateZeroThrottleClutchEngaged( const PxVehicleEngineData* inOwner ) { return inOwner->mDampingRateZeroThrottleClutchEngaged; }
inline void setPxVehicleEngineDataMDampingRateZeroThrottleClutchEngaged( PxVehicleEngineData* inOwner, PxReal inData) { inOwner->mDampingRateZeroThrottleClutchEngaged = inData; }
inline PxReal getPxVehicleEngineDataMDampingRateZeroThrottleClutchDisengaged( const PxVehicleEngineData* inOwner ) { return inOwner->mDampingRateZeroThrottleClutchDisengaged; }
inline void setPxVehicleEngineDataMDampingRateZeroThrottleClutchDisengaged( PxVehicleEngineData* inOwner, PxReal inData) { inOwner->mDampingRateZeroThrottleClutchDisengaged = inData; }
PxVehicleEngineDataGeneratedInfo::PxVehicleEngineDataGeneratedInfo()
: RecipMOI( "RecipMOI", getPxVehicleEngineData_RecipMOI)
, RecipMaxOmega( "RecipMaxOmega", getPxVehicleEngineData_RecipMaxOmega)
, MMOI( "MMOI", setPxVehicleEngineDataMMOI, getPxVehicleEngineDataMMOI )
, MPeakTorque( "MPeakTorque", setPxVehicleEngineDataMPeakTorque, getPxVehicleEngineDataMPeakTorque )
, MMaxOmega( "MMaxOmega", setPxVehicleEngineDataMMaxOmega, getPxVehicleEngineDataMMaxOmega )
, MDampingRateFullThrottle( "MDampingRateFullThrottle", setPxVehicleEngineDataMDampingRateFullThrottle, getPxVehicleEngineDataMDampingRateFullThrottle )
, MDampingRateZeroThrottleClutchEngaged( "MDampingRateZeroThrottleClutchEngaged", setPxVehicleEngineDataMDampingRateZeroThrottleClutchEngaged, getPxVehicleEngineDataMDampingRateZeroThrottleClutchEngaged )
, MDampingRateZeroThrottleClutchDisengaged( "MDampingRateZeroThrottleClutchDisengaged", setPxVehicleEngineDataMDampingRateZeroThrottleClutchDisengaged, getPxVehicleEngineDataMDampingRateZeroThrottleClutchDisengaged )
{}
PxVehicleEngineDataGeneratedValues::PxVehicleEngineDataGeneratedValues( const PxVehicleEngineData* inSource )
:RecipMOI( getPxVehicleEngineData_RecipMOI( inSource ) )
,RecipMaxOmega( getPxVehicleEngineData_RecipMaxOmega( inSource ) )
,MMOI( inSource->mMOI )
,MPeakTorque( inSource->mPeakTorque )
,MMaxOmega( inSource->mMaxOmega )
,MDampingRateFullThrottle( inSource->mDampingRateFullThrottle )
,MDampingRateZeroThrottleClutchEngaged( inSource->mDampingRateZeroThrottleClutchEngaged )
,MDampingRateZeroThrottleClutchDisengaged( inSource->mDampingRateZeroThrottleClutchDisengaged )
{
PX_UNUSED(inSource);
}
void setPxVehicleGearsData_GearRatio( PxVehicleGearsData* inObj, PxVehicleGearsData::Enum inIndex, PxReal inArg ){ inObj->setGearRatio( inIndex, inArg ); }
PxReal getPxVehicleGearsData_GearRatio( const PxVehicleGearsData* inObj, PxVehicleGearsData::Enum inIndex ) { return inObj->getGearRatio( inIndex ); }
inline PxReal getPxVehicleGearsDataMFinalRatio( const PxVehicleGearsData* inOwner ) { return inOwner->mFinalRatio; }
inline void setPxVehicleGearsDataMFinalRatio( PxVehicleGearsData* inOwner, PxReal inData) { inOwner->mFinalRatio = inData; }
inline PxU32 getPxVehicleGearsDataMNbRatios( const PxVehicleGearsData* inOwner ) { return inOwner->mNbRatios; }
inline void setPxVehicleGearsDataMNbRatios( PxVehicleGearsData* inOwner, PxU32 inData) { inOwner->mNbRatios = inData; }
inline PxReal getPxVehicleGearsDataMSwitchTime( const PxVehicleGearsData* inOwner ) { return inOwner->mSwitchTime; }
inline void setPxVehicleGearsDataMSwitchTime( PxVehicleGearsData* inOwner, PxReal inData) { inOwner->mSwitchTime = inData; }
PxVehicleGearsDataGeneratedInfo::PxVehicleGearsDataGeneratedInfo()
: GearRatio( "GearRatio", setPxVehicleGearsData_GearRatio, getPxVehicleGearsData_GearRatio)
, MFinalRatio( "MFinalRatio", setPxVehicleGearsDataMFinalRatio, getPxVehicleGearsDataMFinalRatio )
, MNbRatios( "MNbRatios", setPxVehicleGearsDataMNbRatios, getPxVehicleGearsDataMNbRatios )
, MSwitchTime( "MSwitchTime", setPxVehicleGearsDataMSwitchTime, getPxVehicleGearsDataMSwitchTime )
{}
PxVehicleGearsDataGeneratedValues::PxVehicleGearsDataGeneratedValues( const PxVehicleGearsData* inSource )
:MFinalRatio( inSource->mFinalRatio )
,MNbRatios( inSource->mNbRatios )
,MSwitchTime( inSource->mSwitchTime )
{
PX_UNUSED(inSource);
for ( PxU32 idx = 0; idx < static_cast<PxU32>( physx::PxVehicleGearsData::eGEARSRATIO_COUNT ); ++idx )
GearRatio[idx] = getPxVehicleGearsData_GearRatio( inSource, static_cast< PxVehicleGearsData::Enum >( idx ) );
}
void setPxVehicleAutoBoxData_Latency( PxVehicleAutoBoxData* inObj, const PxReal inArg){ inObj->setLatency( inArg ); }
PxReal getPxVehicleAutoBoxData_Latency( const PxVehicleAutoBoxData* inObj ) { return inObj->getLatency(); }
void setPxVehicleAutoBoxData_UpRatios( PxVehicleAutoBoxData* inObj, PxVehicleGearsData::Enum inIndex, PxReal inArg ){ inObj->setUpRatios( inIndex, inArg ); }
PxReal getPxVehicleAutoBoxData_UpRatios( const PxVehicleAutoBoxData* inObj, PxVehicleGearsData::Enum inIndex ) { return inObj->getUpRatios( inIndex ); }
void setPxVehicleAutoBoxData_DownRatios( PxVehicleAutoBoxData* inObj, PxVehicleGearsData::Enum inIndex, PxReal inArg ){ inObj->setDownRatios( inIndex, inArg ); }
PxReal getPxVehicleAutoBoxData_DownRatios( const PxVehicleAutoBoxData* inObj, PxVehicleGearsData::Enum inIndex ) { return inObj->getDownRatios( inIndex ); }
PxVehicleAutoBoxDataGeneratedInfo::PxVehicleAutoBoxDataGeneratedInfo()
: Latency( "Latency", setPxVehicleAutoBoxData_Latency, getPxVehicleAutoBoxData_Latency)
, UpRatios( "UpRatios", setPxVehicleAutoBoxData_UpRatios, getPxVehicleAutoBoxData_UpRatios)
, DownRatios( "DownRatios", setPxVehicleAutoBoxData_DownRatios, getPxVehicleAutoBoxData_DownRatios)
{}
PxVehicleAutoBoxDataGeneratedValues::PxVehicleAutoBoxDataGeneratedValues( const PxVehicleAutoBoxData* inSource )
:Latency( getPxVehicleAutoBoxData_Latency( inSource ) )
{
PX_UNUSED(inSource);
for ( PxU32 idx = 0; idx < static_cast<PxU32>( physx::PxVehicleGearsData::eGEARSRATIO_COUNT ); ++idx )
UpRatios[idx] = getPxVehicleAutoBoxData_UpRatios( inSource, static_cast< PxVehicleGearsData::Enum >( idx ) );
for ( PxU32 idx = 0; idx < static_cast<PxU32>( physx::PxVehicleGearsData::eGEARSRATIO_COUNT ); ++idx )
DownRatios[idx] = getPxVehicleAutoBoxData_DownRatios( inSource, static_cast< PxVehicleGearsData::Enum >( idx ) );
}
inline PxReal getPxVehicleDifferential4WDataMFrontRearSplit( const PxVehicleDifferential4WData* inOwner ) { return inOwner->mFrontRearSplit; }
inline void setPxVehicleDifferential4WDataMFrontRearSplit( PxVehicleDifferential4WData* inOwner, PxReal inData) { inOwner->mFrontRearSplit = inData; }
inline PxReal getPxVehicleDifferential4WDataMFrontLeftRightSplit( const PxVehicleDifferential4WData* inOwner ) { return inOwner->mFrontLeftRightSplit; }
inline void setPxVehicleDifferential4WDataMFrontLeftRightSplit( PxVehicleDifferential4WData* inOwner, PxReal inData) { inOwner->mFrontLeftRightSplit = inData; }
inline PxReal getPxVehicleDifferential4WDataMRearLeftRightSplit( const PxVehicleDifferential4WData* inOwner ) { return inOwner->mRearLeftRightSplit; }
inline void setPxVehicleDifferential4WDataMRearLeftRightSplit( PxVehicleDifferential4WData* inOwner, PxReal inData) { inOwner->mRearLeftRightSplit = inData; }
inline PxReal getPxVehicleDifferential4WDataMCentreBias( const PxVehicleDifferential4WData* inOwner ) { return inOwner->mCentreBias; }
inline void setPxVehicleDifferential4WDataMCentreBias( PxVehicleDifferential4WData* inOwner, PxReal inData) { inOwner->mCentreBias = inData; }
inline PxReal getPxVehicleDifferential4WDataMFrontBias( const PxVehicleDifferential4WData* inOwner ) { return inOwner->mFrontBias; }
inline void setPxVehicleDifferential4WDataMFrontBias( PxVehicleDifferential4WData* inOwner, PxReal inData) { inOwner->mFrontBias = inData; }
inline PxReal getPxVehicleDifferential4WDataMRearBias( const PxVehicleDifferential4WData* inOwner ) { return inOwner->mRearBias; }
inline void setPxVehicleDifferential4WDataMRearBias( PxVehicleDifferential4WData* inOwner, PxReal inData) { inOwner->mRearBias = inData; }
inline PxVehicleDifferential4WData::Enum getPxVehicleDifferential4WDataMType( const PxVehicleDifferential4WData* inOwner ) { return inOwner->mType; }
inline void setPxVehicleDifferential4WDataMType( PxVehicleDifferential4WData* inOwner, PxVehicleDifferential4WData::Enum inData) { inOwner->mType = inData; }
PxVehicleDifferential4WDataGeneratedInfo::PxVehicleDifferential4WDataGeneratedInfo()
: MFrontRearSplit( "MFrontRearSplit", setPxVehicleDifferential4WDataMFrontRearSplit, getPxVehicleDifferential4WDataMFrontRearSplit )
, MFrontLeftRightSplit( "MFrontLeftRightSplit", setPxVehicleDifferential4WDataMFrontLeftRightSplit, getPxVehicleDifferential4WDataMFrontLeftRightSplit )
, MRearLeftRightSplit( "MRearLeftRightSplit", setPxVehicleDifferential4WDataMRearLeftRightSplit, getPxVehicleDifferential4WDataMRearLeftRightSplit )
, MCentreBias( "MCentreBias", setPxVehicleDifferential4WDataMCentreBias, getPxVehicleDifferential4WDataMCentreBias )
, MFrontBias( "MFrontBias", setPxVehicleDifferential4WDataMFrontBias, getPxVehicleDifferential4WDataMFrontBias )
, MRearBias( "MRearBias", setPxVehicleDifferential4WDataMRearBias, getPxVehicleDifferential4WDataMRearBias )
, MType( "MType", setPxVehicleDifferential4WDataMType, getPxVehicleDifferential4WDataMType )
{}
PxVehicleDifferential4WDataGeneratedValues::PxVehicleDifferential4WDataGeneratedValues( const PxVehicleDifferential4WData* inSource )
:MFrontRearSplit( inSource->mFrontRearSplit )
,MFrontLeftRightSplit( inSource->mFrontLeftRightSplit )
,MRearLeftRightSplit( inSource->mRearLeftRightSplit )
,MCentreBias( inSource->mCentreBias )
,MFrontBias( inSource->mFrontBias )
,MRearBias( inSource->mRearBias )
,MType( inSource->mType )
{
PX_UNUSED(inSource);
}
void setPxVehicleDifferentialNWData_DrivenWheelStatus( PxVehicleDifferentialNWData* inObj, PxU32 inArg){ inObj->setDrivenWheelStatus( inArg ); }
PxU32 getPxVehicleDifferentialNWData_DrivenWheelStatus( const PxVehicleDifferentialNWData* inObj ) { return inObj->getDrivenWheelStatus(); }
PxVehicleDifferentialNWDataGeneratedInfo::PxVehicleDifferentialNWDataGeneratedInfo()
: DrivenWheelStatus( "DrivenWheelStatus", setPxVehicleDifferentialNWData_DrivenWheelStatus, getPxVehicleDifferentialNWData_DrivenWheelStatus)
{}
PxVehicleDifferentialNWDataGeneratedValues::PxVehicleDifferentialNWDataGeneratedValues( const PxVehicleDifferentialNWData* inSource )
:DrivenWheelStatus( getPxVehicleDifferentialNWData_DrivenWheelStatus( inSource ) )
{
PX_UNUSED(inSource);
}
inline PxReal getPxVehicleAckermannGeometryDataMAccuracy( const PxVehicleAckermannGeometryData* inOwner ) { return inOwner->mAccuracy; }
inline void setPxVehicleAckermannGeometryDataMAccuracy( PxVehicleAckermannGeometryData* inOwner, PxReal inData) { inOwner->mAccuracy = inData; }
inline PxReal getPxVehicleAckermannGeometryDataMFrontWidth( const PxVehicleAckermannGeometryData* inOwner ) { return inOwner->mFrontWidth; }
inline void setPxVehicleAckermannGeometryDataMFrontWidth( PxVehicleAckermannGeometryData* inOwner, PxReal inData) { inOwner->mFrontWidth = inData; }
inline PxReal getPxVehicleAckermannGeometryDataMRearWidth( const PxVehicleAckermannGeometryData* inOwner ) { return inOwner->mRearWidth; }
inline void setPxVehicleAckermannGeometryDataMRearWidth( PxVehicleAckermannGeometryData* inOwner, PxReal inData) { inOwner->mRearWidth = inData; }
inline PxReal getPxVehicleAckermannGeometryDataMAxleSeparation( const PxVehicleAckermannGeometryData* inOwner ) { return inOwner->mAxleSeparation; }
inline void setPxVehicleAckermannGeometryDataMAxleSeparation( PxVehicleAckermannGeometryData* inOwner, PxReal inData) { inOwner->mAxleSeparation = inData; }
PxVehicleAckermannGeometryDataGeneratedInfo::PxVehicleAckermannGeometryDataGeneratedInfo()
: MAccuracy( "MAccuracy", setPxVehicleAckermannGeometryDataMAccuracy, getPxVehicleAckermannGeometryDataMAccuracy )
, MFrontWidth( "MFrontWidth", setPxVehicleAckermannGeometryDataMFrontWidth, getPxVehicleAckermannGeometryDataMFrontWidth )
, MRearWidth( "MRearWidth", setPxVehicleAckermannGeometryDataMRearWidth, getPxVehicleAckermannGeometryDataMRearWidth )
, MAxleSeparation( "MAxleSeparation", setPxVehicleAckermannGeometryDataMAxleSeparation, getPxVehicleAckermannGeometryDataMAxleSeparation )
{}
PxVehicleAckermannGeometryDataGeneratedValues::PxVehicleAckermannGeometryDataGeneratedValues( const PxVehicleAckermannGeometryData* inSource )
:MAccuracy( inSource->mAccuracy )
,MFrontWidth( inSource->mFrontWidth )
,MRearWidth( inSource->mRearWidth )
,MAxleSeparation( inSource->mAxleSeparation )
{
PX_UNUSED(inSource);
}
inline PxReal getPxVehicleClutchDataMStrength( const PxVehicleClutchData* inOwner ) { return inOwner->mStrength; }
inline void setPxVehicleClutchDataMStrength( PxVehicleClutchData* inOwner, PxReal inData) { inOwner->mStrength = inData; }
inline PxVehicleClutchAccuracyMode::Enum getPxVehicleClutchDataMAccuracyMode( const PxVehicleClutchData* inOwner ) { return inOwner->mAccuracyMode; }
inline void setPxVehicleClutchDataMAccuracyMode( PxVehicleClutchData* inOwner, PxVehicleClutchAccuracyMode::Enum inData) { inOwner->mAccuracyMode = inData; }
inline PxU32 getPxVehicleClutchDataMEstimateIterations( const PxVehicleClutchData* inOwner ) { return inOwner->mEstimateIterations; }
inline void setPxVehicleClutchDataMEstimateIterations( PxVehicleClutchData* inOwner, PxU32 inData) { inOwner->mEstimateIterations = inData; }
PxVehicleClutchDataGeneratedInfo::PxVehicleClutchDataGeneratedInfo()
: MStrength( "MStrength", setPxVehicleClutchDataMStrength, getPxVehicleClutchDataMStrength )
, MAccuracyMode( "MAccuracyMode", setPxVehicleClutchDataMAccuracyMode, getPxVehicleClutchDataMAccuracyMode )
, MEstimateIterations( "MEstimateIterations", setPxVehicleClutchDataMEstimateIterations, getPxVehicleClutchDataMEstimateIterations )
{}
PxVehicleClutchDataGeneratedValues::PxVehicleClutchDataGeneratedValues( const PxVehicleClutchData* inSource )
:MStrength( inSource->mStrength )
,MAccuracyMode( inSource->mAccuracyMode )
,MEstimateIterations( inSource->mEstimateIterations )
{
PX_UNUSED(inSource);
}
PxReal getPxVehicleTireLoadFilterData_Denominator( const PxVehicleTireLoadFilterData* inObj ) { return inObj->getDenominator(); }
inline PxReal getPxVehicleTireLoadFilterDataMMinNormalisedLoad( const PxVehicleTireLoadFilterData* inOwner ) { return inOwner->mMinNormalisedLoad; }
inline void setPxVehicleTireLoadFilterDataMMinNormalisedLoad( PxVehicleTireLoadFilterData* inOwner, PxReal inData) { inOwner->mMinNormalisedLoad = inData; }
inline PxReal getPxVehicleTireLoadFilterDataMMinFilteredNormalisedLoad( const PxVehicleTireLoadFilterData* inOwner ) { return inOwner->mMinFilteredNormalisedLoad; }
inline void setPxVehicleTireLoadFilterDataMMinFilteredNormalisedLoad( PxVehicleTireLoadFilterData* inOwner, PxReal inData) { inOwner->mMinFilteredNormalisedLoad = inData; }
inline PxReal getPxVehicleTireLoadFilterDataMMaxNormalisedLoad( const PxVehicleTireLoadFilterData* inOwner ) { return inOwner->mMaxNormalisedLoad; }
inline void setPxVehicleTireLoadFilterDataMMaxNormalisedLoad( PxVehicleTireLoadFilterData* inOwner, PxReal inData) { inOwner->mMaxNormalisedLoad = inData; }
inline PxReal getPxVehicleTireLoadFilterDataMMaxFilteredNormalisedLoad( const PxVehicleTireLoadFilterData* inOwner ) { return inOwner->mMaxFilteredNormalisedLoad; }
inline void setPxVehicleTireLoadFilterDataMMaxFilteredNormalisedLoad( PxVehicleTireLoadFilterData* inOwner, PxReal inData) { inOwner->mMaxFilteredNormalisedLoad = inData; }
PxVehicleTireLoadFilterDataGeneratedInfo::PxVehicleTireLoadFilterDataGeneratedInfo()
: Denominator( "Denominator", getPxVehicleTireLoadFilterData_Denominator)
, MMinNormalisedLoad( "MMinNormalisedLoad", setPxVehicleTireLoadFilterDataMMinNormalisedLoad, getPxVehicleTireLoadFilterDataMMinNormalisedLoad )
, MMinFilteredNormalisedLoad( "MMinFilteredNormalisedLoad", setPxVehicleTireLoadFilterDataMMinFilteredNormalisedLoad, getPxVehicleTireLoadFilterDataMMinFilteredNormalisedLoad )
, MMaxNormalisedLoad( "MMaxNormalisedLoad", setPxVehicleTireLoadFilterDataMMaxNormalisedLoad, getPxVehicleTireLoadFilterDataMMaxNormalisedLoad )
, MMaxFilteredNormalisedLoad( "MMaxFilteredNormalisedLoad", setPxVehicleTireLoadFilterDataMMaxFilteredNormalisedLoad, getPxVehicleTireLoadFilterDataMMaxFilteredNormalisedLoad )
{}
PxVehicleTireLoadFilterDataGeneratedValues::PxVehicleTireLoadFilterDataGeneratedValues( const PxVehicleTireLoadFilterData* inSource )
:Denominator( getPxVehicleTireLoadFilterData_Denominator( inSource ) )
,MMinNormalisedLoad( inSource->mMinNormalisedLoad )
,MMinFilteredNormalisedLoad( inSource->mMinFilteredNormalisedLoad )
,MMaxNormalisedLoad( inSource->mMaxNormalisedLoad )
,MMaxFilteredNormalisedLoad( inSource->mMaxFilteredNormalisedLoad )
{
PX_UNUSED(inSource);
}
PxReal getPxVehicleWheelData_RecipRadius( const PxVehicleWheelData* inObj ) { return inObj->getRecipRadius(); }
PxReal getPxVehicleWheelData_RecipMOI( const PxVehicleWheelData* inObj ) { return inObj->getRecipMOI(); }
inline PxReal getPxVehicleWheelDataMRadius( const PxVehicleWheelData* inOwner ) { return inOwner->mRadius; }
inline void setPxVehicleWheelDataMRadius( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mRadius = inData; }
inline PxReal getPxVehicleWheelDataMWidth( const PxVehicleWheelData* inOwner ) { return inOwner->mWidth; }
inline void setPxVehicleWheelDataMWidth( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mWidth = inData; }
inline PxReal getPxVehicleWheelDataMMass( const PxVehicleWheelData* inOwner ) { return inOwner->mMass; }
inline void setPxVehicleWheelDataMMass( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mMass = inData; }
inline PxReal getPxVehicleWheelDataMMOI( const PxVehicleWheelData* inOwner ) { return inOwner->mMOI; }
inline void setPxVehicleWheelDataMMOI( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mMOI = inData; }
inline PxReal getPxVehicleWheelDataMDampingRate( const PxVehicleWheelData* inOwner ) { return inOwner->mDampingRate; }
inline void setPxVehicleWheelDataMDampingRate( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mDampingRate = inData; }
inline PxReal getPxVehicleWheelDataMMaxBrakeTorque( const PxVehicleWheelData* inOwner ) { return inOwner->mMaxBrakeTorque; }
inline void setPxVehicleWheelDataMMaxBrakeTorque( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mMaxBrakeTorque = inData; }
inline PxReal getPxVehicleWheelDataMMaxHandBrakeTorque( const PxVehicleWheelData* inOwner ) { return inOwner->mMaxHandBrakeTorque; }
inline void setPxVehicleWheelDataMMaxHandBrakeTorque( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mMaxHandBrakeTorque = inData; }
inline PxReal getPxVehicleWheelDataMMaxSteer( const PxVehicleWheelData* inOwner ) { return inOwner->mMaxSteer; }
inline void setPxVehicleWheelDataMMaxSteer( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mMaxSteer = inData; }
inline PxReal getPxVehicleWheelDataMToeAngle( const PxVehicleWheelData* inOwner ) { return inOwner->mToeAngle; }
inline void setPxVehicleWheelDataMToeAngle( PxVehicleWheelData* inOwner, PxReal inData) { inOwner->mToeAngle = inData; }
PxVehicleWheelDataGeneratedInfo::PxVehicleWheelDataGeneratedInfo()
: RecipRadius( "RecipRadius", getPxVehicleWheelData_RecipRadius)
, RecipMOI( "RecipMOI", getPxVehicleWheelData_RecipMOI)
, MRadius( "MRadius", setPxVehicleWheelDataMRadius, getPxVehicleWheelDataMRadius )
, MWidth( "MWidth", setPxVehicleWheelDataMWidth, getPxVehicleWheelDataMWidth )
, MMass( "MMass", setPxVehicleWheelDataMMass, getPxVehicleWheelDataMMass )
, MMOI( "MMOI", setPxVehicleWheelDataMMOI, getPxVehicleWheelDataMMOI )
, MDampingRate( "MDampingRate", setPxVehicleWheelDataMDampingRate, getPxVehicleWheelDataMDampingRate )
, MMaxBrakeTorque( "MMaxBrakeTorque", setPxVehicleWheelDataMMaxBrakeTorque, getPxVehicleWheelDataMMaxBrakeTorque )
, MMaxHandBrakeTorque( "MMaxHandBrakeTorque", setPxVehicleWheelDataMMaxHandBrakeTorque, getPxVehicleWheelDataMMaxHandBrakeTorque )
, MMaxSteer( "MMaxSteer", setPxVehicleWheelDataMMaxSteer, getPxVehicleWheelDataMMaxSteer )
, MToeAngle( "MToeAngle", setPxVehicleWheelDataMToeAngle, getPxVehicleWheelDataMToeAngle )
{}
PxVehicleWheelDataGeneratedValues::PxVehicleWheelDataGeneratedValues( const PxVehicleWheelData* inSource )
:RecipRadius( getPxVehicleWheelData_RecipRadius( inSource ) )
,RecipMOI( getPxVehicleWheelData_RecipMOI( inSource ) )
,MRadius( inSource->mRadius )
,MWidth( inSource->mWidth )
,MMass( inSource->mMass )
,MMOI( inSource->mMOI )
,MDampingRate( inSource->mDampingRate )
,MMaxBrakeTorque( inSource->mMaxBrakeTorque )
,MMaxHandBrakeTorque( inSource->mMaxHandBrakeTorque )
,MMaxSteer( inSource->mMaxSteer )
,MToeAngle( inSource->mToeAngle )
{
PX_UNUSED(inSource);
}
PxReal getPxVehicleSuspensionData_RecipMaxCompression( const PxVehicleSuspensionData* inObj ) { return inObj->getRecipMaxCompression(); }
PxReal getPxVehicleSuspensionData_RecipMaxDroop( const PxVehicleSuspensionData* inObj ) { return inObj->getRecipMaxDroop(); }
void setPxVehicleSuspensionData_MassAndPreserveNaturalFrequency( PxVehicleSuspensionData* inObj, const PxReal inArg){ inObj->setMassAndPreserveNaturalFrequency( inArg ); }
inline PxReal getPxVehicleSuspensionDataMSpringStrength( const PxVehicleSuspensionData* inOwner ) { return inOwner->mSpringStrength; }
inline void setPxVehicleSuspensionDataMSpringStrength( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mSpringStrength = inData; }
inline PxReal getPxVehicleSuspensionDataMSpringDamperRate( const PxVehicleSuspensionData* inOwner ) { return inOwner->mSpringDamperRate; }
inline void setPxVehicleSuspensionDataMSpringDamperRate( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mSpringDamperRate = inData; }
inline PxReal getPxVehicleSuspensionDataMMaxCompression( const PxVehicleSuspensionData* inOwner ) { return inOwner->mMaxCompression; }
inline void setPxVehicleSuspensionDataMMaxCompression( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mMaxCompression = inData; }
inline PxReal getPxVehicleSuspensionDataMMaxDroop( const PxVehicleSuspensionData* inOwner ) { return inOwner->mMaxDroop; }
inline void setPxVehicleSuspensionDataMMaxDroop( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mMaxDroop = inData; }
inline PxReal getPxVehicleSuspensionDataMSprungMass( const PxVehicleSuspensionData* inOwner ) { return inOwner->mSprungMass; }
inline void setPxVehicleSuspensionDataMSprungMass( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mSprungMass = inData; }
inline PxReal getPxVehicleSuspensionDataMCamberAtRest( const PxVehicleSuspensionData* inOwner ) { return inOwner->mCamberAtRest; }
inline void setPxVehicleSuspensionDataMCamberAtRest( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mCamberAtRest = inData; }
inline PxReal getPxVehicleSuspensionDataMCamberAtMaxCompression( const PxVehicleSuspensionData* inOwner ) { return inOwner->mCamberAtMaxCompression; }
inline void setPxVehicleSuspensionDataMCamberAtMaxCompression( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mCamberAtMaxCompression = inData; }
inline PxReal getPxVehicleSuspensionDataMCamberAtMaxDroop( const PxVehicleSuspensionData* inOwner ) { return inOwner->mCamberAtMaxDroop; }
inline void setPxVehicleSuspensionDataMCamberAtMaxDroop( PxVehicleSuspensionData* inOwner, PxReal inData) { inOwner->mCamberAtMaxDroop = inData; }
PxVehicleSuspensionDataGeneratedInfo::PxVehicleSuspensionDataGeneratedInfo()
: RecipMaxCompression( "RecipMaxCompression", getPxVehicleSuspensionData_RecipMaxCompression)
, RecipMaxDroop( "RecipMaxDroop", getPxVehicleSuspensionData_RecipMaxDroop)
, MassAndPreserveNaturalFrequency( "MassAndPreserveNaturalFrequency", setPxVehicleSuspensionData_MassAndPreserveNaturalFrequency)
, MSpringStrength( "MSpringStrength", setPxVehicleSuspensionDataMSpringStrength, getPxVehicleSuspensionDataMSpringStrength )
, MSpringDamperRate( "MSpringDamperRate", setPxVehicleSuspensionDataMSpringDamperRate, getPxVehicleSuspensionDataMSpringDamperRate )
, MMaxCompression( "MMaxCompression", setPxVehicleSuspensionDataMMaxCompression, getPxVehicleSuspensionDataMMaxCompression )
, MMaxDroop( "MMaxDroop", setPxVehicleSuspensionDataMMaxDroop, getPxVehicleSuspensionDataMMaxDroop )
, MSprungMass( "MSprungMass", setPxVehicleSuspensionDataMSprungMass, getPxVehicleSuspensionDataMSprungMass )
, MCamberAtRest( "MCamberAtRest", setPxVehicleSuspensionDataMCamberAtRest, getPxVehicleSuspensionDataMCamberAtRest )
, MCamberAtMaxCompression( "MCamberAtMaxCompression", setPxVehicleSuspensionDataMCamberAtMaxCompression, getPxVehicleSuspensionDataMCamberAtMaxCompression )
, MCamberAtMaxDroop( "MCamberAtMaxDroop", setPxVehicleSuspensionDataMCamberAtMaxDroop, getPxVehicleSuspensionDataMCamberAtMaxDroop )
{}
PxVehicleSuspensionDataGeneratedValues::PxVehicleSuspensionDataGeneratedValues( const PxVehicleSuspensionData* inSource )
:RecipMaxCompression( getPxVehicleSuspensionData_RecipMaxCompression( inSource ) )
,RecipMaxDroop( getPxVehicleSuspensionData_RecipMaxDroop( inSource ) )
,MSpringStrength( inSource->mSpringStrength )
,MSpringDamperRate( inSource->mSpringDamperRate )
,MMaxCompression( inSource->mMaxCompression )
,MMaxDroop( inSource->mMaxDroop )
,MSprungMass( inSource->mSprungMass )
,MCamberAtRest( inSource->mCamberAtRest )
,MCamberAtMaxCompression( inSource->mCamberAtMaxCompression )
,MCamberAtMaxDroop( inSource->mCamberAtMaxDroop )
{
PX_UNUSED(inSource);
}
inline PxU32 getPxVehicleAntiRollBarDataMWheel0( const PxVehicleAntiRollBarData* inOwner ) { return inOwner->mWheel0; }
inline void setPxVehicleAntiRollBarDataMWheel0( PxVehicleAntiRollBarData* inOwner, PxU32 inData) { inOwner->mWheel0 = inData; }
inline PxU32 getPxVehicleAntiRollBarDataMWheel1( const PxVehicleAntiRollBarData* inOwner ) { return inOwner->mWheel1; }
inline void setPxVehicleAntiRollBarDataMWheel1( PxVehicleAntiRollBarData* inOwner, PxU32 inData) { inOwner->mWheel1 = inData; }
inline PxF32 getPxVehicleAntiRollBarDataMStiffness( const PxVehicleAntiRollBarData* inOwner ) { return inOwner->mStiffness; }
inline void setPxVehicleAntiRollBarDataMStiffness( PxVehicleAntiRollBarData* inOwner, PxF32 inData) { inOwner->mStiffness = inData; }
PxVehicleAntiRollBarDataGeneratedInfo::PxVehicleAntiRollBarDataGeneratedInfo()
: MWheel0( "MWheel0", setPxVehicleAntiRollBarDataMWheel0, getPxVehicleAntiRollBarDataMWheel0 )
, MWheel1( "MWheel1", setPxVehicleAntiRollBarDataMWheel1, getPxVehicleAntiRollBarDataMWheel1 )
, MStiffness( "MStiffness", setPxVehicleAntiRollBarDataMStiffness, getPxVehicleAntiRollBarDataMStiffness )
{}
PxVehicleAntiRollBarDataGeneratedValues::PxVehicleAntiRollBarDataGeneratedValues( const PxVehicleAntiRollBarData* inSource )
:MWheel0( inSource->mWheel0 )
,MWheel1( inSource->mWheel1 )
,MStiffness( inSource->mStiffness )
{
PX_UNUSED(inSource);
}
PxReal getPxVehicleTireData_RecipLongitudinalStiffnessPerUnitGravity( const PxVehicleTireData* inObj ) { return inObj->getRecipLongitudinalStiffnessPerUnitGravity(); }
PxReal getPxVehicleTireData_FrictionVsSlipGraphRecipx1Minusx0( const PxVehicleTireData* inObj ) { return inObj->getFrictionVsSlipGraphRecipx1Minusx0(); }
PxReal getPxVehicleTireData_FrictionVsSlipGraphRecipx2Minusx1( const PxVehicleTireData* inObj ) { return inObj->getFrictionVsSlipGraphRecipx2Minusx1(); }
inline PxReal getPxVehicleTireDataMLatStiffX( const PxVehicleTireData* inOwner ) { return inOwner->mLatStiffX; }
inline void setPxVehicleTireDataMLatStiffX( PxVehicleTireData* inOwner, PxReal inData) { inOwner->mLatStiffX = inData; }
inline PxReal getPxVehicleTireDataMLatStiffY( const PxVehicleTireData* inOwner ) { return inOwner->mLatStiffY; }
inline void setPxVehicleTireDataMLatStiffY( PxVehicleTireData* inOwner, PxReal inData) { inOwner->mLatStiffY = inData; }
inline PxReal getPxVehicleTireDataMLongitudinalStiffnessPerUnitGravity( const PxVehicleTireData* inOwner ) { return inOwner->mLongitudinalStiffnessPerUnitGravity; }
inline void setPxVehicleTireDataMLongitudinalStiffnessPerUnitGravity( PxVehicleTireData* inOwner, PxReal inData) { inOwner->mLongitudinalStiffnessPerUnitGravity = inData; }
inline PxReal getPxVehicleTireDataMCamberStiffnessPerUnitGravity( const PxVehicleTireData* inOwner ) { return inOwner->mCamberStiffnessPerUnitGravity; }
inline void setPxVehicleTireDataMCamberStiffnessPerUnitGravity( PxVehicleTireData* inOwner, PxReal inData) { inOwner->mCamberStiffnessPerUnitGravity = inData; }
inline PxU32 getPxVehicleTireDataMType( const PxVehicleTireData* inOwner ) { return inOwner->mType; }
inline void setPxVehicleTireDataMType( PxVehicleTireData* inOwner, PxU32 inData) { inOwner->mType = inData; }
PxVehicleTireDataGeneratedInfo::PxVehicleTireDataGeneratedInfo()
: RecipLongitudinalStiffnessPerUnitGravity( "RecipLongitudinalStiffnessPerUnitGravity", getPxVehicleTireData_RecipLongitudinalStiffnessPerUnitGravity)
, FrictionVsSlipGraphRecipx1Minusx0( "FrictionVsSlipGraphRecipx1Minusx0", getPxVehicleTireData_FrictionVsSlipGraphRecipx1Minusx0)
, FrictionVsSlipGraphRecipx2Minusx1( "FrictionVsSlipGraphRecipx2Minusx1", getPxVehicleTireData_FrictionVsSlipGraphRecipx2Minusx1)
, MLatStiffX( "MLatStiffX", setPxVehicleTireDataMLatStiffX, getPxVehicleTireDataMLatStiffX )
, MLatStiffY( "MLatStiffY", setPxVehicleTireDataMLatStiffY, getPxVehicleTireDataMLatStiffY )
, MLongitudinalStiffnessPerUnitGravity( "MLongitudinalStiffnessPerUnitGravity", setPxVehicleTireDataMLongitudinalStiffnessPerUnitGravity, getPxVehicleTireDataMLongitudinalStiffnessPerUnitGravity )
, MCamberStiffnessPerUnitGravity( "MCamberStiffnessPerUnitGravity", setPxVehicleTireDataMCamberStiffnessPerUnitGravity, getPxVehicleTireDataMCamberStiffnessPerUnitGravity )
, MType( "MType", setPxVehicleTireDataMType, getPxVehicleTireDataMType )
{}
PxVehicleTireDataGeneratedValues::PxVehicleTireDataGeneratedValues( const PxVehicleTireData* inSource )
:RecipLongitudinalStiffnessPerUnitGravity( getPxVehicleTireData_RecipLongitudinalStiffnessPerUnitGravity( inSource ) )
,FrictionVsSlipGraphRecipx1Minusx0( getPxVehicleTireData_FrictionVsSlipGraphRecipx1Minusx0( inSource ) )
,FrictionVsSlipGraphRecipx2Minusx1( getPxVehicleTireData_FrictionVsSlipGraphRecipx2Minusx1( inSource ) )
,MLatStiffX( inSource->mLatStiffX )
,MLatStiffY( inSource->mLatStiffY )
,MLongitudinalStiffnessPerUnitGravity( inSource->mLongitudinalStiffnessPerUnitGravity )
,MCamberStiffnessPerUnitGravity( inSource->mCamberStiffnessPerUnitGravity )
,MType( inSource->mType )
{
PX_UNUSED(inSource);
PxMemCopy( MFrictionVsSlipGraph, inSource->mFrictionVsSlipGraph, sizeof( MFrictionVsSlipGraph ) );
}
const PxReal * getPxVehicleWheels4SimData_TireRestLoadsArray( const PxVehicleWheels4SimData* inObj ) { return inObj->getTireRestLoadsArray(); }
const PxReal * getPxVehicleWheels4SimData_RecipTireRestLoadsArray( const PxVehicleWheels4SimData* inObj ) { return inObj->getRecipTireRestLoadsArray(); }
PxVehicleWheels4SimDataGeneratedInfo::PxVehicleWheels4SimDataGeneratedInfo()
: TireRestLoadsArray( "TireRestLoadsArray", getPxVehicleWheels4SimData_TireRestLoadsArray)
, RecipTireRestLoadsArray( "RecipTireRestLoadsArray", getPxVehicleWheels4SimData_RecipTireRestLoadsArray)
{}
PxVehicleWheels4SimDataGeneratedValues::PxVehicleWheels4SimDataGeneratedValues( const PxVehicleWheels4SimData* inSource )
:TireRestLoadsArray( getPxVehicleWheels4SimData_TireRestLoadsArray( inSource ) )
,RecipTireRestLoadsArray( getPxVehicleWheels4SimData_RecipTireRestLoadsArray( inSource ) )
{
PX_UNUSED(inSource);
}
void setPxVehicleWheelsSimData_ChassisMass( PxVehicleWheelsSimData* inObj, const PxF32 inArg){ inObj->setChassisMass( inArg ); }
PxVehicleSuspensionData getPxVehicleWheelsSimData_SuspensionData( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getSuspensionData( index ); }
PxU32 getNbPxVehicleWheelsSimData_SuspensionData( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbSuspensionData( ); }
void setPxVehicleWheelsSimData_SuspensionData( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVehicleSuspensionData inValue ){ inObj->setSuspensionData( inIndex, inValue ); }
PxVehicleWheelData getPxVehicleWheelsSimData_WheelData( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getWheelData( index ); }
PxU32 getNbPxVehicleWheelsSimData_WheelData( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbWheelData( ); }
void setPxVehicleWheelsSimData_WheelData( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVehicleWheelData inValue ){ inObj->setWheelData( inIndex, inValue ); }
PxVehicleTireData getPxVehicleWheelsSimData_TireData( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getTireData( index ); }
PxU32 getNbPxVehicleWheelsSimData_TireData( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbTireData( ); }
void setPxVehicleWheelsSimData_TireData( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVehicleTireData inValue ){ inObj->setTireData( inIndex, inValue ); }
PxVec3 getPxVehicleWheelsSimData_SuspTravelDirection( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getSuspTravelDirection( index ); }
PxU32 getNbPxVehicleWheelsSimData_SuspTravelDirection( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbSuspTravelDirection( ); }
void setPxVehicleWheelsSimData_SuspTravelDirection( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVec3 inValue ){ inObj->setSuspTravelDirection( inIndex, inValue ); }
PxVec3 getPxVehicleWheelsSimData_SuspForceAppPointOffset( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getSuspForceAppPointOffset( index ); }
PxU32 getNbPxVehicleWheelsSimData_SuspForceAppPointOffset( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbSuspForceAppPointOffset( ); }
void setPxVehicleWheelsSimData_SuspForceAppPointOffset( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVec3 inValue ){ inObj->setSuspForceAppPointOffset( inIndex, inValue ); }
PxVec3 getPxVehicleWheelsSimData_TireForceAppPointOffset( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getTireForceAppPointOffset( index ); }
PxU32 getNbPxVehicleWheelsSimData_TireForceAppPointOffset( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbTireForceAppPointOffset( ); }
void setPxVehicleWheelsSimData_TireForceAppPointOffset( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVec3 inValue ){ inObj->setTireForceAppPointOffset( inIndex, inValue ); }
PxVec3 getPxVehicleWheelsSimData_WheelCentreOffset( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getWheelCentreOffset( index ); }
PxU32 getNbPxVehicleWheelsSimData_WheelCentreOffset( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbWheelCentreOffset( ); }
void setPxVehicleWheelsSimData_WheelCentreOffset( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVec3 inValue ){ inObj->setWheelCentreOffset( inIndex, inValue ); }
PxI32 getPxVehicleWheelsSimData_WheelShapeMapping( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getWheelShapeMapping( index ); }
PxU32 getNbPxVehicleWheelsSimData_WheelShapeMapping( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbWheelShapeMapping( ); }
void setPxVehicleWheelsSimData_WheelShapeMapping( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxI32 inValue ){ inObj->setWheelShapeMapping( inIndex, inValue ); }
PxFilterData getPxVehicleWheelsSimData_SceneQueryFilterData( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getSceneQueryFilterData( index ); }
PxU32 getNbPxVehicleWheelsSimData_SceneQueryFilterData( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbSceneQueryFilterData( ); }
void setPxVehicleWheelsSimData_SceneQueryFilterData( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxFilterData inValue ){ inObj->setSceneQueryFilterData( inIndex, inValue ); }
PxVehicleAntiRollBarData getPxVehicleWheelsSimData_AntiRollBarData( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getAntiRollBarData( index ); }
PxU32 getNbPxVehicleWheelsSimData_AntiRollBarData( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbAntiRollBarData( ); }
void setPxVehicleWheelsSimData_AntiRollBarData( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, PxVehicleAntiRollBarData inValue ){ inObj->setAntiRollBarData( inIndex, inValue ); }
void setPxVehicleWheelsSimData_TireLoadFilterData( PxVehicleWheelsSimData* inObj, const PxVehicleTireLoadFilterData & inArg){ inObj->setTireLoadFilterData( inArg ); }
PxVehicleTireLoadFilterData getPxVehicleWheelsSimData_TireLoadFilterData( const PxVehicleWheelsSimData* inObj ) { return inObj->getTireLoadFilterData(); }
void setPxVehicleWheelsSimData_MinLongSlipDenominator( PxVehicleWheelsSimData* inObj, const PxReal inArg){ inObj->setMinLongSlipDenominator( inArg ); }
PxF32 getPxVehicleWheelsSimData_MinLongSlipDenominator( const PxVehicleWheelsSimData* inObj ) { return inObj->getMinLongSlipDenominator(); }
void setPxVehicleWheelsSimData_Flags( PxVehicleWheelsSimData* inObj, PxVehicleWheelsSimFlags inArg){ inObj->setFlags( inArg ); }
PxVehicleWheelsSimFlags getPxVehicleWheelsSimData_Flags( const PxVehicleWheelsSimData* inObj ) { return inObj->getFlags(); }
void setPxVehicleWheelsSimData_ThresholdLongSpeed( PxVehicleWheelsSimData* inObj, const PxF32 inArg){ inObj->setThresholdLongSpeed( inArg ); }
PxF32 getPxVehicleWheelsSimData_ThresholdLongSpeed( const PxVehicleWheelsSimData* inObj ) { return inObj->getThresholdLongSpeed(); }
void setPxVehicleWheelsSimData_LowForwardSpeedSubStepCount( PxVehicleWheelsSimData* inObj, const PxU32 inArg){ inObj->setLowForwardSpeedSubStepCount( inArg ); }
PxU32 getPxVehicleWheelsSimData_LowForwardSpeedSubStepCount( const PxVehicleWheelsSimData* inObj ) { return inObj->getLowForwardSpeedSubStepCount(); }
void setPxVehicleWheelsSimData_HighForwardSpeedSubStepCount( PxVehicleWheelsSimData* inObj, const PxU32 inArg){ inObj->setHighForwardSpeedSubStepCount( inArg ); }
PxU32 getPxVehicleWheelsSimData_HighForwardSpeedSubStepCount( const PxVehicleWheelsSimData* inObj ) { return inObj->getHighForwardSpeedSubStepCount(); }
_Bool getPxVehicleWheelsSimData_WheelEnabledState( const PxVehicleWheelsSimData* inObj, const PxU32 index ) { return inObj->getWheelEnabledState( index ); }
PxU32 getNbPxVehicleWheelsSimData_WheelEnabledState( const PxVehicleWheelsSimData* inObj ) { return inObj->getNbWheelEnabledState( ); }
void setPxVehicleWheelsSimData_WheelEnabledState( PxVehicleWheelsSimData* inObj, const PxU32 inIndex, _Bool inValue ){ inObj->setWheelEnabledState( inIndex, inValue ); }
PxVehicleWheelsSimDataGeneratedInfo::PxVehicleWheelsSimDataGeneratedInfo()
: ChassisMass( "ChassisMass", setPxVehicleWheelsSimData_ChassisMass)
, SuspensionData( "SuspensionData", getPxVehicleWheelsSimData_SuspensionData, getNbPxVehicleWheelsSimData_SuspensionData, setPxVehicleWheelsSimData_SuspensionData )
, WheelData( "WheelData", getPxVehicleWheelsSimData_WheelData, getNbPxVehicleWheelsSimData_WheelData, setPxVehicleWheelsSimData_WheelData )
, TireData( "TireData", getPxVehicleWheelsSimData_TireData, getNbPxVehicleWheelsSimData_TireData, setPxVehicleWheelsSimData_TireData )
, SuspTravelDirection( "SuspTravelDirection", getPxVehicleWheelsSimData_SuspTravelDirection, getNbPxVehicleWheelsSimData_SuspTravelDirection, setPxVehicleWheelsSimData_SuspTravelDirection )
, SuspForceAppPointOffset( "SuspForceAppPointOffset", getPxVehicleWheelsSimData_SuspForceAppPointOffset, getNbPxVehicleWheelsSimData_SuspForceAppPointOffset, setPxVehicleWheelsSimData_SuspForceAppPointOffset )
, TireForceAppPointOffset( "TireForceAppPointOffset", getPxVehicleWheelsSimData_TireForceAppPointOffset, getNbPxVehicleWheelsSimData_TireForceAppPointOffset, setPxVehicleWheelsSimData_TireForceAppPointOffset )
, WheelCentreOffset( "WheelCentreOffset", getPxVehicleWheelsSimData_WheelCentreOffset, getNbPxVehicleWheelsSimData_WheelCentreOffset, setPxVehicleWheelsSimData_WheelCentreOffset )
, WheelShapeMapping( "WheelShapeMapping", getPxVehicleWheelsSimData_WheelShapeMapping, getNbPxVehicleWheelsSimData_WheelShapeMapping, setPxVehicleWheelsSimData_WheelShapeMapping )
, SceneQueryFilterData( "SceneQueryFilterData", getPxVehicleWheelsSimData_SceneQueryFilterData, getNbPxVehicleWheelsSimData_SceneQueryFilterData, setPxVehicleWheelsSimData_SceneQueryFilterData )
, AntiRollBarData( "AntiRollBarData", getPxVehicleWheelsSimData_AntiRollBarData, getNbPxVehicleWheelsSimData_AntiRollBarData, setPxVehicleWheelsSimData_AntiRollBarData )
, TireLoadFilterData( "TireLoadFilterData", setPxVehicleWheelsSimData_TireLoadFilterData, getPxVehicleWheelsSimData_TireLoadFilterData)
, MinLongSlipDenominator( "MinLongSlipDenominator", setPxVehicleWheelsSimData_MinLongSlipDenominator, getPxVehicleWheelsSimData_MinLongSlipDenominator)
, Flags( "Flags", setPxVehicleWheelsSimData_Flags, getPxVehicleWheelsSimData_Flags)
, ThresholdLongSpeed( "ThresholdLongSpeed", setPxVehicleWheelsSimData_ThresholdLongSpeed, getPxVehicleWheelsSimData_ThresholdLongSpeed)
, LowForwardSpeedSubStepCount( "LowForwardSpeedSubStepCount", setPxVehicleWheelsSimData_LowForwardSpeedSubStepCount, getPxVehicleWheelsSimData_LowForwardSpeedSubStepCount)
, HighForwardSpeedSubStepCount( "HighForwardSpeedSubStepCount", setPxVehicleWheelsSimData_HighForwardSpeedSubStepCount, getPxVehicleWheelsSimData_HighForwardSpeedSubStepCount)
, WheelEnabledState( "WheelEnabledState", getPxVehicleWheelsSimData_WheelEnabledState, getNbPxVehicleWheelsSimData_WheelEnabledState, setPxVehicleWheelsSimData_WheelEnabledState )
{}
PxVehicleWheelsSimDataGeneratedValues::PxVehicleWheelsSimDataGeneratedValues( const PxVehicleWheelsSimData* inSource )
:TireLoadFilterData( getPxVehicleWheelsSimData_TireLoadFilterData( inSource ) )
,MinLongSlipDenominator( getPxVehicleWheelsSimData_MinLongSlipDenominator( inSource ) )
,Flags( getPxVehicleWheelsSimData_Flags( inSource ) )
,ThresholdLongSpeed( getPxVehicleWheelsSimData_ThresholdLongSpeed( inSource ) )
,LowForwardSpeedSubStepCount( getPxVehicleWheelsSimData_LowForwardSpeedSubStepCount( inSource ) )
,HighForwardSpeedSubStepCount( getPxVehicleWheelsSimData_HighForwardSpeedSubStepCount( inSource ) )
{
PX_UNUSED(inSource);
}
void setPxVehicleWheelsDynData_TireForceShaderFunction( PxVehicleWheelsDynData* inObj, PxVehicleComputeTireForce inArg){ inObj->setTireForceShaderFunction( inArg ); }
PxReal getPxVehicleWheelsDynData_WheelRotationSpeed( const PxVehicleWheelsDynData* inObj, const PxU32 index ) { return inObj->getWheelRotationSpeed( index ); }
PxU32 getNbPxVehicleWheelsDynData_WheelRotationSpeed( const PxVehicleWheelsDynData* inObj ) { return inObj->getNbWheelRotationSpeed( ); }
void setPxVehicleWheelsDynData_WheelRotationSpeed( PxVehicleWheelsDynData* inObj, const PxU32 inIndex, PxReal inValue ){ inObj->setWheelRotationSpeed( inIndex, inValue ); }
PxReal getPxVehicleWheelsDynData_WheelRotationAngle( const PxVehicleWheelsDynData* inObj, const PxU32 index ) { return inObj->getWheelRotationAngle( index ); }
PxU32 getNbPxVehicleWheelsDynData_WheelRotationAngle( const PxVehicleWheelsDynData* inObj ) { return inObj->getNbWheelRotationAngle( ); }
void setPxVehicleWheelsDynData_WheelRotationAngle( PxVehicleWheelsDynData* inObj, const PxU32 inIndex, PxReal inValue ){ inObj->setWheelRotationAngle( inIndex, inValue ); }
PxVehicleWheels4DynData * getPxVehicleWheelsDynData_Wheel4DynData( const PxVehicleWheelsDynData* inObj ) { return inObj->getWheel4DynData(); }
PxU32 getPxVehicleWheelsDynData_Constraints( const PxVehicleWheelsDynData* inObj, PxConstraint ** outBuffer, PxU32 inBufSize ) { return inObj->getConstraints( outBuffer, inBufSize ); }
PxU32 getNbPxVehicleWheelsDynData_Constraints( const PxVehicleWheelsDynData* inObj ) { return inObj->getNbConstraints( ); }
PxVehicleWheelsDynDataGeneratedInfo::PxVehicleWheelsDynDataGeneratedInfo()
: TireForceShaderFunction( "TireForceShaderFunction", setPxVehicleWheelsDynData_TireForceShaderFunction)
, WheelRotationSpeed( "WheelRotationSpeed", getPxVehicleWheelsDynData_WheelRotationSpeed, getNbPxVehicleWheelsDynData_WheelRotationSpeed, setPxVehicleWheelsDynData_WheelRotationSpeed )
, WheelRotationAngle( "WheelRotationAngle", getPxVehicleWheelsDynData_WheelRotationAngle, getNbPxVehicleWheelsDynData_WheelRotationAngle, setPxVehicleWheelsDynData_WheelRotationAngle )
, Wheel4DynData( "Wheel4DynData", getPxVehicleWheelsDynData_Wheel4DynData)
, Constraints( "Constraints", getPxVehicleWheelsDynData_Constraints, getNbPxVehicleWheelsDynData_Constraints )
{}
PxVehicleWheelsDynDataGeneratedValues::PxVehicleWheelsDynDataGeneratedValues( const PxVehicleWheelsDynData* inSource )
:Wheel4DynData( getPxVehicleWheelsDynData_Wheel4DynData( inSource ) )
{
PX_UNUSED(inSource);
}
PxU32 getPxVehicleWheels_VehicleType( const PxVehicleWheels* inObj ) { return inObj->getVehicleType(); }
const PxRigidDynamic * getPxVehicleWheels_RigidDynamicActor( const PxVehicleWheels* inObj ) { return inObj->getRigidDynamicActor(); }
const char * getPxVehicleWheels_ConcreteTypeName( const PxVehicleWheels* inObj ) { return inObj->getConcreteTypeName(); }
inline PxVehicleWheelsSimData getPxVehicleWheelsMWheelsSimData( const PxVehicleWheels* inOwner ) { return inOwner->mWheelsSimData; }
inline void setPxVehicleWheelsMWheelsSimData( PxVehicleWheels* inOwner, PxVehicleWheelsSimData inData) { inOwner->mWheelsSimData = inData; }
inline PxVehicleWheelsDynData getPxVehicleWheelsMWheelsDynData( const PxVehicleWheels* inOwner ) { return inOwner->mWheelsDynData; }
inline void setPxVehicleWheelsMWheelsDynData( PxVehicleWheels* inOwner, PxVehicleWheelsDynData inData) { inOwner->mWheelsDynData = inData; }
PxVehicleWheelsGeneratedInfo::PxVehicleWheelsGeneratedInfo()
: VehicleType( "VehicleType", getPxVehicleWheels_VehicleType)
, RigidDynamicActor( "RigidDynamicActor", getPxVehicleWheels_RigidDynamicActor)
, ConcreteTypeName( "ConcreteTypeName", getPxVehicleWheels_ConcreteTypeName)
, MWheelsSimData( "MWheelsSimData", setPxVehicleWheelsMWheelsSimData, getPxVehicleWheelsMWheelsSimData )
, MWheelsDynData( "MWheelsDynData", setPxVehicleWheelsMWheelsDynData, getPxVehicleWheelsMWheelsDynData )
{}
PxVehicleWheelsGeneratedValues::PxVehicleWheelsGeneratedValues( const PxVehicleWheels* inSource )
:VehicleType( getPxVehicleWheels_VehicleType( inSource ) )
,RigidDynamicActor( getPxVehicleWheels_RigidDynamicActor( inSource ) )
,ConcreteTypeName( getPxVehicleWheels_ConcreteTypeName( inSource ) )
,MWheelsSimData( inSource->mWheelsSimData )
,MWheelsDynData( inSource->mWheelsDynData )
{
PX_UNUSED(inSource);
}
PxReal getPxVehicleDriveDynData_AnalogInput( const PxVehicleDriveDynData* inObj, const PxU32 index ) { return inObj->getAnalogInput( index ); }
PxU32 getNbPxVehicleDriveDynData_AnalogInput( const PxVehicleDriveDynData* inObj ) { return inObj->getNbAnalogInput( ); }
void setPxVehicleDriveDynData_AnalogInput( PxVehicleDriveDynData* inObj, const PxU32 inIndex, PxReal inValue ){ inObj->setAnalogInput( inIndex, inValue ); }
void setPxVehicleDriveDynData_GearUp( PxVehicleDriveDynData* inObj, const _Bool inArg){ inObj->setGearUp( inArg ); }
_Bool getPxVehicleDriveDynData_GearUp( const PxVehicleDriveDynData* inObj ) { return inObj->getGearUp(); }
void setPxVehicleDriveDynData_GearDown( PxVehicleDriveDynData* inObj, const _Bool inArg){ inObj->setGearDown( inArg ); }
_Bool getPxVehicleDriveDynData_GearDown( const PxVehicleDriveDynData* inObj ) { return inObj->getGearDown(); }
void setPxVehicleDriveDynData_UseAutoGears( PxVehicleDriveDynData* inObj, const _Bool inArg){ inObj->setUseAutoGears( inArg ); }
_Bool getPxVehicleDriveDynData_UseAutoGears( const PxVehicleDriveDynData* inObj ) { return inObj->getUseAutoGears(); }
void setPxVehicleDriveDynData_CurrentGear( PxVehicleDriveDynData* inObj, PxU32 inArg){ inObj->setCurrentGear( inArg ); }
PxU32 getPxVehicleDriveDynData_CurrentGear( const PxVehicleDriveDynData* inObj ) { return inObj->getCurrentGear(); }
void setPxVehicleDriveDynData_TargetGear( PxVehicleDriveDynData* inObj, PxU32 inArg){ inObj->setTargetGear( inArg ); }
PxU32 getPxVehicleDriveDynData_TargetGear( const PxVehicleDriveDynData* inObj ) { return inObj->getTargetGear(); }
void setPxVehicleDriveDynData_EngineRotationSpeed( PxVehicleDriveDynData* inObj, const PxF32 inArg){ inObj->setEngineRotationSpeed( inArg ); }
PxReal getPxVehicleDriveDynData_EngineRotationSpeed( const PxVehicleDriveDynData* inObj ) { return inObj->getEngineRotationSpeed(); }
void setPxVehicleDriveDynData_GearChange( PxVehicleDriveDynData* inObj, const PxU32 inArg){ inObj->setGearChange( inArg ); }
PxU32 getPxVehicleDriveDynData_GearChange( const PxVehicleDriveDynData* inObj ) { return inObj->getGearChange(); }
void setPxVehicleDriveDynData_GearSwitchTime( PxVehicleDriveDynData* inObj, const PxReal inArg){ inObj->setGearSwitchTime( inArg ); }
PxReal getPxVehicleDriveDynData_GearSwitchTime( const PxVehicleDriveDynData* inObj ) { return inObj->getGearSwitchTime(); }
void setPxVehicleDriveDynData_AutoBoxSwitchTime( PxVehicleDriveDynData* inObj, const PxReal inArg){ inObj->setAutoBoxSwitchTime( inArg ); }
PxReal getPxVehicleDriveDynData_AutoBoxSwitchTime( const PxVehicleDriveDynData* inObj ) { return inObj->getAutoBoxSwitchTime(); }
inline _Bool getPxVehicleDriveDynDataMUseAutoGears( const PxVehicleDriveDynData* inOwner ) { return inOwner->mUseAutoGears; }
inline void setPxVehicleDriveDynDataMUseAutoGears( PxVehicleDriveDynData* inOwner, _Bool inData) { inOwner->mUseAutoGears = inData; }
inline _Bool getPxVehicleDriveDynDataMGearUpPressed( const PxVehicleDriveDynData* inOwner ) { return inOwner->mGearUpPressed; }
inline void setPxVehicleDriveDynDataMGearUpPressed( PxVehicleDriveDynData* inOwner, _Bool inData) { inOwner->mGearUpPressed = inData; }
inline _Bool getPxVehicleDriveDynDataMGearDownPressed( const PxVehicleDriveDynData* inOwner ) { return inOwner->mGearDownPressed; }
inline void setPxVehicleDriveDynDataMGearDownPressed( PxVehicleDriveDynData* inOwner, _Bool inData) { inOwner->mGearDownPressed = inData; }
inline PxU32 getPxVehicleDriveDynDataMCurrentGear( const PxVehicleDriveDynData* inOwner ) { return inOwner->mCurrentGear; }
inline void setPxVehicleDriveDynDataMCurrentGear( PxVehicleDriveDynData* inOwner, PxU32 inData) { inOwner->mCurrentGear = inData; }
inline PxU32 getPxVehicleDriveDynDataMTargetGear( const PxVehicleDriveDynData* inOwner ) { return inOwner->mTargetGear; }
inline void setPxVehicleDriveDynDataMTargetGear( PxVehicleDriveDynData* inOwner, PxU32 inData) { inOwner->mTargetGear = inData; }
inline PxReal getPxVehicleDriveDynDataMEnginespeed( const PxVehicleDriveDynData* inOwner ) { return inOwner->mEnginespeed; }
inline void setPxVehicleDriveDynDataMEnginespeed( PxVehicleDriveDynData* inOwner, PxReal inData) { inOwner->mEnginespeed = inData; }
inline PxReal getPxVehicleDriveDynDataMGearSwitchTime( const PxVehicleDriveDynData* inOwner ) { return inOwner->mGearSwitchTime; }
inline void setPxVehicleDriveDynDataMGearSwitchTime( PxVehicleDriveDynData* inOwner, PxReal inData) { inOwner->mGearSwitchTime = inData; }
inline PxReal getPxVehicleDriveDynDataMAutoBoxSwitchTime( const PxVehicleDriveDynData* inOwner ) { return inOwner->mAutoBoxSwitchTime; }
inline void setPxVehicleDriveDynDataMAutoBoxSwitchTime( PxVehicleDriveDynData* inOwner, PxReal inData) { inOwner->mAutoBoxSwitchTime = inData; }
PxVehicleDriveDynDataGeneratedInfo::PxVehicleDriveDynDataGeneratedInfo()
: AnalogInput( "AnalogInput", getPxVehicleDriveDynData_AnalogInput, getNbPxVehicleDriveDynData_AnalogInput, setPxVehicleDriveDynData_AnalogInput )
, GearUp( "GearUp", setPxVehicleDriveDynData_GearUp, getPxVehicleDriveDynData_GearUp)
, GearDown( "GearDown", setPxVehicleDriveDynData_GearDown, getPxVehicleDriveDynData_GearDown)
, UseAutoGears( "UseAutoGears", setPxVehicleDriveDynData_UseAutoGears, getPxVehicleDriveDynData_UseAutoGears)
, CurrentGear( "CurrentGear", setPxVehicleDriveDynData_CurrentGear, getPxVehicleDriveDynData_CurrentGear)
, TargetGear( "TargetGear", setPxVehicleDriveDynData_TargetGear, getPxVehicleDriveDynData_TargetGear)
, EngineRotationSpeed( "EngineRotationSpeed", setPxVehicleDriveDynData_EngineRotationSpeed, getPxVehicleDriveDynData_EngineRotationSpeed)
, GearChange( "GearChange", setPxVehicleDriveDynData_GearChange, getPxVehicleDriveDynData_GearChange)
, GearSwitchTime( "GearSwitchTime", setPxVehicleDriveDynData_GearSwitchTime, getPxVehicleDriveDynData_GearSwitchTime)
, AutoBoxSwitchTime( "AutoBoxSwitchTime", setPxVehicleDriveDynData_AutoBoxSwitchTime, getPxVehicleDriveDynData_AutoBoxSwitchTime)
, MUseAutoGears( "MUseAutoGears", setPxVehicleDriveDynDataMUseAutoGears, getPxVehicleDriveDynDataMUseAutoGears )
, MGearUpPressed( "MGearUpPressed", setPxVehicleDriveDynDataMGearUpPressed, getPxVehicleDriveDynDataMGearUpPressed )
, MGearDownPressed( "MGearDownPressed", setPxVehicleDriveDynDataMGearDownPressed, getPxVehicleDriveDynDataMGearDownPressed )
, MCurrentGear( "MCurrentGear", setPxVehicleDriveDynDataMCurrentGear, getPxVehicleDriveDynDataMCurrentGear )
, MTargetGear( "MTargetGear", setPxVehicleDriveDynDataMTargetGear, getPxVehicleDriveDynDataMTargetGear )
, MEnginespeed( "MEnginespeed", setPxVehicleDriveDynDataMEnginespeed, getPxVehicleDriveDynDataMEnginespeed )
, MGearSwitchTime( "MGearSwitchTime", setPxVehicleDriveDynDataMGearSwitchTime, getPxVehicleDriveDynDataMGearSwitchTime )
, MAutoBoxSwitchTime( "MAutoBoxSwitchTime", setPxVehicleDriveDynDataMAutoBoxSwitchTime, getPxVehicleDriveDynDataMAutoBoxSwitchTime )
{}
PxVehicleDriveDynDataGeneratedValues::PxVehicleDriveDynDataGeneratedValues( const PxVehicleDriveDynData* inSource )
:GearUp( getPxVehicleDriveDynData_GearUp( inSource ) )
,GearDown( getPxVehicleDriveDynData_GearDown( inSource ) )
,UseAutoGears( getPxVehicleDriveDynData_UseAutoGears( inSource ) )
,CurrentGear( getPxVehicleDriveDynData_CurrentGear( inSource ) )
,TargetGear( getPxVehicleDriveDynData_TargetGear( inSource ) )
,EngineRotationSpeed( getPxVehicleDriveDynData_EngineRotationSpeed( inSource ) )
,GearChange( getPxVehicleDriveDynData_GearChange( inSource ) )
,GearSwitchTime( getPxVehicleDriveDynData_GearSwitchTime( inSource ) )
,AutoBoxSwitchTime( getPxVehicleDriveDynData_AutoBoxSwitchTime( inSource ) )
,MUseAutoGears( inSource->mUseAutoGears )
,MGearUpPressed( inSource->mGearUpPressed )
,MGearDownPressed( inSource->mGearDownPressed )
,MCurrentGear( inSource->mCurrentGear )
,MTargetGear( inSource->mTargetGear )
,MEnginespeed( inSource->mEnginespeed )
,MGearSwitchTime( inSource->mGearSwitchTime )
,MAutoBoxSwitchTime( inSource->mAutoBoxSwitchTime )
{
PX_UNUSED(inSource);
}
void setPxVehicleDriveSimData_EngineData( PxVehicleDriveSimData* inObj, const PxVehicleEngineData & inArg){ inObj->setEngineData( inArg ); }
PxVehicleEngineData getPxVehicleDriveSimData_EngineData( const PxVehicleDriveSimData* inObj ) { return inObj->getEngineData(); }
void setPxVehicleDriveSimData_GearsData( PxVehicleDriveSimData* inObj, const PxVehicleGearsData & inArg){ inObj->setGearsData( inArg ); }
PxVehicleGearsData getPxVehicleDriveSimData_GearsData( const PxVehicleDriveSimData* inObj ) { return inObj->getGearsData(); }
void setPxVehicleDriveSimData_ClutchData( PxVehicleDriveSimData* inObj, const PxVehicleClutchData & inArg){ inObj->setClutchData( inArg ); }
PxVehicleClutchData getPxVehicleDriveSimData_ClutchData( const PxVehicleDriveSimData* inObj ) { return inObj->getClutchData(); }
void setPxVehicleDriveSimData_AutoBoxData( PxVehicleDriveSimData* inObj, const PxVehicleAutoBoxData & inArg){ inObj->setAutoBoxData( inArg ); }
PxVehicleAutoBoxData getPxVehicleDriveSimData_AutoBoxData( const PxVehicleDriveSimData* inObj ) { return inObj->getAutoBoxData(); }
PxVehicleDriveSimDataGeneratedInfo::PxVehicleDriveSimDataGeneratedInfo()
: EngineData( "EngineData", setPxVehicleDriveSimData_EngineData, getPxVehicleDriveSimData_EngineData)
, GearsData( "GearsData", setPxVehicleDriveSimData_GearsData, getPxVehicleDriveSimData_GearsData)
, ClutchData( "ClutchData", setPxVehicleDriveSimData_ClutchData, getPxVehicleDriveSimData_ClutchData)
, AutoBoxData( "AutoBoxData", setPxVehicleDriveSimData_AutoBoxData, getPxVehicleDriveSimData_AutoBoxData)
{}
PxVehicleDriveSimDataGeneratedValues::PxVehicleDriveSimDataGeneratedValues( const PxVehicleDriveSimData* inSource )
:EngineData( getPxVehicleDriveSimData_EngineData( inSource ) )
,GearsData( getPxVehicleDriveSimData_GearsData( inSource ) )
,ClutchData( getPxVehicleDriveSimData_ClutchData( inSource ) )
,AutoBoxData( getPxVehicleDriveSimData_AutoBoxData( inSource ) )
{
PX_UNUSED(inSource);
}
void setPxVehicleDriveSimData4W_DiffData( PxVehicleDriveSimData4W* inObj, const PxVehicleDifferential4WData & inArg){ inObj->setDiffData( inArg ); }
PxVehicleDifferential4WData getPxVehicleDriveSimData4W_DiffData( const PxVehicleDriveSimData4W* inObj ) { return inObj->getDiffData(); }
void setPxVehicleDriveSimData4W_AckermannGeometryData( PxVehicleDriveSimData4W* inObj, const PxVehicleAckermannGeometryData & inArg){ inObj->setAckermannGeometryData( inArg ); }
PxVehicleAckermannGeometryData getPxVehicleDriveSimData4W_AckermannGeometryData( const PxVehicleDriveSimData4W* inObj ) { return inObj->getAckermannGeometryData(); }
PxVehicleDriveSimData4WGeneratedInfo::PxVehicleDriveSimData4WGeneratedInfo()
: DiffData( "DiffData", setPxVehicleDriveSimData4W_DiffData, getPxVehicleDriveSimData4W_DiffData)
, AckermannGeometryData( "AckermannGeometryData", setPxVehicleDriveSimData4W_AckermannGeometryData, getPxVehicleDriveSimData4W_AckermannGeometryData)
{}
PxVehicleDriveSimData4WGeneratedValues::PxVehicleDriveSimData4WGeneratedValues( const PxVehicleDriveSimData4W* inSource )
:PxVehicleDriveSimDataGeneratedValues( inSource )
,DiffData( getPxVehicleDriveSimData4W_DiffData( inSource ) )
,AckermannGeometryData( getPxVehicleDriveSimData4W_AckermannGeometryData( inSource ) )
{
PX_UNUSED(inSource);
}
const char * getPxVehicleDrive_ConcreteTypeName( const PxVehicleDrive* inObj ) { return inObj->getConcreteTypeName(); }
inline PxVehicleDriveDynData getPxVehicleDriveMDriveDynData( const PxVehicleDrive* inOwner ) { return inOwner->mDriveDynData; }
inline void setPxVehicleDriveMDriveDynData( PxVehicleDrive* inOwner, PxVehicleDriveDynData inData) { inOwner->mDriveDynData = inData; }
PxVehicleDriveGeneratedInfo::PxVehicleDriveGeneratedInfo()
: ConcreteTypeName( "ConcreteTypeName", getPxVehicleDrive_ConcreteTypeName)
, MDriveDynData( "MDriveDynData", setPxVehicleDriveMDriveDynData, getPxVehicleDriveMDriveDynData )
{}
PxVehicleDriveGeneratedValues::PxVehicleDriveGeneratedValues( const PxVehicleDrive* inSource )
:PxVehicleWheelsGeneratedValues( inSource )
,ConcreteTypeName( getPxVehicleDrive_ConcreteTypeName( inSource ) )
,MDriveDynData( inSource->mDriveDynData )
{
PX_UNUSED(inSource);
}
const char * getPxVehicleDrive4W_ConcreteTypeName( const PxVehicleDrive4W* inObj ) { return inObj->getConcreteTypeName(); }
inline PxVehicleDriveSimData4W getPxVehicleDrive4WMDriveSimData( const PxVehicleDrive4W* inOwner ) { return inOwner->mDriveSimData; }
inline void setPxVehicleDrive4WMDriveSimData( PxVehicleDrive4W* inOwner, PxVehicleDriveSimData4W inData) { inOwner->mDriveSimData = inData; }
PxVehicleDrive4WGeneratedInfo::PxVehicleDrive4WGeneratedInfo()
: ConcreteTypeName( "ConcreteTypeName", getPxVehicleDrive4W_ConcreteTypeName)
, MDriveSimData( "MDriveSimData", setPxVehicleDrive4WMDriveSimData, getPxVehicleDrive4WMDriveSimData )
{}
PxVehicleDrive4WGeneratedValues::PxVehicleDrive4WGeneratedValues( const PxVehicleDrive4W* inSource )
:PxVehicleDriveGeneratedValues( inSource )
,ConcreteTypeName( getPxVehicleDrive4W_ConcreteTypeName( inSource ) )
,MDriveSimData( inSource->mDriveSimData )
{
PX_UNUSED(inSource);
}
void setPxVehicleDriveTank_DriveModel( PxVehicleDriveTank* inObj, const PxVehicleDriveTankControlModel::Enum inArg){ inObj->setDriveModel( inArg ); }
PxVehicleDriveTankControlModel::Enum getPxVehicleDriveTank_DriveModel( const PxVehicleDriveTank* inObj ) { return inObj->getDriveModel(); }
const char * getPxVehicleDriveTank_ConcreteTypeName( const PxVehicleDriveTank* inObj ) { return inObj->getConcreteTypeName(); }
inline PxVehicleDriveSimData getPxVehicleDriveTankMDriveSimData( const PxVehicleDriveTank* inOwner ) { return inOwner->mDriveSimData; }
inline void setPxVehicleDriveTankMDriveSimData( PxVehicleDriveTank* inOwner, PxVehicleDriveSimData inData) { inOwner->mDriveSimData = inData; }
PxVehicleDriveTankGeneratedInfo::PxVehicleDriveTankGeneratedInfo()
: DriveModel( "DriveModel", setPxVehicleDriveTank_DriveModel, getPxVehicleDriveTank_DriveModel)
, ConcreteTypeName( "ConcreteTypeName", getPxVehicleDriveTank_ConcreteTypeName)
, MDriveSimData( "MDriveSimData", setPxVehicleDriveTankMDriveSimData, getPxVehicleDriveTankMDriveSimData )
{}
PxVehicleDriveTankGeneratedValues::PxVehicleDriveTankGeneratedValues( const PxVehicleDriveTank* inSource )
:PxVehicleDriveGeneratedValues( inSource )
,DriveModel( getPxVehicleDriveTank_DriveModel( inSource ) )
,ConcreteTypeName( getPxVehicleDriveTank_ConcreteTypeName( inSource ) )
,MDriveSimData( inSource->mDriveSimData )
{
PX_UNUSED(inSource);
}
void setPxVehicleDriveSimDataNW_DiffData( PxVehicleDriveSimDataNW* inObj, const PxVehicleDifferentialNWData & inArg){ inObj->setDiffData( inArg ); }
PxVehicleDifferentialNWData getPxVehicleDriveSimDataNW_DiffData( const PxVehicleDriveSimDataNW* inObj ) { return inObj->getDiffData(); }
PxVehicleDriveSimDataNWGeneratedInfo::PxVehicleDriveSimDataNWGeneratedInfo()
: DiffData( "DiffData", setPxVehicleDriveSimDataNW_DiffData, getPxVehicleDriveSimDataNW_DiffData)
{}
PxVehicleDriveSimDataNWGeneratedValues::PxVehicleDriveSimDataNWGeneratedValues( const PxVehicleDriveSimDataNW* inSource )
:PxVehicleDriveSimDataGeneratedValues( inSource )
,DiffData( getPxVehicleDriveSimDataNW_DiffData( inSource ) )
{
PX_UNUSED(inSource);
}
const char * getPxVehicleDriveNW_ConcreteTypeName( const PxVehicleDriveNW* inObj ) { return inObj->getConcreteTypeName(); }
inline PxVehicleDriveSimDataNW getPxVehicleDriveNWMDriveSimData( const PxVehicleDriveNW* inOwner ) { return inOwner->mDriveSimData; }
inline void setPxVehicleDriveNWMDriveSimData( PxVehicleDriveNW* inOwner, PxVehicleDriveSimDataNW inData) { inOwner->mDriveSimData = inData; }
PxVehicleDriveNWGeneratedInfo::PxVehicleDriveNWGeneratedInfo()
: ConcreteTypeName( "ConcreteTypeName", getPxVehicleDriveNW_ConcreteTypeName)
, MDriveSimData( "MDriveSimData", setPxVehicleDriveNWMDriveSimData, getPxVehicleDriveNWMDriveSimData )
{}
PxVehicleDriveNWGeneratedValues::PxVehicleDriveNWGeneratedValues( const PxVehicleDriveNW* inSource )
:PxVehicleDriveGeneratedValues( inSource )
,ConcreteTypeName( getPxVehicleDriveNW_ConcreteTypeName( inSource ) )
,MDriveSimData( inSource->mDriveSimData )
{
PX_UNUSED(inSource);
}
PxReal getPxVehicleNoDrive_BrakeTorque( const PxVehicleNoDrive* inObj, const PxU32 index ) { return inObj->getBrakeTorque( index ); }
PxU32 getNbPxVehicleNoDrive_BrakeTorque( const PxVehicleNoDrive* inObj ) { return inObj->getNbBrakeTorque( ); }
void setPxVehicleNoDrive_BrakeTorque( PxVehicleNoDrive* inObj, const PxU32 inIndex, PxReal inValue ){ inObj->setBrakeTorque( inIndex, inValue ); }
PxReal getPxVehicleNoDrive_DriveTorque( const PxVehicleNoDrive* inObj, const PxU32 index ) { return inObj->getDriveTorque( index ); }
PxU32 getNbPxVehicleNoDrive_DriveTorque( const PxVehicleNoDrive* inObj ) { return inObj->getNbDriveTorque( ); }
void setPxVehicleNoDrive_DriveTorque( PxVehicleNoDrive* inObj, const PxU32 inIndex, PxReal inValue ){ inObj->setDriveTorque( inIndex, inValue ); }
PxReal getPxVehicleNoDrive_SteerAngle( const PxVehicleNoDrive* inObj, const PxU32 index ) { return inObj->getSteerAngle( index ); }
PxU32 getNbPxVehicleNoDrive_SteerAngle( const PxVehicleNoDrive* inObj ) { return inObj->getNbSteerAngle( ); }
void setPxVehicleNoDrive_SteerAngle( PxVehicleNoDrive* inObj, const PxU32 inIndex, PxReal inValue ){ inObj->setSteerAngle( inIndex, inValue ); }
const char * getPxVehicleNoDrive_ConcreteTypeName( const PxVehicleNoDrive* inObj ) { return inObj->getConcreteTypeName(); }
PxVehicleNoDriveGeneratedInfo::PxVehicleNoDriveGeneratedInfo()
: BrakeTorque( "BrakeTorque", getPxVehicleNoDrive_BrakeTorque, getNbPxVehicleNoDrive_BrakeTorque, setPxVehicleNoDrive_BrakeTorque )
, DriveTorque( "DriveTorque", getPxVehicleNoDrive_DriveTorque, getNbPxVehicleNoDrive_DriveTorque, setPxVehicleNoDrive_DriveTorque )
, SteerAngle( "SteerAngle", getPxVehicleNoDrive_SteerAngle, getNbPxVehicleNoDrive_SteerAngle, setPxVehicleNoDrive_SteerAngle )
, ConcreteTypeName( "ConcreteTypeName", getPxVehicleNoDrive_ConcreteTypeName)
{}
PxVehicleNoDriveGeneratedValues::PxVehicleNoDriveGeneratedValues( const PxVehicleNoDrive* inSource )
:PxVehicleWheelsGeneratedValues( inSource )
,ConcreteTypeName( getPxVehicleNoDrive_ConcreteTypeName( inSource ) )
{
PX_UNUSED(inSource);
}
| 69,970 |
C++
| 93.17362 | 217 | 0.843061 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/physxmetadata/include/PxVehicleMetaDataObjects.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_VEHICLE_META_DATA_OBJECTS_H
#define PX_VEHICLE_META_DATA_OBJECTS_H
#include "PxPhysicsAPI.h"
#include "extensions/PxExtensionsAPI.h"
#include "PxMetaDataObjects.h"
#include "PxExtensionMetaDataObjects.h"
/** \addtogroup physics
@{
*/
namespace physx
{
struct PxVehiclePropertyInfoName
{
enum Enum
{
Unnamed = PxExtensionsPropertyInfoName::LastPxPropertyInfoName,
#include "PxVehicleAutoGeneratedMetaDataObjectNames.h"
LastPxPropertyInfoName
};
};
#define DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( type, prop, valueStruct ) \
template<> struct PxPropertyToValueStructMemberMap< PxVehiclePropertyInfoName::type##_##prop > \
{ \
PxU32 Offset; \
PxPropertyToValueStructMemberMap< PxVehiclePropertyInfoName::type##_##prop >() : Offset( PX_OFFSET_OF_RT( valueStruct, prop ) ) {} \
template<typename TOperator> void visitProp( TOperator inOperator, valueStruct& inStruct ) { inOperator( inStruct.prop ); } \
};
struct MFrictionVsSlipGraphProperty : public PxExtendedDualIndexedPropertyInfo<PxVehiclePropertyInfoName::PxVehicleTireData_MFrictionVsSlipGraph
, PxVehicleTireData
, PxU32
, PxU32
, PxReal>
{
PX_PHYSX_CORE_API MFrictionVsSlipGraphProperty();
};
struct MTorqueCurveProperty : public PxFixedSizeLookupTablePropertyInfo<PxVehiclePropertyInfoName::PxVehicleEngineData_MTorqueCurve
, PxVehicleEngineData
, PxU32
, PxReal>
{
PX_PHYSX_CORE_API MTorqueCurveProperty();
};
#if PX_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-identifier"
#if __has_warning("-Wshadow-field")
#pragma clang diagnostic ignored "-Wshadow-field"
#endif
#endif
#include "PxVehicleAutoGeneratedMetaDataObjects.h"
#if PX_CLANG
#pragma clang diagnostic pop
#endif
#undef DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP
}
/** @} */
#endif
| 3,682 |
C
| 36.969072 | 144 | 0.730038 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/physxmetadata/include/PxVehicleAutoGeneratedMetaDataObjects.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// This code is auto-generated by the PhysX Clang metadata generator. Do not edit or be
// prepared for your edits to be quietly ignored next time the clang metadata generator is
// run. You can find the most recent version of clang metadata generator by contacting
// Chris Nuernberger <[email protected]> or Dilip or Adam.
// The source code for the generate was at one time checked into:
// physx/PhysXMetaDataGenerator/llvm/tools/clang/lib/Frontend/PhysXMetaDataAction.cpp
#define THERE_IS_NO_INCLUDE_GUARD_HERE_FOR_A_REASON
#define PX_PROPERTY_INFO_NAME PxVehiclePropertyInfoName
class PxVehicleChassisData;
struct PxVehicleChassisDataGeneratedValues
{
PxVec3 MMOI;
PxReal MMass;
PxVec3 MCMOffset;
PxVehicleChassisDataGeneratedValues( const PxVehicleChassisData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleChassisData, MMOI, PxVehicleChassisDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleChassisData, MMass, PxVehicleChassisDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleChassisData, MCMOffset, PxVehicleChassisDataGeneratedValues)
struct PxVehicleChassisDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleChassisData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleChassisData_MMOI, PxVehicleChassisData, PxVec3, PxVec3 > MMOI;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleChassisData_MMass, PxVehicleChassisData, PxReal, PxReal > MMass;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleChassisData_MCMOffset, PxVehicleChassisData, PxVec3, PxVec3 > MCMOffset;
PxVehicleChassisDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleChassisData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 3; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( MMOI, inStartIndex + 0 );;
inOperator( MMass, inStartIndex + 1 );;
inOperator( MCMOffset, inStartIndex + 2 );;
return 3 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleChassisData>
{
PxVehicleChassisDataGeneratedInfo Info;
const PxVehicleChassisDataGeneratedInfo* getInfo() { return &Info; }
};
static PxU32ToName g_physx__PxEMPTYConversion[] = {
{ "PxEmpty", static_cast<PxU32>( physx::PxEmpty ) },
{ NULL, 0 }
};
template<> struct PxEnumTraits< const physx::PxEMPTY > { PxEnumTraits() : NameConversion( g_physx__PxEMPTYConversion ) {} const PxU32ToName* NameConversion; };
class PxVehicleEngineData;
struct PxVehicleEngineDataGeneratedValues
{
PxReal RecipMOI;
PxReal RecipMaxOmega;
PxReal MMOI;
PxReal MPeakTorque;
PxReal MMaxOmega;
PxReal MDampingRateFullThrottle;
PxReal MDampingRateZeroThrottleClutchEngaged;
PxReal MDampingRateZeroThrottleClutchDisengaged;
PxVehicleEngineDataGeneratedValues( const PxVehicleEngineData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, RecipMOI, PxVehicleEngineDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, RecipMaxOmega, PxVehicleEngineDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, MMOI, PxVehicleEngineDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, MPeakTorque, PxVehicleEngineDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, MMaxOmega, PxVehicleEngineDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, MDampingRateFullThrottle, PxVehicleEngineDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, MDampingRateZeroThrottleClutchEngaged, PxVehicleEngineDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleEngineData, MDampingRateZeroThrottleClutchDisengaged, PxVehicleEngineDataGeneratedValues)
struct PxVehicleEngineDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleEngineData"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_RecipMOI, PxVehicleEngineData, PxReal > RecipMOI;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_RecipMaxOmega, PxVehicleEngineData, PxReal > RecipMaxOmega;
MTorqueCurveProperty MTorqueCurve;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_MMOI, PxVehicleEngineData, PxReal, PxReal > MMOI;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_MPeakTorque, PxVehicleEngineData, PxReal, PxReal > MPeakTorque;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_MMaxOmega, PxVehicleEngineData, PxReal, PxReal > MMaxOmega;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_MDampingRateFullThrottle, PxVehicleEngineData, PxReal, PxReal > MDampingRateFullThrottle;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_MDampingRateZeroThrottleClutchEngaged, PxVehicleEngineData, PxReal, PxReal > MDampingRateZeroThrottleClutchEngaged;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleEngineData_MDampingRateZeroThrottleClutchDisengaged, PxVehicleEngineData, PxReal, PxReal > MDampingRateZeroThrottleClutchDisengaged;
PxVehicleEngineDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleEngineData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 9; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( RecipMOI, inStartIndex + 0 );;
inOperator( RecipMaxOmega, inStartIndex + 1 );;
inOperator( MTorqueCurve, inStartIndex + 2 );;
inOperator( MMOI, inStartIndex + 3 );;
inOperator( MPeakTorque, inStartIndex + 4 );;
inOperator( MMaxOmega, inStartIndex + 5 );;
inOperator( MDampingRateFullThrottle, inStartIndex + 6 );;
inOperator( MDampingRateZeroThrottleClutchEngaged, inStartIndex + 7 );;
inOperator( MDampingRateZeroThrottleClutchDisengaged, inStartIndex + 8 );;
return 9 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleEngineData>
{
PxVehicleEngineDataGeneratedInfo Info;
const PxVehicleEngineDataGeneratedInfo* getInfo() { return &Info; }
};
static PxU32ToName g_physx__PxVehicleGearsData__EnumConversion[] = {
{ "eREVERSE", static_cast<PxU32>( physx::PxVehicleGearsData::eREVERSE ) },
{ "eNEUTRAL", static_cast<PxU32>( physx::PxVehicleGearsData::eNEUTRAL ) },
{ "eFIRST", static_cast<PxU32>( physx::PxVehicleGearsData::eFIRST ) },
{ "eSECOND", static_cast<PxU32>( physx::PxVehicleGearsData::eSECOND ) },
{ "eTHIRD", static_cast<PxU32>( physx::PxVehicleGearsData::eTHIRD ) },
{ "eFOURTH", static_cast<PxU32>( physx::PxVehicleGearsData::eFOURTH ) },
{ "eFIFTH", static_cast<PxU32>( physx::PxVehicleGearsData::eFIFTH ) },
{ "eSIXTH", static_cast<PxU32>( physx::PxVehicleGearsData::eSIXTH ) },
{ "eSEVENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eSEVENTH ) },
{ "eEIGHTH", static_cast<PxU32>( physx::PxVehicleGearsData::eEIGHTH ) },
{ "eNINTH", static_cast<PxU32>( physx::PxVehicleGearsData::eNINTH ) },
{ "eTENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTENTH ) },
{ "eELEVENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eELEVENTH ) },
{ "eTWELFTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWELFTH ) },
{ "eTHIRTEENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTHIRTEENTH ) },
{ "eFOURTEENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eFOURTEENTH ) },
{ "eFIFTEENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eFIFTEENTH ) },
{ "eSIXTEENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eSIXTEENTH ) },
{ "eSEVENTEENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eSEVENTEENTH ) },
{ "eEIGHTEENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eEIGHTEENTH ) },
{ "eNINETEENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eNINETEENTH ) },
{ "eTWENTIETH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTIETH ) },
{ "eTWENTYFIRST", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYFIRST ) },
{ "eTWENTYSECOND", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYSECOND ) },
{ "eTWENTYTHIRD", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYTHIRD ) },
{ "eTWENTYFOURTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYFOURTH ) },
{ "eTWENTYFIFTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYFIFTH ) },
{ "eTWENTYSIXTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYSIXTH ) },
{ "eTWENTYSEVENTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYSEVENTH ) },
{ "eTWENTYEIGHTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYEIGHTH ) },
{ "eTWENTYNINTH", static_cast<PxU32>( physx::PxVehicleGearsData::eTWENTYNINTH ) },
{ "eTHIRTIETH", static_cast<PxU32>( physx::PxVehicleGearsData::eTHIRTIETH ) },
{ NULL, 0 }
};
template<> struct PxEnumTraits< physx::PxVehicleGearsData::Enum > { PxEnumTraits() : NameConversion( g_physx__PxVehicleGearsData__EnumConversion ) {} const PxU32ToName* NameConversion; };
class PxVehicleGearsData;
struct PxVehicleGearsDataGeneratedValues
{
PxReal GearRatio[physx::PxVehicleGearsData::eGEARSRATIO_COUNT];
PxReal MFinalRatio;
PxU32 MNbRatios;
PxReal MSwitchTime;
PxVehicleGearsDataGeneratedValues( const PxVehicleGearsData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleGearsData, GearRatio, PxVehicleGearsDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleGearsData, MFinalRatio, PxVehicleGearsDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleGearsData, MNbRatios, PxVehicleGearsDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleGearsData, MSwitchTime, PxVehicleGearsDataGeneratedValues)
struct PxVehicleGearsDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleGearsData"; }
PxIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleGearsData_GearRatio, PxVehicleGearsData, PxVehicleGearsData::Enum, PxReal > GearRatio;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleGearsData_MFinalRatio, PxVehicleGearsData, PxReal, PxReal > MFinalRatio;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleGearsData_MNbRatios, PxVehicleGearsData, PxU32, PxU32 > MNbRatios;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleGearsData_MSwitchTime, PxVehicleGearsData, PxReal, PxReal > MSwitchTime;
PxVehicleGearsDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleGearsData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 4; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( GearRatio, inStartIndex + 0 );;
inOperator( MFinalRatio, inStartIndex + 1 );;
inOperator( MNbRatios, inStartIndex + 2 );;
inOperator( MSwitchTime, inStartIndex + 3 );;
return 4 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleGearsData>
{
PxVehicleGearsDataGeneratedInfo Info;
const PxVehicleGearsDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleAutoBoxData;
struct PxVehicleAutoBoxDataGeneratedValues
{
PxReal Latency;
PxReal UpRatios[physx::PxVehicleGearsData::eGEARSRATIO_COUNT];
PxReal DownRatios[physx::PxVehicleGearsData::eGEARSRATIO_COUNT];
PxVehicleAutoBoxDataGeneratedValues( const PxVehicleAutoBoxData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAutoBoxData, Latency, PxVehicleAutoBoxDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAutoBoxData, UpRatios, PxVehicleAutoBoxDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAutoBoxData, DownRatios, PxVehicleAutoBoxDataGeneratedValues)
struct PxVehicleAutoBoxDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleAutoBoxData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAutoBoxData_Latency, PxVehicleAutoBoxData, const PxReal, PxReal > Latency;
PxIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAutoBoxData_UpRatios, PxVehicleAutoBoxData, PxVehicleGearsData::Enum, PxReal > UpRatios;
PxIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAutoBoxData_DownRatios, PxVehicleAutoBoxData, PxVehicleGearsData::Enum, PxReal > DownRatios;
PxVehicleAutoBoxDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleAutoBoxData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 3; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( Latency, inStartIndex + 0 );;
inOperator( UpRatios, inStartIndex + 1 );;
inOperator( DownRatios, inStartIndex + 2 );;
return 3 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleAutoBoxData>
{
PxVehicleAutoBoxDataGeneratedInfo Info;
const PxVehicleAutoBoxDataGeneratedInfo* getInfo() { return &Info; }
};
static PxU32ToName g_physx__PxVehicleDifferential4WData__EnumConversion[] = {
{ "eDIFF_TYPE_LS_4WD", static_cast<PxU32>( physx::PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD ) },
{ "eDIFF_TYPE_LS_FRONTWD", static_cast<PxU32>( physx::PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD ) },
{ "eDIFF_TYPE_LS_REARWD", static_cast<PxU32>( physx::PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD ) },
{ "eDIFF_TYPE_OPEN_4WD", static_cast<PxU32>( physx::PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD ) },
{ "eDIFF_TYPE_OPEN_FRONTWD", static_cast<PxU32>( physx::PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD ) },
{ "eDIFF_TYPE_OPEN_REARWD", static_cast<PxU32>( physx::PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD ) },
{ "eMAX_NB_DIFF_TYPES", static_cast<PxU32>( physx::PxVehicleDifferential4WData::eMAX_NB_DIFF_TYPES ) },
{ NULL, 0 }
};
template<> struct PxEnumTraits< physx::PxVehicleDifferential4WData::Enum > { PxEnumTraits() : NameConversion( g_physx__PxVehicleDifferential4WData__EnumConversion ) {} const PxU32ToName* NameConversion; };
class PxVehicleDifferential4WData;
struct PxVehicleDifferential4WDataGeneratedValues
{
PxReal MFrontRearSplit;
PxReal MFrontLeftRightSplit;
PxReal MRearLeftRightSplit;
PxReal MCentreBias;
PxReal MFrontBias;
PxReal MRearBias;
PxVehicleDifferential4WData::Enum MType;
PxVehicleDifferential4WDataGeneratedValues( const PxVehicleDifferential4WData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferential4WData, MFrontRearSplit, PxVehicleDifferential4WDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferential4WData, MFrontLeftRightSplit, PxVehicleDifferential4WDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferential4WData, MRearLeftRightSplit, PxVehicleDifferential4WDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferential4WData, MCentreBias, PxVehicleDifferential4WDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferential4WData, MFrontBias, PxVehicleDifferential4WDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferential4WData, MRearBias, PxVehicleDifferential4WDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferential4WData, MType, PxVehicleDifferential4WDataGeneratedValues)
struct PxVehicleDifferential4WDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDifferential4WData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferential4WData_MFrontRearSplit, PxVehicleDifferential4WData, PxReal, PxReal > MFrontRearSplit;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferential4WData_MFrontLeftRightSplit, PxVehicleDifferential4WData, PxReal, PxReal > MFrontLeftRightSplit;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferential4WData_MRearLeftRightSplit, PxVehicleDifferential4WData, PxReal, PxReal > MRearLeftRightSplit;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferential4WData_MCentreBias, PxVehicleDifferential4WData, PxReal, PxReal > MCentreBias;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferential4WData_MFrontBias, PxVehicleDifferential4WData, PxReal, PxReal > MFrontBias;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferential4WData_MRearBias, PxVehicleDifferential4WData, PxReal, PxReal > MRearBias;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferential4WData_MType, PxVehicleDifferential4WData, PxVehicleDifferential4WData::Enum, PxVehicleDifferential4WData::Enum > MType;
PxVehicleDifferential4WDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDifferential4WData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 7; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( MFrontRearSplit, inStartIndex + 0 );;
inOperator( MFrontLeftRightSplit, inStartIndex + 1 );;
inOperator( MRearLeftRightSplit, inStartIndex + 2 );;
inOperator( MCentreBias, inStartIndex + 3 );;
inOperator( MFrontBias, inStartIndex + 4 );;
inOperator( MRearBias, inStartIndex + 5 );;
inOperator( MType, inStartIndex + 6 );;
return 7 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDifferential4WData>
{
PxVehicleDifferential4WDataGeneratedInfo Info;
const PxVehicleDifferential4WDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDifferentialNWData;
struct PxVehicleDifferentialNWDataGeneratedValues
{
PxU32 DrivenWheelStatus;
PxVehicleDifferentialNWDataGeneratedValues( const PxVehicleDifferentialNWData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDifferentialNWData, DrivenWheelStatus, PxVehicleDifferentialNWDataGeneratedValues)
struct PxVehicleDifferentialNWDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDifferentialNWData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDifferentialNWData_DrivenWheelStatus, PxVehicleDifferentialNWData, PxU32, PxU32 > DrivenWheelStatus;
PxVehicleDifferentialNWDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDifferentialNWData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 1; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( DrivenWheelStatus, inStartIndex + 0 );;
return 1 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDifferentialNWData>
{
PxVehicleDifferentialNWDataGeneratedInfo Info;
const PxVehicleDifferentialNWDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleAckermannGeometryData;
struct PxVehicleAckermannGeometryDataGeneratedValues
{
PxReal MAccuracy;
PxReal MFrontWidth;
PxReal MRearWidth;
PxReal MAxleSeparation;
PxVehicleAckermannGeometryDataGeneratedValues( const PxVehicleAckermannGeometryData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAckermannGeometryData, MAccuracy, PxVehicleAckermannGeometryDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAckermannGeometryData, MFrontWidth, PxVehicleAckermannGeometryDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAckermannGeometryData, MRearWidth, PxVehicleAckermannGeometryDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAckermannGeometryData, MAxleSeparation, PxVehicleAckermannGeometryDataGeneratedValues)
struct PxVehicleAckermannGeometryDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleAckermannGeometryData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAckermannGeometryData_MAccuracy, PxVehicleAckermannGeometryData, PxReal, PxReal > MAccuracy;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAckermannGeometryData_MFrontWidth, PxVehicleAckermannGeometryData, PxReal, PxReal > MFrontWidth;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAckermannGeometryData_MRearWidth, PxVehicleAckermannGeometryData, PxReal, PxReal > MRearWidth;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAckermannGeometryData_MAxleSeparation, PxVehicleAckermannGeometryData, PxReal, PxReal > MAxleSeparation;
PxVehicleAckermannGeometryDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleAckermannGeometryData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 4; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( MAccuracy, inStartIndex + 0 );;
inOperator( MFrontWidth, inStartIndex + 1 );;
inOperator( MRearWidth, inStartIndex + 2 );;
inOperator( MAxleSeparation, inStartIndex + 3 );;
return 4 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleAckermannGeometryData>
{
PxVehicleAckermannGeometryDataGeneratedInfo Info;
const PxVehicleAckermannGeometryDataGeneratedInfo* getInfo() { return &Info; }
};
static PxU32ToName g_physx__PxVehicleClutchAccuracyMode__EnumConversion[] = {
{ "eESTIMATE", static_cast<PxU32>( physx::PxVehicleClutchAccuracyMode::eESTIMATE ) },
{ "eBEST_POSSIBLE", static_cast<PxU32>( physx::PxVehicleClutchAccuracyMode::eBEST_POSSIBLE ) },
{ NULL, 0 }
};
template<> struct PxEnumTraits< physx::PxVehicleClutchAccuracyMode::Enum > { PxEnumTraits() : NameConversion( g_physx__PxVehicleClutchAccuracyMode__EnumConversion ) {} const PxU32ToName* NameConversion; };
class PxVehicleClutchData;
struct PxVehicleClutchDataGeneratedValues
{
PxReal MStrength;
PxVehicleClutchAccuracyMode::Enum MAccuracyMode;
PxU32 MEstimateIterations;
PxVehicleClutchDataGeneratedValues( const PxVehicleClutchData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleClutchData, MStrength, PxVehicleClutchDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleClutchData, MAccuracyMode, PxVehicleClutchDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleClutchData, MEstimateIterations, PxVehicleClutchDataGeneratedValues)
struct PxVehicleClutchDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleClutchData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleClutchData_MStrength, PxVehicleClutchData, PxReal, PxReal > MStrength;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleClutchData_MAccuracyMode, PxVehicleClutchData, PxVehicleClutchAccuracyMode::Enum, PxVehicleClutchAccuracyMode::Enum > MAccuracyMode;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleClutchData_MEstimateIterations, PxVehicleClutchData, PxU32, PxU32 > MEstimateIterations;
PxVehicleClutchDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleClutchData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 3; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( MStrength, inStartIndex + 0 );;
inOperator( MAccuracyMode, inStartIndex + 1 );;
inOperator( MEstimateIterations, inStartIndex + 2 );;
return 3 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleClutchData>
{
PxVehicleClutchDataGeneratedInfo Info;
const PxVehicleClutchDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleTireLoadFilterData;
struct PxVehicleTireLoadFilterDataGeneratedValues
{
PxReal Denominator;
PxReal MMinNormalisedLoad;
PxReal MMinFilteredNormalisedLoad;
PxReal MMaxNormalisedLoad;
PxReal MMaxFilteredNormalisedLoad;
PxVehicleTireLoadFilterDataGeneratedValues( const PxVehicleTireLoadFilterData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireLoadFilterData, Denominator, PxVehicleTireLoadFilterDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireLoadFilterData, MMinNormalisedLoad, PxVehicleTireLoadFilterDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireLoadFilterData, MMinFilteredNormalisedLoad, PxVehicleTireLoadFilterDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireLoadFilterData, MMaxNormalisedLoad, PxVehicleTireLoadFilterDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireLoadFilterData, MMaxFilteredNormalisedLoad, PxVehicleTireLoadFilterDataGeneratedValues)
struct PxVehicleTireLoadFilterDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleTireLoadFilterData"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireLoadFilterData_Denominator, PxVehicleTireLoadFilterData, PxReal > Denominator;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireLoadFilterData_MMinNormalisedLoad, PxVehicleTireLoadFilterData, PxReal, PxReal > MMinNormalisedLoad;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireLoadFilterData_MMinFilteredNormalisedLoad, PxVehicleTireLoadFilterData, PxReal, PxReal > MMinFilteredNormalisedLoad;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireLoadFilterData_MMaxNormalisedLoad, PxVehicleTireLoadFilterData, PxReal, PxReal > MMaxNormalisedLoad;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireLoadFilterData_MMaxFilteredNormalisedLoad, PxVehicleTireLoadFilterData, PxReal, PxReal > MMaxFilteredNormalisedLoad;
PxVehicleTireLoadFilterDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleTireLoadFilterData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 5; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( Denominator, inStartIndex + 0 );;
inOperator( MMinNormalisedLoad, inStartIndex + 1 );;
inOperator( MMinFilteredNormalisedLoad, inStartIndex + 2 );;
inOperator( MMaxNormalisedLoad, inStartIndex + 3 );;
inOperator( MMaxFilteredNormalisedLoad, inStartIndex + 4 );;
return 5 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleTireLoadFilterData>
{
PxVehicleTireLoadFilterDataGeneratedInfo Info;
const PxVehicleTireLoadFilterDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleWheelData;
struct PxVehicleWheelDataGeneratedValues
{
PxReal RecipRadius;
PxReal RecipMOI;
PxReal MRadius;
PxReal MWidth;
PxReal MMass;
PxReal MMOI;
PxReal MDampingRate;
PxReal MMaxBrakeTorque;
PxReal MMaxHandBrakeTorque;
PxReal MMaxSteer;
PxReal MToeAngle;
PxVehicleWheelDataGeneratedValues( const PxVehicleWheelData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, RecipRadius, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, RecipMOI, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MRadius, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MWidth, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MMass, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MMOI, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MDampingRate, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MMaxBrakeTorque, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MMaxHandBrakeTorque, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MMaxSteer, PxVehicleWheelDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelData, MToeAngle, PxVehicleWheelDataGeneratedValues)
struct PxVehicleWheelDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleWheelData"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_RecipRadius, PxVehicleWheelData, PxReal > RecipRadius;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_RecipMOI, PxVehicleWheelData, PxReal > RecipMOI;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MRadius, PxVehicleWheelData, PxReal, PxReal > MRadius;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MWidth, PxVehicleWheelData, PxReal, PxReal > MWidth;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MMass, PxVehicleWheelData, PxReal, PxReal > MMass;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MMOI, PxVehicleWheelData, PxReal, PxReal > MMOI;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MDampingRate, PxVehicleWheelData, PxReal, PxReal > MDampingRate;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MMaxBrakeTorque, PxVehicleWheelData, PxReal, PxReal > MMaxBrakeTorque;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MMaxHandBrakeTorque, PxVehicleWheelData, PxReal, PxReal > MMaxHandBrakeTorque;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MMaxSteer, PxVehicleWheelData, PxReal, PxReal > MMaxSteer;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelData_MToeAngle, PxVehicleWheelData, PxReal, PxReal > MToeAngle;
PxVehicleWheelDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleWheelData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 11; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( RecipRadius, inStartIndex + 0 );;
inOperator( RecipMOI, inStartIndex + 1 );;
inOperator( MRadius, inStartIndex + 2 );;
inOperator( MWidth, inStartIndex + 3 );;
inOperator( MMass, inStartIndex + 4 );;
inOperator( MMOI, inStartIndex + 5 );;
inOperator( MDampingRate, inStartIndex + 6 );;
inOperator( MMaxBrakeTorque, inStartIndex + 7 );;
inOperator( MMaxHandBrakeTorque, inStartIndex + 8 );;
inOperator( MMaxSteer, inStartIndex + 9 );;
inOperator( MToeAngle, inStartIndex + 10 );;
return 11 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleWheelData>
{
PxVehicleWheelDataGeneratedInfo Info;
const PxVehicleWheelDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleSuspensionData;
struct PxVehicleSuspensionDataGeneratedValues
{
PxReal RecipMaxCompression;
PxReal RecipMaxDroop;
PxReal MSpringStrength;
PxReal MSpringDamperRate;
PxReal MMaxCompression;
PxReal MMaxDroop;
PxReal MSprungMass;
PxReal MCamberAtRest;
PxReal MCamberAtMaxCompression;
PxReal MCamberAtMaxDroop;
PxVehicleSuspensionDataGeneratedValues( const PxVehicleSuspensionData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, RecipMaxCompression, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, RecipMaxDroop, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MSpringStrength, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MSpringDamperRate, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MMaxCompression, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MMaxDroop, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MSprungMass, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MCamberAtRest, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MCamberAtMaxCompression, PxVehicleSuspensionDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleSuspensionData, MCamberAtMaxDroop, PxVehicleSuspensionDataGeneratedValues)
struct PxVehicleSuspensionDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleSuspensionData"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_RecipMaxCompression, PxVehicleSuspensionData, PxReal > RecipMaxCompression;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_RecipMaxDroop, PxVehicleSuspensionData, PxReal > RecipMaxDroop;
PxWriteOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MassAndPreserveNaturalFrequency, PxVehicleSuspensionData, const PxReal > MassAndPreserveNaturalFrequency;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MSpringStrength, PxVehicleSuspensionData, PxReal, PxReal > MSpringStrength;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MSpringDamperRate, PxVehicleSuspensionData, PxReal, PxReal > MSpringDamperRate;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MMaxCompression, PxVehicleSuspensionData, PxReal, PxReal > MMaxCompression;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MMaxDroop, PxVehicleSuspensionData, PxReal, PxReal > MMaxDroop;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MSprungMass, PxVehicleSuspensionData, PxReal, PxReal > MSprungMass;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MCamberAtRest, PxVehicleSuspensionData, PxReal, PxReal > MCamberAtRest;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MCamberAtMaxCompression, PxVehicleSuspensionData, PxReal, PxReal > MCamberAtMaxCompression;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleSuspensionData_MCamberAtMaxDroop, PxVehicleSuspensionData, PxReal, PxReal > MCamberAtMaxDroop;
PxVehicleSuspensionDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleSuspensionData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 11; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( RecipMaxCompression, inStartIndex + 0 );;
inOperator( RecipMaxDroop, inStartIndex + 1 );;
inOperator( MassAndPreserveNaturalFrequency, inStartIndex + 2 );;
inOperator( MSpringStrength, inStartIndex + 3 );;
inOperator( MSpringDamperRate, inStartIndex + 4 );;
inOperator( MMaxCompression, inStartIndex + 5 );;
inOperator( MMaxDroop, inStartIndex + 6 );;
inOperator( MSprungMass, inStartIndex + 7 );;
inOperator( MCamberAtRest, inStartIndex + 8 );;
inOperator( MCamberAtMaxCompression, inStartIndex + 9 );;
inOperator( MCamberAtMaxDroop, inStartIndex + 10 );;
return 11 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleSuspensionData>
{
PxVehicleSuspensionDataGeneratedInfo Info;
const PxVehicleSuspensionDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleAntiRollBarData;
struct PxVehicleAntiRollBarDataGeneratedValues
{
PxU32 MWheel0;
PxU32 MWheel1;
PxF32 MStiffness;
PxVehicleAntiRollBarDataGeneratedValues( const PxVehicleAntiRollBarData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAntiRollBarData, MWheel0, PxVehicleAntiRollBarDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAntiRollBarData, MWheel1, PxVehicleAntiRollBarDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleAntiRollBarData, MStiffness, PxVehicleAntiRollBarDataGeneratedValues)
struct PxVehicleAntiRollBarDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleAntiRollBarData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAntiRollBarData_MWheel0, PxVehicleAntiRollBarData, PxU32, PxU32 > MWheel0;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAntiRollBarData_MWheel1, PxVehicleAntiRollBarData, PxU32, PxU32 > MWheel1;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleAntiRollBarData_MStiffness, PxVehicleAntiRollBarData, PxF32, PxF32 > MStiffness;
PxVehicleAntiRollBarDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleAntiRollBarData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 3; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( MWheel0, inStartIndex + 0 );;
inOperator( MWheel1, inStartIndex + 1 );;
inOperator( MStiffness, inStartIndex + 2 );;
return 3 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleAntiRollBarData>
{
PxVehicleAntiRollBarDataGeneratedInfo Info;
const PxVehicleAntiRollBarDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleTireData;
struct PxVehicleTireDataGeneratedValues
{
PxReal RecipLongitudinalStiffnessPerUnitGravity;
PxReal FrictionVsSlipGraphRecipx1Minusx0;
PxReal FrictionVsSlipGraphRecipx2Minusx1;
PxReal MLatStiffX;
PxReal MLatStiffY;
PxReal MLongitudinalStiffnessPerUnitGravity;
PxReal MCamberStiffnessPerUnitGravity;
PxU32 MType;
PxReal MFrictionVsSlipGraph[3][2];
PxVehicleTireDataGeneratedValues( const PxVehicleTireData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, RecipLongitudinalStiffnessPerUnitGravity, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, FrictionVsSlipGraphRecipx1Minusx0, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, FrictionVsSlipGraphRecipx2Minusx1, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, MLatStiffX, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, MLatStiffY, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, MLongitudinalStiffnessPerUnitGravity, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, MCamberStiffnessPerUnitGravity, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, MType, PxVehicleTireDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleTireData, MFrictionVsSlipGraph, PxVehicleTireDataGeneratedValues)
struct PxVehicleTireDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleTireData"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_RecipLongitudinalStiffnessPerUnitGravity, PxVehicleTireData, PxReal > RecipLongitudinalStiffnessPerUnitGravity;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_FrictionVsSlipGraphRecipx1Minusx0, PxVehicleTireData, PxReal > FrictionVsSlipGraphRecipx1Minusx0;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_FrictionVsSlipGraphRecipx2Minusx1, PxVehicleTireData, PxReal > FrictionVsSlipGraphRecipx2Minusx1;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_MLatStiffX, PxVehicleTireData, PxReal, PxReal > MLatStiffX;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_MLatStiffY, PxVehicleTireData, PxReal, PxReal > MLatStiffY;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_MLongitudinalStiffnessPerUnitGravity, PxVehicleTireData, PxReal, PxReal > MLongitudinalStiffnessPerUnitGravity;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_MCamberStiffnessPerUnitGravity, PxVehicleTireData, PxReal, PxReal > MCamberStiffnessPerUnitGravity;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleTireData_MType, PxVehicleTireData, PxU32, PxU32 > MType;
MFrictionVsSlipGraphProperty MFrictionVsSlipGraph;
PxVehicleTireDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleTireData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 9; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( RecipLongitudinalStiffnessPerUnitGravity, inStartIndex + 0 );;
inOperator( FrictionVsSlipGraphRecipx1Minusx0, inStartIndex + 1 );;
inOperator( FrictionVsSlipGraphRecipx2Minusx1, inStartIndex + 2 );;
inOperator( MLatStiffX, inStartIndex + 3 );;
inOperator( MLatStiffY, inStartIndex + 4 );;
inOperator( MLongitudinalStiffnessPerUnitGravity, inStartIndex + 5 );;
inOperator( MCamberStiffnessPerUnitGravity, inStartIndex + 6 );;
inOperator( MType, inStartIndex + 7 );;
inOperator( MFrictionVsSlipGraph, inStartIndex + 8 );;
return 9 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleTireData>
{
PxVehicleTireDataGeneratedInfo Info;
const PxVehicleTireDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleWheels4SimData;
struct PxVehicleWheels4SimDataGeneratedValues
{
const PxReal * TireRestLoadsArray;
const PxReal * RecipTireRestLoadsArray;
PxVehicleWheels4SimDataGeneratedValues( const PxVehicleWheels4SimData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheels4SimData, TireRestLoadsArray, PxVehicleWheels4SimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheels4SimData, RecipTireRestLoadsArray, PxVehicleWheels4SimDataGeneratedValues)
struct PxVehicleWheels4SimDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleWheels4SimData"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheels4SimData_TireRestLoadsArray, PxVehicleWheels4SimData, const PxReal * > TireRestLoadsArray;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheels4SimData_RecipTireRestLoadsArray, PxVehicleWheels4SimData, const PxReal * > RecipTireRestLoadsArray;
PxVehicleWheels4SimDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleWheels4SimData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 2; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( TireRestLoadsArray, inStartIndex + 0 );;
inOperator( RecipTireRestLoadsArray, inStartIndex + 1 );;
return 2 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleWheels4SimData>
{
PxVehicleWheels4SimDataGeneratedInfo Info;
const PxVehicleWheels4SimDataGeneratedInfo* getInfo() { return &Info; }
};
static PxU32ToName g_physx__PxVehicleWheelsSimFlag__EnumConversion[] = {
{ "eLIMIT_SUSPENSION_EXPANSION_VELOCITY", static_cast<PxU32>( physx::PxVehicleWheelsSimFlag::eLIMIT_SUSPENSION_EXPANSION_VELOCITY ) },
{ "eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST", static_cast<PxU32>( physx::PxVehicleWheelsSimFlag::eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST ) },
{ "eDISABLE_SUSPENSION_FORCE_PROJECTION", static_cast<PxU32>( physx::PxVehicleWheelsSimFlag::eDISABLE_SUSPENSION_FORCE_PROJECTION ) },
{ "eDISABLE_SPRUNG_MASS_SUM_CHECK", static_cast<PxU32>( physx::PxVehicleWheelsSimFlag::eDISABLE_SPRUNG_MASS_SUM_CHECK ) },
{ NULL, 0 }
};
template<> struct PxEnumTraits< physx::PxVehicleWheelsSimFlag::Enum > { PxEnumTraits() : NameConversion( g_physx__PxVehicleWheelsSimFlag__EnumConversion ) {} const PxU32ToName* NameConversion; };
class PxVehicleWheelsSimData;
struct PxVehicleWheelsSimDataGeneratedValues
{
PxVehicleTireLoadFilterData TireLoadFilterData;
PxF32 MinLongSlipDenominator;
PxVehicleWheelsSimFlags Flags;
PxF32 ThresholdLongSpeed;
PxU32 LowForwardSpeedSubStepCount;
PxU32 HighForwardSpeedSubStepCount;
PxVehicleWheelsSimDataGeneratedValues( const PxVehicleWheelsSimData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelsSimData, TireLoadFilterData, PxVehicleWheelsSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelsSimData, MinLongSlipDenominator, PxVehicleWheelsSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelsSimData, Flags, PxVehicleWheelsSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelsSimData, ThresholdLongSpeed, PxVehicleWheelsSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelsSimData, LowForwardSpeedSubStepCount, PxVehicleWheelsSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelsSimData, HighForwardSpeedSubStepCount, PxVehicleWheelsSimDataGeneratedValues)
struct PxVehicleWheelsSimDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleWheelsSimData"; }
PxWriteOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_ChassisMass, PxVehicleWheelsSimData, const PxF32 > ChassisMass;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_SuspensionData, PxVehicleWheelsSimData, const PxU32, PxVehicleSuspensionData > SuspensionData;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_WheelData, PxVehicleWheelsSimData, const PxU32, PxVehicleWheelData > WheelData;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_TireData, PxVehicleWheelsSimData, const PxU32, PxVehicleTireData > TireData;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_SuspTravelDirection, PxVehicleWheelsSimData, const PxU32, PxVec3 > SuspTravelDirection;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_SuspForceAppPointOffset, PxVehicleWheelsSimData, const PxU32, PxVec3 > SuspForceAppPointOffset;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_TireForceAppPointOffset, PxVehicleWheelsSimData, const PxU32, PxVec3 > TireForceAppPointOffset;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_WheelCentreOffset, PxVehicleWheelsSimData, const PxU32, PxVec3 > WheelCentreOffset;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_WheelShapeMapping, PxVehicleWheelsSimData, const PxU32, PxI32 > WheelShapeMapping;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_SceneQueryFilterData, PxVehicleWheelsSimData, const PxU32, PxFilterData > SceneQueryFilterData;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_AntiRollBarData, PxVehicleWheelsSimData, const PxU32, PxVehicleAntiRollBarData > AntiRollBarData;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_TireLoadFilterData, PxVehicleWheelsSimData, const PxVehicleTireLoadFilterData &, PxVehicleTireLoadFilterData > TireLoadFilterData;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_MinLongSlipDenominator, PxVehicleWheelsSimData, const PxReal, PxF32 > MinLongSlipDenominator;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_Flags, PxVehicleWheelsSimData, PxVehicleWheelsSimFlags, PxVehicleWheelsSimFlags > Flags;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_ThresholdLongSpeed, PxVehicleWheelsSimData, const PxF32, PxF32 > ThresholdLongSpeed;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_LowForwardSpeedSubStepCount, PxVehicleWheelsSimData, const PxU32, PxU32 > LowForwardSpeedSubStepCount;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_HighForwardSpeedSubStepCount, PxVehicleWheelsSimData, const PxU32, PxU32 > HighForwardSpeedSubStepCount;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsSimData_WheelEnabledState, PxVehicleWheelsSimData, const PxU32, _Bool > WheelEnabledState;
PxVehicleWheelsSimDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleWheelsSimData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 18; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( ChassisMass, inStartIndex + 0 );;
inOperator( SuspensionData, inStartIndex + 1 );;
inOperator( WheelData, inStartIndex + 2 );;
inOperator( TireData, inStartIndex + 3 );;
inOperator( SuspTravelDirection, inStartIndex + 4 );;
inOperator( SuspForceAppPointOffset, inStartIndex + 5 );;
inOperator( TireForceAppPointOffset, inStartIndex + 6 );;
inOperator( WheelCentreOffset, inStartIndex + 7 );;
inOperator( WheelShapeMapping, inStartIndex + 8 );;
inOperator( SceneQueryFilterData, inStartIndex + 9 );;
inOperator( AntiRollBarData, inStartIndex + 10 );;
inOperator( TireLoadFilterData, inStartIndex + 11 );;
inOperator( MinLongSlipDenominator, inStartIndex + 12 );;
inOperator( Flags, inStartIndex + 13 );;
inOperator( ThresholdLongSpeed, inStartIndex + 14 );;
inOperator( LowForwardSpeedSubStepCount, inStartIndex + 15 );;
inOperator( HighForwardSpeedSubStepCount, inStartIndex + 16 );;
inOperator( WheelEnabledState, inStartIndex + 17 );;
return 18 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleWheelsSimData>
{
PxVehicleWheelsSimDataGeneratedInfo Info;
const PxVehicleWheelsSimDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleWheelsDynData;
struct PxVehicleWheelsDynDataGeneratedValues
{
PxVehicleWheels4DynData * Wheel4DynData;
PxVehicleWheelsDynDataGeneratedValues( const PxVehicleWheelsDynData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheelsDynData, Wheel4DynData, PxVehicleWheelsDynDataGeneratedValues)
struct PxVehicleWheelsDynDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleWheelsDynData"; }
PxWriteOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsDynData_TireForceShaderFunction, PxVehicleWheelsDynData, PxVehicleComputeTireForce > TireForceShaderFunction;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsDynData_WheelRotationSpeed, PxVehicleWheelsDynData, const PxU32, PxReal > WheelRotationSpeed;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsDynData_WheelRotationAngle, PxVehicleWheelsDynData, const PxU32, PxReal > WheelRotationAngle;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsDynData_Wheel4DynData, PxVehicleWheelsDynData, PxVehicleWheels4DynData * > Wheel4DynData;
PxReadOnlyCollectionPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheelsDynData_Constraints, PxVehicleWheelsDynData, PxConstraint * > Constraints;
PxVehicleWheelsDynDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleWheelsDynData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 5; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( TireForceShaderFunction, inStartIndex + 0 );;
inOperator( WheelRotationSpeed, inStartIndex + 1 );;
inOperator( WheelRotationAngle, inStartIndex + 2 );;
inOperator( Wheel4DynData, inStartIndex + 3 );;
inOperator( Constraints, inStartIndex + 4 );;
return 5 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleWheelsDynData>
{
PxVehicleWheelsDynDataGeneratedInfo Info;
const PxVehicleWheelsDynDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleWheels;
struct PxVehicleWheelsGeneratedValues
{
PxU32 VehicleType;
const PxRigidDynamic * RigidDynamicActor;
const char * ConcreteTypeName;
PxVehicleWheelsSimData MWheelsSimData;
PxVehicleWheelsDynData MWheelsDynData;
PxVehicleWheelsGeneratedValues( const PxVehicleWheels* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheels, VehicleType, PxVehicleWheelsGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheels, RigidDynamicActor, PxVehicleWheelsGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheels, ConcreteTypeName, PxVehicleWheelsGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheels, MWheelsSimData, PxVehicleWheelsGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleWheels, MWheelsDynData, PxVehicleWheelsGeneratedValues)
struct PxVehicleWheelsGeneratedInfo
{
static const char* getClassName() { return "PxVehicleWheels"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheels_VehicleType, PxVehicleWheels, PxU32 > VehicleType;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheels_RigidDynamicActor, PxVehicleWheels, const PxRigidDynamic * > RigidDynamicActor;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheels_ConcreteTypeName, PxVehicleWheels, const char * > ConcreteTypeName;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheels_MWheelsSimData, PxVehicleWheels, PxVehicleWheelsSimData, PxVehicleWheelsSimData > MWheelsSimData;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleWheels_MWheelsDynData, PxVehicleWheels, PxVehicleWheelsDynData, PxVehicleWheelsDynData > MWheelsDynData;
PxVehicleWheelsGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleWheels*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 5; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( VehicleType, inStartIndex + 0 );;
inOperator( RigidDynamicActor, inStartIndex + 1 );;
inOperator( ConcreteTypeName, inStartIndex + 2 );;
inOperator( MWheelsSimData, inStartIndex + 3 );;
inOperator( MWheelsDynData, inStartIndex + 4 );;
return 5 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleWheels>
{
PxVehicleWheelsGeneratedInfo Info;
const PxVehicleWheelsGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDriveDynData;
struct PxVehicleDriveDynDataGeneratedValues
{
_Bool GearUp;
_Bool GearDown;
_Bool UseAutoGears;
PxU32 CurrentGear;
PxU32 TargetGear;
PxReal EngineRotationSpeed;
PxU32 GearChange;
PxReal GearSwitchTime;
PxReal AutoBoxSwitchTime;
_Bool MUseAutoGears;
_Bool MGearUpPressed;
_Bool MGearDownPressed;
PxU32 MCurrentGear;
PxU32 MTargetGear;
PxReal MEnginespeed;
PxReal MGearSwitchTime;
PxReal MAutoBoxSwitchTime;
PxVehicleDriveDynDataGeneratedValues( const PxVehicleDriveDynData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, GearUp, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, GearDown, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, UseAutoGears, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, CurrentGear, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, TargetGear, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, EngineRotationSpeed, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, GearChange, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, GearSwitchTime, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, AutoBoxSwitchTime, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MUseAutoGears, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MGearUpPressed, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MGearDownPressed, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MCurrentGear, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MTargetGear, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MEnginespeed, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MGearSwitchTime, PxVehicleDriveDynDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveDynData, MAutoBoxSwitchTime, PxVehicleDriveDynDataGeneratedValues)
struct PxVehicleDriveDynDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDriveDynData"; }
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_AnalogInput, PxVehicleDriveDynData, const PxU32, PxReal > AnalogInput;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_GearUp, PxVehicleDriveDynData, const _Bool, _Bool > GearUp;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_GearDown, PxVehicleDriveDynData, const _Bool, _Bool > GearDown;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_UseAutoGears, PxVehicleDriveDynData, const _Bool, _Bool > UseAutoGears;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_CurrentGear, PxVehicleDriveDynData, PxU32, PxU32 > CurrentGear;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_TargetGear, PxVehicleDriveDynData, PxU32, PxU32 > TargetGear;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_EngineRotationSpeed, PxVehicleDriveDynData, const PxF32, PxReal > EngineRotationSpeed;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_GearChange, PxVehicleDriveDynData, const PxU32, PxU32 > GearChange;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_GearSwitchTime, PxVehicleDriveDynData, const PxReal, PxReal > GearSwitchTime;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_AutoBoxSwitchTime, PxVehicleDriveDynData, const PxReal, PxReal > AutoBoxSwitchTime;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MUseAutoGears, PxVehicleDriveDynData, _Bool, _Bool > MUseAutoGears;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MGearUpPressed, PxVehicleDriveDynData, _Bool, _Bool > MGearUpPressed;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MGearDownPressed, PxVehicleDriveDynData, _Bool, _Bool > MGearDownPressed;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MCurrentGear, PxVehicleDriveDynData, PxU32, PxU32 > MCurrentGear;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MTargetGear, PxVehicleDriveDynData, PxU32, PxU32 > MTargetGear;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MEnginespeed, PxVehicleDriveDynData, PxReal, PxReal > MEnginespeed;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MGearSwitchTime, PxVehicleDriveDynData, PxReal, PxReal > MGearSwitchTime;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveDynData_MAutoBoxSwitchTime, PxVehicleDriveDynData, PxReal, PxReal > MAutoBoxSwitchTime;
PxVehicleDriveDynDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDriveDynData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 18; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( AnalogInput, inStartIndex + 0 );;
inOperator( GearUp, inStartIndex + 1 );;
inOperator( GearDown, inStartIndex + 2 );;
inOperator( UseAutoGears, inStartIndex + 3 );;
inOperator( CurrentGear, inStartIndex + 4 );;
inOperator( TargetGear, inStartIndex + 5 );;
inOperator( EngineRotationSpeed, inStartIndex + 6 );;
inOperator( GearChange, inStartIndex + 7 );;
inOperator( GearSwitchTime, inStartIndex + 8 );;
inOperator( AutoBoxSwitchTime, inStartIndex + 9 );;
inOperator( MUseAutoGears, inStartIndex + 10 );;
inOperator( MGearUpPressed, inStartIndex + 11 );;
inOperator( MGearDownPressed, inStartIndex + 12 );;
inOperator( MCurrentGear, inStartIndex + 13 );;
inOperator( MTargetGear, inStartIndex + 14 );;
inOperator( MEnginespeed, inStartIndex + 15 );;
inOperator( MGearSwitchTime, inStartIndex + 16 );;
inOperator( MAutoBoxSwitchTime, inStartIndex + 17 );;
return 18 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDriveDynData>
{
PxVehicleDriveDynDataGeneratedInfo Info;
const PxVehicleDriveDynDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDriveSimData;
struct PxVehicleDriveSimDataGeneratedValues
{
PxVehicleEngineData EngineData;
PxVehicleGearsData GearsData;
PxVehicleClutchData ClutchData;
PxVehicleAutoBoxData AutoBoxData;
PxVehicleDriveSimDataGeneratedValues( const PxVehicleDriveSimData* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveSimData, EngineData, PxVehicleDriveSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveSimData, GearsData, PxVehicleDriveSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveSimData, ClutchData, PxVehicleDriveSimDataGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveSimData, AutoBoxData, PxVehicleDriveSimDataGeneratedValues)
struct PxVehicleDriveSimDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDriveSimData"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveSimData_EngineData, PxVehicleDriveSimData, const PxVehicleEngineData &, PxVehicleEngineData > EngineData;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveSimData_GearsData, PxVehicleDriveSimData, const PxVehicleGearsData &, PxVehicleGearsData > GearsData;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveSimData_ClutchData, PxVehicleDriveSimData, const PxVehicleClutchData &, PxVehicleClutchData > ClutchData;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveSimData_AutoBoxData, PxVehicleDriveSimData, const PxVehicleAutoBoxData &, PxVehicleAutoBoxData > AutoBoxData;
PxVehicleDriveSimDataGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDriveSimData*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 4; }
static PxU32 totalPropertyCount() { return instancePropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( EngineData, inStartIndex + 0 );;
inOperator( GearsData, inStartIndex + 1 );;
inOperator( ClutchData, inStartIndex + 2 );;
inOperator( AutoBoxData, inStartIndex + 3 );;
return 4 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDriveSimData>
{
PxVehicleDriveSimDataGeneratedInfo Info;
const PxVehicleDriveSimDataGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDriveSimData4W;
struct PxVehicleDriveSimData4WGeneratedValues
: PxVehicleDriveSimDataGeneratedValues {
PxVehicleDifferential4WData DiffData;
PxVehicleAckermannGeometryData AckermannGeometryData;
PxVehicleDriveSimData4WGeneratedValues( const PxVehicleDriveSimData4W* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveSimData4W, DiffData, PxVehicleDriveSimData4WGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveSimData4W, AckermannGeometryData, PxVehicleDriveSimData4WGeneratedValues)
struct PxVehicleDriveSimData4WGeneratedInfo
: PxVehicleDriveSimDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDriveSimData4W"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveSimData4W_DiffData, PxVehicleDriveSimData4W, const PxVehicleDifferential4WData &, PxVehicleDifferential4WData > DiffData;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveSimData4W_AckermannGeometryData, PxVehicleDriveSimData4W, const PxVehicleAckermannGeometryData &, PxVehicleAckermannGeometryData > AckermannGeometryData;
PxVehicleDriveSimData4WGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDriveSimData4W*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
inOperator( *static_cast<PxVehicleDriveSimDataGeneratedInfo*>( this ) );
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inStartIndex = PxVehicleDriveSimDataGeneratedInfo::visitBaseProperties( inOperator, inStartIndex );
inStartIndex = PxVehicleDriveSimDataGeneratedInfo::visitInstanceProperties( inOperator, inStartIndex );
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 2; }
static PxU32 totalPropertyCount() { return instancePropertyCount()
+ PxVehicleDriveSimDataGeneratedInfo::totalPropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( DiffData, inStartIndex + 0 );;
inOperator( AckermannGeometryData, inStartIndex + 1 );;
return 2 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDriveSimData4W>
{
PxVehicleDriveSimData4WGeneratedInfo Info;
const PxVehicleDriveSimData4WGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDrive;
struct PxVehicleDriveGeneratedValues
: PxVehicleWheelsGeneratedValues {
const char * ConcreteTypeName;
PxVehicleDriveDynData MDriveDynData;
PxVehicleDriveGeneratedValues( const PxVehicleDrive* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDrive, ConcreteTypeName, PxVehicleDriveGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDrive, MDriveDynData, PxVehicleDriveGeneratedValues)
struct PxVehicleDriveGeneratedInfo
: PxVehicleWheelsGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDrive"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDrive_ConcreteTypeName, PxVehicleDrive, const char * > ConcreteTypeName;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDrive_MDriveDynData, PxVehicleDrive, PxVehicleDriveDynData, PxVehicleDriveDynData > MDriveDynData;
PxVehicleDriveGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDrive*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
inOperator( *static_cast<PxVehicleWheelsGeneratedInfo*>( this ) );
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inStartIndex = PxVehicleWheelsGeneratedInfo::visitBaseProperties( inOperator, inStartIndex );
inStartIndex = PxVehicleWheelsGeneratedInfo::visitInstanceProperties( inOperator, inStartIndex );
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 2; }
static PxU32 totalPropertyCount() { return instancePropertyCount()
+ PxVehicleWheelsGeneratedInfo::totalPropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( ConcreteTypeName, inStartIndex + 0 );;
inOperator( MDriveDynData, inStartIndex + 1 );;
return 2 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDrive>
{
PxVehicleDriveGeneratedInfo Info;
const PxVehicleDriveGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDrive4W;
struct PxVehicleDrive4WGeneratedValues
: PxVehicleDriveGeneratedValues {
const char * ConcreteTypeName;
PxVehicleDriveSimData4W MDriveSimData;
PxVehicleDrive4WGeneratedValues( const PxVehicleDrive4W* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDrive4W, ConcreteTypeName, PxVehicleDrive4WGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDrive4W, MDriveSimData, PxVehicleDrive4WGeneratedValues)
struct PxVehicleDrive4WGeneratedInfo
: PxVehicleDriveGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDrive4W"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDrive4W_ConcreteTypeName, PxVehicleDrive4W, const char * > ConcreteTypeName;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDrive4W_MDriveSimData, PxVehicleDrive4W, PxVehicleDriveSimData4W, PxVehicleDriveSimData4W > MDriveSimData;
PxVehicleDrive4WGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDrive4W*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
inOperator( *static_cast<PxVehicleDriveGeneratedInfo*>( this ) );
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inStartIndex = PxVehicleDriveGeneratedInfo::visitBaseProperties( inOperator, inStartIndex );
inStartIndex = PxVehicleDriveGeneratedInfo::visitInstanceProperties( inOperator, inStartIndex );
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 2; }
static PxU32 totalPropertyCount() { return instancePropertyCount()
+ PxVehicleDriveGeneratedInfo::totalPropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( ConcreteTypeName, inStartIndex + 0 );;
inOperator( MDriveSimData, inStartIndex + 1 );;
return 2 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDrive4W>
{
PxVehicleDrive4WGeneratedInfo Info;
const PxVehicleDrive4WGeneratedInfo* getInfo() { return &Info; }
};
static PxU32ToName g_physx__PxVehicleDriveTankControlModel__EnumConversion[] = {
{ "eSTANDARD", static_cast<PxU32>( physx::PxVehicleDriveTankControlModel::eSTANDARD ) },
{ "eSPECIAL", static_cast<PxU32>( physx::PxVehicleDriveTankControlModel::eSPECIAL ) },
{ NULL, 0 }
};
template<> struct PxEnumTraits< physx::PxVehicleDriveTankControlModel::Enum > { PxEnumTraits() : NameConversion( g_physx__PxVehicleDriveTankControlModel__EnumConversion ) {} const PxU32ToName* NameConversion; };
class PxVehicleDriveTank;
struct PxVehicleDriveTankGeneratedValues
: PxVehicleDriveGeneratedValues {
PxVehicleDriveTankControlModel::Enum DriveModel;
const char * ConcreteTypeName;
PxVehicleDriveSimData MDriveSimData;
PxVehicleDriveTankGeneratedValues( const PxVehicleDriveTank* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveTank, DriveModel, PxVehicleDriveTankGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveTank, ConcreteTypeName, PxVehicleDriveTankGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveTank, MDriveSimData, PxVehicleDriveTankGeneratedValues)
struct PxVehicleDriveTankGeneratedInfo
: PxVehicleDriveGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDriveTank"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveTank_DriveModel, PxVehicleDriveTank, const PxVehicleDriveTankControlModel::Enum, PxVehicleDriveTankControlModel::Enum > DriveModel;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveTank_ConcreteTypeName, PxVehicleDriveTank, const char * > ConcreteTypeName;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveTank_MDriveSimData, PxVehicleDriveTank, PxVehicleDriveSimData, PxVehicleDriveSimData > MDriveSimData;
PxVehicleDriveTankGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDriveTank*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
inOperator( *static_cast<PxVehicleDriveGeneratedInfo*>( this ) );
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inStartIndex = PxVehicleDriveGeneratedInfo::visitBaseProperties( inOperator, inStartIndex );
inStartIndex = PxVehicleDriveGeneratedInfo::visitInstanceProperties( inOperator, inStartIndex );
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 3; }
static PxU32 totalPropertyCount() { return instancePropertyCount()
+ PxVehicleDriveGeneratedInfo::totalPropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( DriveModel, inStartIndex + 0 );;
inOperator( ConcreteTypeName, inStartIndex + 1 );;
inOperator( MDriveSimData, inStartIndex + 2 );;
return 3 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDriveTank>
{
PxVehicleDriveTankGeneratedInfo Info;
const PxVehicleDriveTankGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDriveSimDataNW;
struct PxVehicleDriveSimDataNWGeneratedValues
: PxVehicleDriveSimDataGeneratedValues {
PxVehicleDifferentialNWData DiffData;
PxVehicleDriveSimDataNWGeneratedValues( const PxVehicleDriveSimDataNW* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveSimDataNW, DiffData, PxVehicleDriveSimDataNWGeneratedValues)
struct PxVehicleDriveSimDataNWGeneratedInfo
: PxVehicleDriveSimDataGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDriveSimDataNW"; }
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveSimDataNW_DiffData, PxVehicleDriveSimDataNW, const PxVehicleDifferentialNWData &, PxVehicleDifferentialNWData > DiffData;
PxVehicleDriveSimDataNWGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDriveSimDataNW*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
inOperator( *static_cast<PxVehicleDriveSimDataGeneratedInfo*>( this ) );
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inStartIndex = PxVehicleDriveSimDataGeneratedInfo::visitBaseProperties( inOperator, inStartIndex );
inStartIndex = PxVehicleDriveSimDataGeneratedInfo::visitInstanceProperties( inOperator, inStartIndex );
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 1; }
static PxU32 totalPropertyCount() { return instancePropertyCount()
+ PxVehicleDriveSimDataGeneratedInfo::totalPropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( DiffData, inStartIndex + 0 );;
return 1 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDriveSimDataNW>
{
PxVehicleDriveSimDataNWGeneratedInfo Info;
const PxVehicleDriveSimDataNWGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleDriveNW;
struct PxVehicleDriveNWGeneratedValues
: PxVehicleDriveGeneratedValues {
const char * ConcreteTypeName;
PxVehicleDriveSimDataNW MDriveSimData;
PxVehicleDriveNWGeneratedValues( const PxVehicleDriveNW* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveNW, ConcreteTypeName, PxVehicleDriveNWGeneratedValues)
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleDriveNW, MDriveSimData, PxVehicleDriveNWGeneratedValues)
struct PxVehicleDriveNWGeneratedInfo
: PxVehicleDriveGeneratedInfo
{
static const char* getClassName() { return "PxVehicleDriveNW"; }
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveNW_ConcreteTypeName, PxVehicleDriveNW, const char * > ConcreteTypeName;
PxPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleDriveNW_MDriveSimData, PxVehicleDriveNW, PxVehicleDriveSimDataNW, PxVehicleDriveSimDataNW > MDriveSimData;
PxVehicleDriveNWGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleDriveNW*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
inOperator( *static_cast<PxVehicleDriveGeneratedInfo*>( this ) );
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inStartIndex = PxVehicleDriveGeneratedInfo::visitBaseProperties( inOperator, inStartIndex );
inStartIndex = PxVehicleDriveGeneratedInfo::visitInstanceProperties( inOperator, inStartIndex );
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 2; }
static PxU32 totalPropertyCount() { return instancePropertyCount()
+ PxVehicleDriveGeneratedInfo::totalPropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( ConcreteTypeName, inStartIndex + 0 );;
inOperator( MDriveSimData, inStartIndex + 1 );;
return 2 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleDriveNW>
{
PxVehicleDriveNWGeneratedInfo Info;
const PxVehicleDriveNWGeneratedInfo* getInfo() { return &Info; }
};
class PxVehicleNoDrive;
struct PxVehicleNoDriveGeneratedValues
: PxVehicleWheelsGeneratedValues {
const char * ConcreteTypeName;
PxVehicleNoDriveGeneratedValues( const PxVehicleNoDrive* inSource );
};
DEFINE_PROPERTY_TO_VALUE_STRUCT_MAP( PxVehicleNoDrive, ConcreteTypeName, PxVehicleNoDriveGeneratedValues)
struct PxVehicleNoDriveGeneratedInfo
: PxVehicleWheelsGeneratedInfo
{
static const char* getClassName() { return "PxVehicleNoDrive"; }
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleNoDrive_BrakeTorque, PxVehicleNoDrive, const PxU32, PxReal > BrakeTorque;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleNoDrive_DriveTorque, PxVehicleNoDrive, const PxU32, PxReal > DriveTorque;
PxExtendedIndexedPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleNoDrive_SteerAngle, PxVehicleNoDrive, const PxU32, PxReal > SteerAngle;
PxReadOnlyPropertyInfo<PX_PROPERTY_INFO_NAME::PxVehicleNoDrive_ConcreteTypeName, PxVehicleNoDrive, const char * > ConcreteTypeName;
PxVehicleNoDriveGeneratedInfo();
template<typename TReturnType, typename TOperator>
TReturnType visitType( TOperator inOperator ) const
{
return inOperator( reinterpret_cast<PxVehicleNoDrive*>(NULL) );
}
template<typename TOperator>
void visitBases( TOperator inOperator )
{
PX_UNUSED(inOperator);
inOperator( *static_cast<PxVehicleWheelsGeneratedInfo*>( this ) );
}
template<typename TOperator>
PxU32 visitBaseProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inStartIndex = PxVehicleWheelsGeneratedInfo::visitBaseProperties( inOperator, inStartIndex );
inStartIndex = PxVehicleWheelsGeneratedInfo::visitInstanceProperties( inOperator, inStartIndex );
return inStartIndex;
}
static PxU32 instancePropertyCount() { return 4; }
static PxU32 totalPropertyCount() { return instancePropertyCount()
+ PxVehicleWheelsGeneratedInfo::totalPropertyCount(); }
template<typename TOperator>
PxU32 visitInstanceProperties( TOperator inOperator, PxU32 inStartIndex = 0 ) const
{
PX_UNUSED(inOperator);
PX_UNUSED(inStartIndex);
inOperator( BrakeTorque, inStartIndex + 0 );;
inOperator( DriveTorque, inStartIndex + 1 );;
inOperator( SteerAngle, inStartIndex + 2 );;
inOperator( ConcreteTypeName, inStartIndex + 3 );;
return 4 + inStartIndex;
}
};
template<> struct PxClassInfoTraits<PxVehicleNoDrive>
{
PxVehicleNoDriveGeneratedInfo Info;
const PxVehicleNoDriveGeneratedInfo* getInfo() { return &Info; }
};
#undef THERE_IS_NO_INCLUDE_GUARD_HERE_FOR_A_REASON
#undef PX_PROPERTY_INFO_NAME
| 90,929 |
C
| 49.182119 | 212 | 0.799921 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/physxmetadata/include/PxVehicleAutoGeneratedMetaDataObjectNames.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// This code is auto-generated by the PhysX Clang metadata generator. Do not edit or be
// prepared for your edits to be quietly ignored next time the clang metadata generator is
// run. You can find the most recent version of clang metadata generator by contacting
// Chris Nuernberger <[email protected]> or Dilip or Adam.
// The source code for the generate was at one time checked into:
// physx/PhysXMetaDataGenerator/llvm/tools/clang/lib/Frontend/PhysXMetaDataAction.cpp
#define THERE_IS_NO_INCLUDE_GUARD_HERE_FOR_A_REASON
PxVehicleChassisData_PropertiesStart,
PxVehicleChassisData_MMOI,
PxVehicleChassisData_MMass,
PxVehicleChassisData_MCMOffset,
PxVehicleChassisData_PropertiesStop,
PxVehicleEngineData_PropertiesStart,
PxVehicleEngineData_RecipMOI,
PxVehicleEngineData_RecipMaxOmega,
PxVehicleEngineData_MTorqueCurve,
PxVehicleEngineData_MMOI,
PxVehicleEngineData_MPeakTorque,
PxVehicleEngineData_MMaxOmega,
PxVehicleEngineData_MDampingRateFullThrottle,
PxVehicleEngineData_MDampingRateZeroThrottleClutchEngaged,
PxVehicleEngineData_MDampingRateZeroThrottleClutchDisengaged,
PxVehicleEngineData_PropertiesStop,
PxVehicleGearsData_PropertiesStart,
PxVehicleGearsData_GearRatio,
PxVehicleGearsData_MFinalRatio,
PxVehicleGearsData_MNbRatios,
PxVehicleGearsData_MSwitchTime,
PxVehicleGearsData_PropertiesStop,
PxVehicleAutoBoxData_PropertiesStart,
PxVehicleAutoBoxData_Latency,
PxVehicleAutoBoxData_UpRatios,
PxVehicleAutoBoxData_DownRatios,
PxVehicleAutoBoxData_PropertiesStop,
PxVehicleDifferential4WData_PropertiesStart,
PxVehicleDifferential4WData_MFrontRearSplit,
PxVehicleDifferential4WData_MFrontLeftRightSplit,
PxVehicleDifferential4WData_MRearLeftRightSplit,
PxVehicleDifferential4WData_MCentreBias,
PxVehicleDifferential4WData_MFrontBias,
PxVehicleDifferential4WData_MRearBias,
PxVehicleDifferential4WData_MType,
PxVehicleDifferential4WData_PropertiesStop,
PxVehicleDifferentialNWData_PropertiesStart,
PxVehicleDifferentialNWData_DrivenWheelStatus,
PxVehicleDifferentialNWData_PropertiesStop,
PxVehicleAckermannGeometryData_PropertiesStart,
PxVehicleAckermannGeometryData_MAccuracy,
PxVehicleAckermannGeometryData_MFrontWidth,
PxVehicleAckermannGeometryData_MRearWidth,
PxVehicleAckermannGeometryData_MAxleSeparation,
PxVehicleAckermannGeometryData_PropertiesStop,
PxVehicleClutchData_PropertiesStart,
PxVehicleClutchData_MStrength,
PxVehicleClutchData_MAccuracyMode,
PxVehicleClutchData_MEstimateIterations,
PxVehicleClutchData_PropertiesStop,
PxVehicleTireLoadFilterData_PropertiesStart,
PxVehicleTireLoadFilterData_Denominator,
PxVehicleTireLoadFilterData_MMinNormalisedLoad,
PxVehicleTireLoadFilterData_MMinFilteredNormalisedLoad,
PxVehicleTireLoadFilterData_MMaxNormalisedLoad,
PxVehicleTireLoadFilterData_MMaxFilteredNormalisedLoad,
PxVehicleTireLoadFilterData_PropertiesStop,
PxVehicleWheelData_PropertiesStart,
PxVehicleWheelData_RecipRadius,
PxVehicleWheelData_RecipMOI,
PxVehicleWheelData_MRadius,
PxVehicleWheelData_MWidth,
PxVehicleWheelData_MMass,
PxVehicleWheelData_MMOI,
PxVehicleWheelData_MDampingRate,
PxVehicleWheelData_MMaxBrakeTorque,
PxVehicleWheelData_MMaxHandBrakeTorque,
PxVehicleWheelData_MMaxSteer,
PxVehicleWheelData_MToeAngle,
PxVehicleWheelData_PropertiesStop,
PxVehicleSuspensionData_PropertiesStart,
PxVehicleSuspensionData_RecipMaxCompression,
PxVehicleSuspensionData_RecipMaxDroop,
PxVehicleSuspensionData_MassAndPreserveNaturalFrequency,
PxVehicleSuspensionData_MSpringStrength,
PxVehicleSuspensionData_MSpringDamperRate,
PxVehicleSuspensionData_MMaxCompression,
PxVehicleSuspensionData_MMaxDroop,
PxVehicleSuspensionData_MSprungMass,
PxVehicleSuspensionData_MCamberAtRest,
PxVehicleSuspensionData_MCamberAtMaxCompression,
PxVehicleSuspensionData_MCamberAtMaxDroop,
PxVehicleSuspensionData_PropertiesStop,
PxVehicleAntiRollBarData_PropertiesStart,
PxVehicleAntiRollBarData_MWheel0,
PxVehicleAntiRollBarData_MWheel1,
PxVehicleAntiRollBarData_MStiffness,
PxVehicleAntiRollBarData_PropertiesStop,
PxVehicleTireData_PropertiesStart,
PxVehicleTireData_RecipLongitudinalStiffnessPerUnitGravity,
PxVehicleTireData_FrictionVsSlipGraphRecipx1Minusx0,
PxVehicleTireData_FrictionVsSlipGraphRecipx2Minusx1,
PxVehicleTireData_MLatStiffX,
PxVehicleTireData_MLatStiffY,
PxVehicleTireData_MLongitudinalStiffnessPerUnitGravity,
PxVehicleTireData_MCamberStiffnessPerUnitGravity,
PxVehicleTireData_MType,
PxVehicleTireData_MFrictionVsSlipGraph,
PxVehicleTireData_PropertiesStop,
PxVehicleWheels4SimData_PropertiesStart,
PxVehicleWheels4SimData_TireRestLoadsArray,
PxVehicleWheels4SimData_RecipTireRestLoadsArray,
PxVehicleWheels4SimData_PropertiesStop,
PxVehicleWheelsSimData_PropertiesStart,
PxVehicleWheelsSimData_ChassisMass,
PxVehicleWheelsSimData_SuspensionData,
PxVehicleWheelsSimData_WheelData,
PxVehicleWheelsSimData_TireData,
PxVehicleWheelsSimData_SuspTravelDirection,
PxVehicleWheelsSimData_SuspForceAppPointOffset,
PxVehicleWheelsSimData_TireForceAppPointOffset,
PxVehicleWheelsSimData_WheelCentreOffset,
PxVehicleWheelsSimData_WheelShapeMapping,
PxVehicleWheelsSimData_SceneQueryFilterData,
PxVehicleWheelsSimData_AntiRollBarData,
PxVehicleWheelsSimData_TireLoadFilterData,
PxVehicleWheelsSimData_MinLongSlipDenominator,
PxVehicleWheelsSimData_Flags,
PxVehicleWheelsSimData_ThresholdLongSpeed,
PxVehicleWheelsSimData_LowForwardSpeedSubStepCount,
PxVehicleWheelsSimData_HighForwardSpeedSubStepCount,
PxVehicleWheelsSimData_WheelEnabledState,
PxVehicleWheelsSimData_PropertiesStop,
PxVehicleWheelsDynData_PropertiesStart,
PxVehicleWheelsDynData_TireForceShaderFunction,
PxVehicleWheelsDynData_WheelRotationSpeed,
PxVehicleWheelsDynData_WheelRotationAngle,
PxVehicleWheelsDynData_Wheel4DynData,
PxVehicleWheelsDynData_Constraints,
PxVehicleWheelsDynData_PropertiesStop,
PxVehicleWheels_PropertiesStart,
PxVehicleWheels_VehicleType,
PxVehicleWheels_RigidDynamicActor,
PxVehicleWheels_ConcreteTypeName,
PxVehicleWheels_MWheelsSimData,
PxVehicleWheels_MWheelsDynData,
PxVehicleWheels_PropertiesStop,
PxVehicleDriveDynData_PropertiesStart,
PxVehicleDriveDynData_AnalogInput,
PxVehicleDriveDynData_GearUp,
PxVehicleDriveDynData_GearDown,
PxVehicleDriveDynData_UseAutoGears,
PxVehicleDriveDynData_CurrentGear,
PxVehicleDriveDynData_TargetGear,
PxVehicleDriveDynData_EngineRotationSpeed,
PxVehicleDriveDynData_GearChange,
PxVehicleDriveDynData_GearSwitchTime,
PxVehicleDriveDynData_AutoBoxSwitchTime,
PxVehicleDriveDynData_MUseAutoGears,
PxVehicleDriveDynData_MGearUpPressed,
PxVehicleDriveDynData_MGearDownPressed,
PxVehicleDriveDynData_MCurrentGear,
PxVehicleDriveDynData_MTargetGear,
PxVehicleDriveDynData_MEnginespeed,
PxVehicleDriveDynData_MGearSwitchTime,
PxVehicleDriveDynData_MAutoBoxSwitchTime,
PxVehicleDriveDynData_PropertiesStop,
PxVehicleDriveSimData_PropertiesStart,
PxVehicleDriveSimData_EngineData,
PxVehicleDriveSimData_GearsData,
PxVehicleDriveSimData_ClutchData,
PxVehicleDriveSimData_AutoBoxData,
PxVehicleDriveSimData_PropertiesStop,
PxVehicleDriveSimData4W_PropertiesStart,
PxVehicleDriveSimData4W_DiffData,
PxVehicleDriveSimData4W_AckermannGeometryData,
PxVehicleDriveSimData4W_PropertiesStop,
PxVehicleDrive_PropertiesStart,
PxVehicleDrive_ConcreteTypeName,
PxVehicleDrive_MDriveDynData,
PxVehicleDrive_PropertiesStop,
PxVehicleDrive4W_PropertiesStart,
PxVehicleDrive4W_ConcreteTypeName,
PxVehicleDrive4W_MDriveSimData,
PxVehicleDrive4W_PropertiesStop,
PxVehicleDriveTank_PropertiesStart,
PxVehicleDriveTank_DriveModel,
PxVehicleDriveTank_ConcreteTypeName,
PxVehicleDriveTank_MDriveSimData,
PxVehicleDriveTank_PropertiesStop,
PxVehicleDriveSimDataNW_PropertiesStart,
PxVehicleDriveSimDataNW_DiffData,
PxVehicleDriveSimDataNW_PropertiesStop,
PxVehicleDriveNW_PropertiesStart,
PxVehicleDriveNW_ConcreteTypeName,
PxVehicleDriveNW_MDriveSimData,
PxVehicleDriveNW_PropertiesStop,
PxVehicleNoDrive_PropertiesStart,
PxVehicleNoDrive_BrakeTorque,
PxVehicleNoDrive_DriveTorque,
PxVehicleNoDrive_SteerAngle,
PxVehicleNoDrive_ConcreteTypeName,
PxVehicleNoDrive_PropertiesStop,
#undef THERE_IS_NO_INCLUDE_GUARD_HERE_FOR_A_REASON
| 9,675 |
C
| 40.527897 | 90 | 0.886305 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmRenderBuffer.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_RENDER_BUFFER_H
#define CM_RENDER_BUFFER_H
#include "common/PxRenderBuffer.h"
#include "CmUtils.h"
#include "foundation/PxArray.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
namespace Cm
{
/**
Implementation of PxRenderBuffer.
*/
class RenderBuffer : public PxRenderBuffer, public PxUserAllocated
{
template <typename T>
void append(PxArray<T>& dst, const T* src, PxU32 count)
{
dst.reserve(dst.size() + count);
for(const T* end=src+count; src<end; ++src)
dst.pushBack(*src);
}
public:
RenderBuffer() :
mPoints("renderBufferPoints"),
mLines("renderBufferLines"),
mTriangles("renderBufferTriangles")
{}
virtual PxU32 getNbPoints() const { return mPoints.size(); }
virtual const PxDebugPoint* getPoints() const { return mPoints.begin(); }
virtual void addPoint(const PxDebugPoint& point) { mPoints.pushBack(point); }
virtual PxU32 getNbLines() const { return mLines.size(); }
virtual const PxDebugLine* getLines() const { return mLines.begin(); }
virtual void addLine(const PxDebugLine& line) { mLines.pushBack(line); }
virtual PxDebugLine* reserveLines(const PxU32 nbLines) {return reserveContainerMemory(mLines, nbLines);}
virtual PxDebugPoint* reservePoints(const PxU32 nbPoints) { return reserveContainerMemory(mPoints, nbPoints); }
virtual PxU32 getNbTriangles() const { return mTriangles.size(); }
virtual const PxDebugTriangle* getTriangles() const { return mTriangles.begin(); }
virtual void addTriangle(const PxDebugTriangle& triangle) { mTriangles.pushBack(triangle); }
virtual void append(const PxRenderBuffer& other)
{
append(mPoints, other.getPoints(), other.getNbPoints());
append(mLines, other.getLines(), other.getNbLines());
append(mTriangles, other.getTriangles(), other.getNbTriangles());
}
virtual void clear()
{
mPoints.clear();
mLines.clear();
mTriangles.clear();
}
virtual bool empty() const
{
return mPoints.empty() && mLines.empty() && mTriangles.empty();
}
virtual void shift(const PxVec3& delta)
{
for(PxU32 i=0; i < mPoints.size(); i++)
mPoints[i].pos += delta;
for(PxU32 i=0; i < mLines.size(); i++)
{
mLines[i].pos0 += delta;
mLines[i].pos1 += delta;
}
for(PxU32 i=0; i < mTriangles.size(); i++)
{
mTriangles[i].pos0 += delta;
mTriangles[i].pos1 += delta;
mTriangles[i].pos2 += delta;
}
}
PxArray<PxDebugPoint> mPoints;
PxArray<PxDebugLine> mLines;
PxArray<PxDebugTriangle> mTriangles;
};
} // Cm
}
#endif
| 4,240 |
C
| 32.393701 | 113 | 0.721226 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmVisualization.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "CmVisualization.h"
using namespace physx;
using namespace Cm;
static const PxU32 gLimitColor = PxU32(PxDebugColor::eARGB_YELLOW);
void Cm::visualizeJointFrames(PxRenderOutput& out, PxReal scale, const PxTransform& parent, const PxTransform& child)
{
if(scale==0.0f)
return;
out << parent << PxDebugBasis(PxVec3(scale, scale, scale) * 1.5f,
PxU32(PxDebugColor::eARGB_DARKRED), PxU32(PxDebugColor::eARGB_DARKGREEN), PxU32(PxDebugColor::eARGB_DARKBLUE));
out << child << PxDebugBasis(PxVec3(scale, scale, scale));
}
void Cm::visualizeLinearLimit(PxRenderOutput& out, PxReal scale, const PxTransform& t0, const PxTransform& /*t1*/, PxReal value)
{
if(scale==0.0f)
return;
// debug circle is around z-axis, and we want it around x-axis
PxTransform r(t0.p+value*t0.q.getBasisVector0(), t0.q*PxQuat(PxPi/2,PxVec3(0,1.f,0)));
out << gLimitColor;
out << PxTransform(PxIdentity);
out << PxDebugArrow(t0.p,r.p-t0.p);
out << r << PxDebugCircle(20, scale*0.3f);
}
void Cm::visualizeAngularLimit(PxRenderOutput& out, PxReal scale, const PxTransform& t, PxReal lower, PxReal upper)
{
if(scale==0.0f)
return;
out << t << gLimitColor;
out << PxRenderOutput::LINES
<< PxVec3(0) << PxVec3(0, PxCos(lower), PxSin(lower)) * scale
<< PxVec3(0) << PxVec3(0, PxCos(upper), PxSin(upper)) * scale;
out << PxRenderOutput::LINESTRIP;
PxReal angle = lower, step = (upper-lower)/20;
for(PxU32 i=0; i<=20; i++, angle += step)
out << PxVec3(0, PxCos(angle), PxSin(angle)) * scale;
}
void Cm::visualizeLimitCone(PxRenderOutput& out, PxReal scale, const PxTransform& t, PxReal tanQSwingY, PxReal tanQSwingZ)
{
if(scale==0.0f)
return;
out << t << gLimitColor;
out << PxRenderOutput::LINES;
PxVec3 prev(0,0,0);
const PxU32 LINES = 32;
for(PxU32 i=0;i<=LINES;i++)
{
PxReal angle = 2*PxPi/LINES*i;
PxReal c = PxCos(angle), s = PxSin(angle);
PxVec3 rv(0,-tanQSwingZ*s, tanQSwingY*c);
PxReal rv2 = rv.magnitudeSquared();
PxQuat q = PxQuat(0,2*rv.y,2*rv.z,1-rv2) * (1/(1+rv2));
PxVec3 a = q.rotate(PxVec3(1.0f,0,0)) * scale;
out << prev << a << PxVec3(0) << a;
prev = a;
}
}
void Cm::visualizeDoubleCone(PxRenderOutput& out, PxReal scale, const PxTransform& t, PxReal angle)
{
if(scale==0.0f)
return;
out << t << gLimitColor;
const PxReal height = PxTan(angle);
const PxU32 LINES = 32;
out << PxRenderOutput::LINESTRIP;
const PxReal step = PxPi*2/LINES;
for(PxU32 i=0; i<=LINES; i++)
out << PxVec3(height, PxCos(step * i), PxSin(step * i)) * scale;
angle = 0;
out << PxRenderOutput::LINESTRIP;
for(PxU32 i=0; i<=LINES; i++, angle += PxPi*2/LINES)
out << PxVec3(-height, PxCos(step * i), PxSin(step * i)) * scale;
angle = 0;
out << PxRenderOutput::LINES;
for(PxU32 i=0;i<LINES;i++, angle += PxPi*2/LINES)
{
out << PxVec3(0) << PxVec3(-height, PxCos(step * i), PxSin(step * i)) * scale;
out << PxVec3(0) << PxVec3(height, PxCos(step * i), PxSin(step * i)) * scale;
}
}
void Cm::renderOutputDebugBox(PxRenderOutput& out, const PxBounds3& box)
{
out << PxDebugBox(box, true);
}
void Cm::renderOutputDebugCircle(PxRenderOutput& out, PxU32 s, PxReal r)
{
out << PxDebugCircle(s, r);
}
void Cm::renderOutputDebugBasis(PxRenderOutput& out, const PxDebugBasis& basis)
{
out << basis;
}
void Cm::renderOutputDebugArrow(PxRenderOutput& out, const PxDebugArrow& arrow)
{
out << arrow;
}
| 5,062 |
C++
| 31.664516 | 128 | 0.706638 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmFlushPool.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_FLUSH_POOL_H
#define CM_FLUSH_POOL_H
#include "foundation/Px.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxMutex.h"
#include "foundation/PxArray.h"
/*
Pool used to allocate variable sized tasks. It's intended to be cleared after a short period (time step).
*/
namespace physx
{
namespace Cm
{
static const PxU32 sSpareChunkCount = 2;
class FlushPool
{
PX_NOCOPY(FlushPool)
public:
FlushPool(PxU32 chunkSize) : mChunks("FlushPoolChunk"), mChunkIndex(0), mOffset(0), mChunkSize(chunkSize)
{
mChunks.pushBack(static_cast<PxU8*>(PX_ALLOC(mChunkSize, "PxU8")));
}
~FlushPool()
{
for (PxU32 i = 0; i < mChunks.size(); ++i)
PX_FREE(mChunks[i]);
}
// alignment must be a power of two
void* allocate(PxU32 size, PxU32 alignment=16)
{
PxMutex::ScopedLock lock(mMutex);
return allocateNotThreadSafe(size, alignment);
}
// alignment must be a power of two
void* allocateNotThreadSafe(PxU32 size, PxU32 alignment=16)
{
PX_ASSERT(PxIsPowerOfTwo(alignment));
PX_ASSERT(size <= mChunkSize && !mChunks.empty());
// padding for alignment
size_t unalignedStart = size_t(mChunks[mChunkIndex]+mOffset);
PxU32 pad = PxU32(((unalignedStart+alignment-1)&~(size_t(alignment)-1)) - unalignedStart);
if (mOffset + size + pad > mChunkSize)
{
mChunkIndex++;
mOffset = 0;
if (mChunkIndex >= mChunks.size())
mChunks.pushBack(static_cast<PxU8*>(PX_ALLOC(mChunkSize, "PxU8")));
// update padding to ensure new alloc is aligned
unalignedStart = size_t(mChunks[mChunkIndex]);
pad = PxU32(((unalignedStart+alignment-1)&~(size_t(alignment)-1)) - unalignedStart);
}
void* ptr = mChunks[mChunkIndex] + mOffset + pad;
PX_ASSERT((size_t(ptr)&(size_t(alignment)-1)) == 0);
mOffset += size + pad;
return ptr;
}
void clear(PxU32 spareChunkCount = sSpareChunkCount)
{
PxMutex::ScopedLock lock(mMutex);
clearNotThreadSafe(spareChunkCount);
}
void clearNotThreadSafe(PxU32 spareChunkCount = sSpareChunkCount)
{
//release memory not used previously
PxU32 targetSize = mChunkIndex+spareChunkCount;
while (mChunks.size() > targetSize)
{
PxU8* ptr = mChunks.popBack();
PX_FREE(ptr);
}
mChunkIndex = 0;
mOffset = 0;
}
void resetNotThreadSafe()
{
PxU8* firstChunk = mChunks[0];
for (PxU32 i = 1; i < mChunks.size(); ++i)
PX_FREE(mChunks[i]);
mChunks.clear();
mChunks.pushBack(firstChunk);
mChunkIndex = 0;
mOffset = 0;
}
void lock()
{
mMutex.lock();
}
void unlock()
{
mMutex.unlock();
}
private:
PxMutex mMutex;
PxArray<PxU8*> mChunks;
PxU32 mChunkIndex;
PxU32 mOffset;
PxU32 mChunkSize;
};
} // namespace Cm
}
#endif
| 4,482 |
C
| 27.737179 | 107 | 0.705042 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmRadixSort.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "foundation/PxAssert.h"
#include "CmRadixSort.h"
// PT: code archeology: this initially came from ICE (IceRevisitedRadix.h/cpp). Consider putting it back the way it was initially.
using namespace physx;
using namespace Cm;
#if defined(__BIG_ENDIAN__) || defined(_XBOX)
#define H0_OFFSET 768
#define H1_OFFSET 512
#define H2_OFFSET 256
#define H3_OFFSET 0
#define BYTES_INC (3-j)
#else
#define H0_OFFSET 0
#define H1_OFFSET 256
#define H2_OFFSET 512
#define H3_OFFSET 768
#define BYTES_INC j
#endif
#define CREATE_HISTOGRAMS(type, buffer) \
/* Clear counters/histograms */ \
PxMemZero(mHistogram1024, 256*4*sizeof(PxU32)); \
\
/* Prepare to count */ \
const PxU8* PX_RESTRICT p = reinterpret_cast<const PxU8*>(input); \
const PxU8* PX_RESTRICT pe = &p[nb*4]; \
PxU32* PX_RESTRICT h0= &mHistogram1024[H0_OFFSET]; /* Histogram for first pass (LSB)*/ \
PxU32* PX_RESTRICT h1= &mHistogram1024[H1_OFFSET]; /* Histogram for second pass */ \
PxU32* PX_RESTRICT h2= &mHistogram1024[H2_OFFSET]; /* Histogram for third pass */ \
PxU32* PX_RESTRICT h3= &mHistogram1024[H3_OFFSET]; /* Histogram for last pass (MSB)*/ \
\
bool AlreadySorted = true; /* Optimism... */ \
\
if(INVALID_RANKS) \
{ \
/* Prepare for temporal coherence */ \
const type* PX_RESTRICT Running = reinterpret_cast<const type*>(buffer); \
type PrevVal = *Running; \
\
while(p!=pe) \
{ \
/* Read input buffer in previous sorted order */ \
const type Val = *Running++; \
/* Check whether already sorted or not */ \
if(Val<PrevVal) { AlreadySorted = false; break; } /* Early out */ \
/* Update for next iteration */ \
PrevVal = Val; \
\
/* Create histograms */ \
h0[*p++]++; h1[*p++]++; h2[*p++]++; h3[*p++]++; \
} \
\
/* If all input values are already sorted, we just have to return and leave the */ \
/* previous list unchanged. That way the routine may take advantage of temporal */ \
/* coherence, for example when used to sort transparent faces. */ \
if(AlreadySorted) \
{ \
mNbHits++; \
for(PxU32 i=0;i<nb;i++) mRanks[i] = i; \
return *this; \
} \
} \
else \
{ \
/* Prepare for temporal coherence */ \
const PxU32* PX_RESTRICT Indices = mRanks; \
type PrevVal = type(buffer[*Indices]); \
\
while(p!=pe) \
{ \
/* Read input buffer in previous sorted order */ \
const type Val = type(buffer[*Indices++]); \
/* Check whether already sorted or not */ \
if(Val<PrevVal) { AlreadySorted = false; break; } /* Early out */ \
/* Update for next iteration */ \
PrevVal = Val; \
\
/* Create histograms */ \
h0[*p++]++; h1[*p++]++; h2[*p++]++; h3[*p++]++; \
} \
\
/* If all input values are already sorted, we just have to return and leave the */ \
/* previous list unchanged. That way the routine may take advantage of temporal */ \
/* coherence, for example when used to sort transparent faces. */ \
if(AlreadySorted) { mNbHits++; return *this; } \
} \
\
/* Else there has been an early out and we must finish computing the histograms */ \
while(p!=pe) \
{ \
/* Create histograms without the previous overhead */ \
h0[*p++]++; h1[*p++]++; h2[*p++]++; h3[*p++]++; \
}
PX_INLINE const PxU32* CheckPassValidity(PxU32 pass, const PxU32* mHistogram1024, PxU32 nb, const void* input, PxU8& UniqueVal)
{
// Shortcut to current counters
const PxU32* CurCount = &mHistogram1024[pass<<8];
// Check pass validity
// If all values have the same byte, sorting is useless.
// It may happen when sorting bytes or words instead of dwords.
// This routine actually sorts words faster than dwords, and bytes
// faster than words. Standard running time (O(4*n))is reduced to O(2*n)
// for words and O(n) for bytes. Running time for floats depends on actual values...
// Get first byte
UniqueVal = *((reinterpret_cast<const PxU8*>(input))+pass);
// Check that byte's counter
if(CurCount[UniqueVal]==nb)
return NULL;
return CurCount;
}
RadixSort::RadixSort() : mCurrentSize(0), mRanks(NULL), mRanks2(NULL), mHistogram1024(0), mLinks256(0), mTotalCalls(0), mNbHits(0), mDeleteRanks(true)
{
// Initialize indices
INVALIDATE_RANKS;
}
RadixSort::~RadixSort()
{
}
/**
* Main sort routine.
* This one is for integer values. After the call, mRanks contains a list of indices in sorted order, i.e. in the order you may process your data.
* \param input [in] a list of integer values to sort
* \param nb [in] number of values to sort, must be < 2^31
* \param hint [in] RADIX_SIGNED to handle negative values, RADIX_UNSIGNED if you know your input buffer only contains positive values
* \return Self-Reference
*/
RadixSort& RadixSort::Sort(const PxU32* input, PxU32 nb, RadixHint hint)
{
PX_ASSERT(mHistogram1024);
PX_ASSERT(mLinks256);
PX_ASSERT(mRanks);
PX_ASSERT(mRanks2);
// Checkings
if(!input || !nb || nb&0x80000000)
return *this;
// Stats
mTotalCalls++;
// Create histograms (counters). Counters for all passes are created in one run.
// Pros: read input buffer once instead of four times
// Cons: mHistogram1024 is 4Kb instead of 1Kb
// We must take care of signed/unsigned values for temporal coherence.... I just
// have 2 code paths even if just a single opcode changes. Self-modifying code, someone?
if(hint==RADIX_UNSIGNED) { CREATE_HISTOGRAMS(PxU32, input); }
else { CREATE_HISTOGRAMS(PxI32, input); }
// Compute #negative values involved if needed
PxU32 NbNegativeValues = 0;
if(hint==RADIX_SIGNED)
{
// An efficient way to compute the number of negatives values we'll have to deal with is simply to sum the 128
// last values of the last histogram. Last histogram because that's the one for the Most Significant Byte,
// responsible for the sign. 128 last values because the 128 first ones are related to positive numbers.
PxU32* PX_RESTRICT h3= &mHistogram1024[768];
for(PxU32 i=128;i<256;i++) NbNegativeValues += h3[i]; // 768 for last histogram, 128 for negative part
}
// Radix sort, j is the pass number (0=LSB, 3=MSB)
for(PxU32 j=0;j<4;j++)
{
// CHECK_PASS_VALIDITY(j);
PxU8 UniqueVal;
const PxU32* PX_RESTRICT CurCount = CheckPassValidity(j, mHistogram1024, nb, input, UniqueVal);
// Sometimes the fourth (negative) pass is skipped because all numbers are negative and the MSB is 0xFF (for example). This is
// not a problem, numbers are correctly sorted anyway.
if(CurCount)
{
PxU32** PX_RESTRICT Links256 = mLinks256;
// Should we care about negative values?
if(j!=3 || hint==RADIX_UNSIGNED)
{
// Here we deal with positive values only
// Create offsets
Links256[0] = mRanks2;
for(PxU32 i=1;i<256;i++)
Links256[i] = Links256[i-1] + CurCount[i-1];
}
else
{
// This is a special case to correctly handle negative integers. They're sorted in the right order but at the wrong place.
// Create biased offsets, in order for negative numbers to be sorted as well
Links256[0] = &mRanks2[NbNegativeValues]; // First positive number takes place after the negative ones
for(PxU32 i=1;i<128;i++)
Links256[i] = Links256[i-1] + CurCount[i-1]; // 1 to 128 for positive numbers
// Fixing the wrong place for negative values
Links256[128] = mRanks2;
for(PxU32 i=129;i<256;i++)
Links256[i] = Links256[i-1] + CurCount[i-1];
}
// Perform Radix Sort
const PxU8* PX_RESTRICT InputBytes = reinterpret_cast<const PxU8*>(input);
InputBytes += BYTES_INC;
if(INVALID_RANKS)
{
for(PxU32 i=0;i<nb;i++)
*Links256[InputBytes[i<<2]]++ = i;
VALIDATE_RANKS;
}
else
{
PxU32* PX_RESTRICT Indices = mRanks;
PxU32* PX_RESTRICT IndicesEnd = &mRanks[nb];
while(Indices!=IndicesEnd)
{
const PxU32 id = *Indices++;
*Links256[InputBytes[id<<2]]++ = id;
}
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in mRanks after the swap.
PxU32* Tmp = mRanks; mRanks = mRanks2; mRanks2 = Tmp;
}
}
return *this;
}
/**
* Main sort routine.
* This one is for floating-point values. After the call, mRanks contains a list of indices in sorted order, i.e. in the order you may process your data.
* \param input2 [in] a list of floating-point values to sort
* \param nb [in] number of values to sort, must be < 2^31
* \return Self-Reference
* \warning only sorts IEEE floating-point values
*/
RadixSort& RadixSort::Sort(const float* input2, PxU32 nb)
{
PX_ASSERT(mHistogram1024);
PX_ASSERT(mLinks256);
PX_ASSERT(mRanks);
PX_ASSERT(mRanks2);
// Checkings
if(!input2 || !nb || nb&0x80000000)
return *this;
// Stats
mTotalCalls++;
const PxU32* PX_RESTRICT input = reinterpret_cast<const PxU32*>(input2);
// Allocate histograms & offsets on the stack
//PxU32 mHistogram1024[256*4];
//PxU32* mLinks256[256];
// Create histograms (counters). Counters for all passes are created in one run.
// Pros: read input buffer once instead of four times
// Cons: mHistogram1024 is 4Kb instead of 1Kb
// Floating-point values are always supposed to be signed values, so there's only one code path there.
// Please note the floating point comparison needed for temporal coherence! Although the resulting asm code
// is dreadful, this is surprisingly not such a performance hit - well, I suppose that's a big one on first
// generation Pentiums....We can't make comparison on integer representations because, as Chris said, it just
// wouldn't work with mixed positive/negative values....
{ CREATE_HISTOGRAMS(float, input2); }
// Compute #negative values involved if needed
PxU32 NbNegativeValues = 0;
// An efficient way to compute the number of negatives values we'll have to deal with is simply to sum the 128
// last values of the last histogram. Last histogram because that's the one for the Most Significant Byte,
// responsible for the sign. 128 last values because the 128 first ones are related to positive numbers.
// ### is that ok on Apple ?!
PxU32* PX_RESTRICT h3= &mHistogram1024[768];
for(PxU32 i=128;i<256;i++) NbNegativeValues += h3[i]; // 768 for last histogram, 128 for negative part
// Radix sort, j is the pass number (0=LSB, 3=MSB)
for(PxU32 j=0;j<4;j++)
{
PxU8 UniqueVal;
const PxU32* PX_RESTRICT CurCount = CheckPassValidity(j, mHistogram1024, nb, input, UniqueVal);
// Should we care about negative values?
if(j!=3)
{
// Here we deal with positive values only
// CHECK_PASS_VALIDITY(j);
// const bool PerformPass = CheckPassValidity(j, mHistogram1024, nb, input);
if(CurCount)
{
PxU32** PX_RESTRICT Links256 = mLinks256;
// Create offsets
Links256[0] = mRanks2;
for(PxU32 i=1;i<256;i++)
Links256[i] = Links256[i-1] + CurCount[i-1];
// Perform Radix Sort
const PxU8* PX_RESTRICT InputBytes = reinterpret_cast<const PxU8*>(input);
InputBytes += BYTES_INC;
if(INVALID_RANKS)
{
for(PxU32 i=0;i<nb;i++)
*Links256[InputBytes[i<<2]]++ = i;
VALIDATE_RANKS;
}
else
{
PxU32* PX_RESTRICT Indices = mRanks;
PxU32* PX_RESTRICT IndicesEnd = &mRanks[nb];
while(Indices!=IndicesEnd)
{
const PxU32 id = *Indices++;
*Links256[InputBytes[id<<2]]++ = id;
}
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in mRanks after the swap.
PxU32* Tmp = mRanks; mRanks = mRanks2; mRanks2 = Tmp;
}
}
else
{
// This is a special case to correctly handle negative values
// CHECK_PASS_VALIDITY(j);
// const bool PerformPass = CheckPassValidity(j, mHistogram1024, nb, input);
if(CurCount)
{
PxU32** PX_RESTRICT Links256 = mLinks256;
// Create biased offsets, in order for negative numbers to be sorted as well
Links256[0] = &mRanks2[NbNegativeValues]; // First positive number takes place after the negative ones
for(PxU32 i=1;i<128;i++)
Links256[i] = Links256[i-1] + CurCount[i-1]; // 1 to 128 for positive numbers
// We must reverse the sorting order for negative numbers!
Links256[255] = mRanks2;
for(PxU32 i=0;i<127;i++)
Links256[254-i] = Links256[255-i] + CurCount[255-i]; // Fixing the wrong order for negative values
for(PxU32 i=128;i<256;i++)
Links256[i] += CurCount[i]; // Fixing the wrong place for negative values
// Perform Radix Sort
if(INVALID_RANKS)
{
for(PxU32 i=0;i<nb;i++)
{
const PxU32 Radix = input[i]>>24; // Radix byte, same as above. AND is useless here (PxU32).
// ### cmp to be killed. Not good. Later.
if(Radix<128) *Links256[Radix]++ = i; // Number is positive, same as above
else *(--Links256[Radix]) = i; // Number is negative, flip the sorting order
}
VALIDATE_RANKS;
}
else
{
const PxU32* PX_RESTRICT Ranks = mRanks;
for(PxU32 i=0;i<nb;i++)
{
const PxU32 Radix = input[Ranks[i]]>>24; // Radix byte, same as above. AND is useless here (PxU32).
// ### cmp to be killed. Not good. Later.
if(Radix<128) *Links256[Radix]++ = Ranks[i]; // Number is positive, same as above
else *(--Links256[Radix]) = Ranks[i]; // Number is negative, flip the sorting order
}
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in mRanks after the swap.
PxU32* Tmp = mRanks; mRanks = mRanks2; mRanks2 = Tmp;
}
else
{
// The pass is useless, yet we still have to reverse the order of current list if all values are negative.
if(UniqueVal>=128)
{
if(INVALID_RANKS)
{
// ###Possible?
for(PxU32 i=0;i<nb;i++) mRanks2[i] = nb-i-1;
VALIDATE_RANKS;
}
else
{
for(PxU32 i=0;i<nb;i++) mRanks2[i] = mRanks[nb-i-1];
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in mRanks after the swap.
PxU32* Tmp = mRanks; mRanks = mRanks2; mRanks2 = Tmp;
}
}
}
}
return *this;
}
bool RadixSort::SetBuffers(PxU32* ranks0, PxU32* ranks1, PxU32* histogram1024, PxU32** links256)
{
if(!ranks0 || !ranks1 || !histogram1024 || !links256)
return false;
mRanks = ranks0;
mRanks2 = ranks1;
mHistogram1024 = histogram1024;
mLinks256 = links256;
mDeleteRanks = false;
INVALIDATE_RANKS;
return true;
}
#include "foundation/PxAllocator.h"
using namespace physx;
using namespace Cm;
RadixSortBuffered::RadixSortBuffered()
: RadixSort()
{
}
RadixSortBuffered::~RadixSortBuffered()
{
reset();
}
void RadixSortBuffered::reset()
{
// Release everything
if(mDeleteRanks)
{
PX_FREE(mRanks2);
PX_FREE(mRanks);
}
mCurrentSize = 0;
INVALIDATE_RANKS;
}
/**
* Resizes the inner lists.
* \param nb [in] new size (number of dwords)
* \return true if success
*/
bool RadixSortBuffered::Resize(PxU32 nb)
{
if(mDeleteRanks)
{
// Free previously used ram
PX_FREE(mRanks2);
PX_FREE(mRanks);
// Get some fresh one
mRanks = PX_ALLOCATE(PxU32, nb, "RadixSortBuffered:mRanks");
mRanks2 = PX_ALLOCATE(PxU32, nb, "RadixSortBuffered:mRanks2");
}
return true;
}
PX_INLINE void RadixSortBuffered::CheckResize(PxU32 nb)
{
PxU32 CurSize = CURRENT_SIZE;
if(nb!=CurSize)
{
if(nb>CurSize)
Resize(nb);
mCurrentSize = nb;
INVALIDATE_RANKS;
}
}
/**
* Main sort routine.
* This one is for integer values. After the call, mRanks contains a list of indices in sorted order, i.e. in the order you may process your data.
* \param input [in] a list of integer values to sort
* \param nb [in] number of values to sort, must be < 2^31
* \param hint [in] RADIX_SIGNED to handle negative values, RADIX_UNSIGNED if you know your input buffer only contains positive values
* \return Self-Reference
*/
RadixSortBuffered& RadixSortBuffered::Sort(const PxU32* input, PxU32 nb, RadixHint hint)
{
// Checkings
if(!input || !nb || nb&0x80000000)
return *this;
// Resize lists if needed
CheckResize(nb);
//Set histogram buffers.
PxU32 histogram[1024];
PxU32* links[256];
mHistogram1024 = histogram;
mLinks256 = links;
RadixSort::Sort(input, nb, hint);
return *this;
}
/**
* Main sort routine.
* This one is for floating-point values. After the call, mRanks contains a list of indices in sorted order, i.e. in the order you may process your data.
* \param input2 [in] a list of floating-point values to sort
* \param nb [in] number of values to sort, must be < 2^31
* \return Self-Reference
* \warning only sorts IEEE floating-point values
*/
RadixSortBuffered& RadixSortBuffered::Sort(const float* input2, PxU32 nb)
{
// Checkings
if(!input2 || !nb || nb&0x80000000)
return *this;
// Resize lists if needed
CheckResize(nb);
//Set histogram buffers.
PxU32 histogram[1024];
PxU32* links[256];
mHistogram1024 = histogram;
mLinks256 = links;
RadixSort::Sort(input2, nb);
return *this;
}
| 19,466 |
C++
| 33.7625 | 153 | 0.644611 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmSerialize.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxIntrinsics.h"
#include "foundation/PxUtilities.h"
#include "CmSerialize.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxFPU.h"
using namespace physx;
using namespace Cm;
void physx::readChunk(PxI8& a, PxI8& b, PxI8& c, PxI8& d, PxInputStream& stream)
{
stream.read(&a, sizeof(PxI8));
stream.read(&b, sizeof(PxI8));
stream.read(&c, sizeof(PxI8));
stream.read(&d, sizeof(PxI8));
}
///////////////////////////////////////////////////////////////////////////////
PxU16 physx::readWord(bool mismatch, PxInputStream& stream)
{
PxU16 d;
stream.read(&d, sizeof(PxU16));
if(mismatch)
flip(d);
return d;
}
PxU32 physx::readDword(bool mismatch, PxInputStream& stream)
{
PxU32 d;
stream.read(&d, sizeof(PxU32));
if(mismatch)
flip(d);
return d;
}
PxF32 physx::readFloat(bool mismatch, PxInputStream& stream)
{
union
{
PxU32 d;
PxF32 f;
} u;
stream.read(&u.d, sizeof(PxU32));
if(mismatch)
flip(u.d);
return u.f;
}
///////////////////////////////////////////////////////////////////////////////
void physx::writeWord(PxU16 value, bool mismatch, PxOutputStream& stream)
{
if(mismatch)
flip(value);
stream.write(&value, sizeof(PxU16));
}
void physx::writeDword(PxU32 value, bool mismatch, PxOutputStream& stream)
{
if(mismatch)
flip(value);
stream.write(&value, sizeof(PxU32));
}
void physx::writeFloat(PxF32 value, bool mismatch, PxOutputStream& stream)
{
if(mismatch)
flip(value);
stream.write(&value, sizeof(PxF32));
}
///////////////////////////////////////////////////////////////////////////////
bool physx::readFloatBuffer(PxF32* dest, PxU32 nbFloats, bool mismatch, PxInputStream& stream)
{
stream.read(dest, sizeof(PxF32)*nbFloats);
if(mismatch)
{
for(PxU32 i=0;i<nbFloats;i++)
flip(dest[i]);
}
return true;
}
void physx::writeFloatBuffer(const PxF32* src, PxU32 nb, bool mismatch, PxOutputStream& stream)
{
if(mismatch)
{
while(nb--)
{
PxF32 f = *src++;
flip(f);
stream.write(&f, sizeof(PxF32));
}
}
else
stream.write(src, sizeof(PxF32) * nb);
}
void physx::writeWordBuffer(const PxU16* src, PxU32 nb, bool mismatch, PxOutputStream& stream)
{
if(mismatch)
{
while(nb--)
{
PxU16 w = *src++;
flip(w);
stream.write(&w, sizeof(PxU16));
}
}
else
stream.write(src, sizeof(PxU16) * nb);
}
void physx::readWordBuffer(PxU16* dest, PxU32 nb, bool mismatch, PxInputStream& stream)
{
stream.read(dest, sizeof(PxU16)*nb);
if(mismatch)
{
for(PxU32 i=0;i<nb;i++)
{
flip(dest[i]);
}
}
}
void physx::writeWordBuffer(const PxI16* src, PxU32 nb, bool mismatch, PxOutputStream& stream)
{
if (mismatch)
{
while (nb--)
{
PxI16 w = *src++;
flip(w);
stream.write(&w, sizeof(PxI16));
}
}
else
stream.write(src, sizeof(PxI16) * nb);
}
void physx::readByteBuffer(PxU8* dest, PxU32 nb, PxInputStream& stream)
{
stream.read(dest, sizeof(PxU8) * nb);
}
void physx::writeByteBuffer(const PxU8* src, PxU32 nb, PxOutputStream& stream)
{
stream.write(src, sizeof(PxU8) * nb);
}
void physx::readWordBuffer(PxI16* dest, PxU32 nb, bool mismatch, PxInputStream& stream)
{
stream.read(dest, sizeof(PxI16)*nb);
if (mismatch)
{
for (PxU32 i = 0; i < nb; i++)
{
flip(dest[i]);
}
}
}
///////////////////////////////////////////////////////////////////////////////
bool physx::writeHeader(PxI8 a, PxI8 b, PxI8 c, PxI8 d, PxU32 version, bool mismatch, PxOutputStream& stream)
{
// Store endianness
PxI8 streamFlags = PxLittleEndian();
if(mismatch)
streamFlags^=1;
// Export header
writeChunk('N', 'X', 'S', streamFlags, stream); // "Novodex stream" identifier
writeChunk(a, b, c, d, stream); // Chunk identifier
writeDword(version, mismatch, stream);
return true;
}
bool Cm::WriteHeader(PxU8 a, PxU8 b, PxU8 c, PxU8 d, PxU32 version, bool mismatch, PxOutputStream& stream)
{
// Store endianness
PxU8 streamFlags = PxU8(PxLittleEndian());
if(mismatch)
streamFlags^=1;
// Export header
writeChunk('I', 'C', 'E', PxI8(streamFlags), stream); // ICE identifier
writeChunk(PxI8(a), PxI8(b), PxI8(c), PxI8(d), stream); // Chunk identifier
writeDword(version, mismatch, stream);
return true;
}
bool physx::readHeader(PxI8 a_, PxI8 b_, PxI8 c_, PxI8 d_, PxU32& version, bool& mismatch, PxInputStream& stream)
{
// Import header
PxI8 a, b, c, d;
readChunk(a, b, c, d, stream);
if(a!='N' || b!='X' || c!='S')
return false;
const PxI8 fileLittleEndian = d&1;
mismatch = fileLittleEndian!=PxLittleEndian();
readChunk(a, b, c, d, stream);
if(a!=a_ || b!=b_ || c!=c_ || d!=d_)
return false;
version = readDword(mismatch, stream);
return true;
}
bool Cm::ReadHeader(PxU8 a_, PxU8 b_, PxU8 c_, PxU8 d_, PxU32& version, bool& mismatch, PxInputStream& stream)
{
// Import header
PxI8 a, b, c, d;
readChunk(a, b, c, d, stream);
if(a!='I' || b!='C' || c!='E')
return false;
const PxU8 FileLittleEndian = PxU8(d&1);
mismatch = FileLittleEndian!=PxLittleEndian();
readChunk(a, b, c, d, stream);
if(a!=a_ || b!=b_ || c!=c_ || d!=d_)
return false;
version = readDword(mismatch, stream);
return true;
}
///////////////////////////////////////////////////////////////////////////////
PxU32 physx::computeMaxIndex(const PxU32* indices, PxU32 nbIndices)
{
PxU32 maxIndex=0;
while(nbIndices--)
{
PxU32 currentIndex = *indices++;
if(currentIndex>maxIndex)
maxIndex = currentIndex;
}
return maxIndex;
}
PxU16 physx::computeMaxIndex(const PxU16* indices, PxU32 nbIndices)
{
PxU16 maxIndex=0;
while(nbIndices--)
{
PxU16 currentIndex = *indices++;
if(currentIndex>maxIndex)
maxIndex = currentIndex;
}
return maxIndex;
}
void physx::storeIndices(PxU32 maxIndex, PxU32 nbIndices, const PxU32* indices, PxOutputStream& stream, bool platformMismatch)
{
if(maxIndex<=0xff)
{
for(PxU32 i=0;i<nbIndices;i++)
{
PxU8 data = PxU8(indices[i]);
stream.write(&data, sizeof(PxU8));
}
}
else if(maxIndex<=0xffff)
{
for(PxU32 i=0;i<nbIndices;i++)
writeWord(PxTo16(indices[i]), platformMismatch, stream);
}
else
{
writeIntBuffer(indices, nbIndices, platformMismatch, stream);
}
}
void physx::readIndices(PxU32 maxIndex, PxU32 nbIndices, PxU32* indices, PxInputStream& stream, bool platformMismatch)
{
if(maxIndex<=0xff)
{
PxU8 data;
for(PxU32 i=0;i<nbIndices;i++)
{
stream.read(&data, sizeof(PxU8));
indices[i] = data;
}
}
else if(maxIndex<=0xffff)
{
for(PxU32 i=0;i<nbIndices;i++)
indices[i] = readWord(platformMismatch, stream);
}
else
{
readIntBuffer(indices, nbIndices, platformMismatch, stream);
}
}
///////////////////////////////////////////////////////////////////////////////
void Cm::StoreIndices(PxU32 maxIndex, PxU32 nbIndices, const PxU32* indices, PxOutputStream& stream, bool platformMismatch)
{
if(maxIndex<=0xff)
{
for(PxU32 i=0;i<nbIndices;i++)
{
PxU8 data = PxU8(indices[i]);
stream.write(&data, sizeof(PxU8));
}
}
else if(maxIndex<=0xffff)
{
for(PxU32 i=0;i<nbIndices;i++)
writeWord(PxTo16(indices[i]), platformMismatch, stream);
}
else
{
// WriteDwordBuffer(indices, nbIndices, platformMismatch, stream);
for(PxU32 i=0;i<nbIndices;i++)
writeDword(indices[i], platformMismatch, stream);
}
}
void Cm::ReadIndices(PxU32 maxIndex, PxU32 nbIndices, PxU32* indices, PxInputStream& stream, bool platformMismatch)
{
if(maxIndex<=0xff)
{
PxU8* tmp = reinterpret_cast<PxU8*>(PxAlloca(nbIndices*sizeof(PxU8)));
stream.read(tmp, nbIndices*sizeof(PxU8));
for(PxU32 i=0;i<nbIndices;i++)
indices[i] = tmp[i];
// for(PxU32 i=0;i<nbIndices;i++)
// indices[i] = stream.ReadByte();
}
else if(maxIndex<=0xffff)
{
PxU16* tmp = reinterpret_cast<PxU16*>(PxAlloca(nbIndices*sizeof(PxU16)));
readWordBuffer(tmp, nbIndices, platformMismatch, stream);
for(PxU32 i=0;i<nbIndices;i++)
indices[i] = tmp[i];
// for(PxU32 i=0;i<nbIndices;i++)
// indices[i] = ReadWord(platformMismatch, stream);
}
else
{
ReadDwordBuffer(indices, nbIndices, platformMismatch, stream);
}
}
void Cm::StoreIndices(PxU16 maxIndex, PxU32 nbIndices, const PxU16* indices, PxOutputStream& stream, bool platformMismatch)
{
if(maxIndex<=0xff)
{
for(PxU32 i=0;i<nbIndices;i++)
{
PxU8 data = PxU8(indices[i]);
stream.write(&data, sizeof(PxU8));
}
}
else
{
for(PxU32 i=0;i<nbIndices;i++)
writeWord(indices[i], platformMismatch, stream);
}
}
void Cm::ReadIndices(PxU16 maxIndex, PxU32 nbIndices, PxU16* indices, PxInputStream& stream, bool platformMismatch)
{
if(maxIndex<=0xff)
{
PxU8* tmp = reinterpret_cast<PxU8*>(PxAlloca(nbIndices*sizeof(PxU8)));
stream.read(tmp, nbIndices*sizeof(PxU8));
for(PxU32 i=0;i<nbIndices;i++)
indices[i] = tmp[i];
}
else
{
readWordBuffer(indices, nbIndices, platformMismatch, stream);
}
}
| 10,480 |
C++
| 24.134293 | 126 | 0.661737 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmRandom.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_RANDOM_H
#define CM_RANDOM_H
#include "common/PxPhysXCommonConfig.h"
#define TEST_MAX_RAND 0xffff
namespace physx
{
namespace Cm
{
class BasicRandom
{
public:
BasicRandom(PxU32 seed = 0) : mRnd(seed) {}
~BasicRandom() {}
PX_FORCE_INLINE void setSeed(PxU32 seed) { mRnd = seed; }
PX_FORCE_INLINE PxU32 getCurrentValue() const { return mRnd; }
PxU32 randomize() { mRnd = mRnd * 2147001325 + 715136305; return mRnd; }
PX_FORCE_INLINE PxU32 rand() { return randomize() & 0xffff; }
PX_FORCE_INLINE PxU32 rand32() { return randomize() & 0xffffffff; }
PxF32 rand(PxF32 a, PxF32 b)
{
const PxF32 r = rand32() / (static_cast<PxF32>(0xffffffff));
return r * (b - a) + a;
}
PxI32 rand(PxI32 a, PxI32 b)
{
return a + static_cast<PxI32>(rand32() % (b - a));
}
PxF32 randomFloat()
{
return rand() / (static_cast<PxF32>(0xffff)) - 0.5f;
}
PxF32 randomFloat32()
{
return rand32() / (static_cast<PxF32>(0xffffffff)) - 0.5f;
}
PxF32 randomFloat32(PxReal a, PxReal b) { return rand32() / PxF32(0xffffffff)*(b - a) + a; }
void unitRandomPt(physx::PxVec3& v)
{
v = unitRandomPt();
}
void unitRandomQuat(physx::PxQuat& v)
{
v = unitRandomQuat();
}
PxVec3 unitRandomPt()
{
PxVec3 v;
do
{
v.x = randomFloat();
v.y = randomFloat();
v.z = randomFloat();
} while (v.normalize() < 1e-6f);
return v;
}
PxQuat unitRandomQuat()
{
PxQuat v;
do
{
v.x = randomFloat();
v.y = randomFloat();
v.z = randomFloat();
v.w = randomFloat();
} while (v.normalize() < 1e-6f);
return v;
}
private:
PxU32 mRnd;
};
//--------------------------------------
// Fast, very good random numbers
//
// Period = 2^249
//
// Kirkpatrick, S., and E. Stoll, 1981; A Very Fast Shift-Register
// Sequence Random Number Generator, Journal of Computational Physics,
// V. 40.
//
// Maier, W.L., 1991; A Fast Pseudo Random Number Generator,
// Dr. Dobb's Journal, May, pp. 152 - 157
class RandomR250
{
public:
RandomR250(PxI32 s)
{
setSeed(s);
}
void setSeed(PxI32 s)
{
BasicRandom lcg(s);
mIndex = 0;
PxI32 j;
for (j = 0; j < 250; j++) // fill r250 buffer with bit values
mBuffer[j] = lcg.randomize();
for (j = 0; j < 250; j++) // set some MSBs to 1
if (lcg.randomize() > 0x40000000L)
mBuffer[j] |= 0x80000000L;
PxU32 msb = 0x80000000; // turn on diagonal bit
PxU32 mask = 0xffffffff; // turn off the leftmost bits
for (j = 0; j < 32; j++)
{
const PxI32 k = 7 * j + 3; // select a word to operate on
mBuffer[k] &= mask; // turn off bits left of the diagonal
mBuffer[k] |= msb; // turn on the diagonal bit
mask >>= 1;
msb >>= 1;
}
}
PxU32 randI()
{
PxI32 j;
// wrap pointer around
if (mIndex >= 147) j = mIndex - 147;
else j = mIndex + 103;
const PxU32 new_rand = mBuffer[mIndex] ^ mBuffer[j];
mBuffer[mIndex] = new_rand;
// increment pointer for next time
if (mIndex >= 249) mIndex = 0;
else mIndex++;
return new_rand >> 1;
}
PxReal randUnit()
{
PxU32 mask = (1 << 23) - 1;
return PxF32(randI()&(mask)) / PxF32(mask);
}
PxReal rand(PxReal lower, PxReal upper)
{
return lower + randUnit() * (upper - lower);
}
private:
PxU32 mBuffer[250];
PxI32 mIndex;
};
static RandomR250 gRandomR250(0x95d6739b);
PX_FORCE_INLINE PxU32 Rand()
{
return gRandomR250.randI() & TEST_MAX_RAND;
}
PX_FORCE_INLINE PxF32 Rand(PxF32 a, PxF32 b)
{
const PxF32 r = static_cast<PxF32>(Rand()) / (static_cast<PxF32>(TEST_MAX_RAND));
return r * (b - a) + a;
}
PX_FORCE_INLINE PxF32 RandLegacy(PxF32 a, PxF32 b)
{
const PxF32 r = static_cast<PxF32>(Rand()) / (static_cast<PxF32>(0x7fff) + 1.0f);
return r * (b - a) + a;
}
//returns numbers from [a, b-1]
PX_FORCE_INLINE PxI32 Rand(PxI32 a, PxI32 b)
{
return a + static_cast<PxI32>(Rand() % (b - a));
}
PX_FORCE_INLINE void SetSeed(PxU32 seed)
{
gRandomR250.setSeed(seed);
}
}
}
#endif
| 5,835 |
C
| 25.053571 | 95 | 0.636161 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmPtrTable.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxAssert.h"
#include "foundation/PxMemory.h"
#include "common/PxMetaData.h"
#include "foundation/PxBitUtils.h"
#include "CmPtrTable.h"
#include "CmUtils.h"
using namespace physx;
using namespace Cm;
PtrTable::PtrTable() :
mList (NULL),
mCount (0),
mOwnsMemory (true),
mBufferUsed (false)
{
}
PtrTable::~PtrTable()
{
PX_ASSERT(mOwnsMemory);
PX_ASSERT(mCount == 0);
PX_ASSERT(mList == NULL);
}
void PtrTable::clear(PtrTableStorageManager& sm)
{
if(mOwnsMemory && mCount>1)
{
const PxU32 implicitCapacity = PxNextPowerOfTwo(PxU32(mCount)-1);
sm.deallocate(mList, implicitCapacity);
}
mList = NULL;
mOwnsMemory = true;
mCount = 0;
}
PxU32 PtrTable::find(const void* ptr) const
{
const PxU32 nbPtrs = mCount;
void*const * PX_RESTRICT ptrs = getPtrs();
for(PxU32 i=0; i<nbPtrs; i++)
{
if(ptrs[i] == ptr)
return i;
}
return 0xffffffff;
}
void PtrTable::exportExtraData(PxSerializationContext& stream)
{
if(mCount>1)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mList, sizeof(void*)*mCount);
}
}
void PtrTable::importExtraData(PxDeserializationContext& context)
{
if(mCount>1)
mList = context.readExtraData<void*, PX_SERIAL_ALIGN>(mCount);
}
void PtrTable::realloc(PxU32 oldCapacity, PxU32 newCapacity, PtrTableStorageManager& sm)
{
PX_ASSERT((mOwnsMemory && oldCapacity) || (!mOwnsMemory && oldCapacity == 0));
PX_ASSERT(newCapacity);
if(mOwnsMemory && sm.canReuse(oldCapacity, newCapacity))
return;
void** newMem = sm.allocate(newCapacity);
PxMemCopy(newMem, mList, mCount * sizeof(void*));
if(mOwnsMemory)
sm.deallocate(mList, oldCapacity);
mList = newMem;
mOwnsMemory = true;
}
void PtrTable::add(void* ptr, PtrTableStorageManager& sm)
{
if(mCount == 0) // 0 -> 1, easy case
{
PX_ASSERT(mOwnsMemory);
PX_ASSERT(mList == NULL);
PX_ASSERT(!mBufferUsed);
mSingle = ptr;
mCount = 1;
mBufferUsed = true;
return;
}
if(mCount == 1) // 1 -> 2, easy case
{
PX_ASSERT(mOwnsMemory);
PX_ASSERT(mBufferUsed);
void* single = mSingle;
mList = sm.allocate(2);
mList[0] = single;
mBufferUsed = false;
mOwnsMemory = true;
}
else
{
PX_ASSERT(!mBufferUsed);
if(!mOwnsMemory) // don't own the memory, must always alloc
realloc(0, PxNextPowerOfTwo(mCount), sm); // we're guaranteed nextPowerOfTwo(x) > x
else if(PxIsPowerOfTwo(mCount)) // count is at implicit capacity, so realloc
realloc(mCount, PxU32(mCount)*2, sm); // ... to next higher power of 2
PX_ASSERT(mOwnsMemory);
}
mList[mCount++] = ptr;
}
void PtrTable::replaceWithLast(PxU32 index, PtrTableStorageManager& sm)
{
PX_ASSERT(mCount!=0);
if(mCount == 1) // 1 -> 0 easy case
{
PX_ASSERT(mOwnsMemory);
PX_ASSERT(mBufferUsed);
mList = NULL;
mCount = 0;
mBufferUsed = false;
}
else if(mCount == 2) // 2 -> 1 easy case
{
PX_ASSERT(!mBufferUsed);
void* ptr = mList[1-index];
if(mOwnsMemory)
sm.deallocate(mList, 2);
mSingle = ptr;
mCount = 1;
mBufferUsed = true;
mOwnsMemory = true;
}
else
{
PX_ASSERT(!mBufferUsed);
mList[index] = mList[--mCount]; // remove before adjusting memory
if(!mOwnsMemory) // don't own the memory, must alloc
realloc(0, PxNextPowerOfTwo(PxU32(mCount)-1), sm); // if currently a power of 2, don't jump to the next one
else if(PxIsPowerOfTwo(mCount)) // own the memory, and implicit capacity requires that we downsize
realloc(PxU32(mCount)*2, PxU32(mCount), sm); // ... from the next power of 2, which was the old implicit capacity
PX_ASSERT(mOwnsMemory);
}
}
void Cm::PtrTable::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PtrTable)
PX_DEF_BIN_METADATA_ITEM(stream, PtrTable, void, mSingle, PxMetaDataFlag::ePTR) // PT: this is actually a union, beware
PX_DEF_BIN_METADATA_ITEM(stream, PtrTable, PxU16, mCount, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PtrTable, bool, mOwnsMemory, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PtrTable, bool, mBufferUsed, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PtrTable, PxU32, mFreeSlot, 0)
//------ Extra-data ------
// mList
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, PtrTable, void, mBufferUsed, mCount, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::ePTR, PX_SERIAL_ALIGN)
}
| 5,990 |
C++
| 27.802884 | 146 | 0.705676 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmIDPool.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_ID_POOL_H
#define CM_ID_POOL_H
#include "foundation/Px.h"
#include "foundation/PxArray.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
namespace Cm
{
template<class FreeBuffer>
class IDPoolBase : public PxUserAllocated
{
protected:
PxU32 mCurrentID;
FreeBuffer mFreeIDs;
public:
IDPoolBase() : mCurrentID(0) {}
void freeID(PxU32 id)
{
// Allocate on first call
// Add released ID to the array of free IDs
if(id == (mCurrentID - 1))
--mCurrentID;
else
mFreeIDs.pushBack(id);
}
void freeAll()
{
mCurrentID = 0;
mFreeIDs.clear();
}
PxU32 getNewID()
{
// If recycled IDs are available, use them
const PxU32 size = mFreeIDs.size();
if(size)
{
// Recycle last ID
return mFreeIDs.popBack();
}
// Else create a new ID
return mCurrentID++;
}
PxU32 getNumUsedID() const
{
return mCurrentID - mFreeIDs.size();
}
PxU32 getMaxID() const
{
return mCurrentID;
}
};
//This class extends IDPoolBase. This is mainly used for when it is unsafe for the application to free the id immediately so that it can
//defer the free process until it is safe to do so
template<class FreeBuffer>
class DeferredIDPoolBase : public IDPoolBase<FreeBuffer>
{
FreeBuffer mDeferredFreeIDs;
public:
//release an index into the deferred list
void deferredFreeID(PxU32 id)
{
mDeferredFreeIDs.pushBack(id);
}
//release the deferred indices into the free list
void processDeferredIds()
{
const PxU32 deferredFreeIDCount = mDeferredFreeIDs.size();
for(PxU32 a = 0; a < deferredFreeIDCount;++a)
{
IDPoolBase<FreeBuffer>::freeID(mDeferredFreeIDs[a]);
}
mDeferredFreeIDs.clear();
}
//release all indices
void freeAll()
{
mDeferredFreeIDs.clear();
IDPoolBase<FreeBuffer>::freeAll();
}
PxU32 getNumUsedID() const
{
return IDPoolBase<FreeBuffer>::getNumUsedID() - mDeferredFreeIDs.size();
}
FreeBuffer& getDeferredFreeIDs() { return mDeferredFreeIDs; }
};
//This is spu friendly fixed size array
template <typename T, uint32_t N>
class InlineFixedArray
{
T mArr[N];
PxU32 mSize;
public:
InlineFixedArray() : mSize(0)
{
}
~InlineFixedArray(){}
void pushBack(const T& t)
{
PX_ASSERT(mSize < N);
mArr[mSize++] = t;
}
T popBack()
{
PX_ASSERT(mSize > 0);
return mArr[--mSize];
}
void clear() { mSize = 0; }
T& operator [] (PxU32 index) { PX_ASSERT(index < N); return mArr[index]; }
const T& operator [] (PxU32 index) const { PX_ASSERT(index < N); return mArr[index]; }
PxU32 size() const { return mSize; }
};
//Fix size IDPool
template<PxU32 Capacity>
class InlineIDPool : public IDPoolBase<InlineFixedArray<PxU32, Capacity> >
{
public:
PxU32 getNumRemainingIDs()
{
return Capacity - this->getNumUsedID();
}
};
//Dynamic resize IDPool
class IDPool : public IDPoolBase<PxArray<PxU32> >
{
};
//This class is used to recycle indices. It supports deferred release, so that until processDeferredIds is called,
//released indices will not be reallocated. This class will fail if the calling code request more id than the InlineDeferredIDPoll
//has. It is the calling code's responsibility to ensure that this does not happen.
template<PxU32 Capacity>
class InlineDeferredIDPool : public DeferredIDPoolBase<InlineFixedArray<PxU32, Capacity> >
{
public:
PxU32 getNumRemainingIDs()
{
return Capacity - IDPoolBase< InlineFixedArray<PxU32, Capacity> >::getNumUsedID();
}
};
//Dynamic resize DeferredIDPool
class DeferredIDPool : public DeferredIDPoolBase<PxArray<PxU32> >
{
};
} // namespace Cm
}
#endif
| 5,366 |
C
| 25.180488 | 137 | 0.711703 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmPriorityQueue.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_PRIORITY_QUEUE_H
#define CM_PRIORITY_QUEUE_H
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxMemory.h"
namespace physx
{
namespace Cm
{
template<class Element, class Comparator = PxLess<Element> >
class PriorityQueueBase : protected Comparator // inherit so that stateless comparators take no space
{
public:
PriorityQueueBase(const Comparator& less, Element* elements) : Comparator(less), mHeapSize(0), mDataPtr(elements)
{
}
~PriorityQueueBase()
{
}
//! Get the element with the highest priority
PX_FORCE_INLINE const Element top() const
{
return mDataPtr[0];
}
//! Get the element with the highest priority
PX_FORCE_INLINE Element top()
{
return mDataPtr[0];
}
//! Check to whether the priority queue is empty
PX_FORCE_INLINE bool empty() const
{
return (mHeapSize == 0);
}
//! Empty the priority queue
PX_FORCE_INLINE void clear()
{
mHeapSize = 0;
}
//! Insert a new element into the priority queue. Only valid when size() is less than Capacity
PX_FORCE_INLINE void push(const Element& value)
{
PxU32 newIndex;
PxU32 parentIndex = parent(mHeapSize);
for (newIndex = mHeapSize; newIndex > 0 && compare(value, mDataPtr[parentIndex]); newIndex = parentIndex, parentIndex= parent(newIndex))
{
mDataPtr[ newIndex ] = mDataPtr[parentIndex];
}
mDataPtr[newIndex] = value;
mHeapSize++;
PX_ASSERT(valid());
}
//! Delete the highest priority element. Only valid when non-empty.
PX_FORCE_INLINE Element pop()
{
PX_ASSERT(mHeapSize > 0);
PxU32 i, child;
//try to avoid LHS
PxU32 tempHs = mHeapSize-1;
mHeapSize = tempHs;
Element min = mDataPtr[0];
Element last = mDataPtr[tempHs];
for (i = 0; (child = left(i)) < tempHs; i = child)
{
/* Find highest priority child */
const PxU32 rightChild = child + 1;
child += ((rightChild < tempHs) & compare((mDataPtr[rightChild]), (mDataPtr[child]))) ? 1 : 0;
if(compare(last, mDataPtr[child]))
break;
mDataPtr[i] = mDataPtr[child];
}
mDataPtr[ i ] = last;
PX_ASSERT(valid());
return min;
}
//! Make sure the priority queue sort all elements correctly
bool valid() const
{
const Element& min = mDataPtr[0];
for(PxU32 i=1; i<mHeapSize; ++i)
{
if(compare(mDataPtr[i], min))
return false;
}
return true;
}
//! Return number of elements in the priority queue
PxU32 size() const
{
return mHeapSize;
}
protected:
PxU32 mHeapSize;
Element* mDataPtr;
PX_FORCE_INLINE bool compare(const Element& a, const Element& b) const
{
return Comparator::operator()(a,b);
}
static PX_FORCE_INLINE PxU32 left(PxU32 nodeIndex)
{
return (nodeIndex << 1) + 1;
}
static PX_FORCE_INLINE PxU32 parent(PxU32 nodeIndex)
{
return (nodeIndex - 1) >> 1;
}
private:
PriorityQueueBase<Element, Comparator>& operator = (const PriorityQueueBase<Element, Comparator>);
};
template <typename Element, PxU32 Capacity, typename Comparator>
class InlinePriorityQueue : public PriorityQueueBase<Element, Comparator>
{
Element mData[Capacity];
public:
InlinePriorityQueue(const Comparator& less = Comparator()) : PriorityQueueBase<Element, Comparator>(less, mData)
{
}
PX_FORCE_INLINE void push(Element& elem)
{
PX_ASSERT(this->mHeapSize < Capacity);
PriorityQueueBase<Element, Comparator>::push(elem);
}
private:
InlinePriorityQueue<Element, Capacity, Comparator>& operator = (const InlinePriorityQueue<Element, Capacity, Comparator>);
};
template <typename Element, typename Comparator, typename Alloc = typename physx::PxAllocatorTraits<Element>::Type>
class PriorityQueue : public PriorityQueueBase<Element, Comparator>, protected Alloc
{
PxU32 mCapacity;
public:
PriorityQueue(const Comparator& less = Comparator(), PxU32 initialCapacity = 0, Alloc alloc = Alloc())
: PriorityQueueBase<Element, Comparator>(less, NULL), Alloc(alloc), mCapacity(initialCapacity)
{
if(initialCapacity > 0)
this->mDataPtr = reinterpret_cast<Element*>(Alloc::allocate(sizeof(Element)*initialCapacity, PX_FL));
}
~PriorityQueue()
{
if(this->mDataPtr)
this->deallocate(this->mDataPtr);
}
PX_FORCE_INLINE void push(Element& elem)
{
if(this->mHeapSize == mCapacity)
{
reserve((this->mHeapSize+1)*2);
}
PriorityQueueBase<Element, Comparator>::push(elem);
}
PX_FORCE_INLINE PxU32 capacity()
{
return mCapacity;
}
PX_FORCE_INLINE void reserve(const PxU32 newCapacity)
{
if(newCapacity > mCapacity)
{
Element* newElems = reinterpret_cast<Element*>(Alloc::allocate(sizeof(Element)*newCapacity, PX_FL));
if(this->mDataPtr)
{
physx::PxMemCopy(newElems, this->mDataPtr, sizeof(Element) * this->mHeapSize);
Alloc::deallocate(this->mDataPtr);
}
this->mDataPtr = newElems;
mCapacity = newCapacity;
}
}
private:
PriorityQueue<Element, Comparator, Alloc>& operator = (const PriorityQueue<Element, Comparator, Alloc>);
};
}
}
#endif
| 6,807 |
C
| 27.970213 | 140 | 0.701924 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmBlockArray.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_BLOCK_ARRAY_H
#define CM_BLOCK_ARRAY_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/PxArray.h"
namespace physx
{
namespace Cm
{
template <typename T, PxU32 SlabSize = 4096>
class BlockArray
{
PxArray<T*> mBlocks;
PxU32 mSize;
PxU32 mCapacity;
public:
BlockArray() : mSize(0), mCapacity(0)
{
}
~BlockArray()
{
for (PxU32 a = 0; a < mBlocks.size(); ++a)
{
for (PxU32 i = 0; i < SlabSize; ++i)
{
mBlocks[a][i].~T();
}
PX_FREE(mBlocks[a]);
}
mBlocks.resize(0);
}
void reserve(PxU32 capacity)
{
if (capacity > mCapacity)
{
PxU32 nbSlabsRequired = (capacity + SlabSize - 1) / SlabSize;
PxU32 nbSlabsToAllocate = nbSlabsRequired - mBlocks.size();
mCapacity += nbSlabsToAllocate * SlabSize;
for (PxU32 a = 0; a < nbSlabsToAllocate; ++a)
{
T* ts = reinterpret_cast<T*>(PX_ALLOC(sizeof(T) * SlabSize, "BlockArray"));
for(PxU32 i = 0; i < SlabSize; ++i)
PX_PLACEMENT_NEW(ts+i, T)();
mBlocks.pushBack(ts);
}
}
}
void resize(PxU32 size)
{
reserve(size);
for (PxU32 a = mSize; a < size; ++a)
{
mBlocks[a / SlabSize][a&(SlabSize - 1)].~T();
mBlocks[a / SlabSize][a&(SlabSize-1)] = T();
}
mSize = size;
}
void forceSize_Unsafe(PxU32 size)
{
PX_ASSERT(size <= mCapacity);
mSize = size;
}
void remove(PxU32 idx)
{
PX_ASSERT(idx < mSize);
for (PxU32 a = idx; a < mSize; ++a)
{
mBlocks[a / SlabSize][a&(SlabSize-1)] = mBlocks[(a + 1) / SlabSize][(a + 1) &(SlabSize-1)];
}
mSize--;
mBlocks[mSize / SlabSize][mSize&(SlabSize - 1)].~T();
}
void replaceWithLast(PxU32 idx)
{
PX_ASSERT(idx < mSize);
--mSize;
mBlocks[idx / SlabSize][idx%SlabSize] = mBlocks[mSize / SlabSize][mSize%SlabSize];
}
T& operator [] (const PxU32 idx)
{
PX_ASSERT(idx < mSize);
return mBlocks[idx / SlabSize][idx%SlabSize];
}
const T& operator [] (const PxU32 idx) const
{
PX_ASSERT(idx < mSize);
return mBlocks[idx / SlabSize][idx%SlabSize];
}
void pushBack(const T& item)
{
reserve(mSize + 1);
mBlocks[mSize / SlabSize][mSize%SlabSize] = item;
mSize++;
}
PxU32 capacity() const { return mCapacity; }
PxU32 size() const { return mSize; }
};
}
}
#endif
| 4,077 |
C
| 24.810126 | 94 | 0.686044 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmTask.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_TASK_H
#define CM_TASK_H
#include "task/PxTask.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxMutex.h"
#include "foundation/PxInlineArray.h"
#include "foundation/PxFPU.h"
namespace physx
{
namespace Cm
{
// wrapper around the public PxLightCpuTask
// internal SDK tasks should be inherited from
// this and override the runInternal() method
// to ensure that the correct floating point
// state is set / reset during execution
class Task : public physx::PxLightCpuTask
{
public:
Task(PxU64 contextId)
{
mContextID = contextId;
}
virtual void run()
{
#if PX_SWITCH // special case because default rounding mode is not nearest
PX_FPU_GUARD;
#else
PX_SIMD_GUARD;
#endif
runInternal();
}
virtual void runInternal()=0;
};
// same as Cm::Task but inheriting from physx::PxBaseTask
// instead of PxLightCpuTask
class BaseTask : public physx::PxBaseTask
{
public:
virtual void run()
{
#if PX_SWITCH // special case because default rounding mode is not nearest
PX_FPU_GUARD;
#else
PX_SIMD_GUARD;
#endif
runInternal();
}
virtual void runInternal()=0;
};
template <class T, void (T::*Fn)(physx::PxBaseTask*) >
class DelegateTask : public Cm::Task, public PxUserAllocated
{
public:
DelegateTask(PxU64 contextID, T* obj, const char* name) : Cm::Task(contextID), mObj(obj), mName(name) {}
virtual void run()
{
#if PX_SWITCH // special case because default rounding mode is not nearest
PX_FPU_GUARD;
#else
PX_SIMD_GUARD;
#endif
(mObj->*Fn)(mCont);
}
virtual void runInternal()
{
(mObj->*Fn)(mCont);
}
virtual const char* getName() const
{
return mName;
}
void setObject(T* obj) { mObj = obj; }
private:
T* mObj;
const char* mName;
};
/**
\brief A task that maintains a list of dependent tasks.
This task maintains a list of dependent tasks that have their reference counts
reduced on completion of the task.
The refcount is incremented every time a dependent task is added.
*/
class FanoutTask : public Cm::BaseTask
{
PX_NOCOPY(FanoutTask)
public:
FanoutTask(PxU64 contextID, const char* name) : Cm::BaseTask(), mRefCount(0), mName(name), mNotifySubmission(false) { mContextID = contextID; }
virtual void runInternal() {}
virtual const char* getName() const { return mName; }
/**
Swap mDependents with mReferencesToRemove when refcount goes to 0.
*/
virtual void removeReference()
{
PxMutex::ScopedLock lock(mMutex);
if (!physx::PxAtomicDecrement(&mRefCount))
{
// prevents access to mReferencesToRemove until release
physx::PxAtomicIncrement(&mRefCount);
mNotifySubmission = false;
PX_ASSERT(mReferencesToRemove.empty());
for (PxU32 i = 0; i < mDependents.size(); i++)
mReferencesToRemove.pushBack(mDependents[i]);
mDependents.clear();
mTm->getCpuDispatcher()->submitTask(*this);
}
}
/**
\brief Increases reference count
*/
virtual void addReference()
{
PxMutex::ScopedLock lock(mMutex);
physx::PxAtomicIncrement(&mRefCount);
mNotifySubmission = true;
}
/**
\brief Return the ref-count for this task
*/
PX_INLINE PxI32 getReference() const
{
return mRefCount;
}
/**
Sets the task manager. Doesn't increase the reference count.
*/
PX_INLINE void setTaskManager(physx::PxTaskManager& tm)
{
mTm = &tm;
}
/**
Adds a dependent task. It also sets the task manager querying it from the dependent task.
The refcount is incremented every time a dependent task is added.
*/
PX_INLINE void addDependent(physx::PxBaseTask& dependent)
{
PxMutex::ScopedLock lock(mMutex);
physx::PxAtomicIncrement(&mRefCount);
mTm = dependent.getTaskManager();
mDependents.pushBack(&dependent);
dependent.addReference();
mNotifySubmission = true;
}
/**
Reduces reference counts of the continuation task and the dependent tasks, also
clearing the copy of continuation and dependents task list.
*/
virtual void release()
{
PxInlineArray<physx::PxBaseTask*, 10> referencesToRemove;
{
PxMutex::ScopedLock lock(mMutex);
const PxU32 contCount = mReferencesToRemove.size();
referencesToRemove.reserve(contCount);
for (PxU32 i=0; i < contCount; ++i)
referencesToRemove.pushBack(mReferencesToRemove[i]);
mReferencesToRemove.clear();
// allow access to mReferencesToRemove again
if (mNotifySubmission)
{
removeReference();
}
else
{
physx::PxAtomicDecrement(&mRefCount);
}
// the scoped lock needs to get freed before the continuation tasks get (potentially) submitted because
// those continuation tasks might trigger events that delete this task and corrupt the memory of the
// mutex (for example, assume this task is a member of the scene then the submitted tasks cause the simulation
// to finish and then the scene gets released which in turn will delete this task. When this task then finally
// continues the heap memory will be corrupted.
}
for (PxU32 i=0; i < referencesToRemove.size(); ++i)
referencesToRemove[i]->removeReference();
}
protected:
volatile PxI32 mRefCount;
const char* mName;
PxInlineArray<physx::PxBaseTask*, 4> mDependents;
PxInlineArray<physx::PxBaseTask*, 4> mReferencesToRemove;
bool mNotifySubmission;
PxMutex mMutex; // guarding mDependents and mNotifySubmission
};
/**
\brief Specialization of FanoutTask class in order to provide the delegation mechanism.
*/
template <class T, void (T::*Fn)(physx::PxBaseTask*) >
class DelegateFanoutTask : public FanoutTask, public PxUserAllocated
{
public:
DelegateFanoutTask(PxU64 contextID, T* obj, const char* name) :
FanoutTask(contextID, name), mObj(obj) { }
virtual void runInternal()
{
physx::PxBaseTask* continuation = mReferencesToRemove.empty() ? NULL : mReferencesToRemove[0];
(mObj->*Fn)(continuation);
}
void setObject(T* obj) { mObj = obj; }
private:
T* mObj;
};
PX_FORCE_INLINE void startTask(Cm::Task* task, PxBaseTask* continuation)
{
if(continuation)
{
// PT: TODO: just make this a PxBaseTask function?
task->setContinuation(continuation);
task->removeReference();
}
else
task->runInternal();
}
} // namespace Cm
}
#endif
| 8,032 |
C
| 26.989547 | 145 | 0.711653 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmUtils.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_UTILS_H
#define CM_UTILS_H
#include "foundation/PxVec3.h"
#include "foundation/PxMat33.h"
#include "foundation/PxBounds3.h"
#include "common/PxBase.h"
#include "foundation/PxInlineArray.h"
#include "foundation/PxArray.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxMemory.h"
namespace physx
{
namespace Cm
{
template<class DstType, class SrcType>
PX_FORCE_INLINE PxU32 getArrayOfPointers(DstType** PX_RESTRICT userBuffer, PxU32 bufferSize, PxU32 startIndex, SrcType*const* PX_RESTRICT src, PxU32 size)
{
const PxU32 remainder = PxU32(PxMax<PxI32>(PxI32(size - startIndex), 0));
const PxU32 writeCount = PxMin(remainder, bufferSize);
src += startIndex;
for(PxU32 i=0;i<writeCount;i++)
userBuffer[i] = static_cast<DstType*>(src[i]);
return writeCount;
}
PX_CUDA_CALLABLE PX_INLINE void transformInertiaTensor(const PxVec3& invD, const PxMat33& M, PxMat33& mIInv)
{
const float axx = invD.x*M(0,0), axy = invD.x*M(1,0), axz = invD.x*M(2,0);
const float byx = invD.y*M(0,1), byy = invD.y*M(1,1), byz = invD.y*M(2,1);
const float czx = invD.z*M(0,2), czy = invD.z*M(1,2), czz = invD.z*M(2,2);
mIInv(0,0) = axx*M(0,0) + byx*M(0,1) + czx*M(0,2);
mIInv(1,1) = axy*M(1,0) + byy*M(1,1) + czy*M(1,2);
mIInv(2,2) = axz*M(2,0) + byz*M(2,1) + czz*M(2,2);
mIInv(0,1) = mIInv(1,0) = axx*M(1,0) + byx*M(1,1) + czx*M(1,2);
mIInv(0,2) = mIInv(2,0) = axx*M(2,0) + byx*M(2,1) + czx*M(2,2);
mIInv(1,2) = mIInv(2,1) = axy*M(2,0) + byy*M(2,1) + czy*M(2,2);
}
// PT: TODO: refactor this with PxBounds3 header
PX_FORCE_INLINE PxVec3 basisExtent(const PxVec3& basis0, const PxVec3& basis1, const PxVec3& basis2, const PxVec3& extent)
{
// extended basis vectors
const PxVec3 c0 = basis0 * extent.x;
const PxVec3 c1 = basis1 * extent.y;
const PxVec3 c2 = basis2 * extent.z;
// find combination of base vectors that produces max. distance for each component = sum of abs()
return PxVec3 ( 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));
}
PX_FORCE_INLINE PxBounds3 basisExtent(const PxVec3& center, const PxVec3& basis0, const PxVec3& basis1, const PxVec3& basis2, const PxVec3& extent)
{
const PxVec3 w = basisExtent(basis0, basis1, basis2, extent);
return PxBounds3(center - w, center + w);
}
PX_FORCE_INLINE bool isValid(const PxVec3& c, const PxVec3& e)
{
return (c.isFinite() && e.isFinite() && (((e.x >= 0.0f) && (e.y >= 0.0f) && (e.z >= 0.0f)) ||
((e.x == -PX_MAX_BOUNDS_EXTENTS) &&
(e.y == -PX_MAX_BOUNDS_EXTENTS) &&
(e.z == -PX_MAX_BOUNDS_EXTENTS))));
}
PX_FORCE_INLINE bool isEmpty(const PxVec3& c, const PxVec3& e)
{
PX_UNUSED(c);
PX_ASSERT(isValid(c, e));
return e.x<0.0f;
}
// Array with externally managed storage.
// Allocation and resize policy are managed by the owner,
// Very minimal functionality right now, just POD types
template <typename T,
typename Owner,
typename IndexType,
void (Owner::*realloc)(T*& currentMem, IndexType& currentCapacity, IndexType size, IndexType requiredMinCapacity)>
class OwnedArray
{
public:
OwnedArray()
: mData(0)
, mCapacity(0)
, mSize(0)
{}
~OwnedArray() // owner must call releaseMem before destruction
{
PX_ASSERT(mCapacity==0);
}
void pushBack(T& element, Owner& owner)
{
// there's a failure case if here if we push an existing element which causes a resize -
// a rare case not worth coding around; if you need it, copy the element then push it.
PX_ASSERT(&element<mData || &element>=mData+mSize);
if(mSize==mCapacity)
(owner.*realloc)(mData, mCapacity, mSize, IndexType(mSize+1));
PX_ASSERT(mData && mSize<mCapacity);
mData[mSize++] = element;
}
IndexType size() const
{
return mSize;
}
void replaceWithLast(IndexType index)
{
PX_ASSERT(index<mSize);
mData[index] = mData[--mSize];
}
T* begin() const
{
return mData;
}
T* end() const
{
return mData+mSize;
}
T& operator [](IndexType index)
{
PX_ASSERT(index<mSize);
return mData[index];
}
const T& operator [](IndexType index) const
{
PX_ASSERT(index<mSize);
return mData[index];
}
void reserve(IndexType capacity, Owner &owner)
{
if(capacity>=mCapacity)
(owner.*realloc)(mData, mCapacity, mSize, capacity);
}
void releaseMem(Owner &owner)
{
mSize = 0;
(owner.*realloc)(mData, mCapacity, 0, 0);
}
private:
T* mData;
IndexType mCapacity;
IndexType mSize;
// just in case someone tries to use a non-POD in here
union FailIfNonPod
{
T t;
int x;
};
};
/**
Any object deriving from PxBase needs to call this function instead of 'delete object;'.
We don't want to implement 'operator delete' in PxBase because that would impose how
memory of derived classes is allocated. Even though most or all of the time derived classes will
be user allocated, we don't want to put UserAllocatable into the API and derive from that.
*/
template<typename T>
PX_INLINE void deletePxBase(T* object)
{
if(object->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
{
PX_DELETE(object);
}
else
object->~T();
}
#define PX_PADDING_8 0xcd
#define PX_PADDING_16 0xcdcd
#define PX_PADDING_32 0xcdcdcdcd
/**
Macro to instantiate a type for serialization testing.
Note: Only use PX_NEW_SERIALIZED once in a scope.
*/
#if PX_CHECKED
#define PX_NEW_SERIALIZED(v,T) \
void* _buf = physx::PxReflectionAllocator<T>().allocate(sizeof(T), PX_FL); \
PxMarkSerializedMemory(_buf, sizeof(T)); \
v = PX_PLACEMENT_NEW(_buf, T)
#else
#define PX_NEW_SERIALIZED(v,T) v = PX_NEW(T)
#endif
template<typename T, class Alloc>
struct ArrayAccess: public PxArray<T, Alloc>
{
void store(PxSerializationContext& context) const
{
if(this->mData && (this->mSize || this->capacity()))
context.writeData(this->mData, this->capacity()*sizeof(T));
}
void load(PxDeserializationContext& context)
{
if(this->mData && (this->mSize || this->capacity()))
this->mData = context.readExtraData<T>(this->capacity());
}
};
template<typename T, typename Alloc>
void exportArray(const PxArray<T, Alloc>& a, PxSerializationContext& context)
{
static_cast<const ArrayAccess<T, Alloc>&>(a).store(context);
}
template<typename T, typename Alloc>
void importArray(PxArray<T, Alloc>& a, PxDeserializationContext& context)
{
static_cast<ArrayAccess<T, Alloc>&>(a).load(context);
}
template<typename T, PxU32 N, typename Alloc>
void exportInlineArray(const PxInlineArray<T, N, Alloc>& a, PxSerializationContext& context)
{
if(!a.isInlined())
Cm::exportArray(a, context);
}
template<typename T, PxU32 N, typename Alloc>
void importInlineArray(PxInlineArray<T, N, Alloc>& a, PxDeserializationContext& context)
{
if(!a.isInlined())
Cm::importArray(a, context);
}
template<class T>
static PX_INLINE T* reserveContainerMemory(PxArray<T>& container, PxU32 nb)
{
const PxU32 maxNbEntries = container.capacity();
const PxU32 requiredSize = container.size() + nb;
if(requiredSize>maxNbEntries)
{
const PxU32 naturalGrowthSize = maxNbEntries ? maxNbEntries*2 : 2;
const PxU32 newSize = PxMax(requiredSize, naturalGrowthSize);
container.reserve(newSize);
}
T* buf = container.end();
container.forceSize_Unsafe(requiredSize);
return buf;
}
} // namespace Cm
}
#endif
| 8,959 |
C
| 28.668874 | 154 | 0.702199 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmCollection.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "CmCollection.h"
using namespace physx;
using namespace Cm;
void Collection::add(PxBase& object, PxSerialObjectId id)
{
PxSerialObjectId originId = getId(object);
if( originId != PX_SERIAL_OBJECT_ID_INVALID)
{
if( originId != id)
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxCollection::add called for an object that has an associated id already present in the collection!");
}
return;
}
if(id != PX_SERIAL_OBJECT_ID_INVALID)
{
if(!mIds.insert(id, &object))
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxCollection::add called with an id which is already used in the collection");
return;
}
}
mObjects[&object] = id;
}
void Collection::remove(PxBase& object)
{
PX_CHECK_AND_RETURN(contains(object), "PxCollection::remove called for an object not contained in the collection!");
const ObjectToIdMap::Entry* e = mObjects.find(&object);
if(e)
{
mIds.erase(e->second);
mObjects.erase(&object);
}
}
bool Collection::contains(PxBase& object) const
{
return mObjects.find(&object) != NULL;
}
void Collection::addId(PxBase& object, PxSerialObjectId id)
{
PX_CHECK_AND_RETURN(contains(object), "PxCollection::addId called for object that is not contained in the collection!");
PX_CHECK_AND_RETURN(id != PX_SERIAL_OBJECT_ID_INVALID, "PxCollection::addId called with PxSerialObjectId being set to PX_SERIAL_OBJECT_ID_INVALID!");
PX_CHECK_AND_RETURN(mIds.find(id) == NULL, "PxCollection::addId called with an id which is already used in the collection!");
const ObjectToIdMap::Entry* e = mObjects.find(&object);
if(e && e->second != PX_SERIAL_OBJECT_ID_INVALID)
mIds.erase(e->second);
mIds.insert(id, &object);
mObjects[&object] = id;
}
void Collection::removeId(PxSerialObjectId id)
{
PX_CHECK_AND_RETURN(id != PX_SERIAL_OBJECT_ID_INVALID, "PxCollection::removeId called with PxSerialObjectId being set to PX_SERIAL_OBJECT_ID_INVALID!");
PX_CHECK_AND_RETURN(mIds.find(id), "PxCollection::removeId called with PxSerialObjectId not contained in the collection!");
const IdToObjectMap::Entry* e = mIds.find(id);
if(e)
{
mObjects[e->second] = PX_SERIAL_OBJECT_ID_INVALID;
mIds.erase(id);
}
}
PxBase* Collection::find(PxSerialObjectId id) const
{
PX_CHECK_AND_RETURN_NULL(id != PX_SERIAL_OBJECT_ID_INVALID, "PxCollection::find called with PxSerialObjectId being set to PX_SERIAL_OBJECT_ID_INVALID!");
const IdToObjectMap::Entry* e = mIds.find(id);
return e ? static_cast<PxBase*>(e->second) : NULL;
}
void Collection::add(PxCollection& _collection)
{
Collection& collection = static_cast<Collection&>(_collection);
PX_CHECK_AND_RETURN(this != &collection, "PxCollection::add(PxCollection&) called with itself!");
mObjects.reserve(mObjects.capacity() + collection.mObjects.size());
const ObjectToIdMap::Entry* e = collection.mObjects.getEntries();
for (PxU32 i = 0; i < collection.mObjects.size(); ++i)
{
PxSerialObjectId id = e[i].second;
if( id != PX_SERIAL_OBJECT_ID_INVALID)
{
if(!mIds.insert(id, e[i].first))
{
if(mIds[id] != e[i].first)
{
PX_CHECK_MSG( false, "PxCollection::add(PxCollection&) called with conflicting id!");
mObjects.insert(e[i].first, PX_SERIAL_OBJECT_ID_INVALID);
}
}
else
mObjects[ e[i].first ] = id;
}
else
mObjects.insert(e[i].first, PX_SERIAL_OBJECT_ID_INVALID);
}
}
void Collection::remove(PxCollection& _collection)
{
Collection& collection = static_cast<Collection&>(_collection);
PX_CHECK_AND_RETURN(this != &collection, "PxCollection::remove(PxCollection&) called with itself!");
const ObjectToIdMap::Entry* e = collection.mObjects.getEntries();
for (PxU32 i = 0; i < collection.mObjects.size(); ++i)
{
const ObjectToIdMap::Entry* e1 = mObjects.find(e[i].first);
if(e1)
{
mIds.erase(e1->second);
mObjects.erase(e1->first);
}
}
}
PxU32 Collection::getNbObjects() const
{
return mObjects.size();
}
PxBase& Collection::getObject(PxU32 index) const
{
PX_ASSERT(index < mObjects.size());
return *mObjects.getEntries()[index].first;
}
PxU32 Collection::getObjects(PxBase** userBuffer, PxU32 bufferSize, PxU32 startIndex) const
{
PX_CHECK_AND_RETURN_NULL(userBuffer != NULL, "PxCollection::getObjects called with userBuffer NULL!");
PX_CHECK_AND_RETURN_NULL(bufferSize != 0, "PxCollection::getObjects called with bufferSize 0!");
PxU32 dstIndex = 0;
const ObjectToIdMap::Entry* e = mObjects.getEntries();
for (PxU32 srcIndex = startIndex; srcIndex < mObjects.size() && dstIndex < bufferSize; ++srcIndex)
userBuffer[dstIndex++] = e[srcIndex].first;
return dstIndex;
}
PxU32 Collection::getNbIds() const
{
return mIds.size();
}
PxSerialObjectId Collection::getId(const PxBase& object) const
{
const ObjectToIdMap::Entry* e = mObjects.find(const_cast<PxBase*>(&object));
return e ? e->second : PX_SERIAL_OBJECT_ID_INVALID;
}
PxU32 Collection::getIds(PxSerialObjectId* userBuffer, PxU32 bufferSize, PxU32 startIndex) const
{
PX_CHECK_AND_RETURN_NULL(userBuffer != NULL, "PxCollection::getIds called with userBuffer NULL!");
PX_CHECK_AND_RETURN_NULL(bufferSize != 0, "PxCollection::getIds called with bufferSize 0!");
PxU32 dstIndex = 0;
IdToObjectMap::Iterator srcIt = (const_cast<IdToObjectMap&>(mIds)).getIterator();
while (!srcIt.done() && dstIndex < bufferSize)
{
if(srcIt->first != PX_SERIAL_OBJECT_ID_INVALID)
{
if(startIndex > 0)
startIndex--;
else
userBuffer[dstIndex++] = srcIt->first;
}
srcIt++;
}
return dstIndex;
}
PxCollection* PxCreateCollection()
{
return PX_NEW(Collection);
}
| 7,379 |
C++
| 33.166667 | 154 | 0.716764 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmRefCountable.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_REFCOUNTABLE_H
#define CM_REFCOUNTABLE_H
#include "foundation/PxAssert.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxAllocator.h"
#include "common/PxBase.h"
namespace physx
{
namespace Cm
{
// PT: this is used to re-implement RefCountable using the ref-counter in PxBase, i.e. to dissociate
// the RefCountable data from the RefCountable code. The goal is to be able to store the ref counter
// in the padding bytes of PxBase, and also to avoid two v-table pointers in the class.
class RefCountableExt : public PxRefCounted
{
public:
RefCountableExt() : PxRefCounted(0, PxBaseFlags(0)) {}
void preExportDataReset()
{
mBuiltInRefCount = 1;
}
void incRefCount()
{
volatile PxI32* val = reinterpret_cast<volatile PxI32*>(&mBuiltInRefCount);
PxAtomicIncrement(val);
// value better be greater than 1, or we've created a ref to an undefined object
PX_ASSERT(mBuiltInRefCount>1);
}
void decRefCount()
{
PX_ASSERT(mBuiltInRefCount>0);
volatile PxI32* val = reinterpret_cast<volatile PxI32*>(&mBuiltInRefCount);
if(physx::PxAtomicDecrement(val) == 0)
onRefCountZero();
}
PX_FORCE_INLINE PxU32 getRefCount() const
{
return mBuiltInRefCount;
}
};
PX_FORCE_INLINE void RefCountable_preExportDataReset(PxRefCounted& base) { static_cast<RefCountableExt&>(base).preExportDataReset(); }
PX_FORCE_INLINE void RefCountable_incRefCount(PxRefCounted& base) { static_cast<RefCountableExt&>(base).incRefCount(); }
PX_FORCE_INLINE void RefCountable_decRefCount(PxRefCounted& base) { static_cast<RefCountableExt&>(base).decRefCount(); }
PX_FORCE_INLINE PxU32 RefCountable_getRefCount(const PxRefCounted& base) { return static_cast<const RefCountableExt&>(base).getRefCount(); }
// simple thread-safe reference count
// when the ref count is zero, the object is in an undefined state (pending delete)
class RefCountable
{
public:
// PX_SERIALIZATION
RefCountable(const PxEMPTY) { PX_ASSERT(mRefCount == 1); }
void preExportDataReset() { mRefCount = 1; }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
explicit RefCountable(PxU32 initialCount = 1)
: mRefCount(PxI32(initialCount))
{
PX_ASSERT(mRefCount!=0);
}
virtual ~RefCountable() {}
/**
Calls 'delete this;'. It needs to be overloaded for classes also deriving from
PxBase and call 'Cm::deletePxBase(this);' instead.
*/
virtual void onRefCountZero()
{
PX_DELETE_THIS;
}
void incRefCount()
{
physx::PxAtomicIncrement(&mRefCount);
// value better be greater than 1, or we've created a ref to an undefined object
PX_ASSERT(mRefCount>1);
}
void decRefCount()
{
PX_ASSERT(mRefCount>0);
if(physx::PxAtomicDecrement(&mRefCount) == 0)
onRefCountZero();
}
PX_FORCE_INLINE PxU32 getRefCount() const
{
return PxU32(mRefCount);
}
private:
volatile PxI32 mRefCount;
};
} // namespace Cm
}
#endif
| 4,651 |
C
| 32.710145 | 141 | 0.734896 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmVisualization.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_VISUALIZATION_H
#define CM_VISUALIZATION_H
#include "foundation/PxTransform.h"
#include "common/PxRenderOutput.h"
#include "PxConstraintDesc.h"
namespace physx
{
namespace Cm
{
// PT: the force-inlined functions in PxRenderOutput generate a lot of code. Use these non-inlined functions instead.
PX_PHYSX_COMMON_API void renderOutputDebugBox(PxRenderOutput& out, const PxBounds3& box);
PX_PHYSX_COMMON_API void renderOutputDebugCircle(PxRenderOutput& out, PxU32 s, PxReal r);
PX_PHYSX_COMMON_API void renderOutputDebugBasis(PxRenderOutput& out, const PxDebugBasis& basis);
PX_PHYSX_COMMON_API void renderOutputDebugArrow(PxRenderOutput& out, const PxDebugArrow& arrow);
PX_PHYSX_COMMON_API void visualizeJointFrames(PxRenderOutput& out,
PxReal scale,
const PxTransform& parent,
const PxTransform& child);
PX_PHYSX_COMMON_API void visualizeLinearLimit(PxRenderOutput& out,
PxReal scale,
const PxTransform& t0,
const PxTransform& t1,
PxReal value);
PX_PHYSX_COMMON_API void visualizeAngularLimit(PxRenderOutput& out,
PxReal scale,
const PxTransform& t0,
PxReal lower,
PxReal upper);
PX_PHYSX_COMMON_API void visualizeLimitCone(PxRenderOutput& out,
PxReal scale,
const PxTransform& t,
PxReal ySwing,
PxReal zSwing);
PX_PHYSX_COMMON_API void visualizeDoubleCone(PxRenderOutput& out,
PxReal scale,
const PxTransform& t,
PxReal angle);
struct ConstraintImmediateVisualizer : public PxConstraintVisualizer
{
PxF32 mFrameScale;
PxF32 mLimitScale;
PxRenderOutput& mCmOutput;
//Not possible to implement
ConstraintImmediateVisualizer& operator=( const ConstraintImmediateVisualizer& );
ConstraintImmediateVisualizer(PxF32 frameScale, PxF32 limitScale, PxRenderOutput& output) :
mFrameScale (frameScale),
mLimitScale (limitScale),
mCmOutput (output)
{
}
virtual void visualizeJointFrames(const PxTransform& parent, const PxTransform& child) PX_OVERRIDE
{
Cm::visualizeJointFrames(mCmOutput, mFrameScale, parent, child);
}
virtual void visualizeLinearLimit(const PxTransform& t0, const PxTransform& t1, PxReal value) PX_OVERRIDE
{
Cm::visualizeLinearLimit(mCmOutput, mLimitScale, t0, t1, value);
}
virtual void visualizeAngularLimit(const PxTransform& t0, PxReal lower, PxReal upper) PX_OVERRIDE
{
Cm::visualizeAngularLimit(mCmOutput, mLimitScale, t0, lower, upper);
}
virtual void visualizeLimitCone(const PxTransform& t, PxReal tanQSwingY, PxReal tanQSwingZ) PX_OVERRIDE
{
Cm::visualizeLimitCone(mCmOutput, mLimitScale, t, tanQSwingY, tanQSwingZ);
}
virtual void visualizeDoubleCone(const PxTransform& t, PxReal angle) PX_OVERRIDE
{
Cm::visualizeDoubleCone(mCmOutput, mLimitScale, t, angle);
}
virtual void visualizeLine( const PxVec3& p0, const PxVec3& p1, PxU32 color) PX_OVERRIDE
{
mCmOutput << color;
mCmOutput.outputSegment(p0, p1);
}
};
}
}
#endif
| 4,725 |
C
| 36.507936 | 118 | 0.74709 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmPtrTable.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_PTR_TABLE_H
#define CM_PTR_TABLE_H
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
class PxSerializationContext;
class PxDeserializationContext;
namespace Cm
{
class PtrTableStorageManager
{
// This will typically be backed by a MultiPool implementation with fallback to the user
// allocator. For MultiPool, when deallocating we want to know what the previously requested size was
// so we can release into the right pool
public:
virtual void** allocate(PxU32 capacity) = 0;
virtual void deallocate(void** addr, PxU32 originalCapacity) = 0;
// whether memory allocated at one capacity can (and should) be safely reused at a different capacity
// allows realloc-style reuse by clients.
virtual bool canReuse(PxU32 originalCapacity, PxU32 newCapacity) = 0;
protected:
virtual ~PtrTableStorageManager() {}
};
// specialized class to hold an array of pointers with extrinsic storage management,
// serialization-compatible with 3.3.1 PtrTable
//
// note that extrinsic storage implies you *must* clear the table before the destructor runs
//
// capacity is implicit:
// if the memory is not owned (i.e. came from deserialization) then the capacity is exactly mCount
// else if mCount==0, capacity is 0
// else the capacity is the power of 2 >= mCount
//
// one implication of this is that if we want to add or remove a pointer from unowned memory, we always realloc
struct PX_PHYSX_COMMON_API PtrTable
{
PtrTable();
~PtrTable();
void add(void* ptr, PtrTableStorageManager& sm);
void replaceWithLast(PxU32 index, PtrTableStorageManager& sm);
void clear(PtrTableStorageManager& sm);
PxU32 find(const void* ptr) const;
PX_FORCE_INLINE PxU32 getCount() const { return mCount; }
PX_FORCE_INLINE void*const* getPtrs() const { return mCount == 1 ? &mSingle : mList; }
PX_FORCE_INLINE void** getPtrs() { return mCount == 1 ? &mSingle : mList; }
// SERIALIZATION
// 3.3.1 compatibility fixup: this implementation ALWAYS sets 'ownsMemory' if the size is 0 or 1
PtrTable(const PxEMPTY)
{
mOwnsMemory = mCount<2;
if(mCount == 0)
mList = NULL;
}
void exportExtraData(PxSerializationContext& stream);
void importExtraData(PxDeserializationContext& context);
static void getBinaryMetaData(physx::PxOutputStream& stream);
private:
void realloc(PxU32 oldCapacity, PxU32 newCapacity, PtrTableStorageManager& sm);
union
{
void* mSingle;
void** mList;
};
PxU16 mCount;
bool mOwnsMemory;
bool mBufferUsed; // dark magic in serialization requires this, otherwise redundant because it's logically equivalent to mCount == 1.
public:
PxU32 mFreeSlot; // PT: padding bytes on x64
};
} // namespace Cm
}
#endif
| 4,383 |
C
| 34.934426 | 134 | 0.753822 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmSpatialVector.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_SPATIAL_VECTOR_H
#define CM_SPATIAL_VECTOR_H
#include "foundation/PxVec3.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxTransform.h"
/*!
Combination of two R3 vectors.
*/
namespace physx
{
namespace Cm
{
PX_ALIGN_PREFIX(16)
class SpatialVector
{
public:
//! Default constructor
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVector()
{}
//! Construct from two PxcVectors
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVector(const PxVec3& lin, const PxVec3& ang)
: linear(lin), pad0(0.0f), angular(ang), pad1(0.0f)
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE ~SpatialVector()
{}
// PT: this one is very important. Without it, the Xbox compiler generates weird "float-to-int" and "int-to-float" LHS
// each time we copy a SpatialVector (see for example PIX on "solveSimpleGroupA" without this operator).
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator = (const SpatialVector& v)
{
linear = v.linear;
pad0 = 0.0f;
angular = v.angular;
pad1 = 0.0f;
}
static PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVector zero() { return SpatialVector(PxVec3(0),PxVec3(0)); }
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVector operator+(const SpatialVector& v) const
{
return SpatialVector(linear+v.linear,angular+v.angular);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVector operator-(const SpatialVector& v) const
{
return SpatialVector(linear-v.linear,angular-v.angular);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVector operator-() const
{
return SpatialVector(-linear,-angular);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVector operator *(PxReal s) const
{
return SpatialVector(linear*s,angular*s);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator+=(const SpatialVector& v)
{
linear+=v.linear;
angular+=v.angular;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator-=(const SpatialVector& v)
{
linear-=v.linear;
angular-=v.angular;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal magnitude() const
{
return angular.magnitude() + linear.magnitude();
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal dot(const SpatialVector& v) const
{
return linear.dot(v.linear) + angular.dot(v.angular);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite() const
{
return linear.isFinite() && angular.isFinite();
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVector scale(PxReal l, PxReal a) const
{
return Cm::SpatialVector(linear*l, angular*a);
}
PxVec3 linear;
PxReal pad0;
PxVec3 angular;
PxReal pad1;
}
PX_ALIGN_SUFFIX(16);
PX_ALIGN_PREFIX(16)
struct SpatialVectorF
{
public:
//! Default constructor
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF()
{}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF(const PxReal* v)
: pad0(0.0f), pad1(0.0f)
{
top.x = v[0]; top.y = v[1]; top.z = v[2];
bottom.x = v[3]; bottom.y = v[4]; bottom.z = v[5];
}
//! Construct from two PxcVectors
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF(const PxVec3& top_, const PxVec3& bottom_)
: top(top_), pad0(0.0f), bottom(bottom_), pad1(0.0f)
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE ~SpatialVectorF()
{}
// PT: this one is very important. Without it, the Xbox compiler generates weird "float-to-int" and "int-to-float" LHS
// each time we copy a SpatialVector (see for example PIX on "solveSimpleGroupA" without this operator).
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator = (const SpatialVectorF& v)
{
top = v.top;
pad0 = 0.0f;
bottom = v.bottom;
pad1 = 0.0f;
}
static PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF Zero() { return SpatialVectorF(PxVec3(0), PxVec3(0)); }
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF operator+(const SpatialVectorF& v) const
{
return SpatialVectorF(top + v.top, bottom + v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF operator-(const SpatialVectorF& v) const
{
return SpatialVectorF(top - v.top, bottom - v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF operator-() const
{
return SpatialVectorF(-top, -bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF operator *(PxReal s) const
{
return SpatialVectorF(top*s, bottom*s);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF multiply(const SpatialVectorF& v) const
{
return SpatialVectorF(top.multiply(v.top), bottom.multiply(v.bottom));
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator *= (const PxReal s)
{
top *= s;
bottom *= s;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator += (const SpatialVectorF& v)
{
top += v.top;
bottom += v.bottom;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator -= (const SpatialVectorF& v)
{
top -= v.top;
bottom -= v.bottom;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal magnitude() const
{
return top.magnitude() + bottom.magnitude();
}
PX_FORCE_INLINE PxReal magnitudeSquared() const
{
return top.magnitudeSquared() + bottom.magnitudeSquared();
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal innerProduct(const SpatialVectorF& v) const
{
return bottom.dot(v.top) + top.dot(v.bottom);
/*PxVec3 p0 = bottom.multiply(v.top);
PxVec3 p1 = top.multiply(v.bottom);
PxReal result = (((p1.y + p1.z) + (p0.z + p1.x)) + (p0.x + p0.y));
return result;*/
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal dot(const SpatialVectorF& v) const
{
return top.dot(v.top) + bottom.dot(v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal dot(const SpatialVector& v) const
{
return bottom.dot(v.angular) + top.dot(v.linear);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF cross(const SpatialVectorF& v) const
{
SpatialVectorF a;
a.top = top.cross(v.top);
a.bottom = top.cross(v.bottom) + bottom.cross(v.top);
return a;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF abs() const
{
return SpatialVectorF(top.abs(), bottom.abs());
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF rotate(const PxTransform& rot) const
{
return SpatialVectorF(rot.rotate(top), rot.rotate(bottom));
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialVectorF rotateInv(const PxTransform& rot) const
{
return SpatialVectorF(rot.rotateInv(top), rot.rotateInv(bottom));
}
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite() const
{
return top.isFinite() && bottom.isFinite();
}
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isValid(const PxReal maxV) const
{
const bool tValid = ((PxAbs(top.x) <= maxV) && (PxAbs(top.y) <= maxV) && (PxAbs(top.z) <= maxV));
const bool bValid = ((PxAbs(bottom.x) <= maxV) && (PxAbs(bottom.y) <= maxV) && (PxAbs(bottom.z) <= maxV));
return tValid && bValid;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF scale(PxReal l, PxReal a) const
{
return Cm::SpatialVectorF(top*l, bottom*a);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void assignTo(PxReal* val) const
{
val[0] = top.x; val[1] = top.y; val[2] = top.z;
val[3] = bottom.x; val[4] = bottom.y; val[5] = bottom.z;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal& operator [] (const PxU32 index)
{
PX_ASSERT(index < 6);
if(index < 3)
return top[index];
return bottom[index-3];
}
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxReal& operator [] (const PxU32 index) const
{
PX_ASSERT(index < 6);
if (index < 3)
return top[index];
return bottom[index-3];
}
PxVec3 top;
PxReal pad0;
PxVec3 bottom;
PxReal pad1;
} PX_ALIGN_SUFFIX(16);
struct UnAlignedSpatialVector
{
public:
//! Default constructor
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector()
{}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector(const PxReal* v)
{
top.x = v[0]; top.y = v[1]; top.z = v[2];
bottom.x = v[3]; bottom.y = v[4]; bottom.z = v[5];
}
//! Construct from two PxcVectors
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector(const PxVec3& top_, const PxVec3& bottom_)
: top(top_), bottom(bottom_)
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE ~UnAlignedSpatialVector()
{}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator = (const SpatialVectorF& v)
{
top = v.top;
bottom = v.bottom;
}
static PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector Zero() { return UnAlignedSpatialVector(PxVec3(0), PxVec3(0)); }
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector operator+(const UnAlignedSpatialVector& v) const
{
return UnAlignedSpatialVector(top + v.top, bottom + v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector operator-(const UnAlignedSpatialVector& v) const
{
return UnAlignedSpatialVector(top - v.top, bottom - v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector operator-() const
{
return UnAlignedSpatialVector(-top, -bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector operator *(PxReal s) const
{
return UnAlignedSpatialVector(top*s, bottom*s);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator *= (const PxReal s)
{
top *= s;
bottom *= s;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator += (const UnAlignedSpatialVector& v)
{
top += v.top;
bottom += v.bottom;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator += (const SpatialVectorF& v)
{
top += v.top;
bottom += v.bottom;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator -= (const UnAlignedSpatialVector& v)
{
top -= v.top;
bottom -= v.bottom;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator -= (const SpatialVectorF& v)
{
top -= v.top;
bottom -= v.bottom;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal magnitude() const
{
return top.magnitude() + bottom.magnitude();
}
PX_FORCE_INLINE PxReal magnitudeSquared() const
{
return top.magnitudeSquared() + bottom.magnitudeSquared();
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal innerProduct(const UnAlignedSpatialVector& v) const
{
return bottom.dot(v.top) + top.dot(v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal innerProduct(const SpatialVectorF& v) const
{
return bottom.dot(v.top) + top.dot(v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal dot(const UnAlignedSpatialVector& v) const
{
return top.dot(v.top) + bottom.dot(v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal dot(const SpatialVectorF& v) const
{
return top.dot(v.top) + bottom.dot(v.bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector cross(const UnAlignedSpatialVector& v) const
{
UnAlignedSpatialVector a;
a.top = top.cross(v.top);
a.bottom = top.cross(v.bottom) + bottom.cross(v.top);
return a;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector abs() const
{
return UnAlignedSpatialVector(top.abs(), bottom.abs());
}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector rotate(const PxTransform& rot) const
{
return UnAlignedSpatialVector(rot.rotate(top), rot.rotate(bottom));
}
PX_CUDA_CALLABLE PX_FORCE_INLINE UnAlignedSpatialVector rotateInv(const PxTransform& rot) const
{
return UnAlignedSpatialVector(rot.rotateInv(top), rot.rotateInv(bottom));
}
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite() const
{
return top.isFinite() && bottom.isFinite();
}
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isValid(const PxReal maxV) const
{
const bool tValid = ((top.x <= maxV) && (top.y <= maxV) && (top.z <= maxV));
const bool bValid = ((bottom.x <= maxV) && (bottom.y <= maxV) && (bottom.z <= maxV));
return tValid && bValid;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::UnAlignedSpatialVector scale(PxReal l, PxReal a) const
{
return Cm::UnAlignedSpatialVector(top*l, bottom*a);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void assignTo(PxReal* val) const
{
val[0] = top.x; val[1] = top.y; val[2] = top.z;
val[3] = bottom.x; val[4] = bottom.y; val[5] = bottom.z;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal& operator [] (const PxU32 index)
{
PX_ASSERT(index < 6);
return (&top.x)[index];
}
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxReal& operator [] (const PxU32 index) const
{
PX_ASSERT(index < 6);
return (&top.x)[index];
}
PxVec3 top; //12 12
PxVec3 bottom; //12 24
};
PX_ALIGN_PREFIX(16)
struct SpatialVectorV
{
aos::Vec3V linear;
aos::Vec3V angular;
PX_FORCE_INLINE SpatialVectorV() {}
PX_FORCE_INLINE SpatialVectorV(PxZERO): linear(aos::V3Zero()), angular(aos::V3Zero()) {}
PX_FORCE_INLINE SpatialVectorV(const Cm::SpatialVector& v): linear(aos::V3LoadA(&v.linear.x)), angular(aos::V3LoadA(&v.angular.x)) {}
PX_FORCE_INLINE SpatialVectorV(const aos::Vec3VArg l, const aos::Vec3VArg a): linear(l), angular(a) {}
PX_FORCE_INLINE SpatialVectorV(const SpatialVectorV& other): linear(other.linear), angular(other.angular) {}
PX_FORCE_INLINE SpatialVectorV& operator=(const SpatialVectorV& other) { linear = other.linear; angular = other.angular; return *this; }
PX_FORCE_INLINE SpatialVectorV operator+(const SpatialVectorV& other) const { return SpatialVectorV(aos::V3Add(linear,other.linear),
aos::V3Add(angular, other.angular)); }
PX_FORCE_INLINE SpatialVectorV& operator+=(const SpatialVectorV& other) { linear = aos::V3Add(linear,other.linear);
angular = aos::V3Add(angular, other.angular);
return *this;
}
PX_FORCE_INLINE SpatialVectorV operator-(const SpatialVectorV& other) const { return SpatialVectorV(aos::V3Sub(linear,other.linear),
aos::V3Sub(angular, other.angular)); }
PX_FORCE_INLINE SpatialVectorV operator-() const { return SpatialVectorV(aos::V3Neg(linear), aos::V3Neg(angular)); }
PX_FORCE_INLINE SpatialVectorV operator*(const aos::FloatVArg r) const { return SpatialVectorV(aos::V3Scale(linear,r), aos::V3Scale(angular,r)); }
PX_FORCE_INLINE SpatialVectorV& operator-=(const SpatialVectorV& other) { linear = aos::V3Sub(linear,other.linear);
angular = aos::V3Sub(angular, other.angular);
return *this;
}
PX_FORCE_INLINE aos::FloatV dot(const SpatialVectorV& other) const { return aos::V3SumElems(aos::V3Add(aos::V3Mul(linear, other.linear), aos::V3Mul(angular, other.angular))); }
PX_FORCE_INLINE SpatialVectorV multiply(const SpatialVectorV& other) const { return SpatialVectorV(aos::V3Mul(linear, other.linear), aos::V3Mul(angular, other.angular)); }
PX_FORCE_INLINE SpatialVectorV multiplyAdd(const SpatialVectorV& m, const SpatialVectorV& a) const { return SpatialVectorV(aos::V3MulAdd(linear, m.linear, a.linear), aos::V3MulAdd(angular, m.angular, a.angular)); }
PX_FORCE_INLINE SpatialVectorV scale(const aos::FloatV& a, const aos::FloatV& b) const { return SpatialVectorV(aos::V3Scale(linear, a), aos::V3Scale(angular, b)); }
}PX_ALIGN_SUFFIX(16);
} // namespace Cm
PX_COMPILE_TIME_ASSERT(sizeof(Cm::SpatialVector) == 32);
PX_COMPILE_TIME_ASSERT(sizeof(Cm::SpatialVectorV) == 32);
}
#endif
| 16,307 |
C
| 29.596623 | 215 | 0.708223 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmPreallocatingPool.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_PREALLOCATING_POOL_H
#define CM_PREALLOCATING_POOL_H
#include "foundation/Px.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxSort.h"
#include "foundation/PxArray.h"
namespace physx
{
namespace Cm
{
class PreallocatingRegion
{
public:
PX_FORCE_INLINE PreallocatingRegion() : mMemory(NULL), mFirstFree(NULL), mNbElements(0) {}
void init(PxU32 maxElements, PxU32 elementSize, const char* typeName)
{
mFirstFree = NULL;
mNbElements = 0;
PX_ASSERT(typeName);
PX_UNUSED(typeName);
mMemory = reinterpret_cast<PxU8*>(PX_ALLOC(sizeof(PxU8)*elementSize*maxElements, typeName?typeName:"SceneSim Pool")); // ### addActor alloc
PX_ASSERT(elementSize*maxElements>=sizeof(void*));
}
void reset()
{
PX_FREE(mMemory);
}
PX_FORCE_INLINE PxU8* allocateMemory(PxU32 maxElements, PxU32 elementSize)
{
if(mFirstFree)
{
PxU8* recycled = reinterpret_cast<PxU8*>(mFirstFree);
void** recycled32 = reinterpret_cast<void**>(recycled);
mFirstFree = *recycled32;
return recycled;
}
else
{
if(mNbElements==maxElements)
return NULL; // Out of memory
const PxU32 freeIndex = mNbElements++;
return mMemory + freeIndex * elementSize;
}
}
void deallocateMemory(PxU32 maxElements, PxU32 elementSize, PxU8* element)
{
PX_ASSERT(element);
PX_ASSERT(element>=mMemory && element<mMemory + maxElements * elementSize);
PX_UNUSED(elementSize);
PX_UNUSED(maxElements);
void** recycled32 = reinterpret_cast<void**>(element);
*recycled32 = mFirstFree;
mFirstFree = element;
}
PX_FORCE_INLINE bool operator < (const PreallocatingRegion& p) const
{
return mMemory < p.mMemory;
}
PX_FORCE_INLINE bool operator > (const PreallocatingRegion& p) const
{
return mMemory > p.mMemory;
}
PxU8* mMemory;
void* mFirstFree;
PxU32 mNbElements;
};
class PreallocatingRegionManager
{
public:
PreallocatingRegionManager(PxU32 maxElements, PxU32 elementSize, const char* typeName)
: mMaxElements (maxElements)
, mElementSize (elementSize)
, mActivePoolIndex (0)
, mPools ("MyPoolManagerPools")
, mNeedsSorting (true)
, mTypeName (typeName)
{
PreallocatingRegion tmp;
tmp.init(maxElements, elementSize, mTypeName);
mPools.pushBack(tmp);
}
~PreallocatingRegionManager()
{
const PxU32 nbPools = mPools.size();
for(PxU32 i=0;i<nbPools;i++)
mPools[i].reset();
}
void preAllocate(PxU32 n)
{
if(!n)
return;
const PxU32 nbPools = mPools.size();
const PxU32 maxElements = mMaxElements;
const PxU32 elementSize = mElementSize;
PxU32 availableSpace = nbPools * maxElements;
while(n>availableSpace)
{
PreallocatingRegion tmp;
tmp.init(maxElements, elementSize, mTypeName);
mPools.pushBack(tmp);
availableSpace += maxElements;
}
}
PX_FORCE_INLINE PxU8* allocateMemory()
{
PX_ASSERT(mActivePoolIndex<mPools.size());
PxU8* memory = mPools[mActivePoolIndex].allocateMemory(mMaxElements, mElementSize);
return memory ? memory : searchForMemory();
}
void deallocateMemory(PxU8* element)
{
if(!element)
return;
if(mNeedsSorting)
PxSort(mPools.begin(), mPools.size());
const PxU32 maxElements = mMaxElements;
const PxU32 elementSize = mElementSize;
const PxU32 slabSize = maxElements * elementSize;
const PxU32 nbPools = mPools.size();
// O(log n) search
int first = 0;
int last = int(nbPools-1);
while(first<=last)
{
const int mid = (first+last)>>1;
PreallocatingRegion& candidate = mPools[PxU32(mid)];
if(contains(candidate.mMemory, slabSize, element))
{
candidate.deallocateMemory(maxElements, elementSize, element);
// when we sorted earlier we trashed the active index, but at least this region has a free element
if(mNeedsSorting)
mActivePoolIndex = PxU32(mid);
mNeedsSorting = false;
return;
}
if(candidate.mMemory<element)
first = mid+1;
else
last = mid-1;
}
PX_ASSERT(0);
}
private:
PreallocatingRegionManager& operator=(const PreallocatingRegionManager&);
PxU8* searchForMemory()
{
const PxU32 nbPools = mPools.size();
const PxU32 activePoolIndex = mActivePoolIndex;
const PxU32 maxElements = mMaxElements;
const PxU32 elementSize = mElementSize;
for(PxU32 i=0;i<nbPools;i++)
{
if(i==activePoolIndex)
continue;
PxU8* memory = mPools[i].allocateMemory(maxElements, elementSize);
if(memory)
{
mActivePoolIndex = i;
return memory;
}
}
mActivePoolIndex = nbPools;
mNeedsSorting = true;
PreallocatingRegion tmp;
tmp.init(maxElements, elementSize, mTypeName);
PreallocatingRegion& newPool = mPools.pushBack(tmp); // ### addActor alloc (StaticSim, ShapeSim, SceneQueryShapeData)
return newPool.allocateMemory(maxElements, elementSize);
}
PX_FORCE_INLINE bool contains(PxU8* memory, const PxU32 slabSize, PxU8* element)
{
return element>=memory && element<memory+slabSize;
}
const PxU32 mMaxElements;
const PxU32 mElementSize;
PxU32 mActivePoolIndex;
PxArray<PreallocatingRegion> mPools;
bool mNeedsSorting;
const char* mTypeName;
};
template<class T>
class PreallocatingPool : public PxUserAllocated
{
PreallocatingPool<T>& operator=(const PreallocatingPool<T>&);
public:
PreallocatingPool(PxU32 maxElements, const char* typeName) : mPool(maxElements, sizeof(T), typeName)
{
}
~PreallocatingPool()
{
}
PX_FORCE_INLINE void preAllocate(PxU32 n)
{
mPool.preAllocate(n);
}
PX_INLINE T* allocate()
{
return reinterpret_cast<T*>(mPool.allocateMemory());
}
PX_FORCE_INLINE T* allocateAndPrefetch()
{
T* t = reinterpret_cast<T*>(mPool.allocateMemory());
PxPrefetch(t, sizeof(T));
return t;
}
PX_INLINE T* construct()
{
T* t = reinterpret_cast<T*>(mPool.allocateMemory());
return t ? PX_PLACEMENT_NEW(t, T()) : NULL;
}
template<class A1>
PX_INLINE T* construct(A1& a)
{
T* t = reinterpret_cast<T*>(mPool.allocateMemory());
return t ? PX_PLACEMENT_NEW(t, T(a)) : NULL;
}
template<class A1, class A2>
PX_INLINE T* construct(A1& a, A2& b)
{
T* t = reinterpret_cast<T*>(mPool.allocateMemory());
return t ? PX_PLACEMENT_NEW(t, T(a,b)) : NULL;
}
template<class A1, class A2, class A3>
PX_INLINE T* construct(A1& a, A2& b, A3& c)
{
T* t = reinterpret_cast<T*>(mPool.allocateMemory());
return t ? PX_PLACEMENT_NEW(t, T(a,b,c)) : NULL;
}
template<class A1, class A2, class A3, class A4>
PX_INLINE T* construct(A1& a, A2& b, A3& c, A4& d)
{
T* t = reinterpret_cast<T*>(mPool.allocateMemory());
return t ? PX_PLACEMENT_NEW(t, T(a,b,c,d)) : NULL;
}
template<class A1, class A2, class A3, class A4, class A5>
PX_INLINE T* construct(A1& a, A2& b, A3& c, A4& d, A5& e)
{
T* t = reinterpret_cast<T*>(mPool.allocateMemory());
return t ? PX_PLACEMENT_NEW(t, T(a,b,c,d,e)) : NULL;
}
////
PX_INLINE T* construct(T* t)
{
PX_ASSERT(t);
return PX_PLACEMENT_NEW(t, T());
}
template<class A1>
PX_INLINE T* construct(T* t, A1& a)
{
PX_ASSERT(t);
return PX_PLACEMENT_NEW(t, T(a));
}
template<class A1, class A2>
PX_INLINE T* construct(T* t, A1& a, A2& b)
{
PX_ASSERT(t);
return PX_PLACEMENT_NEW(t, T(a,b));
}
template<class A1, class A2, class A3>
PX_INLINE T* construct(T* t, A1& a, A2& b, A3& c)
{
PX_ASSERT(t);
return PX_PLACEMENT_NEW(t, T(a,b,c));
}
template<class A1, class A2, class A3, class A4>
PX_INLINE T* construct(T* t, A1& a, A2& b, A3& c, A4& d)
{
PX_ASSERT(t);
return PX_PLACEMENT_NEW(t, T(a,b,c,d));
}
template<class A1, class A2, class A3, class A4, class A5>
PX_INLINE T* construct(T* t, A1& a, A2& b, A3& c, A4& d, A5& e)
{
PX_ASSERT(t);
return PX_PLACEMENT_NEW(t, T(a,b,c,d,e));
}
PX_INLINE void destroy(T* const p)
{
if(p)
{
p->~T();
mPool.deallocateMemory(reinterpret_cast<PxU8*>(p));
}
}
PX_INLINE void releasePreallocated(T* const p)
{
if(p)
mPool.deallocateMemory(reinterpret_cast<PxU8*>(p));
}
protected:
PreallocatingRegionManager mPool;
};
template<class T>
class BufferedPreallocatingPool : public PreallocatingPool<T>
{
PxArray<T*> mDeletedElems;
PX_NOCOPY(BufferedPreallocatingPool<T>)
public:
BufferedPreallocatingPool(PxU32 maxElements, const char* typeName) : PreallocatingPool<T>(maxElements, typeName)
{
}
PX_INLINE void destroy(T* const p)
{
if (p)
{
p->~T();
mDeletedElems.pushBack(p);
}
}
void processPendingDeletedElems()
{
for (PxU32 i = 0; i < mDeletedElems.size(); ++i)
this->mPool.deallocateMemory(reinterpret_cast<PxU8*>(mDeletedElems[i]));
mDeletedElems.clear();
}
};
} // namespace Cm
}
#endif
| 10,358 |
C
| 23.146853 | 141 | 0.691253 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmScaling.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_SCALING_H
#define CM_SCALING_H
#include "foundation/PxBounds3.h"
#include "foundation/PxMat33.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxMat34.h"
#include "foundation/PxSIMDHelpers.h"
#include "geometry/PxMeshScale.h"
#include "CmUtils.h"
namespace physx
{
namespace Cm
{
// PT: same as PxMeshScale::toMat33() but faster
PX_FORCE_INLINE PxMat33 toMat33(const PxMeshScale& meshScale)
{
const PxMat33Padded rot(meshScale.rotation);
PxMat33 trans = rot.getTranspose();
trans.column0 *= meshScale.scale[0];
trans.column1 *= meshScale.scale[1];
trans.column2 *= meshScale.scale[2];
return trans * rot;
}
// class that can perform scaling fast. Relatively large size, generated from PxMeshScale on demand.
// CS: I've removed most usages of this class, because most of the time only one-way transform is needed.
// If you only need a temporary FastVertex2ShapeScaling, setup your transform as PxMat34Legacy and use
// normal matrix multiplication or a transform() overload to convert points and bounds between spaces.
class FastVertex2ShapeScaling
{
public:
PX_INLINE FastVertex2ShapeScaling()
{
//no scaling by default:
vertex2ShapeSkew = PxMat33(PxIdentity);
shape2VertexSkew = PxMat33(PxIdentity);
mFlipNormal = false;
}
PX_INLINE explicit FastVertex2ShapeScaling(const PxMeshScale& scale)
{
init(scale);
}
PX_INLINE FastVertex2ShapeScaling(const PxVec3& scale, const PxQuat& rotation)
{
init(scale, rotation);
}
PX_INLINE void init(const PxMeshScale& scale)
{
init(scale.scale, scale.rotation);
}
PX_INLINE void setIdentity()
{
vertex2ShapeSkew = PxMat33(PxIdentity);
shape2VertexSkew = PxMat33(PxIdentity);
mFlipNormal = false;
}
PX_INLINE void init(const PxVec3& scale, const PxQuat& rotation)
{
// TODO: may want to optimize this for cases where we have uniform or axis aligned scaling!
// That would introduce branches and it's unclear to me whether that's faster than just doing the math.
// Lazy computation would be another option, at the cost of introducing even more branches.
const PxMat33Padded R(rotation);
vertex2ShapeSkew = R.getTranspose();
const PxMat33 diagonal = PxMat33::createDiagonal(scale);
vertex2ShapeSkew = vertex2ShapeSkew * diagonal;
vertex2ShapeSkew = vertex2ShapeSkew * R;
/*
The inverse, is, explicitly:
shape2VertexSkew.setTransposed(R);
shape2VertexSkew.multiplyDiagonal(PxVec3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z));
shape2VertexSkew *= R;
It may be competitive to compute the inverse -- though this has a branch in it:
*/
shape2VertexSkew = vertex2ShapeSkew.getInverse();
mFlipNormal = ((scale.x * scale.y * scale.z) < 0.0f);
}
PX_FORCE_INLINE void flipNormal(PxVec3& v1, PxVec3& v2) const
{
if (mFlipNormal)
{
PxVec3 tmp = v1; v1 = v2; v2 = tmp;
}
}
PX_FORCE_INLINE PxVec3 operator* (const PxVec3& src) const
{
return vertex2ShapeSkew * src;
}
PX_FORCE_INLINE PxVec3 operator% (const PxVec3& src) const
{
return shape2VertexSkew * src;
}
PX_FORCE_INLINE const PxMat33& getVertex2ShapeSkew() const
{
return vertex2ShapeSkew;
}
PX_FORCE_INLINE const PxMat33& getShape2VertexSkew() const
{
return shape2VertexSkew;
}
PX_INLINE PxMat34 getVertex2WorldSkew(const PxMat34& shape2world) const
{
const PxMat34 vertex2worldSkew = shape2world * getVertex2ShapeSkew();
//vertex2worldSkew = shape2world * [vertex2shapeSkew, 0]
//[aR at] * [bR bt] = [aR * bR aR * bt + at] NOTE: order of operations important so it works when this ?= left ?= right.
return vertex2worldSkew;
}
PX_INLINE PxMat34 getWorld2VertexSkew(const PxMat34& shape2world) const
{
//world2vertexSkew = shape2vertex * invPQ(shape2world)
//[aR 0] * [bR' -bR'*bt] = [aR * bR' -aR * bR' * bt + 0]
const PxMat33 rotate( shape2world[0], shape2world[1], shape2world[2] );
const PxMat33 M = getShape2VertexSkew() * rotate.getTranspose();
return PxMat34(M[0], M[1], M[2], -M * shape2world[3]);
}
//! Transforms a shape space OBB to a vertex space OBB. All 3 params are in and out.
void transformQueryBounds(PxVec3& center, PxVec3& extents, PxMat33& basis) const
{
basis.column0 = shape2VertexSkew * (basis.column0 * extents.x);
basis.column1 = shape2VertexSkew * (basis.column1 * extents.y);
basis.column2 = shape2VertexSkew * (basis.column2 * extents.z);
center = shape2VertexSkew * center;
extents = PxOptimizeBoundingBox(basis);
}
void transformPlaneToShapeSpace(const PxVec3& nIn, const PxReal dIn, PxVec3& nOut, PxReal& dOut) const
{
const PxVec3 tmp = shape2VertexSkew.transformTranspose(nIn);
const PxReal denom = 1.0f / tmp.magnitude();
nOut = tmp * denom;
dOut = dIn * denom;
}
PX_FORCE_INLINE bool flipsNormal() const { return mFlipNormal; }
private:
PxMat33 vertex2ShapeSkew;
PxMat33 shape2VertexSkew;
bool mFlipNormal;
};
PX_FORCE_INLINE void getScaledVertices(PxVec3* v, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, bool idtMeshScale, const Cm::FastVertex2ShapeScaling& scaling)
{
if(idtMeshScale)
{
v[0] = v0;
v[1] = v1;
v[2] = v2;
}
else
{
const PxI32 winding = scaling.flipsNormal() ? 1 : 0;
v[0] = scaling * v0;
v[1+winding] = scaling * v1;
v[2-winding] = scaling * v2;
}
}
} // namespace Cm
PX_INLINE PxMat34 operator*(const PxTransform& transform, const PxMeshScale& scale)
{
const PxMat33Padded tmp(transform.q);
return PxMat34(tmp * Cm::toMat33(scale), transform.p);
}
PX_INLINE PxMat34 operator*(const PxMeshScale& scale, const PxTransform& transform)
{
const PxMat33 scaleMat = Cm::toMat33(scale);
const PxMat33Padded t(transform.q);
const PxMat33 r = scaleMat * t;
const PxVec3 p = scaleMat * transform.p;
return PxMat34(r, p);
}
PX_INLINE PxMat34 operator*(const PxMat34& transform, const PxMeshScale& scale)
{
return PxMat34(transform.m * Cm::toMat33(scale), transform.p);
}
PX_INLINE PxMat34 operator*(const PxMeshScale& scale, const PxMat34& transform)
{
const PxMat33 scaleMat = Cm::toMat33(scale);
return PxMat34(scaleMat * transform.m, scaleMat * transform.p);
}
}
#endif
| 7,912 |
C
| 31.698347 | 167 | 0.721436 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmTransformUtils.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_TRANSFORM_UTILS_H
#define CM_TRANSFORM_UTILS_H
#include "foundation/PxVecMath.h"
namespace
{
using namespace physx::aos;
// V3PrepareCross would help here, but it's not on all platforms yet...
PX_FORCE_INLINE void transformFast(const FloatVArg wa, const Vec3VArg va, const Vec3VArg pa,
const FloatVArg wb, const Vec3VArg vb, const Vec3VArg pb,
FloatV& wo, Vec3V& vo, Vec3V& po)
{
wo = FSub(FMul(wa, wb), V3Dot(va, vb));
vo = V3ScaleAdd(va, wb, V3ScaleAdd(vb, wa, V3Cross(va, vb)));
const Vec3V t1 = V3Scale(pb, FScaleAdd(wa, wa, FLoad(-0.5f)));
const Vec3V t2 = V3ScaleAdd(V3Cross(va, pb), wa, t1);
const Vec3V t3 = V3ScaleAdd(va, V3Dot(va, pb), t2);
po = V3ScaleAdd(t3, FLoad(2.f), pa);
}
PX_FORCE_INLINE void transformInvFast(const FloatVArg wa, const Vec3VArg va, const Vec3VArg pa,
const FloatVArg wb, const Vec3VArg vb, const Vec3VArg pb,
FloatV& wo, Vec3V& vo, Vec3V& po)
{
wo = FScaleAdd(wa, wb, V3Dot(va, vb));
vo = V3NegScaleSub(va, wb, V3ScaleAdd(vb, wa, V3Cross(vb, va)));
const Vec3V pt = V3Sub(pb, pa);
const Vec3V t1 = V3Scale(pt, FScaleAdd(wa, wa, FLoad(-0.5f)));
const Vec3V t2 = V3ScaleAdd(V3Cross(pt, va), wa, t1);
const Vec3V t3 = V3ScaleAdd(va, V3Dot(va, pt), t2);
po = V3Add(t3,t3);
}
}
namespace physx
{
namespace Cm
{
// PT: actor2World * shape2Actor
PX_FORCE_INLINE void getStaticGlobalPoseAligned(const PxTransform& actor2World, const PxTransform& shape2Actor, PxTransform& outTransform)
{
using namespace aos;
PX_ASSERT((size_t(&actor2World)&15) == 0);
PX_ASSERT((size_t(&shape2Actor)&15) == 0);
PX_ASSERT((size_t(&outTransform)&15) == 0);
const Vec3V actor2WorldPos = V3LoadA(actor2World.p);
const QuatV actor2WorldRot = QuatVLoadA(&actor2World.q.x);
const Vec3V shape2ActorPos = V3LoadA(shape2Actor.p);
const QuatV shape2ActorRot = QuatVLoadA(&shape2Actor.q.x);
Vec3V v,p;
FloatV w;
transformFast(V4GetW(actor2WorldRot), Vec3V_From_Vec4V(actor2WorldRot), actor2WorldPos,
V4GetW(shape2ActorRot), Vec3V_From_Vec4V(shape2ActorRot), shape2ActorPos,
w, v, p);
V3StoreA(p, outTransform.p);
V4StoreA(V4SetW(v,w), &outTransform.q.x);
}
// PT: body2World * body2Actor.getInverse() * shape2Actor
PX_FORCE_INLINE void getDynamicGlobalPoseAligned(const PxTransform& body2World, const PxTransform& shape2Actor, const PxTransform& body2Actor, PxTransform& outTransform)
{
PX_ASSERT((size_t(&body2World)&15) == 0);
PX_ASSERT((size_t(&shape2Actor)&15) == 0);
PX_ASSERT((size_t(&body2Actor)&15) == 0);
PX_ASSERT((size_t(&outTransform)&15) == 0);
using namespace aos;
const Vec3V shape2ActorPos = V3LoadA(shape2Actor.p);
const QuatV shape2ActorRot = QuatVLoadA(&shape2Actor.q.x);
const Vec3V body2ActorPos = V3LoadA(body2Actor.p);
const QuatV body2ActorRot = QuatVLoadA(&body2Actor.q.x);
const Vec3V body2WorldPos = V3LoadA(body2World.p);
const QuatV body2WorldRot = QuatVLoadA(&body2World.q.x);
Vec3V v1, p1, v2, p2;
FloatV w1, w2;
transformInvFast(V4GetW(body2ActorRot), Vec3V_From_Vec4V(body2ActorRot), body2ActorPos,
V4GetW(shape2ActorRot), Vec3V_From_Vec4V(shape2ActorRot), shape2ActorPos,
w1, v1, p1);
transformFast(V4GetW(body2WorldRot), Vec3V_From_Vec4V(body2WorldRot), body2WorldPos,
w1, v1, p1,
w2, v2, p2);
V3StoreA(p2, outTransform.p);
V4StoreA(V4SetW(v2, w2), &outTransform.q.x);
}
}
}
#endif
| 5,094 |
C
| 35.392857 | 169 | 0.726934 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmPool.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_POOL_H
#define CM_POOL_H
#include "foundation/PxSort.h"
#include "foundation/PxMutex.h"
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxBitMap.h"
namespace physx
{
namespace Cm
{
/*!
Allocator for pools of data structures
Also decodes indices (which can be computed from handles) into objects. To make this
faster, the EltsPerSlab must be a power of two
*/
template <class T, class ArgumentType>
class PoolList : public PxAllocatorTraits<T>::Type
{
typedef typename PxAllocatorTraits<T>::Type Alloc;
PX_NOCOPY(PoolList)
public:
PX_INLINE PoolList(const Alloc& alloc, ArgumentType* argument, PxU32 eltsPerSlab)
: Alloc(alloc),
mEltsPerSlab(eltsPerSlab),
mSlabCount(0),
mFreeList(0),
mFreeCount(0),
mSlabs(NULL),
mArgument(argument)
{
PX_ASSERT(mEltsPerSlab>0);
PX_ASSERT((mEltsPerSlab & (mEltsPerSlab-1)) == 0);
mLog2EltsPerSlab = 0;
for(mLog2EltsPerSlab=0; mEltsPerSlab!=PxU32(1<<mLog2EltsPerSlab); mLog2EltsPerSlab++)
;
}
PX_INLINE ~PoolList()
{
destroy();
}
PX_INLINE void destroy()
{
// Run all destructors
for(PxU32 i=0;i<mSlabCount;i++)
{
PX_ASSERT(mSlabs);
T* slab = mSlabs[i];
for(PxU32 j=0;j<mEltsPerSlab;j++)
{
slab[j].~T();
}
}
//Deallocate
for(PxU32 i=0;i<mSlabCount;i++)
{
Alloc::deallocate(mSlabs[i]);
mSlabs[i] = NULL;
}
mSlabCount = 0;
if(mFreeList)
Alloc::deallocate(mFreeList);
mFreeList = NULL;
if(mSlabs)
{
Alloc::deallocate(mSlabs);
mSlabs = NULL;
}
}
PxU32 preallocate(const PxU32 nbRequired, T** elements)
{
//(1) Allocate and pull out an array of X elements
PxU32 nbToAllocate = nbRequired > mFreeCount ? nbRequired - mFreeCount : 0;
PxU32 nbElements = nbRequired - nbToAllocate;
PxMemCopy(elements, mFreeList + (mFreeCount - nbElements), sizeof(T*) * nbElements);
//PxU32 originalFreeCount = mFreeCount;
mFreeCount -= nbElements;
if (nbToAllocate)
{
PX_ASSERT(mFreeCount == 0);
PxU32 nbSlabs = (nbToAllocate + mEltsPerSlab - 1) / mEltsPerSlab; //The number of slabs we need to allocate...
//allocate our slabs...
PxU32 freeCount = mFreeCount;
for (PxU32 i = 0; i < nbSlabs; ++i)
{
//KS - would be great to allocate this using a single allocation but it will make releasing slabs fail later :(
T * mAddr = reinterpret_cast<T*>(Alloc::allocate(mEltsPerSlab * sizeof(T), PX_FL));
if (!mAddr)
return nbElements; //Allocation failed so only return the set of elements we could allocate from the free list
PxU32 newSlabCount = mSlabCount+1;
// Make sure the usage bitmap is up-to-size
if (mUseBitmap.size() < newSlabCount*mEltsPerSlab)
{
mUseBitmap.resize(2 * newSlabCount*mEltsPerSlab); //set last element as not used
if (mFreeList)
Alloc::deallocate(mFreeList);
mFreeList = reinterpret_cast<T**>(Alloc::allocate(2 * newSlabCount * mEltsPerSlab * sizeof(T*), PX_FL));
T** slabs = reinterpret_cast<T**>(Alloc::allocate(2* newSlabCount *sizeof(T*), PX_FL));
if (mSlabs)
{
PxMemCopy(slabs, mSlabs, sizeof(T*)*mSlabCount);
Alloc::deallocate(mSlabs);
}
mSlabs = slabs;
}
mSlabs[mSlabCount++] = mAddr;
PxU32 baseIndex = (mSlabCount-1) * mEltsPerSlab;
//Now add all these to the mFreeList and elements...
PxI32 idx = PxI32(mEltsPerSlab - 1);
for (; idx >= PxI32(nbToAllocate); --idx)
{
mFreeList[freeCount++] = PX_PLACEMENT_NEW(mAddr + idx, T(mArgument, baseIndex + idx));
}
PxU32 origElements = nbElements;
T** writeIdx = elements + nbElements;
for (; idx >= 0; --idx)
{
writeIdx[idx] = PX_PLACEMENT_NEW(mAddr + idx, T(mArgument, baseIndex + idx));
nbElements++;
}
nbToAllocate -= (nbElements - origElements);
}
mFreeCount = freeCount;
}
PX_ASSERT(nbElements == nbRequired);
for (PxU32 a = 0; a < nbElements; ++a)
{
mUseBitmap.set(elements[a]->getIndex());
}
return nbRequired;
}
// TODO: would be nice to add templated construct/destroy methods like ObjectPool
PX_INLINE T* get()
{
if(mFreeCount == 0 && !extend())
return 0;
T* element = mFreeList[--mFreeCount];
mUseBitmap.set(element->getIndex());
return element;
}
PX_INLINE void put(T* element)
{
PxU32 i = element->getIndex();
mUseBitmap.reset(i);
mFreeList[mFreeCount++] = element;
}
/*
WARNING: Unlike findByIndexFast below, this method is NOT safe to use if another thread
is concurrently updating the pool (e.g. through put/get/extend/getIterator), since the
safety boundedTest uses mSlabCount and mUseBitmap.
*/
PX_FORCE_INLINE T* findByIndex(PxU32 index) const
{
if(index>=mSlabCount*mEltsPerSlab || !(mUseBitmap.boundedTest(index)))
return 0;
return mSlabs[index>>mLog2EltsPerSlab] + (index&(mEltsPerSlab-1));
}
/*
This call is safe to do while other threads update the pool.
*/
PX_FORCE_INLINE T* findByIndexFast(PxU32 index) const
{
return mSlabs[index>>mLog2EltsPerSlab] + (index&(mEltsPerSlab-1));
}
bool extend()
{
T * mAddr = reinterpret_cast<T*>(Alloc::allocate(mEltsPerSlab * sizeof(T), PX_FL));
if(!mAddr)
return false;
PxU32 newSlabCount = mSlabCount+1;
// Make sure the usage bitmap is up-to-size
if(mUseBitmap.size() < newSlabCount*mEltsPerSlab)
{
mUseBitmap.resize(2* newSlabCount*mEltsPerSlab); //set last element as not used
if(mFreeList)
Alloc::deallocate(mFreeList);
mFreeList = reinterpret_cast<T**>(Alloc::allocate(2* newSlabCount * mEltsPerSlab * sizeof(T*), PX_FL));
T** slabs = reinterpret_cast<T**>(Alloc::allocate(2 * newSlabCount * sizeof(T*), PX_FL));
if (mSlabs)
{
PxMemCopy(slabs, mSlabs, sizeof(T*)*mSlabCount);
Alloc::deallocate(mSlabs);
}
mSlabs = slabs;
}
mSlabs[mSlabCount++] = mAddr;
// Add to free list in descending order so that lowest indices get allocated first -
// the FW context code currently *relies* on this behavior to grab the zero-index volume
// which can't be allocated to the user. TODO: fix this
PxU32 baseIndex = (mSlabCount-1) * mEltsPerSlab;
PxU32 freeCount = mFreeCount;
for(PxI32 i=PxI32(mEltsPerSlab-1);i>=0;i--)
mFreeList[freeCount++] = PX_PLACEMENT_NEW(mAddr+i, T(mArgument, baseIndex+ i));
mFreeCount = freeCount;
return true;
}
PX_INLINE PxU32 getMaxUsedIndex() const
{
return mUseBitmap.findLast();
}
PX_INLINE PxBitMap::Iterator getIterator() const
{
return PxBitMap::Iterator(mUseBitmap);
}
private:
const PxU32 mEltsPerSlab;
PxU32 mSlabCount;
PxU32 mLog2EltsPerSlab;
T** mFreeList;
PxU32 mFreeCount;
T** mSlabs;
ArgumentType* mArgument;
PxBitMap mUseBitmap;
};
}
}
#endif
| 8,399 |
C
| 27.093645 | 115 | 0.692702 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmCollection.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_COLLECTION_H
#define CM_COLLECTION_H
#include "common/PxCollection.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxAllocator.h"
namespace physx
{
namespace Cm
{
template <class Key,
class Value,
class HashFn = PxHash<Key>,
class Allocator = PxAllocator >
class CollectionHashMap : public PxCoalescedHashMap< Key, Value, HashFn, Allocator>
{
typedef physx::PxHashMapBase< Key, Value, HashFn, Allocator> MapBase;
typedef PxPair<const Key,Value> EntryData;
public:
CollectionHashMap(PxU32 initialTableSize = 64, float loadFactor = 0.75f):
PxCoalescedHashMap< Key, Value, HashFn, Allocator>(initialTableSize,loadFactor) {}
void insertUnique(const Key& k, const Value& v)
{
PX_PLACEMENT_NEW(MapBase::mBase.insertUnique(k), EntryData)(k,v);
}
};
class Collection : public PxCollection, public PxUserAllocated
{
public:
typedef CollectionHashMap<PxBase*, PxSerialObjectId> ObjectToIdMap;
typedef CollectionHashMap<PxSerialObjectId, PxBase*> IdToObjectMap;
virtual void add(PxBase& object, PxSerialObjectId ref);
virtual void remove(PxBase& object);
virtual bool contains(PxBase& object) const;
virtual void addId(PxBase& object, PxSerialObjectId id);
virtual void removeId(PxSerialObjectId id);
virtual PxBase* find(PxSerialObjectId ref) const;
virtual void add(PxCollection& collection);
virtual void remove(PxCollection& collection);
virtual PxU32 getNbObjects() const;
virtual PxBase& getObject(PxU32 index) const;
virtual PxU32 getObjects(PxBase** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const;
virtual PxU32 getNbIds() const;
virtual PxSerialObjectId getId(const PxBase& object) const;
virtual PxU32 getIds(PxSerialObjectId* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const;
void release() { PX_DELETE_THIS; }
// Only for internal use. Bypasses virtual calls, specialized behaviour.
PX_INLINE void internalAdd(PxBase* s, PxSerialObjectId id = PX_SERIAL_OBJECT_ID_INVALID) { mObjects.insertUnique(s, id); }
PX_INLINE PxU32 internalGetNbObjects() const { return mObjects.size(); }
PX_INLINE PxBase* internalGetObject(PxU32 i) const { PX_ASSERT(i<mObjects.size()); return mObjects.getEntries()[i].first; }
PX_INLINE const ObjectToIdMap::Entry* internalGetObjects() const { return mObjects.getEntries(); }
IdToObjectMap mIds;
ObjectToIdMap mObjects;
};
}
}
#endif
| 4,288 |
C
| 43.216494 | 130 | 0.735541 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmSerialize.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_SERIALIZE_H
#define CM_SERIALIZE_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxIO.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxUtilities.h"
namespace physx
{
PX_INLINE void flip(PxU16& v)
{
PxU8* b = reinterpret_cast<PxU8*>(&v);
PxU8 temp = b[0];
b[0] = b[1];
b[1] = temp;
}
PX_INLINE void flip(PxI16& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
PxI8 temp = b[0];
b[0] = b[1];
b[1] = temp;
}
PX_INLINE void flip(PxU32& v)
{
PxU8* b = reinterpret_cast<PxU8*>(&v);
PxU8 temp = b[0];
b[0] = b[3];
b[3] = temp;
temp = b[1];
b[1] = b[2];
b[2] = temp;
}
// MS: It is important to modify the value directly and not use a temporary variable or a return
// value. The reason for this is that a flipped float might have a bit pattern which indicates
// an invalid float. If such a float is assigned to another float, the bit pattern
// can change again (maybe to map invalid floats to a common invalid pattern?).
// When reading the float and flipping again, the changed bit pattern will result in a different
// float than the original one.
PX_INLINE void flip(PxF32& v)
{
PxU8* b = reinterpret_cast<PxU8*>(&v);
PxU8 temp = b[0];
b[0] = b[3];
b[3] = temp;
temp = b[1];
b[1] = b[2];
b[2] = temp;
}
PX_INLINE void writeChunk(PxI8 a, PxI8 b, PxI8 c, PxI8 d, PxOutputStream& stream)
{
stream.write(&a, sizeof(PxI8));
stream.write(&b, sizeof(PxI8));
stream.write(&c, sizeof(PxI8));
stream.write(&d, sizeof(PxI8));
}
void readChunk(PxI8& a, PxI8& b, PxI8& c, PxI8& d, PxInputStream& stream);
PxU16 readWord(bool mismatch, PxInputStream& stream);
PxU32 readDword(bool mismatch, PxInputStream& stream);
PxF32 readFloat(bool mismatch, PxInputStream& stream);
void writeWord(PxU16 value, bool mismatch, PxOutputStream& stream);
void writeDword(PxU32 value, bool mismatch, PxOutputStream& stream);
void writeFloat(PxF32 value, bool mismatch, PxOutputStream& stream);
bool readFloatBuffer(PxF32* dest, PxU32 nbFloats, bool mismatch, PxInputStream& stream);
void writeFloatBuffer(const PxF32* src, PxU32 nb, bool mismatch, PxOutputStream& stream);
void writeWordBuffer(const PxU16* src, PxU32 nb, bool mismatch, PxOutputStream& stream);
void readWordBuffer(PxU16* dest, PxU32 nb, bool mismatch, PxInputStream& stream);
void writeWordBuffer(const PxI16* src, PxU32 nb, bool mismatch, PxOutputStream& stream);
void readWordBuffer(PxI16* dest, PxU32 nb, bool mismatch, PxInputStream& stream);
void writeByteBuffer(const PxU8* src, PxU32 nb, PxOutputStream& stream);
void readByteBuffer(PxU8* dest, PxU32 nb, PxInputStream& stream);
bool writeHeader(PxI8 a, PxI8 b, PxI8 c, PxI8 d, PxU32 version, bool mismatch, PxOutputStream& stream);
bool readHeader(PxI8 a, PxI8 b, PxI8 c, PxI8 d, PxU32& version, bool& mismatch, PxInputStream& stream);
PX_INLINE bool readIntBuffer(PxU32* dest, PxU32 nbInts, bool mismatch, PxInputStream& stream)
{
return readFloatBuffer(reinterpret_cast<PxF32*>(dest), nbInts, mismatch, stream);
}
PX_INLINE void writeIntBuffer(const PxU32* src, PxU32 nb, bool mismatch, PxOutputStream& stream)
{
writeFloatBuffer(reinterpret_cast<const PxF32*>(src), nb, mismatch, stream);
}
PX_INLINE bool ReadDwordBuffer(PxU32* dest, PxU32 nb, bool mismatch, PxInputStream& stream)
{
return readFloatBuffer(reinterpret_cast<float*>(dest), nb, mismatch, stream);
}
PX_INLINE void WriteDwordBuffer(const PxU32* src, PxU32 nb, bool mismatch, PxOutputStream& stream)
{
writeFloatBuffer(reinterpret_cast<const float*>(src), nb, mismatch, stream);
}
PxU32 computeMaxIndex(const PxU32* indices, PxU32 nbIndices);
PxU16 computeMaxIndex(const PxU16* indices, PxU32 nbIndices);
void storeIndices(PxU32 maxIndex, PxU32 nbIndices, const PxU32* indices, PxOutputStream& stream, bool platformMismatch);
void readIndices(PxU32 maxIndex, PxU32 nbIndices, PxU32* indices, PxInputStream& stream, bool platformMismatch);
// PT: see PX-1163
PX_FORCE_INLINE bool readBigEndianVersionNumber(PxInputStream& stream, bool mismatch_, PxU32& fileVersion, bool& mismatch)
{
// PT: allright this is going to be subtle:
// - in version 1 the data was always saved in big-endian format
// - *including the version number*!
// - so we cannot just read the version "as usual" using the passed mismatch param
// PT: mismatch value for version 1
mismatch = (PxLittleEndian() == 1);
const PxU32 rawFileVersion = readDword(false, stream);
if(rawFileVersion==1)
{
// PT: this is a version-1 file with no flip
fileVersion = 1;
PX_ASSERT(!mismatch);
}
else
{
PxU32 fileVersionFlipped = rawFileVersion;
flip(fileVersionFlipped);
if(fileVersionFlipped==1)
{
// PT: this is a version-1 file with flip
fileVersion = 1;
PX_ASSERT(mismatch);
}
else
{
// PT: this is at least version 2 so we can process it "as usual"
mismatch = mismatch_;
fileVersion = mismatch_ ? fileVersionFlipped : rawFileVersion;
}
}
PX_ASSERT(fileVersion<=3);
if(fileVersion>3)
return false;
return true;
}
// PT: TODO: copied from IceSerialize.h, still needs to be refactored/cleaned up.
namespace Cm
{
bool WriteHeader(PxU8 a, PxU8 b, PxU8 c, PxU8 d, PxU32 version, bool mismatch, PxOutputStream& stream);
bool ReadHeader(PxU8 a_, PxU8 b_, PxU8 c_, PxU8 d_, PxU32& version, bool& mismatch, PxInputStream& stream);
void StoreIndices(PxU32 maxIndex, PxU32 nbIndices, const PxU32* indices, PxOutputStream& stream, bool platformMismatch);
void ReadIndices(PxU32 maxIndex, PxU32 nbIndices, PxU32* indices, PxInputStream& stream, bool platformMismatch);
void StoreIndices(PxU16 maxIndex, PxU32 nbIndices, const PxU16* indices, PxOutputStream& stream, bool platformMismatch);
void ReadIndices(PxU16 maxIndex, PxU32 nbIndices, PxU16* indices, PxInputStream& stream, bool platformMismatch);
}
}
#endif
| 7,710 |
C
| 37.944444 | 123 | 0.720233 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmConeLimitHelper.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_CONE_LIMIT_HELPER_H
#define CM_CONE_LIMIT_HELPER_H
// This class contains methods for supporting the tan-quarter swing limit - that
// is the, ellipse defined by tanQ(theta)^2/tanQ(thetaMax)^2 + tanQ(phi)^2/tanQ(phiMax)^2 = 1
//
// Angles are passed as an PxVec3 swing vector with x = 0 and y and z the swing angles
// around the y and z axes
#include "foundation/PxMathUtils.h"
namespace physx
{
namespace Cm
{
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal tanAdd(PxReal tan1, PxReal tan2)
{
PX_ASSERT(PxAbs(1.0f-tan1*tan2)>1e-6f);
return (tan1+tan2)/(1.0f-tan1*tan2);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE float computeAxisAndError(const PxVec3& r, const PxVec3& d, const PxVec3& twistAxis, PxVec3& axis)
{
// the point on the cone defined by the tanQ swing vector r
// this code is equal to quatFromTanQVector(r).rotate(PxVec3(1.0f, 0.0f, 0.0f);
const PxVec3 p(1.0f, 0.0f, 0.0f);
const PxReal r2 = r.dot(r), a = 1.0f - r2, b = 1.0f/(1.0f+r2), b2 = b*b;
const PxReal v1 = 2.0f * a * b2;
const PxVec3 v2(a, 2.0f * r.z, -2.0f * r.y); // a*p + 2*r.cross(p);
const PxVec3 coneLine = v1 * v2 - p; // already normalized
// the derivative of coneLine in the direction d
const PxReal rd = r.dot(d);
const PxReal dv1 = -4.0f * rd * (3.0f - r2)*b2*b;
const PxVec3 dv2(-2.0f * rd, 2.0f * d.z, -2.0f * d.y);
const PxVec3 coneNormal = v1 * dv2 + dv1 * v2;
axis = coneLine.cross(coneNormal)/coneNormal.magnitude();
return coneLine.cross(axis).dot(twistAxis);
}
// this is here because it's used in both LL and Extensions. However, it
// should STAY IN THE SDK CODE BASE because it's SDK-specific
class ConeLimitHelper
{
public:
PX_CUDA_CALLABLE ConeLimitHelper(PxReal tanQSwingY, PxReal tanQSwingZ, PxReal tanQPadding)
: mTanQYMax(tanQSwingY), mTanQZMax(tanQSwingZ), mTanQPadding(tanQPadding) {}
// whether the point is inside the (inwardly) padded cone - if it is, there's no limit
// constraint
PX_CUDA_CALLABLE PX_FORCE_INLINE bool contains(const PxVec3& tanQSwing) const
{
const PxReal tanQSwingYPadded = tanAdd(PxAbs(tanQSwing.y),mTanQPadding);
const PxReal tanQSwingZPadded = tanAdd(PxAbs(tanQSwing.z),mTanQPadding);
return PxSqr(tanQSwingYPadded/mTanQYMax)+PxSqr(tanQSwingZPadded/mTanQZMax) <= 1;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 clamp(const PxVec3& tanQSwing, PxVec3& normal) const
{
const PxVec3 p = PxEllipseClamp(tanQSwing, PxVec3(0.0f, mTanQYMax, mTanQZMax));
normal = PxVec3(0.0f, p.y/PxSqr(mTanQYMax), p.z/PxSqr(mTanQZMax));
#ifdef PX_PARANOIA_ELLIPSE_CHECK
PxReal err = PxAbs(PxSqr(p.y/mTanQYMax) + PxSqr(p.z/mTanQZMax) - 1);
PX_ASSERT(err<1e-3);
#endif
return p;
}
// input is a swing quat, such that swing.x = twist.y = twist.z = 0, q = swing * twist
// The routine is agnostic to the sign of q.w (i.e. we don't need the minimal-rotation swing)
// output is an axis such that positive rotation increases the angle outward from the
// limit (i.e. the image of the x axis), the error is the sine of the angular difference,
// positive if the twist axis is inside the cone
PX_CUDA_CALLABLE bool getLimit(const PxQuat& swing, PxVec3& axis, PxReal& error) const
{
PX_ASSERT(swing.w>0.0f);
const PxVec3 twistAxis = swing.getBasisVector0();
const PxVec3 tanQSwing = PxVec3(0.0f, PxTanHalf(swing.z,swing.w), -PxTanHalf(swing.y,swing.w));
if(contains(tanQSwing))
return false;
PxVec3 normal, clamped = clamp(tanQSwing, normal);
// rotation vector and ellipse normal
const PxVec3 r(0.0f, -clamped.z, clamped.y), d(0.0f, -normal.z, normal.y);
error = computeAxisAndError(r, d, twistAxis, axis);
PX_ASSERT(PxAbs(axis.magnitude()-1)<1e-5f);
#ifdef PX_PARANOIA_ELLIPSE_CHECK
bool inside = PxSqr(tanQSwing.y/mTanQYMax) + PxSqr(tanQSwing.z/mTanQZMax) <= 1;
PX_ASSERT(inside && error>-1e-4f || !inside && error<1e-4f);
#endif
return true;
}
private:
PxReal mTanQYMax, mTanQZMax, mTanQPadding;
};
class ConeLimitHelperTanLess
{
public:
PX_CUDA_CALLABLE ConeLimitHelperTanLess(PxReal swingY, PxReal swingZ)
: mYMax(swingY), mZMax(swingZ) {}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 clamp(const PxVec3& swing, PxVec3& normal) const
{
// finds the closest point on the ellipse to a given point
const PxVec3 p = PxEllipseClamp(swing, PxVec3(0.0f, mYMax, mZMax));
// normal to the point on ellipse
normal = PxVec3(0.0f, p.y/PxSqr(mYMax), p.z/PxSqr(mZMax));
#ifdef PX_PARANOIA_ELLIPSE_CHECK
PxReal err = PxAbs(PxSqr(p.y/mYMax) + PxSqr(p.z/mZMax) - 1);
PX_ASSERT(err<1e-3);
#endif
return p;
}
// input is a swing quat, such that swing.x = twist.y = twist.z = 0, q = swing * twist
// The routine is agnostic to the sign of q.w (i.e. we don't need the minimal-rotation swing)
// output is an axis such that positive rotation increases the angle outward from the
// limit (i.e. the image of the x axis), the error is the sine of the angular difference,
// positive if the twist axis is inside the cone
PX_CUDA_CALLABLE void getLimit(const PxQuat& swing, PxVec3& axis, PxReal& error) const
{
PX_ASSERT(swing.w>0.0f);
const PxVec3 twistAxis = swing.getBasisVector0();
// get the angles from the swing quaternion
const PxVec3 swingAngle(0.0f, 4.0f * PxAtan2(swing.y, 1.0f + swing.w), 4.0f * PxAtan2(swing.z, 1.0f + swing.w));
PxVec3 normal, clamped = clamp(swingAngle, normal);
// rotation vector and ellipse normal
const PxVec3 r(0.0f, PxTan(clamped.y/4.0f), PxTan(clamped.z/4.0f)), d(0.0f, normal.y, normal.z);
error = computeAxisAndError(r, d, twistAxis, axis);
PX_ASSERT(PxAbs(axis.magnitude()-1.0f)<1e-5f);
}
private:
PxReal mYMax, mZMax;
};
} // namespace Cm
}
#endif
| 7,434 |
C
| 38.338624 | 132 | 0.71025 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmRadixSort.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef CM_RADIX_SORT_H
#define CM_RADIX_SORT_H
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Cm
{
enum RadixHint
{
RADIX_SIGNED, //!< Input values are signed
RADIX_UNSIGNED, //!< Input values are unsigned
RADIX_FORCE_DWORD = 0x7fffffff
};
#define INVALIDATE_RANKS mCurrentSize|=0x80000000
#define VALIDATE_RANKS mCurrentSize&=0x7fffffff
#define CURRENT_SIZE (mCurrentSize&0x7fffffff)
#define INVALID_RANKS (mCurrentSize&0x80000000)
class PX_PHYSX_COMMON_API RadixSort
{
PX_NOCOPY(RadixSort)
public:
RadixSort();
virtual ~RadixSort();
// Sorting methods
RadixSort& Sort(const PxU32* input, PxU32 nb, RadixHint hint=RADIX_SIGNED);
RadixSort& Sort(const float* input, PxU32 nb);
//! Access to results. mRanks is a list of indices in sorted order, i.e. in the order you may further process your data
PX_FORCE_INLINE const PxU32* GetRanks() const { return mRanks; }
//! mIndices2 gets trashed on calling the sort routine, but otherwise you can recycle it the way you want.
PX_FORCE_INLINE PxU32* GetRecyclable() const { return mRanks2; }
//! Returns the total number of calls to the radix sorter.
PX_FORCE_INLINE PxU32 GetNbTotalCalls() const { return mTotalCalls; }
//! Returns the number of eraly exits due to temporal coherence.
PX_FORCE_INLINE PxU32 GetNbHits() const { return mNbHits; }
PX_FORCE_INLINE void invalidateRanks() { INVALIDATE_RANKS; }
bool SetBuffers(PxU32* ranks0, PxU32* ranks1, PxU32* histogram1024, PxU32** links256);
protected:
PxU32 mCurrentSize; //!< Current size of the indices list
PxU32* mRanks; //!< Two lists, swapped each pass
PxU32* mRanks2;
PxU32* mHistogram1024;
PxU32** mLinks256;
// Stats
PxU32 mTotalCalls; //!< Total number of calls to the sort routine
PxU32 mNbHits; //!< Number of early exits due to coherence
// Stack-radix
bool mDeleteRanks; //!<
};
#define StackRadixSort(name, ranks0, ranks1) \
RadixSort name; \
PxU32 histogramBuffer[1024]; \
PxU32* linksBuffer[256]; \
name.SetBuffers(ranks0, ranks1, histogramBuffer, linksBuffer);
class PX_PHYSX_COMMON_API RadixSortBuffered : public RadixSort
{
public:
RadixSortBuffered();
~RadixSortBuffered();
void reset();
RadixSortBuffered& Sort(const PxU32* input, PxU32 nb, RadixHint hint=RADIX_SIGNED);
RadixSortBuffered& Sort(const float* input, PxU32 nb);
private:
RadixSortBuffered(const RadixSortBuffered& object);
RadixSortBuffered& operator=(const RadixSortBuffered& object);
// Internal methods
void CheckResize(PxU32 nb);
bool Resize(PxU32 nb);
};
}
}
#endif // CM_RADIX_SORT_H
| 4,476 |
C
| 36.940678 | 121 | 0.718275 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/windows/CmWindowsModuleUpdateLoader.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifdef SUPPORT_UPDATE_LOADER_LOGGING
#if PX_X86
#define NX_USE_SDK_DLLS
#include "PhysXUpdateLoader.h"
#endif
#endif /* SUPPORT_UPDATE_LOADER_LOGGING */
#include "windows/CmWindowsModuleUpdateLoader.h"
#include "windows/CmWindowsLoadLibrary.h"
#include "stdio.h"
namespace physx { namespace Cm {
#if PX_VC
#pragma warning(disable: 4191) //'operator/operation' : unsafe conversion from 'type of expression' to 'type required'
#endif
typedef HMODULE (*GetUpdatedModule_FUNC)(const char*, const char*);
#ifdef SUPPORT_UPDATE_LOADER_LOGGING
#if PX_X86
typedef void (*setLogging_FUNC)(PXUL_ErrorCode, pt2LogFunc);
static void LogMessage(PXUL_ErrorCode messageType, char* message)
{
switch(messageType)
{
case PXUL_ERROR_MESSAGES:
getFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL,
"PhysX Update Loader Error: %s.", message);
break;
case PXUL_WARNING_MESSAGES:
getFoundation().error(PX_WARN, "PhysX Update Loader Warning: %s.", message);
break;
case PXUL_INFO_MESSAGES:
getFoundation().error(PX_INFO, "PhysX Update Loader Information: %s.", message);
break;
default:
getFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL,
"Unknown message type from update loader.");
break;
}
}
#endif
#endif /* SUPPORT_UPDATE_LOADER_LOGGING */
CmModuleUpdateLoader::CmModuleUpdateLoader(const char* updateLoaderDllName)
: mGetUpdatedModuleFunc(NULL)
{
mUpdateLoaderDllHandle = loadLibrary(updateLoaderDllName);
if (mUpdateLoaderDllHandle != NULL)
{
mGetUpdatedModuleFunc = GetProcAddress(mUpdateLoaderDllHandle, "GetUpdatedModule");
#ifdef SUPPORT_UPDATE_LOADER_LOGGING
#if PX_X86
setLogging_FUNC setLoggingFunc;
setLoggingFunc = (setLogging_FUNC)GetProcAddress(mUpdateLoaderDllHandle, "setLoggingFunction");
if(setLoggingFunc != NULL)
{
setLoggingFunc(PXUL_ERROR_MESSAGES, LogMessage);
}
#endif
#endif /* SUPPORT_UPDATE_LOADER_LOGGING */
}
}
CmModuleUpdateLoader::~CmModuleUpdateLoader()
{
if (mUpdateLoaderDllHandle != NULL)
{
FreeLibrary(mUpdateLoaderDllHandle);
mUpdateLoaderDllHandle = NULL;
}
}
HMODULE CmModuleUpdateLoader::LoadModule(const char* moduleName, const char* appGUID)
{
HMODULE result = NULL;
if (mGetUpdatedModuleFunc != NULL)
{
// Try to get the module through PhysXUpdateLoader
GetUpdatedModule_FUNC getUpdatedModuleFunc = (GetUpdatedModule_FUNC)mGetUpdatedModuleFunc;
result = getUpdatedModuleFunc(moduleName, appGUID);
}
else
{
// If no PhysXUpdateLoader, just load the DLL directly
result = loadLibrary(moduleName);
if (result == NULL)
{
const DWORD err = GetLastError();
printf("%s:%i: loadLibrary error when loading %s: %lu\n", PX_FL, moduleName, err);
}
}
return result;
}
}; // end of namespace
}; // end of namespace
| 4,455 |
C++
| 32.007407 | 118 | 0.752413 |
NVIDIA-Omniverse/PhysX/physx/source/common/include/omnipvd/CmOmniPvdAutoGenCreateRegistrationStruct.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
//
// The macro logic in this header (and the headers CmOmniPvdAutoGenRegisterData.h and
// and CmOmniPvdAutoGenSetData.h) is meant as a helper to automatically generate a
// structure that stores all PVD class and attribute handles for a module, handles the
// registration logic and adds methods for object creation, setting attribute
// values etc. At the core of the generation logic is a user defined header file
// that describes the classes and attributes as follows:
//
// OMNI_PVD_CLASS_BEGIN(MyClass1)
// OMNI_PVD_ATTRIBUTE(MyClass1, myAttr1, PxReal, OmniPvdDataType::eFLOAT32)
// OMNI_PVD_ATTRIBUTE(MyClass1, myAttr2, PxReal, OmniPvdDataType::eFLOAT32)
// OMNI_PVD_CLASS_END(MyClass1)
//
// OMNI_PVD_CLASS_UNTYPED_BEGIN(MyClass2)
// OMNI_PVD_ATTRIBUTE(MyClass2, myAttr1, PxU32, OmniPvdDataType::eUINT32)
// OMNI_PVD_CLASS_END(MyClass2)
//
// The structure to create from this description will look somewhat like this:
//
// struct MyModulePvdObjectsDescriptor
// {
//
// struct PvdMyClass1
// {
// typedef MyClass1 ObjectType;
// static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectRef) { return reinterpret_cast<OmniPvdObjectHandle>(&objectRef); }
//
// OmniPvdClassHandle classHandle;
//
// void createInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) const
// {
// writer.createObject(contextHandle, classHandle, getObjectHandle(objectRef), NULL);
// }
//
// static void destroyInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef)
// {
// writer.destroyObject(contextHandle, getObjectHandle(objectRef));
// }
//
// OmniPvdAttributeHandle myAttr1;
// void set_myAttr1_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const PxReal& value) const
// {
// writer.setAttribute(contextHandle, getObjectHandle(objectRef), myAttr1, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT32>());
// }
//
// OmniPvdAttributeHandle myAttr2;
// void set_myAttr2_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const PxReal& value) const
// {
// writer.setAttribute(contextHandle, getObjectHandle(objectRef), myAttr2, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT32>());
// }
// };
// PvdMyClass1 pvdMyClass1;
//
//
// struct PvdMyClass2
// {
// typedef OmniPvdObjectHandle ObjectType;
// static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectHandle) { return objectHandle; }
//
// OmniPvdClassHandle classHandle;
//
// void createInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) const
// {
// writer.createObject(contextHandle, classHandle, getObjectHandle(objectRef), NULL);
// }
//
// static void destroyInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef)
// {
// writer.destroyObject(contextHandle, getObjectHandle(objectRef));
// }
//
// OmniPvdAttributeHandle myAttr1;
// void set_myAttr1_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const PxU32& value) const
// {
// writer.setAttribute(contextHandle, getObjectHandle(objectRef), myAttr1, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<OmniPvdDataType::eUINT32>());
// }
// };
// PvdMyClass2 pvdMyClass2;
//
//
// void myRegisterDataMethod(OmniPvdWriter& writer)
// {
// pvdMyClass1.classHandle = writer.registerClass("MyClass1");
// pvdMyClass1.myAttr1 = writer.registerAttribute(pvdMyClass1.classHandle, "myAttr1", OmniPvdDataType::eFLOAT32, 1);
// pvdMyClass1.myAttr2 = writer.registerAttribute(pvdMyClass1.classHandle, "myAttr2", OmniPvdDataType::eFLOAT32, 1);
//
// pvdMyClass2.classHandle = writer.registerClass("MyClass2");
// pvdMyClass2.myAttr1 = writer.registerAttribute(pvdMyClass2.classHandle, "myAttr1", OmniPvdDataType::eUINT32, 1);
// }
//
// };
//
// Assuming the class and attribute definitions are in a file called MyModulePvdObjectDefinitions.h,
// the described structure can be generated like this:
//
// struct MyModulePvdObjectsDescriptor
// {
//
// #include "CmOmniPvdAutoGenCreateRegistrationStruct.h"
// #include "MyModulePvdObjectDefinitions.h"
// #include "CmOmniPvdAutoGenClearDefines.h"
//
// // custom registration data related members that are not auto-generated can go here, for example
//
//
// void myRegisterDataMethod(OmniPvdWriter& writer)
// {
// #define OMNI_PVD_WRITER_VAR writer
//
// #include "CmOmniPvdAutoGenRegisterData.h"
// #include "MyModulePvdObjectDefinitions.h"
// #include "CmOmniPvdAutoGenClearDefines.h"
//
// // custom registration code that is not auto-generated can go here too
//
// #undef OMNI_PVD_WRITER_VAR
// }
// };
//
// As can be seen, CmOmniPvdAutoGenCreateRegistrationStruct.h is responsible for generating the structs,
// members and setter methods. CmOmniPvdAutoGenRegisterData.h is responsible for generating the registration
// code (note that defining OMNI_PVD_WRITER_VAR is important in this context since it is used inside
// CmOmniPvdAutoGenRegisterData.h)
//
// Note that it is the user's responsibility to include the necessary headers before applying these helpers
// (for example, OmniPvdDefines.h etc.).
//
// Last but not least, the helpers in CmOmniPvdAutoGenSetData.h provide a way to use this structure to
// set values of attributes, create class instances etc. An example usage is shown below:
//
// OmniPvdContextHandle contextHandle; // assuming this holds the context the objects belong to
// MyClass1 myClass1Instance;
// PxReal value; // assuming this holds the value to set the attribute to
//
// OMNI_PVD_CREATE(contextHandle, MyClass1, myClass1Instance);
// OMNI_PVD_SET(contextHandle, MyClass1, myAttr1, myClass1Instance, value);
//
// To use these helper macros, the following things need to be defined before including CmOmniPvdAutoGenSetData.h:
//
// #define OMNI_PVD_GET_WRITER(writer)
// OmniPvdWriter* writer = GetPvdWriterForMyModule();
//
// #define OMNI_PVD_GET_REGISTRATION_DATA(regData)
// MyModulePvdObjectsDescriptor* regData = GetPvdObjectsDescForMyModule();
//
// #include "CmOmniPvdAutoGenSetData.h"
//
// GetPvdWriterForMyModule() and GetPvdObjectsDescForMyModule() just stand for the logic the user needs
// to provide to access the OmniPvdWriter object and the generated description structure. In the given example,
// the variables "writer" and "regData" need to be assigned but the code to do so will be user specific.
//
//
#define OMNI_PVD_CLASS_INTERNALS \
\
OmniPvdClassHandle classHandle; \
\
void createInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) const \
{ \
writer.createObject(contextHandle, classHandle, getObjectHandle(objectRef), NULL); \
} \
\
static void destroyInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) \
{ \
writer.destroyObject(contextHandle, getObjectHandle(objectRef)); \
}
//
// Define a PVD class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: name of the class to register in PVD (note: has to be an existing C++ class)
//
#define OMNI_PVD_CLASS_BEGIN(classID) \
\
struct Pvd##classID \
{ \
typedef classID ObjectType; \
\
static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectRef) { return reinterpret_cast<OmniPvdObjectHandle>(&objectRef); } \
\
OMNI_PVD_CLASS_INTERNALS
//
// Define a PVD class that is derived from another class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: see OMNI_PVD_CLASS_BEGIN
// baseClassID: the name of the class to derive from
//
#define OMNI_PVD_CLASS_DERIVED_BEGIN(classID, baseClassID) OMNI_PVD_CLASS_BEGIN(classID)
//
// Define a PVD class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: name of the class to register in PVD (note: the class does not need to match an actually existing
// class but still needs to follow C++ naming conventions)
//
#define OMNI_PVD_CLASS_UNTYPED_BEGIN(classID) \
\
struct Pvd##classID \
{ \
typedef OmniPvdObjectHandle ObjectType; \
\
static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectHandle) { return objectHandle; } \
\
OMNI_PVD_CLASS_INTERNALS
//
// Define a PVD class that is derived from another class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: see OMNI_PVD_CLASS_UNTYPED_BEGIN
// baseClassID: the name of the class to derive from
//
#define OMNI_PVD_CLASS_UNTYPED_DERIVED_BEGIN(classID, baseClassID) OMNI_PVD_CLASS_UNTYPED_BEGIN(classID)
//
// See OMNI_PVD_CLASS_BEGIN for more info.
//
#define OMNI_PVD_CLASS_END(classID) \
\
}; \
Pvd##classID pvd##classID;
//
// Define a PVD enum class.
//
// Note: has to be paired with OMNI_PVD_ENUM_END
//
// enumID: name of the enum class (has to follow C++ naming conventions)
//
#define OMNI_PVD_ENUM_BEGIN(enumID) \
\
struct Pvd##enumID \
{ \
OmniPvdClassHandle classHandle;
//
// See OMNI_PVD_ENUM_BEGIN
//
#define OMNI_PVD_ENUM_END(enumID) OMNI_PVD_CLASS_END(enumID)
//
// Define a simple PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// classID: name of the class to add the attribute to (see OMNI_PVD_CLASS_BEGIN)
// attributeID: name of the attribute (has to follow C++ naming conventions)
// valueType: attribute data type (int, float etc.)
// pvdDataType: PVD attribute data type (see OmniPvdDataType)
//
#define OMNI_PVD_ATTRIBUTE(classID, attributeID, valueType, pvdDataType) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
PX_ASSERT(sizeof(valueType) == getOmniPvdDataTypeSize<pvdDataType>()); \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<pvdDataType>()); \
}
//
// Define a fixed size multi-value PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// The attribute is a fixed size array of values of the given pvd data type.
//
// entryCount: number of entries the array will hold.
//
// See OMNI_PVD_ATTRIBUTE for the other parameters. Note that valueType is
// expected to hold a type that matches the size of the whole array, i.e.,
// sizeof(valueType) == entryCount * getOmniPvdDataTypeSize<pvdDataType>()
//
#define OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE(classID, attributeID, valueType, pvdDataType, entryCount) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
const uint32_t byteSize = static_cast<uint32_t>(sizeof(valueType)); \
PX_ASSERT(byteSize == (entryCount * getOmniPvdDataTypeSize<pvdDataType>())); \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(&value), byteSize); \
}
//
// Define a variable size multi-value PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// The attribute is a variable size array of values of the given pvd data type.
//
// See OMNI_PVD_ATTRIBUTE for a parameter description. Note that valueType is expected
// to define the type of a single array element, for example, int for an integer array.
//
#define OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE(classID, attributeID, valueType, pvdDataType) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType* values, uint32_t valueCount) const \
{ \
const uint32_t byteSize = valueCount * getOmniPvdDataTypeSize<pvdDataType>(); \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(values), byteSize); \
}
//
// Define a string PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// See OMNI_PVD_ATTRIBUTE for a parameter description.
//
#define OMNI_PVD_ATTRIBUTE_STRING(classID, attributeID) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const char* values, uint32_t valueCount) const \
{ \
const uint32_t byteSize = valueCount; \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(values), byteSize); \
}
//
// Define a unique list PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// See OMNI_PVD_ATTRIBUTE for a parameter description. Note that valueType is expected
// to define the class the list will hold pointers to. If it shall hold pointers to
// instances of class MyClass, then the valueType is MyClass.
//
#define OMNI_PVD_ATTRIBUTE_UNIQUE_LIST(classID, attributeID, valueType) \
\
OmniPvdAttributeHandle attributeID; \
\
void addTo_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
const OmniPvdObjectHandle objHandle = reinterpret_cast<OmniPvdObjectHandle>(&value); \
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&objHandle); \
writer.addToUniqueListAttribute(contextHandle, getObjectHandle(objectRef), attributeID, ptr, sizeof(OmniPvdObjectHandle)); \
} \
\
void removeFrom_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
const OmniPvdObjectHandle objHandle = reinterpret_cast<OmniPvdObjectHandle>(&value); \
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&objHandle); \
writer.removeFromUniqueListAttribute(contextHandle, getObjectHandle(objectRef), attributeID, ptr, sizeof(OmniPvdObjectHandle)); \
}
//
// Define a flag PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// enumType: the enum type this attribute refers to
// enumID: the name of the enum class that describes the enum (see OMNI_PVD_ENUM_BEGIN)
//
// See OMNI_PVD_ATTRIBUTE for the other parameters.
//
#define OMNI_PVD_ATTRIBUTE_FLAG(classID, attributeID, enumType, enumID) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const enumType& value) const \
{ \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(&value), sizeof(enumType)); \
}
//
// Define an enum entry.
//
// Note: needs to be placed between a OMNI_PVD_ENUM_BEGIN, OMNI_PVD_ENUM_END
// sequence
//
// enumID: name of the enum class to add an entry to (see OMNI_PVD_ENUM_BEGIN)
// enumEntryID: the name of the enum entry to add to the enum class (has to follow C++ naming conventions)
// value: the enum value
//
#define OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, value)
//
// Define an enum entry.
//
// Note: needs to be placed between a OMNI_PVD_ENUM_BEGIN, OMNI_PVD_ENUM_END
// sequence
//
// See OMNI_PVD_ENUM_VALUE_EXPLICIT for a description of the parameters. This shorter form expects the enum to
// have a C++ definition of the form:
//
// struct <enumID>
// {
// enum Enum
// {
// <enumEntryID> = ...
// }
// }
//
// such that the value can be derived using: <enumID>::<enumEntryID>
//
#define OMNI_PVD_ENUM_VALUE(enumID, enumEntryID) \
\
OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, enumID::enumEntryID)
| 25,110 |
C
| 54.067982 | 176 | 0.526245 |
NVIDIA-Omniverse/PhysX/physx/source/common/include/omnipvd/CmOmniPvdAutoGenSetData.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
//
// This header provides macros to register PVD object instances, to set PVD attribute
// values etc. This only works in combination with a registration structure that was
// defined using the logic in CmOmniPvdAutoGenCreateRegistrationStruct.h.
// OMNI_PVD_GET_WRITER and OMNI_PVD_GET_REGISTRATION_DATA have to be defined before
// including this header. These two macros need to fetch and assign the pointer to
// the OmniPvdWriter instance and the registration structure instance respectively.
// See CmOmniPvdAutoGenCreateRegistrationStruct.h for a more detailed overview of the
// whole approach.
//
#if PX_SUPPORT_OMNI_PVD
//
// It is recommended to use this macro when multiple PVD attributes get written
// in one go since the writer and registration structure is then fetched once only.
//
// Note: has to be paired with OMNI_PVD_WRITE_SCOPE_END
//
// writer: a pointer to the OmniPvdWriter instance will get assigned to a variable
// named "writer"
// regData: a pointer to the registration structure instance will get assigned to
// a variable named "regData"
//
// General usage would look like this:
//
// OMNI_PVD_WRITE_SCOPE_BEGIN(writer, regData)
// OMNI_PVD_SET_EXPLICIT(writer, regData, ...)
// OMNI_PVD_SET_EXPLICIT(writer, regData, ...)
// ...
// OMNI_PVD_WRITE_SCOPE_END
//
#define OMNI_PVD_WRITE_SCOPE_BEGIN(writer, regData) \
\
OMNI_PVD_GET_WRITER(writer) \
if (writer != NULL) \
{ \
OMNI_PVD_GET_REGISTRATION_DATA(regData)
//
// See OMNI_PVD_WRITE_SCOPE_BEGIN for more info.
//
#define OMNI_PVD_WRITE_SCOPE_END \
\
}
//
// Create a PVD object instance using the provided pointers to the writer and registration
// structure instance.
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_CREATE_EXPLICIT(writer, regData, contextHandle, classID, objectRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.createInstance(*writer, contextHandle, objectRef);
//
// Create a PVD object instance.
//
// Note: if attribute values are to be set directly after the object instance registration,
// it is recommended to use OMNI_PVD_WRITE_SCOPE_BEGIN & OMNI_PVD_CREATE_EXPLICIT etc. instead
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_CREATE(contextHandle, classID, objectRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, objectRef); \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Destroy a PVD object instance using the provided pointer to the writer instance.
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_DESTROY_EXPLICIT(writer, regData, contextHandle, classID, objectRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.destroyInstance(*writer, contextHandle, objectRef);
//
// Destroy a PVD object instance.
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_DESTROY(contextHandle, classID, objectRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_DESTROY_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, objectRef); \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Set a PVD attribute value using the provided pointers to the writer and registration
// structure instance.
//
// writer: the variable named "writer" has to hold a pointer to the OmniPvdWriter instance
// regData: the variable named "regData" has to hold a pointer to the registration
// structure
//
// See OMNI_PVD_SET for a description of the other parameters.
//
#define OMNI_PVD_SET_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.set_##attributeID##_(*writer, contextHandle, objectRef, valueRef);
//
// Set a PVD attribute value.
//
// Note: if multiple attribute values should get set in a row, it is recommended
// to use OMNI_PVD_WRITE_SCOPE_BEGIN & OMNI_PVD_SET_EXPLICIT etc. instead
//
// contextHandle: the handle of the context the object instance belongs to
// classID: the name of the class (as defined in OMNI_PVD_CLASS_BEGIN() etc.) the attribute
// belongs to
// attributeID: the name of the attribute (as defined in OMNI_PVD_ATTRIBUTE() etc.) to set the
// value for
// objectRef: reference to the class instance to set the attribute for (for untyped classes this shall be
// a reference to a OmniPvdObjectHandle. For typed classes, the pointer value will be used as the
// object handle value).
// valueRef: a reference to a variable that holds the value to set the attribute to
//
#define OMNI_PVD_SET(contextHandle, classID, attributeID, objectRef, valueRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valueRef) \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Set PVD array attribute values (variable size array) using the provided pointers to the writer and registration
// structure instance.
//
// valuesPtr: pointer to the array data to set the attribute to
// valueCount: number of entries in valuePtr
//
// See OMNI_PVD_SET for a description of the other parameters.
//
#define OMNI_PVD_SET_ARRAY_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.set_##attributeID##_(*writer, contextHandle, objectRef, valuesPtr, valueCount);
//
// Set PVD array attribute values (variable size array).
//
// Note: if multiple attribute values should get set in a row, it is recommended
// to use OMNI_PVD_WRITE_SCOPE_BEGIN & OMNI_PVD_SET_EXPLICIT etc. instead
//
// See OMNI_PVD_SET_ARRAY_EXPLICIT for a description of the parameters.
//
#define OMNI_PVD_SET_ARRAY(contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount) \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Add an entry to a PVD unique list attribute using the provided pointers to the writer and registration
// structure instance.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_ADD_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.addTo_##attributeID##_(*writer, contextHandle, objectRef, valueRef);
//
// Add an entry to a PVD unique list attribute.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_ADD(contextHandle, classID, attributeID, objectRef, valueRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_ADD_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valueRef) \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Remove an entry from a PVD unique list attribute using the provided pointers to the writer and registration
// structure instance.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_REMOVE_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.removeFrom_##attributeID##_(*writer, contextHandle, objectRef, valueRef);
//
// Remove an entry from a PVD unique list attribute.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_REMOVE(contextHandle, classID, attributeID, objectRef, valueRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_REMOVE_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valueRef) \
OMNI_PVD_WRITE_SCOPE_END \
}
#else
#define OMNI_PVD_WRITE_SCOPE_BEGIN(writer, regData)
#define OMNI_PVD_WRITE_SCOPE_END
#define OMNI_PVD_CREATE_EXPLICIT(writer, regData, contextHandle, classID, objectRef)
#define OMNI_PVD_CREATE(contextHandle, classID, objectRef)
#define OMNI_PVD_DESTROY_EXPLICIT(writer, regData, contextHandle, classID, objectRef)
#define OMNI_PVD_DESTROY(contextHandle, classID, objectRef)
#define OMNI_PVD_SET_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_SET(contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_SET_ARRAY_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount)
#define OMNI_PVD_SET_ARRAY(contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount)
#define OMNI_PVD_ADD_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_ADD(contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_REMOVE_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_REMOVE(contextHandle, classID, attributeID, objectRef, valueRef)
#endif // PX_SUPPORT_OMNI_PVD
| 14,716 |
C
| 51.003533 | 125 | 0.552664 |
NVIDIA-Omniverse/PhysX/physx/source/common/include/omnipvd/CmOmniPvdAutoGenRegisterData.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
//
// The macro logic in this header will generate the PVD class/attribute registration
// code based on a class/attribute definition file. OMNI_PVD_WRITER_VAR needs to be
// defined before including this header. OMNI_PVD_WRITER_VAR has to represent the
// variable that holds a reference to a OmniPvdWriter instance. See
// CmOmniPvdAutoGenCreateRegistrationStruct.h for a more detailed overview of the
// whole approach. The various parameters are described there too.
//
#define OMNI_PVD_CLASS_BEGIN(classID) \
\
pvd##classID.classHandle = OMNI_PVD_WRITER_VAR.registerClass(#classID);
#define OMNI_PVD_CLASS_DERIVED_BEGIN(classID, baseClassID) \
\
pvd##classID.classHandle = OMNI_PVD_WRITER_VAR.registerClass(#classID, pvd##baseClassID.classHandle);
#define OMNI_PVD_CLASS_UNTYPED_BEGIN(classID) OMNI_PVD_CLASS_BEGIN(classID)
#define OMNI_PVD_CLASS_UNTYPED_DERIVED_BEGIN(classID, baseClassID) OMNI_PVD_CLASS_DERIVED_BEGIN(classID, baseClassID)
#define OMNI_PVD_CLASS_END(classID)
#define OMNI_PVD_ENUM_BEGIN(enumID) OMNI_PVD_CLASS_BEGIN(enumID)
#define OMNI_PVD_ENUM_END(enumID) OMNI_PVD_CLASS_END(enumID)
#define OMNI_PVD_ATTRIBUTE(classID, attributeID, valueType, pvdDataType) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, pvdDataType, 1);
#define OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE(classID, attributeID, valueType, pvdDataType, entryCount) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, pvdDataType, entryCount);
#define OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE(classID, attributeID, valueType, pvdDataType) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, pvdDataType, 0);
#define OMNI_PVD_ATTRIBUTE_STRING(classID, attributeID) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, OmniPvdDataType::eSTRING, 1);
#define OMNI_PVD_ATTRIBUTE_UNIQUE_LIST(classID, attributeID, valueType) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerUniqueListAttribute(pvd##classID.classHandle, #attributeID, OmniPvdDataType::eOBJECT_HANDLE);
#define OMNI_PVD_ATTRIBUTE_FLAG(classID, attributeID, enumType, enumID) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerFlagsAttribute(pvd##classID.classHandle, #attributeID, pvd##enumID.classHandle);
#define OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, value) \
\
OMNI_PVD_WRITER_VAR.registerEnumValue(pvd##enumID.classHandle, #enumEntryID, value);
#define OMNI_PVD_ENUM_VALUE(enumID, enumEntryID) \
\
OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, enumID::enumEntryID)
| 5,083 |
C
| 48.359223 | 148 | 0.674208 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxActor/VhPhysXActorFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/commands/PxVehicleCommandStates.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorFunctions.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
#include "PxRigidDynamic.h"
#include "PxArticulationLink.h"
#include "PxArticulationReducedCoordinate.h"
namespace physx
{
namespace vehicle2
{
void PxVehiclePhysxActorWakeup(
const PxVehicleCommandState& commands,
const PxVehicleEngineDriveTransmissionCommandState* transmissionCommands,
const PxVehicleGearboxParams* gearParams,
const PxVehicleGearboxState* gearState,
PxRigidBody& physxActor,
PxVehiclePhysXSteerState& physxSteerState)
{
PX_CHECK_AND_RETURN(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehiclePhysxActorWakeup: physxActor is kinematic. This is not supported");
PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
PxArticulationLink* link = physxActor.is<PxArticulationLink>();
bool intentToChangeState = ((commands.throttle != 0.0f) || ((PX_VEHICLE_UNSPECIFIED_STEER_STATE != physxSteerState.previousSteerCommand) && (commands.steer != physxSteerState.previousSteerCommand)));
if (!intentToChangeState && transmissionCommands)
{
PX_ASSERT(gearParams);
PX_ASSERT(gearState);
// Manual gear switch (includes going from neutral or reverse to automatic)
intentToChangeState = (gearState->currentGear == gearState->targetGear) &&
(((transmissionCommands->targetGear != PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR) && (gearState->targetGear != transmissionCommands->targetGear)) ||
((transmissionCommands->targetGear == PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR) && (gearState->currentGear <= gearParams->neutralGear)));
}
if(rd && rd->isSleeping() && intentToChangeState)
{
rd->wakeUp();
}
else if(link && link->getArticulation().isSleeping() && intentToChangeState)
{
link->getArticulation().wakeUp();
}
physxSteerState.previousSteerCommand = commands.steer;
}
bool PxVehiclePhysxActorSleepCheck
(const PxVehicleAxleDescription& axleDescription,
const PxRigidBody& physxActor,
const PxVehicleEngineParams* engineParams,
PxVehicleRigidBodyState& rigidBodyState,
PxVehiclePhysXConstraints& physxConstraints,
PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
PxVehicleEngineState* engineState)
{
PX_CHECK_AND_RETURN_VAL(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehiclePhysxActorSleepCheck: physxActor is kinematic. This is not supported", false);
const PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
const PxArticulationLink* link = physxActor.is<PxArticulationLink>();
bool isSleeping = false;
if (rd && rd->isSleeping())
{
isSleeping = true;
}
else if (link && link->getArticulation().isSleeping())
{
isSleeping = true;
}
if (isSleeping)
{
// note: pose is not copied as isSleeping() implies that pose was not changed by the
// simulation step (see docu). If a user explicitly calls putToSleep or manually
// changes pose, it will only get reflected in the vehicle rigid body state once
// the body wakes up.
rigidBodyState.linearVelocity = PxVec3(PxZero);
rigidBodyState.angularVelocity = PxVec3(PxZero);
rigidBodyState.previousLinearVelocity = PxVec3(PxZero);
rigidBodyState.previousAngularVelocity = PxVec3(PxZero);
bool markConstraintsDirty = false;
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
PxVehicleWheelRigidBody1dState& wheelState = wheelRigidBody1dStates[wheelId];
wheelState.rotationSpeed = 0.0f;
wheelState.correctedRotationSpeed = 0.0f;
// disable constraints if there are active ones. The idea is that if something
// is crashing into a sleeping vehicle and waking it up, then the vehicle should
// be able to move if the impact was large enough. Thus, there is also no logic
// to reset the sticky tire timers, for example. If the impact was small, the
// constraints should potentially kick in again in the subsequent sim step.
PxVehiclePhysXConstraintState& constraintState = physxConstraints.constraintStates[wheelId];
if (constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] ||
constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL] ||
constraintState.suspActiveStatus)
{
constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] = false;
constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL] = false;
constraintState.suspActiveStatus = false;
markConstraintsDirty = true;
}
}
if (markConstraintsDirty)
PxVehicleConstraintsDirtyStateUpdate(physxConstraints);
if (engineState)
{
PX_ASSERT(engineParams);
engineState->rotationSpeed = engineParams->idleOmega;
}
}
return isSleeping;
}
PX_FORCE_INLINE static void setWakeCounter(const PxReal wakeCounter, PxRigidDynamic* rd, PxArticulationLink* link)
{
if (rd && (!(rd->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
rd->setWakeCounter(wakeCounter);
}
else if (link)
{
link->getArticulation().setWakeCounter(wakeCounter);
}
}
void PxVehiclePhysxActorKeepAwakeCheck
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxReal wakeCounterThreshold,
const PxReal wakeCounterResetValue,
const PxVehicleGearboxState* gearState,
const PxReal* throttle,
PxRigidBody& physxActor)
{
PX_CHECK_AND_RETURN(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehiclePhysxActorKeepAwakeCheck: physxActor is kinematic. This is not supported");
PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
PxArticulationLink* link = physxActor.is<PxArticulationLink>();
PxReal wakeCounter = PX_MAX_REAL;
if (rd)
{
wakeCounter = rd->getWakeCounter();
}
else if (link)
{
wakeCounter = link->getArticulation().getWakeCounter();
}
if (wakeCounter < wakeCounterThreshold)
{
if ((throttle && ((*throttle) > 0.0f)) ||
(gearState && (gearState->currentGear != gearState->targetGear)))
{
setWakeCounter(wakeCounterResetValue, rd, link);
return;
}
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
const PxVehicleWheelParams& wheelParam = wheelParams[wheelId];
const PxVehicleWheelRigidBody1dState& wheelState = wheelRigidBody1dStates[wheelId];
// note: the translational part of the energy is ignored here as this is mainly for
// scenarios where there is almost no translation but the wheels are spinning
const PxReal normalizedEnergy = (0.5f * wheelState.correctedRotationSpeed * wheelState.correctedRotationSpeed *
wheelParam.moi) / wheelParam.mass;
PxReal sleepThreshold = PX_MAX_REAL;
if (rd)
{
sleepThreshold = rd->getSleepThreshold();
}
else if (link)
{
sleepThreshold = link->getArticulation().getSleepThreshold();
}
if (normalizedEnergy > sleepThreshold)
{
setWakeCounter(wakeCounterResetValue, rd, link);
return;
}
}
}
}
void PxVehicleReadRigidBodyStateFromPhysXActor
(const PxRigidBody& physxActor,
PxVehicleRigidBodyState& rigidBodyState)
{
PX_CHECK_AND_RETURN(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehicleReadRigidBodyStateFromPhysXActor: physxActor is kinematic. This is not supported");
const PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
const PxArticulationLink* link = physxActor.is<PxArticulationLink>();
PX_ASSERT(rd || link);
if(rd)
{
rigidBodyState.pose = physxActor.getGlobalPose()*physxActor.getCMassLocalPose();
rigidBodyState.angularVelocity = rd->getAngularVelocity();
rigidBodyState.linearVelocity = rd->getLinearVelocity();
}
else
{
rigidBodyState.pose = physxActor.getGlobalPose()*physxActor.getCMassLocalPose();
rigidBodyState.angularVelocity = link->getAngularVelocity();
rigidBodyState.linearVelocity = link->getLinearVelocity();
}
rigidBodyState.previousLinearVelocity = rigidBodyState.linearVelocity;
rigidBodyState.previousAngularVelocity = rigidBodyState.angularVelocity;
}
void PxVehicleWriteWheelLocalPoseToPhysXWheelShape
(const PxTransform& wheelLocalPose, const PxTransform& wheelShapeLocalPose, PxShape* shape)
{
if(!shape)
return;
PxRigidActor* ra = shape->getActor();
if(!ra)
return;
PxRigidBody* rb = ra->is<PxRigidBody>();
if(!rb)
return;
PX_CHECK_AND_RETURN(!(rb->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehicleWriteWheelLocalPoseToPhysXWheelShape: shape is attached to a kinematic actor. This is not supported");
//Local pose in actor frame.
const PxTransform& localPoseCMassFrame = wheelLocalPose*wheelShapeLocalPose;
const PxTransform cmassLocalPose = rb->getCMassLocalPose();
const PxTransform localPoseActorFrame = cmassLocalPose * localPoseCMassFrame;
//Apply the local pose to the shape.
shape->setLocalPose(localPoseActorFrame);
}
void PxVehicleWriteRigidBodyStateToPhysXActor
(const PxVehiclePhysXActorUpdateMode::Enum updateMode,
const PxVehicleRigidBodyState& rigidBodyState,
const PxReal dt,
PxRigidBody& rb)
{
PX_CHECK_AND_RETURN(!(rb.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehicleWriteRigidBodyStateToPhysXActor: physxActor is kinematic. This is not supported");
PxRigidDynamic* rd = rb.is<PxRigidDynamic>();
PxArticulationLink* link = rb.is<PxArticulationLink>();
PX_ASSERT(rd || link);
if(rb.getScene() && // check for scene to support immediate mode style vehicles
((rd && rd->isSleeping()) || (link && link->getArticulation().isSleeping())))
{
// note: sort of a safety mechanism to be able to keep running the full vehicle pipeline
// even if the physx actor fell asleep. Without it, the vehicle state can drift from
// physx actor state in the course of multiple simulation steps up to the point
// where the physx actor suddenly wakes up.
return;
}
switch (updateMode)
{
case PxVehiclePhysXActorUpdateMode::eAPPLY_VELOCITY:
{
PX_ASSERT(rd);
rd->setLinearVelocity(rigidBodyState.linearVelocity, false);
rd->setAngularVelocity(rigidBodyState.angularVelocity, false);
}
break;
case PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION:
{
const PxVec3 linAccel = (rigidBodyState.linearVelocity - rigidBodyState.previousLinearVelocity)/dt;
const PxVec3 angAccel = (rigidBodyState.angularVelocity - rigidBodyState.previousAngularVelocity)/dt;
if (rd)
{
rd->addForce(linAccel, PxForceMode::eACCELERATION, false);
rd->addTorque(angAccel, PxForceMode::eACCELERATION, false);
}
else
{
PX_ASSERT(link);
link->addForce(linAccel, PxForceMode::eACCELERATION, false);
link->addTorque(angAccel, PxForceMode::eACCELERATION, false);
}
}
break;
default:
break;
}
}
} //namespace vehicle2
} //namespace physx
| 13,124 |
C++
| 36.393162 | 200 | 0.770344 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxActor/VhPhysXActorHelpers.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorHelpers.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "cooking/PxCooking.h"
#include "PxPhysics.h"
#include "PxRigidDynamic.h"
#include "PxArticulationReducedCoordinate.h"
#include "PxArticulationLink.h"
#include "PxScene.h"
#include "extensions/PxDefaultStreams.h"
namespace physx
{
namespace vehicle2
{
void createShapes(
const PxVehicleFrame& vehicleFrame,
const PxVehiclePhysXRigidActorShapeParams& rigidActorShapeParams,
const PxVehiclePhysXWheelParams& wheelParams, const PxVehiclePhysXWheelShapeParams& wheelShapeParams,
PxRigidBody* rd,
PxPhysics& physics, const PxCookingParams& params,
PxVehiclePhysXActor& vehiclePhysXActor)
{
//Create a shape for the vehicle body.
{
PxShape* shape = physics.createShape(rigidActorShapeParams.geometry, rigidActorShapeParams.material, true);
shape->setLocalPose(rigidActorShapeParams.localPose);
shape->setFlags(rigidActorShapeParams.flags);
shape->setSimulationFilterData(rigidActorShapeParams.simulationFilterData);
shape->setQueryFilterData(rigidActorShapeParams.queryFilterData);
rd->attachShape(*shape);
shape->release();
}
//Create shapes for wheels.
for (PxU32 i = 0; i < wheelParams.axleDescription.nbWheels; i++)
{
const PxU32 wheelId = wheelParams.axleDescription.wheelIdsInAxleOrder[i];
const PxF32 radius = wheelParams.wheelParams[wheelId].radius;
const PxF32 halfWidth = wheelParams.wheelParams[wheelId].halfWidth;
PxVec3 verts[32];
for (PxU32 k = 0; k < 16; k++)
{
const PxF32 lng = radius * PxCos(k*2.0f*PxPi / 16.0f);
const PxF32 lat = halfWidth;
const PxF32 vrt = radius * PxSin(k*2.0f*PxPi / 16.0f);
const PxVec3 pos0 = vehicleFrame.getFrame()*PxVec3(lng, lat, vrt);
const PxVec3 pos1 = vehicleFrame.getFrame()*PxVec3(lng, -lat, vrt);
verts[2 * k + 0] = pos0;
verts[2 * k + 1] = pos1;
}
// Create descriptor for convex mesh
PxConvexMeshDesc convexDesc;
convexDesc.points.count = 32;
convexDesc.points.stride = sizeof(PxVec3);
convexDesc.points.data = verts;
convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX;
PxConvexMesh* convexMesh = NULL;
PxDefaultMemoryOutputStream buf;
if (PxCookConvexMesh(params, convexDesc, buf))
{
PxDefaultMemoryInputData id(buf.getData(), buf.getSize());
convexMesh = physics.createConvexMesh(id);
}
PxConvexMeshGeometry convexMeshGeom(convexMesh);
PxShape* wheelShape = physics.createShape(convexMeshGeom, wheelShapeParams.material, true);
wheelShape->setFlags(wheelShapeParams.flags);
wheelShape->setSimulationFilterData(wheelShapeParams.simulationFilterData);
wheelShape->setQueryFilterData(wheelShapeParams.queryFilterData);
rd->attachShape(*wheelShape);
wheelShape->release();
convexMesh->release();
vehiclePhysXActor.wheelShapes[wheelId] = wheelShape;
}
}
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)
{
PxRigidDynamic* rd = physics.createRigidDynamic(PxTransform(PxIdentity));
vehiclePhysXActor.rigidBody = rd;
PxVehiclePhysXActorConfigure(rigidActorParams, rigidActorCmassLocalPose, *rd);
createShapes(vehicleFrame, rigidActorShapeParams, wheelParams, wheelShapeParams, rd, physics, params, vehiclePhysXActor);
}
void PxVehiclePhysXActorConfigure
(const PxVehiclePhysXRigidActorParams& rigidActorParams, const PxTransform& rigidActorCmassLocalPose,
PxRigidBody& rigidBody)
{
rigidBody.setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, false);
rigidBody.setCMassLocalPose(rigidActorCmassLocalPose);
rigidBody.setMass(rigidActorParams.rigidBodyParams.mass);
rigidBody.setMassSpaceInertiaTensor(rigidActorParams.rigidBodyParams.moi);
rigidBody.setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true);
rigidBody.setName(rigidActorParams.physxActorName);
}
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)
{
PxArticulationReducedCoordinate* art = physics.createArticulationReducedCoordinate();
PxArticulationLink* link = art->createLink(NULL, PxTransform(PxIdentity));
vehiclePhysXActor.rigidBody = link;
PxVehiclePhysXActorConfigure(rigidActorParams, rigidActorCmassLocalPose, *link);
createShapes(vehicleFrame, rigidActorShapeParams, wheelParams, wheelShapeParams, link, physics, params, vehiclePhysXActor);
}
void PxVehiclePhysXActorDestroy
(PxVehiclePhysXActor& vehiclePhysXActor)
{
PxRigidDynamic* rd = vehiclePhysXActor.rigidBody->is<PxRigidDynamic>();
PxArticulationLink* link = vehiclePhysXActor.rigidBody->is<PxArticulationLink>();
if(rd)
{
rd->release();
vehiclePhysXActor.rigidBody = NULL;
}
else if(link)
{
PxArticulationReducedCoordinate& articulation = link->getArticulation();
PxScene* scene = articulation.getScene();
if(scene)
{
scene->removeArticulation(articulation);
}
articulation.release();
vehiclePhysXActor.rigidBody = NULL;
}
}
} //namespace vehicle2
} //namespace physx
| 7,572 |
C++
| 39.068783 | 124 | 0.795695 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/rigidBody/VhRigidBodyFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMat33.h"
#include "foundation/PxTransform.h"
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyFunctions.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
namespace physx
{
namespace vehicle2
{
PX_FORCE_INLINE void transformInertiaTensor(const PxVec3& invD, const PxMat33& M, PxMat33& mIInv)
{
const float axx = invD.x*M(0, 0), axy = invD.x*M(1, 0), axz = invD.x*M(2, 0);
const float byx = invD.y*M(0, 1), byy = invD.y*M(1, 1), byz = invD.y*M(2, 1);
const float czx = invD.z*M(0, 2), czy = invD.z*M(1, 2), czz = invD.z*M(2, 2);
mIInv(0, 0) = axx * M(0, 0) + byx * M(0, 1) + czx * M(0, 2);
mIInv(1, 1) = axy * M(1, 0) + byy * M(1, 1) + czy * M(1, 2);
mIInv(2, 2) = axz * M(2, 0) + byz * M(2, 1) + czz * M(2, 2);
mIInv(0, 1) = mIInv(1, 0) = axx * M(1, 0) + byx * M(1, 1) + czx * M(1, 2);
mIInv(0, 2) = mIInv(2, 0) = axx * M(2, 0) + byx * M(2, 1) + czx * M(2, 2);
mIInv(1, 2) = mIInv(2, 1) = axy * M(2, 0) + byy * M(2, 1) + czy * M(2, 2);
}
PX_FORCE_INLINE void integrateBody
(const PxF32 mass, const PxVec3& moi, const PxVec3& force, const PxVec3& torque, const PxF32 dt,
PxVec3& linvel, PxVec3& angvel, PxTransform& t)
{
const PxF32 inverseMass = 1.0f/mass;
const PxVec3 inverseMOI(1.0f/moi.x, 1.0f/moi.y, 1.0f/moi.z);
//Integrate linear velocity.
linvel += force * (inverseMass*dt);
//Integrate angular velocity.
PxMat33 inverseInertia;
transformInertiaTensor(inverseMOI, PxMat33(t.q), inverseInertia);
angvel += inverseInertia * (torque*dt);
//Integrate position.
t.p += linvel * dt;
//Integrate quaternion.
PxQuat wq(angvel.x, angvel.y, angvel.z, 0.0f);
PxQuat q = t.q;
PxQuat qdot = wq * q*(dt*0.5f);
q += qdot;
q.normalize();
t.q = q;
}
void PxVehicleRigidBodyUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleRigidBodyParams& rigidBodyParams,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxReal dt, const PxVec3& gravity,
PxVehicleRigidBodyState& rigidBodyState)
{
//Sum all the forces and torques.
const PxU32 nbAxles = axleDescription.getNbAxles();
PxVec3 force(PxZero);
PxVec3 torque(PxZero);
for (PxU32 i = 0; i < nbAxles; i++)
{
PxVec3 axleSuspForce(PxZero);
PxVec3 axleTireLongForce(PxZero);
PxVec3 axleTireLatForce(PxZero);
PxVec3 axleSuspTorque(PxZero);
PxVec3 axleTireLongTorque(PxZero);
PxVec3 axleTireLatTorque(PxZero);
for (PxU32 j = 0; j < axleDescription.getNbWheelsOnAxle(i); j++)
{
const PxU32 wheelId = axleDescription.getWheelOnAxle(j, i);
const PxVehicleSuspensionForce& suspForce = suspensionForces[wheelId];
const PxVehicleTireForce& tireForce = tireForces[wheelId];
axleSuspForce += suspForce.force;
axleTireLongForce += tireForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL];
axleTireLatForce += tireForce.forces[PxVehicleTireDirectionModes::eLATERAL];
axleSuspTorque += suspForce.torque;
axleTireLongTorque += tireForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL];
axleTireLatTorque += tireForce.torques[PxVehicleTireDirectionModes::eLATERAL];
}
const PxVec3 axleForce = axleSuspForce + axleTireLongForce + axleTireLatForce;
const PxVec3 axleTorque = axleSuspTorque + axleTireLongTorque + axleTireLatTorque;
force += axleForce;
torque += axleTorque;
}
force += gravity * rigidBodyParams.mass;
force += rigidBodyState.externalForce;
torque += rigidBodyState.externalTorque;
torque += (antiRollTorque ? antiRollTorque->antiRollTorque : PxVec3(PxZero));
//Rigid body params.
const PxF32 mass = rigidBodyParams.mass;
const PxVec3& moi = rigidBodyParams.moi;
//Perform the integration.
PxTransform& t = rigidBodyState.pose;
PxVec3& linvel = rigidBodyState.linearVelocity;
PxVec3& angvel = rigidBodyState.angularVelocity;
integrateBody(
mass, moi,
force, torque, dt,
linvel, angvel, t);
//Reset the accumulated external forces after using them.
rigidBodyState.externalForce = PxVec3(PxZero);
rigidBodyState.externalTorque = PxVec3(PxZero);
}
} //namespace vehicle2
} //namespace physx
| 6,054 |
C++
| 39.099337 | 99 | 0.736373 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/wheel/VhWheelFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "vehicle2/wheel/PxVehicleWheelFunctions.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleWheelRotationAngleUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleWheelActuationState& actState, const PxVehicleSuspensionState& suspState, const PxVehicleTireSpeedState& trSpeedState,
const PxReal thresholdForwardSpeedForWheelAngleIntegration, const PxReal dt,
PxVehicleWheelRigidBody1dState& whlRigidBody1dState)
{
//At low vehicle forward speeds we have some numerical difficulties getting the
//wheel rotation speeds to be correct due to the tire model's difficulties at low vz.
//The solution is to blend between the rolling speed at the wheel and the wheel's actual rotation speed.
//If the wheel is
//(i) in the air or,
//(ii) under braking torque or,
//(iii) driven by a drive torque
//then always use the wheel's actual rotation speed.
//Just to be clear, this means we will blend when the wheel
//(i) is on the ground and
//(ii) has no brake applied and
//(iii) has no drive torque and
//(iv) is at low forward speed
const PxF32 jounce = suspState.jounce;
const bool isBrakeApplied = actState.isBrakeApplied;
const bool isDriveApplied = actState.isDriveApplied;
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 absLngSpeed = PxAbs(lngSpeed);
PxF32 wheelOmega = whlRigidBody1dState.rotationSpeed;
if (jounce > 0 && //(i) wheel touching ground
!isBrakeApplied && //(ii) no brake applied
!isDriveApplied && //(iii) no drive torque applied
(absLngSpeed < thresholdForwardSpeedForWheelAngleIntegration)) //(iv) low speed
{
const PxF32 wheelRadius = whlParams.radius;
const PxF32 alpha = absLngSpeed / thresholdForwardSpeedForWheelAngleIntegration;
wheelOmega = (lngSpeed/wheelRadius)*(1.0f - alpha) + wheelOmega * alpha;
}
whlRigidBody1dState.correctedRotationSpeed = wheelOmega;
//Integrate angle.
PxF32 newRotAngle = whlRigidBody1dState.rotationAngle + wheelOmega * dt;
//Clamp in range (-2*Pi,2*Pi)
newRotAngle = newRotAngle - (PxI32(newRotAngle / PxTwoPi) * PxTwoPi);
//Set the angle.
whlRigidBody1dState.rotationAngle = newRotAngle;
}
} //namespace vehicle2
} //namespace physx
| 4,222 |
C++
| 44.408602 | 134 | 0.763382 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/suspension/VhSuspensionFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionFunctions.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
namespace physx
{
namespace vehicle2
{
#define VH_SUSPENSION_NO_INTERSECTION_MARKER FLT_MIN
PX_FORCE_INLINE void computeJounceAndSeparation(const PxF32 depth, const PxF32 suspDirDotPlaneNormal,
const PxF32 suspTravelDist, const PxF32 previousJounce,
PxF32& jounce, PxF32& separation)
{
if (suspDirDotPlaneNormal != 0.0f)
{
if (depth <= 0.0f)
{
//There is overlap at max droop
const PxF32 suspDeltaToDepthZero = depth / suspDirDotPlaneNormal;
if ((suspDeltaToDepthZero > 0.0f) && (suspDeltaToDepthZero <= suspTravelDist))
{
//The wheel can be placed on the plane for a jounce between max droop and max compression.
jounce = suspDeltaToDepthZero;
separation = 0.0f;
}
else
{
if (suspDeltaToDepthZero > suspTravelDist)
{
//There is overlap even at max compression. Compute the depth at max
//compression.
jounce = suspTravelDist;
separation = (depth * (suspDeltaToDepthZero - suspTravelDist)) / suspDeltaToDepthZero;
}
else
{
PX_ASSERT(suspDeltaToDepthZero <= 0.0f);
//There is overlap at max droop and in addition, the suspension would have to expand
//beyond max droop to move out of plane contact. This scenario can be reached, for
//example, if a car rolls over or if something touches a wheel from "above".
jounce = 0.0f;
separation = depth;
}
}
}
else
{
//At max droop there is no overlap => let the suspension fully expand.
//Note that this check is important because without it, you can get unexpected
//behavior like the wheel compressing just so that it touches the plane again.
jounce = 0.0f;
separation = VH_SUSPENSION_NO_INTERSECTION_MARKER;
}
}
else
{
//The suspension direction and hit normal are perpendicular, thus no change to
//suspension jounce will change the distance to the plane.
if (depth >= 0.0f)
{
jounce = 0.0f;
separation = VH_SUSPENSION_NO_INTERSECTION_MARKER;
}
else
{
jounce = (previousJounce != PX_VEHICLE_UNSPECIFIED_JOUNCE) ? previousJounce : suspTravelDist;
separation = depth;
// note: since The suspension direction and hit normal are perpendicular, the
// depth will be the same for all jounce values
}
}
}
PX_FORCE_INLINE void intersectRayPlane
(const PxVehicleFrame& frame, const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspParams,
const PxF32 steerAngle, const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxF32 previousJounce,
PxVec3& suspDir, PxF32& jounce, PxF32& separation)
{
//Compute the position on the wheel surface along the suspension direction that is closest to
//the plane (for the purpose of computing the separation from the plane). The wheel center position
//is chosen at max droop (zero jounce).
PxVehicleSuspensionState suspState;
suspState.setToDefault(0.0f);
const PxTransform wheelPose = PxVehicleComputeWheelPose(frame, suspParams, suspState, 0.0f, 0.0f, steerAngle,
rigidBodyState.pose, 0.0f);
suspDir = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
const PxPlane& hitPlane = roadGeomState.plane;
const PxF32 suspDirDotPlaneNormal = suspDir.dot(hitPlane.n);
PxVec3 wheelRefPoint;
if (suspDirDotPlaneNormal < 0.0f)
{
wheelRefPoint = wheelPose.p + (suspDir * wheelParams.radius);
//The "wheel bottom" has to be placed on the plane to resolve collision
}
else if (suspDirDotPlaneNormal > 0.0f)
{
wheelRefPoint = wheelPose.p - (suspDir * wheelParams.radius);
//The "wheel top" has to be placed on the plane to resolve collision
}
else
{
//The hit normal and susp dir are prependicular
//-> any point along the suspension direction will do to compute the depth
wheelRefPoint = wheelPose.p;
}
//Compute the penetration depth of the reference point with respect to the plane
const PxF32 depth = hitPlane.n.dot(wheelRefPoint) + hitPlane.d;
//How far along the susp dir do we have to move to place the wheel exactly on the plane.
computeJounceAndSeparation(depth, suspDirDotPlaneNormal, suspParams.suspensionTravelDist, previousJounce,
jounce, separation);
}
PX_FORCE_INLINE bool intersectPlanes(const PxPlane& a, const PxPlane& b, PxVec3& v, PxVec3& w)
{
const PxF32 n1x = a.n.x;
const PxF32 n1y = a.n.y;
const PxF32 n1z = a.n.z;
const PxF32 n1d = a.d;
const PxF32 n2x = b.n.x;
const PxF32 n2y = b.n.y;
const PxF32 n2z = b.n.z;
const PxF32 n2d = b.d;
PxF32 dx = (n1y * n2z) - (n1z * n2y);
PxF32 dy = (n1z * n2x) - (n1x * n2z);
PxF32 dz = (n1x * n2y) - (n1y * n2x);
const PxF32 dx2 = dx * dx;
const PxF32 dy2 = dy * dy;
const PxF32 dz2 = dz * dz;
PxF32 px, py, pz;
if ((dz2 > dy2) && (dz2 > dx2) && (dz2 > 0))
{
px = ((n1y * n2d) - (n2y * n1d)) / dz;
py = ((n2x * n1d) - (n1x * n2d)) / dz;
pz = 0;
}
else if ((dy2 > dx2) && (dy2 > 0))
{
px = -((n1z * n2d) - (n2z * n1d)) / dy;
py = 0;
pz = -((n2x * n1d) - (n1x * n2d)) / dy;
}
else if (dx2 > 0)
{
px = 0;
py = ((n1z * n2d) - (n2z * n1d)) / dx;
pz = ((n2y * n1d) - (n1y * n2d)) / dx;
}
else
{
px = 0;
py = 0;
pz = 0;
return false;
}
const PxF32 ld = PxSqrt(dx2 + dy2 + dz2);
dx /= ld;
dy /= ld;
dz /= ld;
w = PxVec3(dx, dy, dz);
v = PxVec3(px, py, pz);
return true;
}
// This method computes how much a wheel cylinder object at max droop (fully elongated suspension)
// has to be pushed along the suspension direction to end up just touching the plane provided in
// the road geometry state.
//
// output:
// suspDir: suspension direction in the world frame
// jounce: the suspension jounce.
// jounce=0 the wheel is at max droop
// jounce>0 the suspension is compressed by length jounce (up to max compression = suspensionTravelDist)
//
// The jounce value will be set to 0 (in the case of no overlap) or to the previous jounce
// (in the case of overlap) for the following special cases:
// - the plane normal and the wheel lateral axis are parallel
// - the plane normal and the suspension direction are perpendicular
// separation: 0 if the suspension can move between max droop and max compression to place
// the wheel on the ground.
// A negative value denotes by how much the wheel cylinder penetrates (along the hit
// plane normal) into the ground for the computed jounce.
// A positive value denotes that the wheel does not touch the ground.
//
PX_FORCE_INLINE void intersectCylinderPlane
(const PxVehicleFrame& frame,
const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams,
const PxF32 steerAngle, const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxF32 previousJounce,
PxVec3& suspDir, PxF32& jounce, PxF32& separation)
{
const PxPlane& hitPlane = roadGeomState.plane;
const PxF32 radius = whlParams.radius;
const PxF32 halfWidth = whlParams.halfWidth;
//Compute the wheel pose at zero jounce ie at max droop.
PxTransform wheelPoseAtZeroJounce;
{
PxTransform start;
PxF32 dist;
PxVehicleComputeSuspensionSweep(frame, suspParams, steerAngle, rigidBodyState.pose, start, suspDir, dist);
wheelPoseAtZeroJounce = PxTransform(start.p + suspDir*dist, start.q);
}
//Compute the plane of the wheel.
PxPlane wheelPlane;
{
wheelPlane = PxPlane(wheelPoseAtZeroJounce.p, wheelPoseAtZeroJounce.rotate(frame.getLatAxis()));
}
//Intersect the plane of the wheel with the hit plane.
//This generates an intersection edge.
PxVec3 intersectionEdgeV, intersectionEdgeW;
const bool intersectPlaneSuccess = intersectPlanes(wheelPlane, hitPlane, intersectionEdgeV, intersectionEdgeW);
PxF32 depth;
if (intersectPlaneSuccess)
{
//Compute the position on the intersection edge that is closest to the wheel centre.
PxVec3 closestPointOnIntersectionEdge;
{
const PxVec3& p = wheelPoseAtZeroJounce.p;
const PxVec3& dir = intersectionEdgeW;
const PxVec3& v = intersectionEdgeV;
const PxF32 t = (p - v).dot(dir);
closestPointOnIntersectionEdge = v + dir * t;
}
//Compute the vector that joins the wheel centre to the intersection edge;
PxVec3 dir;
{
const PxF32 wheelCentreD = hitPlane.n.dot(wheelPoseAtZeroJounce.p) + hitPlane.d;
dir = ((wheelCentreD >= 0) ? closestPointOnIntersectionEdge - wheelPoseAtZeroJounce.p : wheelPoseAtZeroJounce.p - closestPointOnIntersectionEdge);
dir.normalize();
}
//Compute the point on the disc diameter that will be the closest to the hit plane or the deepest inside the hit plane.
const PxVec3 pos = wheelPoseAtZeroJounce.p + dir*radius;
//Now compute the maximum depth of the inside and outside discs against the plane.
{
const PxVec3& latDir = wheelPlane.n;
const PxF32 signDot = PxVehicleComputeSign(hitPlane.n.dot(latDir));
const PxVec3 deepestPos = pos - latDir * (signDot*halfWidth);
depth = hitPlane.n.dot(deepestPos) + hitPlane.d;
}
}
else
{
//The hit plane normal and the wheel lateral axis are parallel
//Now compute the maximum depth of the inside and outside discs against the plane.
const PxVec3& latDir = wheelPlane.n;
const PxF32 signDot = PxVehicleComputeSign(hitPlane.n.dot(latDir));
depth = hitPlane.d - halfWidth - (signDot*wheelPlane.d);
// examples:
// halfWidth = 0.5
//
// wheelPlane.d hitplane.d depth
//=============================================
// -3 -> -3.5 -> -1
// 3 <- -3.5 -> -1
//
// -3 -> 3.5 <- 0
// 3 <- 3.5 <- 0
//
}
//How far along the susp dir do we have to move to place the wheel exactly on the plane.
const PxF32 suspDirDotPlaneNormal = hitPlane.n.dot(suspDir);
computeJounceAndSeparation(depth, suspDirDotPlaneNormal, suspParams.suspensionTravelDist, previousJounce,
jounce, separation);
}
static void limitSuspensionExpansionVelocity
(const PxReal jounceSpeed, const PxReal previousJounceSpeed, const PxReal previousJounce,
const PxReal suspStiffness, const PxReal suspDamping,
const PxVec3& suspDirWorld, const PxReal wheelMass,
const PxReal dt, const PxVec3& gravity, const bool hasGroundHit,
PxVehicleSuspensionState& suspState)
{
PX_ASSERT(jounceSpeed < 0.0f); // don't call this method if the suspension is not expanding
// The suspension is expanding. Check if the suspension can expand fast enough to actually reach the
// target jounce within the given time step.
// Without the suspension elongating, the wheel would end up in the air. Compute the suspension force
// that pushes the wheel towards the ground. Note that gravity is ignored here as it applies to sprung
// mass and wheel equally.
const PxReal springForceAlongSuspDir = (previousJounce * suspStiffness);
const PxReal suspDirVelSpring = (springForceAlongSuspDir / wheelMass) * dt;
const PxReal dampingForceAlongSuspDir = (previousJounceSpeed * suspDamping); // note: negative jounce speed = expanding
const PxReal suspDirVelDamping = (dampingForceAlongSuspDir / wheelMass) * dt;
PxReal suspDirVel = suspDirVelSpring - previousJounceSpeed;
// add damping part but such that it does not flip the velocity sign (covering case of
// crazily high damping values)
const PxReal suspDirVelTmp = suspDirVel + suspDirVelDamping;
if (suspDirVel >= 0.0f)
suspDirVel = PxMax(0.0f, suspDirVelTmp);
else
suspDirVel = PxMin(0.0f, suspDirVelTmp);
const PxReal gravitySuspDir = gravity.dot(suspDirWorld);
PxReal velocityThreshold;
if (hasGroundHit)
{
velocityThreshold = (gravitySuspDir > 0.0f) ? suspDirVel + (gravitySuspDir * dt) : suspDirVel;
// gravity is considered too as it affects the wheel and can close the distance to the ground
// too. External forces acting on the sprung mass are ignored as those propagate
// through the suspension to the wheel.
// If gravity points in the opposite direction of the suspension travel direction, it is
// ignored. The suspension should never elongate more than what's given by the current delta
// jounce (defined by jounceSpeed, i.e., jounceSpeed < -suspDirVel has to hold all the time
// for the clamping to take place).
}
else
{
velocityThreshold = suspDirVel;
// if there was no hit detected, the gravity will not be taken into account since there is no
// ground to move towards.
}
if (jounceSpeed < (-velocityThreshold))
{
// The suspension can not expand fast enough to place the wheel on the ground. As a result,
// the scenario is interpreted as if there was no hit and the wheels end up in air. The
// jounce is adjusted based on the clamped velocity to not have it snap to the target immediately.
// note: could consider applying the suspension force to the sprung mass too but the complexity
// seems high enough already.
const PxReal expansionDelta = suspDirVel * dt;
const PxReal clampedJounce = previousJounce - expansionDelta;
PX_ASSERT(clampedJounce >= 0.0f);
// No need to cover the case of a negative jounce as the input jounce speed is expected to make
// sure that no negative jounce would result (and the speed considered here is smaller than the
// non-clamped input jounce speed).
if (suspState.separation >= 0.0f) // do not adjust separation if ground penetration was detected
{
suspState.separation = clampedJounce - suspState.jounce;
}
suspState.jounce = clampedJounce;
suspState.jounceSpeed = -suspDirVel;
}
}
void PxVehicleSuspensionStateUpdate
(const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams, const PxVehicleSuspensionStateCalculationParams& suspStateCalcParams,
const PxReal suspStiffness, const PxReal suspDamping,
const PxF32 steerAngle, const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxReal dt, const PxVehicleFrame& frame, const PxVec3& gravity,
PxVehicleSuspensionState& suspState)
{
const PxReal prevJounce = suspState.jounce;
const PxReal prevJounceSpeed = suspState.jounceSpeed;
suspState.setToDefault(0.0f, VH_SUSPENSION_NO_INTERSECTION_MARKER);
if(!roadGeomState.hitState)
{
if (suspStateCalcParams.limitSuspensionExpansionVelocity && (prevJounce != PX_VEHICLE_UNSPECIFIED_JOUNCE))
{
if (prevJounce > 0.0f)
{
PX_ASSERT(suspState.jounce == 0.0f); // the expectation is that setToDefault() above does this
const PxReal jounceSpeed = (-prevJounce) / dt;
const PxVec3 suspDirWorld = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
limitSuspensionExpansionVelocity(jounceSpeed, prevJounceSpeed, prevJounce,
suspStiffness, suspDamping, suspDirWorld, whlParams.mass, dt, gravity, false,
suspState);
}
}
return;
}
PxVec3 suspDir;
PxF32 currJounce;
PxF32 separation;
switch(suspStateCalcParams.suspensionJounceCalculationType)
{
case PxVehicleSuspensionJounceCalculationType::eRAYCAST:
{
//Compute the distance along the suspension direction that places the wheel on the ground plane.
intersectRayPlane(frame, whlParams, suspParams, steerAngle, roadGeomState, rigidBodyState,
prevJounce,
suspDir, currJounce, separation);
}
break;
case PxVehicleSuspensionJounceCalculationType::eSWEEP:
{
//Compute the distance along the suspension direction that places the wheel on the ground plane.
intersectCylinderPlane(frame, whlParams, suspParams, steerAngle, roadGeomState, rigidBodyState,
prevJounce,
suspDir, currJounce, separation);
}
break;
default:
{
PX_ASSERT(false);
currJounce = 0.0f;
separation = VH_SUSPENSION_NO_INTERSECTION_MARKER;
}
break;
}
suspState.jounce = currJounce;
suspState.jounceSpeed = (PX_VEHICLE_UNSPECIFIED_JOUNCE != prevJounce) ? (currJounce - prevJounce) / dt : 0.0f;
suspState.separation = separation;
if (suspStateCalcParams.limitSuspensionExpansionVelocity && (suspState.jounceSpeed < 0.0f))
{
limitSuspensionExpansionVelocity(suspState.jounceSpeed, prevJounceSpeed, prevJounce,
suspStiffness, suspDamping, suspDir, whlParams.mass, dt, gravity, true,
suspState);
}
}
void PxVehicleSuspensionComplianceUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionComplianceParams& compParams,
const PxVehicleSuspensionState& suspState,
PxVehicleSuspensionComplianceState& compState)
{
compState.setToDefault();
//Compliance is normalised in range (0,1) with:
//0 being fully elongated (ie jounce = 0)
//1 being fully compressed (ie jounce = maxTravelDist)
const PxF32 jounce = suspState.jounce;
const PxF32 maxTravelDist = suspParams.suspensionTravelDist;
const PxF32 r = jounce/maxTravelDist;
//Camber and toe relative the wheel reference pose.
{
compState.camber = compParams.wheelCamberAngle.interpolate(r);
compState.toe = compParams.wheelToeAngle.interpolate(r);
}
//Tire force application point as an offset from wheel reference pose.
{
compState.tireForceAppPoint = compParams.tireForceAppPoint.interpolate(r);
}
//Susp force application point as an offset from wheel reference pose.
{
compState.suspForceAppPoint = compParams.suspForceAppPoint.interpolate(r);
}
}
PX_FORCE_INLINE void setSuspensionForceAndTorque
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState,
const PxF32 suspForceMagnitude, const PxF32 normalForceMagnitude,
PxVehicleSuspensionForce& suspForce)
{
const PxVec3 r = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.transform(suspComplianceState.suspForceAppPoint));
const PxVec3 f = roadGeomState.plane.n*suspForceMagnitude;
suspForce.force = f;
suspForce.torque = r.cross(f);
suspForce.normalForce = normalForceMagnitude;
}
void PxVehicleSuspensionForceUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionForceParams& suspForceParams,
const PxVehicleRoadGeometryState& roadGeom, const PxVehicleSuspensionState& suspState,
const PxVehicleSuspensionComplianceState& compState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVec3& gravity, const PxReal vehicleMass,
PxVehicleSuspensionForce& suspForces)
{
suspForces.setToDefault();
//If the wheel cannot touch the ground then carry on with zero force.
if (!PxVehicleIsWheelOnGround(suspState))
return;
//For the following computations, the external force Fe acting on the suspension
//is seen as the sum of two forces Fe0 and Fe1. Fe0 acts along the suspension
//direction while Fe1 is the part perpendicular to Fe0. The suspension spring
//force Fs0 works against Fe0, while the suspension "collision" force Fs1 works
//against Fe1 (can be seen as a force that is trying to push the suspension
//into the ground in a direction where the spring can not do anything against
//it because it's perpendicular to the spring direction).
//For the system to be at rest, we require Fs0 = -Fe0 and Fs1 = -Fe1
//The forces Fe0 and Fe1 can each be split further into parts that act along
//the ground patch normal and parts that act parallel to the ground patch.
//Fs0 and Fs1 work against the former as the ground prevents the suspension
//from penetrating. However, to work against the latter, friction would have
//to be considered. The current model does not do this (or rather: it is the
//tire model that deals with forces parallel to the ground patch). As a result,
//only the force parts of Fs0 and Fs1 perpendicular to the ground patch are
//considered here. Furthermore, Fs1 is set to zero, if the external force is
//not pushing the suspension towards the ground patch (imagine a vehicle with
//a "tilted" suspension direction "driving" up a wall. No "collision" force
//should be added in such a scenario).
PxF32 suspForceMagnitude = 0.0f;
{
const PxF32 jounce = suspState.jounce;
const PxF32 stiffness = suspForceParams.stiffness;
const PxF32 jounceSpeed = suspState.jounceSpeed;
const PxF32 damping = suspForceParams.damping;
const PxVec3 suspDirWorld = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
const PxVec3 suspSpringForce = suspDirWorld * (-(jounce*stiffness + jounceSpeed*damping));
const PxF32 suspSpringForceProjected = roadGeom.plane.n.dot(suspSpringForce);
suspForceMagnitude = suspSpringForceProjected;
const PxVec3 comToSuspWorld = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.p);
const PxVec3 externalForceLin = (gravity * vehicleMass) + rigidBodyState.externalForce;
const PxReal comToSuspDistSqr = comToSuspWorld.magnitudeSquared();
PxVec3 externalForceAng;
if (comToSuspDistSqr > 0.0f)
{
// t = r x F
// t x r = (r x F) x r = -[r x (r x F)] = -[((r o F) * r) - ((r o r) * F)]
// r and F perpendicular (r o F = 0) => = (r o r) * F = |r|^2 * F
externalForceAng = (rigidBodyState.externalTorque.cross(comToSuspWorld)) / comToSuspDistSqr;
}
else
externalForceAng = PxVec3(PxZero);
const PxVec3 externalForce = externalForceLin + externalForceAng;
const PxVec3 externalForceSusp = externalForce * (suspForceParams.sprungMass / vehicleMass);
if (roadGeom.plane.n.dot(externalForceSusp) < 0.0f)
{
const PxF32 suspDirExternalForceMagn = suspDirWorld.dot(externalForceSusp);
const PxVec3 collisionForce = externalForceSusp - (suspDirWorld * suspDirExternalForceMagn);
const PxF32 suspCollisionForceProjected = -roadGeom.plane.n.dot(collisionForce);
suspForceMagnitude += suspCollisionForceProjected;
}
}
setSuspensionForceAndTorque(suspParams, roadGeom, compState, rigidBodyState, suspForceMagnitude, suspForceMagnitude, suspForces);
}
void PxVehicleSuspensionLegacyForceUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionForceLegacyParams& suspForceParamsLegacy,
const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleSuspensionState& suspState,
const PxVehicleSuspensionComplianceState& compState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVec3& gravity,
PxVehicleSuspensionForce& suspForces)
{
suspForces.setToDefault();
//If the wheel cannot touch the ground then carry on with zero force.
if (!PxVehicleIsWheelOnGround(suspState))
return;
PxF32 suspForceMagnitude = 0.0f;
{
//Get the params for the legacy model.
//const PxF32 restDistance = suspForceParamsLegacy.restDistance;
const PxF32 sprungMass = suspForceParamsLegacy.sprungMass;
const PxF32 restDistance = suspForceParamsLegacy.restDistance;
//Get the non-legacy params.
const PxF32 stiffness = suspForceParamsLegacy.stiffness;
const PxF32 damperRate = suspForceParamsLegacy.damping;
const PxF32 maxTravelDist = suspParams.suspensionTravelDist;
//Suspension state.
const PxF32 jounce = suspState.jounce;
const PxF32 jounceSpeed = suspState.jounceSpeed;
//Decompose gravity into a term along w and a term perpendicular to w
//gravity = w*alpha + T*beta
//where T is a unit vector perpendicular to w; alpha and beta are scalars.
//The vector w*alpha*mass is the component of gravitational force that acts along the spring direction.
//The vector T*beta*mass is the component of gravitational force that will be resisted by the spring
//because the spring only supports a single degree of freedom along w.
//We only really need to know T*beta so don't bother calculating T or beta.
const PxVec3 w = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
const PxF32 gravitySuspDir = gravity.dot(w);
const PxF32 alpha = PxMax(0.0f, gravitySuspDir);
const PxVec3 TTimesBeta = (0.0f != alpha) ? gravity - w * alpha : PxVec3(0, 0, 0);
//Compute the magnitude of the force along w.
PxF32 suspensionForceW =
PxMax(0.0f,
sprungMass*alpha + //force to support sprung mass at zero jounce
stiffness*(jounce + restDistance - maxTravelDist)); //linear spring
suspensionForceW += jounceSpeed * damperRate; //damping
//Compute the total force acting on the suspension.
//Remember that the spring force acts along -w.
//Remember to account for the term perpendicular to w and that it acts along -TTimesBeta
suspForceMagnitude = roadGeomState.plane.n.dot(-w * suspensionForceW - TTimesBeta * sprungMass);
}
setSuspensionForceAndTorque(suspParams, roadGeomState, compState, rigidBodyState, suspForceMagnitude, suspForceMagnitude, suspForces);
}
void PxVehicleAntiRollForceUpdate
(const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams,
const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& complianceStates,
const PxVehicleRigidBodyState& rigidBodyState,
PxVehicleAntiRollTorque& antiRollTorque)
{
antiRollTorque.setToDefault();
for (PxU32 i = 0; i < antiRollParams.size; i++)
{
if (antiRollParams[i].stiffness != 0.0f)
{
const PxU32 w0 = antiRollParams[i].wheel0;
const PxU32 w1 = antiRollParams[i].wheel1;
const bool w0InAir = (0.0f == suspensionStates[w0].jounce);
const bool w1InAir = (0.0f == suspensionStates[w1].jounce);
if (!w0InAir || !w1InAir)
{
//Compute the difference in jounce and compute the force.
const PxF32 w0Jounce = suspensionStates[w0].jounce;
const PxF32 w1Jounce = suspensionStates[w1].jounce;
const PxF32 antiRollForceMag = (w0Jounce - w1Jounce) * antiRollParams[i].stiffness;
//Apply the antiRollForce postiviely to wheel0, negatively to wheel 1
PxU32 wheelIds[2] = { 0xffffffff, 0xffffffff };
PxF32 antiRollForceMags[2];
PxU32 numWheelIds = 0;
if (!w0InAir)
{
wheelIds[numWheelIds] = w0;
antiRollForceMags[numWheelIds] = -antiRollForceMag;
numWheelIds++;
}
if (!w1InAir)
{
wheelIds[numWheelIds] = w1;
antiRollForceMags[numWheelIds] = +antiRollForceMag;
numWheelIds++;
}
for (PxU32 j = 0; j < numWheelIds; j++)
{
const PxU32 wheelId = wheelIds[j];
const PxVec3& antiRollForceDir = suspensionParams[wheelId].suspensionTravelDir;
const PxVec3 antiRollForce = antiRollForceDir * antiRollForceMags[j];
const PxVec3 r = suspensionParams[wheelId].suspensionAttachment.transform(complianceStates[wheelId].suspForceAppPoint);
antiRollTorque.antiRollTorque += rigidBodyState.pose.rotate(r.cross(antiRollForce));
}
}
}
}
}
} //namespace vehicle2
} //namespace physx
| 28,511 |
C++
| 38.710306 | 160 | 0.746344 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/suspension/VhSuspensionHelpers.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleMaths.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
namespace physx
{
namespace vehicle2
{
#define DETERMINANT_THRESHOLD (1e-6f)
bool PxVehicleComputeSprungMasses(const PxU32 numSprungMasses, const PxVec3* sprungMassCoordinates, const PxReal totalMass, const PxVehicleAxes::Enum gravityDir, PxReal* sprungMasses)
{
if (numSprungMasses < 1)
return false;
if (numSprungMasses > PxVehicleLimits::eMAX_NB_WHEELS)
return false;
if (totalMass <= 0.0f)
return false;
if (!sprungMassCoordinates || !sprungMasses)
return false;
const PxVec3 centreOfMass(PxZero);
PxU32 gravityDirection = 0xffffffff;
switch (gravityDir)
{
case PxVehicleAxes::eNegX:
case PxVehicleAxes::ePosX:
gravityDirection = 0;
break;
case PxVehicleAxes::eNegY:
case PxVehicleAxes::ePosY:
gravityDirection = 1;
break;
case PxVehicleAxes::eNegZ:
case PxVehicleAxes::ePosZ:
gravityDirection = 2;
break;
default:
PX_ASSERT(false);
break;
}
if (1 == numSprungMasses)
{
sprungMasses[0] = totalMass;
}
else if (2 == numSprungMasses)
{
PxVec3 v = sprungMassCoordinates[0];
v[gravityDirection] = 0;
PxVec3 w = sprungMassCoordinates[1] - sprungMassCoordinates[0];
w[gravityDirection] = 0;
w.normalize();
PxVec3 cm = centreOfMass;
cm[gravityDirection] = 0;
PxF32 t = w.dot(cm - v);
PxVec3 p = v + w * t;
PxVec3 x0 = sprungMassCoordinates[0];
x0[gravityDirection] = 0;
PxVec3 x1 = sprungMassCoordinates[1];
x1[gravityDirection] = 0;
const PxF32 r0 = (x0 - p).dot(w);
const PxF32 r1 = (x1 - p).dot(w);
if (PxAbs(r0 - r1) <= DETERMINANT_THRESHOLD)
return false;
const PxF32 m0 = totalMass * r1 / (r1 - r0);
const PxF32 m1 = totalMass - m0;
sprungMasses[0] = m0;
sprungMasses[1] = m1;
}
else if (3 == numSprungMasses)
{
const PxU32 d0 = (gravityDirection + 1) % 3;
const PxU32 d1 = (gravityDirection + 2) % 3;
PxVehicleMatrixNN A(3);
PxVehicleVectorN b(3);
A.set(0, 0, sprungMassCoordinates[0][d0]);
A.set(0, 1, sprungMassCoordinates[1][d0]);
A.set(0, 2, sprungMassCoordinates[2][d0]);
A.set(1, 0, sprungMassCoordinates[0][d1]);
A.set(1, 1, sprungMassCoordinates[1][d1]);
A.set(1, 2, sprungMassCoordinates[2][d1]);
A.set(2, 0, 1.f);
A.set(2, 1, 1.f);
A.set(2, 2, 1.f);
b[0] = totalMass * centreOfMass[d0];
b[1] = totalMass * centreOfMass[d1];
b[2] = totalMass;
PxVehicleVectorN result(3);
PxVehicleMatrixNNLUSolver solver;
solver.decomposeLU(A);
if (PxAbs(solver.getDet()) <= DETERMINANT_THRESHOLD)
return false;
solver.solve(b, result);
sprungMasses[0] = result[0];
sprungMasses[1] = result[1];
sprungMasses[2] = result[2];
}
else if (numSprungMasses >= 4)
{
const PxU32 d0 = (gravityDirection + 1) % 3;
const PxU32 d1 = (gravityDirection + 2) % 3;
const PxF32 mbar = totalMass / (numSprungMasses*1.0f);
//See http://en.wikipedia.org/wiki/Lagrange_multiplier
//particularly the section on multiple constraints.
//3 Constraint equations.
//g0 = sum_ xi*mi=xcm
//g1 = sum_ zi*mi=zcm
//g2 = sum_ mi = totalMass
//Minimisation function to achieve solution with minimum mass variance.
//f = sum_ (mi - mave)^2
//Lagrange terms (N equations, N+3 unknowns)
//2*mi - xi*lambda0 - zi*lambda1 - 1*lambda2 = 2*mave
PxVehicleMatrixNN A(numSprungMasses + 3);
PxVehicleVectorN b(numSprungMasses + 3);
//g0, g1, g2
for (PxU32 i = 0; i < numSprungMasses; i++)
{
A.set(0, i, sprungMassCoordinates[i][d0]); //g0
A.set(1, i, sprungMassCoordinates[i][d1]); //g1
A.set(2, i, 1.0f); //g2
}
for (PxU32 i = numSprungMasses; i < numSprungMasses + 3; i++)
{
A.set(0, i, 0); //g0 independent of lambda0,lambda1,lambda2
A.set(1, i, 0); //g1 independent of lambda0,lambda1,lambda2
A.set(2, i, 0); //g2 independent of lambda0,lambda1,lambda2
}
b[0] = totalMass * (centreOfMass[d0]); //g0
b[1] = totalMass * (centreOfMass[d1]); //g1
b[2] = totalMass; //g2
//Lagrange terms.
for (PxU32 i = 0; i < numSprungMasses; i++)
{
//Off-diagonal terms from the derivative of f
for (PxU32 j = 0; j < numSprungMasses; j++)
{
A.set(i + 3, j, 0);
}
//Diagonal term from the derivative of f
A.set(i + 3, i, 2.f);
//Derivative of g
A.set(i + 3, numSprungMasses + 0, sprungMassCoordinates[i][d0]);
A.set(i + 3, numSprungMasses + 1, sprungMassCoordinates[i][d1]);
A.set(i + 3, numSprungMasses + 2, 1.0f);
//rhs.
b[i + 3] = 2 * mbar;
}
//Solve Ax=b
PxVehicleVectorN result(numSprungMasses + 3);
PxVehicleMatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b, result);
if (PxAbs(solver.getDet()) <= DETERMINANT_THRESHOLD)
return false;
for (PxU32 i = 0; i < numSprungMasses; i++)
{
sprungMasses[i] = result[i];
}
}
return true;
}
} //namespace vehicle2
} //namespace physx
| 6,768 |
C++
| 30.483721 | 184 | 0.671395 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/tire/VhTireFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
#include "vehicle2/tire/PxVehicleTireFunctions.h"
#include "vehicle2/tire/PxVehicleTireParams.h"
#include "vehicle2/wheel/PxVehicleWheelHelpers.h"
namespace physx
{
namespace vehicle2
{
PX_FORCE_INLINE PxF32 computeFilteredNormalisedTireLoad
(const PxF32 xmin, const PxF32 ymin, const PxF32 xmax, const PxF32 ymax, const PxF32 x)
{
if (x <= xmin)
{
return ymin;
}
else if (x >= xmax)
{
return ymax;
}
else
{
return (ymin + (x - xmin)*(ymax - ymin)/ (xmax - xmin));
}
}
void PxVehicleTireDirsLegacyUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxReal steerAngle, const PxVehicleRoadGeometryState& rdGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVehicleFrame& frame,
PxVehicleTireDirectionState& trSlipDirs)
{
trSlipDirs.setToDefault();
//If there are no hits we'll have no ground plane.
if (!rdGeomState.hitState)
return;
//Compute wheel orientation with zero compliance, zero steer and zero
//rotation. Ignore rotation because it plays no role due to radial
//symmetry of wheel. Steer will be applied to the pose so we can
//ignore when computing the orientation. Compliance ought to be applied but
//we're not doing this in legacy code.
const PxQuat wheelOrientation = PxVehicleComputeWheelOrientation(frame, suspParams, 0.0f, 0.0f, 0.0f,
rigidBodyState.pose.q, 0.0f);
//We need lateral dir and hit norm to project wheel into ground plane.
const PxVec3 latDir = wheelOrientation.rotate(frame.getLatAxis());
const PxVec3& hitNorm = rdGeomState.plane.n;
//Compute the tire axes in the ground plane.
PxVec3 tLongRaw = latDir.cross(hitNorm);
PxVec3 tLatRaw = hitNorm.cross(tLongRaw);
tLongRaw.normalize();
tLatRaw.normalize();
//Rotate the tire using the steer angle.
const PxF32 yawAngle = steerAngle;
const PxF32 cosWheelSteer = PxCos(yawAngle);
const PxF32 sinWheelSteer = PxSin(yawAngle);
const PxVec3 tLong = tLongRaw * cosWheelSteer + tLatRaw * sinWheelSteer;
const PxVec3 tLat = tLatRaw * cosWheelSteer - tLongRaw * sinWheelSteer;
trSlipDirs.directions[PxVehicleTireDirectionModes::eLATERAL] = tLat;
trSlipDirs.directions[PxVehicleTireDirectionModes::eLONGITUDINAL] = tLong;
}
void PxVehicleTireDirsUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxReal steerAngle, const PxVec3& groundNormal, bool isWheelOnGround,
const PxVehicleSuspensionComplianceState& compState,
const PxVehicleRigidBodyState& rigidBodyState,
const PxVehicleFrame& frame,
PxVehicleTireDirectionState& trSlipDirs)
{
trSlipDirs.setToDefault();
//Skip if the suspension could not push the wheel to the ground.
if (!isWheelOnGround)
return;
//Compute the wheel quaternion in the world frame.
//Ignore rotation because it plays no role due to radial symmetry of wheel.
const PxQuat wheelOrientation = PxVehicleComputeWheelOrientation(frame, suspParams, compState.camber, compState.toe, steerAngle,
rigidBodyState.pose.q, 0.0f);
//We need lateral dir and hit norm to project wheel into ground plane.
const PxVec3 latDir = wheelOrientation.rotate(frame.getLatAxis());
//Compute the tire axes in the ground plane.
PxVec3 lng = latDir.cross(groundNormal);
PxVec3 lat = groundNormal.cross(lng);
lng.normalize();
lat.normalize();
//Set the direction vectors.
trSlipDirs.directions[PxVehicleTireDirectionModes::eLATERAL] = lat;
trSlipDirs.directions[PxVehicleTireDirectionModes::eLONGITUDINAL] = lng;
}
PX_FORCE_INLINE PxF32 computeLateralSlip
(const PxF32 lngSpeed, const PxF32 latSpeed, const PxF32 minLatSlipDenominator)
{
const PxF32 latSlip = PxAtan(latSpeed / (PxAbs(lngSpeed) + minLatSlipDenominator));
return latSlip;
}
PX_FORCE_INLINE PxF32 computeLongitudionalSlip
(const bool useLegacyLongSlipCalculation,
const PxF32 longSpeed,
const PxF32 wheelOmega, const PxF32 wheelRadius,
const PxF32 minPassiveLongSlipDenominator, const PxF32 minActiveLongSlipDenominator,
const bool isAccelApplied, const bool isBrakeApplied)
{
const PxF32 longSpeedAbs = PxAbs(longSpeed);
const PxF32 wheelSpeed = wheelOmega * wheelRadius;
const PxF32 wheelSpeedAbs = PxAbs(wheelSpeed);
PxF32 lngSlip = 0.0f;
//If nothing is moving just avoid a divide by zero and set the long slip to zero.
if (longSpeed == 0 && wheelOmega == 0)
{
lngSlip = 0.0f;
}
else
{
if (isBrakeApplied || isAccelApplied)
{
//Wheel experiencing an applied torque.
//Use the raw denominator value plus an offset to avoid anything approaching a divide by zero.
//When accelerating from rest the small denominator will generate really quite large
//slip values, which will, in turn, generate large longitudinal forces. With large
//time-steps this might lead to a temporary oscillation in longSlip direction and an
//oscillation in wheel speed direction. The amplitude of the oscillation should be low
//unless the timestep is really large.
//There's not really an obvious solution to this without setting the denominator offset higher
//(or decreasing the timestep). Setting the denominator higher affects handling everywhere so
//settling for a potential temporary oscillation is probably the least worst compromise.
if (useLegacyLongSlipCalculation)
{
lngSlip = (wheelSpeed - longSpeed) / (PxMax(longSpeedAbs, wheelSpeedAbs) + minActiveLongSlipDenominator);
}
else
{
lngSlip = (wheelSpeed - longSpeed) / (longSpeedAbs + minActiveLongSlipDenominator);
}
}
else
{
//Wheel not experiencing an applied torque.
//If the denominator becomes too small then the longSlip becomes large and the longitudinal force
//can overshoot zero at large timesteps. This can be really noticeable so it's harder to justify
//not taking action. Further, the car isn't being actually driven so there is a strong case to fiddle
//with the denominator because it doesn't really affect active handling.
//Don't let the denominator fall below a user-specified value. This can be tuned upwards until the
//oscillation in the sign of longSlip disappears.
if (useLegacyLongSlipCalculation)
{
lngSlip = (wheelSpeed - longSpeed) / (PxMax(minPassiveLongSlipDenominator, PxMax(longSpeedAbs, wheelSpeedAbs)));
}
else
{
lngSlip = (wheelSpeed - longSpeed) / (longSpeedAbs + minPassiveLongSlipDenominator);
}
}
}
return lngSlip;
}
void PxVehicleTireSlipSpeedsUpdate
(const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams,
const PxF32 steerAngle, const PxVehicleSuspensionState& suspStates, const PxVehicleTireDirectionState& trSlipDirs,
const PxVehicleRigidBodyState& rigidBodyState, const PxVehicleRoadGeometryState& roadGeometryState,
const PxVehicleFrame& frame,
PxVehicleTireSpeedState& trSpeedState)
{
trSpeedState.setToDefault();
//Compute the position of the bottom of the wheel (placed on the ground plane).
PxVec3 wheelBottomPos;
{
PxVec3 v,w;
PxF32 dist;
PxVehicleComputeSuspensionRaycast(frame, whlParams, suspParams, steerAngle, rigidBodyState.pose, v, w, dist);
wheelBottomPos = v + w*(dist - suspStates.jounce);
}
//Compute the rigid body velocity at the bottom of the wheel (placed on the ground plane).
PxVec3 wheelBottomVel;
{
const PxVec3 r = wheelBottomPos - rigidBodyState.pose.p;
wheelBottomVel = rigidBodyState.linearVelocity + rigidBodyState.angularVelocity.cross(r) - roadGeometryState.velocity;
}
//Comput the velocities along lateral and longitudinal tire directions.
trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL] = wheelBottomVel.dot(trSlipDirs.directions[PxVehicleTireDirectionModes::eLONGITUDINAL]);
trSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL] = wheelBottomVel.dot(trSlipDirs.directions[PxVehicleTireDirectionModes::eLATERAL]);
}
void vehicleTireSlipsUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleTireSlipParams& trSlipParams, const bool useLegacyLongSlipCalculation,
const PxVehicleWheelActuationState& actState, PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlRigidBody1dState,
PxVehicleTireSlipState& trSlipState)
{
trSlipState.setToDefault();
PxF32 latSlip = 0.0f;
{
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 latSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 minLatSlipDenominator = trSlipParams.minLatSlipDenominator;
latSlip = computeLateralSlip(lngSpeed, latSpeed, minLatSlipDenominator);
}
PxF32 lngSlip = 0.0f;
{
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 wheelRotSpeed = whlRigidBody1dState.rotationSpeed;
const PxF32 wheelRadius = whlParams.radius;
const PxF32 minPassiveLngSlipDenominator = trSlipParams.minPassiveLongSlipDenominator;
const PxF32 minActiveLngSlipDenominator = trSlipParams.minActiveLongSlipDenominator;
const bool isBrakeApplied = actState.isBrakeApplied;
const bool isAccelApplied = actState.isDriveApplied;
lngSlip = computeLongitudionalSlip(
useLegacyLongSlipCalculation,
lngSpeed, wheelRotSpeed, wheelRadius,
minPassiveLngSlipDenominator, minActiveLngSlipDenominator,
isAccelApplied, isBrakeApplied);
}
trSlipState.slips[PxVehicleTireDirectionModes::eLATERAL] = latSlip;
trSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL] = lngSlip;
}
void PxVehicleTireSlipsUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleTireSlipParams& trSlipParams,
const PxVehicleWheelActuationState& actState, PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlRigidBody1dState,
PxVehicleTireSlipState& trSlipState)
{
vehicleTireSlipsUpdate(
whlParams, trSlipParams, false,
actState, trSpeedState, whlRigidBody1dState,
trSlipState);
}
void PxVehicleTireSlipsLegacyUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleTireSlipParams& trSlipParams,
const PxVehicleWheelActuationState& actState, PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlRigidBody1dState,
PxVehicleTireSlipState& trSlipState)
{
vehicleTireSlipsUpdate(
whlParams, trSlipParams, true,
actState, trSpeedState, whlRigidBody1dState,
trSlipState);
}
void PxVehicleTireCamberAnglesUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxReal steerAngle, const PxVec3& groundNormal, bool isWheelOnGround,
const PxVehicleSuspensionComplianceState& compState,
const PxVehicleRigidBodyState& rigidBodyState,
const PxVehicleFrame& frame,
PxVehicleTireCamberAngleState& trCamberAngleState)
{
trCamberAngleState.setToDefault();
//Use zero camber if the suspension could not push the wheel to the ground.
if (!isWheelOnGround)
return;
//Compute the wheel quaternion in the world frame.
//Ignore rotation due to radial symmetry.
const PxQuat wheelOrientation = PxVehicleComputeWheelOrientation(frame, suspParams, compState.camber, compState.toe, steerAngle,
rigidBodyState.pose.q, 0.0f);
//Compute the axes of the wheel.
const PxVec3 latDir = wheelOrientation.rotate(frame.getLatAxis());
const PxVec3 lngDir = wheelOrientation.rotate(frame.getLngAxis());
//Project normal into lateral/vertical plane.
//Start with:
//n = lat*alpha + lng*beta + vrt*delta
//Want to work out
//T = n - lng*beta
// = n - lng*(n.dot(lng))
//Don't forget to normalise T.
//For the angle theta to look for we have:
//T.vrtDir = cos(theta)
//However, the cosine destroys the sign of the angle, thus we
//use:
//T.latDir = cos(pi/2 - theta) = sin(theta) (latDir and vrtDir are perpendicular)
const PxF32 beta = groundNormal.dot(lngDir);
PxVec3 T = groundNormal - lngDir * beta;
T.normalize();
const PxF32 sinTheta = T.dot(latDir);
const PxF32 theta = PxAsin(sinTheta);
trCamberAngleState.camberAngle = theta;
}
PX_FORCE_INLINE PxF32 updateLowLngSpeedTimer
(const PxF32 lngSpeed, const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 lngThresholdSpeed,
const bool isIntentionToAccelerate, const PxF32 dt, const PxF32 lowLngSpeedTime)
{
//If the tire is rotating slowly and the longitudinal speed is slow then increment the slow longitudinal speed timer.
//If the intention of the driver is to accelerate the vehicle then reset the timer because the intention has been signalled NOT to bring
//the wheel to rest.
PxF32 newLowSpeedTime = 0.0f;
if ((PxAbs(lngSpeed) < lngThresholdSpeed) && (PxAbs(wheelOmega*wheelRadius) < lngThresholdSpeed) && !isIntentionToAccelerate)
{
newLowSpeedTime = lowLngSpeedTime + dt;
}
else
{
newLowSpeedTime = 0;
}
return newLowSpeedTime;
}
PX_FORCE_INLINE void activateStickyFrictionLngConstraint
(const PxF32 longSpeed, const PxF32 wheelOmega, const PxF32 lowLngSpeedTime, const bool isIntentionToBrake,
const PxF32 thresholdSpeed, const PxF32 thresholdTime,
bool& stickyTireActiveFlag)
{
//Setup the sticky friction constraint to bring the vehicle to rest at the tire contact point.
//The idea here is to resolve the singularity of the tire long slip at low vz by replacing the long force with a velocity constraint.
//Only do this if we can guarantee that the intention is to bring the car to rest (no accel pedal applied).
//We're going to replace the longitudinal tire force with the sticky friction so set the long slip to zero to ensure zero long force.
//Apply sticky friction to this tire if
//(1) the wheel is locked (this means the brake/handbrake must be on) and the longitudinal speed at the tire contact point is vanishingly small.
//(2) the accumulated time of low longitudinal speed is greater than a threshold.
stickyTireActiveFlag = false;
if (((PxAbs(longSpeed) < thresholdSpeed) && (0.0f == wheelOmega) && isIntentionToBrake) || (lowLngSpeedTime > thresholdTime))
{
stickyTireActiveFlag = true;
}
}
PX_FORCE_INLINE PxF32 updateLowLatSpeedTimer
(const PxF32 latSpeed, const bool isIntentionToAccelerate, const PxF32 timestep, const PxF32 thresholdSpeed, const PxF32 lowSpeedTime)
{
//If the lateral speed is slow then increment the slow lateral speed timer.
//If the intention of the driver is to accelerate the vehicle then reset the timer because the intention has been signalled NOT to bring
//the wheel to rest.
PxF32 newLowSpeedTime = lowSpeedTime;
if ((PxAbs(latSpeed) < thresholdSpeed) && !isIntentionToAccelerate)
{
newLowSpeedTime += timestep;
}
else
{
newLowSpeedTime = 0;
}
return newLowSpeedTime;
}
PX_FORCE_INLINE void activateStickyFrictionLatConstraint
(const bool lowSpeedLngTimerActive,
const PxF32 lowLatSpeedTimer, const PxF32 thresholdTime,
bool& stickyTireActiveFlag)
{
//Setup the sticky friction constraint to bring the vehicle to rest at the tire contact point.
//Only do this if we can guarantee that the intention is to bring the car to rest (no accel pedal applied).
//We're going to replace the lateral tire force with the sticky friction so set the lat slip to zero to ensure zero lat force.
//Apply sticky friction to this tire if
//(1) the low longitudinal speed timer is > 0.
//(2) the accumulated time of low longitudinal speed is greater than a threshold.
stickyTireActiveFlag = false;
if (lowSpeedLngTimerActive && (lowLatSpeedTimer > thresholdTime))
{
stickyTireActiveFlag = true;
}
}
void PxVehicleTireStickyStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleWheelParams& whlParams,
const PxVehicleTireStickyParams& trStickyParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates,
const PxVehicleTireGripState& trGripState, const PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlState,
const PxReal dt,
PxVehicleTireStickyState& trStickyState)
{
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] = false;
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL] = false;
//Only process sticky state if tire can generate force.
const PxF32 load = trGripState.load;
const PxF32 friction = trGripState.friction;
if(0 == load*friction)
{
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL] = 0.0f;
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL] = 0.0f;
return;
}
//Work out if any wheel is to have a drive applied to it.
bool isIntentionToAccelerate = false;
bool isIntentionToBrake = false;
for(PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if(actuationStates[wheelId].isDriveApplied)
isIntentionToAccelerate = true;
if (actuationStates[wheelId].isBrakeApplied)
isIntentionToBrake = true;
}
//Long sticky state.
bool lngTimerActive = false;
{
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 wheelOmega = whlState.rotationSpeed;
const PxF32 wheelRadius = whlParams.radius;
const PxF32 lngThresholdSpeed = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].thresholdSpeed;
const PxF32 lngLowSpeedTime = trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 newLowLngSpeedTime = updateLowLngSpeedTimer(
lngSpeed, wheelOmega, wheelRadius, lngThresholdSpeed,
isIntentionToAccelerate,
dt, lngLowSpeedTime);
lngTimerActive = (newLowLngSpeedTime > 0);
bool lngActiveState = false;
const PxF32 lngThresholdTime = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].thresholdTime;
activateStickyFrictionLngConstraint(
lngSpeed, wheelOmega, newLowLngSpeedTime, isIntentionToBrake,
lngThresholdSpeed, lngThresholdTime,
lngActiveState);
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL] = newLowLngSpeedTime;
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] = lngActiveState;
}
//Lateral sticky state
{
const PxF32 latSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 latThresholdSpeed = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLATERAL].thresholdSpeed;
const PxF32 latLowSpeedTime = trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 latNewLowSpeedTime = updateLowLatSpeedTimer(latSpeed, isIntentionToAccelerate, dt, latThresholdSpeed, latLowSpeedTime);
bool latActiveState = false;
const PxF32 latThresholdTime = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLATERAL].thresholdTime;
activateStickyFrictionLatConstraint(lngTimerActive, latNewLowSpeedTime, latThresholdTime,
latActiveState);
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL] = latNewLowSpeedTime;
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL] = latActiveState;
}
}
PX_FORCE_INLINE PxF32 computeTireLoad
(const PxVehicleTireForceParams& trForceParams, const PxVehicleSuspensionForce& suspForce)
{
//Compute the normalised load.
const PxF32 rawLoad = suspForce.normalForce;
const PxF32 restLoad = trForceParams.restLoad;
const PxF32 normalisedLoad = rawLoad / restLoad;
//Get the load filter params.
const PxF32 minNormalisedLoad = trForceParams.loadFilter[0][0];
const PxF32 minFilteredNormalisedLoad = trForceParams.loadFilter[0][1];
const PxF32 maxNormalisedLoad = trForceParams.loadFilter[1][0];
const PxF32 maxFilteredNormalisedLoad = trForceParams.loadFilter[1][1];
//Compute the filtered load.
const PxF32 filteredNormalisedLoad = computeFilteredNormalisedTireLoad(minNormalisedLoad, minFilteredNormalisedLoad, maxNormalisedLoad, maxFilteredNormalisedLoad, normalisedLoad);
const PxF32 filteredLoad = restLoad * filteredNormalisedLoad;
//Set the load after applying the filter.
return filteredLoad;
}
PX_FORCE_INLINE PxF32 computeTireFriction
(const PxVehicleTireForceParams& trForceParams,
const PxReal frictionCoefficient, const PxVehicleTireSlipState& tireSlipState)
{
//Interpolate the friction using the long slip value.
const PxF32 x0 = trForceParams.frictionVsSlip[0][0];
const PxF32 y0 = trForceParams.frictionVsSlip[0][1];
const PxF32 x1 = trForceParams.frictionVsSlip[1][0];
const PxF32 y1 = trForceParams.frictionVsSlip[1][1];
const PxF32 x2 = trForceParams.frictionVsSlip[2][0];
const PxF32 y2 = trForceParams.frictionVsSlip[2][1];
const PxF32 longSlipAbs = PxAbs(tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL]);
PxF32 mu;
if (longSlipAbs < x1)
{
mu = y0 + (y1 - y0)*(longSlipAbs - x0) / (x1 - x0);
}
else if (longSlipAbs < x2)
{
mu = y1 + (y2 - y1)*(longSlipAbs - x1) / (x2 - x1);
}
else
{
mu = y2;
}
PX_ASSERT(mu >= 0);
const PxF32 tireFriction = frictionCoefficient * mu;
return tireFriction;
}
void PxVehicleTireGripUpdate
(const PxVehicleTireForceParams& trForceParams,
const PxReal frictionCoefficient, bool isWheelOnGround, const PxVehicleSuspensionForce& suspForce,
const PxVehicleTireSlipState& trSlipState,
PxVehicleTireGripState& trGripState)
{
trGripState.setToDefault();
//If the wheel is not touching the ground then carry on with zero grip state.
if (!isWheelOnGround)
return;
//Compute load and friction.
trGripState.load = computeTireLoad(trForceParams, suspForce);
trGripState.friction = computeTireFriction(trForceParams, frictionCoefficient, trSlipState);
}
void PxVehicleTireSlipsAccountingForStickyStatesUpdate
(const PxVehicleTireStickyState& trStickyState,
PxVehicleTireSlipState& trSlipState)
{
if(trStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL])
trSlipState.slips[PxVehicleTireDirectionModes::eLATERAL] = 0.f;
if (trStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL])
trSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL] = 0.f;
}
////////////////////////////////////////////////////////////////////////////
//Default tire force shader function.
//Taken from Michigan tire model.
//Computes tire long and lat forces plus the aligning moment arising from
//the lat force and the torque to apply back to the wheel arising from the
//long force (application of Newton's 3rd law).
////////////////////////////////////////////////////////////////////////////
#define ONE_TWENTYSEVENTH 0.037037f
#define ONE_THIRD 0.33333f
PX_FORCE_INLINE PxF32 smoothingFunction1(const PxF32 K)
{
//Equation 20 in CarSimEd manual Appendix F.
//Looks a bit like a curve of sqrt(x) for 0<x<1 but reaching 1.0 on y-axis at K=3.
PX_ASSERT(K >= 0.0f);
return PxMin(1.0f, K - ONE_THIRD * K*K + ONE_TWENTYSEVENTH * K*K*K);
}
PX_FORCE_INLINE PxF32 smoothingFunction2(const PxF32 K)
{
//Equation 21 in CarSimEd manual Appendix F.
//Rises to a peak at K=0.75 and falls back to zero by K=3
PX_ASSERT(K >= 0.0f);
return (K - K * K + ONE_THIRD * K*K*K - ONE_TWENTYSEVENTH * K*K*K*K);
}
void computeTireForceMichiganModel
(const PxVehicleTireForceParams& tireData,
const PxF32 tireFriction,
const PxF32 longSlipUnClamped, const PxF32 latSlipUnClamped, const PxF32 camberUnclamped,
const PxF32 wheelRadius,
const PxF32 tireLoad,
PxF32& wheelTorque, PxF32& tireLongForceMag, PxF32& tireLatForceMag, PxF32& tireAlignMoment)
{
PX_ASSERT(tireFriction > 0);
PX_ASSERT(tireLoad > 0);
wheelTorque = 0.0f;
tireLongForceMag = 0.0f;
tireLatForceMag = 0.0f;
tireAlignMoment = 0.0f;
//Clamp the slips to a minimum value.
const PxF32 minimumSlipThreshold = 1e-5f;
const PxF32 latSlip = PxAbs(latSlipUnClamped) >= minimumSlipThreshold ? latSlipUnClamped : 0.0f;
const PxF32 longSlip = PxAbs(longSlipUnClamped) >= minimumSlipThreshold ? longSlipUnClamped : 0.0f;
const PxF32 camber = PxAbs(camberUnclamped) >= minimumSlipThreshold ? camberUnclamped : 0.0f;
//Normalise the tire load.
const PxF32 restTireLoad = tireData.restLoad;
const PxF32 normalisedTireLoad = tireLoad/ restTireLoad;
//Compute the lateral stiffness
const PxF32 latStiff = (0.0f == tireData.latStiffX) ? tireData.latStiffY : tireData.latStiffY*smoothingFunction1(normalisedTireLoad*3.0f / tireData.latStiffX);
//Get the longitudinal stiffness
const PxF32 longStiff = tireData.longStiff;
//Get the camber stiffness.
const PxF32 camberStiff = tireData.camberStiff;
//If long slip/lat slip/camber are all zero than there will be zero tire force.
if ((0 == latSlip*latStiff) && (0 == longSlip*longStiff) && (0 == camber*camberStiff))
{
return;
}
//Carry on and compute the forces.
const PxF32 TEff = PxTan(latSlip + (camber * camberStiff / latStiff)); // "+" because we define camber stiffness as a positive value
const PxF32 K = PxSqrt(latStiff*TEff*latStiff*TEff + longStiff * longSlip*longStiff*longSlip) / (tireFriction*tireLoad);
//const PxF32 KAbs=PxAbs(K);
PxF32 FBar = smoothingFunction1(K);//K - ONE_THIRD*PxAbs(K)*K + ONE_TWENTYSEVENTH*K*K*K;
PxF32 MBar = smoothingFunction2(K); //K - KAbs*K + ONE_THIRD*K*K*K - ONE_TWENTYSEVENTH*KAbs*K*K*K;
//Mbar = PxMin(Mbar, 1.0f);
PxF32 nu = 1;
if (K <= 2.0f*PxPi)
{
const PxF32 latOverlLong = latStiff/longStiff;
nu = 0.5f*(1.0f + latOverlLong - (1.0f - latOverlLong)*PxCos(K*0.5f));
}
const PxF32 FZero = tireFriction * tireLoad / (PxSqrt(longSlip*longSlip + nu * TEff*nu*TEff));
const PxF32 fz = longSlip * FBar*FZero;
const PxF32 fx = -nu * TEff*FBar*FZero;
//TODO: pneumatic trail.
const PxF32 pneumaticTrail = 1.0f;
const PxF32 fMy = nu * pneumaticTrail * TEff * MBar * FZero;
//We can add the torque to the wheel.
wheelTorque = -fz * wheelRadius;
tireLongForceMag = fz;
tireLatForceMag = fx;
tireAlignMoment = fMy;
}
void PxVehicleTireForcesUpdate
(const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams,
const PxVehicleTireForceParams& trForceParams,
const PxVehicleSuspensionComplianceState& compState,
const PxVehicleTireGripState& trGripState, const PxVehicleTireDirectionState& trDirectionState,
const PxVehicleTireSlipState& trSlipState, const PxVehicleTireCamberAngleState& cmbAngleState,
const PxVehicleRigidBodyState& rigidBodyState,
PxVehicleTireForce& trForce)
{
trForce.setToDefault();
//If the tire can generate no force then carry on with zero force.
if(0 == trGripState.friction*trGripState.load)
return;
PxF32 wheelTorque = 0;
PxF32 tireLongForceMag = 0;
PxF32 tireLatForceMag = 0;
PxF32 tireAlignMoment = 0;
const PxF32 friction = trGripState.friction;
const PxF32 tireLoad = trGripState.load;
const PxF32 lngSlip = trSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 latSlip = trSlipState.slips[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 camber = cmbAngleState.camberAngle;
const PxF32 wheelRadius = whlParams.radius;
computeTireForceMichiganModel(trForceParams, friction, lngSlip, latSlip, camber, wheelRadius, tireLoad,
wheelTorque, tireLongForceMag, tireLatForceMag, tireAlignMoment);
//Compute the forces.
const PxVec3 tireLongForce = trDirectionState.directions[PxVehicleTireDirectionModes::eLONGITUDINAL]*tireLongForceMag;
const PxVec3 tireLatForce = trDirectionState.directions[PxVehicleTireDirectionModes::eLATERAL]*tireLatForceMag;
//Compute the torques.
const PxVec3 r = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.transform(compState.tireForceAppPoint));
const PxVec3 tireLongTorque = r.cross(tireLongForce);
const PxVec3 tireLatTorque = r.cross(tireLatForce);
//Set the torques.
trForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL] = tireLongForce;
trForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL] = tireLongTorque;
trForce.forces[PxVehicleTireDirectionModes::eLATERAL] = tireLatForce;
trForce.torques[PxVehicleTireDirectionModes::eLATERAL] = tireLatTorque;
trForce.aligningMoment = tireAlignMoment;
trForce.wheelTorque = wheelTorque;
}
} //namespace vehicle2
} //namespace physx
| 29,600 |
C++
| 40.055478 | 180 | 0.782196 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/drivetrain/VhDrivetrainHelpers.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleFunctions.h"
#include "vehicle2/PxVehicleMaths.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleMatrixNNLUSolver::decomposeLU(const PxVehicleMatrixNN& A)
{
const PxU32 D = A.mSize;
mLU = A;
mDetM = 1.0f;
for (PxU32 k = 0; k < D - 1; ++k)
{
PxU32 pivot_row = k;
PxU32 pivot_col = k;
float abs_pivot_elem = 0.0f;
for (PxU32 c = k; c < D; ++c)
{
for (PxU32 r = k; r < D; ++r)
{
const PxF32 abs_elem = PxAbs(mLU.get(r, c));
if (abs_elem > abs_pivot_elem)
{
abs_pivot_elem = abs_elem;
pivot_row = r;
pivot_col = c;
}
}
}
mP[k] = pivot_row;
if (pivot_row != k)
{
mDetM = -mDetM;
for (PxU32 c = 0; c < D; ++c)
{
//swap(m_LU(k,c), m_LU(pivot_row,c));
const PxF32 pivotrowc = mLU.get(pivot_row, c);
mLU.set(pivot_row, c, mLU.get(k, c));
mLU.set(k, c, pivotrowc);
}
}
mQ[k] = pivot_col;
if (pivot_col != k)
{
mDetM = -mDetM;
for (PxU32 r = 0; r < D; ++r)
{
//swap(m_LU(r,k), m_LU(r,pivot_col));
const PxF32 rpivotcol = mLU.get(r, pivot_col);
mLU.set(r, pivot_col, mLU.get(r, k));
mLU.set(r, k, rpivotcol);
}
}
mDetM *= mLU.get(k, k);
if (mLU.get(k, k) != 0.0f)
{
for (PxU32 r = k + 1; r < D; ++r)
{
mLU.set(r, k, mLU.get(r, k) / mLU.get(k, k));
for (PxU32 c = k + 1; c < D; ++c)
{
//m_LU(r,c) -= m_LU(r,k)*m_LU(k,c);
const PxF32 rc = mLU.get(r, c);
const PxF32 rk = mLU.get(r, k);
const PxF32 kc = mLU.get(k, c);
mLU.set(r, c, rc - rk * kc);
}
}
}
}
mDetM *= mLU.get(D - 1, D - 1);
}
bool PxVehicleMatrixNNLUSolver::solve(const PxVehicleVectorN& b, PxVehicleVectorN& x) const
{
const PxU32 D = x.getSize();
if ((b.getSize() != x.getSize()) || (b.getSize() != mLU.getSize()) || (0.0f == mDetM))
{
for (PxU32 i = 0; i < D; i++)
{
x[i] = 0.0f;
}
return false;
}
x = b;
// Perform row permutation to get Pb
for (PxU32 i = 0; i < D - 1; ++i)
{
//swap(x(i), x(m_P[i]));
const PxF32 xp = x[mP[i]];
x[mP[i]] = x[i];
x[i] = xp;
}
// Forward substitute to get (L^-1)Pb
for (PxU32 r = 1; r < D; ++r)
{
for (PxU32 i = 0; i < r; ++i)
{
x[r] -= mLU.get(r, i)*x[i];
}
}
// Back substitute to get (U^-1)(L^-1)Pb
for (PxU32 r = D; r-- > 0;)
{
for (PxU32 i = r + 1; i < D; ++i)
{
x[r] -= mLU.get(r, i)*x[i];
}
x[r] /= mLU.get(r, r);
}
// Perform column permutation to get the solution (Q^T)(U^-1)(L^-1)Pb
for (PxU32 i = D - 1; i-- > 0;)
{
//swap(x(i), x(m_Q[i]));
const PxF32 xq = x[mQ[i]];
x[mQ[i]] = x[i];
x[i] = xq;
}
return true;
}
void PxVehicleMatrixNGaussSeidelSolver::solve(const PxU32 maxIterations, const PxF32 tolerance, const PxVehicleMatrixNN& A, const PxVehicleVectorN& b, PxVehicleVectorN& result) const
{
const PxU32 N = A.getSize();
PxVehicleVectorN DInv(N);
PxF32 bLength2 = 0.0f;
for (PxU32 i = 0; i < N; i++)
{
DInv[i] = 1.0f / A.get(i, i);
bLength2 += (b[i] * b[i]);
}
PxU32 iteration = 0;
PxF32 error = PX_MAX_F32;
while (iteration < maxIterations && tolerance < error)
{
for (PxU32 i = 0; i < N; i++)
{
PxF32 l = 0.0f;
for (PxU32 j = 0; j < i; j++)
{
l += A.get(i, j) * result[j];
}
PxF32 u = 0.0f;
for (PxU32 j = i + 1; j < N; j++)
{
u += A.get(i, j) * result[j];
}
result[i] = DInv[i] * (b[i] - l - u);
}
//Compute the error.
PxF32 rLength2 = 0;
for (PxU32 i = 0; i < N; i++)
{
PxF32 e = -b[i];
for (PxU32 j = 0; j < N; j++)
{
e += A.get(i, j) * result[j];
}
rLength2 += e * e;
}
error = (rLength2 / (bLength2 + 1e-10f));
iteration++;
}
}
bool PxVehicleMatrix33Solver::solve(const PxVehicleMatrixNN& A_, const PxVehicleVectorN& b_, PxVehicleVectorN& result) const
{
const PxF32 a = A_.get(0, 0);
const PxF32 b = A_.get(0, 1);
const PxF32 c = A_.get(0, 2);
const PxF32 d = A_.get(1, 0);
const PxF32 e = A_.get(1, 1);
const PxF32 f = A_.get(1, 2);
const PxF32 g = A_.get(2, 0);
const PxF32 h = A_.get(2, 1);
const PxF32 k = A_.get(2, 2);
const PxF32 detA = a * (e*k - f * h) - b * (k*d - f * g) + c * (d*h - e * g);
if (0.0f == detA)
{
return false;
}
const PxF32 detAInv = 1.0f / detA;
const PxF32 A = (e*k - f * h);
const PxF32 D = -(b*k - c * h);
const PxF32 G = (b*f - c * e);
const PxF32 B = -(d*k - f * g);
const PxF32 E = (a*k - c * g);
const PxF32 H = -(a*f - c * d);
const PxF32 C = (d*h - e * g);
const PxF32 F = -(a*h - b * g);
const PxF32 K = (a*e - b * d);
result[0] = detAInv * (A*b_[0] + D * b_[1] + G * b_[2]);
result[1] = detAInv * (B*b_[0] + E * b_[1] + H * b_[2]);
result[2] = detAInv * (C*b_[0] + F * b_[1] + K * b_[2]);
return true;
}
void PxVehicleLegacyDifferentialWheelSpeedContributionsCompute
(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams,
const PxU32 nbWheels, PxReal* diffAveWheelSpeedContributions)
{
PxMemZero(diffAveWheelSpeedContributions, sizeof(PxReal) * nbWheels);
const PxU32 wheelIds[4] =
{
diffParams.frontWheelIds[0],
diffParams.frontWheelIds[1],
diffParams.rearWheelIds[0],
diffParams.rearWheelIds[1],
};
const PxF32 frontRearSplit = diffParams.frontRearSplit;
const PxF32 frontNegPosSplit = diffParams.frontNegPosSplit;
const PxF32 rearNegPosSplit = diffParams.rearNegPosSplit;
const PxF32 oneMinusFrontRearSplit = 1.0f - diffParams.frontRearSplit;
const PxF32 oneMinusFrontNegPosSplit = 1.0f - diffParams.frontNegPosSplit;
const PxF32 oneMinusRearNegPosSplit = 1.0f - diffParams.rearNegPosSplit;
switch (diffParams.type)
{
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_4WD:
diffAveWheelSpeedContributions[wheelIds[0]] = frontRearSplit * frontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[1]] = frontRearSplit * oneMinusFrontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[2]] = oneMinusFrontRearSplit * rearNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[3]] = oneMinusFrontRearSplit * oneMinusRearNegPosSplit;
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_FRONTWD:
diffAveWheelSpeedContributions[wheelIds[0]] = frontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[1]] = oneMinusFrontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[2]] = 0.0f;
diffAveWheelSpeedContributions[wheelIds[3]] = 0.0f;
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_REARWD:
diffAveWheelSpeedContributions[wheelIds[0]] = 0.0f;
diffAveWheelSpeedContributions[wheelIds[1]] = 0.0f;
diffAveWheelSpeedContributions[wheelIds[2]] = rearNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[3]] = oneMinusRearNegPosSplit;
break;
default:
PX_ASSERT(false);
break;
}
PX_ASSERT(
((diffAveWheelSpeedContributions[wheelIds[0]] + diffAveWheelSpeedContributions[wheelIds[1]] + diffAveWheelSpeedContributions[wheelIds[2]] + diffAveWheelSpeedContributions[wheelIds[3]]) >= 0.999f) &&
((diffAveWheelSpeedContributions[wheelIds[0]] + diffAveWheelSpeedContributions[wheelIds[1]] + diffAveWheelSpeedContributions[wheelIds[2]] + diffAveWheelSpeedContributions[wheelIds[3]]) <= 1.001f));
}
PX_FORCE_INLINE void splitTorque
(const PxF32 w1, const PxF32 w2, const PxF32 diffBias, const PxF32 defaultSplitRatio,
PxF32* t1, PxF32* t2)
{
PX_ASSERT(PxVehicleComputeSign(w1) == PxVehicleComputeSign(w2) && 0.0f != PxVehicleComputeSign(w1));
const PxF32 w1Abs = PxAbs(w1);
const PxF32 w2Abs = PxAbs(w2);
const PxF32 omegaMax = PxMax(w1Abs, w2Abs);
const PxF32 omegaMin = PxMin(w1Abs, w2Abs);
const PxF32 delta = omegaMax - diffBias * omegaMin;
const PxF32 deltaTorque = physx::intrinsics::fsel(delta, delta / omegaMax, 0.0f);
const PxF32 f1 = physx::intrinsics::fsel(w1Abs - w2Abs, defaultSplitRatio*(1.0f - deltaTorque), defaultSplitRatio*(1.0f + deltaTorque));
const PxF32 f2 = physx::intrinsics::fsel(w1Abs - w2Abs, (1.0f - defaultSplitRatio)*(1.0f + deltaTorque), (1.0f - defaultSplitRatio)*(1.0f - deltaTorque));
const PxF32 denom = 1.0f / (f1 + f2);
*t1 = f1 * denom;
*t2 = f2 * denom;
PX_ASSERT((*t1 + *t2) >= 0.999f && (*t1 + *t2) <= 1.001f);
}
void PxVehicleLegacyDifferentialTorqueRatiosCompute
(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelOmegas,
const PxU32 nbWheels, PxReal* diffTorqueRatios)
{
PxMemZero(diffTorqueRatios, sizeof(PxReal) * nbWheels);
const PxU32 wheelIds[4] =
{
diffParams.frontWheelIds[0],
diffParams.frontWheelIds[1],
diffParams.rearWheelIds[0],
diffParams.rearWheelIds[1],
};
const PxF32 wfl = wheelOmegas[wheelIds[0]].rotationSpeed;
const PxF32 wfr = wheelOmegas[wheelIds[1]].rotationSpeed;
const PxF32 wrl = wheelOmegas[wheelIds[2]].rotationSpeed;
const PxF32 wrr = wheelOmegas[wheelIds[3]].rotationSpeed;
const PxF32 centreBias = diffParams.centerBias;
const PxF32 frontBias = diffParams.frontBias;
const PxF32 rearBias = diffParams.rearBias;
const PxF32 frontRearSplit = diffParams.frontRearSplit;
const PxF32 frontLeftRightSplit = diffParams.frontNegPosSplit;
const PxF32 rearLeftRightSplit = diffParams.rearNegPosSplit;
const PxF32 oneMinusFrontRearSplit = 1.0f - diffParams.frontRearSplit;
const PxF32 oneMinusFrontLeftRightSplit = 1.0f - diffParams.frontNegPosSplit;
const PxF32 oneMinusRearLeftRightSplit = 1.0f - diffParams.rearNegPosSplit;
const PxF32 swfl = PxVehicleComputeSign(wfl);
//Split a torque of 1 between front and rear.
//Then split that torque between left and right.
PxF32 torqueFrontLeft = 0;
PxF32 torqueFrontRight = 0;
PxF32 torqueRearLeft = 0;
PxF32 torqueRearRight = 0;
switch (diffParams.type)
{
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_4WD:
if (0.0f != swfl && swfl == PxVehicleComputeSign(wfr) && swfl == PxVehicleComputeSign(wrl) && swfl == PxVehicleComputeSign(wrr))
{
PxF32 torqueFront, torqueRear;
const PxF32 omegaFront = PxAbs(wfl + wfr);
const PxF32 omegaRear = PxAbs(wrl + wrr);
splitTorque(omegaFront, omegaRear, centreBias, frontRearSplit, &torqueFront, &torqueRear);
splitTorque(wfl, wfr, frontBias, frontLeftRightSplit, &torqueFrontLeft, &torqueFrontRight);
splitTorque(wrl, wrr, rearBias, rearLeftRightSplit, &torqueRearLeft, &torqueRearRight);
torqueFrontLeft *= torqueFront;
torqueFrontRight *= torqueFront;
torqueRearLeft *= torqueRear;
torqueRearRight *= torqueRear;
}
else
{
torqueFrontLeft = frontRearSplit * frontLeftRightSplit;
torqueFrontRight = frontRearSplit * oneMinusFrontLeftRightSplit;
torqueRearLeft = oneMinusFrontRearSplit * rearLeftRightSplit;
torqueRearRight = oneMinusFrontRearSplit * oneMinusRearLeftRightSplit;
}
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_FRONTWD:
if (0.0f != swfl && swfl == PxVehicleComputeSign(wfr))
{
splitTorque(wfl, wfr, frontBias, frontLeftRightSplit, &torqueFrontLeft, &torqueFrontRight);
}
else
{
torqueFrontLeft = frontLeftRightSplit;
torqueFrontRight = oneMinusFrontLeftRightSplit;
}
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_REARWD:
if (0.0f != PxVehicleComputeSign(wrl) && PxVehicleComputeSign(wrl) == PxVehicleComputeSign(wrr))
{
splitTorque(wrl, wrr, rearBias, rearLeftRightSplit, &torqueRearLeft, &torqueRearRight);
}
else
{
torqueRearLeft = rearLeftRightSplit;
torqueRearRight = oneMinusRearLeftRightSplit;
}
break;
default:
PX_ASSERT(false);
break;
}
diffTorqueRatios[wheelIds[0]] = torqueFrontLeft;
diffTorqueRatios[wheelIds[1]] = torqueFrontRight;
diffTorqueRatios[wheelIds[2]] = torqueRearLeft;
diffTorqueRatios[wheelIds[3]] = torqueRearRight;
PX_ASSERT(((torqueFrontLeft + torqueFrontRight + torqueRearLeft + torqueRearRight) >= 0.999f) && ((torqueFrontLeft + torqueFrontRight + torqueRearLeft + torqueRearRight) <= 1.001f));
}
} //namespace vehicle2
} //namespace physx
| 13,838 |
C++
| 30.452273 | 200 | 0.686226 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/drivetrain/VhDrivetrainFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleFunctions.h"
#include "vehicle2/PxVehicleMaths.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainFunctions.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleDirectDriveThrottleCommandResponseUpdate
(const PxReal throttle, const PxVehicleDirectDriveTransmissionCommandState& transmissionCommands, const PxReal longitudinalSpeed,
const PxU32 wheelId, const PxVehicleDirectDriveThrottleCommandResponseParams& responseParams,
PxReal& throttleResponse)
{
//The gearing decides how we will multiply the response.
PxF32 gearMultiplier = 0.0f;
switch (transmissionCommands.gear)
{
case PxVehicleDirectDriveTransmissionCommandState::eREVERSE:
gearMultiplier = -1.0f;
break;
case PxVehicleDirectDriveTransmissionCommandState::eNEUTRAL:
gearMultiplier = 0.0f;
break;
case PxVehicleDirectDriveTransmissionCommandState::eFORWARD:
gearMultiplier = 1.0f;
break;
}
throttleResponse = gearMultiplier * PxVehicleNonLinearResponseCompute(throttle, longitudinalSpeed, wheelId, responseParams);
}
void PxVehicleDirectDriveActuationStateUpdate
(const PxReal brakeTorque, const PxReal driveTorque,
PxVehicleWheelActuationState& actState)
{
PxMemZero(&actState, sizeof(PxVehicleWheelActuationState));
actState.isBrakeApplied = (brakeTorque != 0.0f);
actState.isDriveApplied = (driveTorque != 0.0f);
}
void PxVehicleDirectDriveUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleWheelActuationState& actState,
const PxReal brkTorque, const PxReal drvTorque, const PxVehicleTireForce& trForce,
const PxF32 dt,
PxVehicleWheelRigidBody1dState& whlState)
{
//w(t+dt) = w(t) + (1/inertia)*(brakeTorque + driveTorque + tireTorque)*dt - (1/inertia)*damping*w(t)*dt ) (1)
//Apply implicit trick and rearrange.
//w(t+dt)[1 + (1/inertia)*damping*dt] = w(t) + (1/inertia)*(brakeTorque + driveTorque + tireTorque)*dt (2)
const PxF32 wheelRotSpeed = whlState.rotationSpeed;
const PxF32 dtOverMOI = dt/whlParams.moi;
const PxF32 tireTorque = trForce.wheelTorque;
const PxF32 brakeTorque = -brkTorque*PxVehicleComputeSign(wheelRotSpeed);
const PxF32 driveTorque = drvTorque;
const PxF32 wheelDampingRate = whlParams.dampingRate;
//Integrate the wheel rotation speed.
const PxF32 newRotSpeedNoBrakelock = (wheelRotSpeed + dtOverMOI*(tireTorque + driveTorque + brakeTorque)) / (1.0f + wheelDampingRate*dtOverMOI);
//If the brake is applied and the sign flipped then lock the brake.
const bool isBrakeApplied = actState.isBrakeApplied;
const PxF32 newRotSpeedWithBrakelock = (isBrakeApplied && ((wheelRotSpeed*newRotSpeedNoBrakelock) <= 0)) ? 0.0f : newRotSpeedNoBrakelock;
whlState.rotationSpeed = newRotSpeedWithBrakelock;
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelStates,
PxVehicleDifferentialState& diffState)
{
diffState.setToDefault();
//4 wheels are connected.
diffState.connectedWheels[0] = diffParams.frontWheelIds[0];
diffState.connectedWheels[1] = diffParams.frontWheelIds[1];
diffState.connectedWheels[2] = diffParams.rearWheelIds[0];
diffState.connectedWheels[3] = diffParams.rearWheelIds[1];
diffState.nbConnectedWheels = 4;
//Compute the contributions to average speed and ratios of available torque.
PxVehicleLegacyDifferentialWheelSpeedContributionsCompute(diffParams, PxVehicleLimits::eMAX_NB_WHEELS,
diffState.aveWheelSpeedContributionAllWheels);
PxVehicleLegacyDifferentialTorqueRatiosCompute(diffParams, wheelStates, PxVehicleLimits::eMAX_NB_WHEELS,
diffState.torqueRatiosAllWheels);
}
PX_FORCE_INLINE PxF32 computeTargetRatio
(const PxF32 target, const PxF32 dt, const PxF32 strength, const PxF32 ratio)
{
const PxF32 targ = (PX_VEHICLE_FOUR_WHEEL_DIFFERENTIAL_MAXIMUM_STRENGTH == strength) ? target : PxMax(target, ratio - strength * dt);
return targ;
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleFourWheelDriveDifferentialParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelStates,
const PxReal dt,
PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState)
{
diffState.setToDefault();
wheelConstraintGroupState.setToDefault();
PxU32 nbConnectedWheels = 0;
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if (diffParams.torqueRatios[wheelId] != 0.0f)
{
diffState.connectedWheels[nbConnectedWheels] = wheelId;
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
nbConnectedWheels++;
}
}
diffState.nbConnectedWheels = nbConnectedWheels;
if (0.0f == diffParams.frontBias && 0.0f == diffParams.rearBias && 0.0f == diffParams.centerBias)
return;
if (0.0f == diffParams.rate)
return;
bool frontBiasBreached = false;
PxF32 Rf = 0.0f;
PxF32 Tf = 0.0f;
{
const PxF32 bias = diffParams.frontBias;
if (bias >= 1.0f)
{
const PxU32 wheel0 = diffParams.frontWheelIds[0];
const PxU32 wheel1 = diffParams.frontWheelIds[1];
const PxReal w0 = wheelStates[wheel0].rotationSpeed;
const PxReal w1 = wheelStates[wheel1].rotationSpeed;
const PxReal aw0 = PxAbs(w0);
const PxReal aw1 = PxAbs(w1);
const PxReal sw0 = PxVehicleComputeSign(w0);
const PxReal sw1 = PxVehicleComputeSign(w1);
if ((w0 != 0.0f) && (sw0 == sw1))
{
const PxF32 ratio = PxMax(aw0, aw1) / PxMin(aw0, aw1);
frontBiasBreached = (ratio > bias);
//const PxF32 target = diffParams.frontTarget + (1.0f - diffParams.strength) * (ratio - diffParams.frontTarget);
const PxF32 target = computeTargetRatio(diffParams.frontTarget, dt, diffParams.rate, ratio);
Tf = (aw0 > aw1) ? 1.0f / target : target;
Rf = aw1 / aw0;
}
}
}
bool rearBiasBreached = false;
PxF32 Rr = 0.0f;
PxF32 Tr = 0.0f;
{
const PxF32 bias = diffParams.rearBias;
if (bias >= 1.0f)
{
const PxU32 wheel2 = diffParams.rearWheelIds[0];
const PxU32 wheel3 = diffParams.rearWheelIds[1];
const PxReal w2 = wheelStates[wheel2].rotationSpeed;
const PxReal w3 = wheelStates[wheel3].rotationSpeed;
const PxReal aw2 = PxAbs(w2);
const PxReal aw3 = PxAbs(w3);
const PxReal sw2 = PxVehicleComputeSign(w2);
const PxReal sw3 = PxVehicleComputeSign(w3);
if ((w2 != 0.0f) && (sw2 == sw3))
{
const PxF32 ratio = PxMax(aw2, aw3) / PxMin(aw2, aw3);
rearBiasBreached = (ratio > bias);
//const PxF32 target = diffParams.rearTarget + (1.0f - diffParams.strength) * (ratio - diffParams.rearTarget);
const PxF32 target = computeTargetRatio(diffParams.rearTarget, dt, diffParams.rate, ratio);
Tr = (aw2 > aw3) ? 1.0f / target : target;
Rr = aw3 / aw2;
}
}
}
bool centreBiasBrached = false;
//PxF32 Rc = 0.0f;
PxF32 Tc = 0.0f;
{
const PxF32 bias = diffParams.centerBias;
if(bias >= 1.0f)
{
const PxU32 wheel0 = diffParams.frontWheelIds[0];
const PxU32 wheel1 = diffParams.frontWheelIds[1];
const PxU32 wheel2 = diffParams.rearWheelIds[0];
const PxU32 wheel3 = diffParams.rearWheelIds[1];
const PxReal w0 = wheelStates[wheel0].rotationSpeed;
const PxReal w1 = wheelStates[wheel1].rotationSpeed;
const PxReal w2 = wheelStates[wheel2].rotationSpeed;
const PxReal w3 = wheelStates[wheel3].rotationSpeed;
const PxReal aw0 = PxAbs(w0);
const PxReal aw1 = PxAbs(w1);
const PxReal aw2 = PxAbs(w2);
const PxReal aw3 = PxAbs(w3);
const PxReal sw0 = PxVehicleComputeSign(w0);
const PxReal sw1 = PxVehicleComputeSign(w1);
const PxReal sw2 = PxVehicleComputeSign(w2);
const PxReal sw3 = PxVehicleComputeSign(w3);
if ((w0 != 0.0f) && (sw0 == sw1) && (sw0 == sw2) && (sw0 == sw3))
{
const PxF32 ratio = PxMax(aw0 + aw1, aw2 + aw3) / PxMin(aw0 + aw1, aw2 + aw3);
centreBiasBrached = (ratio > bias);
//const PxF32 target = diffParams.centerTarget + (1.0f - diffParams.strength) * (ratio - diffParams.centerTarget);
const PxF32 target = computeTargetRatio(diffParams.centerTarget, dt, diffParams.rate, ratio);
Tc = ((aw0 + aw1) > (aw2 + aw3)) ? 1.0f / target : target;
//Rc = (aw2 + aw3) / (aw0 + aw1);
}
}
}
if (centreBiasBrached)
{
PxF32 f = 0.0f;
PxF32 r = 0.0f;
if (frontBiasBreached && rearBiasBreached)
{
f = Tf;
r = Tr;
}
else if (frontBiasBreached)
{
f = Tf;
r = Rr;
}
else if (rearBiasBreached)
{
f = Rf;
r = Tr;
}
else
{
f = Rf;
r = Rr;
}
const PxU32 wheel0 = diffParams.frontWheelIds[0];
const PxU32 wheel1 = diffParams.frontWheelIds[1];
const PxU32 wheel2 = diffParams.rearWheelIds[0];
const PxU32 wheel3 = diffParams.rearWheelIds[1];
const PxU32 wheelIds[4] = { wheel0, wheel1, wheel2, wheel3 };
const PxF32 constraintMultipliers[4] = { 1.0f, f, Tc*(1 + f) / (1 + r), r*Tc*(1 + f) / (1 + r) };
wheelConstraintGroupState.addConstraintGroup(4, wheelIds, constraintMultipliers);
}
else
{
if (frontBiasBreached)
{
const PxU32* wheelIds = diffParams.frontWheelIds;
const PxF32 constraintMultipliers[2] = { 1.0f, Tf };
wheelConstraintGroupState.addConstraintGroup(2, wheelIds, constraintMultipliers);
}
if (rearBiasBreached)
{
const PxU32* wheelIds = diffParams.rearWheelIds;
const PxF32 constraintMultipliers[2] = { 1.0f, Tr };
wheelConstraintGroupState.addConstraintGroup(2, wheelIds, constraintMultipliers);
}
}
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleMultiWheelDriveDifferentialParams& diffParams,
PxVehicleDifferentialState& diffState)
{
diffState.setToDefault();
PxU32 nbConnectedWheels = 0;
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if (diffParams.torqueRatios[wheelId] != 0.0f)
{
diffState.connectedWheels[nbConnectedWheels] = wheelId;
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
nbConnectedWheels++;
}
}
diffState.nbConnectedWheels = nbConnectedWheels;
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, const PxVehicleTankDriveDifferentialParams& diffParams,
const PxReal thrust0, PxReal thrust1,
PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState)
{
diffState.setToDefault();
wheelConstraintGroupState.setToDefault();
//Store the tank track id for each wheel.
//Store the thrust controller id for each wheel.
//Store 0xffffffff for wheels not in a tank track.
PxU32 tankTrackIds[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemSet(tankTrackIds, 0xff, sizeof(tankTrackIds));
PxU32 thrustControllerIds[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemSet(thrustControllerIds, 0xff, sizeof(thrustControllerIds));
for (PxU32 i = 0; i < diffParams.getNbTracks(); i++)
{
const PxU32 thrustControllerIndex = diffParams.getThrustControllerIndex(i);
for (PxU32 j = 0; j < diffParams.getNbWheelsInTrack(i); j++)
{
const PxU32 wheelId = diffParams.getWheelInTrack(j, i);
tankTrackIds[wheelId] = i;
thrustControllerIds[wheelId] = thrustControllerIndex;
}
}
//Treat every wheel connected to a tank track as connected to the differential but with zero torque split.
//If a wheel is not connected to the differential but is connected to a tank track then we treat that as a connected wheel with
//zero drive torque applied.
//We do this because we need to treat these wheels as being coupled to other wheels in the linear equations that solve engine+wheels
PxU32 nbConnectedWheels = 0;
const PxReal thrusts[2] = { thrust0, thrust1 };
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
const PxU32 tankTrackId = tankTrackIds[wheelId];
if (diffParams.torqueRatios[wheelId] != 0.0f && 0xffffffff != tankTrackId)
{
//Wheel connected to diff and in a tank track.
//Modify the default torque split using the relevant thrust.
const PxU32 thrustId = thrustControllerIds[wheelId];
const PxF32 torqueSplitMultiplier = thrusts[thrustId];
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.torqueRatios[wheelId] * torqueSplitMultiplier;
diffState.connectedWheels[nbConnectedWheels] = wheelId;
nbConnectedWheels++;
}
else if (diffParams.torqueRatios[wheelId] != 0.0f)
{
//Wheel connected to diff but not in a tank track.
//Use the default torque split.
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.torqueRatios[wheelId];
diffState.connectedWheels[nbConnectedWheels] = wheelId;
nbConnectedWheels++;
}
else if (0xffffffff != tankTrackId)
{
//Wheel not connected to diff but is in a tank track.
//Zero torque split.
diffState.aveWheelSpeedContributionAllWheels[wheelId] = 0.0f;
diffState.torqueRatiosAllWheels[wheelId] = 0.0f;
diffState.connectedWheels[nbConnectedWheels] = wheelId;
nbConnectedWheels++;
}
}
diffState.nbConnectedWheels = nbConnectedWheels;
//Add each tank track as a constraint group.
for (PxU32 i = 0; i < diffParams.getNbTracks(); i++)
{
const PxU32 nbWheelsInTrack = diffParams.getNbWheelsInTrack(i);
if (nbWheelsInTrack >= 2)
{
const PxU32* wheelsInTrack = diffParams.wheelIdsInTrackOrder + diffParams.trackToWheelIds[i];
PxF32 multipliers[PxVehicleLimits::eMAX_NB_WHEELS];
const PxU32 wheelId0 = wheelsInTrack[0];
const PxF32 wheelRadius0 = wheelParams[wheelId0].radius;
//for (PxU32 j = 0; j < 1; j++)
{
//j = 0 is a special case with multiplier = 1.0
multipliers[0] = 1.0f;
}
for (PxU32 j = 1; j < nbWheelsInTrack; j++)
{
const PxU32 wheelIdJ = wheelsInTrack[j];
const PxF32 wheelRadiusJ = wheelParams[wheelIdJ].radius;
multipliers[j] = wheelRadius0 / wheelRadiusJ;
}
wheelConstraintGroupState.addConstraintGroup(nbWheelsInTrack, wheelsInTrack, multipliers);
}
}
}
void PxVehicleEngineDriveActuationStateUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleGearboxParams& gearboxParams,
const PxVehicleArrayData<const PxReal>& brakeResponseStates,
const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState,
const PxVehicleGearboxState& gearboxState, const PxVehicleDifferentialState& diffState, const PxVehicleClutchCommandResponseState& clutchResponseState,
PxVehicleArrayData<PxVehicleWheelActuationState>& actuationStates)
{
//Which wheels receive drive torque from the engine?
const PxF32* diffTorqueRatios = diffState.torqueRatiosAllWheels;
//Work out the clutch strength.
//If the cutch strength is zero then none of the wheels receive drive torque from the engine.
const PxF32 K = PxVehicleClutchStrengthCompute(clutchResponseState, gearboxParams, gearboxState);
//Work out the applied throttle
const PxF32 appliedThrottle = throttleResponseState.commandResponse;
//Ready to set the boolean actuation state that is used to compute the tire slips.
//(Note: for a tire under drive or brake torque we compute the slip with a smaller denominator to accentuate the applied torque).
//(Note: for a tire that is not under drive or brake torque we compute the sip with a larger denominator to smooth the vehicle slowing down).
for(PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
//Reset the actuation states.
PxVehicleWheelActuationState& actState = actuationStates[wheelId];
PxMemZero(&actState, sizeof(PxVehicleWheelActuationState));
const PxF32 brakeTorque = brakeResponseStates[wheelId];
const PxF32 diffTorqueRatio = diffTorqueRatios[wheelId];
const bool isIntentionToAccelerate = (0.0f == brakeTorque) && (K != 0.0f) && (diffTorqueRatio != 0.0f) && (appliedThrottle != 0.0f);
actState.isDriveApplied = isIntentionToAccelerate;
actState.isBrakeApplied = (brakeTorque!= 0.0f);
}
}
void PxVehicleGearCommandResponseUpdate
(const PxU32 targetGearCommand,
const PxVehicleGearboxParams& gearboxParams,
PxVehicleGearboxState& gearboxState)
{
//Check that we're not halfway through a gear change and we need to execute a change of gear.
//If we are halfway through a gear change then we cannot execute another until the first is complete.
//Check that the command stays in a legal gear range.
if ((gearboxState.currentGear == gearboxState.targetGear) && (targetGearCommand != gearboxState.currentGear) && (targetGearCommand < gearboxParams.nbRatios))
{
//We're not executing a gear change and we need to start one.
//Start the gear change by
//a)setting the target gear.
//b)putting vehicle in neutral
//c)set the switch time to PX_VEHICLE_GEAR_SWITCH_INITIATED to flag that we just started a gear change.
gearboxState.currentGear = gearboxParams.neutralGear;
gearboxState.targetGear = targetGearCommand;
gearboxState.gearSwitchTime = PX_VEHICLE_GEAR_SWITCH_INITIATED;
}
}
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)
{
if(targetGearCommand != PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR)
{
autoboxState.activeAutoboxGearShift = false;
autoboxState.timeSinceLastShift = PX_VEHICLE_UNSPECIFIED_TIME_SINCE_LAST_SHIFT;
return;
}
//Current and target gear allow us to determine if a gear change is underway.
const PxU32 currentGear = gearboxState.currentGear;
const PxU32 targetGear = gearboxState.targetGear;
//Set to current target gear in case no gear change will be initiated.
targetGearCommand = targetGear;
//If the autobox triggered a gear change and the gear change is complete then
//reset the corresponding flag.
if(autoboxState.activeAutoboxGearShift && (currentGear == targetGear))
{
autoboxState.activeAutoboxGearShift = false;
}
//If the autobox triggered a gear change and the gear change is incomplete then
//turn off the throttle pedal. This happens in autoboxes
//to stop the driver revving the engine then damaging the
//clutch when the clutch re-engages at the end of the gear change.
if(autoboxState.activeAutoboxGearShift && (currentGear != targetGear))
{
throttle = 0.0f;
}
//Only process the autobox if no gear change is underway and the time passed since
//the last autobox gear change is greater than the autobox latency.
if (targetGear == currentGear)
{
const PxF32 autoBoxSwitchTime = autoboxState.timeSinceLastShift;
const PxF32 autoBoxLatencyTime = autoboxParams.latency;
if ((currentGear <= gearboxParams.neutralGear) && ((gearboxParams.neutralGear + 1) < gearboxParams.nbRatios))
{
// eAUTOMATIC_GEAR has been set while in neutral or one of the reverse gears
// => switch to first
targetGearCommand = gearboxParams.neutralGear + 1;
throttle = 0.0f;
autoboxState.timeSinceLastShift = 0.0f;
autoboxState.activeAutoboxGearShift = true;
}
else if (autoBoxSwitchTime > autoBoxLatencyTime)
{
const PxF32 normalisedEngineOmega = engineState.rotationSpeed/engineParams.maxOmega;
const PxU32 neutralGear = gearboxParams.neutralGear;
const PxU32 nbGears = gearboxParams.nbRatios;
const PxF32 upRatio = autoboxParams.upRatios[currentGear];
const PxF32 downRatio = autoboxParams.downRatios[currentGear];
//If revs too high and not in reverse/neutral and there is a higher gear then switch up.
//Note: never switch up from neutral to first
//Note: never switch up from reverse to neutral
//Note: never switch up from one reverse gear to another reverse gear.
PX_ASSERT(currentGear > neutralGear);
if ((normalisedEngineOmega > upRatio) && ((currentGear + 1) < nbGears))
{
targetGearCommand = currentGear + 1;
throttle = 0.0f;
autoboxState.timeSinceLastShift = 0.0f;
autoboxState.activeAutoboxGearShift = true;
}
//If revs too low and in gear higher than first then switch down.
//Note: never switch from forward to neutral
//Note: never switch from neutral to reverse
//Note: never switch from reverse gear to reverse gear.
if ((normalisedEngineOmega < downRatio) && (currentGear > (neutralGear + 1)))
{
targetGearCommand = currentGear - 1;
throttle = 0.0f;
autoboxState.timeSinceLastShift = 0.0f;
autoboxState.activeAutoboxGearShift = true;
}
}
else
{
autoboxState.timeSinceLastShift += dt;
}
}
else
{
autoboxState.timeSinceLastShift += dt;
}
}
void PxVehicleGearboxUpdate(const PxVehicleGearboxParams& gearboxParams, const PxF32 dt, PxVehicleGearboxState& gearboxState)
{
if(gearboxState.targetGear != gearboxState.currentGear)
{
//If we just started a gear change then set the timer to zero.
//This replicates legacy behaviour.
if(gearboxState.gearSwitchTime == PX_VEHICLE_GEAR_SWITCH_INITIATED)
gearboxState.gearSwitchTime = 0.0f;
else
gearboxState.gearSwitchTime += dt;
//If we've exceed the switch time then switch to the target gear
//and reset the timer.
if (gearboxState.gearSwitchTime > gearboxParams.switchTime)
{
gearboxState.currentGear = gearboxState.targetGear;
gearboxState.gearSwitchTime = PX_VEHICLE_NO_GEAR_SWITCH_PENDING;
}
}
}
void countConnectedWheelsNotInConstraintGroup
(const PxU32* connectedWheelIds, const PxU32 nbConnectedWheelIds, const PxVehicleWheelConstraintGroupState& constraintGroups,
PxU32 connectedWheelsNotInConstraintGroup[PxVehicleLimits::eMAX_NB_WHEELS], PxU32& nbConnectedWheelsNotInConstraintGroup)
{
//Record the constraint group for each wheel.
//0xffffffff is reserved for a wheel not in a constraint group.
PxU32 wheelConstraintGroupIds[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemSet(wheelConstraintGroupIds, 0xffffffff, sizeof(wheelConstraintGroupIds));
for (PxU32 i = 0; i < constraintGroups.getNbConstraintGroups(); i++)
{
for (PxU32 j = 0; j < constraintGroups.getNbWheelsInConstraintGroup(i); j++)
{
const PxU32 wheelId = constraintGroups.getWheelInConstraintGroup(j, i);
wheelConstraintGroupIds[wheelId] = i;
}
}
//Iterate over all connected wheels and count the number not in a group.
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
const PxU32 constraintGroupId = wheelConstraintGroupIds[wheelId];
if (0xffffffff == constraintGroupId)
{
connectedWheelsNotInConstraintGroup[nbConnectedWheelsNotInConstraintGroup] = wheelId;
nbConnectedWheelsNotInConstraintGroup++;
}
}
}
void PxVehicleEngineDrivetrainUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleEngineParams& engineParams, const PxVehicleClutchParams& clutchParams, const PxVehicleGearboxParams& gearboxParams,
const PxVehicleArrayData<const PxReal>& brakeResponseStates,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehicleGearboxState& gearboxState,
const PxVehicleEngineDriveThrottleCommandResponseState& throttleCommandResponseState, const PxVehicleClutchCommandResponseState& clutchCommandResponseState,
const PxVehicleDifferentialState& diffState, const PxVehicleWheelConstraintGroupState* constraintGroupState,
const PxReal DT,
PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidbody1dStates,
PxVehicleEngineState& engineState,
PxVehicleClutchSlipState& clutchState)
{
const PxF32 K = PxVehicleClutchStrengthCompute(clutchCommandResponseState, gearboxParams, gearboxState);
const PxF32 G = PxVehicleGearRatioCompute(gearboxParams, gearboxState);
const PxF32 engineDriveTorque = PxVehicleEngineDriveTorqueCompute(engineParams, engineState, throttleCommandResponseState);
const PxF32 engineDampingRate = PxVehicleEngineDampingRateCompute(engineParams, gearboxParams, gearboxState, clutchCommandResponseState, throttleCommandResponseState);
//Arrange wheel parameters in they order they appear in the connected wheel list.
const PxU32* connectedWheelIds = diffState.connectedWheels;
const PxU32 nbConnectedWheelIds = diffState.nbConnectedWheels;
PxU32 wheelIdToConnectedWheelId[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelDiffTorqueRatios[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelGearings[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelAveWheelSpeedContributions[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelMois[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelRotSpeeds[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelBrakeTorques[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelTireTorques[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelDampingRates[PxVehicleLimits::eMAX_NB_WHEELS];
bool connectedWheelIsBrakeApplied[PxVehicleLimits::eMAX_NB_WHEELS];
//PxF32 connectedWheelRadii[PxVehicleLimits::eMAX_NB_WHEELS];
for(PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
wheelIdToConnectedWheelId[wheelId] = i;
connectedWheelDiffTorqueRatios[i] = PxAbs(diffState.torqueRatiosAllWheels[wheelId]);
connectedWheelGearings[i] = PxVehicleComputeSign(diffState.torqueRatiosAllWheels[wheelId]);
connectedWheelAveWheelSpeedContributions[i] = diffState.aveWheelSpeedContributionAllWheels[wheelId];
connectedWheelMois[i] = wheelParams[wheelId].moi;
connectedWheelRotSpeeds[i] = wheelRigidbody1dStates[wheelId].rotationSpeed;
connectedWheelBrakeTorques[i] = -PxVehicleComputeSign(wheelRigidbody1dStates[wheelId].rotationSpeed)*brakeResponseStates[wheelId];
connectedWheelTireTorques[i] = tireForces[wheelId].wheelTorque;
connectedWheelDampingRates[i] = wheelParams[wheelId].dampingRate;
connectedWheelIsBrakeApplied[i] = actuationStates[wheelId].isBrakeApplied;
//connectedWheelRadii[i] = wheelParams[wheelId].radius;
};
//Compute the clutch slip
clutchState.setToDefault();
PxF32 clutchSlip = 0;
{
PxF32 averageWheelSpeed = 0;
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
averageWheelSpeed += connectedWheelRotSpeeds[i] * connectedWheelAveWheelSpeedContributions[i];
}
clutchSlip = G*averageWheelSpeed - engineState.rotationSpeed;
}
clutchState.clutchSlip = clutchSlip;
//
//torque at clutch:
//tc = K*{G*[alpha0*w0 + alpha1*w1 + alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}
//where
//(i) G is the gearing ratio,
//(ii) alphai is the fractional contribution of the ith wheel to the average wheel speed at the clutch (alpha(i) is zero for undriven wheels)
//(iii) wi is the angular speed of the ith wheel
//(iv) K is the clutch strength
//(v) wEng is the angular speed of the engine
//torque applied to ith wheel is
//ti = G*gammai*tc + bt(i) + tt(i)
//where
//gammai is the fractional proportion of the clutch torque that the differential delivers to the ith wheel
//bt(i) is the brake torque applied to the ith wheel
//tt(i) is the tire torque applied to the ith wheel
//acceleration applied to ith wheel is
//ai = G*gammai*K*{G*[alpha0*w0 + alpha1*w1 alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}/Ii + (bt(i) + tt(i))/Ii
//wheer Ii is the moi of the ith wheel
//express ai as
//ai = [wi(t+dt) - wi(t)]/dt
//and rearrange
//wi(t+dt) - wi(t)] = dt*G*gammai*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1)(t+dt)] - wEng(t+dt)}/Ii + dt*(bt(i) + tt(i))/Ii
//Do the same for tEng (torque applied to engine)
//tEng = -tc + engineDriveTorque
//where engineDriveTorque is the drive torque applied to the engine
//Assuming the engine has unit mass then
//wEng(t+dt) -wEng(t) = -dt*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1(t+dt))] - wEng(t+dt)}/Ieng + dt*engineDriveTorque]/IEng
//Introduce the vector w=(w0,w1,w2....w(N-1), wEng)
//and re-express as a matrix after collecting all unknowns at (t+dt) and knowns at time t.
//A*w(t+dt)=b(t);
PxVehicleMatrixNN M(nbConnectedWheelIds + 1);
PxVehicleVectorN b(nbConnectedWheelIds + 1);
PxVehicleVectorN result(nbConnectedWheelIds + 1);
const PxF32 KG = K * G;
const PxF32 KGG = K * G*G;
//Wheels
{
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxF32 dt = DT / connectedWheelMois[i];
const PxF32 R = connectedWheelDiffTorqueRatios[i];
const PxF32 g = connectedWheelGearings[i];
const PxF32 dtKGGRg = dt * KGG*R*g;
for(PxU32 j = 0; j < nbConnectedWheelIds; j++)
{
M.set(i, j, dtKGGRg*connectedWheelAveWheelSpeedContributions[j]*connectedWheelGearings[j]);
}
M.set(i, i, 1.0f + dtKGGRg*connectedWheelAveWheelSpeedContributions[i]*connectedWheelGearings[i] + dt * connectedWheelDampingRates[i]);
M.set(i, nbConnectedWheelIds, -dt*KG*R*g);
b[i] = connectedWheelRotSpeeds[i] + dt * (connectedWheelBrakeTorques[i] + connectedWheelTireTorques[i]);
result[i] = connectedWheelRotSpeeds[i];
}
}
//Engine.
{
const PxF32 dt = DT / engineParams.moi;
const PxF32 dtKG = dt*K*G;
for(PxU32 j = 0; j < nbConnectedWheelIds; j++)
{
M.set(nbConnectedWheelIds, j, -dtKG * connectedWheelAveWheelSpeedContributions[j]* connectedWheelGearings[j]);
}
M.set(nbConnectedWheelIds, nbConnectedWheelIds, 1.0f + dt * (K + engineDampingRate));
b[nbConnectedWheelIds] = engineState.rotationSpeed + dt * engineDriveTorque;
result[nbConnectedWheelIds] = engineState.rotationSpeed;
}
if (constraintGroupState && constraintGroupState->getNbConstraintGroups() > 0)
{
const PxU32 nbConstraintGroups = constraintGroupState->getNbConstraintGroups();
//Count the wheels not in a constraint group.
PxU32 connectedWheelsNotInConstraintGroup[PxVehicleLimits::eMAX_NB_WHEELS];
PxU32 nbConnectedWheelsNotInConstraintGroup = 0;
countConnectedWheelsNotInConstraintGroup(
connectedWheelIds, nbConnectedWheelIds, *constraintGroupState,
connectedWheelsNotInConstraintGroup, nbConnectedWheelsNotInConstraintGroup);
//After applying constraint groups:
// number of columns remains nbConnectedWheelIds + 1
// each row will be of length nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups + 1
PxVehicleMatrixNN A(nbConnectedWheelIds + 1);
for (PxU32 i = 0; i < nbConnectedWheelIds + 1; i++)
{
//1 entry for each wheel not in a constraint group.
for (PxU32 j = 0; j < nbConnectedWheelsNotInConstraintGroup; j++)
{
const PxU32 wheelId = connectedWheelsNotInConstraintGroup[j];
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
const PxF32 MIJ = M.get(i, connectedWheelId);
A.set(i, j, MIJ);
}
//1 entry for each constraint group.
for (PxU32 j = nbConnectedWheelsNotInConstraintGroup; j < nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups; j++)
{
const PxU32 constraintGroupId = (j - nbConnectedWheelsNotInConstraintGroup);
PxF32 sum = 0.0f;
//for (PxU32 k = 0; k < 1; k++)
{
//k = 0 is a special case with multiplier = 1.0.
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(0, constraintGroupId);
const PxF32 multiplier = 1.0f;
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
const PxF32 MIK = M.get(i, connectedWheelId);
sum += MIK * multiplier;
}
for (PxU32 k = 1; k < constraintGroupState->getNbWheelsInConstraintGroup(constraintGroupId); k++)
{
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(k, constraintGroupId);
const PxF32 multiplier = constraintGroupState->getMultiplierInConstraintGroup(k, constraintGroupId);
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
const PxF32 MIK = M.get(i, connectedWheelId);
sum += MIK*multiplier;
}
A.set(i, j, sum);
}
//1 entry for the engine.
{
const PxF32 MIJ = M.get(i, nbConnectedWheelIds);
A.set(i, nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups, MIJ);
}
}
const PxU32 N = (nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups + 1);
//Compute A^T * A
PxVehicleMatrixNN ATA(N);
for (PxU32 i = 0; i < N; i++)
{
for (PxU32 j = 0; j < N; j++)
{
PxF32 sum = 0.0f;
for (PxU32 k = 0; k < nbConnectedWheelIds + 1; k++)
{
sum += A.get(k, i)*A.get(k, j);
}
ATA.set(i, j, sum);
}
}
//Compute A^T*b;
PxVehicleVectorN ATb(N);
for (PxU32 i = 0; i < N; i++)
{
PxF32 sum = 0;
for (PxU32 j = 0; j < nbConnectedWheelIds + 1; j++)
{
sum += A.get(j, i)*b[j];
}
ATb[i] = sum;
}
//Solve it.
PxVehicleMatrixNNLUSolver solver;
PxVehicleVectorN result2(N);
solver.decomposeLU(ATA);
solver.solve(ATb, result2);
//Map from result2 back to result.
for (PxU32 j = 0; j < nbConnectedWheelsNotInConstraintGroup; j++)
{
const PxU32 wheelId = connectedWheelsNotInConstraintGroup[j];
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
result[connectedWheelId] = result2[j];
}
for (PxU32 j = nbConnectedWheelsNotInConstraintGroup; j < nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups; j++)
{
const PxU32 constraintGroupId = (j - nbConnectedWheelsNotInConstraintGroup);
//for (PxU32 k = 0; k < 1; k++)
{
//k = 0 is a special case with multiplier = 1.0
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(0, constraintGroupId);
const PxF32 multiplier = 1.0f;
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
result[connectedWheelId] = multiplier * result2[j];
}
for (PxU32 k = 1; k < constraintGroupState->getNbWheelsInConstraintGroup(constraintGroupId); k++)
{
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(k, constraintGroupId);
const PxF32 multiplier = constraintGroupState->getMultiplierInConstraintGroup(k, constraintGroupId);
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
result[connectedWheelId] = multiplier * result2[j];
}
}
{
result[nbConnectedWheelIds] = result2[nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups];
}
}
else if (PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == clutchParams.accuracyMode)
{
//Solve Aw=b
PxVehicleMatrixNNLUSolver solver;
solver.decomposeLU(M);
solver.solve(b, result);
//PX_WARN_ONCE_IF(!isValid(A, b, result), "Unable to compute new PxVehicleDrive4W internal rotation speeds. Please check vehicle sim data, especially clutch strength; engine moi and damping; wheel moi and damping");
}
else
{
PxVehicleMatrixNGaussSeidelSolver solver;
solver.solve(clutchParams.estimateIterations, 1e-10f, M, b, result);
}
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//A consequence of this quick fix is that locked wheels remain locked until the brake is entirely released.
//This isn't strictly mathematically or physically correct - a more accurate solution would either formulate the
//brake as a lcp problem or repeatedly solve with constraints that locked wheels remain at zero rotation speed.
//The physically correct solution will certainly be more expensive so let's live with the restriction that
//locked wheels remain locked until the brake is released.
//newOmega=result[i], oldOmega=wheelSpeeds[i], if newOmega*oldOmega<=0 and isBrakeApplied then lock wheel.
for(PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
result[i] = (connectedWheelIsBrakeApplied[i] && (connectedWheelRotSpeeds[i] * result[i] <= 0)) ? 0.0f : result[i];
}
//Clamp the engine revs.
//Again, this is not physically or mathematically correct but the loss in behaviour will be hard to notice.
//The alternative would be to add constraints to the solver, which would be much more expensive.
result[nbConnectedWheelIds] = PxClamp(result[nbConnectedWheelIds], engineParams.idleOmega, engineParams.maxOmega);
//Copy back to the car's internal rotation speeds.
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
wheelRigidbody1dStates[wheelId].rotationSpeed = result[i];
}
engineState.rotationSpeed = result[nbConnectedWheelIds];
//Update the undriven wheels.
bool isDrivenWheel[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemZero(isDrivenWheel, sizeof(isDrivenWheel));
for(PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
isDrivenWheel[wheelId] = true;
}
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if (!isDrivenWheel[wheelId])
{
PxVehicleDirectDriveUpdate(
wheelParams[wheelId],
actuationStates[wheelId],
brakeResponseStates[wheelId], 0.0f,
tireForces[wheelId], DT, wheelRigidbody1dStates[wheelId]);
}
}
}
void PxVehicleClutchCommandResponseLinearUpdate
(const PxReal clutchCommand,
const PxVehicleClutchCommandResponseParams& clutchResponseParams,
PxVehicleClutchCommandResponseState& clutchResponse)
{
clutchResponse.normalisedCommandResponse = (1.0f - clutchCommand);
clutchResponse.commandResponse = (1.0f - clutchCommand)*clutchResponseParams.maxResponse;
}
void PxVehicleEngineDriveThrottleCommandResponseLinearUpdate
(const PxVehicleCommandState& commands,
PxVehicleEngineDriveThrottleCommandResponseState& throttleResponse)
{
throttleResponse.commandResponse = commands.throttle;
}
} //namespace vehicle2
} //namespace physx
| 40,132 |
C++
| 40.077789 | 218 | 0.75598 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "VhPvdAttributeHandles.h"
#include "VhPvdObjectHandles.h"
#include "VhPvdWriter.h"
#include "vehicle2/pvd/PxVehiclePvdFunctions.h"
#include "foundation/PxAllocatorCallback.h"
#include <stdio.h>
#include <stdlib.h>
namespace physx
{
namespace vehicle2
{
#if PX_SUPPORT_OMNI_PVD
PX_FORCE_INLINE void createPvdObject
(OmniPvdWriter& omniWriter, OmniPvdContextHandle contextHandle,
OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName)
{
omniWriter.createObject(contextHandle, classHandle, objectHandle, objectName);
}
PX_FORCE_INLINE void writeObjectHandleAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah,
OmniPvdObjectHandle val)
{
PX_ASSERT(oh);
PX_ASSERT(ah);
if(val)
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(OmniPvdObjectHandle));
}
PX_FORCE_INLINE void addObjectHandleToUniqueList
(OmniPvdWriter& ow, OmniPvdContextHandle ch, OmniPvdObjectHandle setOwnerOH, OmniPvdAttributeHandle setAH, OmniPvdObjectHandle ohToAdd)
{
PX_ASSERT(setOwnerOH);
PX_ASSERT(setAH);
if(ohToAdd)
ow.addToUniqueListAttribute(ch, setOwnerOH, setAH, reinterpret_cast<const uint8_t*>(&ohToAdd), sizeof(OmniPvdObjectHandle));
}
PX_FORCE_INLINE void appendWithInt(char* buffer, PxU32 number)
{
char num[8];
sprintf(num, "%d", number);
strcat(buffer, num);
}
PX_FORCE_INLINE void createVehicleObject
(const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter)
{
// Register the top-level vehicle object if this hasn't already been done.
if(0 == objectHandles.vehicleOH)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle vehicleOH = reinterpret_cast<OmniPvdObjectHandle>(&objectHandles.vehicleOH);
createPvdObject(omniWriter, objectHandles.contextHandle, attributeHandles.vehicle.CH, vehicleOH, "Vehicle");
objectHandles.vehicleOH = vehicleOH;
}
}
/////////////////////////////////
//RIGID BODY
/////////////////////////////////
void PxVehiclePvdRigidBodyRegister
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(rbodyParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.rigidBodyParamsOH);
createPvdObject(ow, ch, ah.rigidBodyParams.CH, oh, "RigidBodyParams");
objHands.rigidBodyParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.rigidBodyParamsAH, oh);
}
if(rbodyState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.rigidBodyStateOH);
createPvdObject(ow, ch, ah.rigidBodyState.CH, oh, "RigidBodyState");
objHands.rigidBodyStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.rigidBodyStateAH, oh);
}
}
void PxVehiclePvdRigidBodyWrite
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
const OmniPvdContextHandle ch = oh.contextHandle;
if(oh.rigidBodyParamsOH && rbodyParams)
{
writeRigidBodyParams(*rbodyParams, oh.rigidBodyParamsOH, ah.rigidBodyParams, ow, ch);
}
if(oh.rigidBodyStateOH && rbodyState)
{
writeRigidBodyState(*rbodyState, oh.rigidBodyStateOH, ah.rigidBodyState, ow, ch);
}
}
//////////////////////////////
//SUSP STATE CALC PARAMS
//////////////////////////////
void PxVehiclePvdSuspensionStateCalculationParamsRegister
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(suspStateCalcParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspStateCalcParamsOH);
createPvdObject(ow, ch, ah.suspStateCalcParams.CH, oh, "SuspStateCalcParams");
objHands.suspStateCalcParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.suspStateCalcParamsAH, oh);
}
}
void PxVehiclePvdSuspensionStateCalculationParamsWrite
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& omniWriter)
{
if(oh.suspStateCalcParamsOH && suspStateCalcParams)
{
writeSuspStateCalcParams(*suspStateCalcParams, oh.suspStateCalcParamsOH, ah.suspStateCalcParams, omniWriter, oh.contextHandle);
}
}
/////////////////////////////
//COMMAND RESPONSE PARAMS
/////////////////////////////
void PxVehiclePvdCommandResponseRegister
(const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
brakeResponseParams.size <= 2,
"PxVehiclePvdCommandResponseRegister : brakeResponseParams.size must have less than or equal to 2");
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
for(PxU32 i = 0; i < brakeResponseParams.size; i++)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.brakeResponseParamOHs[i]);
char objectName[32] = "BrakeComandResponseParams";
appendWithInt(objectName, i);
createPvdObject(ow, ch, ah.brakeCommandResponseParams.CH, oh, objectName);
objHands.brakeResponseParamOHs[i] = oh;
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.brakeResponseParamsSetAH, oh);
}
if(steerResponseParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.steerResponseParamsOH);
const char objectName[32] = "SteerCommandResponseParams";
createPvdObject(ow, ch, ah.steerCommandResponseParams.CH, oh, objectName);
objHands.steerResponseParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.steerResponseParamsAH, oh);
}
if (ackermannParams)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.ackermannParamsOH);
createPvdObject(ow, ch, ah.ackermannParams.CH, oh, "AckermannParams");
objHands.ackermannParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.ackermannParamsAH, oh);
}
if(!brakeResponseStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.brakeResponseStateOH);
const char objectName[32] = "BrakeCommandResponseStates";
createPvdObject(ow, ch, ah.brakeCommandResponseStates.CH, oh, objectName);
objHands.brakeResponseStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.brakeResponseStatesAH, oh);
}
if(!steerResponseStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.steerResponseStateOH);
const char objectName[32] = "SteerCommandResponseStates";
createPvdObject(ow, ch, ah.steerCommandResponseStates.CH, oh, objectName);
objHands.steerResponseStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.steerResponseStatesAH, oh);
}
}
void PxVehiclePvdCommandResponseWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
brakeResponseParams.size <= 2,
"PxVehiclePvdCommandResponseWrite : brakeResponseParams.size must have less than or equal to 2");
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < brakeResponseParams.size; i++)
{
if(oh.brakeResponseParamOHs[i])
{
writeBrakeResponseParams(
axleDesc, brakeResponseParams[i],
oh.brakeResponseParamOHs[i], ah.brakeCommandResponseParams, ow, ch);
}
}
if(oh.steerResponseParamsOH && steerResponseParams)
{
writeSteerResponseParams(
axleDesc, *steerResponseParams,
oh.steerResponseParamsOH, ah.steerCommandResponseParams, ow, ch);
}
if (oh.ackermannParamsOH && ackermannParams)
{
writeAckermannParams(*ackermannParams, oh.ackermannParamsOH, ah.ackermannParams, ow, ch);
}
if(oh.brakeResponseStateOH && !brakeResponseStates.isEmpty())
{
writeBrakeResponseStates(axleDesc, brakeResponseStates, oh.brakeResponseStateOH, ah.brakeCommandResponseStates, ow, ch);
}
if(oh.steerResponseStateOH && !steerResponseStates.isEmpty())
{
writeSteerResponseStates(axleDesc, steerResponseStates, oh.steerResponseStateOH, ah.steerCommandResponseStates, ow, ch);
}
}
void PxVehiclePvdWheelAttachmentsRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspCompParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
// Register the wheel attachments
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < objHands.nbWheels,
"PxVehiclePvdWheelAttachmentsRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(!wheelParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelParamsOHs[wheelId]);
char objectName[32] = "WheelParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelParams.CH, oh, objectName);
objHands.wheelParamsOHs[wheelId] = oh;
}
if(!wheelActuationStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelActuationStateOHs[wheelId]);
char objectName[32] = "WheelActuationState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelActuationState.CH, oh, objectName);
objHands.wheelActuationStateOHs[wheelId] = oh;
}
if(!wheelRigidBody1dStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelRigidBody1dStateOHs[wheelId]);
char objectName[32] = "WheelRigidBody1dState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelRigidBody1dState.CH, oh, objectName);
objHands.wheelRigidBody1dStateOHs[wheelId] = oh;
}
if(!wheelLocalPoses.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelLocalPoseStateOHs[wheelId]);
char objectName[32] = "WheelLocalPoseState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelLocalPoseState.CH, oh, objectName);
objHands.wheelLocalPoseStateOHs[wheelId] = oh;
}
if(!roadGeometryStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.roadGeomStateOHs[wheelId]);
char objectName[32] = "RoadGeometryState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.roadGeomState.CH, oh, objectName);
objHands.roadGeomStateOHs[wheelId] = oh;
}
if(!suspParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspParamsOHs[wheelId]);
char objectName[32] = "SuspParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspParams.CH, oh, objectName);
objHands.suspParamsOHs[wheelId] = oh;
}
if(!suspCompParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspCompParamsOHs[wheelId]);
char objectName[32] = "SuspCompParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspCompParams.CH, oh, objectName);
objHands.suspCompParamsOHs[wheelId] = oh;
}
if(!suspForceParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspForceParamsOHs[wheelId]);
char objectName[32] = "SuspForceParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspForceParams.CH, oh, objectName);
objHands.suspForceParamsOHs[wheelId] = oh;
}
if(!suspStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspStateOHs[wheelId]);
char objectName[32] = "SuspState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspState.CH, oh, objectName);
objHands.suspStateOHs[wheelId] = oh;
}
if(!suspCompStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspCompStateOHs[wheelId]);
char objectName[32] = "SuspComplianceState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspCompState.CH, oh, objectName);
objHands.suspCompStateOHs[wheelId] = oh;
}
if(!suspForces.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspForceOHs[wheelId]);
char objectName[32] = "SuspForce";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspForce.CH, oh, objectName);
objHands.suspForceOHs[wheelId] = oh;
}
if(!tireForceParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireParamsOHs[wheelId]);
char objectName[32] = "TireParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireParams.CH, oh, objectName);
objHands.tireParamsOHs[wheelId] = oh;
}
if(!tireDirectionStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireDirectionStateOHs[wheelId]);
char objectName[32] = "TireDirectionState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireDirectionState.CH, oh, objectName);
objHands.tireDirectionStateOHs[wheelId] = oh;
}
if(!tireSpeedStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireSpeedStateOHs[wheelId]);
char objectName[32] = "TireSpeedState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireSpeedState.CH, oh, objectName);
objHands.tireSpeedStateOHs[wheelId] = oh;
}
if(!tireSlipStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireSlipStateOHs[wheelId]);
char objectName[32] = "TireSlipState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireSlipState.CH, oh, objectName);
objHands.tireSlipStateOHs[wheelId] = oh;
}
if(!tireStickyStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireStickyStateOHs[wheelId]);
char objectName[32] = "TireStickyState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireStickyState.CH, oh, objectName);
objHands.tireStickyStateOHs[wheelId] = oh;
}
if(!tireGripStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireGripStateOHs[wheelId]);
char objectName[32] = "TireGripState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireGripState.CH, oh, objectName);
objHands.tireGripStateOHs[wheelId] = oh;
}
if(!tireCamberStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireCamberStateOHs[wheelId]);
char objectName[32] = "TireCamberState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireCamberState.CH, oh, objectName);
objHands.tireCamberStateOHs[wheelId] = oh;
}
if(!tireForces.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireForceOHs[wheelId]);
char objectName[32] = "TireForce";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireForce.CH, oh, objectName);
objHands.tireForceOHs[wheelId] = oh;
}
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelAttachmentOHs[wheelId]);
char objectName[32] = "WheelAttachment";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelAttachment.CH, oh, objectName);
objHands.wheelAttachmentOHs[wheelId] = oh;
// Point the wheel attachment object at the wheel params, susp state, tire force etc objects.
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelParamsAH, objHands.wheelParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelActuationStateAH, objHands.wheelActuationStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelRigidBody1dStateAH, objHands.wheelRigidBody1dStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelLocalPoseStateAH, objHands.wheelLocalPoseStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.roadGeomStateAH, objHands.roadGeomStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspParamsAH, objHands.suspParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspCompParamsAH, objHands.suspCompParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspForceParamsAH, objHands.suspForceParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspStateAH, objHands.suspStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspCompStateAH, objHands.suspCompStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspForceAH, objHands.suspForceOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireParamsAH, objHands.tireParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireDirectionStateAH, objHands.tireDirectionStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireSpeedStateAH, objHands.tireSpeedStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireSlipStateAH, objHands.tireSlipStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireStickyStateAH, objHands.tireStickyStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireGripStateAH, objHands.tireGripStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireCamberStateAH, objHands.tireCamberStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireForceAH, objHands.tireForceOHs[wheelId]);
//Point the vehicle object at the wheel attachment object.
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.wheelAttachmentSetAH, oh);
}
}
}
void PxVehiclePvdWheelAttachmentsWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspComplianceParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < oh.nbWheels,
"PxVehiclePvdWheelAttachmentsRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(oh.wheelParamsOHs[wheelId] && !wheelParams.isEmpty())
{
writeWheelParams(wheelParams[wheelId], oh.wheelParamsOHs[wheelId], ah.wheelParams, ow, ch);
}
if(oh.wheelActuationStateOHs[wheelId] && !wheelActuationStates.isEmpty())
{
writeWheelActuationState(wheelActuationStates[wheelId], oh.wheelActuationStateOHs[wheelId], ah.wheelActuationState, ow, ch);
}
if(oh.wheelRigidBody1dStateOHs[wheelId] && !wheelRigidBody1dStates.isEmpty())
{
writeWheelRigidBody1dState(wheelRigidBody1dStates[wheelId], oh.wheelRigidBody1dStateOHs[wheelId], ah.wheelRigidBody1dState, ow, ch);
}
if(oh.wheelLocalPoseStateOHs[wheelId] && !wheelLocalPoses.isEmpty())
{
writeWheelLocalPoseState(wheelLocalPoses[wheelId], oh.wheelLocalPoseStateOHs[wheelId], ah.wheelLocalPoseState, ow, ch);
}
if(oh.roadGeomStateOHs[wheelId] && !roadGeometryStates.isEmpty())
{
writeRoadGeomState(roadGeometryStates[wheelId], oh.roadGeomStateOHs[wheelId], ah.roadGeomState, ow, ch);
}
if(oh.suspParamsOHs[wheelId] && !suspParams.isEmpty())
{
writeSuspParams(suspParams[wheelId], oh.suspParamsOHs[wheelId], ah.suspParams, ow, ch);
}
if(oh.suspCompParamsOHs[wheelId] && !suspComplianceParams.isEmpty())
{
writeSuspComplianceParams(suspComplianceParams[wheelId], oh.suspCompParamsOHs[wheelId], ah.suspCompParams, ow, ch);
}
if(oh.suspForceParamsOHs[wheelId] && !suspForceParams.isEmpty())
{
writeSuspForceParams(suspForceParams[wheelId], oh.suspForceParamsOHs[wheelId], ah.suspForceParams, ow, ch);
}
if(oh.suspStateOHs[wheelId] && !suspStates.isEmpty())
{
writeSuspState(suspStates[wheelId], oh.suspStateOHs[wheelId], ah.suspState, ow, ch);
}
if(oh.suspCompStateOHs[wheelId] && !suspCompStates.isEmpty())
{
writeSuspComplianceState(suspCompStates[wheelId], oh.suspCompStateOHs[wheelId], ah.suspCompState, ow, ch);
}
if(oh.suspForceOHs[wheelId] && !suspForces.isEmpty())
{
writeSuspForce(suspForces[wheelId], oh.suspForceOHs[wheelId], ah.suspForce, ow, ch);
}
if(oh.tireParamsOHs[wheelId] && !tireForceParams.isEmpty())
{
writeTireParams(tireForceParams[wheelId], oh.tireParamsOHs[wheelId], ah.tireParams, ow, ch);
}
if(oh.tireDirectionStateOHs[wheelId] && !tireDirectionStates.isEmpty())
{
writeTireDirectionState(tireDirectionStates[wheelId], oh.tireDirectionStateOHs[wheelId], ah.tireDirectionState, ow, ch);
}
if(oh.tireSpeedStateOHs[wheelId] && !tireSpeedStates.isEmpty())
{
writeTireSpeedState(tireSpeedStates[wheelId], oh.tireSpeedStateOHs[wheelId], ah.tireSpeedState, ow, ch);
}
if(oh.tireSlipStateOHs[wheelId] && !tireSlipStates.isEmpty())
{
writeTireSlipState(tireSlipStates[wheelId], oh.tireSlipStateOHs[wheelId], ah.tireSlipState, ow, ch);
}
if(oh.tireStickyStateOHs[wheelId] && !tireStickyStates.isEmpty())
{
writeTireStickyState(tireStickyStates[wheelId], oh.tireStickyStateOHs[wheelId], ah.tireStickyState, ow, ch);
}
if(oh.tireGripStateOHs[wheelId] && !tireGripStates.isEmpty())
{
writeTireGripState(tireGripStates[wheelId], oh.tireGripStateOHs[wheelId], ah.tireGripState, ow, ch);
}
if(oh.tireCamberStateOHs[wheelId] && !tireCamberStates.isEmpty())
{
writeTireCamberState(tireCamberStates[wheelId], oh.tireCamberStateOHs[wheelId], ah.tireCamberState, ow, ch);
}
if(oh.tireForceOHs[wheelId] && !tireForces.isEmpty())
{
writeTireForce(tireForces[wheelId], oh.tireForceOHs[wheelId], ah.tireForce, ow, ch);
}
}
}
void PxVehiclePvdDirectDrivetrainRegister
(const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(commandState)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveCommandStateOH);
createPvdObject(ow, ch, ah.directDriveCommandState.CH, oh, "DirectDriveCommandState");
objHands.directDriveCommandStateOH = oh;
}
if(transmissionState)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveTransmissionCommandStateOH);
createPvdObject(ow, ch, ah.directDriveTransmissionCommandState.CH, oh, "DirectDriveTransmissionCommandState");
objHands.directDriveTransmissionCommandStateOH = oh;
}
if(directDriveThrottleResponseParams)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveThrottleResponseParamsOH);
createPvdObject(ow, ch, ah.directDriveThrottleCommandResponseParams.CH, oh, "DirectDriveThrottleResponseParams");
objHands.directDriveThrottleResponseParamsOH = oh;
}
if(!directDriveThrottleResponseState.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveThrottleResponseStateOH);
createPvdObject(ow, ch, ah.directDriveThrottleCommandResponseState.CH, oh, "DirectDriveThrottleResponseState");
objHands.directDriveThrottleResponseStateOH = oh;
}
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDrivetrainOH);
createPvdObject(ow, ch, ah.directDrivetrain.CH, oh, "DirectDrivetrain");
objHands.directDrivetrainOH = oh;
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.commandStateAH, objHands.directDriveCommandStateOH);
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.transmissionCommandStateAH, objHands.directDriveTransmissionCommandStateOH);
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.throttleResponseParamsAH, objHands.directDriveThrottleResponseParamsOH);
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.throttleResponseStateAH, objHands.directDriveThrottleResponseStateOH);
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.directDrivetrainAH, oh);
}
}
void PxVehiclePvdDirectDrivetrainWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
const OmniPvdContextHandle ch = oh.contextHandle;
if(oh.directDriveCommandStateOH && commandState)
{
writeDirectDriveCommandState(*commandState, oh.directDriveCommandStateOH, ah.directDriveCommandState, ow, ch);
}
if(oh.directDriveTransmissionCommandStateOH && transmissionState)
{
writeDirectDriveTransmissionCommandState(*transmissionState, oh.directDriveTransmissionCommandStateOH, ah.directDriveTransmissionCommandState, ow, ch);
}
if(oh.directDriveThrottleResponseParamsOH)
{
writeDirectDriveThrottleResponseParams(axleDesc, *directDriveThrottleResponseParams, oh.directDriveThrottleResponseParamsOH, ah.directDriveThrottleCommandResponseParams, ow, ch);
}
if(oh.directDriveThrottleResponseStateOH && !directDriveThrottleResponseState.isEmpty())
{
writeDirectDriveThrottleResponseState(axleDesc, directDriveThrottleResponseState, oh.directDriveThrottleResponseStateOH, ah.directDriveThrottleCommandResponseState, ow, ch);
}
}
void PxVehiclePvdEngineDrivetrainRegister
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
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& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(commandState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDriveCommandStateOH);
createPvdObject(ow, ch, ah.engineDriveCommandState.CH, oh, "EngineDriveCommandState");
objHands.engineDriveCommandStateOH = oh;
}
if(engineDriveTransmissionCommandState || tankDriveTransmissionCommandState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDriveTransmissionCommandStateOH);
objHands.engineDriveTransmissionCommandStateOH = oh;
if (engineDriveTransmissionCommandState)
{
createPvdObject(ow, ch, ah.engineDriveTransmissionCommandState.CH, oh, "EngineDriveTransmissionCommandState");
}
else
{
PX_ASSERT(tankDriveTransmissionCommandState);
createPvdObject(ow, ch, ah.tankDriveTransmissionCommandState.CH, oh, "TankDriveTransmissionCommandState");
}
}
if(clutchResponseParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchResponseParamsOH);
createPvdObject(ow, ch, ah.clutchCommandResponseParams.CH, oh, "ClutchResponseParams");
objHands.clutchResponseParamsOH = oh;
}
if(clutchParms)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchParamsOH);
createPvdObject(ow, ch, ah.clutchParams.CH, oh, "ClutchParams");
objHands.clutchParamsOH = oh;
}
if(engineParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineParamsOH);
createPvdObject(ow, ch, ah.engineParams.CH, oh, "EngineParams");
objHands.engineParamsOH = oh;
}
if(gearboxParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.gearboxParamsOH);
createPvdObject(ow, ch, ah.gearboxParams.CH, oh, "GearboxParams");
objHands.gearboxParamsOH = oh;
}
if(autoboxParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.autoboxParamsOH);
createPvdObject(ow, objHands.contextHandle, ah.autoboxParams.CH, oh, "AutoboxParams");
objHands.autoboxParamsOH = oh;
}
if(multiWheelDiffParams || fourWheelDiffParams || tankDiffParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.differentialParamsOH);
objHands.differentialParamsOH = oh;
if(multiWheelDiffParams)
{
createPvdObject(ow, ch, ah.multiwheelDiffParams.CH, oh, "MultiWheelDiffParams");
}
else if(fourWheelDiffParams)
{
createPvdObject(ow, ch, ah.fourwheelDiffParams.CH, oh, "FourWheelDiffParams");
}
else
{
PX_ASSERT(tankDiffParams);
createPvdObject(ow, ch, ah.tankDiffParams.CH, oh, "TankDiffParams");
}
}
if(clutchResponseState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchResponseStateOH);
createPvdObject(ow, ch, ah.clutchResponseState.CH, oh, "ClutchResponseState");
objHands.clutchResponseStateOH = oh;
}
if(throttleResponseState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDriveThrottleResponseStateOH);
createPvdObject(ow, ch, ah.throttleResponseState.CH, oh, "ThrottleResponseState");
objHands.engineDriveThrottleResponseStateOH = oh;
}
if(engineState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineStateOH);
createPvdObject(ow, ch, ah.engineState.CH, oh, "EngineState");
objHands.engineStateOH = oh;
}
if(gearboxState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.gearboxStateOH);
createPvdObject(ow, ch, ah.gearboxState.CH, oh, "GearboxState");
objHands.gearboxStateOH = oh;
}
if(autoboxState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.autoboxStateOH);
createPvdObject(ow, ch, ah.autoboxState.CH, oh, "AutoboxState");
objHands.autoboxStateOH = oh;
}
if(diffState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.diffStateOH);
createPvdObject(ow, ch, ah.diffState.CH, oh, "DiffState");
objHands.diffStateOH = oh;
}
if(clutchSlipState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchSlipStateOH);
createPvdObject(ow, ch, ah.clutchSlipState.CH, oh, "ClutchSlipState");
objHands.clutchSlipStateOH = oh;
}
//Engine drivetrain
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDrivetrainOH);
createPvdObject(ow, ch, ah.engineDrivetrain.CH, oh, "EngineDrivetrain");
objHands.engineDrivetrainOH = oh;
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.commandStateAH, objHands.engineDriveCommandStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.transmissionCommandStateAH, objHands.engineDriveTransmissionCommandStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchResponseParamsAH, objHands.clutchResponseParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchParamsAH, objHands.clutchParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.engineParamsAH, objHands.engineParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.gearboxParamsAH, objHands.gearboxParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.autoboxParamsAH, objHands.autoboxParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.differentialParamsAH, objHands.differentialParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchResponseStateAH, objHands.clutchResponseStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.throttleResponseStateAH, objHands.engineDriveThrottleResponseStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.engineStateAH, objHands.engineStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.gearboxStateAH, objHands.gearboxStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.autoboxStateAH, objHands.autoboxStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.diffStateAH, objHands.diffStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchSlipStateAH, objHands.clutchSlipStateOH);
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.engineDriveTrainAH, oh);
}
}
void PxVehiclePvdEngineDrivetrainWrite
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
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& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& omniWriter)
{
const OmniPvdContextHandle ch = oh.contextHandle;
if(oh.engineDriveCommandStateOH && commandState)
{
writeEngineDriveCommandState(*commandState, oh.engineDriveCommandStateOH, ah.engineDriveCommandState, omniWriter, ch);
}
if(oh.engineDriveTransmissionCommandStateOH)
{
if (engineDriveTransmissionCommandState)
{
writeEngineDriveTransmissionCommandState(*engineDriveTransmissionCommandState,
oh.engineDriveTransmissionCommandStateOH, ah.engineDriveTransmissionCommandState, omniWriter, ch);
}
else if (tankDriveTransmissionCommandState)
{
writeTankDriveTransmissionCommandState(*tankDriveTransmissionCommandState, oh.engineDriveTransmissionCommandStateOH,
ah.engineDriveTransmissionCommandState, ah.tankDriveTransmissionCommandState, omniWriter, ch);
}
}
if(oh.clutchResponseParamsOH && clutchResponseParams)
{
writeClutchResponseParams(*clutchResponseParams, oh.clutchResponseParamsOH, ah.clutchCommandResponseParams, omniWriter, ch);
}
if(oh.clutchParamsOH && clutchParms)
{
writeClutchParams(*clutchParms, oh.clutchParamsOH, ah.clutchParams, omniWriter, ch);
}
if(oh.engineParamsOH && engineParams)
{
writeEngineParams(*engineParams, oh.engineParamsOH, ah.engineParams, omniWriter, ch);
}
if(oh.gearboxParamsOH && gearboxParams)
{
writeGearboxParams(*gearboxParams, oh.gearboxParamsOH, ah.gearboxParams, omniWriter, ch);
}
if(oh.autoboxParamsOH && autoboxParams)
{
writeAutoboxParams(*autoboxParams, oh.autoboxParamsOH, ah.autoboxParams, omniWriter, ch);
}
if(oh.differentialParamsOH)
{
if (multiWheelDiffParams)
{
writeMultiWheelDiffParams(*multiWheelDiffParams, oh.differentialParamsOH,
ah.multiwheelDiffParams, omniWriter, ch);
}
else if (fourWheelDiffParams)
{
writeFourWheelDiffParams(*fourWheelDiffParams, oh.differentialParamsOH,
ah.multiwheelDiffParams, ah.fourwheelDiffParams, omniWriter, ch);
}
else if (tankDiffParams)
{
writeTankDiffParams(*tankDiffParams, oh.differentialParamsOH,
ah.multiwheelDiffParams, ah.tankDiffParams, omniWriter, ch);
}
}
if(oh.clutchResponseStateOH && clutchResponseState)
{
writeClutchResponseState(*clutchResponseState, oh.clutchResponseStateOH, ah.clutchResponseState, omniWriter, ch);
}
if(oh.engineDriveThrottleResponseStateOH && throttleResponseState)
{
writeThrottleResponseState(*throttleResponseState, oh.engineDriveThrottleResponseStateOH, ah.throttleResponseState, omniWriter, ch);
}
if(oh.engineStateOH && engineState)
{
writeEngineState(*engineState, oh.engineStateOH, ah.engineState, omniWriter, ch);
}
if(oh.gearboxStateOH && gearboxState)
{
writeGearboxState(*gearboxState, oh.gearboxStateOH, ah.gearboxState, omniWriter, ch);
}
if(oh.autoboxStateOH && autoboxState)
{
writeAutoboxState(*autoboxState, oh.autoboxStateOH, ah.autoboxState, omniWriter, ch);
}
if(oh.diffStateOH && diffState)
{
writeDiffState(*diffState, oh.diffStateOH, ah.diffState, omniWriter, ch);
}
if(oh.clutchSlipStateOH && clutchSlipState)
{
writeClutchSlipState(*clutchSlipState, oh.clutchSlipStateOH, ah.clutchSlipState, omniWriter, ch);
}
}
void PxVehiclePvdAntiRollsRegister
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
antiRollForceParams.size <= objHands.nbAntirolls,
"PxVehiclePvdAntiRollsRegister - antiRollForceParams.size must be less than or equal to vallue of nbAntirolls argument in the function PxVehiclePvdObjectCreate");
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
// Register the antiroll params.
for(PxU32 i = 0; i < antiRollForceParams.size; i++)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.antiRollParamOHs[i]);
char objectName[32] = "AntiRollParams";
appendWithInt(objectName, i);
createPvdObject(ow, ch, ah.antiRollParams.CH, oh, objectName);
objHands.antiRollParamOHs[i] = oh;
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.antiRollSetAH, oh);
}
// Register the antiroll force.
if(antiRollTorque)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.antiRollTorqueOH);
const char objectName[32] = "AntiRollTorque";
createPvdObject(ow, ch, ah.antiRollForce.CH, oh, objectName);
objHands.antiRollTorqueOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.antiRollForceAH, oh);
}
}
void PxVehiclePvdAntiRollsWrite
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
antiRollForceParams.size <= oh.nbAntirolls,
"PxVehiclePvdAntiRollsWrite - antiRollForceParams.size must be less than or equal to vallue of nbAntirolls argument in the function PxVehiclePvdObjectCreate");
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < antiRollForceParams.size; i++)
{
if(oh.antiRollParamOHs[i] && !antiRollForceParams.isEmpty())
{
writeAntiRollParams(antiRollForceParams[i], oh.antiRollParamOHs[i], ah.antiRollParams, ow, ch);
}
}
if(oh.antiRollTorqueOH && antiRollTorque)
{
writeAntiRollForce(*antiRollTorque, oh.antiRollTorqueOH, ah.antiRollForce, ow, ch);
}
}
void PxVehiclePvdPhysXWheelAttachmentRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomState,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxRoadGeomState);
PX_UNUSED(physxConstraintStates);
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
// Register the wheel attachments
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < objHands.nbWheels,
"PxVehiclePvdPhysXWheelAttachmentRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(!physxSuspLimitConstraintParams.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxConstraintParamOHs[wheelId]);
char objectName[32] = "PhysXSuspLimtConstraintParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxSuspLimitConstraintParams.CH, oh, objectName);
objHands.physxConstraintParamOHs[wheelId] = oh;
}
if(physxActor && physxActor->wheelShapes[wheelId])
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxWheelShapeOHs[wheelId]);
char objectName[32] = "PhysXWheelShape";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxWheelShape.CH, oh, objectName);
objHands.physxWheelShapeOHs[wheelId] = oh;
}
if(!physxConstraintStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxConstraintStateOHs[wheelId]);
char objectName[32] = "PhysXConstraintState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxConstraintState.CH, oh, objectName);
objHands.physxConstraintStateOHs[wheelId] = oh;
}
if(!physxRoadGeomState.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomStateOHs[wheelId]);
char objectName[32] = "PhysXRoadGeomState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxRoadGeomState.CH, oh, objectName);
objHands.physxRoadGeomStateOHs[wheelId] = oh;
}
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxWheelAttachmentOHs[wheelId]);
char objectName[32] = "PhysxWheelAttachment";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxWheelAttachment.CH, oh, objectName);
objHands.physxWheelAttachmentOHs[wheelId] = oh;
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxConstraintParamsAH, objHands.physxConstraintParamOHs[wheelId]);
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxWeelShapeAH, objHands.physxWheelShapeOHs[wheelId]);
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxRoadGeometryStateAH, objHands.physxRoadGeomStateOHs[wheelId]);
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxConstraintStateAH, objHands.physxConstraintStateOHs[wheelId]);
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.physxWheelAttachmentSetAH, oh);
}
if(!physxMaterialFrictionParams.isEmpty())
{
for(PxU32 j = 0; j < objHands.nbPhysXMaterialFrictions; j++)
{
const PxU32 id = wheelId*objHands.nbPhysXMaterialFrictions + j;
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxMaterialFrictionOHs[id]);
char objectName[32] = "PhysxMaterialFriction";
appendWithInt(objectName, wheelId);
strcat(objectName, "_");
appendWithInt(objectName, j);
createPvdObject(ow, ch, ah.physxMaterialFriction.CH, oh, objectName);
objHands.physxMaterialFrictionOHs[id] = oh;
addObjectHandleToUniqueList(ow, ch, objHands.physxWheelAttachmentOHs[wheelId], ah.physxWheelAttachment.physxMaterialFrictionSetAH, oh);
}
}
}
if(physxRoadGeomQryParams)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomQueryParamOH);
char objectName[32] = "PhysxRoadGeomQryParams";
createPvdObject(ow, ch, ah.physxRoadGeometryQueryParams.CH, oh, objectName);
objHands.physxRoadGeomQueryParamOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.physxRoadGeometryQueryParamsAH, oh);
const OmniPvdObjectHandle defaultFilterDataOH = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomQueryDefaultFilterDataOH);
createPvdObject(ow, ch, ah.physxRoadGeometryQueryParams.filterDataParams.CH, defaultFilterDataOH, "");
objHands.physxRoadGeomQueryDefaultFilterDataOH = defaultFilterDataOH;
writeObjectHandleAttribute(ow, ch, objHands.physxRoadGeomQueryParamOH, ah.physxRoadGeometryQueryParams.defaultFilterDataAH, defaultFilterDataOH);
if (physxRoadGeomQryParams->filterDataEntries)
{
for (PxU32 j = 0; j < axleDesc.nbWheels; j++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[j];
const OmniPvdObjectHandle filterDataOH = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomQueryFilterDataOHs[wheelId]);
char filterDataObjectName[32] = "FilterData";
appendWithInt(filterDataObjectName, wheelId);
createPvdObject(ow, ch, ah.physxRoadGeometryQueryParams.filterDataParams.CH, filterDataOH, filterDataObjectName);
objHands.physxRoadGeomQueryFilterDataOHs[wheelId] = filterDataOH;
addObjectHandleToUniqueList(ow, ch, objHands.physxRoadGeomQueryParamOH, ah.physxRoadGeometryQueryParams.filterDataSetAH, filterDataOH);
}
}
#if PX_DEBUG
else
{
for (PxU32 j = 0; j < axleDesc.nbWheels; j++)
{
// note: objHands.physxRoadGeomQueryFilterDataOHs entries are zero initialized
// which matches the invalid handle for now.
PX_ASSERT(objHands.physxRoadGeomQueryFilterDataOHs[j] == 0);
// TODO: test against invalid hanndle once it gets introduced
}
}
#endif
}
}
void PxVehiclePvdPhysXWheelAttachmentWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomStates,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxRoadGeomStates);
PX_UNUSED(physxConstraintStates);
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < oh.nbWheels,
"PxVehiclePvdPhysXWheelAttachmentRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(oh.physxConstraintParamOHs[wheelId] && !physxSuspLimitConstraintParams.isEmpty())
{
writePhysXSuspLimitConstraintParams(physxSuspLimitConstraintParams[wheelId], oh.physxConstraintParamOHs[wheelId], ah.physxSuspLimitConstraintParams, ow, ch);
}
if(oh.physxWheelShapeOHs[wheelId] && physxActor)
{
writePhysXWheelShape(physxActor->wheelShapes[wheelId], oh.physxWheelShapeOHs[wheelId], ah.physxWheelShape, ow, ch);
}
if(oh.physxRoadGeomStateOHs[wheelId] && !physxRoadGeomStates.isEmpty())
{
writePhysXRoadGeomState(physxRoadGeomStates[wheelId], oh.physxRoadGeomStateOHs[wheelId], ah.physxRoadGeomState, ow, ch);
}
if(oh.physxConstraintStateOHs[wheelId] && !physxConstraintStates.isEmpty())
{
writePhysXConstraintState(physxConstraintStates[wheelId], oh.physxConstraintStateOHs[wheelId], ah.physxConstraintState, ow, ch);
}
if(!physxMaterialFrictionParams.isEmpty())
{
for(PxU32 j = 0; j < physxMaterialFrictionParams[wheelId].nbMaterialFrictions; j++)
{
const PxU32 id = wheelId*oh.nbPhysXMaterialFrictions + j;
if(oh.physxMaterialFrictionOHs[id])
{
const PxVehiclePhysXMaterialFriction& m = physxMaterialFrictionParams[wheelId].materialFrictions[j];
writePhysXMaterialFriction(m, oh.physxMaterialFrictionOHs[id], ah.physxMaterialFriction, ow, ch);
}
}
for(PxU32 j = physxMaterialFrictionParams[wheelId].nbMaterialFrictions; j < oh.nbPhysXMaterialFrictions; j++)
{
const PxU32 id = wheelId*oh.nbPhysXMaterialFrictions + j;
if(oh.physxMaterialFrictionOHs[id])
{
PxVehiclePhysXMaterialFriction m;
m.friction = -1.0f;
m.material = NULL;
writePhysXMaterialFriction(m, oh.physxMaterialFrictionOHs[id], ah.physxMaterialFriction, ow, ch);
}
}
}
}
if(oh.physxRoadGeomQueryParamOH && physxRoadGeomQryParams)
{
writePhysXRoadGeometryQueryParams(*physxRoadGeomQryParams, axleDesc,
oh.physxRoadGeomQueryParamOH, oh.physxRoadGeomQueryDefaultFilterDataOH, oh.physxRoadGeomQueryFilterDataOHs,
ah.physxRoadGeometryQueryParams, ow, ch);
}
}
void PxVehiclePvdPhysXRigidActorRegister
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(physxActor && physxActor->rigidBody)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRigidActorOH);
createPvdObject(ow, ch, ah.physxRigidActor.CH, oh, "PhysXRigidActor");
objHands.physxRigidActorOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.physxRigidActorAH, oh);
}
}
void PxVehiclePvdPhysXRigidActorWrite
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
if(oh.physxRigidActorOH && physxActor)
{
writePhysXRigidActor(physxActor->rigidBody, oh.physxRigidActorOH, ah.physxRigidActor, ow, oh.contextHandle);
}
}
void PxVehiclePvdPhysXSteerStateRegister
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(physxSteerState)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxSteerStateOH);
createPvdObject(ow, ch, ah.physxSteerState.CH, oh, "PhysXSteerState");
objHands.physxSteerStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.physxSteerStateAH, oh);
}
}
void PxVehiclePvdPhysXSteerStateWrite
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
if (objHands.physxSteerStateOH && physxSteerState) // TODO: test against invalid handle once that gets introduced
{
writePhysXSteerState(*physxSteerState, objHands.physxSteerStateOH, ah.physxSteerState, ow, objHands.contextHandle);
}
}
#else //PX_SUPPORT_OMNI_PVD
void PxVehiclePvdRigidBodyRegister
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(rbodyParams);
PX_UNUSED(rbodyState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdRigidBodyWrite
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(rbodyParams);
PX_UNUSED(rbodyState);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdSuspensionStateCalculationParamsRegister
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(suspStateCalcParams);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdSuspensionStateCalculationParamsWrite
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(suspStateCalcParams);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdCommandResponseRegister
(const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(steerResponseParams);
PX_UNUSED(brakeResponseParams);
PX_UNUSED(ackermannParams);
PX_UNUSED(steerResponseStates);
PX_UNUSED(brakeResponseStates);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdCommandResponseWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(steerResponseParams);
PX_UNUSED(brakeResponseParams);
PX_UNUSED(ackermannParams);
PX_UNUSED(steerResponseStates);
PX_UNUSED(brakeResponseStates);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdWheelAttachmentsRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspCompParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(wheelParams);
PX_UNUSED(wheelActuationStates);
PX_UNUSED(wheelRigidBody1dStates);
PX_UNUSED(wheelLocalPoses);
PX_UNUSED(roadGeometryStates);
PX_UNUSED(suspParams);
PX_UNUSED(suspCompParams);
PX_UNUSED(suspForceParams);
PX_UNUSED(suspStates);
PX_UNUSED(suspCompStates);
PX_UNUSED(suspForces);
PX_UNUSED(tireForceParams);
PX_UNUSED(tireDirectionStates);
PX_UNUSED(tireSpeedStates);
PX_UNUSED(tireSlipStates);
PX_UNUSED(tireStickyStates);
PX_UNUSED(tireGripStates);
PX_UNUSED(tireCamberStates);
PX_UNUSED(tireForces);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdWheelAttachmentsWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspComplianceParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(wheelParams);
PX_UNUSED(wheelActuationStates);
PX_UNUSED(wheelRigidBody1dStates);
PX_UNUSED(wheelLocalPoses);
PX_UNUSED(roadGeometryStates);
PX_UNUSED(suspParams);
PX_UNUSED(suspComplianceParams);
PX_UNUSED(suspForceParams);
PX_UNUSED(suspStates);
PX_UNUSED(suspCompStates);
PX_UNUSED(suspForces);
PX_UNUSED(tireForceParams);
PX_UNUSED(tireDirectionStates);
PX_UNUSED(tireSpeedStates);
PX_UNUSED(tireSlipStates);
PX_UNUSED(tireStickyStates);
PX_UNUSED(tireGripStates);
PX_UNUSED(tireCamberStates);
PX_UNUSED(tireForces);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdDirectDrivetrainRegister
(const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(commandState);
PX_UNUSED(transmissionState);
PX_UNUSED(directDriveThrottleResponseParams);
PX_UNUSED(directDriveThrottleResponseState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdDirectDrivetrainWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(commandState);
PX_UNUSED(transmissionState);
PX_UNUSED(directDriveThrottleResponseParams);
PX_UNUSED(directDriveThrottleResponseState);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdEngineDrivetrainRegister
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
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& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(commandState);
PX_UNUSED(engineDriveTransmissionCommandState);
PX_UNUSED(tankDriveTransmissionCommandState);
PX_UNUSED(clutchResponseParams);
PX_UNUSED(clutchParms);
PX_UNUSED(engineParams);
PX_UNUSED(gearboxParams);
PX_UNUSED(autoboxParams);
PX_UNUSED(multiWheelDiffParams);
PX_UNUSED(fourWheelDiffPrams);
PX_UNUSED(tankDiffParams);
PX_UNUSED(clutchResponseState);
PX_UNUSED(throttleResponseState);
PX_UNUSED(engineState);
PX_UNUSED(gearboxState);
PX_UNUSED(autoboxState);
PX_UNUSED(diffState);
PX_UNUSED(clutchSlipState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdEngineDrivetrainWrite
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
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& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& omniWriter)
{
PX_UNUSED(commandState);
PX_UNUSED(engineDriveTransmissionCommandState);
PX_UNUSED(tankDriveTransmissionCommandState);
PX_UNUSED(clutchResponseParams);
PX_UNUSED(clutchParms);
PX_UNUSED(engineParams);
PX_UNUSED(gearboxParams);
PX_UNUSED(autoboxParams);
PX_UNUSED(multiWheelDiffParams);
PX_UNUSED(fourWheelDiffParams);
PX_UNUSED(tankDiffParams);
PX_UNUSED(clutchResponseState);
PX_UNUSED(throttleResponseState);
PX_UNUSED(engineState);
PX_UNUSED(gearboxState);
PX_UNUSED(autoboxState);
PX_UNUSED(diffState);
PX_UNUSED(clutchSlipState);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(omniWriter);
}
void PxVehiclePvdAntiRollsRegister
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(antiRollForceParams);
PX_UNUSED(antiRollTorque);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdAntiRollsWrite
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(antiRollForceParams);
PX_UNUSED(antiRollTorque);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXWheelAttachmentRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomState,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(physxSuspLimitConstraintParams);
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxActor);
PX_UNUSED(physxRoadGeomQryParams);
PX_UNUSED(physxRoadGeomState);
PX_UNUSED(physxConstraintStates);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXWheelAttachmentWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomStates,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(physxSuspLimitConstraintParams);
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxActor);
PX_UNUSED(physxRoadGeomQryParams);
PX_UNUSED(physxRoadGeomStates);
PX_UNUSED(physxConstraintStates);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXRigidActorRegister
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxActor);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXRigidActorWrite
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(physxActor);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXSteerStateRegister
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxSteerState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXSteerStateWrite
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxSteerState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
#endif
} // namespace vehicle2
} // namespace physx
/** @} */
| 77,426 |
C++
| 39.923362 | 181 | 0.803761 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdObjectHandles.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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"
#if PX_SUPPORT_OMNI_PVD
#include "OmniPvdWriter.h"
#endif
#include "foundation/PxMemory.h"
/** \addtogroup vehicle2
@{
*/
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehiclePvdObjectHandles
{
#if PX_SUPPORT_OMNI_PVD
OmniPvdObjectHandle vehicleOH;
OmniPvdObjectHandle rigidBodyParamsOH;
OmniPvdObjectHandle rigidBodyStateOH;
OmniPvdObjectHandle suspStateCalcParamsOH;
OmniPvdObjectHandle brakeResponseParamOHs[2];
OmniPvdObjectHandle steerResponseParamsOH;
OmniPvdObjectHandle brakeResponseStateOH;
OmniPvdObjectHandle steerResponseStateOH;
OmniPvdObjectHandle ackermannParamsOH;
OmniPvdObjectHandle directDriveCommandStateOH;
OmniPvdObjectHandle directDriveTransmissionCommandStateOH;
OmniPvdObjectHandle directDriveThrottleResponseParamsOH;
OmniPvdObjectHandle directDriveThrottleResponseStateOH;
OmniPvdObjectHandle directDrivetrainOH;
OmniPvdObjectHandle engineDriveCommandStateOH;
OmniPvdObjectHandle engineDriveTransmissionCommandStateOH;
OmniPvdObjectHandle clutchResponseParamsOH;
OmniPvdObjectHandle clutchParamsOH;
OmniPvdObjectHandle engineParamsOH;
OmniPvdObjectHandle gearboxParamsOH;
OmniPvdObjectHandle autoboxParamsOH;
OmniPvdObjectHandle differentialParamsOH;
OmniPvdObjectHandle clutchResponseStateOH;
OmniPvdObjectHandle engineDriveThrottleResponseStateOH;
OmniPvdObjectHandle engineStateOH;
OmniPvdObjectHandle gearboxStateOH;
OmniPvdObjectHandle autoboxStateOH;
OmniPvdObjectHandle diffStateOH;
OmniPvdObjectHandle clutchSlipStateOH;
OmniPvdObjectHandle engineDrivetrainOH;
OmniPvdObjectHandle* wheelAttachmentOHs;
OmniPvdObjectHandle* wheelParamsOHs;
OmniPvdObjectHandle* wheelActuationStateOHs;
OmniPvdObjectHandle* wheelRigidBody1dStateOHs;
OmniPvdObjectHandle* wheelLocalPoseStateOHs;
OmniPvdObjectHandle* roadGeomStateOHs;
OmniPvdObjectHandle* suspParamsOHs;
OmniPvdObjectHandle* suspCompParamsOHs;
OmniPvdObjectHandle* suspForceParamsOHs;
OmniPvdObjectHandle* suspStateOHs;
OmniPvdObjectHandle* suspCompStateOHs;
OmniPvdObjectHandle* suspForceOHs;
OmniPvdObjectHandle* tireParamsOHs;
OmniPvdObjectHandle* tireDirectionStateOHs;
OmniPvdObjectHandle* tireSpeedStateOHs;
OmniPvdObjectHandle* tireSlipStateOHs;
OmniPvdObjectHandle* tireStickyStateOHs;
OmniPvdObjectHandle* tireGripStateOHs;
OmniPvdObjectHandle* tireCamberStateOHs;
OmniPvdObjectHandle* tireForceOHs;
OmniPvdObjectHandle* physxWheelAttachmentOHs;
OmniPvdObjectHandle* physxWheelShapeOHs;
OmniPvdObjectHandle* physxConstraintParamOHs;
OmniPvdObjectHandle* physxConstraintStateOHs;
OmniPvdObjectHandle* physxRoadGeomStateOHs;
OmniPvdObjectHandle physxSteerStateOH;
OmniPvdObjectHandle* physxMaterialFrictionSetOHs;
OmniPvdObjectHandle* physxMaterialFrictionOHs;
OmniPvdObjectHandle physxRoadGeomQueryParamOH;
OmniPvdObjectHandle physxRoadGeomQueryDefaultFilterDataOH;
OmniPvdObjectHandle* physxRoadGeomQueryFilterDataOHs;
OmniPvdObjectHandle physxRigidActorOH;
OmniPvdObjectHandle* antiRollParamOHs;
OmniPvdObjectHandle antiRollTorqueOH;
PxU32 nbWheels;
PxU32 nbPhysXMaterialFrictions;
PxU32 nbAntirolls;
OmniPvdContextHandle contextHandle;
#endif //PX_SUPPORT_OMNI_PVD
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,002 |
C
| 34.482269 | 74 | 0.833667 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdWriter.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "VhPvdWriter.h"
namespace physx
{
namespace vehicle2
{
#if PX_SUPPORT_OMNI_PVD
PX_FORCE_INLINE void writeFloatAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, float val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<uint8_t*>(&val), sizeof(float));
}
PX_FORCE_INLINE void writeFloatArrayAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const float* val, const PxU32 nbVals)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(val), sizeof(float) * nbVals);
}
PX_FORCE_INLINE void writeUInt32ArrayAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const uint32_t* val, const PxU32 nbVals)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(val), sizeof(uint32_t) * nbVals);
}
PX_FORCE_INLINE void writeVec3Attribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const PxVec3& val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(PxVec3));
}
PX_FORCE_INLINE void writePlaneAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const PxPlane& val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(PxPlane));
}
PX_FORCE_INLINE void writeQuatAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const PxQuat& val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(PxQuat));
}
PX_FORCE_INLINE void writeUInt8Attribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, uint8_t val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(uint8_t));
}
PX_FORCE_INLINE void writeUInt32Attribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, uint32_t val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(uint32_t));
}
PX_FORCE_INLINE void writeFlagAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, uint32_t val)
{
writeUInt32Attribute(omniWriter, ch, oh, ah, val);
}
PX_FORCE_INLINE void writeLookupTableAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, PxVehicleFixedSizeLookupTable<float, 3> val)
{
float buffer[6] = { -1.0f, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f };
for(PxU32 i = 0; i < val.nbDataPairs; i++)
{
buffer[2 * i + 0] = val.xVals[i];
buffer[2 * i + 1] = val.yVals[i];
}
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(buffer), sizeof(buffer));
}
PX_FORCE_INLINE void writeLookupTableAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, PxVehicleFixedSizeLookupTable<PxVec3, 3> val)
{
float buffer[12] = { -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f };
for(PxU32 i = 0; i < val.nbDataPairs; i++)
{
buffer[4 * i + 0] = val.xVals[i];
buffer[4 * i + 1] = val.yVals[i].x;
buffer[4 * i + 2] = val.yVals[i].y;
buffer[4 * i + 3] = val.yVals[i].z;
}
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(buffer), sizeof(buffer));
}
void writePtrAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const void* val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(val));
}
////////////////////////////////
//RIGID BODY
////////////////////////////////
RigidBodyParams registerRigidBodyParams(OmniPvdWriter& omniWriter)
{
RigidBodyParams r;
r.CH = omniWriter.registerClass("RigidBodyParams");
r.massAH = omniWriter.registerAttribute(r.CH, "mass", OmniPvdDataType::eFLOAT32, 1);
r.moiAH = omniWriter.registerAttribute(r.CH, "moi", OmniPvdDataType::eFLOAT32, 3);
return r;
}
void writeRigidBodyParams
(const PxVehicleRigidBodyParams& rbodyParams,
const OmniPvdObjectHandle oh, const RigidBodyParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.massAH, rbodyParams.mass);
writeVec3Attribute(omniWriter, ch, oh, ah.moiAH, rbodyParams.moi);
}
RigidBodyState registerRigidBodyState(OmniPvdWriter& omniWriter)
{
RigidBodyState r;
r.CH = omniWriter.registerClass("RigidBodyState");
r.posAH = omniWriter.registerAttribute(r.CH, "pos", OmniPvdDataType::eFLOAT32, 3);
r.quatAH = omniWriter.registerAttribute(r.CH, "quat", OmniPvdDataType::eFLOAT32, 4);
r.linearVelocityAH = omniWriter.registerAttribute(r.CH, "linvel", OmniPvdDataType::eFLOAT32, 3);
r.angularVelocityAH = omniWriter.registerAttribute(r.CH, "angvel", OmniPvdDataType::eFLOAT32, 3);
r.previousLinearVelocityAH = omniWriter.registerAttribute(r.CH, "prevLinvel", OmniPvdDataType::eFLOAT32, 3);
r.previousAngularVelocityAH = omniWriter.registerAttribute(r.CH, "prevAngvel", OmniPvdDataType::eFLOAT32, 3);
r.externalForceAH = omniWriter.registerAttribute(r.CH, "extForce", OmniPvdDataType::eFLOAT32, 3);
r.externalTorqueAH = omniWriter.registerAttribute(r.CH, "extTorque", OmniPvdDataType::eFLOAT32, 3);
return r;
}
void writeRigidBodyState
(const PxVehicleRigidBodyState& rbodyState,
const OmniPvdObjectHandle oh, const RigidBodyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.posAH, rbodyState.pose.p);
writeQuatAttribute(omniWriter, ch, oh, ah.quatAH, rbodyState.pose.q);
writeVec3Attribute(omniWriter, ch, oh, ah.linearVelocityAH, rbodyState.linearVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.angularVelocityAH, rbodyState.angularVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.previousLinearVelocityAH, rbodyState.previousLinearVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.previousAngularVelocityAH, rbodyState.previousAngularVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.externalForceAH, rbodyState.externalForce);
writeVec3Attribute(omniWriter, ch, oh, ah.externalTorqueAH, rbodyState.externalTorque);
}
/////////////////////////////////
//CONTROLS
/////////////////////////////////
WheelResponseParams registerWheelResponseParams(const char* name, OmniPvdWriter& omniWriter)
{
WheelResponseParams w;
w.CH = omniWriter.registerClass(name);
w.maxResponseAH = omniWriter.registerAttribute(w.CH, "maxResponse", OmniPvdDataType::eFLOAT32, 1);
w.responseMultipliers0To3AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers0To3", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers4To7AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers4To7", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers8To11AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers8To11", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers12To15AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers12To15", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers16To19AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers16To19", OmniPvdDataType::eFLOAT32, 4);
return w;
}
WheelResponseParams registerSteerResponseParams(OmniPvdWriter& omniWriter)
{
return registerWheelResponseParams("SteerResponseParams", omniWriter);
}
WheelResponseParams registerBrakeResponseParams(OmniPvdWriter& omniWriter)
{
return registerWheelResponseParams("BrakeResponseParams", omniWriter);
}
WheelResponseStates registerWheelResponseStates(const char* name, OmniPvdWriter& omniWriter)
{
WheelResponseStates w;
w.CH = omniWriter.registerClass(name);
w.responseStates0To3AH = omniWriter.registerAttribute(w.CH, "wheelStates0To3", OmniPvdDataType::eFLOAT32, 4);
w.responseStates4To7AH = omniWriter.registerAttribute(w.CH, "wheelStatess4To7", OmniPvdDataType::eFLOAT32, 4);
w.responseStates8To11AH = omniWriter.registerAttribute(w.CH, "wheelStates8To11", OmniPvdDataType::eFLOAT32, 4);
w.responseStates12To15AH = omniWriter.registerAttribute(w.CH, "wheelStates12To15", OmniPvdDataType::eFLOAT32, 4);
w.responseStates16To19AH = omniWriter.registerAttribute(w.CH, "wheelStates16To19", OmniPvdDataType::eFLOAT32, 4);
return w;
}
WheelResponseStates registerSteerResponseStates(OmniPvdWriter& omniWriter)
{
return registerWheelResponseStates("SteerResponseState", omniWriter);
}
WheelResponseStates registerBrakeResponseStates(OmniPvdWriter& omniWriter)
{
return registerWheelResponseStates("BrakeResponseState", omniWriter);
}
AckermannParams registerAckermannParams(OmniPvdWriter& omniWriter)
{
AckermannParams a;
a.CH = omniWriter.registerClass("AckermannParams");
a.wheelIdsAH = omniWriter.registerAttribute(a.CH, "wheelIds", OmniPvdDataType::eUINT32, 2);
a.wheelBaseAH = omniWriter.registerAttribute(a.CH, "wheelBase", OmniPvdDataType::eFLOAT32, 1);
a.trackWidthAH = omniWriter.registerAttribute(a.CH, "trackWidth", OmniPvdDataType::eFLOAT32, 1);
a.strengthAH = omniWriter.registerAttribute(a.CH, "strength", OmniPvdDataType::eFLOAT32, 1);
return a;
}
void writeWheelResponseParams
(const PxVehicleAxleDescription& axleDesc, const PxVehicleCommandResponseParams& responseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.maxResponseAH, responseParams.maxResponse);
float responseMultipliers[PxVehicleLimits::eMAX_NB_WHEELS];
for(PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++)
{
responseMultipliers[i] = PX_MAX_F32;
}
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
responseMultipliers[wheelId] = responseParams.wheelResponseMultipliers[wheelId];
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers0To3AH, responseMultipliers + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers4To7AH, responseMultipliers + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers8To11AH, responseMultipliers + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers12To15AH, responseMultipliers + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers16To19AH, responseMultipliers + 16, 4);
}
void writeSteerResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSteerCommandResponseParams& steerResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseParams(axleDesc, steerResponseParams, oh, ah, omniWriter, ch);
}
void writeBrakeResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleBrakeCommandResponseParams& brakeResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseParams(axleDesc, brakeResponseParams, oh, ah, omniWriter, ch);
}
void writeWheelResponseStates
(const PxVehicleAxleDescription& axleDesc, const PxVehicleArrayData<PxReal>& responseState,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float responseStates[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemZero(responseStates, sizeof(responseStates));
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
responseStates[wheelId] = responseState[wheelId];
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates0To3AH, responseStates + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates4To7AH, responseStates + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates8To11AH, responseStates + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates12To15AH, responseStates + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates16To19AH, responseStates + 16, 4);
}
void writeSteerResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseStates(axleDesc, steerResponseStates, oh, ah, omniWriter, ch);
}
void writeBrakeResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseStates(axleDesc, brakeResponseStates, oh, ah, omniWriter, ch);
}
void writeAckermannParams
(const PxVehicleAckermannParams& ackermannParams,
const OmniPvdObjectHandle oh, const AckermannParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.wheelIdsAH, ackermannParams.wheelIds,
sizeof(PxVehicleAckermannParams::wheelIds) / sizeof(PxVehicleAckermannParams::wheelIds[0]));
writeFloatAttribute(omniWriter, ch, oh, ah.wheelBaseAH, ackermannParams.wheelBase);
writeFloatAttribute(omniWriter, ch, oh, ah.trackWidthAH, ackermannParams.trackWidth);
writeFloatAttribute(omniWriter, ch, oh, ah.strengthAH, ackermannParams.strength);
}
void writeClutchResponseParams
(const PxVehicleClutchCommandResponseParams& clutchResponseParams,
const OmniPvdObjectHandle oh, const ClutchResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.maxResponseAH, clutchResponseParams.maxResponse);
}
//////////////////////////////
//WHEEL ATTACHMENTS
//////////////////////////////
WheelParams registerWheelParams(OmniPvdWriter& omniWriter)
{
WheelParams w;
w.CH = omniWriter.registerClass("WheelParams");
w.wheelRadiusAH = omniWriter.registerAttribute(w.CH, "radius", OmniPvdDataType::eFLOAT32, 1);
w.halfWidthAH = omniWriter.registerAttribute(w.CH, "halfWidth", OmniPvdDataType::eFLOAT32, 1);
w.massAH = omniWriter.registerAttribute(w.CH, "mass", OmniPvdDataType::eFLOAT32, 1);
w.moiAH = omniWriter.registerAttribute(w.CH, "moi", OmniPvdDataType::eFLOAT32, 1);
w.dampingRateAH = omniWriter.registerAttribute(w.CH, "dampingRate", OmniPvdDataType::eFLOAT32, 1);
return w;
}
void writeWheelParams
(const PxVehicleWheelParams& params,
const OmniPvdObjectHandle oh, const WheelParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateAH, params.dampingRate);
writeFloatAttribute(omniWriter, ch, oh, ah.halfWidthAH, params.halfWidth);
writeFloatAttribute(omniWriter, ch, oh, ah.massAH, params.mass);
writeFloatAttribute(omniWriter, ch, oh, ah.moiAH, params.moi);
writeFloatAttribute(omniWriter, ch, oh, ah.wheelRadiusAH, params.radius);
}
WheelActuationState registerWheelActuationState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("WheelStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
WheelActuationState w;
w.CH = omniWriter.registerClass("WheelActuationState");
w.isBrakeAppliedAH = omniWriter.registerFlagsAttribute(w.CH, "isBrakeApplied", boolAsEnum.CH);
w.isDriveAppliedAH = omniWriter.registerFlagsAttribute(w.CH, "isDriveApplied", boolAsEnum.CH);
return w;
}
void writeWheelActuationState
(const PxVehicleWheelActuationState& actState,
const OmniPvdObjectHandle oh, const WheelActuationState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.isBrakeAppliedAH, actState.isBrakeApplied ? 1 : 0);
writeFlagAttribute(omniWriter, ch, oh, ah.isDriveAppliedAH, actState.isDriveApplied ? 1 : 0);
}
WheelRigidBody1dState registerWheelRigidBody1dState(OmniPvdWriter& omniWriter)
{
WheelRigidBody1dState w;
w.CH = omniWriter.registerClass("WheelRigidBodyState");
w.rotationSpeedAH = omniWriter.registerAttribute(w.CH, "rotationSpeed", OmniPvdDataType::eFLOAT32, 1);
w.correctedRotationSpeedAH = omniWriter.registerAttribute(w.CH, "correctedRotationSpeed", OmniPvdDataType::eFLOAT32, 1);
w.rotationAngleAH = omniWriter.registerAttribute(w.CH, "rotationAngle", OmniPvdDataType::eFLOAT32, 1);
return w;
}
void writeWheelRigidBody1dState
(const PxVehicleWheelRigidBody1dState& rigidBodyState,
const OmniPvdObjectHandle oh, const WheelRigidBody1dState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.rotationSpeedAH, rigidBodyState.rotationSpeed);
writeFloatAttribute(omniWriter, ch, oh, ah.correctedRotationSpeedAH, rigidBodyState.correctedRotationSpeed);
writeFloatAttribute(omniWriter, ch, oh, ah.rotationAngleAH, rigidBodyState.rotationAngle);
}
WheelLocalPoseState registerWheelLocalPoseState(OmniPvdWriter& omniWriter)
{
WheelLocalPoseState w;
w.CH = omniWriter.registerClass("WheelLocalPoseState");
w.posAH = omniWriter.registerAttribute(w.CH, "posInRbodyFrame", OmniPvdDataType::eFLOAT32, 3);
w.quatAH = omniWriter.registerAttribute(w.CH, "quatInRbodyFrame", OmniPvdDataType::eFLOAT32, 4);
return w;
}
void writeWheelLocalPoseState
(const PxVehicleWheelLocalPose& pose,
const OmniPvdObjectHandle oh, const WheelLocalPoseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.posAH, pose.localPose.p);
writeQuatAttribute(omniWriter, ch, oh, ah.quatAH, pose.localPose.q);
}
RoadGeometryState registerRoadGeomState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("RoadGeomStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
RoadGeometryState r;
r.CH = omniWriter.registerClass("RoadGeometryState");
r.planeAH = omniWriter.registerAttribute(r.CH, "plane", OmniPvdDataType::eFLOAT32, 4);
r.frictionAH = omniWriter.registerAttribute(r.CH, "friction", OmniPvdDataType::eFLOAT32, 1);
r.hitStateAH = omniWriter.registerFlagsAttribute(r.CH, "hitState", boolAsEnum.CH);
r.velocityAH = omniWriter.registerAttribute(r.CH, "hitVelocity", OmniPvdDataType::eFLOAT32, 3);
return r;
}
void writeRoadGeomState
(const PxVehicleRoadGeometryState& roadGeometryState,
const OmniPvdObjectHandle oh, const RoadGeometryState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writePlaneAttribute(omniWriter, ch, oh, ah.planeAH, roadGeometryState.plane);
writeFloatAttribute(omniWriter, ch, oh, ah.frictionAH, roadGeometryState.friction);
writeFlagAttribute(omniWriter, ch, oh, ah.hitStateAH, roadGeometryState.hitState);
writeVec3Attribute(omniWriter, ch, oh, ah.velocityAH, roadGeometryState.velocity);
}
SuspParams registerSuspParams(OmniPvdWriter& omniWriter)
{
SuspParams s;
s.CH = omniWriter.registerClass("SuspensionParams");
s.suspAttachmentPosAH = omniWriter.registerAttribute(s.CH, "suspAttachmentPos", OmniPvdDataType::eFLOAT32, 3);
s.suspAttachmentQuatAH = omniWriter.registerAttribute(s.CH, "suspAttachmentQuat", OmniPvdDataType::eFLOAT32, 4);
s.suspDirAH = omniWriter.registerAttribute(s.CH, "suspDir", OmniPvdDataType::eFLOAT32, 3);
s.suspTravleDistAH = omniWriter.registerAttribute(s.CH, "suspTravelDist", OmniPvdDataType::eFLOAT32, 1);
s.wheelAttachmentPosAH = omniWriter.registerAttribute(s.CH, "wheelAttachmentPos", OmniPvdDataType::eFLOAT32, 3);
s.wheelAttachmentQuatAH = omniWriter.registerAttribute(s.CH, "wheelAttachmentQuat", OmniPvdDataType::eFLOAT32, 3);
return s;
}
void writeSuspParams
(const PxVehicleSuspensionParams& suspParams,
const OmniPvdObjectHandle oh, const SuspParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.suspAttachmentPosAH, suspParams.suspensionAttachment.p);
writeQuatAttribute(omniWriter, ch, oh, ah.suspAttachmentQuatAH, suspParams.suspensionAttachment.q);
writeVec3Attribute(omniWriter, ch, oh, ah.suspDirAH, suspParams.suspensionTravelDir);
writeFloatAttribute(omniWriter, ch, oh, ah.suspTravleDistAH, suspParams.suspensionTravelDist);
writeVec3Attribute(omniWriter, ch, oh, ah.wheelAttachmentPosAH, suspParams.wheelAttachment.p);
writeQuatAttribute(omniWriter, ch, oh, ah.wheelAttachmentQuatAH, suspParams.wheelAttachment.q);
}
SuspCompParams registerSuspComplianceParams(OmniPvdWriter& omniWriter)
{
SuspCompParams s;
s.CH = omniWriter.registerClass("SuspensionComplianceParams");
s.toeAngleAH = omniWriter.registerAttribute(s.CH, "toeAngle", OmniPvdDataType::eFLOAT32, 6);
s.camberAngleAH = omniWriter.registerAttribute(s.CH, "camberAngle", OmniPvdDataType::eFLOAT32, 6);
s.suspForceAppPointAH = omniWriter.registerAttribute(s.CH, "suspForceAppPoint", OmniPvdDataType::eFLOAT32, 12);
s.tireForceAppPointAH = omniWriter.registerAttribute(s.CH, "tireForceAppPoint", OmniPvdDataType::eFLOAT32, 12);
return s;
}
void writeSuspComplianceParams
(const PxVehicleSuspensionComplianceParams& compParams,
const OmniPvdObjectHandle oh, const SuspCompParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeLookupTableAttribute(omniWriter, ch, oh, ah.camberAngleAH, compParams.wheelCamberAngle);
writeLookupTableAttribute(omniWriter, ch, oh, ah.toeAngleAH, compParams.wheelToeAngle);
writeLookupTableAttribute(omniWriter, ch, oh, ah.suspForceAppPointAH, compParams.suspForceAppPoint);
writeLookupTableAttribute(omniWriter, ch, oh, ah.tireForceAppPointAH, compParams.tireForceAppPoint);
}
SuspForceParams registerSuspForceParams(OmniPvdWriter& omniWriter)
{
SuspForceParams s;
s.CH = omniWriter.registerClass("SuspensionForceParams");
s.stiffnessAH = omniWriter.registerAttribute(s.CH, "stiffness", OmniPvdDataType::eFLOAT32, 1);
s.dampingAH = omniWriter.registerAttribute(s.CH, "damping", OmniPvdDataType::eFLOAT32, 1);
s.sprungMassAH = omniWriter.registerAttribute(s.CH, "sprungMass", OmniPvdDataType::eFLOAT32, 1);
return s;
}
void writeSuspForceParams
(const PxVehicleSuspensionForceParams& forceParams,
const OmniPvdObjectHandle oh, const SuspForceParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.dampingAH, forceParams.damping);
writeFloatAttribute(omniWriter, ch, oh, ah.sprungMassAH, forceParams.sprungMass);
writeFloatAttribute(omniWriter, ch, oh, ah.stiffnessAH, forceParams.stiffness);
}
SuspState registerSuspState(OmniPvdWriter& omniWriter)
{
SuspState s;
s.CH = omniWriter.registerClass("SuspensionState");
s.jounceAH = omniWriter.registerAttribute(s.CH, "jounce", OmniPvdDataType::eFLOAT32, 1);
s.jounceSpeedAH = omniWriter.registerAttribute(s.CH, "jounceSpeed", OmniPvdDataType::eFLOAT32, 1);
s.separationAH = omniWriter.registerAttribute(s.CH, "separation", OmniPvdDataType::eFLOAT32, 1);
return s;
}
void writeSuspState
(const PxVehicleSuspensionState& suspState,
const OmniPvdObjectHandle oh, const SuspState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.jounceAH, suspState.jounce);
writeFloatAttribute(omniWriter, ch, oh, ah.jounceSpeedAH, suspState.jounceSpeed);
writeFloatAttribute(omniWriter, ch, oh, ah.separationAH, suspState.separation);
}
SuspCompState registerSuspComplianceState(OmniPvdWriter& omniWriter)
{
SuspCompState s;
s.CH = omniWriter.registerClass("SuspensionComplianceState");
s.toeAH = omniWriter.registerAttribute(s.CH, "toe", OmniPvdDataType::eFLOAT32, 1);
s.camberAH = omniWriter.registerAttribute(s.CH, "camber", OmniPvdDataType::eFLOAT32, 1);
s.tireForceAppPointAH = omniWriter.registerAttribute(s.CH, "tireForceAppPoint", OmniPvdDataType::eFLOAT32, 3);
s.suspForceAppPointAH = omniWriter.registerAttribute(s.CH, "suspForceAppPoint", OmniPvdDataType::eFLOAT32, 3);
return s;
}
void writeSuspComplianceState
(const PxVehicleSuspensionComplianceState& suspCompState,
const OmniPvdObjectHandle oh, const SuspCompState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.camberAH, suspCompState.camber);
writeFloatAttribute(omniWriter, ch, oh, ah.toeAH, suspCompState.toe);
writeVec3Attribute(omniWriter, ch, oh, ah.suspForceAppPointAH, suspCompState.suspForceAppPoint);
writeVec3Attribute(omniWriter, ch, oh, ah.tireForceAppPointAH, suspCompState.tireForceAppPoint);
}
SuspForce registerSuspForce(OmniPvdWriter& omniWriter)
{
SuspForce s;
s.CH = omniWriter.registerClass("SuspensionForce");
s.forceAH = omniWriter.registerAttribute(s.CH, "force", OmniPvdDataType::eFLOAT32, 3);
s.torqueAH = omniWriter.registerAttribute(s.CH, "torque", OmniPvdDataType::eFLOAT32, 3);
s.normalForceAH = omniWriter.registerAttribute(s.CH, "normalForce", OmniPvdDataType::eFLOAT32, 3);
return s;
}
void writeSuspForce
(const PxVehicleSuspensionForce& suspForce,
const OmniPvdObjectHandle oh, const SuspForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.forceAH, suspForce.force);
writeVec3Attribute(omniWriter, ch, oh, ah.torqueAH, suspForce.torque);
writeFloatAttribute(omniWriter, ch, oh, ah.normalForceAH, suspForce.normalForce);
}
TireParams registerTireParams(OmniPvdWriter& omniWriter)
{
TireParams t;
t.CH = omniWriter.registerClass("TireParams");
t.latStiffXAH = omniWriter.registerAttribute(t.CH, "latStiffX", OmniPvdDataType::eFLOAT32, 1);
t.latStiffYAH = omniWriter.registerAttribute(t.CH, "latStiffY", OmniPvdDataType::eFLOAT32, 1);
t.longStiffAH = omniWriter.registerAttribute(t.CH, "longStiff", OmniPvdDataType::eFLOAT32, 1);
t.camberStiffAH = omniWriter.registerAttribute(t.CH, "camberStiff", OmniPvdDataType::eFLOAT32, 1);
t.frictionVsSlipAH = omniWriter.registerAttribute(t.CH, "frictionVsSlip", OmniPvdDataType::eFLOAT32, 6);
t.restLoadAH = omniWriter.registerAttribute(t.CH, "restLoad", OmniPvdDataType::eFLOAT32, 1);
t.loadFilterAH = omniWriter.registerAttribute(t.CH, "loadFilter", OmniPvdDataType::eFLOAT32, 4);
return t;
}
void writeTireParams
(const PxVehicleTireForceParams& tireParams,
const OmniPvdObjectHandle oh, const TireParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.latStiffXAH, tireParams.latStiffX);
writeFloatAttribute(omniWriter, ch, oh, ah.latStiffYAH, tireParams.latStiffY);
writeFloatAttribute(omniWriter, ch, oh, ah.longStiffAH, tireParams.longStiff);
writeFloatAttribute(omniWriter, ch, oh, ah.camberStiffAH, tireParams.camberStiff);
writeFloatAttribute(omniWriter, ch, oh, ah.restLoadAH, tireParams.restLoad);
const float fricVsSlip[6] =
{
tireParams.frictionVsSlip[0][0], tireParams.frictionVsSlip[0][1], tireParams.frictionVsSlip[1][0],
tireParams.frictionVsSlip[1][1], tireParams.frictionVsSlip[2][0], tireParams.frictionVsSlip[2][1],
};
writeFloatArrayAttribute(omniWriter, ch, oh, ah.frictionVsSlipAH, fricVsSlip, 6);
const float loadFilter[4] =
{
tireParams.loadFilter[0][0], tireParams.loadFilter[0][1],
tireParams.loadFilter[1][0], tireParams.loadFilter[1][1]
};
writeFloatArrayAttribute(omniWriter, ch, oh, ah.loadFilterAH, loadFilter, 4);
}
TireDirectionState registerTireDirectionState(OmniPvdWriter& omniWriter)
{
TireDirectionState t;
t.CH = omniWriter.registerClass("TireDirectionState");
t.lngDirectionAH = omniWriter.registerAttribute(t.CH, "lngDir", OmniPvdDataType::eFLOAT32, 3);
t.latDirectionAH = omniWriter.registerAttribute(t.CH, "latDir", OmniPvdDataType::eFLOAT32, 3);
return t;
}
void writeTireDirectionState
(const PxVehicleTireDirectionState& tireDirState,
const OmniPvdObjectHandle oh, const TireDirectionState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.lngDirectionAH, tireDirState.directions[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.latDirectionAH, tireDirState.directions[PxVehicleTireDirectionModes::eLATERAL]);
}
TireSpeedState registerTireSpeedState(OmniPvdWriter& omniWriter)
{
TireSpeedState t;
t.CH = omniWriter.registerClass("TireSpeedState");
t.lngSpeedAH = omniWriter.registerAttribute(t.CH, "lngSpeed", OmniPvdDataType::eFLOAT32, 1);
t.latSpeedAH = omniWriter.registerAttribute(t.CH, "latSpeed", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireSpeedState
(const PxVehicleTireSpeedState& tireSpeedState,
const OmniPvdObjectHandle oh, const TireSpeedState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.lngSpeedAH, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.latSpeedAH, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL]);
}
TireSlipState registerTireSlipState(OmniPvdWriter& omniWriter)
{
TireSlipState t;
t.CH = omniWriter.registerClass("TireSlipState");
t.lngSlipAH = omniWriter.registerAttribute(t.CH, "lngSlip", OmniPvdDataType::eFLOAT32, 1);
t.latSlipAH = omniWriter.registerAttribute(t.CH, "latSlip", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireSlipState
(const PxVehicleTireSlipState& tireSlipState,
const OmniPvdObjectHandle oh, const TireSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.lngSlipAH, tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.latSlipAH, tireSlipState.slips[PxVehicleTireDirectionModes::eLATERAL]);
}
TireStickyState registerTireStickyState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("StickyTireBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
TireStickyState t;
t.CH = omniWriter.registerClass("TireStickyState");
t.lngStickyStateTimer = omniWriter.registerAttribute(t.CH, "lngStickyTimer", OmniPvdDataType::eFLOAT32, 1);
t.lngStickyStateStatus = omniWriter.registerFlagsAttribute(t.CH, "lngStickyStatus", boolAsEnum.CH);
t.latStickyStateTimer = omniWriter.registerAttribute(t.CH, "latStickyTimer", OmniPvdDataType::eFLOAT32, 1);
t.latStickyStateStatus = omniWriter.registerFlagsAttribute(t.CH, "latStickyStatus", boolAsEnum.CH);
return t;
}
void writeTireStickyState
(const PxVehicleTireStickyState& tireStickyState,
const OmniPvdObjectHandle oh, const TireStickyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.latStickyStateStatus, tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL] ? 1 : 0);
writeFlagAttribute(omniWriter, ch, oh, ah.lngStickyStateStatus, tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] ? 1 : 0);
writeFloatAttribute(omniWriter, ch, oh, ah.latStickyStateTimer, tireStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.lngStickyStateTimer, tireStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL]);
}
TireGripState registerTireGripState(OmniPvdWriter& omniWriter)
{
TireGripState t;
t.CH = omniWriter.registerClass("TireGripState");
t.loadAH = omniWriter.registerAttribute(t.CH, "load", OmniPvdDataType::eFLOAT32, 1);
t.frictionAH = omniWriter.registerAttribute(t.CH, "friction", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireGripState
(const PxVehicleTireGripState& tireGripState,
const OmniPvdObjectHandle oh, const TireGripState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.frictionAH, tireGripState.friction);
writeFloatAttribute(omniWriter, ch, oh, ah.loadAH, tireGripState.load);
}
TireCamberState registerTireCamberState(OmniPvdWriter& omniWriter)
{
TireCamberState t;
t.CH = omniWriter.registerClass("TireCamberState");
t.camberAngleAH = omniWriter.registerAttribute(t.CH, "camberAngle", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireCamberState
(const PxVehicleTireCamberAngleState& tireCamberState,
const OmniPvdObjectHandle oh, const TireCamberState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.camberAngleAH, tireCamberState.camberAngle);
}
TireForce registerTireForce(OmniPvdWriter& omniWriter)
{
TireForce t;
t.CH = omniWriter.registerClass("TireForce");
t.lngForceAH = omniWriter.registerAttribute(t.CH, "lngForce", OmniPvdDataType::eFLOAT32, 3);
t.lngTorqueAH = omniWriter.registerAttribute(t.CH, "lngTorque", OmniPvdDataType::eFLOAT32, 3);
t.latForceAH = omniWriter.registerAttribute(t.CH, "latForce", OmniPvdDataType::eFLOAT32, 3);
t.latTorqueAH = omniWriter.registerAttribute(t.CH, "latTorque", OmniPvdDataType::eFLOAT32, 3);
t.aligningMomentAH = omniWriter.registerAttribute(t.CH, "aligningMoment", OmniPvdDataType::eFLOAT32, 3);
t.wheelTorqueAH = omniWriter.registerAttribute(t.CH, "wheelTorque", OmniPvdDataType::eFLOAT32, 3);
return t;
}
void writeTireForce
(const PxVehicleTireForce& tireForce,
const OmniPvdObjectHandle oh, const TireForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.lngForceAH, tireForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.lngTorqueAH, tireForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.latForceAH, tireForce.forces[PxVehicleTireDirectionModes::eLATERAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.latTorqueAH, tireForce.torques[PxVehicleTireDirectionModes::eLATERAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.aligningMomentAH, tireForce.aligningMoment);
writeFloatAttribute(omniWriter, ch, oh, ah.wheelTorqueAH, tireForce.wheelTorque);
}
WheelAttachment registerWheelAttachment(OmniPvdWriter& omniWriter)
{
WheelAttachment w;
w.CH = omniWriter.registerClass("WheelAttachment");
w.wheelParamsAH = omniWriter.registerAttribute(w.CH, "wheelParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.wheelActuationStateAH = omniWriter.registerAttribute(w.CH, "wheelActuationState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.wheelRigidBody1dStateAH = omniWriter.registerAttribute(w.CH, "wheelRigidBody1dState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.wheelLocalPoseStateAH = omniWriter.registerAttribute(w.CH, "wheelLocalPosetate", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.roadGeomStateAH = omniWriter.registerAttribute(w.CH, "roadGeomState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspParamsAH = omniWriter.registerAttribute(w.CH, "suspParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspCompParamsAH = omniWriter.registerAttribute(w.CH, "suspComplianceParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspForceParamsAH = omniWriter.registerAttribute(w.CH, "suspForceParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspStateAH = omniWriter.registerAttribute(w.CH, "suspState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspCompStateAH = omniWriter.registerAttribute(w.CH, "suspComplianceState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspForceAH = omniWriter.registerAttribute(w.CH, "suspForce", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireParamsAH = omniWriter.registerAttribute(w.CH, "tireParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireDirectionStateAH = omniWriter.registerAttribute(w.CH, "tireDirectionState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireSpeedStateAH = omniWriter.registerAttribute(w.CH, "tireSpeedState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireSlipStateAH = omniWriter.registerAttribute(w.CH, "tireSlipState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireStickyStateAH = omniWriter.registerAttribute(w.CH, "tireStickyState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireGripStateAH = omniWriter.registerAttribute(w.CH, "tireGripState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireCamberStateAH = omniWriter.registerAttribute(w.CH, "tireCamberState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireForceAH = omniWriter.registerAttribute(w.CH, "tireForce", OmniPvdDataType::eOBJECT_HANDLE, 1);
return w;
}
//////////////////////////
//ANTIROLL
//////////////////////////
AntiRollParams registerAntiRollParams(OmniPvdWriter& omniWriter)
{
AntiRollParams a;
a.CH = omniWriter.registerClass("AntiRollParams");
a.wheel0AH = omniWriter.registerAttribute(a.CH, "wheel0", OmniPvdDataType::eUINT32, 1);
a.wheel1AH = omniWriter.registerAttribute(a.CH, "wheel1", OmniPvdDataType::eUINT32, 1);
a.stiffnessAH = omniWriter.registerAttribute(a.CH, "stiffness", OmniPvdDataType::eFLOAT32, 1);
return a;
}
void writeAntiRollParams
(const PxVehicleAntiRollForceParams& antiRollParams,
const OmniPvdObjectHandle oh, const AntiRollParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.wheel0AH, antiRollParams.wheel0);
writeUInt32Attribute(omniWriter, ch, oh, ah.wheel1AH, antiRollParams.wheel1);
writeFloatAttribute(omniWriter, ch, oh, ah.stiffnessAH, antiRollParams.stiffness);
}
AntiRollForce registerAntiRollForce(OmniPvdWriter& omniWriter)
{
AntiRollForce a;
a.CH = omniWriter.registerClass("AntiRollForce");
a.torqueAH = omniWriter.registerAttribute(a.CH, "torque", OmniPvdDataType::eFLOAT32, 3);
return a;
}
void writeAntiRollForce
(const PxVehicleAntiRollTorque& antiRollForce,
const OmniPvdObjectHandle oh, const AntiRollForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.torqueAH, antiRollForce.antiRollTorque);
}
//////////////////////////////////
//SUSPENSION STATE CALCULATION
//////////////////////////////////
SuspStateCalcParams registerSuspStateCalcParams(OmniPvdWriter& omniWriter)
{
struct SuspJounceCalcType
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle raycastAH;
OmniPvdAttributeHandle sweepAH;
OmniPvdAttributeHandle noneAH;
};
SuspJounceCalcType jounceCalcType;
jounceCalcType.CH = omniWriter.registerClass("SuspJounceCalculationType");
jounceCalcType.raycastAH = omniWriter.registerEnumValue(jounceCalcType.CH, "raycast", PxVehicleSuspensionJounceCalculationType::eRAYCAST);
jounceCalcType.sweepAH = omniWriter.registerEnumValue(jounceCalcType.CH, "sweep", PxVehicleSuspensionJounceCalculationType::eSWEEP);
jounceCalcType.noneAH = omniWriter.registerEnumValue(jounceCalcType.CH, "none", PxVehicleSuspensionJounceCalculationType::eMAX_NB);
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("SuspStateCalcParamsBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
SuspStateCalcParams s;
s.CH = omniWriter.registerClass("SuspStateCalculationParams");
s.calcTypeAH = omniWriter.registerFlagsAttribute(s.CH, "suspJounceCalculationType", jounceCalcType.CH);
s.limitExpansionValAH = omniWriter.registerFlagsAttribute(s.CH, "limitSuspensionExpansionVelocity", boolAsEnum.CH);
return s;
}
void writeSuspStateCalcParams
(const PxVehicleSuspensionStateCalculationParams& suspStateCalcParams,
const OmniPvdObjectHandle oh, const SuspStateCalcParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.limitExpansionValAH, suspStateCalcParams.limitSuspensionExpansionVelocity ? 1 : 0);
writeFlagAttribute(omniWriter, ch, oh, ah.calcTypeAH, suspStateCalcParams.suspensionJounceCalculationType);
}
//////////////////////////////////////
//DIRECT DRIVETRAIN
//////////////////////////////////////
DirectDriveCommandState registerDirectDriveCommandState(OmniPvdWriter& omniWriter)
{
DirectDriveCommandState c;
c.CH = omniWriter.registerClass("DirectDriveCommandState");
c.brakesAH= omniWriter.registerAttribute(c.CH, "brakes", OmniPvdDataType::eFLOAT32, 2);
c.throttleAH= omniWriter.registerAttribute(c.CH, "throttle", OmniPvdDataType::eFLOAT32, 1);
c.steerAH= omniWriter.registerAttribute(c.CH, "steer", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeDirectDriveCommandState
(const PxVehicleCommandState& commands,
const OmniPvdObjectHandle oh, const DirectDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float brakes[2];
for(PxU32 i = 0; i < commands.nbBrakes; i++)
{
brakes[i] = commands.brakes[i];
}
for(PxU32 i = commands.nbBrakes; i < 2; i++)
{
brakes[i] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.brakesAH, brakes, 2);
writeFloatAttribute(omniWriter, ch, oh, ah.throttleAH, commands.throttle);
writeFloatAttribute(omniWriter, ch, oh, ah.steerAH, commands.steer);
}
DirectDriveTransmissionCommandState registerDirectDriveTransmissionCommandState(OmniPvdWriter& omniWriter)
{
struct DirectDriveGear
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle reverse;
OmniPvdAttributeHandle neutral;
OmniPvdAttributeHandle forward;
};
DirectDriveGear g;
g.CH = omniWriter.registerClass("DirectDriveGear");
g.reverse = omniWriter.registerEnumValue(g.CH, "reverse", PxVehicleDirectDriveTransmissionCommandState::eREVERSE);
g.neutral = omniWriter.registerEnumValue(g.CH, "neutral", PxVehicleDirectDriveTransmissionCommandState::eNEUTRAL);
g.forward = omniWriter.registerEnumValue(g.CH, "forward", PxVehicleDirectDriveTransmissionCommandState::eFORWARD);
DirectDriveTransmissionCommandState c;
c.CH = omniWriter.registerClass("DirectDriveTransmissionCommandState");
c.gearAH = omniWriter.registerFlagsAttribute(c.CH, "gear", g.CH);
return c;
}
void writeDirectDriveTransmissionCommandState
(const PxVehicleDirectDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const DirectDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.gearAH, transmission.gear);
}
WheelResponseParams registerDirectDriveThrottleResponseParams(OmniPvdWriter& omniWriter)
{
return registerWheelResponseParams("DirectDriveThrottleResponseParams", omniWriter);
}
void writeDirectDriveThrottleResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleDirectDriveThrottleCommandResponseParams& directDriveThrottleResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseParams(axleDesc, directDriveThrottleResponseParams, oh, ah, omniWriter, ch);
}
DirectDriveThrottleResponseState registerDirectDriveThrottleResponseState(OmniPvdWriter& omniWriter)
{
DirectDriveThrottleResponseState d;
d.CH = omniWriter.registerClass("DirectDriveThrottleResponseState");
d.states0To3AH = omniWriter.registerAttribute(d.CH, "responseState0To3", OmniPvdDataType::eFLOAT32, 4);
d.states4To7AH = omniWriter.registerAttribute(d.CH, "responseState4To7", OmniPvdDataType::eFLOAT32, 4);
d.states8To11AH = omniWriter.registerAttribute(d.CH, "responseState8To11", OmniPvdDataType::eFLOAT32, 4);
d.states12To15AH = omniWriter.registerAttribute(d.CH, "responseState12To15", OmniPvdDataType::eFLOAT32, 4);
d.states16To19AH = omniWriter.registerAttribute(d.CH, "responseState16To19", OmniPvdDataType::eFLOAT32, 4);
return d;
}
void writeDirectDriveThrottleResponseState
(const PxVehicleAxleDescription& axleDesc, const PxVehicleArrayData<PxReal>& throttleResponseState,
const OmniPvdObjectHandle oh, const DirectDriveThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
//States are always in setToDefault() state as default.
PxF32 states[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemZero(states, sizeof(states));
if(!throttleResponseState.isEmpty())
{
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
states[wheelId] = throttleResponseState[wheelId];
}
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states0To3AH, states + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states4To7AH, states + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states8To11AH, states + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states12To15AH, states + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states16To19AH, states + 16, 4);
}
DirectDrivetrain registerDirectDrivetrain(OmniPvdWriter& omniWriter)
{
DirectDrivetrain d;
d.CH = omniWriter.registerClass("DirectDrivetrain");
d.throttleResponseParamsAH = omniWriter.registerAttribute(d.CH, "throttleResponseParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
d.commandStateAH = omniWriter.registerAttribute(d.CH, "commandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
d.transmissionCommandStateAH = omniWriter.registerAttribute(d.CH, "transmissionCommandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
d.throttleResponseStateAH = omniWriter.registerAttribute(d.CH, "throttleResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
return d;
}
//////////////////////////////
//ENGINE DRIVETRAIN
//////////////////////////////
EngineDriveCommandState registerEngineDriveCommandState(OmniPvdWriter& omniWriter)
{
EngineDriveCommandState c;
c.CH = omniWriter.registerClass("EngineDriveCommandState");
c.brakesAH = omniWriter.registerAttribute(c.CH, "brakes", OmniPvdDataType::eFLOAT32, 2);
c.throttleAH = omniWriter.registerAttribute(c.CH, "throttle", OmniPvdDataType::eFLOAT32, 1);
c.steerAH = omniWriter.registerAttribute(c.CH, "steer", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeEngineDriveCommandState
(const PxVehicleCommandState& commands,
const OmniPvdObjectHandle oh, const EngineDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float brakes[2];
for(PxU32 i = 0; i < commands.nbBrakes; i++)
{
brakes[i] = commands.brakes[i];
}
for(PxU32 i = commands.nbBrakes; i < 2; i++)
{
brakes[i] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.brakesAH, brakes, 2);
writeFloatAttribute(omniWriter, ch, oh, ah.throttleAH, commands.throttle);
writeFloatAttribute(omniWriter, ch, oh, ah.steerAH, commands.steer);
}
EngineDriveTransmissionCommandState registerEngineDriveTransmissionCommandState(OmniPvdWriter& omniWriter)
{
EngineDriveTransmissionCommandState c;
c.CH = omniWriter.registerClass("EngineDriveTransmissionCommandState");
c.gearAH = omniWriter.registerAttribute(c.CH, "targetGear", OmniPvdDataType::eUINT32, 1);
c.clutchAH = omniWriter.registerAttribute(c.CH, "clutch", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeEngineDriveTransmissionCommandState
(const PxVehicleEngineDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const EngineDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.gearAH, transmission.targetGear);
writeFloatAttribute(omniWriter, ch, oh, ah.clutchAH, transmission.clutch);
}
static const PxU32 tankThrustsCommandEntryCount = sizeof(PxVehicleTankDriveTransmissionCommandState::thrusts) / sizeof(PxVehicleTankDriveTransmissionCommandState::thrusts[0]);
TankDriveTransmissionCommandState registerTankDriveTransmissionCommandState(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass)
{
TankDriveTransmissionCommandState t;
t.CH = omniWriter.registerClass("TankDriveTransmissionCommandState", baseClass);
t.thrustsAH = omniWriter.registerAttribute(t.CH, "thrusts", OmniPvdDataType::eFLOAT32, tankThrustsCommandEntryCount);
return t;
}
void writeTankDriveTransmissionCommandState
(const PxVehicleTankDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const EngineDriveTransmissionCommandState& engineDriveAH,
const TankDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeEngineDriveTransmissionCommandState(transmission, oh, engineDriveAH, omniWriter, ch);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.thrustsAH, transmission.thrusts, tankThrustsCommandEntryCount);
}
ClutchResponseParams registerClutchResponseParams(OmniPvdWriter& omniWriter)
{
ClutchResponseParams c;
c.CH = omniWriter.registerClass("ClutchResponseParams");
c.maxResponseAH = omniWriter.registerAttribute(c.CH, "MaxResponse", OmniPvdDataType::eFLOAT32, 1);
return c;
}
ClutchParams registerClutchParams(OmniPvdWriter& omniWriter)
{
struct VehicleClutchAccuracyMode
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle estimateAH;
OmniPvdAttributeHandle bestPossibleAH;
};
VehicleClutchAccuracyMode mode;
mode.CH = omniWriter.registerClass("ClutchAccuracyMode");
mode.estimateAH = omniWriter.registerEnumValue(mode.CH, "estimate", PxVehicleClutchAccuracyMode::eESTIMATE);
mode.bestPossibleAH = omniWriter.registerEnumValue(mode.CH, "bestPossible", PxVehicleClutchAccuracyMode::eBEST_POSSIBLE);
ClutchParams v;
v.CH = omniWriter.registerClass("ClutchParams");
v.accuracyAH = omniWriter.registerFlagsAttribute(v.CH, "accuracyMode", mode.CH);
v.iterationsAH = omniWriter.registerAttribute(v.CH, "iterations", OmniPvdDataType::eUINT32, 1);
return v;
}
void writeClutchParams
(const PxVehicleClutchParams& clutchParams,
const OmniPvdObjectHandle oh, const ClutchParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.accuracyAH, clutchParams.accuracyMode);
writeUInt32Attribute(omniWriter, ch, oh, ah.iterationsAH, clutchParams.estimateIterations);
}
EngineParams registerEngineParams(OmniPvdWriter& omniWriter)
{
EngineParams e;
e.CH = omniWriter.registerClass("EngineParams");
e.torqueCurveAH = omniWriter.registerAttribute(e.CH, "torqueCurve", OmniPvdDataType::eFLOAT32, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES*2);
e.peakTorqueAH = omniWriter.registerAttribute(e.CH, "peakTorque", OmniPvdDataType::eFLOAT32, 1);
e.moiAH = omniWriter.registerAttribute(e.CH, "moi", OmniPvdDataType::eFLOAT32, 1);
e.idleOmegaAH = omniWriter.registerAttribute(e.CH, "idleOmega", OmniPvdDataType::eFLOAT32, 1);
e.maxOmegaAH = omniWriter.registerAttribute(e.CH, "maxOmega", OmniPvdDataType::eFLOAT32, 1);
e.dampingRateFullThrottleAH = omniWriter.registerAttribute(e.CH, "dampingRateFullThrottleAH", OmniPvdDataType::eFLOAT32, 1);
e.dampingRateZeroThrottleClutchDisengagedAH = omniWriter.registerAttribute(e.CH, "dampingRateZeroThrottleClutchDisengaged", OmniPvdDataType::eFLOAT32, 1);
e.dampingRateZeroThrottleClutchEngagedAH = omniWriter.registerAttribute(e.CH, "dampingRateZeroThrottleClutchEngaged", OmniPvdDataType::eFLOAT32, 1);
return e;
}
void writeEngineParams
(const PxVehicleEngineParams& engineParams,
const OmniPvdObjectHandle oh, const EngineParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float torqueCurve[PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES*2];
for(PxU32 i = 0; i < engineParams.torqueCurve.nbDataPairs; i++)
{
torqueCurve[2*i + 0] = engineParams.torqueCurve.xVals[i];
torqueCurve[2*i + 1] = engineParams.torqueCurve.yVals[i];
}
for(PxU32 i = engineParams.torqueCurve.nbDataPairs; i < PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES; i++)
{
torqueCurve[2*i + 0] = PX_MAX_F32;
torqueCurve[2*i + 1] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueCurveAH, torqueCurve, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES*2);
writeFloatAttribute(omniWriter, ch, oh, ah.peakTorqueAH, engineParams.peakTorque);
writeFloatAttribute(omniWriter, ch, oh, ah.moiAH, engineParams.moi);
writeFloatAttribute(omniWriter, ch, oh, ah.idleOmegaAH, engineParams.idleOmega);
writeFloatAttribute(omniWriter, ch, oh, ah.maxOmegaAH, engineParams.maxOmega);
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateFullThrottleAH, engineParams.dampingRateFullThrottle);
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateZeroThrottleClutchDisengagedAH, engineParams.dampingRateZeroThrottleClutchDisengaged);
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateZeroThrottleClutchEngagedAH, engineParams.dampingRateZeroThrottleClutchEngaged);
}
GearboxParams registerGearboxParams(OmniPvdWriter& omniWriter)
{
GearboxParams g;
g.CH = omniWriter.registerClass("GearboxParams");
g.ratiosAH = omniWriter.registerAttribute(g.CH, "ratios", OmniPvdDataType::eFLOAT32, PxVehicleGearboxParams::eMAX_NB_GEARS);
g.nbRatiosAH = omniWriter.registerAttribute(g.CH, "nbRatios", OmniPvdDataType::eUINT32, 1);
g.neutralGearAH = omniWriter.registerAttribute(g.CH, "neutralGear", OmniPvdDataType::eUINT32, 1);
g.finalRatioAH = omniWriter.registerAttribute(g.CH, "finalRatio", OmniPvdDataType::eFLOAT32, 1);
g.switchTimeAH = omniWriter.registerAttribute(g.CH, "switchTime", OmniPvdDataType::eFLOAT32, 1);
return g;
}
void writeGearboxParams
(const PxVehicleGearboxParams& gearboxParams,
const OmniPvdObjectHandle oh, const GearboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float ratios[PxVehicleGearboxParams::eMAX_NB_GEARS];
PxMemCopy(ratios, gearboxParams.ratios, sizeof(float)*gearboxParams.nbRatios);
for(PxU32 i = gearboxParams.nbRatios; i < PxVehicleGearboxParams::eMAX_NB_GEARS; i++)
{
ratios[i] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.ratiosAH, ratios, PxVehicleGearboxParams::eMAX_NB_GEARS);
writeUInt32Attribute(omniWriter, ch, oh, ah.nbRatiosAH, gearboxParams.nbRatios);
writeUInt32Attribute(omniWriter, ch, oh, ah.neutralGearAH, gearboxParams.neutralGear);
writeFloatAttribute(omniWriter, ch, oh, ah.finalRatioAH, gearboxParams.finalRatio);
writeFloatAttribute(omniWriter, ch, oh, ah.switchTimeAH, gearboxParams.switchTime);
}
AutoboxParams registerAutoboxParams(OmniPvdWriter& omniWriter)
{
AutoboxParams a;
a.CH = omniWriter.registerClass("AutoboxParams");
a.upRatiosAH = omniWriter.registerAttribute(a.CH, "upRatios", OmniPvdDataType::eFLOAT32, PxVehicleGearboxParams::eMAX_NB_GEARS);
a.downRatiosAH = omniWriter.registerAttribute(a.CH, "downRatios", OmniPvdDataType::eFLOAT32, PxVehicleGearboxParams::eMAX_NB_GEARS);
a.latencyAH = omniWriter.registerAttribute(a.CH, "latency", OmniPvdDataType::eFLOAT32, 1);
return a;
}
void writeAutoboxParams
(const PxVehicleAutoboxParams& autoboxParams,
const OmniPvdObjectHandle oh, const AutoboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatArrayAttribute(omniWriter, ch, oh, ah.upRatiosAH, autoboxParams.upRatios, PxVehicleGearboxParams::eMAX_NB_GEARS);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.downRatiosAH, autoboxParams.downRatios, PxVehicleGearboxParams::eMAX_NB_GEARS);
writeFloatAttribute(omniWriter, ch, oh, ah.latencyAH, autoboxParams.latency);
}
MultiWheelDiffParams registerMultiWheelDiffParams(OmniPvdWriter& omniWriter)
{
MultiWheelDiffParams m;
m.CH = omniWriter.registerClass("MultiWheelDiffParams");
m.torqueRatios0To3AH = omniWriter.registerAttribute(m.CH, "torqueRatios0To3", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios4To7AH = omniWriter.registerAttribute(m.CH, "torqueRatios4To7", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios8To11AH = omniWriter.registerAttribute(m.CH, "torqueRatios8To11", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios12To15AH = omniWriter.registerAttribute(m.CH, "torqueRatios12To15", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios16To19AH = omniWriter.registerAttribute(m.CH, "torqueRatios16To19", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios0To3AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios0To3", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios4To7AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios4To7", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios8To11AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios8To11", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios12To15AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios12To15", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios16To19AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios16To19", OmniPvdDataType::eFLOAT32, 4);
return m;
}
FourWheelDiffParams registerFourWheelDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass)
{
FourWheelDiffParams m;
m.CH = omniWriter.registerClass("FourWheelDiffParams", baseClass);
m.frontBiasAH = omniWriter.registerAttribute(m.CH, "frontBias", OmniPvdDataType::eFLOAT32, 1);
m.frontTargetAH = omniWriter.registerAttribute(m.CH, "frontTarget", OmniPvdDataType::eFLOAT32, 1);
m.rearBiasAH = omniWriter.registerAttribute(m.CH, "rearBias", OmniPvdDataType::eFLOAT32, 1);
m.rearTargetAH = omniWriter.registerAttribute(m.CH, "rearTarget", OmniPvdDataType::eFLOAT32, 1);
m.centreBiasAH = omniWriter.registerAttribute(m.CH, "centerBias", OmniPvdDataType::eFLOAT32, 1);
m.centreTargetAH = omniWriter.registerAttribute(m.CH, "centerTarget", OmniPvdDataType::eFLOAT32, 1);
m.frontWheelsAH = omniWriter.registerAttribute(m.CH, "frontWheels", OmniPvdDataType::eUINT32, 2);
m.rearWheelsAH = omniWriter.registerAttribute(m.CH, "rearWheels", OmniPvdDataType::eUINT32, 2);
return m;
}
TankDiffParams registerTankDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass)
{
TankDiffParams t;
t.CH = omniWriter.registerClass("TankDiffParams", baseClass);
t.nbTracksAH = omniWriter.registerAttribute(t.CH, "nbTracks", OmniPvdDataType::eUINT32, 1);
t.thrustIdPerTrackAH = omniWriter.registerAttribute(t.CH, "thrustIdPerTrack", OmniPvdDataType::eUINT32, 0);
t.nbWheelsPerTrackAH = omniWriter.registerAttribute(t.CH, "nbWheelsPerTrack", OmniPvdDataType::eUINT32, 0);
t.trackToWheelIdsAH = omniWriter.registerAttribute(t.CH, "trackToWheelIds", OmniPvdDataType::eUINT32, 0);
t.wheelIdsInTrackOrderAH = omniWriter.registerAttribute(t.CH, "wheelIdsInTrackOrder", OmniPvdDataType::eUINT32, 0);
return t;
}
void writeMultiWheelDiffParams
(const PxVehicleMultiWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios0To3AH, diffParams.aveWheelSpeedRatios + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios4To7AH, diffParams.aveWheelSpeedRatios + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios8To11AH, diffParams.aveWheelSpeedRatios + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios12To15AH, diffParams.aveWheelSpeedRatios + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios16To19AH, diffParams.aveWheelSpeedRatios + 16, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios0To3AH, diffParams.torqueRatios + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios4To7AH, diffParams.torqueRatios + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios8To11AH, diffParams.torqueRatios + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios12To15AH, diffParams.torqueRatios + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios16To19AH, diffParams.torqueRatios + 16, 4);
}
void writeFourWheelDiffParams
(const PxVehicleFourWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& multiWheelDiffAH, const FourWheelDiffParams& ah,
OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeMultiWheelDiffParams(diffParams, oh, multiWheelDiffAH, omniWriter, ch);
writeFloatAttribute(omniWriter, ch, oh, ah.frontBiasAH, diffParams.frontBias);
writeFloatAttribute(omniWriter, ch, oh, ah.frontTargetAH, diffParams.frontTarget);
writeFloatAttribute(omniWriter, ch, oh, ah.rearBiasAH, diffParams.rearBias);
writeFloatAttribute(omniWriter, ch, oh, ah.rearTargetAH, diffParams.rearTarget);
writeFloatAttribute(omniWriter, ch, oh, ah.centreBiasAH, diffParams.centerBias);
writeFloatAttribute(omniWriter, ch, oh, ah.centreTargetAH, diffParams.centerTarget);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.frontWheelsAH, diffParams.frontWheelIds, 2);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.rearWheelsAH, diffParams.rearWheelIds, 2);
}
void writeTankDiffParams
(const PxVehicleTankDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& multiWheelDiffAH, const TankDiffParams& ah,
OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
PxU32 entryCount = 0;
for (PxU32 i = 0; i < diffParams.nbTracks; i++)
{
entryCount = PxMax(entryCount, diffParams.trackToWheelIds[i] + diffParams.nbWheelsPerTrack[i]);
// users can remove tracks such that there are holes in the wheelIdsInTrackOrder buffer
}
writeMultiWheelDiffParams(diffParams, oh, multiWheelDiffAH, omniWriter, ch);
writeUInt32Attribute(omniWriter, ch, oh, ah.nbTracksAH, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.thrustIdPerTrackAH, diffParams.thrustIdPerTrack, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.nbWheelsPerTrackAH, diffParams.nbWheelsPerTrack, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.trackToWheelIdsAH, diffParams.trackToWheelIds, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.wheelIdsInTrackOrderAH, diffParams.wheelIdsInTrackOrder, entryCount);
}
ClutchResponseState registerClutchResponseState(OmniPvdWriter& omniWriter)
{
ClutchResponseState c;
c.CH = omniWriter.registerClass("ClutchResponseState");
c.normalisedResponseAH = omniWriter.registerAttribute(c.CH, "normalisedResponse", OmniPvdDataType::eFLOAT32, 1);
c.responseAH = omniWriter.registerAttribute(c.CH, "response", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeClutchResponseState
(const PxVehicleClutchCommandResponseState& clutchResponseState,
const OmniPvdObjectHandle oh, const ClutchResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.normalisedResponseAH, clutchResponseState.normalisedCommandResponse);
writeFloatAttribute(omniWriter, ch, oh, ah.responseAH, clutchResponseState.commandResponse);
}
ThrottleResponseState registerThrottleResponseState(OmniPvdWriter& omniWriter)
{
ThrottleResponseState t;
t.CH = omniWriter.registerClass("ThrottleResponseState");
t.responseAH = omniWriter.registerAttribute(t.CH, "response", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeThrottleResponseState
(const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState,
const OmniPvdObjectHandle oh, const ThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.responseAH, throttleResponseState.commandResponse);
}
EngineState registerEngineState(OmniPvdWriter& omniWriter)
{
EngineState e;
e.CH = omniWriter.registerClass("EngineState");
e.rotationSpeedAH = omniWriter.registerAttribute(e.CH, "rotationSpeed", OmniPvdDataType::eFLOAT32, 1);
return e;
}
void writeEngineState
(const PxVehicleEngineState& engineState,
const OmniPvdObjectHandle oh, const EngineState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.rotationSpeedAH, engineState.rotationSpeed);
}
GearboxState registerGearboxState(OmniPvdWriter& omniWriter)
{
GearboxState g;
g.CH = omniWriter.registerClass("GearboxState");
g.currentGearAH = omniWriter.registerAttribute(g.CH, "currentGear", OmniPvdDataType::eUINT32, 1);
g.targetGearAH = omniWriter.registerAttribute(g.CH, "targetGear", OmniPvdDataType::eUINT32, 1);
g.switchTimeAH = omniWriter.registerAttribute(g.CH, "switchTime", OmniPvdDataType::eFLOAT32, 1);
return g;
}
void writeGearboxState
(const PxVehicleGearboxState& gearboxState,
const OmniPvdObjectHandle oh, const GearboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.currentGearAH, gearboxState.currentGear);
writeUInt32Attribute(omniWriter, ch, oh, ah.targetGearAH, gearboxState.targetGear);
writeFloatAttribute(omniWriter, ch, oh, ah.switchTimeAH, gearboxState.gearSwitchTime);
}
AutoboxState registerAutoboxState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("AutoboxStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
AutoboxState a;
a.CH = omniWriter.registerClass("AutoboxState");
a.timeSinceLastShiftAH = omniWriter.registerAttribute(a.CH, "timeSinceLastShift", OmniPvdDataType::eFLOAT32, 1);
a.activeAutoboxGearShiftAH = omniWriter.registerFlagsAttribute(a.CH, "activeAutoboxShift", boolAsEnum.CH);
return a;
}
void writeAutoboxState
(const PxVehicleAutoboxState& autoboxState,
const OmniPvdObjectHandle oh, const AutoboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.timeSinceLastShiftAH, autoboxState.timeSinceLastShift);
writeFlagAttribute(omniWriter, ch, oh, ah.activeAutoboxGearShiftAH, autoboxState.activeAutoboxGearShift ? 1: 0);
}
DiffState registerDiffState(OmniPvdWriter& omniWriter)
{
DiffState d;
d.CH = omniWriter.registerClass("DifferentialState");
d.torqueRatios0To3AH = omniWriter.registerAttribute(d.CH, "torqueRatios0To3", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios4To7AH = omniWriter.registerAttribute(d.CH, "torqueRatios4To7", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios8To11AH = omniWriter.registerAttribute(d.CH, "torqueRatios8To11", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios12To15AH = omniWriter.registerAttribute(d.CH, "torqueRatios12To15", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios16To19AH = omniWriter.registerAttribute(d.CH, "torqueRatios16To19", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios0To3AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios0To3", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios4To7AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios4To7", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios8To11AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios8To11", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios12To15AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios12To15", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios16To19AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios16To19", OmniPvdDataType::eFLOAT32, 4);
return d;
}
void writeDiffState
(const PxVehicleDifferentialState& diffState,
const OmniPvdObjectHandle oh, const DiffState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios0To3AH, diffState.aveWheelSpeedContributionAllWheels + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios4To7AH, diffState.aveWheelSpeedContributionAllWheels + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios8To11AH, diffState.aveWheelSpeedContributionAllWheels + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios12To15AH, diffState.aveWheelSpeedContributionAllWheels + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios16To19AH, diffState.aveWheelSpeedContributionAllWheels + 16, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios0To3AH, diffState.torqueRatiosAllWheels + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios4To7AH, diffState.torqueRatiosAllWheels + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios8To11AH, diffState.torqueRatiosAllWheels + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios12To15AH, diffState.torqueRatiosAllWheels + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios16To19AH, diffState.torqueRatiosAllWheels + 16, 4);
}
ClutchSlipState registerClutchSlipState(OmniPvdWriter& omniWriter)
{
ClutchSlipState c;
c.CH = omniWriter.registerClass("ClutchSlipState");
c.slipAH = omniWriter.registerAttribute(c.CH, "clutchSlip", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeClutchSlipState
(const PxVehicleClutchSlipState& clutchSlipState,
const OmniPvdObjectHandle oh, const ClutchSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.slipAH, clutchSlipState.clutchSlip);
}
EngineDrivetrain registerEngineDrivetrain(OmniPvdWriter& omniWriter)
{
EngineDrivetrain e;
e.CH = omniWriter.registerClass("EngineDrivetrain");
e.commandStateAH = omniWriter.registerAttribute(e.CH, "commandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.transmissionCommandStateAH = omniWriter.registerAttribute(e.CH, "transmissionCommandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchResponseParamsAH = omniWriter.registerAttribute(e.CH, "clutchResponseParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchParamsAH = omniWriter.registerAttribute(e.CH, "clutchParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.engineParamsAH = omniWriter.registerAttribute(e.CH, "engineParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.gearboxParamsAH = omniWriter.registerAttribute(e.CH, "gearboxParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.autoboxParamsAH = omniWriter.registerAttribute(e.CH, "autoboxParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.differentialParamsAH = omniWriter.registerAttribute(e.CH, "differentialParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchResponseStateAH= omniWriter.registerAttribute(e.CH, "clutchResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.throttleResponseStateAH= omniWriter.registerAttribute(e.CH, "throttleResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.engineStateAH = omniWriter.registerAttribute(e.CH, "engineState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.gearboxStateAH = omniWriter.registerAttribute(e.CH, "gearboxState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.autoboxStateAH = omniWriter.registerAttribute(e.CH, "autoboxState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.diffStateAH = omniWriter.registerAttribute(e.CH, "diffState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchSlipStateAH = omniWriter.registerAttribute(e.CH, "clutchSlipState", OmniPvdDataType::eOBJECT_HANDLE, 1);
return e;
}
////////////////////////////
//PHYSX WHEEL ATTACHMENT
////////////////////////////
PhysXSuspensionLimitConstraintParams registerSuspLimitConstraintParams(OmniPvdWriter& omniWriter)
{
struct DirSpecifier
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle suspensionAH;
OmniPvdAttributeHandle geomNormalAH;
OmniPvdAttributeHandle noneAH;
};
DirSpecifier s;
s.CH = omniWriter.registerClass("DirectionSpecifier");
s.suspensionAH = omniWriter.registerEnumValue(s.CH, "suspensionDir",
PxVehiclePhysXSuspensionLimitConstraintParams::DirectionSpecifier::eSUSPENSION);
s.geomNormalAH = omniWriter.registerEnumValue(s.CH, "geomNormalDir",
PxVehiclePhysXSuspensionLimitConstraintParams::DirectionSpecifier::eROAD_GEOMETRY_NORMAL);
s.noneAH = omniWriter.registerEnumValue(s.CH, "geomNormalDir",
PxVehiclePhysXSuspensionLimitConstraintParams::DirectionSpecifier::eNONE);
PhysXSuspensionLimitConstraintParams c;
c.CH = omniWriter.registerClass("PhysXSuspLimitConstraintParams");
c.restitutionAH = omniWriter.registerAttribute(c.CH, "restitution", OmniPvdDataType::eFLOAT32, 1);
c.directionForSuspensionLimitConstraintAH = omniWriter.registerFlagsAttribute(c.CH, "directionMode", s.CH);
return c;
}
void writePhysXSuspLimitConstraintParams
(const PxVehiclePhysXSuspensionLimitConstraintParams& params,
const OmniPvdObjectHandle oh, const PhysXSuspensionLimitConstraintParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.directionForSuspensionLimitConstraintAH, params.directionForSuspensionLimitConstraint);
writeFloatAttribute(omniWriter, ch, oh, ah.restitutionAH, params.restitution);
}
PhysXWheelShape registerPhysXWheelShape(OmniPvdWriter& omniWriter)
{
PhysXWheelShape w;
w.CH = omniWriter.registerClass("PhysXWheelShape");
w.shapePtrAH = omniWriter.registerAttribute(w.CH, "pxShapePtr", OmniPvdDataType::eOBJECT_HANDLE, 1);
return w;
}
void writePhysXWheelShape
(const PxShape* wheelShape,
const OmniPvdObjectHandle oh, const PhysXWheelShape& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writePtrAttribute(omniWriter, ch, oh, ah.shapePtrAH, wheelShape);
}
PhysXRoadGeomState registerPhysXRoadGeomState(OmniPvdWriter& omniWriter)
{
PhysXRoadGeomState g;
g.CH = omniWriter.registerClass("PhysXRoadGeomState");
g.hitPositionAH = omniWriter.registerAttribute(g.CH, "hitPosition", OmniPvdDataType::eFLOAT32, 3);
g.hitActorPtrAH = omniWriter.registerAttribute(g.CH, "PxActor", OmniPvdDataType::eOBJECT_HANDLE, 1);
g.hitShapePtrAH = omniWriter.registerAttribute(g.CH, "PxShape", OmniPvdDataType::eOBJECT_HANDLE, 1);
g.hitMaterialPtrAH = omniWriter.registerAttribute(g.CH, "PxMaterial", OmniPvdDataType::eOBJECT_HANDLE, 1);
return g;
}
void writePhysXRoadGeomState
(const PxVehiclePhysXRoadGeometryQueryState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXRoadGeomState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.hitPositionAH, roadGeomState.hitPosition);
writePtrAttribute(omniWriter, ch, oh, ah.hitActorPtrAH, roadGeomState.actor);
writePtrAttribute(omniWriter, ch, oh, ah.hitMaterialPtrAH, roadGeomState.material);
writePtrAttribute(omniWriter, ch, oh, ah.hitShapePtrAH, roadGeomState.shape);
}
PhysXConstraintState registerPhysXConstraintState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("PhysXConstraintStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
PhysXConstraintState c;
c.CH = omniWriter.registerClass("PhysXConstraintState");
c.tireLongActiveStatusAH = omniWriter.registerFlagsAttribute(c.CH, "tireLongitudinalActiveStatus", boolAsEnum.CH);
c.tireLongLinearAH = omniWriter.registerAttribute(c.CH, "tireLongitudinalLinear", OmniPvdDataType::eFLOAT32, 3);
c.tireLongAngularAH = omniWriter.registerAttribute(c.CH, "tireLongitudinalAngular", OmniPvdDataType::eFLOAT32, 3);
c.tireLongDampingAH = omniWriter.registerAttribute(c.CH, "tireLongitudinalDamping", OmniPvdDataType::eFLOAT32, 1);
c.tireLatActiveStatusAH = omniWriter.registerFlagsAttribute(c.CH, "tireLateralActiveStatus", boolAsEnum.CH);
c.tireLatLinearAH = omniWriter.registerAttribute(c.CH, "tireLateralLinear", OmniPvdDataType::eFLOAT32, 3);
c.tireLatAngularAH = omniWriter.registerAttribute(c.CH, "tireLateralAngular", OmniPvdDataType::eFLOAT32, 3);
c.tireLatDampingAH = omniWriter.registerAttribute(c.CH, "tireLateralDamping", OmniPvdDataType::eFLOAT32, 1);
c.suspActiveStatusAH = omniWriter.registerFlagsAttribute(c.CH, "suspActiveStatus", boolAsEnum.CH);
c.suspLinearAH = omniWriter.registerAttribute(c.CH, "suspLinear", OmniPvdDataType::eFLOAT32, 3);
c.suspAngularAH = omniWriter.registerAttribute(c.CH, "suspAngular", OmniPvdDataType::eFLOAT32, 3);
c.suspRestitutionAH = omniWriter.registerAttribute(c.CH, "suspRestitution", OmniPvdDataType::eFLOAT32, 1);
c.suspGeometricErrorAH = omniWriter.registerAttribute(c.CH, "suspGeometricError", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writePhysXConstraintState
(const PxVehiclePhysXConstraintState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXConstraintState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.suspActiveStatusAH, roadGeomState.suspActiveStatus ? 1 : 0);
writeVec3Attribute(omniWriter, ch, oh, ah.suspLinearAH, roadGeomState.suspLinear);
writeVec3Attribute(omniWriter, ch, oh, ah.suspAngularAH, roadGeomState.suspAngular);
writeFloatAttribute(omniWriter, ch, oh, ah.suspGeometricErrorAH, roadGeomState.suspGeometricError);
writeFloatAttribute(omniWriter, ch, oh, ah.suspRestitutionAH, roadGeomState.restitution);
writeFlagAttribute(omniWriter, ch, oh, ah.tireLongActiveStatusAH, roadGeomState.tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] ? 1 : 0);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLongLinearAH, roadGeomState.tireLinears[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLongAngularAH, roadGeomState.tireAngulars[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.tireLongDampingAH, roadGeomState.tireDamping[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFlagAttribute(omniWriter, ch, oh, ah.tireLatActiveStatusAH, roadGeomState.tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL] ? 1 : 0);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLatLinearAH, roadGeomState.tireLinears[PxVehicleTireDirectionModes::eLATERAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLatAngularAH, roadGeomState.tireAngulars[PxVehicleTireDirectionModes::eLATERAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.tireLatDampingAH, roadGeomState.tireDamping[PxVehicleTireDirectionModes::eLATERAL]);
}
PhysXMaterialFriction registerPhysXMaterialFriction(OmniPvdWriter& omniWriter)
{
PhysXMaterialFriction f;
f.CH = omniWriter.registerClass("PhysXMaterialFriction");
f.frictionAH = omniWriter.registerAttribute(f.CH, "friction", OmniPvdDataType::eFLOAT32, 1);
f.materialPtrAH = omniWriter.registerAttribute(f.CH, "material", OmniPvdDataType::eOBJECT_HANDLE, 1);
return f;
}
void writePhysXMaterialFriction
(const PxVehiclePhysXMaterialFriction& materialFriction,
const OmniPvdObjectHandle oh, const PhysXMaterialFriction& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.frictionAH, materialFriction.friction);
writePtrAttribute(omniWriter, ch, oh, ah.materialPtrAH, materialFriction.material);
}
PhysXWheelAttachment registerPhysXWheelAttachment(OmniPvdWriter& omniWriter)
{
PhysXWheelAttachment w;
w.CH = omniWriter.registerClass("PhysXWheelAttachment");
w.physxConstraintParamsAH = omniWriter.registerAttribute(w.CH, "physxConstraintParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxConstraintStateAH = omniWriter.registerAttribute(w.CH, "physxConstraintState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxWeelShapeAH = omniWriter.registerAttribute(w.CH, "physxWheelShape", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxRoadGeometryStateAH = omniWriter.registerAttribute(w.CH, "physxRoadGeomState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxMaterialFrictionSetAH = omniWriter.registerUniqueListAttribute(w.CH, "physXMaterialFrictions", OmniPvdDataType::eOBJECT_HANDLE);
return w;
}
//////////////////////////
//PHYSX RIGID ACTOR
//////////////////////////
PhysXRigidActor registerPhysXRigidActor(OmniPvdWriter& omniWriter)
{
PhysXRigidActor a;
a.CH = omniWriter.registerClass("PhysXRigidActor");
a.rigidActorAH = omniWriter.registerAttribute(a.CH, "rigidActor", OmniPvdDataType::eOBJECT_HANDLE, 1);
return a;
}
void writePhysXRigidActor
(const PxRigidActor* actor,
const OmniPvdObjectHandle oh, const PhysXRigidActor& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writePtrAttribute(omniWriter, ch, oh, ah.rigidActorAH, actor);
}
PhysXRoadGeometryQueryParams registerPhysXRoadGeometryQueryParams(OmniPvdWriter& omniWriter)
{
struct QueryType
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle raycastAH;
OmniPvdAttributeHandle sweepAH;
OmniPvdAttributeHandle noneAH;
};
QueryType queryType;
queryType.CH = omniWriter.registerClass("PhysXRoadGeometryQueryTpe");
queryType.raycastAH = omniWriter.registerEnumValue(queryType.CH, "raycast", PxVehiclePhysXRoadGeometryQueryType::eRAYCAST);
queryType.sweepAH = omniWriter.registerEnumValue(queryType.CH, "sweep", PxVehiclePhysXRoadGeometryQueryType::eSWEEP);
queryType.noneAH = omniWriter.registerEnumValue(queryType.CH, "none", PxVehiclePhysXRoadGeometryQueryType::eNONE);
PhysXRoadGeometryQueryParams a;
a.CH = omniWriter.registerClass("PhysXRoadGeomQueryParams");
a.queryTypeAH = omniWriter.registerFlagsAttribute(a.CH, "physxQueryType", queryType.CH);
struct QueryFlag
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle staticAH;
OmniPvdAttributeHandle dynamicAH;
OmniPvdAttributeHandle preFilterAH;
OmniPvdAttributeHandle postFilterAH;
OmniPvdAttributeHandle anyHitAH;
OmniPvdAttributeHandle noBlockAH;
OmniPvdAttributeHandle batchQueryLegacyBehaviourAH;
OmniPvdAttributeHandle disableHardcodedFilterAH;
};
QueryFlag queryFlag;
queryFlag.CH = omniWriter.registerClass("PhysXRoadGeometryQueryFlag");
queryFlag.staticAH = omniWriter.registerEnumValue(queryFlag.CH, "eSTATIC", PxQueryFlag::eSTATIC);
queryFlag.dynamicAH = omniWriter.registerEnumValue(queryFlag.CH, "eDYNAMIC", PxQueryFlag::eDYNAMIC);
queryFlag.preFilterAH = omniWriter.registerEnumValue(queryFlag.CH, "ePREFILTER", PxQueryFlag::ePREFILTER);
queryFlag.postFilterAH = omniWriter.registerEnumValue(queryFlag.CH, "ePOSTFILTER", PxQueryFlag::ePOSTFILTER);
queryFlag.anyHitAH = omniWriter.registerEnumValue(queryFlag.CH, "eANY_HIT", PxQueryFlag::eANY_HIT);
queryFlag.noBlockAH = omniWriter.registerEnumValue(queryFlag.CH, "eNO_BLOCK", PxQueryFlag::eNO_BLOCK);
queryFlag.batchQueryLegacyBehaviourAH = omniWriter.registerEnumValue(queryFlag.CH, "eBATCH_QUERY_LEGACY_BEHAVIOUR", PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR);
queryFlag.disableHardcodedFilterAH = omniWriter.registerEnumValue(queryFlag.CH, "eDISABLE_HARDCODED_FILTER", PxQueryFlag::eDISABLE_HARDCODED_FILTER);
a.filterDataParams.CH = omniWriter.registerClass("PhysXRoadGeometryQueryFilterData");
a.filterDataParams.word0AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word0", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.word1AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word1", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.word2AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word2", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.word3AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word3", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.flagsAH = omniWriter.registerFlagsAttribute(a.filterDataParams.CH, "flags", queryFlag.CH);
a.defaultFilterDataAH = omniWriter.registerAttribute(a.CH, "defaultFilterData", OmniPvdDataType::eOBJECT_HANDLE, 1);
a.filterDataSetAH = omniWriter.registerUniqueListAttribute(a.CH, "filterDataSet", OmniPvdDataType::eOBJECT_HANDLE);
return a;
}
void writePhysXRoadGeometryQueryFilterData
(const PxQueryFilterData& queryFilterData,
const OmniPvdObjectHandle oh, const PhysXRoadGeometryQueryFilterData& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.word0AH, queryFilterData.data.word0);
writeUInt32Attribute(omniWriter, ch, oh, ah.word1AH, queryFilterData.data.word1);
writeUInt32Attribute(omniWriter, ch, oh, ah.word2AH, queryFilterData.data.word2);
writeUInt32Attribute(omniWriter, ch, oh, ah.word3AH, queryFilterData.data.word3);
writeFlagAttribute(omniWriter, ch, oh, ah.flagsAH, queryFilterData.flags);
}
void writePhysXRoadGeometryQueryParams
(const PxVehiclePhysXRoadGeometryQueryParams& queryParams, const PxVehicleAxleDescription& axleDesc,
const OmniPvdObjectHandle queryParamsOH, const OmniPvdObjectHandle defaultFilterDataOH, const OmniPvdObjectHandle* filterDataOHs,
const PhysXRoadGeometryQueryParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, queryParamsOH, ah.queryTypeAH, queryParams.roadGeometryQueryType);
if (defaultFilterDataOH) // TODO: test against invalid hanndle once it gets introduced
{
writePhysXRoadGeometryQueryFilterData(queryParams.defaultFilterData, defaultFilterDataOH, ah.filterDataParams,
omniWriter, ch);
}
if (queryParams.filterDataEntries)
{
for (PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
const OmniPvdObjectHandle fdOH = filterDataOHs[wheelId];
if (fdOH) // TODO: test against invalid hanndle once it gets introduced
{
writePhysXRoadGeometryQueryFilterData(queryParams.filterDataEntries[wheelId], fdOH, ah.filterDataParams,
omniWriter, ch);
}
}
}
}
PhysXSteerState registerPhysXSteerState(OmniPvdWriter& omniWriter)
{
PhysXSteerState s;
s.CH = omniWriter.registerClass("PhysXSteerState");
s.previousSteerCommandAH = omniWriter.registerAttribute(s.CH, "previousSteerCommand", OmniPvdDataType::eFLOAT32, 1);
return s;
}
void writePhysXSteerState
(const PxVehiclePhysXSteerState& steerState,
const OmniPvdObjectHandle oh, const PhysXSteerState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.previousSteerCommandAH, steerState.previousSteerCommand);
}
//////////////////////
//VEHICLE
//////////////////////
Vehicle registerVehicle(OmniPvdWriter& omniWriter)
{
Vehicle v;
v.CH = omniWriter.registerClass("Vehicle");
v.rigidBodyParamsAH = omniWriter.registerAttribute(v.CH, "rigidBodyParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.rigidBodyStateAH = omniWriter.registerAttribute(v.CH, "rigidBodyState", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.suspStateCalcParamsAH = omniWriter.registerAttribute(v.CH, "suspStateCalcParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.wheelAttachmentSetAH = omniWriter.registerUniqueListAttribute(v.CH, "wheelAttachmentSet", OmniPvdDataType::eOBJECT_HANDLE);
v.antiRollSetAH = omniWriter.registerUniqueListAttribute(v.CH, "antiRollSet", OmniPvdDataType::eOBJECT_HANDLE);
v.antiRollForceAH = omniWriter.registerAttribute(v.CH, "antiRollForce", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.brakeResponseParamsSetAH = omniWriter.registerUniqueListAttribute(v.CH, "brakeResponseParamsSet", OmniPvdDataType::eOBJECT_HANDLE);
v.steerResponseParamsAH = omniWriter.registerAttribute(v.CH, "steerResponseParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.brakeResponseStatesAH = omniWriter.registerAttribute(v.CH, "brakeResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.steerResponseStatesAH = omniWriter.registerAttribute(v.CH, "steerResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.ackermannParamsAH = omniWriter.registerAttribute(v.CH, "ackermannParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.directDrivetrainAH = omniWriter.registerAttribute(v.CH, "directDrivetrain", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.engineDriveTrainAH = omniWriter.registerAttribute(v.CH, "engineDrivetrain", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.physxWheelAttachmentSetAH = omniWriter.registerUniqueListAttribute(v.CH, "physxWheelAttachmentSet", OmniPvdDataType::eOBJECT_HANDLE);
v.physxRoadGeometryQueryParamsAH = omniWriter.registerAttribute(v.CH, "physxRoadGeomQryParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.physxRigidActorAH = omniWriter.registerAttribute(v.CH, "physxRigidActor", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.physxSteerStateAH = omniWriter.registerAttribute(v.CH, "physxSteerState", OmniPvdDataType::eOBJECT_HANDLE, 1);
return v;
}
#endif //PX_SUPPORT_OMNI_PVD
} // namespace vehicle2
} // namespace physx
/** @} */
| 89,353 |
C++
| 49.114414 | 175 | 0.80455 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdAttributeHandles.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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/pvd/PxVehiclePvdHelpers.h"
#include "VhPvdWriter.h"
/** \addtogroup vehicle2
@{
*/
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehiclePvdAttributeHandles
{
#if PX_SUPPORT_OMNI_PVD
/////////////////////
//RIGID BODY
/////////////////////////
RigidBodyParams rigidBodyParams;
RigidBodyState rigidBodyState;
/////////////////////////
//SUSP STATE CALC PARAMS
/////////////////////////
SuspStateCalcParams suspStateCalcParams;
/////////////////////////
//CONTROL ATTRIBUTES
/////////////////////////
WheelResponseParams brakeCommandResponseParams;
WheelResponseParams steerCommandResponseParams;
AckermannParams ackermannParams;
WheelResponseStates brakeCommandResponseStates;
WheelResponseStates steerCommandResponseStates;
/////////////////////////////////
//WHEEL ATTACHMENT ATTRIBUTES
/////////////////////////////////
WheelParams wheelParams;
WheelActuationState wheelActuationState;
WheelRigidBody1dState wheelRigidBody1dState;
WheelLocalPoseState wheelLocalPoseState;
RoadGeometryState roadGeomState;
SuspParams suspParams;
SuspCompParams suspCompParams;
SuspForceParams suspForceParams;
SuspState suspState;
SuspCompState suspCompState;
SuspForce suspForce;
TireParams tireParams;
TireDirectionState tireDirectionState;
TireSpeedState tireSpeedState;
TireSlipState tireSlipState;
TireStickyState tireStickyState;
TireGripState tireGripState;
TireCamberState tireCamberState;
TireForce tireForce;
WheelAttachment wheelAttachment;
///////////////////////
//ANTIROLL BARS
///////////////////////
AntiRollParams antiRollParams;
AntiRollForce antiRollForce;
///////////////////////////////////
//DIRECT DRIVETRAIN
///////////////////////////////////
DirectDriveCommandState directDriveCommandState;
DirectDriveTransmissionCommandState directDriveTransmissionCommandState;
WheelResponseParams directDriveThrottleCommandResponseParams;
DirectDriveThrottleResponseState directDriveThrottleCommandResponseState;
DirectDrivetrain directDrivetrain;
//////////////////////////////////
//ENGINE DRIVETRAIN ATTRIBUTES
//////////////////////////////////
EngineDriveCommandState engineDriveCommandState;
EngineDriveTransmissionCommandState engineDriveTransmissionCommandState;
TankDriveTransmissionCommandState tankDriveTransmissionCommandState;
ClutchResponseParams clutchCommandResponseParams;
ClutchParams clutchParams;
EngineParams engineParams;
GearboxParams gearboxParams;
AutoboxParams autoboxParams;
MultiWheelDiffParams multiwheelDiffParams;
FourWheelDiffParams fourwheelDiffParams;
TankDiffParams tankDiffParams;
ClutchResponseState clutchResponseState;
ThrottleResponseState throttleResponseState;
EngineState engineState;
GearboxState gearboxState;
AutoboxState autoboxState;
DiffState diffState;
ClutchSlipState clutchSlipState;
EngineDrivetrain engineDrivetrain;
//////////////////////////////////////
//PHYSX WHEEL ATTACHMENT INTEGRATION
//////////////////////////////////////
PhysXSuspensionLimitConstraintParams physxSuspLimitConstraintParams;
PhysXWheelShape physxWheelShape;
PhysXRoadGeomState physxRoadGeomState;
PhysXConstraintState physxConstraintState;
PhysXMaterialFriction physxMaterialFriction;
PhysXWheelAttachment physxWheelAttachment;
////////////////////
//PHYSX RIGID ACTOR
////////////////////
PhysXRoadGeometryQueryParams physxRoadGeometryQueryParams;
PhysXRigidActor physxRigidActor;
PhysXSteerState physxSteerState;
//////////////////////////////////
//VEHICLE ATTRIBUTES
//////////////////////////////////
Vehicle vehicle;
#endif
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,419 |
C
| 30.32948 | 74 | 0.731685 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdWriter.h
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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/braking/PxVehicleBrakingParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.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"
#if PX_SUPPORT_OMNI_PVD
#include "OmniPvdWriter.h"
#endif
/** \addtogroup vehicle2
@{
*/
#if PX_SUPPORT_OMNI_PVD
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
///////////////////////////////
//RIGID BODY
///////////////////////////////
struct RigidBodyParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle moiAH;
OmniPvdAttributeHandle massAH;
};
struct RigidBodyState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle posAH;
OmniPvdAttributeHandle quatAH;
OmniPvdAttributeHandle linearVelocityAH;
OmniPvdAttributeHandle angularVelocityAH;
OmniPvdAttributeHandle previousLinearVelocityAH;
OmniPvdAttributeHandle previousAngularVelocityAH;
OmniPvdAttributeHandle externalForceAH;
OmniPvdAttributeHandle externalTorqueAH;
};
RigidBodyParams registerRigidBodyParams(OmniPvdWriter& omniWriter);
RigidBodyState registerRigidBodyState(OmniPvdWriter& omniWriter);
void writeRigidBodyParams
(const PxVehicleRigidBodyParams& rbodyParams,
const OmniPvdObjectHandle oh, const RigidBodyParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeRigidBodyState
(const PxVehicleRigidBodyState& rbodyParams,
const OmniPvdObjectHandle oh, const RigidBodyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////
//CONTROL
/////////////////////////////////
struct WheelResponseParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle responseMultipliers0To3AH;
OmniPvdAttributeHandle responseMultipliers4To7AH;
OmniPvdAttributeHandle responseMultipliers8To11AH;
OmniPvdAttributeHandle responseMultipliers12To15AH;
OmniPvdAttributeHandle responseMultipliers16To19AH;
OmniPvdAttributeHandle maxResponseAH;
};
struct WheelResponseStates
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle responseStates0To3AH;
OmniPvdAttributeHandle responseStates4To7AH;
OmniPvdAttributeHandle responseStates8To11AH;
OmniPvdAttributeHandle responseStates12To15AH;
OmniPvdAttributeHandle responseStates16To19AH;
};
struct AckermannParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheelIdsAH;
OmniPvdAttributeHandle wheelBaseAH;
OmniPvdAttributeHandle trackWidthAH;
OmniPvdAttributeHandle strengthAH;
};
WheelResponseParams registerSteerResponseParams(OmniPvdWriter& omniWriter);
WheelResponseParams registerBrakeResponseParams(OmniPvdWriter& omniWriter);
WheelResponseStates registerSteerResponseStates(OmniPvdWriter& omniWriter);
WheelResponseStates registerBrakeResponseStates(OmniPvdWriter& omniWriter);
AckermannParams registerAckermannParams(OmniPvdWriter&);
void writeSteerResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSteerCommandResponseParams& steerResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeBrakeResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleBrakeCommandResponseParams& brakeResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSteerResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeBrakeResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAckermannParams
(const PxVehicleAckermannParams&,
const OmniPvdObjectHandle, const AckermannParams&, OmniPvdWriter&, OmniPvdContextHandle);
/////////////////////////////////////////////
//WHEEL ATTACHMENTS
/////////////////////////////////////////////
struct WheelParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheelRadiusAH;
OmniPvdAttributeHandle halfWidthAH;
OmniPvdAttributeHandle massAH;
OmniPvdAttributeHandle moiAH;
OmniPvdAttributeHandle dampingRateAH;
};
struct WheelActuationState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle isBrakeAppliedAH;
OmniPvdAttributeHandle isDriveAppliedAH;
};
struct WheelRigidBody1dState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rotationSpeedAH;
OmniPvdAttributeHandle correctedRotationSpeedAH;
OmniPvdAttributeHandle rotationAngleAH;
};
struct WheelLocalPoseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle posAH;
OmniPvdAttributeHandle quatAH;
};
struct RoadGeometryState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle planeAH;
OmniPvdAttributeHandle frictionAH;
OmniPvdAttributeHandle velocityAH;
OmniPvdAttributeHandle hitStateAH;
};
struct SuspParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle suspAttachmentPosAH;
OmniPvdAttributeHandle suspAttachmentQuatAH;
OmniPvdAttributeHandle suspDirAH;
OmniPvdAttributeHandle suspTravleDistAH;
OmniPvdAttributeHandle wheelAttachmentPosAH;
OmniPvdAttributeHandle wheelAttachmentQuatAH;
};
struct SuspCompParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle toeAngleAH;
OmniPvdAttributeHandle camberAngleAH;
OmniPvdAttributeHandle suspForceAppPointAH;
OmniPvdAttributeHandle tireForceAppPointAH;
};
struct SuspForceParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle stiffnessAH;
OmniPvdAttributeHandle dampingAH;
OmniPvdAttributeHandle sprungMassAH;
};
struct SuspState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle jounceAH;
OmniPvdAttributeHandle jounceSpeedAH;
OmniPvdAttributeHandle separationAH;
};
struct SuspCompState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle toeAH;
OmniPvdAttributeHandle camberAH;
OmniPvdAttributeHandle tireForceAppPointAH;
OmniPvdAttributeHandle suspForceAppPointAH;
};
struct SuspForce
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle forceAH;
OmniPvdAttributeHandle torqueAH;
OmniPvdAttributeHandle normalForceAH;
};
struct TireParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle latStiffXAH;
OmniPvdAttributeHandle latStiffYAH;
OmniPvdAttributeHandle longStiffAH;
OmniPvdAttributeHandle camberStiffAH;
OmniPvdAttributeHandle frictionVsSlipAH;
OmniPvdAttributeHandle restLoadAH;
OmniPvdAttributeHandle loadFilterAH;
};
struct TireDirectionState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngDirectionAH;
OmniPvdAttributeHandle latDirectionAH;
};
struct TireSpeedState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngSpeedAH;
OmniPvdAttributeHandle latSpeedAH;
};
struct TireSlipState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngSlipAH;
OmniPvdAttributeHandle latSlipAH;
};
struct TireGripState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle loadAH;
OmniPvdAttributeHandle frictionAH;
};
struct TireCamberState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle camberAngleAH;
};
struct TireStickyState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngStickyStateTimer;
OmniPvdAttributeHandle lngStickyStateStatus;
OmniPvdAttributeHandle latStickyStateTimer;
OmniPvdAttributeHandle latStickyStateStatus;
};
struct TireForce
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngForceAH;
OmniPvdAttributeHandle lngTorqueAH;
OmniPvdAttributeHandle latForceAH;
OmniPvdAttributeHandle latTorqueAH;
OmniPvdAttributeHandle aligningMomentAH;
OmniPvdAttributeHandle wheelTorqueAH;
};
struct WheelAttachment
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheelParamsAH;
OmniPvdAttributeHandle wheelActuationStateAH;
OmniPvdAttributeHandle wheelRigidBody1dStateAH;
OmniPvdAttributeHandle wheelLocalPoseStateAH;
OmniPvdAttributeHandle roadGeomStateAH;
OmniPvdAttributeHandle suspParamsAH;
OmniPvdAttributeHandle suspCompParamsAH;
OmniPvdAttributeHandle suspForceParamsAH;
OmniPvdAttributeHandle suspStateAH;
OmniPvdAttributeHandle suspCompStateAH;
OmniPvdAttributeHandle suspForceAH;
OmniPvdAttributeHandle tireParamsAH;
OmniPvdAttributeHandle tireDirectionStateAH;
OmniPvdAttributeHandle tireSpeedStateAH;
OmniPvdAttributeHandle tireSlipStateAH;
OmniPvdAttributeHandle tireStickyStateAH;
OmniPvdAttributeHandle tireGripStateAH;
OmniPvdAttributeHandle tireCamberStateAH;
OmniPvdAttributeHandle tireForceAH;
};
WheelParams registerWheelParams(OmniPvdWriter& omniWriter);
WheelActuationState registerWheelActuationState(OmniPvdWriter& omniWriter);
WheelRigidBody1dState registerWheelRigidBody1dState(OmniPvdWriter& omniWriter);
WheelLocalPoseState registerWheelLocalPoseState(OmniPvdWriter& omniWriter);
RoadGeometryState registerRoadGeomState(OmniPvdWriter& omniWriter);
SuspParams registerSuspParams(OmniPvdWriter& omniWriter);
SuspCompParams registerSuspComplianceParams(OmniPvdWriter& omniWriter);
SuspForceParams registerSuspForceParams(OmniPvdWriter& omniWriter);
SuspState registerSuspState(OmniPvdWriter& omniWriter);
SuspCompState registerSuspComplianceState(OmniPvdWriter& omniWriter);
SuspForce registerSuspForce(OmniPvdWriter& omniWriter);
TireParams registerTireParams(OmniPvdWriter& omniWriter);
TireDirectionState registerTireDirectionState(OmniPvdWriter& omniWriter);
TireSpeedState registerTireSpeedState(OmniPvdWriter& omniWriter);
TireSlipState registerTireSlipState(OmniPvdWriter& omniWriter);
TireStickyState registerTireStickyState(OmniPvdWriter& omniWriter);
TireGripState registerTireGripState(OmniPvdWriter& omniWriter);
TireCamberState registerTireCamberState(OmniPvdWriter& omniWriter);
TireForce registerTireForce(OmniPvdWriter& omniWriter);
WheelAttachment registerWheelAttachment(OmniPvdWriter& omniWriter);
void writeWheelParams
(const PxVehicleWheelParams& params,
const OmniPvdObjectHandle oh, const WheelParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeWheelActuationState
(const PxVehicleWheelActuationState& actState,
const OmniPvdObjectHandle oh, const WheelActuationState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeWheelRigidBody1dState
(const PxVehicleWheelRigidBody1dState& rigidBodyState,
const OmniPvdObjectHandle oh, const WheelRigidBody1dState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeWheelLocalPoseState
(const PxVehicleWheelLocalPose& pose,
const OmniPvdObjectHandle oh, const WheelLocalPoseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeRoadGeomState
(const PxVehicleRoadGeometryState& roadGeometryState,
const OmniPvdObjectHandle oh, const RoadGeometryState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspParams
(const PxVehicleSuspensionParams& suspParams,
const OmniPvdObjectHandle oh, const SuspParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspComplianceParams
(const PxVehicleSuspensionComplianceParams& compParams,
const OmniPvdObjectHandle oh, const SuspCompParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspForceParams
(const PxVehicleSuspensionForceParams& forceParams,
const OmniPvdObjectHandle oh, const SuspForceParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspState
(const PxVehicleSuspensionState& suspState,
const OmniPvdObjectHandle oh, const SuspState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspComplianceState
(const PxVehicleSuspensionComplianceState& suspCompState,
const OmniPvdObjectHandle oh, const SuspCompState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspForce
(const PxVehicleSuspensionForce& suspForce,
const OmniPvdObjectHandle oh, const SuspForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireParams
(const PxVehicleTireForceParams& tireParams,
const OmniPvdObjectHandle oh, const TireParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireDirectionState
(const PxVehicleTireDirectionState& tireDirState,
const OmniPvdObjectHandle oh, const TireDirectionState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireSpeedState
(const PxVehicleTireSpeedState& tireSpeedState,
const OmniPvdObjectHandle oh, const TireSpeedState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireSlipState
(const PxVehicleTireSlipState& tireSlipState,
const OmniPvdObjectHandle oh, const TireSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireStickyState
(const PxVehicleTireStickyState& tireStickyState,
const OmniPvdObjectHandle oh, const TireStickyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireGripState
(const PxVehicleTireGripState& tireGripState,
const OmniPvdObjectHandle oh, const TireGripState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireCamberState
(const PxVehicleTireCamberAngleState& tireCamberState,
const OmniPvdObjectHandle oh, const TireCamberState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireForce
(const PxVehicleTireForce& tireForce,
const OmniPvdObjectHandle oh, const TireForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////////////
//ANTIROLL
/////////////////////////////////////////
struct AntiRollParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheel0AH;
OmniPvdAttributeHandle wheel1AH;
OmniPvdAttributeHandle stiffnessAH;
};
struct AntiRollForce
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueAH;
};
AntiRollParams registerAntiRollParams(OmniPvdWriter& omniWriter);
AntiRollForce registerAntiRollForce(OmniPvdWriter& omniWriter);
void writeAntiRollParams
(const PxVehicleAntiRollForceParams& antiRollParams,
const OmniPvdObjectHandle oh, const AntiRollParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAntiRollForce
(const PxVehicleAntiRollTorque& antiRollForce,
const OmniPvdObjectHandle oh, const AntiRollForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
////////////////////////////////////////
//SUSPENSION STATE CALCULATION
////////////////////////////////////////
struct SuspStateCalcParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle calcTypeAH;
OmniPvdAttributeHandle limitExpansionValAH;
};
SuspStateCalcParams registerSuspStateCalcParams(OmniPvdWriter& omniWriter);
void writeSuspStateCalcParams
(const PxVehicleSuspensionStateCalculationParams& suspStateCalcParams,
const OmniPvdObjectHandle oh, const SuspStateCalcParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////////////
//DIRECT DRIVETRAIN
////////////////////////////////////////
struct DirectDriveCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle brakesAH;
OmniPvdAttributeHandle throttleAH;
OmniPvdAttributeHandle steerAH;
};
struct DirectDriveTransmissionCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle gearAH;
};
struct DirectDriveThrottleResponseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle states0To3AH;
OmniPvdAttributeHandle states4To7AH;
OmniPvdAttributeHandle states8To11AH;
OmniPvdAttributeHandle states12To15AH;
OmniPvdAttributeHandle states16To19AH;
};
struct DirectDrivetrain
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle throttleResponseParamsAH;
OmniPvdAttributeHandle commandStateAH;
OmniPvdAttributeHandle transmissionCommandStateAH;
OmniPvdAttributeHandle throttleResponseStateAH;
};
WheelResponseParams registerDirectDriveThrottleResponseParams(OmniPvdWriter& omniWriter);
DirectDriveCommandState registerDirectDriveCommandState(OmniPvdWriter& omniWriter);
DirectDriveTransmissionCommandState registerDirectDriveTransmissionCommandState(OmniPvdWriter& omniWriter);
DirectDriveThrottleResponseState registerDirectDriveThrottleResponseState(OmniPvdWriter& omniWriter);
DirectDrivetrain registerDirectDrivetrain(OmniPvdWriter& omniWriter);
void writeDirectDriveThrottleResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleDirectDriveThrottleCommandResponseParams& directDriveThrottleResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDirectDriveCommandState
(const PxVehicleCommandState& commands,
const OmniPvdObjectHandle oh, const DirectDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDirectDriveTransmissionCommandState
(const PxVehicleDirectDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const DirectDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDirectDriveThrottleResponseState
(const PxVehicleAxleDescription& axleDesc, const PxVehicleArrayData<PxReal>& throttleResponseState,
const OmniPvdObjectHandle oh, const DirectDriveThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////////////
//ENGINE DRIVETRAIN
////////////////////////////////////////
struct EngineDriveCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle brakesAH;
OmniPvdAttributeHandle throttleAH;
OmniPvdAttributeHandle steerAH;
};
struct EngineDriveTransmissionCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle gearAH;
OmniPvdAttributeHandle clutchAH;
};
struct TankDriveTransmissionCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle thrustsAH;
};
struct ClutchResponseParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle maxResponseAH;
};
struct ClutchParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle accuracyAH;
OmniPvdAttributeHandle iterationsAH;
};
struct EngineParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueCurveAH;
OmniPvdAttributeHandle moiAH;
OmniPvdAttributeHandle peakTorqueAH;
OmniPvdAttributeHandle idleOmegaAH;
OmniPvdAttributeHandle maxOmegaAH;
OmniPvdAttributeHandle dampingRateFullThrottleAH;
OmniPvdAttributeHandle dampingRateZeroThrottleClutchEngagedAH;
OmniPvdAttributeHandle dampingRateZeroThrottleClutchDisengagedAH;
};
struct GearboxParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle ratiosAH;
OmniPvdAttributeHandle nbRatiosAH;
OmniPvdAttributeHandle neutralGearAH;
OmniPvdAttributeHandle finalRatioAH;
OmniPvdAttributeHandle switchTimeAH;
};
struct AutoboxParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle upRatiosAH;
OmniPvdAttributeHandle downRatiosAH;
OmniPvdAttributeHandle latencyAH;
};
struct MultiWheelDiffParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueRatios0To3AH;
OmniPvdAttributeHandle torqueRatios4To7AH;
OmniPvdAttributeHandle torqueRatios8To11AH;
OmniPvdAttributeHandle torqueRatios12To15AH;
OmniPvdAttributeHandle torqueRatios16To19AH;
OmniPvdAttributeHandle aveWheelSpeedRatios0To3AH;
OmniPvdAttributeHandle aveWheelSpeedRatios4To7AH;
OmniPvdAttributeHandle aveWheelSpeedRatios8To11AH;
OmniPvdAttributeHandle aveWheelSpeedRatios12To15AH;
OmniPvdAttributeHandle aveWheelSpeedRatios16To19AH;
};
struct FourWheelDiffParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle frontWheelsAH;
OmniPvdAttributeHandle rearWheelsAH;
OmniPvdAttributeHandle frontBiasAH;
OmniPvdAttributeHandle frontTargetAH;
OmniPvdAttributeHandle rearBiasAH;
OmniPvdAttributeHandle rearTargetAH;
OmniPvdAttributeHandle centreBiasAH;
OmniPvdAttributeHandle centreTargetAH;
};
struct TankDiffParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle nbTracksAH;
OmniPvdAttributeHandle thrustIdPerTrackAH;
OmniPvdAttributeHandle nbWheelsPerTrackAH;
OmniPvdAttributeHandle trackToWheelIdsAH;
OmniPvdAttributeHandle wheelIdsInTrackOrderAH;
};
struct ClutchResponseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle normalisedResponseAH;
OmniPvdAttributeHandle responseAH;
};
struct ThrottleResponseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle responseAH;
};
struct EngineState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rotationSpeedAH;
};
struct GearboxState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle currentGearAH;
OmniPvdAttributeHandle targetGearAH;
OmniPvdAttributeHandle switchTimeAH;
};
struct AutoboxState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle timeSinceLastShiftAH;
OmniPvdAttributeHandle activeAutoboxGearShiftAH;
};
struct DiffState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueRatios0To3AH;
OmniPvdAttributeHandle torqueRatios4To7AH;
OmniPvdAttributeHandle torqueRatios8To11AH;
OmniPvdAttributeHandle torqueRatios12To15AH;
OmniPvdAttributeHandle torqueRatios16To19AH;
OmniPvdAttributeHandle aveWheelSpeedRatios0To3AH;
OmniPvdAttributeHandle aveWheelSpeedRatios4To7AH;
OmniPvdAttributeHandle aveWheelSpeedRatios8To11AH;
OmniPvdAttributeHandle aveWheelSpeedRatios12To15AH;
OmniPvdAttributeHandle aveWheelSpeedRatios16To19AH;
};
struct ClutchSlipState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle slipAH;
};
struct EngineDrivetrain
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle commandStateAH;
OmniPvdAttributeHandle transmissionCommandStateAH;
OmniPvdAttributeHandle clutchResponseParamsAH;
OmniPvdAttributeHandle clutchParamsAH;
OmniPvdAttributeHandle engineParamsAH;
OmniPvdAttributeHandle gearboxParamsAH;
OmniPvdAttributeHandle autoboxParamsAH;
OmniPvdAttributeHandle differentialParamsAH;
OmniPvdAttributeHandle clutchResponseStateAH;
OmniPvdAttributeHandle throttleResponseStateAH;
OmniPvdAttributeHandle engineStateAH;
OmniPvdAttributeHandle gearboxStateAH;
OmniPvdAttributeHandle autoboxStateAH;
OmniPvdAttributeHandle diffStateAH;
OmniPvdAttributeHandle clutchSlipStateAH;
};
EngineDriveCommandState registerEngineDriveCommandState(OmniPvdWriter& omniWriter);
EngineDriveTransmissionCommandState registerEngineDriveTransmissionCommandState(OmniPvdWriter& omniWriter);
TankDriveTransmissionCommandState registerTankDriveTransmissionCommandState(OmniPvdWriter&, OmniPvdClassHandle baseClass);
ClutchResponseParams registerClutchResponseParams(OmniPvdWriter& omniWriter);
ClutchParams registerClutchParams(OmniPvdWriter& omniWriter);
EngineParams registerEngineParams(OmniPvdWriter& omniWriter);
GearboxParams registerGearboxParams(OmniPvdWriter& omniWriter);
AutoboxParams registerAutoboxParams(OmniPvdWriter& omniWriter);
MultiWheelDiffParams registerMultiWheelDiffParams(OmniPvdWriter& omniWriter);
FourWheelDiffParams registerFourWheelDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass);
TankDiffParams registerTankDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass);
//TankDiffParams registerTankDiffParams(OmniPvdWriter& omniWriter);
ClutchResponseState registerClutchResponseState(OmniPvdWriter& omniWriter);
ThrottleResponseState registerThrottleResponseState(OmniPvdWriter& omniWriter);
EngineState registerEngineState(OmniPvdWriter& omniWriter);
GearboxState registerGearboxState(OmniPvdWriter& omniWriter);
AutoboxState registerAutoboxState(OmniPvdWriter& omniWriter);
DiffState registerDiffState(OmniPvdWriter& omniWriter);
ClutchSlipState registerClutchSlipState(OmniPvdWriter& omniWriter);
EngineDrivetrain registerEngineDrivetrain(OmniPvdWriter& omniWriter);
void writeEngineDriveCommandState
(const PxVehicleCommandState& commandState,
const OmniPvdObjectHandle oh, const EngineDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeEngineDriveTransmissionCommandState
(const PxVehicleEngineDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const EngineDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTankDriveTransmissionCommandState
(const PxVehicleTankDriveTransmissionCommandState&, const OmniPvdObjectHandle,
const EngineDriveTransmissionCommandState&, const TankDriveTransmissionCommandState&,
OmniPvdWriter&, OmniPvdContextHandle);
void writeClutchResponseParams
(const PxVehicleClutchCommandResponseParams& clutchResponseParams,
const OmniPvdObjectHandle oh, const ClutchResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeClutchParams
(const PxVehicleClutchParams& clutchParams,
const OmniPvdObjectHandle oh, const ClutchParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeEngineParams
(const PxVehicleEngineParams& engineParams,
const OmniPvdObjectHandle oh, const EngineParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeGearboxParams
(const PxVehicleGearboxParams& gearboxParams,
const OmniPvdObjectHandle oh, const GearboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAutoboxParams
(const PxVehicleAutoboxParams& gearboxParams,
const OmniPvdObjectHandle oh, const AutoboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeMultiWheelDiffParams
(const PxVehicleMultiWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeFourWheelDiffParams
(const PxVehicleFourWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams&, const FourWheelDiffParams& ah,
OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTankDiffParams
(const PxVehicleTankDriveDifferentialParams&,
const OmniPvdObjectHandle, const MultiWheelDiffParams&, const TankDiffParams&,
OmniPvdWriter&, OmniPvdContextHandle);
void writeClutchResponseState
(const PxVehicleClutchCommandResponseState& clutchResponseState,
const OmniPvdObjectHandle oh, const ClutchResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeThrottleResponseState
(const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState,
const OmniPvdObjectHandle oh, const ThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeEngineState
(const PxVehicleEngineState& engineState,
const OmniPvdObjectHandle oh, const EngineState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeGearboxState
(const PxVehicleGearboxState& gearboxState,
const OmniPvdObjectHandle oh, const GearboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAutoboxState
(const PxVehicleAutoboxState& gearboxState,
const OmniPvdObjectHandle oh, const AutoboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDiffState
(const PxVehicleDifferentialState& diffState,
const OmniPvdObjectHandle oh, const DiffState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeClutchSlipState
(const PxVehicleClutchSlipState& clutchSlipState,
const OmniPvdObjectHandle oh, const ClutchSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
///////////////////////////////
//WHEEL ATTACHMENT PHYSX INTEGRATION
///////////////////////////////
struct PhysXSuspensionLimitConstraintParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle restitutionAH;
OmniPvdAttributeHandle directionForSuspensionLimitConstraintAH;
};
struct PhysXWheelShape
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle shapePtrAH;
};
struct PhysXRoadGeomState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle hitActorPtrAH;
OmniPvdAttributeHandle hitShapePtrAH;
OmniPvdAttributeHandle hitMaterialPtrAH;
OmniPvdAttributeHandle hitPositionAH;
};
struct PhysXConstraintState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle tireLongActiveStatusAH;
OmniPvdAttributeHandle tireLongLinearAH;
OmniPvdAttributeHandle tireLongAngularAH;
OmniPvdAttributeHandle tireLongDampingAH;
OmniPvdAttributeHandle tireLatActiveStatusAH;
OmniPvdAttributeHandle tireLatLinearAH;
OmniPvdAttributeHandle tireLatAngularAH;
OmniPvdAttributeHandle tireLatDampingAH;
OmniPvdAttributeHandle suspActiveStatusAH;
OmniPvdAttributeHandle suspLinearAH;
OmniPvdAttributeHandle suspAngularAH;
OmniPvdAttributeHandle suspGeometricErrorAH;
OmniPvdAttributeHandle suspRestitutionAH;
};
struct PhysXWheelAttachment
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle physxWeelShapeAH;
OmniPvdAttributeHandle physxConstraintParamsAH;
OmniPvdAttributeHandle physxRoadGeometryStateAH;
OmniPvdAttributeHandle physxConstraintStateAH;
OmniPvdAttributeHandle physxMaterialFrictionSetAH;
};
struct PhysXMaterialFriction
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle frictionAH;
OmniPvdAttributeHandle materialPtrAH;
};
PhysXSuspensionLimitConstraintParams registerSuspLimitConstraintParams(OmniPvdWriter& omniWriter);
PhysXWheelShape registerPhysXWheelShape(OmniPvdWriter& omniWriter);
PhysXRoadGeomState registerPhysXRoadGeomState(OmniPvdWriter& omniWriter);
PhysXConstraintState registerPhysXConstraintState(OmniPvdWriter& omniWriter);
PhysXWheelAttachment registerPhysXWheelAttachment(OmniPvdWriter& omniWriter);
PhysXMaterialFriction registerPhysXMaterialFriction(OmniPvdWriter& omniWriter);
void writePhysXSuspLimitConstraintParams
(const PxVehiclePhysXSuspensionLimitConstraintParams& params,
const OmniPvdObjectHandle oh, const PhysXSuspensionLimitConstraintParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXWheelShape
(const PxShape* wheelShape,
const OmniPvdObjectHandle oh, const PhysXWheelShape& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXRoadGeomState
(const PxVehiclePhysXRoadGeometryQueryState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXRoadGeomState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXConstraintState
(const PxVehiclePhysXConstraintState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXConstraintState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXMaterialFriction
(const PxVehiclePhysXMaterialFriction& materialFriction,
const OmniPvdObjectHandle oh, const PhysXMaterialFriction& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
//////////////////////////////
//PHYSX RIGID ACTOR
//////////////////////////////
struct PhysXRoadGeometryQueryFilterData
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle word0AH;
OmniPvdAttributeHandle word1AH;
OmniPvdAttributeHandle word2AH;
OmniPvdAttributeHandle word3AH;
OmniPvdAttributeHandle flagsAH;
};
struct PhysXRoadGeometryQueryParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle queryTypeAH;
PhysXRoadGeometryQueryFilterData filterDataParams;
OmniPvdAttributeHandle defaultFilterDataAH;
OmniPvdAttributeHandle filterDataSetAH;
};
struct PhysXRigidActor
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rigidActorAH;
};
struct PhysXSteerState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle previousSteerCommandAH;
};
PhysXRoadGeometryQueryParams registerPhysXRoadGeometryQueryParams(OmniPvdWriter& omniWriter);
PhysXRigidActor registerPhysXRigidActor(OmniPvdWriter& omniWriter);
PhysXSteerState registerPhysXSteerState(OmniPvdWriter& omniWriter);
void writePhysXRigidActor
(const PxRigidActor* actor,
const OmniPvdObjectHandle oh, const PhysXRigidActor& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXRoadGeometryQueryFilterData
(const PxQueryFilterData&,
const OmniPvdObjectHandle, const PhysXRoadGeometryQueryFilterData&, OmniPvdWriter&, OmniPvdContextHandle);
void writePhysXRoadGeometryQueryParams
(const PxVehiclePhysXRoadGeometryQueryParams&, const PxVehicleAxleDescription& axleDesc,
const OmniPvdObjectHandle queryParamsOH, const OmniPvdObjectHandle defaultFilterDataOH, const OmniPvdObjectHandle* filterDataOHs,
const PhysXRoadGeometryQueryParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXSteerState
(const PxVehiclePhysXSteerState&,
const OmniPvdObjectHandle, const PhysXSteerState&, OmniPvdWriter&, OmniPvdContextHandle);
//////////////////////////////
//VEHICLE
//////////////////////////////
struct Vehicle
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rigidBodyParamsAH;
OmniPvdAttributeHandle rigidBodyStateAH;
OmniPvdAttributeHandle suspStateCalcParamsAH;
OmniPvdAttributeHandle brakeResponseParamsSetAH;
OmniPvdAttributeHandle steerResponseParamsAH;
OmniPvdAttributeHandle brakeResponseStatesAH;
OmniPvdAttributeHandle steerResponseStatesAH;
OmniPvdAttributeHandle ackermannParamsAH;
OmniPvdAttributeHandle wheelAttachmentSetAH;
OmniPvdAttributeHandle antiRollSetAH;
OmniPvdAttributeHandle antiRollForceAH;
OmniPvdAttributeHandle directDrivetrainAH;
OmniPvdAttributeHandle engineDriveTrainAH;
OmniPvdAttributeHandle physxWheelAttachmentSetAH;
OmniPvdAttributeHandle physxRoadGeometryQueryParamsAH;
OmniPvdAttributeHandle physxRigidActorAH;
OmniPvdAttributeHandle physxSteerStateAH;
};
Vehicle registerVehicle(OmniPvdWriter& omniWriter);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
#endif //PX_SUPPORT_OMNI_PVD
/** @} */
| 35,223 |
C
| 32.901829 | 131 | 0.845385 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdHelpers.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/pvd/PxVehiclePvdHelpers.h"
#include "foundation/PxAllocatorCallback.h"
#include "VhPvdAttributeHandles.h"
#include "VhPvdObjectHandles.h"
namespace physx
{
namespace vehicle2
{
#if PX_SUPPORT_OMNI_PVD
///////////////////////////////
//ATTRIBUTE REGISTRATION
///////////////////////////////
PxVehiclePvdAttributeHandles* PxVehiclePvdAttributesCreate(PxAllocatorCallback& allocator, OmniPvdWriter& omniWriter)
{
PxVehiclePvdAttributeHandles* attributeHandles =
reinterpret_cast<PxVehiclePvdAttributeHandles*>(
allocator.allocate(sizeof(PxVehiclePvdAttributeHandles), "PxVehiclePvdAttributeHandles", PX_FL));
PxMemZero(attributeHandles, sizeof(PxVehiclePvdAttributeHandles));
//Rigid body
attributeHandles->rigidBodyParams = registerRigidBodyParams(omniWriter);
attributeHandles->rigidBodyState = registerRigidBodyState(omniWriter);
//Susp state calc params.
attributeHandles->suspStateCalcParams = registerSuspStateCalcParams(omniWriter);
//Controls
attributeHandles->steerCommandResponseParams = registerSteerResponseParams(omniWriter);
attributeHandles->brakeCommandResponseParams = registerBrakeResponseParams(omniWriter);
attributeHandles->steerCommandResponseStates = registerSteerResponseStates(omniWriter);
attributeHandles->brakeCommandResponseStates = registerBrakeResponseStates(omniWriter);
attributeHandles->ackermannParams = registerAckermannParams(omniWriter);
//Wheel attachment
attributeHandles->wheelParams = registerWheelParams(omniWriter);
attributeHandles->wheelActuationState = registerWheelActuationState(omniWriter);
attributeHandles->wheelRigidBody1dState = registerWheelRigidBody1dState(omniWriter);
attributeHandles->wheelLocalPoseState = registerWheelLocalPoseState(omniWriter);
attributeHandles->roadGeomState = registerRoadGeomState(omniWriter);
attributeHandles->suspParams = registerSuspParams(omniWriter);
attributeHandles->suspCompParams = registerSuspComplianceParams(omniWriter);
attributeHandles->suspForceParams = registerSuspForceParams(omniWriter);
attributeHandles->suspState = registerSuspState(omniWriter);
attributeHandles->suspCompState = registerSuspComplianceState(omniWriter);
attributeHandles->suspForce = registerSuspForce(omniWriter);
attributeHandles->tireParams = registerTireParams(omniWriter);
attributeHandles->tireDirectionState = registerTireDirectionState(omniWriter);
attributeHandles->tireSpeedState = registerTireSpeedState(omniWriter);
attributeHandles->tireSlipState = registerTireSlipState(omniWriter);
attributeHandles->tireStickyState = registerTireStickyState(omniWriter);
attributeHandles->tireGripState = registerTireGripState(omniWriter);
attributeHandles->tireCamberState = registerTireCamberState(omniWriter);
attributeHandles->tireForce = registerTireForce(omniWriter);
attributeHandles->wheelAttachment = registerWheelAttachment(omniWriter);
//Antiroll
attributeHandles->antiRollParams = registerAntiRollParams(omniWriter);
attributeHandles->antiRollForce = registerAntiRollForce(omniWriter);
//Direct drivetrain
attributeHandles->directDriveThrottleCommandResponseParams = registerDirectDriveThrottleResponseParams(omniWriter);
attributeHandles->directDriveCommandState = registerDirectDriveCommandState(omniWriter);
attributeHandles->directDriveTransmissionCommandState = registerDirectDriveTransmissionCommandState(omniWriter);
attributeHandles->directDriveThrottleCommandResponseState = registerDirectDriveThrottleResponseState(omniWriter);
attributeHandles->directDrivetrain = registerDirectDrivetrain(omniWriter);
//Engine drivetrain
attributeHandles->engineDriveCommandState = registerEngineDriveCommandState(omniWriter);
attributeHandles->engineDriveTransmissionCommandState = registerEngineDriveTransmissionCommandState(omniWriter);
attributeHandles->tankDriveTransmissionCommandState = registerTankDriveTransmissionCommandState(omniWriter,
attributeHandles->engineDriveTransmissionCommandState.CH);
attributeHandles->clutchCommandResponseParams = registerClutchResponseParams(omniWriter);
attributeHandles->clutchParams = registerClutchParams(omniWriter);
attributeHandles->engineParams = registerEngineParams(omniWriter);
attributeHandles->gearboxParams = registerGearboxParams(omniWriter);
attributeHandles->autoboxParams = registerAutoboxParams(omniWriter);
attributeHandles->multiwheelDiffParams = registerMultiWheelDiffParams(omniWriter);
attributeHandles->fourwheelDiffParams = registerFourWheelDiffParams(omniWriter, attributeHandles->multiwheelDiffParams.CH);
attributeHandles->tankDiffParams = registerTankDiffParams(omniWriter, attributeHandles->multiwheelDiffParams.CH);
attributeHandles->clutchResponseState = registerClutchResponseState(omniWriter);
attributeHandles->throttleResponseState = registerThrottleResponseState(omniWriter);
attributeHandles->engineState = registerEngineState(omniWriter);
attributeHandles->gearboxState = registerGearboxState(omniWriter);
attributeHandles->autoboxState = registerAutoboxState(omniWriter);
attributeHandles->diffState = registerDiffState(omniWriter);
attributeHandles->clutchSlipState = registerClutchSlipState(omniWriter);
attributeHandles->engineDrivetrain = registerEngineDrivetrain(omniWriter);
//Physx wheel attachment
attributeHandles->physxSuspLimitConstraintParams = registerSuspLimitConstraintParams(omniWriter);
attributeHandles->physxWheelShape = registerPhysXWheelShape(omniWriter);
attributeHandles->physxRoadGeomState = registerPhysXRoadGeomState(omniWriter);
attributeHandles->physxConstraintState = registerPhysXConstraintState(omniWriter);
attributeHandles->physxWheelAttachment = registerPhysXWheelAttachment(omniWriter);
attributeHandles->physxMaterialFriction = registerPhysXMaterialFriction(omniWriter);
//Physx rigid actor
attributeHandles->physxRoadGeometryQueryParams = registerPhysXRoadGeometryQueryParams(omniWriter);
attributeHandles->physxRigidActor = registerPhysXRigidActor(omniWriter);
attributeHandles->physxSteerState = registerPhysXSteerState(omniWriter);
//Vehicle
attributeHandles->vehicle = registerVehicle(omniWriter);
return attributeHandles;
}
///////////////////////////////
//ATTRIBUTE DESTRUCTION
///////////////////////////////
void PxVehiclePvdAttributesRelease(PxAllocatorCallback& allocator, PxVehiclePvdAttributeHandles& attributeHandles)
{
allocator.deallocate(&attributeHandles);
}
////////////////////////////////////////
//OBJECT REGISTRATION
////////////////////////////////////////
PxVehiclePvdObjectHandles* PxVehiclePvdObjectCreate
(const PxU32 nbWheels, const PxU32 nbAntirolls, const PxU32 maxNbPhysXMaterialFrictions,
const OmniPvdContextHandle contextHandle,
PxAllocatorCallback& allocator)
{
const PxU32 byteSize =
sizeof(PxVehiclePvdObjectHandles) +
sizeof(OmniPvdObjectHandle)*nbWheels*(
1 + //OmniPvdObjectHandle* wheelAttachmentOHs;
1 + //OmniPvdObjectHandle* wheelParamsOHs;
1 + //OmniPvdObjectHandle* wheelActuationStateOHs;
1 + //OmniPvdObjectHandle* wheelRigidBody1dStateOHs;
1 + //OmniPvdObjectHandle* wheelLocalPoseStateOHs;
1 + //OmniPvdObjectHandle* roadGeomStateOHs;
1 + //OmniPvdObjectHandle* suspParamsOHs;
1 + //OmniPvdObjectHandle* suspCompParamsOHs;
1 + //OmniPvdObjectHandle* suspForceParamsOHs;
1 + //OmniPvdObjectHandle* suspStateOHs;
1 + //OmniPvdObjectHandle* suspCompStateOHs;
1 + //OmniPvdObjectHandle* suspForceOHs;
1 + //OmniPvdObjectHandle* tireParamsOHs;
1 + //OmniPvdObjectHandle* tireDirectionStateOHs;
1 + //OmniPvdObjectHandle* tireSpeedStateOHs;
1 + //OmniPvdObjectHandle* tireSlipStateOHs;
1 + //OmniPvdObjectHandle* tireStickyStateOHs;
1 + //OmniPvdObjectHandle* tireGripStateOHs;
1 + //OmniPvdObjectHandle* tireCamberStateOHs;
1 + //OmniPvdObjectHandle* tireForceOHs;
1 + //OmniPvdObjectHandle* physxWheelAttachmentOHs;
1 + //OmniPvdObjectHandle* physxWheelShapeOHs;
1 + //OmniPvdObjectHandle* physxConstraintParamOHs;
1 + //OmniPvdObjectHandle* physxConstraintStateOHs;
1 + //OmniPvdObjectHandle* physxRoadGeomStateOHs;
1 + //OmniPvdObjectHandle* physxMaterialFrictionSetOHs;
maxNbPhysXMaterialFrictions + //OmniPvdObjectHandle* physxMaterialFrictionOHs;
1) + //OmniPvdObjectHandle* physxRoadGeomQueryFilterDataOHs;
sizeof(OmniPvdObjectHandle)*nbAntirolls*(
1); //OmniPvdObjectHandle* antiRollParamOHs
PxU8* buffer = reinterpret_cast<PxU8*>(allocator.allocate(byteSize, "PxVehiclePvdObjectHandles", PX_FL));
#if PX_ENABLE_ASSERTS
PxU8* start = buffer;
#endif
PxMemZero(buffer, byteSize);
PxVehiclePvdObjectHandles* objectHandles = reinterpret_cast<PxVehiclePvdObjectHandles*>(buffer);
buffer += sizeof(PxVehiclePvdObjectHandles);
if(nbWheels != 0)
{
objectHandles->wheelAttachmentOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelActuationStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelRigidBody1dStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelLocalPoseStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->roadGeomStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspCompParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspForceParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspCompStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspForceOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireDirectionStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireSpeedStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireSlipStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireStickyStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireGripStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireCamberStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireForceOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxWheelAttachmentOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxConstraintParamOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxWheelShapeOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxConstraintStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxRoadGeomStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
if(maxNbPhysXMaterialFrictions != 0)
{
objectHandles->physxMaterialFrictionSetOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxMaterialFrictionOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels*maxNbPhysXMaterialFrictions;
}
objectHandles->physxRoadGeomQueryFilterDataOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
}
if(nbAntirolls != 0)
{
objectHandles->antiRollParamOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbAntirolls;
}
objectHandles->nbWheels = nbWheels;
objectHandles->nbPhysXMaterialFrictions = maxNbPhysXMaterialFrictions;
objectHandles->nbAntirolls = nbAntirolls;
objectHandles->contextHandle = contextHandle;
PX_ASSERT((start + byteSize) == buffer);
return objectHandles;
}
////////////////////////////////////
//OBJECT DESTRUCTION
////////////////////////////////////
PX_FORCE_INLINE void destroyObject
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh)
{
// note: "0" needs to be replaced with a marker for invalid object handle as soon as PVD
// provides it (and PxVehiclePvdObjectCreate needs to initialize accordingly or
// compile time assert that the value is 0 for now)
if(oh != 0)
omniWriter.destroyObject(ch, oh);
}
void PxVehiclePvdObjectRelease
(OmniPvdWriter& ow, PxAllocatorCallback& allocator, PxVehiclePvdObjectHandles& oh)
{
const OmniPvdContextHandle ch = oh.contextHandle;
//rigid body
destroyObject(ow, ch, oh.rigidBodyParamsOH);
destroyObject(ow, ch, oh.rigidBodyStateOH);
//susp state calc params
destroyObject(ow, ch, oh.suspStateCalcParamsOH);
//controls
for(PxU32 i = 0; i < 2; i++)
{
destroyObject(ow, ch, oh.brakeResponseParamOHs[i]);
}
destroyObject(ow, ch, oh.steerResponseParamsOH);
destroyObject(ow, ch, oh.brakeResponseStateOH);
destroyObject(ow, ch, oh.steerResponseStateOH);
destroyObject(ow, ch, oh.ackermannParamsOH);
//Wheel attachments
for(PxU32 i = 0; i < oh.nbWheels; i++)
{
destroyObject(ow, ch, oh.wheelParamsOHs[i]);
destroyObject(ow, ch, oh.wheelActuationStateOHs[i]);
destroyObject(ow, ch, oh.wheelRigidBody1dStateOHs[i]);
destroyObject(ow, ch, oh.wheelLocalPoseStateOHs[i]);
destroyObject(ow, ch, oh.suspParamsOHs[i]);
destroyObject(ow, ch, oh.suspCompParamsOHs[i]);
destroyObject(ow, ch, oh.suspForceParamsOHs[i]);
destroyObject(ow, ch, oh.suspStateOHs[i]);
destroyObject(ow, ch, oh.suspCompStateOHs[i]);
destroyObject(ow, ch, oh.suspForceOHs[i]);
destroyObject(ow, ch, oh.tireParamsOHs[i]);
destroyObject(ow, ch, oh.tireDirectionStateOHs[i]);
destroyObject(ow, ch, oh.tireSpeedStateOHs[i]);
destroyObject(ow, ch, oh.tireSlipStateOHs[i]);
destroyObject(ow, ch, oh.tireStickyStateOHs[i]);
destroyObject(ow, ch, oh.tireGripStateOHs[i]);
destroyObject(ow, ch, oh.tireCamberStateOHs[i]);
destroyObject(ow, ch, oh.tireForceOHs[i]);
destroyObject(ow, ch, oh.wheelAttachmentOHs[i]);
}
//Antiroll
for(PxU32 i = 0; i < oh.nbAntirolls; i++)
{
destroyObject(ow, ch, oh.antiRollParamOHs[i]);
}
destroyObject(ow, ch, oh.antiRollTorqueOH);
//direct drive
destroyObject(ow, ch, oh.directDriveCommandStateOH);
destroyObject(ow, ch, oh.directDriveTransmissionCommandStateOH);
destroyObject(ow, ch, oh.directDriveThrottleResponseParamsOH);
destroyObject(ow, ch, oh.directDriveThrottleResponseStateOH);
destroyObject(ow, ch, oh.directDrivetrainOH);
//engine drive
destroyObject(ow, ch, oh.engineDriveCommandStateOH);
destroyObject(ow, ch, oh.engineDriveTransmissionCommandStateOH);
destroyObject(ow, ch, oh.clutchResponseParamsOH);
destroyObject(ow, ch, oh.clutchParamsOH);
destroyObject(ow, ch, oh.engineParamsOH);
destroyObject(ow, ch, oh.gearboxParamsOH);
destroyObject(ow, ch, oh.autoboxParamsOH);
destroyObject(ow, ch, oh.differentialParamsOH);
destroyObject(ow, ch, oh.clutchResponseStateOH);
destroyObject(ow, ch, oh.engineDriveThrottleResponseStateOH);
destroyObject(ow, ch, oh.engineStateOH);
destroyObject(ow, ch, oh.gearboxStateOH);
destroyObject(ow, ch, oh.autoboxStateOH);
destroyObject(ow, ch, oh.diffStateOH);
destroyObject(ow, ch, oh.clutchSlipStateOH);
destroyObject(ow, ch, oh.engineDrivetrainOH);
//PhysX Wheel attachments
for(PxU32 i = 0; i < oh.nbWheels; i++)
{
destroyObject(ow, ch, oh.physxConstraintParamOHs[i]);
destroyObject(ow, ch, oh.physxWheelShapeOHs[i]);
destroyObject(ow, ch, oh.physxRoadGeomStateOHs[i]);
destroyObject(ow, ch, oh.physxConstraintStateOHs[i]);
for(PxU32 j = 0; j < oh.nbPhysXMaterialFrictions; j++)
{
const PxU32 id = i*oh.nbPhysXMaterialFrictions + j;
destroyObject(ow, ch, oh.physxMaterialFrictionOHs[id]);
}
destroyObject(ow, ch, oh.physxWheelAttachmentOHs[i]);
}
//Physx rigid actor
destroyObject(ow, ch, oh.physxRoadGeomQueryParamOH);
destroyObject(ow, ch, oh.physxRoadGeomQueryDefaultFilterDataOH);
for (PxU32 i = 0; i < oh.nbWheels; i++)
{
destroyObject(ow, ch, oh.physxRoadGeomQueryFilterDataOHs[i]);
// safe even if not using per wheel filter data since it should hold the
// invalid handle value and thus destroyObject will do nothing
}
destroyObject(ow, ch, oh.physxRigidActorOH);
destroyObject(ow, ch, oh.physxSteerStateOH);
//Free the memory.
allocator.deallocate(&oh);
}
#else //#if PX_SUPPORT_OMNI_PVD
PxVehiclePvdAttributeHandles* PxVehiclePvdAttributesCreate(PxAllocatorCallback& allocator, OmniPvdWriter& omniWriter)
{
PX_UNUSED(allocator);
PX_UNUSED(omniWriter);
return NULL;
}
void PxVehiclePvdAttributesRelease(PxAllocatorCallback& allocator, PxVehiclePvdAttributeHandles& attributeHandles)
{
PX_UNUSED(allocator);
PX_UNUSED(attributeHandles);
}
PxVehiclePvdObjectHandles* PxVehiclePvdObjectCreate
(const PxU32 nbWheels, const PxU32 nbAntirolls, const PxU32 maxNbPhysXMaterialFrictions,
const PxU64 contextHandle,
PxAllocatorCallback& allocator)
{
PX_UNUSED(nbWheels);
PX_UNUSED(nbAntirolls);
PX_UNUSED(maxNbPhysXMaterialFrictions);
PX_UNUSED(contextHandle);
PX_UNUSED(allocator);
return NULL;
}
void PxVehiclePvdObjectRelease
(OmniPvdWriter& ow, PxAllocatorCallback& allocator, PxVehiclePvdObjectHandles& oh)
{
PX_UNUSED(ow);
PX_UNUSED(allocator);
PX_UNUSED(oh);
}
#endif //#if PX_SUPPORT_OMNI_PVD
} // namespace vehicle2
} // namespace physx
/** @} */
| 20,482 |
C++
| 44.619154 | 124 | 0.784103 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/steering/VhSteeringFunctions.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/steering/PxVehicleSteeringParams.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleSteerCommandResponseUpdate
(const PxReal steer, const PxReal longitudinalSpeed,
const PxU32 wheelId, const PxVehicleSteerCommandResponseParams& responseParams,
PxReal& steerResponse)
{
PxReal sign = PxSign(steer);
steerResponse = sign * PxVehicleNonLinearResponseCompute(PxAbs(steer), longitudinalSpeed, wheelId, responseParams);
}
void PxVehicleAckermannSteerUpdate
(const PxReal steer,
const PxVehicleSteerCommandResponseParams& steerResponseParams, const PxVehicleSizedArrayData<const PxVehicleAckermannParams>& ackermannParams,
PxVehicleArrayData<PxReal>& steerResponseStates)
{
for (PxU32 i = 0; i < ackermannParams.size; i++)
{
const PxVehicleAckermannParams& ackParams = ackermannParams[i];
if (ackParams.strength > 0.0f)
{
//Axle yaw is the average of the two wheels.
const PxF32 axleYaw =
(PxVehicleLinearResponseCompute(steer, ackParams.wheelIds[0], steerResponseParams) +
PxVehicleLinearResponseCompute(steer, ackParams.wheelIds[1], steerResponseParams))*0.5f;
if (axleYaw != 0.0f)
{
//Work out the ackermann steer for +ve steer then swap and negate the steer angles if the steer is -ve.
//Uncorrected yaw angle.
//One of the wheels will adopt this angle.
//The other will be corrected.
const PxF32 posWheelYaw = PxAbs(axleYaw);
//Work out the yaw of the other wheel.
PxF32 negWheelCorrectedYaw;
{
const PxF32 dz = ackParams.wheelBase;
const PxF32 dx = ackParams.trackWidth + ackParams.wheelBase / PxTan(posWheelYaw);
const PxF32 negWheelPerfectYaw = PxAtan(dz / dx);
negWheelCorrectedYaw = posWheelYaw + ackParams.strength*(negWheelPerfectYaw - posWheelYaw);
}
//Now assign axleYaw and negWheelCorrectedYaw to the correct wheels with the correct signs.
const PxF32 negWheelFinalYaw = intrinsics::fsel(axleYaw, negWheelCorrectedYaw, -posWheelYaw);
const PxF32 posWheelFinalYaw = intrinsics::fsel(axleYaw, posWheelYaw, -negWheelCorrectedYaw);
//Apply the per axle distributions to each wheel on the axle that is affected by this Ackermann correction.
steerResponseStates[ackParams.wheelIds[0]] = negWheelFinalYaw;
steerResponseStates[ackParams.wheelIds[1]] = posWheelFinalYaw;
}
}
}
}
} //namespace vehicle2
} //namespace physx
| 4,232 |
C++
| 42.639175 | 144 | 0.766068 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/commands/VhCommandHelpers.cpp
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "vehicle2/commands/PxVehicleCommandParams.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
namespace physx
{
namespace vehicle2
{
static float interpolate(const PxReal* speedVals, const PxReal* responseVals, const PxU16 nb, const PxReal speed)
{
if (1 == nb)
{
return responseVals[0];
}
else
{
const PxReal smallestSpeed = speedVals[0];
const PxReal largestSpeed = speedVals[nb - 1];
if (smallestSpeed >= speed)
{
return responseVals[0];
}
else if (largestSpeed <= speed)
{
return responseVals[nb - 1];
}
else
{
PxU16 speedId = 0;
while ((speedVals[speedId] < speed) && (speedId < nb))
speedId++;
// Make sure that we stay in range.
PxU16 speedLowerId = speedId - 1;
PxU16 speeddUpperId = speedId;
if (nb == speedId)
speeddUpperId = nb - 1;
if (0 == speedId)
speedLowerId = 0;
return responseVals[speedLowerId] + (speed - speedVals[speedLowerId]) * (responseVals[speeddUpperId] - responseVals[speedLowerId]) / (speedVals[speeddUpperId] - speedVals[speedLowerId]);
}
}
}
PxReal PxVehicleNonLinearResponseCompute
(const PxReal commandValue, const PxReal speed, const PxU32 wheelId, const PxVehicleCommandResponseParams& responseParams)
{
const PxU16 nbResponsesAtSpeeds = responseParams.nonlinearResponse.nbSpeedResponses;
if (0 == nbResponsesAtSpeeds)
{
//Empty response table.
//Use linear interpolation.
return PxVehicleLinearResponseCompute(commandValue, wheelId, responseParams);
}
const PxReal* commandValues = responseParams.nonlinearResponse.commandValues;
const PxU16* speedResponsesPerCommandValue = responseParams.nonlinearResponse.speedResponsesPerCommandValue;
const PxU16* nbSpeedResponsesPerCommandValue = responseParams.nonlinearResponse.nbSpeedResponsesPerCommandValue;
const PxU16 nbCommandValues = responseParams.nonlinearResponse.nbCommandValues;
const PxReal* speedResponses = responseParams.nonlinearResponse.speedResponses;
PxReal normalisedResponse = 0.0f;
if ((1 == nbCommandValues) || (commandValues[0] >= commandValue))
{
//Input command value less than the smallest value in the response table or
//there is just a single command value in the response table.
//No need to interpolate response of two command values.
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[0];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[0];
const PxU16 nb = nbSpeedResponsesPerCommandValue[0];
normalisedResponse = interpolate(speeds, responseValues, nb, speed);
}
else if (commandValues[nbCommandValues - 1] <= commandValue)
{
//Input command value greater than the largest value in the response table.
//No need to interpolate response of two command values.
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[nbCommandValues - 1];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[nbCommandValues - 1];
const PxU16 nb = nbSpeedResponsesPerCommandValue[nbCommandValues - 1];
normalisedResponse = interpolate(speeds, responseValues, nb, speed);
}
else
{
// Find the id of the command value that is immediately above the input command
PxU16 commandId = 0;
while ((commandValues[commandId] < commandValue) && (commandId < nbCommandValues))
{
commandId++;
}
// Make sure that we stay in range.
PxU16 commandLowerId = commandId - 1;
PxU16 commandUpperId = commandId;
if (nbCommandValues == commandId)
commandUpperId = nbCommandValues - 1;
if (0 == commandId)
commandLowerId = 0;
if (commandUpperId != commandLowerId)
{
float zLower;
{
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[commandLowerId];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[commandLowerId];
const PxU16 nb = nbSpeedResponsesPerCommandValue[commandLowerId];
zLower = interpolate(speeds, responseValues, nb, speed);
}
float zUpper;
{
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[commandUpperId];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[commandUpperId];
const PxU16 nb = nbSpeedResponsesPerCommandValue[commandUpperId];
zUpper = interpolate(speeds, responseValues, nb, speed);
}
const PxReal commandUpper = commandValues[commandUpperId];
const PxReal commandLower = commandValues[commandLowerId];
normalisedResponse = zLower + (commandValue - commandLower) * (zUpper - zLower) / (commandUpper - commandLower);
}
else
{
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[commandUpperId];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[commandUpperId];
const PxU16 nb = nbSpeedResponsesPerCommandValue[commandUpperId];
normalisedResponse = interpolate(speeds, responseValues, nb, speed);
}
}
return PxVehicleLinearResponseCompute(normalisedResponse, wheelId, responseParams);
}
} // namespace vehicle2
} // namespace physx
| 6,702 |
C++
| 40.63354 | 189 | 0.760668 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.