file_path
stringlengths 21
202
| content
stringlengths 13
1.02M
| size
int64 13
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 5.43
98.5
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.91
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/drivetrain/PxVehicleDrivetrainFunctions.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxSimpleTypes.h"
#include "vehicle2/PxVehicleParams.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehicleCommandState;
struct PxVehicleDirectDriveTransmissionCommandState;
struct PxVehicleEngineDriveTransmissionCommandState;
struct PxVehicleDirectDriveThrottleCommandResponseParams;
struct PxVehicleWheelActuationState;
struct PxVehicleWheelParams;
struct PxVehicleTireForce;
struct PxVehicleWheelRigidBody1dState;
struct PxVehicleEngineParams;
struct PxVehicleGearboxParams;
struct PxVehicleAutoboxParams;
struct PxVehicleEngineState;
struct PxVehicleGearboxState;
struct PxVehicleAutoboxState;
struct PxVehicleClutchCommandResponseParams;
struct PxVehicleClutchCommandResponseState;
struct PxVehicleEngineDriveThrottleCommandResponseState;
struct PxVehicleDifferentialState;
struct PxVehicleMultiWheelDriveDifferentialParams;
struct PxVehicleFourWheelDriveDifferentialParams;
struct PxVehicleTankDriveDifferentialParams;
struct PxVehicleFourWheelDriveDifferentialLegacyParams;
struct PxVehicleClutchParams;
struct PxVehicleWheelConstraintGroupState;
struct PxVehicleClutchSlipState;
/**
\brief Compute the drive torque response to a throttle command.
\param[in] throttle is the throttle command.
\param[in] transmissionCommands is the gearing command to apply to the direct drive tranmission.
\param[in] longitudinalSpeed is the longitudinal speed of the vehicle's rigid body.
\param[in] wheelId specifies the wheel that is to have its throttle response computed.
\param[in] throttleResponseParams specifies the per wheel drive torque response to the throttle command as a nonlinear function of throttle command and longitudinal speed.
\param[out] throttleResponseState is the drive torque response to the input throttle command.
*/
void PxVehicleDirectDriveThrottleCommandResponseUpdate
(const PxReal throttle, const PxVehicleDirectDriveTransmissionCommandState& transmissionCommands, const PxReal longitudinalSpeed,
const PxU32 wheelId, const PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams,
PxReal& throttleResponseState);
/**
\brief Determine the actuation state of a wheel given the brake torque, handbrake torque and drive torque applied to it.
\param[in] brakeTorque is the brake torque to be applied to the wheel.
\param[in] driveTorque is the drive torque to be applied to the wheel.
\param[out] actuationState contains a binary record of whether brake or drive torque is applied to the wheel.
*/
void PxVehicleDirectDriveActuationStateUpdate
(const PxReal brakeTorque, const PxReal driveTorque,
PxVehicleWheelActuationState& actuationState);
/**
\brief Forward integrate the angular speed of a wheel given the brake and drive torque applied to it
\param[in] wheelParams specifies the moment of inertia of the wheel.
\param[in] actuationState is a binary record of whether brake and drive torque are to be applied to the wheel.
\param[in] brakeTorque is the brake torque to be applied to the wheel.
\param[in] driveTorque is the drive torque to be applied to the wheel.
\param[in] tireForce specifies the torque to apply to the wheel as a response to the longitudinal tire force.
\param[in] dt is the timestep of the forward integration.
\param[out] wheelRigidBody1dState describes the angular speed of the wheel.
*/
void PxVehicleDirectDriveUpdate
(const PxVehicleWheelParams& wheelParams,
const PxVehicleWheelActuationState& actuationState,
const PxReal brakeTorque, const PxReal driveTorque, const PxVehicleTireForce& tireForce,
const PxF32 dt,
PxVehicleWheelRigidBody1dState& wheelRigidBody1dState);
/**
\param[in] engineParams specifies the engine configuration.
\param[in] gearboxParams specifies the gear ratios and the time required to complete a gear change.
\param[in] autoboxParams specifies the conditions for switching gear.
\param[in] engineState contains the current angular speed of the engine.
\param[in] gearboxState describes the current and target gear.
\param[in] dt is the time that has lapsed since the last call to PxVehicleAutoBoxUpdate.
\param[in,out] targetGearCommand specifies the desired target gear for the gearbox. If set to
PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR, the value will get overwritten
with a target gear chosen by the autobox.
\param[out] autoboxState specifies the time that has lapsed since the last automated gear change and contains a record of
any ongoing automated gear change.
\param[out] throttle A throttle command value in [0, 1] that will be set to 0 if a gear change is initiated or is ongoing.
\note The autobox will not begin a gear change if a gear change is already ongoing.
\note The autobox will not begin a gear change until a threshold time has lapsed since the last automated gear change.
\note A gear change is considered as ongoing for as long as PxVehicleGearboxState::currentGear is different from
PxVehicleGearboxState::targetGear.
\note The autobox will not shift down from 1st gear or up from reverse gear.
\note The autobox shifts in single gear increments or decrements.
\note The autobox instantiates a gear change by setting PxVehicleCommandState::targetGear to be different from
from PxVehicleGearboxState::currentGear
*/
void PxVehicleAutoBoxUpdate
(const PxVehicleEngineParams& engineParams, const PxVehicleGearboxParams& gearboxParams, const PxVehicleAutoboxParams& autoboxParams,
const PxVehicleEngineState& engineState, const PxVehicleGearboxState& gearboxState,
const PxReal dt,
PxU32& targetGearCommand, PxVehicleAutoboxState& autoboxState,
PxReal& throttle);
/**
\brief Propagate input gear commands to the gearbox state.
\param[in] targetGearCommand specifies the target gear for the gearbox.
\param[in] gearboxParams specifies the number of gears and the index of neutral gear.
\param[out] gearboxState contains a record of the current and target gear.
\note Any ongoing gear change must complete before starting another.
\note A gear change is considered as ongoing for as long as PxVehicleGearboxState::currentGear is different from
PxVehicleGearboxState::targetGear.
\note The gearbox remains in neutral for the duration of the gear change.
\note A gear change begins if PxVehicleCommandState::targetGear is different from PxVehicleGearboxState::currentGear.
*/
void PxVehicleGearCommandResponseUpdate
(const PxU32 targetGearCommand,
const PxVehicleGearboxParams& gearboxParams,
PxVehicleGearboxState& gearboxState);
/**
\brief Propagate the input clutch command to the clutch response state.
\param[in] clutchCommand specifies the state of the clutch pedal.
\param[in] clutchResponseParams specifies how the clutch responds to the input clutch command.
\param[out] clutchResponse specifies the response of the clutch to the input clutch command.
*/
void PxVehicleClutchCommandResponseLinearUpdate
(const PxReal clutchCommand,
const PxVehicleClutchCommandResponseParams& clutchResponseParams,
PxVehicleClutchCommandResponseState& clutchResponse);
/**
\brief Propagate the input throttle command to the throttle response state.
\param[in] commands specifies the state of the throttle pedal.
\param[out] throttleResponse specifies how the clutch responds to the input throttle command.
*/
void PxVehicleEngineDriveThrottleCommandResponseLinearUpdate
(const PxVehicleCommandState& commands,
PxVehicleEngineDriveThrottleCommandResponseState& throttleResponse);
/**
\brief Determine the actuation state of all wheels on a vehicle.
\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle.
\param[in] gearboxParams specifies the index of the neutral gear of the gearbox.
\param[in] brakeResponseStates specifies the response of each wheel to the input brake command.
\param[in] throttleResponseState specifies the response of the engine to the input throttle command.
\param[in] gearboxState specifies the current gear.
\param[in] diffState specifies the fraction of available drive torque to be delivered to each wheel.
\param[in] clutchResponseState specifies the response of the clutch to the input throttle command.
\param[out] actuationStates is an array of binary records determining whether brake and drive torque are to be applied to each wheel.
\note Drive torque is not applied to a wheel if
a) the gearbox is in neutral
b) the differential delivers no torque to the wheel
c) no throttle is applied to the engine
c) the clutch is fully disengaged.
*/
void PxVehicleEngineDriveActuationStateUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleGearboxParams& gearboxParams,
const PxVehicleArrayData<const PxReal>& brakeResponseStates,
const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState,
const PxVehicleGearboxState& gearboxState, const PxVehicleDifferentialState& diffState, const PxVehicleClutchCommandResponseState& clutchResponseState,
PxVehicleArrayData<PxVehicleWheelActuationState>& actuationStates);
/**
@deprecated
\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all
wheels connected to the differential.
\param[in] diffParams specifies the operation of a differential that can be connected to up to four wheels.
\param[in] wheelStates describes the angular speed of each wheel
\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel.
\note If the handbrake is on then torque is only delivered to the wheels specified as the front wheels of the differential.
*/
void PX_DEPRECATED PxVehicleDifferentialStateUpdate
(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelStates,
PxVehicleDifferentialState& diffState);
/**
\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all
wheels connected to the differential. Additionally, add wheel constraints for wheel pairs whose
rotational speed ratio exceeds the corresponding differential bias.
\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle.
\param[in] diffParams describe the division of available drive torque and the biases of the limited
slip differential.
\param[in] wheelStates describes the rotational speeds of each wheel.
\param[in] dt is the simulation time that has passes since the last call to PxVehicleDifferentialStateUpdate()
\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel.
\param[out] wheelConstraintGroupState describes the groups of wheels that have exceeded their corresponding
differential biases.
*/
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleFourWheelDriveDifferentialParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelStates,
const PxReal dt,
PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState);
/**
\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all
wheels connected to the differential.
\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle.
\param[in] diffParams specifies the operation of a differential that can be connected to any combination of wheels.
\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel connected to the differential.
*/
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleMultiWheelDriveDifferentialParams& diffParams,
PxVehicleDifferentialState& diffState);
/**
\brief Compute the fraction of available torque to be delivered to each wheel and gather a list of all
wheels connected to the differential.
\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle.
\param[in] wheelParams is an array that describes the wheel radius of each wheel.
\param[in] diffParams specifies the operation of a tank differential.
\param[in] thrustCommand0 is the state of one of the two thrust controllers.
\param[in] thrustCommand1 is the state of one of the two thrust controllers.
\param[out] diffState contains the fraction of available drive torque to be delivered to each wheel connected to the differential.
\param[out] wheelConstraintGroupState describes the groups of wheels connected by sharing a tank track.
*/
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, const PxVehicleTankDriveDifferentialParams& diffParams,
const PxReal thrustCommand0, PxReal thrustCommand1,
PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState);
/**
\brief Update the current gear of the gearbox. If a gear change is ongoing then complete the gear change if a threshold
time has passed since the beginning of the gear change.
\param[in] gearboxParams describes the time required to complete a gear change.
\param[in] dt is the time that has lapsed since the last call to PxVehicleGearboxUpdate.
\param[out] gearboxState is the gearbox state to be updated.
\note A gear change is considered as ongoing for as long as PxVehicleGearboxState::currentGear is different from
PxVehicleGearboxState::targetGear.
*/
void PxVehicleGearboxUpdate
(const PxVehicleGearboxParams& gearboxParams,
const PxF32 dt,
PxVehicleGearboxState& gearboxState);
/**
\brief Forward integrate the angular speed of the vehicle's wheels and engine, given the state of clutch, differential and gearbox.
\param[in] axleDescription is a decription of the axles of the vehicle and the wheels on each axle.
\param[in] wheelParams specifies the moment of inertia of each wheel.
\param[in] engineParams specifies the torque curve of the engine and its moment of inertia.
\param[in] clutchParams specifies the maximum clutch strength that happens when the clutch is fully engaged.
\param[in] gearboxParams specifies the gearing ratios of the gearbox.
\param[in] brakeResponseStates describes the per wheel response to the input brake command.
\param[in] actuationStates is a binary record of whether brake or drive torque is applied to each wheel.
\param[in] tireForces describes the torque to apply to each wheel as a response to the longitudinal tire force.
\param[in] gearboxState describes the current gear.
\param[in] throttleResponse describes the engine response to the input throttle pedal.
\param[in] clutchResponse describes the clutch response to the input clutch pedal.
\param[in] diffState describes the fraction of available drive torque to be delivered to each wheel.
\param[in] constraintGroupState describes groups of wheels with rotational speed constrained to the same value.
\param[in] dt is the time that has lapsed since the last call to PxVehicleEngineDrivetrainUpdate
\param[out] wheelRigidbody1dStates describes the angular speed of each wheel.
\param[out] engineState describes the angular speed of the engine.
\param[out] clutchState describes the clutch slip.
\note If constraintGroupState is NULL then it is assumed that there are no wheels subject to rotational speed constraints.
*/
void PxVehicleEngineDrivetrainUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<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& throttleResponse, const PxVehicleClutchCommandResponseState& clutchResponse,
const PxVehicleDifferentialState& diffState, const PxVehicleWheelConstraintGroupState* constraintGroupState,
const PxReal dt,
PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidbody1dStates,
PxVehicleEngineState& engineState, PxVehicleClutchSlipState& clutchState);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 18,099 | C | 55.739812 | 177 | 0.823637 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/drivetrain/PxVehicleDrivetrainParams.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxFoundation.h"
#include "common/PxCoreUtilityTypes.h"
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/commands/PxVehicleCommandParams.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
/**
\brief Distribute a throttle response to the wheels of a direct drive vehicle.
\note The drive torque applied to each wheel on the ith axle is throttleCommand * maxResponse * wheelResponseMultipliers[i].
\note A typical use case is to set maxResponse to be the vehicle's maximum achievable drive torque
that occurs when the steer command is equal to 1.0. The array wheelResponseMultipliers[i] would then be used
to specify the maximum achievable drive torque per wheel as a fractional multiplier of the vehicle's maximum achievable steer angle.
*/
struct PxVehicleDirectDriveThrottleCommandResponseParams : public PxVehicleCommandResponseParams
{
PX_FORCE_INLINE PxVehicleDirectDriveThrottleCommandResponseParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PxVehicleDirectDriveThrottleCommandResponseParams r = *this;
const PxReal scale = trgScale.scale/srcScale.scale;
r.maxResponse *= (scale*scale); //Max response is a torque!
return r;
}
PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const
{
PX_CHECK_AND_RETURN_VAL(PxIsFinite(maxResponse), "PxVehicleDirectDriveThrottleCommandResponseParams.maxResponse must be a finite value", false);
for (PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
PX_CHECK_AND_RETURN_VAL(PxIsFinite(wheelResponseMultipliers[axleDesc.wheelIdsInAxleOrder[i]]), "PxVehicleDirectDriveThrottleCommandResponseParams.wheelResponseMultipliers[i] must be a finite value", false);
}
return true;
}
};
/**
\brief Specifies the maximum clutch strength that occurs when the clutch pedal is fully disengaged and the clutch is fully engaged.
*/
struct PxVehicleClutchCommandResponseParams
{
/**
\brief Strength of clutch.
\note The clutch is the mechanism that couples the engine to the wheels.
A stronger clutch more strongly couples the engine to the wheels, while a
clutch of strength zero completely decouples the engine from the wheels.
Stronger clutches more quickly bring the wheels and engine into equilibrium, while weaker
clutches take longer, resulting in periods of clutch slip and delays in power transmission
from the engine to the wheels.
The torque generated by the clutch is proportional to the clutch strength and
the velocity difference between the engine's rotational speed and the rotational speed of the
driven wheels after accounting for the gear ratio.
The torque at the clutch is applied negatively to the engine and positively to the driven wheels.
<b>Range:</b> [0,inf)<br>
<b>Unit:</b> torque * time = mass * (length^2) / time
*/
PxReal maxResponse;
PX_FORCE_INLINE PxVehicleClutchCommandResponseParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
const PxReal scale = trgScale.scale/srcScale.scale;
PxVehicleClutchCommandResponseParams r = *this;
r.maxResponse *= (scale*scale);
return r;
}
PX_FORCE_INLINE bool isValid() const
{
PX_CHECK_AND_RETURN_VAL(maxResponse >= 0.0f, "PxVehicleClutchCommandResponseParams.maxResponse must be greater than or equal to zero", false);
return true;
}
};
/**
\brief Choose between a potentially more expensive but more accurate solution to the clutch model or a potentially cheaper but less accurate solution.
@see PxVehicleClutchParams
*/
struct PxVehicleClutchAccuracyMode
{
enum Enum
{
eESTIMATE = 0,
eBEST_POSSIBLE
};
};
/**
\brief The clutch connects two plates together. One plate rotates with the speed of the engine. The second plate rotates with a weighted average of all
wheels connected to the differential after accounting for the gear ratio. The difference in rotation speeds generates a restoring torque applied to engine and wheels
that aims to reduce the difference in rotational speed. The restoring torque is proportional to the clutch strength and the clutch pedal position.
*/
struct PxVehicleClutchParams
{
public:
/**
\brief The engine and wheel rotation speeds that are coupled through the clutch can be updated by choosing
one of two modes: eESTIMATE and eBEST_POSSIBLE.
\note If eESTIMATE is chosen the vehicle sdk will update the wheel and engine rotation speeds
with estimated values to the implemented clutch model.
\note If eBEST_POSSIBLE is chosen the vehicle sdk will compute the best possible
solution (within floating point tolerance) to the implemented clutch model.
This is the recommended mode.
\note The clutch model remains the same if either eESTIMATE or eBEST_POSSIBLE is chosen but the accuracy and
computational cost of the solution to the model can be tuned as required.
*/
PxVehicleClutchAccuracyMode::Enum accuracyMode;
/**
\brief Tune the mathematical accuracy and computational cost of the computed estimate to the wheel and
engine rotation speeds if eESTIMATE is chosen.
\note As estimateIterations increases the computational cost of the clutch also increases and the solution
approaches the solution that would be computed if eBEST_POSSIBLE was chosen instead.
\note This has no effect if eBEST_POSSIBLE is chosen as the accuracy mode.
\note A value of zero is not allowed if eESTIMATE is chosen as the accuracy mode.
*/
PxU32 estimateIterations;
PX_FORCE_INLINE PxVehicleClutchParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid() const
{
PX_CHECK_AND_RETURN_VAL((PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == accuracyMode) || ((PxVehicleClutchAccuracyMode::eESTIMATE == accuracyMode) && (estimateIterations > 0)), "PxVehicleClutchParams.estimateIterations must be greater than zero if PxVehicleClutchAccuracyMode::eESTIMATE is selected", false);
return true;
}
};
struct PxVehicleEngineParams
{
/**
\brief Maximum supported number of points in the #torqueCurve graph.
*/
enum
{
eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES = 8
};
/**
\brief Graph of normalized torque (torque/#peakTorque) against normalized engine speed ( engineRotationSpeed / #maxOmega ).
\note The normalized engine speed is the x-axis of the graph, while the normalized torque is the y-axis of the graph.
*/
PxVehicleFixedSizeLookupTable<PxReal, eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES> torqueCurve;
/**
\brief Moment of inertia of the engine around the axis of rotation.
<b>Range:</b> (0, inf)<br>
<b>Unit:</b> mass * (length^2)
*/
PxReal moi;
/**
\brief Maximum torque available to apply to the engine when the accelerator pedal is at maximum.
\note The torque available is the value of the accelerator pedal (in range [0, 1]) multiplied by the normalized torque as computed from #torqueCurve multiplied by #peakTorque.
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> mass * (length^2) / (time^2)
*/
PxReal peakTorque;
/**
\brief Minimum rotation speed of the engine.
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> radians / time
*/
PxReal idleOmega;
/**
\brief Maximum rotation speed of the engine.
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> radians / time
*/
PxReal maxOmega;
/**
\brief Damping rate of engine when full throttle is applied.
\note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation
between #dampingRateZeroThrottleClutchEngaged and #dampingRateFullThrottle:
#dampingRateZeroThrottleClutchEngaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchEngaged)*acceleratorPedal;
\note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation
between #dampingRateZeroThrottleClutchDisengaged and #dampingRateFullThrottle:
#dampingRateZeroThrottleClutchDisengaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchDisengaged)*acceleratorPedal;
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> torque * time = mass * (length^2) / time
*/
PxReal dampingRateFullThrottle;
/**
\brief Damping rate of engine when no throttle is applied and with engaged clutch.
\note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation
between #dampingRateZeroThrottleClutchEngaged and #dampingRateFullThrottle:
#dampingRateZeroThrottleClutchEngaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchEngaged)*acceleratorPedal;
\note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation
between #dampingRateZeroThrottleClutchDisengaged and #dampingRateFullThrottle:
#dampingRateZeroThrottleClutchDisengaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchDisengaged)*acceleratorPedal;
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> torque * time = mass * (length^2) / time
*/
PxReal dampingRateZeroThrottleClutchEngaged;
/**
\brief Damping rate of engine when no throttle is applied and with disengaged clutch.
\note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation
between #dampingRateZeroThrottleClutchEngaged and #dampingRateFullThrottle:
#dampingRateZeroThrottleClutchEngaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchEngaged)*acceleratorPedal;
\note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation
between #dampingRateZeroThrottleClutchDisengaged and #dampingRateFullThrottle:
#dampingRateZeroThrottleClutchDisengaged + (#dampingRateFullThrottle-#dampingRateZeroThrottleClutchDisengaged)*acceleratorPedal;
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> torque * time = mass * (length^2) / time
*/
PxReal dampingRateZeroThrottleClutchDisengaged;
PX_FORCE_INLINE PxVehicleEngineParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PxVehicleEngineParams r = *this;
const PxReal scale = trgScale.scale/srcScale.scale;
r.moi *= (scale*scale);
r.peakTorque *= (scale*scale);
r.dampingRateFullThrottle *= (scale*scale);
r.dampingRateZeroThrottleClutchDisengaged *= (scale*scale);
r.dampingRateZeroThrottleClutchEngaged *= (scale*scale);
return r;
}
PX_FORCE_INLINE bool isValid() const
{
PX_CHECK_AND_RETURN_VAL(moi > 0.0f, "PxVehicleEngineParams.moi must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(peakTorque >= 0.0f, "PxVehicleEngineParams.peakTorque must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(torqueCurve.isValid(), "PxVehicleEngineParams.torqueCurve is invalid", false);
PX_CHECK_AND_RETURN_VAL(maxOmega >= 0.0f, "PxVehicleEngineParams.maxOmega must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(idleOmega >= 0.0f, "PxVehicleEngineParams.idleOmega must be greater or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(dampingRateFullThrottle >= 0.0f, "PxVehicleEngineParams.dampingRateFullThrottle must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(dampingRateZeroThrottleClutchEngaged >= 0.0f, "PxVehicleEngineParams.dampingRateZeroThrottleClutchEngaged must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL(dampingRateZeroThrottleClutchDisengaged >= 0.0f, "PxVehicleEngineParams.dampingRateZeroThrottleClutchDisengaged must be greater than or equal to zero", false)
return true;
}
};
struct PxVehicleGearboxParams
{
public:
/**
\brief The gear that denotes neutral gear
*/
PxU32 neutralGear;
/**
\brief Maximum supported number of gears, including reverse and neutral.
*/
enum Enum
{
eMAX_NB_GEARS = 32
};
/**
\brief Gear ratios
The ratio for reverse gears must be negative, the ratio for the neutral gear
has to be 0 and the ratio for forward gears must be positive.
*/
PxReal ratios[eMAX_NB_GEARS];
/**
\brief Gear ratio applied is #ratios[currentGear]*#finalRatio
<b>Range:</b> (0, inf)<br>
*/
PxReal finalRatio;
/**
\brief Number of gears (including reverse and neutral).
<b>Range:</b> [1, eMAX_NB_GEARS]<br>
*/
PxU32 nbRatios;
/**
\brief Time it takes to switch gear.
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> time
*/
PxReal switchTime;
PX_FORCE_INLINE PxVehicleGearboxParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid() const
{
PX_CHECK_AND_RETURN_VAL(finalRatio > 0, "PxVehicleGearboxParams.finalRatio must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(nbRatios >= 1, "PxVehicleGearboxParams.nbRatios must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(nbRatios <= eMAX_NB_GEARS, "PxVehicleGearboxParams.nbRatios must be less than or equal to eMAX_NB_GEARS", false);
PX_CHECK_AND_RETURN_VAL(neutralGear < nbRatios, "PxVehicleGearboxParams.neutralGear must be less than PxVehicleGearboxParams.nbRatios", false);
PX_CHECK_AND_RETURN_VAL(switchTime >= 0.0f, "PxVehicleGearboxParams.switchTime must be greater than or equal to zero", false);
for(PxU32 i = 0; i < neutralGear; i++)
{
PX_CHECK_AND_RETURN_VAL(ratios[i] < 0.0f, "Reverse gear ratios must be less than zero", false);
}
{
PX_CHECK_AND_RETURN_VAL(ratios[neutralGear] == 0.0f, "Neutral gear ratio must be equal to zero", false);
}
for (PxU32 i = neutralGear + 1; i < nbRatios; i++)
{
PX_CHECK_AND_RETURN_VAL(ratios[i] > 0.0f, "Forward gear ratios must be greater than zero", false);
}
for (PxU32 i = neutralGear + 2; i < nbRatios; i++)
{
PX_CHECK_AND_RETURN_VAL(ratios[i] < ratios[i - 1], "Forward gear ratios must be a descending sequence of gear ratios", false);
}
return true;
}
};
struct PxVehicleAutoboxParams
{
public:
/**
\brief Value of ( engineRotationSpeed /maxEngineRevs ) that is high enough to increment gear.
\note When ( engineRotationSpeed / #PxVehicleEngineParams::maxOmega ) > upRatios[currentGear] the autobox will begin
a transition to currentGear+1 unless currentGear is the highest possible gear or neutral or reverse.
<b>Range:</b> [0, 1]<br>
*/
PxReal upRatios[PxVehicleGearboxParams::eMAX_NB_GEARS];
/**
\brief Value of engineRevs/maxEngineRevs that is low enough to decrement gear.
\note When ( engineRotationSpeed / #PxVehicleEngineParams::maxOmega) < downRatios[currentGear] the autobox will begin
a transition to currentGear-1 unless currentGear is first gear or neutral or reverse.
<b>Range:</b> [0, 1]<br>
*/
PxReal downRatios[PxVehicleGearboxParams::eMAX_NB_GEARS];
/**
\brief Set the latency time of the autobox.
\note Latency time is the minimum time that must pass between each gear change that is initiated by the autobox.
The auto-box will only attempt to initiate another gear change up or down if the simulation time that has passed since the most recent
automated gear change is greater than the specified latency.
<b>Range:</b> [0, inf)<br>
<b>Unit:</b> time
*/
PxReal latency;
PX_FORCE_INLINE PxVehicleAutoboxParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid(const PxVehicleGearboxParams& gearboxParams) const
{
if (!gearboxParams.isValid())
return false;
for (PxU32 i = gearboxParams.neutralGear + 1; i < gearboxParams.nbRatios-1; i++)
{
PX_CHECK_AND_RETURN_VAL(upRatios[i] >= 0.0f, "PxVehicleAutoboxParams.upRatios must be greater than or equal to zero", false);
}
for (PxU32 i = gearboxParams.neutralGear + 2; i < gearboxParams.nbRatios; i++)
{
PX_CHECK_AND_RETURN_VAL(downRatios[i] >= 0.0f, "PxVehicleAutoboxParams.downRatios must be greater than or equal to zero", false);
}
PX_CHECK_AND_RETURN_VAL(latency >= 0.0f, "PxVehicleAutoboxParams.latency must be greater than or equal to zero", false);
return true;
}
};
/**
@deprecated
*/
struct PX_DEPRECATED PxVehicleFourWheelDriveDifferentialLegacyParams
{
public:
enum Enum
{
eDIFF_TYPE_LS_4WD, //limited slip differential for car with 4 driven wheels
eDIFF_TYPE_LS_FRONTWD, //limited slip differential for car with front-wheel drive
eDIFF_TYPE_LS_REARWD, //limited slip differential for car with rear-wheel drive
eMAX_NB_DIFF_TYPES
};
/**
\brief The two front wheels are specified by the array frontWheelIds.
\note The states eDIFF_TYPE_LS_4WD, eDIFF_TYPE_LS_FRONTWD require knowledge of the front wheels
to allow torque splits between front and rear axles as well as torque splits across the front axle.
\note frontWheelIds[0] should specify the wheel on the front axle that is negatively placed on the lateral axis.
\note frontWheelIds[1] should specify the wheel on the front axle that is positively placed on the lateral axis.
\note If #frontNegPosSplit > 0.5, more torque will be delivered to the wheel specified by frontWheelIds[0] than to the wheel
specified by frontWheelIds[1]. The converse is true if #frontNegPosSplit < 0.5.
*/
PxU32 frontWheelIds[2];
/**
\brief The two rear wheels are specified by the array rearWheelIds.
\note The states eDIFF_TYPE_LS_4WD, eDIFF_TYPE_LS_REARWD require knowledge of the rear wheels
to allow torque splits between front and rear axles as well as torque splits across the rear axle.
\note rearWheelIds[0] should specify the wheel on the rear axle that is negatively placed on the lateral axis.
\note rearWheelIds[1] should specify the wheel on the rear axle that is positively placed on the lateral axis.
\note If #rearNegPosSplit > 0.5, more torque will be delivered to the wheel specified by rearWheelIds[0] than to the wheel
specified by rearWheelIds[1]. The converse is true if #rearNegPosSplit < 0.5.
*/
PxU32 rearWheelIds[2];
/**
\brief Ratio of torque split between front and rear wheels (>0.5 means more front, <0.5 means more to rear).
\note Only applied to DIFF_TYPE_LS_4WD
<b>Range:</b> [0, 1]<br>
*/
PxReal frontRearSplit;
/**
\brief Ratio of torque split between front-negative and front-positive wheels (>0.5 means more to #frontWheelIds[0], <0.5 means more to #frontWheelIds[1]).
\note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_FRONTWD
<b>Range:</b> [0, 1]<br>
*/
PxReal frontNegPosSplit;
/**
\brief Ratio of torque split between rear-negative wheel and rear-positive wheels (>0.5 means more to #rearWheelIds[0], <0.5 means more to #rearWheelIds[1]).
\note Only applied to DIFF_TYPE_LS_4WD and eDIFF_TYPE_LS_REARWD
<b>Range:</b> [0, 1]<br>
*/
PxReal rearNegPosSplit;
/**
\brief Maximum allowed ratio of average front wheel rotation speed and rear wheel rotation speeds.
The differential will divert more torque to the slower wheels when the bias is exceeded.
\note Only applied to DIFF_TYPE_LS_4WD
<b>Range:</b> [1, inf)<br>
*/
PxReal centerBias;
/**
\brief Maximum allowed ratio of front-left and front-right wheel rotation speeds.
The differential will divert more torque to the slower wheel when the bias is exceeded.
\note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_FRONTWD
<b>Range:</b> [1, inf)<br>
*/
PxReal frontBias;
/**
\brief Maximum allowed ratio of rear-left and rear-right wheel rotation speeds.
The differential will divert more torque to the slower wheel when the bias is exceeded.
\note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_REARWD
<b>Range:</b> [1, inf)<br>
*/
PxReal rearBias;
/**
\brief Type of differential.
<b>Range:</b> [DIFF_TYPE_LS_4WD, eDIFF_TYPE_LS_REARWD]<br>
*/
Enum type;
PX_FORCE_INLINE PxVehicleFourWheelDriveDifferentialLegacyParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const
{
PX_UNUSED(axleDesc);
PX_CHECK_AND_RETURN_VAL((axleDesc.getAxle(frontWheelIds[0]) != 0xffffffff) && (axleDesc.getAxle(frontWheelIds[0])== axleDesc.getAxle(frontWheelIds[1])), "frontWheelIds[0] and frontWheelIds[1] must reference wheels on the same axle", false);
PX_CHECK_AND_RETURN_VAL((axleDesc.getAxle(rearWheelIds[0]) != 0xffffffff) && (axleDesc.getAxle(rearWheelIds[0]) == axleDesc.getAxle(rearWheelIds[1])), "rearWheelIds[0] and rearWheelIds[1] must reference wheels on the same axle", false);
PX_CHECK_AND_RETURN_VAL(frontRearSplit <= 1.0f && frontRearSplit >= 0.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.frontRearSplit must be in range [0,1]", false);
PX_CHECK_AND_RETURN_VAL(frontNegPosSplit <= 1.0f && frontNegPosSplit >= 0.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.frontNegPosSplit must be in range [0,1]", false);
PX_CHECK_AND_RETURN_VAL(rearNegPosSplit <= 1.0f && rearNegPosSplit >= 0.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.rearNegPosSplit must be in range [0,1]", false);
PX_CHECK_AND_RETURN_VAL(centerBias >= 1.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.centerBias must be greater than or equal to 1.0f", false);
PX_CHECK_AND_RETURN_VAL(frontBias >= 1.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.frontBias must be greater than or equal to 1.0f", false);
PX_CHECK_AND_RETURN_VAL(rearBias >= 1.0f, "PxVehicleLegacyFourWheelDriveDifferentialParams.rearBias must be greater than or equal to 1.0f", false);
PX_CHECK_AND_RETURN_VAL(type < PxVehicleFourWheelDriveDifferentialLegacyParams::eMAX_NB_DIFF_TYPES, "PxVehicleLegacyFourWheelDriveDifferentialParams.type has illegal value", false);
return true;
}
};
/**
\brief PxVehicleMultiWheelDriveDifferentialParams specifies the wheels that are to receive drive torque from the differential
and the division of torque between the wheels that are connected to the differential.
*/
struct PxVehicleMultiWheelDriveDifferentialParams
{
/**
\brief torqueRatios describes the fraction of torque delivered to each wheel through the differential.
\note Wheels not connected to the differential must receive zero torque.
\note Wheels connected to the differential may receive a non-zero torque.
\note The sum of the absolute of the ratios of all wheels must equal to 1.0.
\note A negative torque ratio simulates a wheel with negative gearing applied.
<b>Range:</b> [1, -1]<br>
*/
PxReal torqueRatios[PxVehicleLimits::eMAX_NB_WHEELS];
/**
\brief aveWheelSpeedRatios describes the contribution of each wheel to the average wheel speed measured at the clutch.
\note Wheels not connected to the differential do not contribute to the average wheel speed measured at the clutch.
\note Wheels connected to the differential may delivere a non-zero contribution to the average wheel speed measured at the clutch.
\note The sum of all ratios of all wheels must equal to 1.0.
<b>Range:</b> [0, 1]<br>
*/
PxReal aveWheelSpeedRatios[PxVehicleLimits::eMAX_NB_WHEELS];
PX_FORCE_INLINE void setToDefault()
{
PxMemZero(this, sizeof(PxVehicleMultiWheelDriveDifferentialParams));
}
PX_FORCE_INLINE PxVehicleMultiWheelDriveDifferentialParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const
{
if (!axleDesc.isValid())
return false;
PxReal aveWheelSpeedSum = 0.0f;
PxReal torqueRatioSum = 0.0f;
for (PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN_VAL(PxAbs(torqueRatios[wheelId]) <= 1.0f, "PxVehicleMultiWheelDriveDifferentialParams.torqueRatios[i] must be in range [-1, 1] for all wheels connected to the differential", false);
PX_CHECK_AND_RETURN_VAL(aveWheelSpeedRatios[wheelId] >= 0.0f && aveWheelSpeedRatios[wheelId] <= 1.0f, "PxVehicleMultiWheelDriveDifferentialParams.aveWheelSpeedRatios[i] must be in range [0, 1] for all wheels connected to the differential", false);
aveWheelSpeedSum += aveWheelSpeedRatios[wheelId];
torqueRatioSum += PxAbs(torqueRatios[wheelId]);
}
PX_CHECK_AND_RETURN_VAL(aveWheelSpeedSum >= 0.99f && aveWheelSpeedSum <= 1.01f, "Sum of PxVehicleMultiWheelDriveDifferentialParams.aveWheelSpeedRatios[i] must be 1.0.", false);
PX_CHECK_AND_RETURN_VAL(torqueRatioSum >= 0.99f && torqueRatioSum <= 1.01f, "Sum of PxVehicleMultiWheelDriveDifferentialParams.torqueRatios[i] must be 1.0.", false);
PX_UNUSED(aveWheelSpeedSum);
PX_UNUSED(torqueRatioSum);
return true;
}
};
/**
\brief A special value that indicates instantaneous resolution of a slip that exceeds a differential bias.
*/
#define PX_VEHICLE_FOUR_WHEEL_DIFFERENTIAL_MAXIMUM_STRENGTH PX_MAX_F32
/**
\brief PxVehicleFourWheelDriveDifferentialParams specifies the wheels that are to receive drive torque from the differential
and the division of torque between the wheels that are connected to the differential. Additionally, it specifies the biases
and strength of a limited slip differential that operates on two wheels specified as front wheels and two wheels specified
as rear wheels.
*/
struct PxVehicleFourWheelDriveDifferentialParams : public PxVehicleMultiWheelDriveDifferentialParams
{
/**
\brief The ids of the two wheels considered by the differential to be the front pair.
\note When the ratio of the rotational speeds of the front wheels exceeds frontBias, drive torque is diverted so
that the ratio approaches the value specified by frontTarget. When the bias is not breached, the drive torque
is specified by the corresponding entries in PxVehicleMultiWheelDriveDifferentialParams::torqueRatios.
*/
PxU32 frontWheelIds[2];
/**
\brief The ids of the two wheels considered by the differential to be the rear pair.
\note When the ratio of the rotational speeds of the rear wheels exceeds rearBias, drive torque is diverted so
that the ratio approaches the value specified by rearTarget. When the bias is not breached, the drive torque
is specified by the corresponding entries in PxVehicleMultiWheelDriveDifferentialParams::torqueRatios.
*/
PxU32 rearWheelIds[2];
/**
\brief The parameter frontBias specifies the maximum angular speed ratio of the two front wheels specified by frontWheelIds[2].
\note If frontBias has value 0.0, the differential will not try to enforce any relationship between the rotational speeds of the two front wheels.
\note If frontBias has value 0.0, the torque split between the front wheels is specified by the array torqueRatios.
\note frontBias must have value 0.0 (deactivated limited slip) or be greater than 1.0 (activated limited slip) or be equal to 1.0 (locked axle).
\note If frontBias has value greater than or equal to 1.0 then the array frontWheelIds must be specified and the corresponding entries of
the isConnected[] array must be set true.
\note If frontBias has value greater than or equal to 1.0 then frontTarget must also be specified.
\note A locked axle may be achieved by setting frontBias and frontTarget to 1.0.
\note A limited slip differential may be achieved by setting frontBias > 1.0 and frontBias > frontTarget > 1.0.
*/
PxReal frontBias;
/**
\brief The parameter frontTarget specifies the target rotational speed ratio of the two front wheels in the event that the ratio exceeds frontBias and frontBias
is configured for an activated limited slip or locked axle.
\note frontTarget must be less than frontBias and greater than 1.0 to implement a limited slip differential.
\note Set frontTarget and frontBias to 1.0 to implement a locked axle.
*/
PxReal frontTarget;
/**
\brief The parameter rearBias specifies the maximum angular speed ratio of the two rear wheels specified by rearWheelIds[2].
\note If rearBias has value 0.0, the differential will not try to enforce any relationship between the rotational speeds of the two rear wheels.
\note If rearBias has value 0.0, the torque split between the rear wheels is specified by the array torqueRatios.
\note rearBias must have value 0.0 (deactivated limited slip) or be greater than 1.0 (activated limited slip) or be equal to 1.0 (locked axle).
\note If rearBias has value greater than or equal to 1.0 then the array rearWheelIds must be specified and the corresponding entries of
the isConnected[] array must be set true.
\note If rearBias has value greater than or equal to 1.0 then rearTarget must also be specified.
\note A locked axle may be achieved by setting rearBias and rearTarget to 1.0.
\note A limited slip differential may be achieved by setting rearBias > 1.0 and rearBias > rearTarget > 1.0
*/
PxReal rearBias;
/**
\brief The parameter rearTarget specifies the target rotational speed ratio of the two rear wheels in the event that the ratio exceeds rearBias and rearBias
is configured for an activated limited slip or locked axle.
\note rearTarget must be less than rearBias and greater than 1.0 to implement a limited slip differential.
\note Set rearTarget and rearBias to 1.0 to implement a locked axle.
*/
PxReal rearTarget;
/**
\brief The parameter centerBias specifies the maximum angular speed ratio of the sum of the two front wheels and the sum of the two rear wheels,
as specified by frontWheelIds[2] and rearWheelIds[2].
\note If centerBias has value 0.0, the differential will not try to enforce any relationship between the rotational speeds of the front and rear wheels.
\note If centerBias has value 0.0, the torque split between the front and rear rear wheels is specified by the array torqueRatios.
\note centerBias must have value 0.0 (deactivated limited slip) or be greater than 1.0 (activated limited slip) or be equal to 1.0 (locked).
\note If centerBias has value greater than or equal to 1.0 then the arrays frontWheelIds and rearWheelIds must be specified and the corresponding entries of
the isConnected[] array must be set true.
\note If centerBias has value greater than or equal to 1.0 then centerTarget must also be specified.
\note A locked front/rear differential may be achieved by setting centerBias and centerTarget to 1.0.
\note A limited slip differential may be achieved by setting centerBias > 1.0 and centerBias > centerTarget > 1.0
*/
PxReal centerBias;
/**
\brief The parameter centerTarget specifies the target rotational speed ratio of the sum of the two front wheels and the sum of the two rear wheels
in the event that the ratio exceeds centerBias and centerBias is configured for an activated limited slip.
\note centerTarget must be less than centerBias and greater than 1.0 to implement a limited slip differential.
\note Set centerTarget and centerBias to 1.0 to implement a locked differential.
*/
PxReal centerTarget;
/**
\brief The parameter rate specifies how quickly the ratio of rotational speeds approaches the target rotational speed ratio.
\note strength must be in range [0,PX_VEHICLE_FOUR_WHEEL_DIFF_MAXIMUM_STRENGTH].
\note The ratio of rotational speeds is decremented each update by rate*dt until the ratio is equal to the target ratio.
\note A value of 0 will result in a deactivated limited slip.
\note A value of PX_VEHICLE_FOUR_WHEEL_DIFF_MAXIMUM_STRENGTH will result in instantaneous correction of the rotational speed ratios.
*/
PxReal rate;
PX_FORCE_INLINE void setToDefault()
{
PxVehicleMultiWheelDriveDifferentialParams::setToDefault();
frontBias = 0.0f;
rearBias = 0.0f;
centerBias = 0.0f;
}
PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const
{
if (!PxVehicleMultiWheelDriveDifferentialParams::isValid(axleDesc))
return false;
PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) ||
(centerBias > 1.0f &&
frontWheelIds[0] < axleDesc.nbWheels && frontWheelIds[1] < axleDesc.nbWheels &&
rearWheelIds[0] < axleDesc.nbWheels && rearWheelIds[1] < axleDesc.nbWheels),
"PxVehicleFourWheelDriveDifferentialParams:: centreBias is enabled but the frontWheelIds and rearWheelIds are not configured correctly.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) ||
(centerBias > 1.0f &&
frontWheelIds[0] != frontWheelIds[1] && frontWheelIds[0] != rearWheelIds[0] && frontWheelIds[0] != rearWheelIds[1] &&
frontWheelIds[1] != rearWheelIds[0] && frontWheelIds[1] != rearWheelIds[1] &&
rearWheelIds[0] != rearWheelIds[1]),
"PxVehicleFourWheelDriveDifferentialParams:: centreBias is enabled but the frontWheelIds and rearWheelIds are not configured correctly.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) ||
(centerBias > 1.0f &&
torqueRatios[frontWheelIds[0]] != 0.0f && torqueRatios[frontWheelIds[1]] != 0.0f && torqueRatios[rearWheelIds[0]] != 0.0f && torqueRatios[rearWheelIds[1]] != 0.0f),
"PxVehicleFourWheelDriveDifferentialParams:: centreBias is enabled but the front and rear wheels are not connected.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == rearBias) ||
(rearBias > 1.0f && rearWheelIds[0] < axleDesc.nbWheels && rearWheelIds[1] < axleDesc.nbWheels),
"PxVehicleFourWheelDriveDifferentialParams:: rearBias is enabled but the rearWheelIds are not configured correctly.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == rearBias) ||
(rearBias > 1.0f && rearWheelIds[0] != rearWheelIds[1]),
"PxVehicleFourWheelDriveDifferentialParams:: rearBias is enabled but the rearWheelIds are not configured correctly.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) ||
(rearBias > 1.0f && torqueRatios[rearWheelIds[0]] != 0.0f && torqueRatios[rearWheelIds[1]] != 0.0f),
"PxVehicleFourWheelDriveDifferentialParams:: rearBias is enabled but the rear wheels are not connected.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) ||
(frontBias > 1.0f && frontWheelIds[0] < axleDesc.nbWheels && frontWheelIds[1] < axleDesc.nbWheels),
"PxVehicleFourWheelDriveDifferentialParams:: frontBias is enabled but the frontWheelIds are not configured correctly.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) ||
(frontBias > 1.0f && frontWheelIds[0] != frontWheelIds[1]),
"PxVehicleFourWheelDriveDifferentialParams:: frontBias is enabled but the frontWheelIds are not configured correctly.", false);
PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) ||
(frontBias > 1.0f && torqueRatios[frontWheelIds[0]] != 0.0f && frontWheelIds[frontWheelIds[1]]),
"PxVehicleFourWheelDriveDifferentialParams:: frontBias is enabled but the front wheels are not connected.", false);
PX_CHECK_AND_RETURN_VAL(((0.0f == frontBias) && (0.0f == rearBias) && (0.0f == centerBias)) || (rate >= 0.0f),
"PxVehicleFourWheelDriveDifferentialParams:: strength must be greater than or equal to zero", false);
PX_CHECK_AND_RETURN_VAL((0.0f == frontBias) || ((1.0f == frontTarget && 1.0f == rearTarget) || (frontTarget > 1.0f && frontTarget < frontBias)),
"PxVehicleFourWheelDriveDifferentialParams: frontBias is enabled but frontTarget not in range (1.0f, frontBias)", false);
PX_CHECK_AND_RETURN_VAL((0.0f == rearBias) || ((1.0f == rearTarget && 1.0f == rearBias) || (rearTarget > 1.0f && rearTarget < rearBias)),
"PxVehicleFourWheelDriveDifferentialParams: rearBias is enabled but rearTarget not in range (1.0f, rearBias)", false);
PX_CHECK_AND_RETURN_VAL((0.0f == centerBias) || ((1.0f == centerTarget && 1.0f == centerBias) || (centerTarget > 1.0f && centerTarget < centerBias)),
"PxVehicleFourWheelDriveDifferentialParams: centerBias is enabled but centerTarget not in range (1.0f, centerBias)", false);
return true;
}
PX_FORCE_INLINE PxVehicleFourWheelDriveDifferentialParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
PxVehicleFourWheelDriveDifferentialParams r = *this;
static_cast<PxVehicleMultiWheelDriveDifferentialParams&>(r) = PxVehicleMultiWheelDriveDifferentialParams::transformAndScale(srcFrame, trgFrame, srcScale, trgScale);
return r;
}
};
/**
\brief A description of a tank differential.
\note The wheels on a tank may be connected to the differential or not connected to the differential.
\note The wheels on a tank track may be connected to a tank track or not connected to a tank track.
\note Wheels connected to the differential but not to a tank track receive the torque split specified by the
corresponding elements of PxVehicleMultiWheelDriveDifferentialParams::torqueRatios[].
\note Wheels connected to a tank track but not to the differential receive no torque from the engine.
\note Wheels connected to a tank track and to the differential receive the torque split specified by the
corresponding elements of PxVehicleMultiWheelDriveDifferentialParams::torqueRatios[] multiplied by the corresponding
thrust controller value. If the thrust controller has a negative value, the wheels will receive a torque that is negative
with respect to the gearing ratio.
\note The wheels in each tank track have a constraint applied to them to enforce the rule that they all have the same longitudinal speed
at the contact point between the wheel and the tank track.
*/
struct PxVehicleTankDriveDifferentialParams : public PxVehicleMultiWheelDriveDifferentialParams
{
PX_FORCE_INLINE void setToDefault()
{
PxVehicleMultiWheelDriveDifferentialParams::setToDefault();
nbTracks = 0;
}
/**
\brief Add a tank track by specifying the number of wheels along the track and an array of wheel ids specifying each wheel in the tank track.
\param[in] nbWheelsInTrackToAdd is the number of wheels in the track to be added.
\param[in] wheelIdsInTrackToAdd is an array of wheel ids specifying all the wheels in the track to be added.
\param[in] thrustControllerIndex specifies the index of the thrust controller that will be used to control the tank track.
*/
void addTankTrack(const PxU32 nbWheelsInTrackToAdd, const PxU32* const wheelIdsInTrackToAdd, const PxU32 thrustControllerIndex)
{
PxU32 trackToWheelIdsOffset = nbTracks ? trackToWheelIds[nbTracks - 1] + nbWheelsPerTrack[nbTracks - 1] : 0;
PX_ASSERT((trackToWheelIdsOffset + nbWheelsInTrackToAdd) <= PxVehicleLimits::eMAX_NB_WHEELS);
PX_ASSERT(nbTracks < PxVehicleLimits::eMAX_NB_WHEELS);
PX_ASSERT(thrustControllerIndex < 2);
nbWheelsPerTrack[nbTracks] = nbWheelsInTrackToAdd;
thrustIdPerTrack[nbTracks] = thrustControllerIndex;
trackToWheelIds[nbTracks] = trackToWheelIdsOffset;
for (PxU32 i = 0; i < nbWheelsInTrackToAdd; i++)
{
wheelIdsInTrackOrder[trackToWheelIdsOffset + i] = wheelIdsInTrackToAdd[i];
}
nbTracks++;
}
/**
\brief Return the number of tracks.
\return The number of tracks.
@see getNbWheelsInTrack()
*/
PX_FORCE_INLINE PxU32 getNbTracks() const
{
return nbTracks;
}
/**
\brief Return the number of wheels in the ith track.
\param[in] i specifies the track to be queried for its wheel count.
\return The number of wheels in the specified track.
@see getWheelInTrack()
*/
PX_FORCE_INLINE PxU32 getNbWheelsInTrack(const PxU32 i) const
{
return nbWheelsPerTrack[i];
}
/**
\brief Return the array of all wheels in the ith track.
\param[in] i specifies the track to be queried for its wheels.
\return The array of wheels in the specified track.
*/
PX_FORCE_INLINE const PxU32* getWheelsInTrack(const PxU32 i) const
{
return (wheelIdsInTrackOrder + trackToWheelIds[i]);
}
/**
\brief Return the wheel id of the jth wheel in the ith track.
\param[in] j specifies that the wheel id to be returned is the jth wheel in the list of wheels on the specified track.
\param[in] i specifies the track to be queried.
\return The wheel id of the jth wheel in the ith track.
@see getNbWheelsInTrack()
*/
PX_FORCE_INLINE PxU32 getWheelInTrack(const PxU32 j, const PxU32 i) const
{
return wheelIdsInTrackOrder[trackToWheelIds[i] + j];
}
/**
\brief Return the index of the thrust controller that will control a specified track.
\param[in] i specifies the track to be queried for its thrust controller index
\return The index of the thrust controller that will control the ith track.
*/
PX_FORCE_INLINE PxU32 getThrustControllerIndex(const PxU32 i) const
{
return thrustIdPerTrack[i];
}
PX_FORCE_INLINE PxVehicleTankDriveDifferentialParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
PxVehicleTankDriveDifferentialParams r = *this;
static_cast<PxVehicleMultiWheelDriveDifferentialParams&>(r) = PxVehicleMultiWheelDriveDifferentialParams::transformAndScale(srcFrame, trgFrame, srcScale, trgScale);
return r;
}
PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const
{
if (!PxVehicleMultiWheelDriveDifferentialParams::isValid(axleDesc))
return false;
PX_CHECK_AND_RETURN_VAL(nbTracks <= PxVehicleLimits::eMAX_NB_WHEELS, "PxVehicleTankDriveDifferentialParams.nbTracks must not exceed PxVehicleLimits::eMAX_NB_WHEELS", false);
const PxU32 nbWheelsInTracksSize = nbTracks ? trackToWheelIds[nbTracks - 1] + nbWheelsPerTrack[nbTracks - 1] : 0;
PX_UNUSED(nbWheelsInTracksSize);
PX_CHECK_AND_RETURN_VAL(nbWheelsInTracksSize <= PxVehicleLimits::eMAX_NB_WHEELS, "PxVehicleTankDriveDifferentialParams.nbWheelsInTracks must not exceed PxVehicleLimits::eMAX_NB_WHEELS", false);
for (PxU32 i = 0; i < nbTracks; i++)
{
PX_CHECK_AND_RETURN_VAL(thrustIdPerTrack[i] < 2, "PxVehicleTankDriveDifferentialParams.thrustId must be less than 2", false);
}
for (PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PxU32 count = 0;
for (PxU32 j = 0; j < nbTracks; j++)
{
const PxU32 nbWheels = getNbWheelsInTrack(j);
const PxU32* wheelIds = getWheelsInTrack(j);
for (PxU32 k = 0; k < nbWheels; k++)
{
if (wheelIds[k] == wheelId)
count++;
}
}
PX_CHECK_AND_RETURN_VAL(count <= 1, "PxVehicleTankDriveDifferentialParams - a wheel cannot be in more than one tank track", false);
}
return true;
}
PxU32 nbTracks; //!< The number of tracks
PxU32 thrustIdPerTrack[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The id of the thrust that will control the track. Must have value 0 or 1.
PxU32 nbWheelsPerTrack[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The number of wheels in each track
PxU32 trackToWheelIds[PxVehicleLimits::eMAX_NB_WHEELS]; //!< The list of wheel ids for the ith tank track begins at wheelIdsInTrackOrder[trackToWheelIds[i]]
PxU32 wheelIdsInTrackOrder[PxVehicleLimits::eMAX_NB_WHEELS];//!< The list of all wheel ids in all tracks
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 45,498 | C | 44.59018 | 310 | 0.763814 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/pvd/PxVehiclePvdFunctions.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
/** \addtogroup vehicle2
@{
*/
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/braking/PxVehicleBrakingParams.h"
#include "vehicle2/commands/PxVehicleCommandStates.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/steering/PxVehicleSteeringParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "vehicle2/tire/PxVehicleTireParams.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
class OmniPvdWriter;
namespace physx
{
class PxAllocatorCallback;
namespace vehicle2
{
struct PxVehiclePvdAttributeHandles;
struct PxVehiclePvdObjectHandles;
} // namespace vehicle2
} // namespace physx
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
/**
\brief Create object instances in omnipvd that will be used to reflect the parameters and state of the rigid body of a vehicle instance.
Handles to the created object instances will be stored in a PxVehiclePvdObjectHandles instance.
\param[in] rbodyParams describes the parameters of the vehicle's rigid body.
\param[in] rbodyState describes the state of the vehicle's rigid body.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If rbodyParams is NULL, omnipvd will not reflect rigid body parameters.
\note If rbodyState is NULL, omnipvd will not reflect rigid body state.
\note PxVehiclePvdRigidBodyRegister should be called once for each vehicle instance.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdRigidBodyWrite
*/
void PxVehiclePvdRigidBodyRegister
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write the parameters and state of the rigid body of a vehicle instance to omnipvd.
\param[in] rbodyParams describes the parameters of the vehicle's rigid body.
\param[in] rbodyState describes the state of the vehicle's rigid body.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If rbodyParams is NULL but a non-NULL value was used in PxVehiclePvdRigidBodyRegister(), the rigid body parameters will not be updated in omnipvd.
\note If rbodyState is NULL but a non-NULL value was used in PxVehiclePvdRigidBodyRegister(), the rigid body state will not be updated in omnipvd.
\note omniWriter must be the same instance used in PxVehiclePvdRigidBodyRegister().
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdRigidBodyRegister
*/
void PxVehiclePvdRigidBodyWrite
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register object instances in omnipvd that will be used to reflect the suspension state calculation parameters of a vehicle instance.
\param[in] suspStateCalcParams describes parameters used to calculate suspension state.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If suspStateCalcParams is NULL, omnipvd will not reflect the suspension state calculation parameters.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdSuspensionStateCalculationParamsWrite
*/
void PxVehiclePvdSuspensionStateCalculationParamsRegister
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write the parameters and state of the rigid body of a vehicle instance to omnipvd.
\param[in] suspStateCalcParams describes parameters used to calculate suspension state.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If suspStateCalcParams is NULL but a non-NULL value was used in void PxVehiclePvdSuspensionStateCalculationParamsRegister(),
the suspension state calculation parameters will not be updated in omnipvd.
\note omniWriter must be the same instance used in PxVehiclePvdSuspensionStateCalculationParamsRegister().
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdSuspensionStateCalculationParamsRegister
*/
void PxVehiclePvdSuspensionStateCalculationParamsWrite
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register object instances in omnipvd that will be used to reflect the brake and steer command response parameters of a vehicle instance.
\param[in] brakeResponseParams is an array of brake command response parameters.
\param[in] steerResponseParams describes the steer command response parameters.
\param[in] ackermannParams defines the Ackermann steer correction.
\param[in] brakeResponseStates is an array of brake responses torqyes,
\param[in] steerResponseStates is an array of steer response angles.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If brakeResponseParams is empty, omnipvd will not reflect any brake command response parameters.
\note If steerResponseParams is NULL, omnipvd will not reflect the steer command response parameters.
\note If ackermannParams is NULL, omnipvd will not reflect any Ackermann steer correction parameters.
\note If brakeResponseStates is empty, omnipvd will not reflect any brake command response state.
\note If steerResponseStates is empty, omnipvd will not reflect any steer command response state.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdCommandResponseWrite
*/
void PxVehiclePvdCommandResponseRegister
(const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write brake and steer command response parameters to omnipvd.
\param[in] axleDesc is a description of the wheels and axles of a vehicle.
\param[in] brakeResponseParams is an array of brake command response parameters.
\param[in] steerResponseParams describes the steer command response parameters.
\param[in] ackermannParams defines the Ackermann steer correction.
\param[in] brakeResponseStates is an array of brake response torques.
\param[in] steerResponseStates is an array of steer response angles.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If brakeResponseParams is empty but a non-empty array was used in PxVehiclePvdCommandResponseRegister(),
the brake command response parameters will not be updated in omnipvd.
\note If steerResponseParams is non-NULL but a NULL value was used in PxVehiclePvdCommandResponseRegister(),
the steer command parameters will not be updated in omnipvd.
\note If ackermannParams is non-NULL but a NULL value was used in PxVehiclePvdCommandResponseRegister(),
the Ackermann steer correction parameters will not be updated in omnipvd.
\note If brakeResponseStates is empty but a non-empty array was used in PxVehiclePvdCommandResponseRegister(),
the brake response states will not be updated in omnipvd.
\note If steerResponseStates is empty but a non-empty array was used in PxVehiclePvdCommandResponseRegister(),
the steer response states will not be updated in omnipvd.
\note omniWriter must be the same instance used in PxVehiclePvdCommandResponseRegister().
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdCommandResponseRegister
*/
void PxVehiclePvdCommandResponseWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register object instances in omnipvd that will be used to reflect wheel attachment data such as tires, suspensions and wheels.
\param[in] axleDesc is a description of the wheels and axles of a vehicle.
\param[in] wheelParams is an array of wheel parameters.
\param[in] wheelActuationStates is an array of wheel actuation states.
\param[in] wheelRigidBody1dStates is an array of wheel rigid body states.
\param[in] wheelLocalPoses is an array of wheel local poses.
\param[in] roadGeometryStates is an array of road geometry states.
\param[in] suspParams is an array of suspension parameters.
\param[in] suspCompParams is an array of suspension compliance parameters.
\param[in] suspForceParams is an array of suspension force parameters.
\param[in] suspStates is an array of suspension states.
\param[in] suspCompStates is an array of suspension compliance states.
\param[in] suspForces is an array of suspension forces.
\param[in] tireForceParams is an array of tire force parameters.
\param[in] tireDirectionStates is an array of tire direction states.
\param[in] tireSpeedStates is an array of tire speed states.
\param[in] tireSlipStates is an array of tire slip states.
\param[in] tireStickyStates is an array of tire sticky states.
\param[in] tireGripStates is an array of tire grip states.
\param[in] tireCamberStates is an array of tire camber states.
\param[in] tireForces is an array of tire forces.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If any array is empty, the corresponding data will not be reflected in omnipvd.
\note Each array must either be empty or contain an entry for each wheel present in axleDesc.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdWheelAttachmentsWrite
*/
void PxVehiclePvdWheelAttachmentsRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<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& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write wheel attachment data such as tire, suspension and wheel data to omnipvd.
\param[in] axleDesc is a description of the wheels and axles of a vehicle.
\param[in] wheelParams is an array of wheel parameters.
\param[in] wheelActuationStates is an array of wheel actuation states.
\param[in] wheelRigidBody1dStates is an array of wheel rigid body states.
\param[in] wheelLocalPoses is an array of wheel local poses.
\param[in] roadGeometryStates is an array of road geometry states.
\param[in] suspParams is an array of suspension parameters.
\param[in] suspCompParams is an array of suspension compliance parameters.
\param[in] suspForceParams is an array of suspension force parameters.
\param[in] suspStates is an array of suspension states.
\param[in] suspCompStates is an array of suspension compliance states.
\param[in] suspForces is an array of suspension forces.
\param[in] tireForceParams is an array of tire force parameters.
\param[in] tireDirectionStates is an array of tire direction states.
\param[in] tireSpeedStates is an array of tire speed states.
\param[in] tireSlipStates is an array of tire slip states.
\param[in] tireStickyStates is an array of tire sticky states.
\param[in] tireGripStates is an array of tire grip states.
\param[in] tireCamberStates is an array of tire camber states.
\param[in] tireForces is an array of tire forces.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If any array is empty but the corresponding argument in PxVehiclePvdWheelAttachmentsRegister was not empty, the corresponding data will not be updated in omnipvd.
\note Each array must either be empty or contain an entry for each wheel present in axleDesc.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdWheelAttachmentsRegister
*/
void PxVehiclePvdWheelAttachmentsWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<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& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register object instances in omnipvd that will be used to reflect the antiroll bars of a vehicle instance.
\param[in] antiRollForceParams is an array of antiroll parameters.
\param[in] antiRollTorque describes the instantaneous accumulated torque from all antiroll bas.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If antiRollForceParams is empty, the corresponding data will not be reflected in omnipvd.
\note If antiRollTorque is NULL, the corresponding data will not be reflected in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdAntiRollsWrite
*/
void PxVehiclePvdAntiRollsRegister
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams, const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write antiroll data to omnipvd.
\param[in] antiRollForceParams is an array of antiroll parameters.
\param[in] antiRollTorque describes the instantaneous accumulated torque from all antiroll bas.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If antiRollForceParams is empty but the corresponding argument was not empty, the corresponding data will not be updated in omnipvd.
\note If antiRollTorque is NULL but the corresponding argument was not NULL, the corresponding data will not be updated in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdAntiRollsRegister
*/
void PxVehiclePvdAntiRollsWrite
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams, const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register object instances in omnipvd that will be used to reflect the direct drivetrain of a vehicle instance.
\param[in] commandState describes the control values applied to the vehicle.
\param[in] transmissionCommandState describes the state of the direct drive transmission.
\param[in] directDriveThrottleResponseParams describes the vehicle's torque response to a throttle command.
\param[in] directDriveThrottleResponseState is the instantaneous torque response of each wheel to a throttle command.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If commandState is NULL, the corresponding data will not be reflected in omnipvd.
\note If transmissionCommandState is NULL, the corresponding data will not be reflected in omnipvd.
\note If directDriveThrottleResponseParams is NULL, the corresponding data will not be reflected in omnipvd.
\note If directDriveThrottleResponseState is empty, the corresponding data will not be reflected in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdDirectDrivetrainWrite
*/
void PxVehiclePvdDirectDrivetrainRegister
(const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionCommandState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write direct drivetrain data to omnipvd.
\param[in] axleDesc is a description of the wheels and axles of a vehicle.
\param[in] commandState describes the control values applied to the vehicle.
\param[in] transmissionCommandState describes the state of the direct drive transmission.
\param[in] directDriveThrottleResponseParams describes the vehicle's torque response to a throttle command.
\param[in] directDriveThrottleResponseState is the instantaneous torque response of each wheel to a throttle command.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If commandState is NULL but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not NULL, the corresponding data will not be updated in omnipvd.
\note If transmissionCommandState is NULL but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not NULL, the corresponding data will not be updated in omnipvd.
\note If directDriveThrottleResponseParams is NULL but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not NULL, the corresponding data will not be updated in omnipvd.
\note If directDriveThrottleResponseState is empty but the corresponding entry in PxVehiclePvdDirectDrivetrainRegister() was not empty, the corresponding data will not be updated in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdDirectDrivetrainRegister
*/
void PxVehiclePvdDirectDrivetrainWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionCommandState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register object instances in omnipvd that will be used to reflect the engine drivetrain of a vehicle instance.
\param[in] commandState describes the control values applied to the vehicle.
\param[in] engineDriveTransmissionCommandState describes the state of the engine drive transmission.
\param[in] tankDriveTransmissionCommandState describes the state of the tank drive transmission.
\param[in] clutchResponseParams describes the vehicle's response to a clutch command.
\param[in] clutchParams describes the vehicle's clutch.
\param[in] engineParams describes the engine.
\param[in] gearboxParams describes the gearbox.
\param[in] autoboxParams describes the automatic gearbox.
\param[in] multiWheelDiffParams describes a multiwheel differential without limited slip compensation.
\param[in] fourWheelDiffPrams describes a differential that delivers torque to four drive wheels with limited slip compensation.
\param[in] tankDiffParams describes the operation of the tank differential.
\param[in] clutchResponseState is the instantaneous reponse of the clutch to a clutch command.
\param[in] throttleResponseState is the instantaneous response to a throttle command.
\param[in] engineState is the instantaneous state of the engine.
\param[in] gearboxState is the instantaneous state of the gearbox.
\param[in] autoboxState is the instantaneous state of the automatic gearbox.
\param[in] diffState is the instantaneous state of the differential.
\param[in] clutchSlipState is the instantaneous slip recorded at the clutch.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If any pointer is NULL, the corresponding data will not be reflected in omnipvd.
\note At most one of engineDriveTransmissionCommandState and tankDriveTransmissionCommandState is expected to be non-NULL.
\note At most one of multiWheelDiffParams, fourWheelDiffParams and tankDiffParams is expected to be non-NULL.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdEngineDrivetrainWrite
*/
void PxVehiclePvdEngineDrivetrainRegister
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParams,
const PxVehicleEngineParams* engineParams,
const PxVehicleGearboxParams* gearboxParams,
const PxVehicleAutoboxParams* autoboxParams,
const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams,
const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffPrams,
const PxVehicleTankDriveDifferentialParams* tankDiffParams,
const PxVehicleClutchCommandResponseState* clutchResponseState,
const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState,
const PxVehicleEngineState* engineState,
const PxVehicleGearboxState* gearboxState,
const PxVehicleAutoboxState* autoboxState,
const PxVehicleDifferentialState* diffState,
const PxVehicleClutchSlipState* clutchSlipState,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write engine drivetrain data of a vehicle instance to omnipvd.
\param[in] commandState describes the control values applied to the vehicle.
\param[in] engineDriveTransmissionCommandState describes the state of the engine drive transmission.
\param[in] tankDriveTransmissionCommandState describes the state of the tank drive transmission.
\param[in] clutchResponseParams describes the vehicle's response to a clutch command.
\param[in] clutchParams describes the vehicle's clutch.
\param[in] engineParams describes the engine.
\param[in] gearboxParams describes the gearbox.
\param[in] autoboxParams describes the automatic gearbox.
\param[in] multiWheelDiffParams describes a multiwheel differential without limited slip compensation.
\param[in] fourWheelDiffParams describes a differential that delivers torque to four drive wheels with limited slip compensation.
\param[in] tankDiffParams describes the operation of the tank differential.
\param[in] clutchResponseState is the instantaneous reponse of the clutch to a clutch command.
\param[in] throttleResponseState is the instantaneous response to a throttle command.
\param[in] engineState is the instantaneous state of the engine.
\param[in] gearboxState is the instantaneous state of the gearbox.
\param[in] autoboxState is the instantaneous state of the automatic gearbox.
\param[in] diffState is the instantaneous state of the differential.
\param[in] clutchSlipState is the instantaneous slip recorded at the clutch.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If any pointer is NULL and the corresponding argument in PxVehiclePvdEngineDrivetrainRegister() was not NULL, the corresponding data will not be reflected in omnipvd.
\note At most one of engineDriveTransmissionCommandState and tankDriveTransmissionCommandState is expected to be non-NULL.
\note At most one of multiWheelDiffParams, fourWheelDiffParams and tankDiffParams is expected to be non-NULL.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdEngineDrivetrainRegister
*/
void PxVehiclePvdEngineDrivetrainWrite
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParams,
const PxVehicleEngineParams* engineParams,
const PxVehicleGearboxParams* gearboxParams,
const PxVehicleAutoboxParams* autoboxParams,
const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams,
const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffParams,
const PxVehicleTankDriveDifferentialParams* tankDiffParams,
const PxVehicleClutchCommandResponseState* clutchResponseState,
const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState,
const PxVehicleEngineState* engineState,
const PxVehicleGearboxState* gearboxState,
const PxVehicleAutoboxState* autoboxState,
const PxVehicleDifferentialState* diffState,
const PxVehicleClutchSlipState* clutchSlipState,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register per wheel attachment data that involves the vehicle's integration with a PhysX scene.
\param[in] axleDesc is a description of the wheels and axles of a vehicle.
\param[in] physxSuspLimitConstraintParams describes the method used by PhysX to enforce suspension travel limits.
\param[in] physxMaterialFrictionParams describes the friction response of each wheel to a set of PxMaterial instances.
\param[in] physxActor describes the PxRigidActor and PxShape instances that are used to represent the vehicle's rigid body and wheel shapes in PhysX.
\param[in] physxRoadGeometryQueryParams describes the physx scene query method used to place each wheel on the ground.
\param[in] physxRoadGeomState is an array of per wheel physx scene query results.
\param[in] physxConstraintStates is an array of constraints states used by PhysX to enforce sticky tire and suspension travel limit constraints.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If any array is empty, the corresponding data will not be reflected in omnipvd.
\note If physxActor is NULL, the corresponding data will not be reflected in omnipvd.
\note If physxRoadGeometryQueryParams is NULL, the corresponding data will not be reflected in omnipvd.
\note Each array must either be empty or contain an entry for each wheel present in axleDesc.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdPhysXWheelAttachmentWrite
*/
void PxVehiclePvdPhysXWheelAttachmentRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeometryQueryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomState,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write to omnipvd the per wheel attachment data that involves the vehicle's integration with a PhysX scene.
\param[in] axleDesc is a description of the wheels and axles of a vehicle.
\param[in] physxSuspLimitConstraintParams describes the method used by PhysX to enforce suspension travel limits.
\param[in] physxMaterialFrictionParams describes the friction response of each wheel to a set of PxMaterial instances.
\param[in] physxActor describes the PxShape instances that are used to represent the vehicle's wheel shapes in PhysX.
\param[in] physxRoadGeometryQueryParams describes the physx scene query method used to place each wheel on the ground.
\param[in] physxRoadGeomState is an array of per wheel physx scene query results.
\param[in] physxConstraintStates is an array of constraints states used by PhysX to enforce sticky tire and suspension travel limit constraints.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If any array is empty but the corresponding array in PxVehiclePvdPhysXWheelAttachmentRegister() was not empty, the corresponding data will not be updated in omnipvd.
\note If physxActor is NULL but the corresponding argument in PxVehiclePvdPhysXWheelAttachmentRegister was not NULL, the corresponding data will not be reflected in omnipvd.
\note If physxRoadGeometryQueryParams is NULL but the corresponding argument in PxVehiclePvdPhysXWheelAttachmentRegister was not NULL, the corresponding data will not be reflected in omnipvd.
\note Each array must either be empty or contain an entry for each wheel present in axleDesc.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdPhysXWheelAttachmentWrite
*/
void PxVehiclePvdPhysXWheelAttachmentWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeometryQueryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomState,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register the PxRigidActor instance that represents the vehicle's rigid body in a PhysX scene.
\param[in] physxActor describes the PxRigidActor instance that is used to represent the vehicle's rigid body in PhysX.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If physxActor is NULL, the corresponding data will not be reflected in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdPhysXRigidActorWrite
*/
void PxVehiclePvdPhysXRigidActorRegister
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write the PxRigidActor instance to omnipvd.
\param[in] physxActor describes the PxRigidActor instance that is used to represent the vehicle's rigid body in PhysX.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If physxActor is NULL and the corresponding argument in PxVehiclePvdPhysXRigidActorRegister was not NULL, the corresponding data will not be updated in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdPhysXRigidActorRegister
*/
void PxVehiclePvdPhysXRigidActorWrite
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Register the PhysX related steer state class.
\param[in] physxSteerState describes the PxVehiclePhysXSteerState instance that holds steer related state information.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If physxSteerState is NULL, the corresponding data will not be reflected in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdPhysXSteerStateWrite
*/
void PxVehiclePvdPhysXSteerStateRegister
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
/**
\brief Write the PxVehiclePhysXSteerState instance to omnipvd.
\param[in] physxSteerState describes the PxVehiclePhysXSteerState instance that holds steer related state information.
\param[in] attributeHandles contains a general description of vehicle parameters and states that will be reflected in omnipvd.
\param[in] objectHandles contains unique handles for the parameters and states of each vehicle instance.
\param[in] omniWriter is an OmniPvdWriter instance used to communicate state and parameter data to omnipvd.
\note If physxSteerState is NULL and the corresponding argument in PxVehiclePvdPhysXSteerStateRegister was not NULL, the corresponding data will not be updated in omnipvd.
@see PxVehiclePvdAttributesCreate
@see PxVehiclePvdObjectCreate
@see PxVehiclePvdPhysXSteerStateRegister
*/
void PxVehiclePvdPhysXSteerStateWrite
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& attributeHandles,
const PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 42,550 | C | 65.589984 | 192 | 0.842374 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/pvd/PxVehiclePvdHelpers.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxSimpleTypes.h"
class OmniPvdWriter;
namespace physx
{
class PxAllocatorCallback;
namespace vehicle2
{
struct PxVehiclePvdAttributeHandles;
struct PxVehiclePvdObjectHandles;
}
}
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
/**
\brief Create the attribute handles necessary to reflect vehicles in omnipvd.
\param[in] allocator is used to allocate the memory used to store the attribute handles.
\param[in] omniWriter is used to register the attribute handles with omnipvd.
@see PxVehicleSimulationContext
@see PxVehiclePVDComponent
@see PxVehiclePvdAttributesRelease
*/
PxVehiclePvdAttributeHandles* PxVehiclePvdAttributesCreate
(PxAllocatorCallback& allocator, OmniPvdWriter& omniWriter);
/**
\brief Destory the attribute handles created by PxVehiclePvdAttributesCreate().
\param[in] allocator must be the instance used by PxVehiclePvdObjectCreate().
\param[in] attributeHandles is the PxVehiclePvdAttributeHandles created by PxVehiclePvdAttributesCreate().
@see PxVehiclePvdAttributesCreate
*/
void PxVehiclePvdAttributesRelease
(PxAllocatorCallback& allocator, PxVehiclePvdAttributeHandles& attributeHandles);
/**
\brief Create omnipvd objects that will be used to reflect an individual veicle in omnipvd.
\param[in] nbWheels must be greater than or equal to the number of wheels on the vehicle.
\param[in] nbAntirolls must be greater than or equal to the number of antiroll bars on the vehicle.
\param[in] maxNbPhysxMaterialFrictions must be greater than or equal to the number of PxPhysXMaterialFriction instances associated with any wheel of the vehicle.
\param[in] contextHandle is typically used to associated vehicles with a particular scene or group.
\param[in] allocator is used to allocate the memory used to store handles to the created omnipvd objects.
\note PxVehiclePvdObjectCreate() must be called after PxVehiclePvdAttributesCreate().
@see PxVehicleAxleDescription
@see PxVehicleAntiRollForceParams
@see PxVehiclePhysXMaterialFrictionParams
@see PxVehiclePVDComponent
@see PxVehiclePvdAttributesCreate
*/
PxVehiclePvdObjectHandles* PxVehiclePvdObjectCreate
(const PxU32 nbWheels, const PxU32 nbAntirolls, const PxU32 maxNbPhysxMaterialFrictions,
const PxU64 contextHandle, PxAllocatorCallback& allocator);
/**
\brief Destroy the PxVehiclePvdObjectHandles instance created by PxVehiclePvdObjectCreate().
\param[in] omniWriter is used to register the attribute handles with omnipvd.
\param[in] allocator must be the instance used by PxVehiclePvdObjectCreate().
\param[in] objectHandles is the PxVehiclePvdObjectHandles that was created by PxVehiclePvdObjectCreate().
*/
void PxVehiclePvdObjectRelease
(OmniPvdWriter& omniWriter, PxAllocatorCallback& allocator, PxVehiclePvdObjectHandles& objectHandles);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 4,592 | C | 41.527777 | 161 | 0.802918 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/pvd/PxVehiclePvdComponents.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
/** \addtogroup vehicle2
@{
*/
#include "vehicle2/PxVehicleComponent.h"
#include "vehicle2/PxVehicleParams.h"
#include "PxVehiclePvdFunctions.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
#define VEHICLE_FLOAT_ARRAY_DATA(b) PxVehicleArrayData<PxReal> b; b.setEmpty();
#define VEHICLE_ARRAY_DATA(a, b) PxVehicleArrayData<const a> b; b.setEmpty();
#define VEHICLE_SIZED_ARRAY_DATA(a, b) PxVehicleSizedArrayData<const a> b; b.setEmpty();
class PxVehiclePVDComponent : public PxVehicleComponent
{
public:
PxVehiclePVDComponent() : PxVehicleComponent() , firstTime(true) {}
virtual ~PxVehiclePVDComponent() {}
virtual void getDataForPVDComponent(
const PxVehicleAxleDescription*& axleDescription,
const PxVehicleRigidBodyParams*& rbodyParams, const PxVehicleRigidBodyState*& rbodyState,
const PxVehicleSuspensionStateCalculationParams*& suspStateCalcParams,
PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams*& steerResponseParams,
const PxVehicleAckermannParams*& ackermannParams,
PxVehicleArrayData<PxReal>& brakeResponseStates,
PxVehicleArrayData<PxReal>& steerResponseStates,
PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeomStates,
PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspCompParams,
PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque*& antiRollTorque,
const PxVehicleCommandState*& commandState,
const PxVehicleDirectDriveThrottleCommandResponseParams*& directDriveThrottleResponseParams,
const PxVehicleDirectDriveTransmissionCommandState*& directDriveTransmissionState,
PxVehicleArrayData<PxReal>& directDrivethrottleResponseState,
const PxVehicleClutchCommandResponseParams*& clutchResponseParams,
const PxVehicleClutchParams*& clutchParams,
const PxVehicleEngineParams*& engineParams,
const PxVehicleGearboxParams*& gearboxParams,
const PxVehicleAutoboxParams*& autoboxParams,
const PxVehicleMultiWheelDriveDifferentialParams*& multiWheelDiffParams,
const PxVehicleFourWheelDriveDifferentialParams*& fourWheelDiffParams,
const PxVehicleTankDriveDifferentialParams*& tankDiffParams,
const PxVehicleEngineDriveTransmissionCommandState*& engineDriveTransmissionState,
const PxVehicleTankDriveTransmissionCommandState*& tankDriveTransmissionState,
const PxVehicleClutchCommandResponseState*& clutchResponseState,
const PxVehicleEngineDriveThrottleCommandResponseState*& engineDriveThrottleResponseState,
const PxVehicleEngineState*& engineState,
const PxVehicleGearboxState*& gearboxState,
const PxVehicleAutoboxState*& autoboxState,
const PxVehicleDifferentialState*& diffState,
const PxVehicleClutchSlipState*& clutchSlipState,
PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxConstraintParams,
PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor*& physxActor,
const PxVehiclePhysXRoadGeometryQueryParams*& physxRoadGeomQryParams,
PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomStates,
PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePhysXSteerState*& physxSteerState,
PxVehiclePvdObjectHandles*& objectHandles) = 0;
virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context)
{
PX_UNUSED(dt);
PX_UNUSED(context);
OmniPvdWriter* pvdWriter = context.pvdContext.writer;
if(!context.pvdContext.attributeHandles || !pvdWriter)
return true;
const PxVehicleAxleDescription* axleDesc = NULL;
const PxVehicleRigidBodyParams* rbodyParams = NULL;
const PxVehicleRigidBodyState* rbodyState = NULL;
const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams = NULL;
VEHICLE_SIZED_ARRAY_DATA(PxVehicleBrakeCommandResponseParams, brakeResponseParams);
const PxVehicleSteerCommandResponseParams* steerResponseParams = NULL;
const PxVehicleAckermannParams* ackermannParams = NULL;
VEHICLE_FLOAT_ARRAY_DATA(brakeResponseStates);
VEHICLE_FLOAT_ARRAY_DATA(steerResponseStates);
VEHICLE_ARRAY_DATA(PxVehicleWheelParams, wheelParams);
VEHICLE_ARRAY_DATA(PxVehicleWheelActuationState, wheelActuationStates);
VEHICLE_ARRAY_DATA(PxVehicleWheelRigidBody1dState, wheelRigidBody1dStates);
VEHICLE_ARRAY_DATA(PxVehicleWheelLocalPose, wheelLocalPoses);
VEHICLE_ARRAY_DATA(PxVehicleRoadGeometryState, roadGeomStates);
VEHICLE_ARRAY_DATA(PxVehicleSuspensionParams, suspParams);
VEHICLE_ARRAY_DATA(PxVehicleSuspensionComplianceParams, suspComplianceParams);
VEHICLE_ARRAY_DATA(PxVehicleSuspensionForceParams, suspForceParams);
VEHICLE_ARRAY_DATA(PxVehicleSuspensionState, suspStates);
VEHICLE_ARRAY_DATA(PxVehicleSuspensionComplianceState, suspComplianceStates);
VEHICLE_ARRAY_DATA(PxVehicleSuspensionForce, suspForces);
VEHICLE_ARRAY_DATA(PxVehicleTireForceParams, tireForceParams);
VEHICLE_ARRAY_DATA(PxVehicleTireDirectionState, tireDirectionStates);
VEHICLE_ARRAY_DATA(PxVehicleTireSpeedState, tireSpeedStates);
VEHICLE_ARRAY_DATA(PxVehicleTireSlipState, tireSlipStates);
VEHICLE_ARRAY_DATA(PxVehicleTireStickyState, tireStickyStates);
VEHICLE_ARRAY_DATA(PxVehicleTireGripState, tireGripStates);
VEHICLE_ARRAY_DATA(PxVehicleTireCamberAngleState, tireCamberStates);
VEHICLE_ARRAY_DATA(PxVehicleTireForce, tireForces);
VEHICLE_SIZED_ARRAY_DATA(PxVehicleAntiRollForceParams, antiRollParams);
const PxVehicleAntiRollTorque* antiRollTorque = NULL;
const PxVehicleCommandState* commandState = NULL;
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams = NULL;
const PxVehicleDirectDriveTransmissionCommandState* directDriveTransmissionState = NULL;
VEHICLE_FLOAT_ARRAY_DATA(directDrivethrottleResponseState);
const PxVehicleClutchCommandResponseParams* clutchResponseParams = NULL;
const PxVehicleClutchParams* clutchParams = NULL;
const PxVehicleEngineParams* engineParams = NULL;
const PxVehicleGearboxParams* gearboxParams = NULL;
const PxVehicleAutoboxParams* autoboxParams = NULL;
const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams = NULL;
const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffParams = NULL;
const PxVehicleTankDriveDifferentialParams* tankDiffParams = NULL;
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState = NULL;
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState = NULL;
const PxVehicleClutchCommandResponseState* clutchResponseState = NULL;
const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState = NULL;
const PxVehicleEngineState* engineState = NULL;
const PxVehicleGearboxState* gearboxState = NULL;
const PxVehicleAutoboxState* autoboxState = NULL;
const PxVehicleDifferentialState* diffState = NULL;
const PxVehicleClutchSlipState* clutchSlipState = NULL;
VEHICLE_ARRAY_DATA(PxVehiclePhysXSuspensionLimitConstraintParams, physxConstraintParams);
VEHICLE_ARRAY_DATA(PxVehiclePhysXMaterialFrictionParams, physxMaterialFrictionParams);
const PxVehiclePhysXActor* physxActor = NULL;
const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams = NULL;
VEHICLE_ARRAY_DATA(PxVehiclePhysXRoadGeometryQueryState, physxRoadGeomStates);
VEHICLE_ARRAY_DATA(PxVehiclePhysXConstraintState, physxConstraintStates);
const PxVehiclePhysXSteerState* physxSteerState = NULL;
PxVehiclePvdObjectHandles* omniPvdObjectHandles = NULL;
getDataForPVDComponent(
axleDesc,
rbodyParams, rbodyState,
suspStateCalcParams,
brakeResponseParams, steerResponseParams, ackermannParams,
brakeResponseStates, steerResponseStates,
wheelParams,
wheelActuationStates, wheelRigidBody1dStates, wheelLocalPoses,
roadGeomStates,
suspParams, suspComplianceParams, suspForceParams,
suspStates, suspComplianceStates,
suspForces,
tireForceParams,
tireDirectionStates, tireSpeedStates, tireSlipStates, tireStickyStates, tireGripStates, tireCamberStates,
tireForces,
antiRollParams, antiRollTorque,
commandState,
directDriveThrottleResponseParams, directDriveTransmissionState, directDrivethrottleResponseState,
clutchResponseParams, clutchParams, engineParams, gearboxParams, autoboxParams,
multiWheelDiffParams, fourWheelDiffParams, tankDiffParams,
engineDriveTransmissionCommandState, tankDriveTransmissionCommandState,
clutchResponseState, throttleResponseState, engineState, gearboxState, autoboxState, diffState, clutchSlipState,
physxConstraintParams, physxMaterialFrictionParams,
physxActor, physxRoadGeomQryParams, physxRoadGeomStates, physxConstraintStates, physxSteerState,
omniPvdObjectHandles);
if(!omniPvdObjectHandles)
return true;
if(firstTime)
{
PxVehiclePvdRigidBodyRegister(
rbodyParams, rbodyState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdSuspensionStateCalculationParamsRegister(
suspStateCalcParams,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdCommandResponseRegister(
brakeResponseParams, steerResponseParams, ackermannParams,
brakeResponseStates, steerResponseStates,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdWheelAttachmentsRegister(
*axleDesc,
wheelParams, wheelActuationStates, wheelRigidBody1dStates, wheelLocalPoses,
roadGeomStates,
suspParams, suspComplianceParams, suspForceParams, suspStates, suspComplianceStates,
suspForces,
tireForceParams,
tireDirectionStates, tireSpeedStates, tireSlipStates, tireStickyStates, tireGripStates, tireCamberStates,
tireForces,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdAntiRollsRegister(
antiRollParams, antiRollTorque,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
if (engineParams)
{
PxVehiclePvdEngineDrivetrainRegister(
commandState, engineDriveTransmissionCommandState, tankDriveTransmissionCommandState,
clutchResponseParams, clutchParams, engineParams, gearboxParams, autoboxParams,
multiWheelDiffParams, fourWheelDiffParams, tankDiffParams,
clutchResponseState, throttleResponseState, engineState, gearboxState, autoboxState, diffState, clutchSlipState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
}
else
{
PxVehiclePvdDirectDrivetrainRegister(
commandState, directDriveTransmissionState,
directDriveThrottleResponseParams,
directDrivethrottleResponseState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
}
PxVehiclePvdPhysXWheelAttachmentRegister(
*axleDesc,
physxConstraintParams, physxMaterialFrictionParams,
physxActor, physxRoadGeomQryParams, physxRoadGeomStates, physxConstraintStates,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdPhysXRigidActorRegister(
physxActor,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdPhysXSteerStateRegister(
physxSteerState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
firstTime = false;
}
PxVehiclePvdRigidBodyWrite(
rbodyParams, rbodyState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdSuspensionStateCalculationParamsWrite(
suspStateCalcParams,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdCommandResponseWrite(
*axleDesc, brakeResponseParams, steerResponseParams, ackermannParams,
brakeResponseStates, steerResponseStates,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdWheelAttachmentsWrite(
*axleDesc,
wheelParams, wheelActuationStates, wheelRigidBody1dStates, wheelLocalPoses,
roadGeomStates,
suspParams, suspComplianceParams, suspForceParams, suspStates, suspComplianceStates,
suspForces,
tireForceParams,
tireDirectionStates, tireSpeedStates, tireSlipStates, tireStickyStates, tireGripStates, tireCamberStates,
tireForces,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdAntiRollsWrite(
antiRollParams, antiRollTorque,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
if (engineParams)
{
PxVehiclePvdEngineDrivetrainWrite(
commandState, engineDriveTransmissionCommandState, tankDriveTransmissionCommandState,
clutchResponseParams, clutchParams, engineParams, gearboxParams, autoboxParams,
multiWheelDiffParams, fourWheelDiffParams, tankDiffParams,
clutchResponseState, throttleResponseState, engineState, gearboxState, autoboxState, diffState, clutchSlipState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
}
else
{
PxVehiclePvdDirectDrivetrainWrite(
*axleDesc,
commandState, directDriveTransmissionState,
directDriveThrottleResponseParams,
directDrivethrottleResponseState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
}
PxVehiclePvdPhysXWheelAttachmentWrite(
*axleDesc,
physxConstraintParams, physxMaterialFrictionParams,
physxActor, physxRoadGeomQryParams, physxRoadGeomStates, physxConstraintStates,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdPhysXRigidActorWrite(
physxActor,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
PxVehiclePvdPhysXSteerStateWrite(
physxSteerState,
*context.pvdContext.attributeHandles, *omniPvdObjectHandles, *pvdWriter);
return true;
}
private:
bool firstTime;
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 16,980 | C | 46.699438 | 117 | 0.824912 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/steering/PxVehicleSteeringFunctions.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxPreprocessor.h"
#include "foundation/PxSimpleTypes.h"
#include "vehicle2/PxVehicleParams.h"
#include "PxVehicleSteeringParams.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehicleCommandState;
/**
\brief Compute the yaw angle response to a steer command.
\param[in] steer is the input steer command value.
\param[in] longitudinalSpeed is the longitudinal speed of the vehicle.
\param[in] wheelId specifies the wheel to have its steer response computed.
\param[in] steerResponseParmas specifies the per wheel yaw angle response to the steer command as a nonlinear function of steer command and longitudinal speed.
\param[out] steerResponseState is the yaw angle response to the input steer command.
*/
void PxVehicleSteerCommandResponseUpdate
(const PxReal steer, const PxReal longitudinalSpeed,
const PxU32 wheelId, const PxVehicleSteerCommandResponseParams& steerResponseParmas,
PxReal& steerResponseState);
/**
\brief Account for Ackermann correction by modifying the per wheel steer response multipliers to engineer an asymmetric steer response across axles.
\param[in] steer is the input steer command value.
\param[in] steerResponseParmas describes the maximum response and a response multiplier per axle.
\param[in] ackermannParams is an array that describes the wheels affected by Ackerman steer correction.
\param[in,out] steerResponseStates contains the corrected per wheel steer response multipliers that take account of Ackermann steer correction.
*/
void PxVehicleAckermannSteerUpdate
(const PxReal steer, const PxVehicleSteerCommandResponseParams& steerResponseParmas,
const PxVehicleSizedArrayData<const PxVehicleAckermannParams>& ackermannParams,
PxVehicleArrayData<PxReal>& steerResponseStates);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 3,599 | C | 43.444444 | 159 | 0.789664 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/steering/PxVehicleSteeringParams.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxFoundation.h"
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/commands/PxVehicleCommandParams.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehicleFrame;
struct PxVehicleScale;
/**
\brief Distribute a steer response to the wheels of a vehicle.
\note The steer angle applied to each wheel on the ith wheel is steerCommand * maxResponse * wheelResponseMultipliers[i].
\note A typical use case is to set maxResponse to be the vehicle's maximum achievable steer angle
that occurs when the steer command is equal to 1.0. The array wheelResponseMultipliers[i] would then be used
to specify the maximum achievable steer angle per wheel as a fractional multiplier of the vehicle's maximum achievable steer angle.
*/
struct PxVehicleSteerCommandResponseParams : public PxVehicleCommandResponseParams
{
PX_FORCE_INLINE PxVehicleSteerCommandResponseParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const
{
if (!axleDesc.isValid())
return false;
for (PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
PX_CHECK_AND_RETURN_VAL(PxAbs(maxResponse*wheelResponseMultipliers[axleDesc.wheelIdsInAxleOrder[i]]) <= PxPi,
"PxVehicleSteerCommandResponseParams.maxResponse*PxVehicleSteerCommandResponseParams.wheelResponseMultipliers[i] must be in range [-Pi, Pi]", false);
}
return true;
}
};
/**
\brief A description of a single axle that is to be affected by Ackermann steer correction.
*/
struct PxVehicleAckermannParams
{
PxU32 wheelIds[2]; //!< wheelIds[0] is the id of the wheel that is negative along the lateral axis, wheelIds[1] is the wheel id that is positive along the lateral axis.
PxReal wheelBase; //!< wheelBase is the longitudinal distance between the axle that is affected by Ackermann correction and a reference axle.
PxReal trackWidth; //!< trackWidth is the width of the axle specified by #wheelIds
PxReal strength; //!< is the strength of the correction with 0 denoting no correction and 1 denoting perfect correction.
PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const
{
PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelIds[0] < axleDesc.getNbWheels(), "PxVehicleAckermannParams.wheelIds[0] must be valid wheel", false);
PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelIds[1] < axleDesc.getNbWheels(), "PxVehicleAckermannParams.wheelIds[1] must be a valid wheel", false);
PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelIds[0] != wheelIds[1], "PxVehicleAckermannParams.wheelIds[0] and PxVehicleAckermannParams.wheelIds[1] must reference two different wheels", false);
PX_CHECK_AND_RETURN_VAL(0.0f == strength || wheelBase > 0.0f, "PxVehicleAckermannParams.wheelBase must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(0.0f == strength || trackWidth > 0.0f, "PxVehicleAckermannParams.trackWidth must be greater than zero", false);
PX_CHECK_AND_RETURN_VAL(strength >= 0.0f && strength <= 1.0f, "PxVehicleAckermannParams.strength must be in range [0,1]", false);
PX_UNUSED(axleDesc);
return true;
}
PX_FORCE_INLINE PxVehicleAckermannParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PxVehicleAckermannParams r = *this;
const PxReal scale = trgScale.scale / srcScale.scale;
r.wheelBase *= scale;
r.trackWidth *= scale;
return r;
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,575 | C | 44.333333 | 198 | 0.763408 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/commands/PxVehicleCommandStates.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxPreprocessor.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxMemory.h"
#include "vehicle2/PxVehicleLimits.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
/**
\brief A description of the state of commands that are applied to the vehicle
\note brakes[0] and brakes[1] may be used to distinguish brake and handbrake controls.
*/
struct PxVehicleCommandState
{
PxReal brakes[2]; //!< The instantaneous state of the brake controllers in range [0,1] with 1 denoting fully pressed and 0 fully depressed.
PxU32 nbBrakes; //|< The number of brake commands.
PxReal throttle; //!< The instantaneous state of the throttle controller in range [0,1] with 1 denoting fully pressed and 0 fully depressed.
PxReal steer; //!< The instantaneous state of the steer controller in range [-1,1].
PX_FORCE_INLINE void setToDefault()
{
PxMemZero(this, sizeof(PxVehicleCommandState));
}
};
/**
\brief A description of the state of transmission-related commands that are applied to a vehicle with direct drive.
*/
struct PxVehicleDirectDriveTransmissionCommandState
{
/**
\brief Direct drive vehicles only have reverse, neutral or forward gear.
*/
enum Enum
{
eREVERSE = 0,
eNEUTRAL,
eFORWARD
};
Enum gear; //!< The desired gear of the input gear controller.
PX_FORCE_INLINE void setToDefault()
{
PxMemZero(this, sizeof(PxVehicleDirectDriveTransmissionCommandState));
}
};
/**
\brief A description of the state of transmission-related commands that are applied to a vehicle with engine drive.
*/
struct PxVehicleEngineDriveTransmissionCommandState
{
enum Enum
{
/**
\brief Special gear value to denote the automatic shift mode (often referred to as DRIVE).
When using automatic transmission, setting this value as target gear will enable automatic
gear shifts between first and highest gear. If the current gear is a reverse gear or
the neutral gear, then this value will trigger a shift to first gear. If this value is
used even though there is no automatic transmission available, the gear state will remain
unchanged.
*/
eAUTOMATIC_GEAR = 0xff
};
PxReal clutch; //!< The instantaneous state of the clutch controller in range [0,1] with 1 denoting fully pressed and 0 fully depressed.
PxU32 targetGear; //!< The desired gear of the input gear controller.
PX_FORCE_INLINE void setToDefault()
{
PxMemZero(this, sizeof(PxVehicleEngineDriveTransmissionCommandState));
}
};
/**
\brief A description of the state of transmission-related commands that are applied to a vehicle with tank drive.
*/
struct PxVehicleTankDriveTransmissionCommandState : public PxVehicleEngineDriveTransmissionCommandState
{
/**
\brief The wheels of each tank track are either all connected to thrusts[0] or all connected to thrusts[1].
\note The thrust commands are used to divert torque from the engine to the wheels of the tank tracks controlled by each thrust.
\note thrusts[0] and thrusts[1] are in range [-1,1] with the sign dictating whether the thrust will be applied positively or negatively with respect to the gearing ratio.
*/
PxReal thrusts[2];
PX_FORCE_INLINE void setToDefault()
{
PxMemZero(this, sizeof(PxVehicleTankDriveTransmissionCommandState));
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,088 | C | 35.092198 | 171 | 0.760024 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/commands/PxVehicleCommandHelpers.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
/** \addtogroup vehicle2
@{
*/
#include "vehicle2/PxVehicleParams.h"
#include "PxVehicleCommandParams.h"
#include "PxVehicleCommandStates.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
/**
\brief Compute the linear response to a command.
\param[in] command is a normalised command value.
\param[in] wheelId specifies the wheel that is to respond to the command.
\param[in] responseParams specifies the wheel responses for all wheels on a vehicle.
\return The linear response of the specified wheel to the command.
*/
PX_FORCE_INLINE PxReal PxVehicleLinearResponseCompute
(const PxReal command, const PxU32 wheelId, const PxVehicleCommandResponseParams& responseParams)
{
return command*responseParams.maxResponse*responseParams.wheelResponseMultipliers[wheelId];
}
/**
\brief Compute the non-linear response to a command.
\param[in] command is a normalised command value.
\param[in] longitudinalSpeed is the longitudional speed of the vehicle.
\param[in] wheelId specifies the wheel that is to respond to the command.
\param[in] responseParams specifies the wheel responses for all wheels on a vehicle.
\note responseParams is used to compute an interpolated normalized response to the combination of command and longitudinalSpeed.
The interpolated normalized response is then used in place of the command as input to PxVehicleComputeLinearResponse().
*/
PxReal PxVehicleNonLinearResponseCompute
(const PxReal command, const PxReal longitudinalSpeed, const PxU32 wheelId, const PxVehicleCommandResponseParams& responseParams);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 3,347 | C | 42.480519 | 130 | 0.782193 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/commands/PxVehicleCommandParams.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxFoundation.h"
#include "vehicle2/PxVehicleLimits.h"
#include "vehicle2/PxVehicleParams.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
/**
\brief Each command value may be associated with a table specifying a normalized response as a function of longitudinal speed.
Multiple instances of PxVehicleCommandValueResponseTable allow a normalized response to be authored as a multi-variate
piecewise polynomial with normalized command response expressed as a nonlinear function of command value and speed.
*/
struct PxVehicleCommandValueResponseTable
{
enum Enum
{
eMAX_NB_SPEED_RESPONSES = 64
};
/**
\brief The command value associated with the table of speed responses.
*/
PxReal commandValue;
/**
\brief A lookup table specifying the normalised response to the specified command value as a function of longitudinal speed.
\note Each entry in the speedResponses table must be of the form (speed, normalizedResponse).
\note The longitudinal speeds in the table must form a strictly increasing series.
\note The normalized responses must be in range [0, 1].
*/
PxVehicleFixedSizeLookupTable<PxReal, eMAX_NB_SPEED_RESPONSES> speedResponses;
};
/**
\note Brake, drive and steer response typically reduce at increased longitudinal speed. Moreover, response to a brake, throttle or steer command is typically
nonlinear and may be subject to dead zones where response is constant with either zero or non-zero response. PxVehicleCommandNonLinearResponseParams allows
command responses to be authored as multi-variate piecewise polynomials with normalized command response a function of command value and longitudinal speed.
*/
class PxVehicleCommandNonLinearResponseParams
{
public:
enum Enum
{
eMAX_NB_COMMAND_VALUES = 8
};
PxVehicleCommandNonLinearResponseParams()
: nbSpeedResponses(0),
nbCommandValues(0)
{
}
void clear()
{
nbCommandValues = 0;
nbSpeedResponses = 0;
}
/**
\brief Add a table of normalised response vs speed and associated it with a specified command value.
\note commandValueSpeedResponses must be authored as a series of strictly increasing speeds with form {speed, normalizedResponse}
\note The responses added must form a series of strictly increasing command values.
*/
bool addResponse(const PxVehicleCommandValueResponseTable& commandValueSpeedResponses)
{
const PxReal commandValue = commandValueSpeedResponses.commandValue;
const PxReal* speeds = commandValueSpeedResponses.speedResponses.xVals;
const PxReal* responses = commandValueSpeedResponses.speedResponses.yVals;
const PxU16 nb = PxU16(commandValueSpeedResponses.speedResponses.nbDataPairs);
PX_CHECK_AND_RETURN_VAL(commandValue >= 0.0f && commandValue <= 1.0f, "PxVehicleCommandAndResponseTable::commandValue must be in range [0, 1]", false);
PX_CHECK_AND_RETURN_VAL(nbCommandValues < eMAX_NB_COMMAND_VALUES, "PxVehicleNonLinearCommandResponse::addResponse - exceeded maximum number of command responses", false);
PX_CHECK_AND_RETURN_VAL(((nbSpeedResponses + nb) <= PxVehicleCommandValueResponseTable::eMAX_NB_SPEED_RESPONSES), "PxVehicleNonLinearCommandResponse::addResponse - exceeded maximum number of command responses", false);
PX_CHECK_AND_RETURN_VAL((0 == nbCommandValues) || (commandValue > commandValues[nbCommandValues - 1]), "PxVehicleNonLinearCommandResponse::addResponse - command must be part of a strictly increasing series", false);
PX_CHECK_AND_RETURN_VAL(nb > 0, "PxVehicleNonLinearCommandResponse::addResponse - each command response must have at least 1 point", false);
#if PX_CHECKED
for (PxU32 i = 1; i < nb; i++)
{
PX_CHECK_AND_RETURN_VAL(speeds[i] > speeds[i - 1], "PxVehicleNonLinearCommandResponse::addResponse - speeds array must be a strictly increasing series", false);
PX_CHECK_AND_RETURN_VAL(responses[i] >= 0.0f && responses[i] <= 1.0f , "PxVehicleNonLinearCommandResponse::addResponse - response must be in range [0, 1]", false);
}
#endif
commandValues[nbCommandValues] = commandValue;
nbSpeedResponsesPerCommandValue[nbCommandValues] = nb;
speedResponsesPerCommandValue[nbCommandValues] = nbSpeedResponses;
PxMemCopy(speedResponses + 2 * nbSpeedResponses, speeds, sizeof(PxReal)*nb);
PxMemCopy(speedResponses + 2 * nbSpeedResponses + nb, responses, sizeof(PxReal)*nb);
nbCommandValues++;
nbSpeedResponses += nb;
return true;
}
public:
/**
\brief A ragged array of speeds and normalized responses.
*/
PxReal speedResponses[PxVehicleCommandValueResponseTable::eMAX_NB_SPEED_RESPONSES * 2];
/**
\brief The number of speeds and normalized responses.
*/
PxU16 nbSpeedResponses;
/**
\brief The table of speed responses for the ith command value begins at speedResponses[2*speedResponsesPerCommandValue[i]]
*/
PxU16 speedResponsesPerCommandValue[eMAX_NB_COMMAND_VALUES];
/**
\brief The ith command value has N speed responses with N = nbSpeedRenponsesPerCommandValue[i].
*/
PxU16 nbSpeedResponsesPerCommandValue[eMAX_NB_COMMAND_VALUES];
/**
\brief The command values.
*/
PxReal commandValues[eMAX_NB_COMMAND_VALUES];
/**
\brief The number of command values.
*/
PxU16 nbCommandValues;
};
/**
\brief A description of the per wheel response to an input command.
*/
struct PxVehicleCommandResponseParams
{
/**
\brief A nonlinear response to command value expressed as a lookup table of normalized response as a function of command value and longitudinal speed.
\note The effect of the default state of nonlinearResponse is a linear response to command value that is independent of longitudinal speed.
*/
PxVehicleCommandNonLinearResponseParams nonlinearResponse;
/**
\brief A description of the per wheel response multiplier to an input command.
*/
PxReal wheelResponseMultipliers[PxVehicleLimits::eMAX_NB_WHEELS];
/**
\brief The maximum response that occurs when the wheel response multiplier has value 1.0 and nonlinearResponse is in the default state of linear response.
*/
PxF32 maxResponse;
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 7,828 | C | 37.566502 | 220 | 0.773633 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxFoundation.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehicleFrame;
struct PxVehicleScale;
/**
\brief A description of the PhysX models employed to resolve suspension limit constraints.
@see PxVehiclePhysXConstraintState
*/
struct PxVehiclePhysXSuspensionLimitConstraintParams
{
/**
\brief restitution is used by the restitution model used to generate a target velocity when resolving suspension limit
constraints.
\note A value of 0.0 means that the restitution model is not employed.
\note Restitution has no effect if directionForSuspensionLimitConstraint has value Enum::eNONE.
@see Px1DConstraintFlag::eRESTITUTION
@see Px1DConstraint::RestitutionModifiers::restitution
*/
PxReal restitution;
/**
\brief Set the direction to apply a constraint impulse when the suspension cannot place the wheel on the ground
and simultaneously respect the limits of suspension travel. The choices are to push along the ground normal to resolve the
geometric error or to push along the suspension direction. The former choice can be thought of as mimicing a force applied
by the tire's contact with the ground, while the latter can be thought of as mimicing a force arising from a suspension limit spring.
When the ground normal and the suspension direction are approximately aligned, both do an equivalent job of maintaining the wheel above
the ground. When the vehicle is on its side, eSUSPENSION does a better job of keeping the wheels above
the ground but comes at the cost of an unnaturally strong torque that can lead to unwanted self-righting behaviour.
eROAD_GEOMETRY_NORMAL is a good choice to avoid self-righting behaviour and still do a reasonable job at maintaining
the wheel above the ground in the event that the vehicle is tending towards a roll onto its side.
eNONE should be chosen if it is desired that no extra impulse is applied when the suspension alone cannot keep the wheels above
the ground plane.
*/
enum DirectionSpecifier
{
eSUSPENSION,
eROAD_GEOMETRY_NORMAL,
eNONE
};
DirectionSpecifier directionForSuspensionLimitConstraint;
PX_FORCE_INLINE PxVehiclePhysXSuspensionLimitConstraintParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid() const
{
PX_CHECK_AND_RETURN_VAL(
PxVehiclePhysXSuspensionLimitConstraintParams::eSUSPENSION == directionForSuspensionLimitConstraint ||
PxVehiclePhysXSuspensionLimitConstraintParams::eROAD_GEOMETRY_NORMAL == directionForSuspensionLimitConstraint ||
PxVehiclePhysXSuspensionLimitConstraintParams::eNONE == directionForSuspensionLimitConstraint, "PxVehiclePhysXSuspensionLimitConstraintParams.directionForSuspensionLimitConstraint must have legal value", false);
PX_CHECK_AND_RETURN_VAL(restitution >= 0.0f && restitution <= 1.0f, "PxVehiclePhysXSuspensionLimitConstraintParams.restitution must be in range [0, 1]", false);
return true;
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 4,988 | C | 43.945946 | 214 | 0.787089 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxAssert.h"
#include "foundation/PxTransform.h"
#include "extensions/PxConstraintExt.h"
#include "vehicle2/PxVehicleLimits.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "PxConstraint.h"
#include "PxConstraintDesc.h"
#if !PX_DOXYGEN
namespace physx
{
class PxConstraint;
namespace vehicle2
{
#endif
/**
\brief A description of the number of PxConstraintConnector instances per vehicle required to maintain suspension limit
and sticky tire instances.
*/
struct PxVehiclePhysXConstraintLimits
{
enum Enum
{
eNB_DOFS_PER_PXCONSTRAINT = 12,
eNB_DOFS_PER_WHEEL = 3,
eNB_WHEELS_PER_PXCONSTRAINT = eNB_DOFS_PER_PXCONSTRAINT / eNB_DOFS_PER_WHEEL,
eNB_CONSTRAINTS_PER_VEHICLE = (PxVehicleLimits::eMAX_NB_WHEELS + (eNB_WHEELS_PER_PXCONSTRAINT - 1)) / (eNB_WHEELS_PER_PXCONSTRAINT)
};
};
/**
\brief PxVehiclePhysXConstraintState is a data structure used to write
constraint data to the internal state of the associated PxScene.
@see Px1dConstraint
*/
struct PxVehiclePhysXConstraintState
{
/**
\brief a boolean describing whether to trigger a low speed constraint along the tire longitudinal and lateral directions.
*/
bool tireActiveStatus[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS];
/**
\brief linear component of velocity jacobian in world space for the tire's longitudinal and lateral directions.
*/
PxVec3 tireLinears[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS];
/**
\brief angular component of velocity jacobian in world space for the tire's longitudinal and lateral directions.
*/
PxVec3 tireAngulars[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS];
/**
\brief damping coefficient applied to the tire's longitudinal and lateral velocities.
The constraint sets a target velocity of 0 and the damping coefficient will impact the size of the
impulse applied to reach the target. Since damping acts as a stiffness with respect to the velocity,
too large a value can cause instabilities.
*/
PxReal tireDamping[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS];
/**
\brief a boolean describing whether to trigger a suspension limit constraint.
*/
bool suspActiveStatus;
/**
\brief linear component of velocity jacobian in the world frame.
*/
PxVec3 suspLinear;
/**
\brief angular component of velocity jacobian in the world frame.
*/
PxVec3 suspAngular;
/**
\brief the excess suspension compression to be resolved by the constraint that cannot be resolved due to the travel limit
of the suspension spring.
\note The expected error value is the excess suspension compression projected onto the ground plane normal and should have
a negative sign.
*/
PxReal suspGeometricError;
/**
\brief restitution value of the restitution model used to generate a target velocity that will resolve the geometric error.
\note A value of 0.0 means that the restitution model is not employed.
@see Px1DConstraintFlag::eRESTITUTION
@see Px1DConstraint::RestitutionModifiers::restitution
*/
PxReal restitution;
PX_FORCE_INLINE void setToDefault()
{
PxMemZero(this, sizeof(PxVehiclePhysXConstraintState));
}
};
//TAG:solverprepshader
PX_FORCE_INLINE PxU32 vehicleConstraintSolverPrep
(Px1DConstraint* constraints,
PxVec3p& body0WorldOffset,
PxU32 maxConstraints,
PxConstraintInvMassScale&,
const void* constantBlock,
const PxTransform& bodyAToWorld,
const PxTransform& bodyBToWorld,
bool,
PxVec3p& cA2w, PxVec3p& cB2w)
{
PX_UNUSED(maxConstraints);
PX_UNUSED(body0WorldOffset);
PX_UNUSED(bodyBToWorld);
PX_ASSERT(bodyAToWorld.isValid()); PX_ASSERT(bodyBToWorld.isValid());
const PxVehiclePhysXConstraintState* data = static_cast<const PxVehiclePhysXConstraintState*>(constantBlock);
PxU32 numActive = 0;
//KS - the TGS solver will use raXn to try to add to the angular part of the linear constraints.
//We overcome this by setting the ra and rb offsets to be 0.
cA2w = bodyAToWorld.p;
cB2w = bodyBToWorld.p;
// note: this is only needed for PxSolverType::eTGS and even then it should not have an effect as
// long as a constraint raises Px1DConstraintFlag::eANGULAR_CONSTRAINT
//Susp limit constraints.
for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT; i++)
{
if (data[i].suspActiveStatus)
{
// Going beyond max suspension compression should be treated similar to rigid body contacts.
// Thus setting up constraints that try to emulate such contacts.
//
// linear l = contact normal = n
// angular a = suspension force application offset x contact normal = cross(r, n)
//
// velocity at contact:
// vl: part from linear vehicle velocity v
// vl = dot(n, v) = dot(l, v)
//
// va: part from angular vehicle velocity w
// va = dot(n, cross(w, r)) = dot(w, cross(r, n)) = dot(w, a)
//
// ve: part from excess suspension compression
// ve = (geomError / dt) (note: geomError is expected to be negative here)
//
// velocity target vt = vl + va + ve
// => should become 0 by applying positive impulse along l. If vt is positive,
// nothing will happen as a negative impulse would have to be applied (but
// min impulse is set to 0). If vt is negative, a positive impulse will get
// applied to push vt towards 0.
//
Px1DConstraint& p = constraints[numActive];
p.linear0 = data[i].suspLinear;
p.angular0 = data[i].suspAngular;
p.geometricError = data[i].suspGeometricError;
p.linear1 = PxVec3(0);
p.angular1 = PxVec3(0);
p.minImpulse = 0;
p.maxImpulse = FLT_MAX;
p.velocityTarget = 0;
p.solveHint = PxConstraintSolveHint::eINEQUALITY;
// note: this is only needed for PxSolverType::eTGS to not have the angular part
// be modified based on the linear part during substeps. Basically, it will
// disable the constraint re-projection etc. to emulate PxSolverType::ePGS.
p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT;
if (data[i].restitution > 0.0f)
{
p.flags |= Px1DConstraintFlag::eRESTITUTION;
p.mods.bounce.restitution = data[i].restitution;
p.mods.bounce.velocityThreshold = -FLT_MAX;
}
numActive++;
}
}
//Sticky tire friction constraints.
for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT; i++)
{
if (data[i].tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL])
{
Px1DConstraint& p = constraints[numActive];
p.linear0 = data[i].tireLinears[PxVehicleTireDirectionModes::eLONGITUDINAL];
p.angular0 = data[i].tireAngulars[PxVehicleTireDirectionModes::eLONGITUDINAL];
p.geometricError = 0.0f;
p.linear1 = PxVec3(0);
p.angular1 = PxVec3(0);
p.minImpulse = -FLT_MAX;
p.maxImpulse = FLT_MAX;
p.velocityTarget = 0.0f;
p.mods.spring.damping = data[i].tireDamping[PxVehicleTireDirectionModes::eLONGITUDINAL];
// note: no stiffness specified as this will have no effect with geometricError=0
p.flags = Px1DConstraintFlag::eSPRING | Px1DConstraintFlag::eACCELERATION_SPRING;
p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT; // see explanation of same flag usage further above
numActive++;
}
}
//Sticky tire friction constraints.
for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT; i++)
{
if (data[i].tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL])
{
Px1DConstraint& p = constraints[numActive];
p.linear0 = data[i].tireLinears[PxVehicleTireDirectionModes::eLATERAL];
p.angular0 = data[i].tireAngulars[PxVehicleTireDirectionModes::eLATERAL];
p.geometricError = 0.0f;
p.linear1 = PxVec3(0);
p.angular1 = PxVec3(0);
p.minImpulse = -FLT_MAX;
p.maxImpulse = FLT_MAX;
p.velocityTarget = 0.0f;
p.mods.spring.damping = data[i].tireDamping[PxVehicleTireDirectionModes::eLATERAL];
// note: no stiffness specified as this will have no effect with geometricError=0
p.flags = Px1DConstraintFlag::eSPRING | Px1DConstraintFlag::eACCELERATION_SPRING;
p.flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT; // see explanation of same flag usage further above
numActive++;
}
}
return numActive;
}
PX_FORCE_INLINE void visualiseVehicleConstraint
(PxConstraintVisualizer &viz,
const void* constantBlock,
const PxTransform& body0Transform,
const PxTransform& body1Transform,
PxU32 flags)
{
PX_UNUSED(&viz);
PX_UNUSED(constantBlock);
PX_UNUSED(body0Transform);
PX_UNUSED(body1Transform);
PX_UNUSED(flags);
PX_ASSERT(body0Transform.isValid());
PX_ASSERT(body1Transform.isValid());
}
class PxVehicleConstraintConnector : public PxConstraintConnector
{
public:
PxVehicleConstraintConnector() : mVehicleConstraintState(NULL) {}
PxVehicleConstraintConnector(PxVehiclePhysXConstraintState* vehicleConstraintState) : mVehicleConstraintState(vehicleConstraintState) {}
~PxVehicleConstraintConnector() {}
void setConstraintState(PxVehiclePhysXConstraintState* constraintState) { mVehicleConstraintState = constraintState; }
virtual void* prepareData() { return mVehicleConstraintState; }
virtual const void* getConstantBlock() const { return mVehicleConstraintState; }
virtual PxConstraintSolverPrep getPrep() const { return vehicleConstraintSolverPrep; }
//Is this necessary if physx no longer supports double-buffering?
virtual void onConstraintRelease() { }
//Can be empty functions.
virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream& pvdConnection, const PxConstraint* c, PxPvdUpdateType::Enum updateType) const
{
PX_UNUSED(pvdConnection);
PX_UNUSED(c);
PX_UNUSED(updateType);
return true;
}
virtual void updateOmniPvdProperties() const { }
virtual void onComShift(PxU32 actor) { PX_UNUSED(actor); }
virtual void onOriginShift(const PxVec3& shift) { PX_UNUSED(shift); }
virtual void* getExternalReference(PxU32& typeID) { typeID = PxConstraintExtIDs::eVEHICLE_JOINT; return this; }
virtual PxBase* getSerializable() { return NULL; }
private:
PxVehiclePhysXConstraintState* mVehicleConstraintState;
};
/**
\brief A mapping between constraint state data and the associated PxConstraint instances.
*/
struct PxVehiclePhysXConstraints
{
/**
\brief PxVehiclePhysXConstraintComponent writes to the constraintStates array and a
callback invoked by PxScene::simulate() reads a portion from it for a block of wheels
and writes that portion to an associated PxConstraint instance.
*/
PxVehiclePhysXConstraintState constraintStates[PxVehicleLimits::eMAX_NB_WHEELS];
/**
\brief PxVehiclePhysXConstraintComponent writes to the constraintStates array and a
callback invoked by PxScene::simulate() reads a portion from it for a block of wheels
and writes that portion to an associated PxConstraint instance.
*/
PxConstraint* constraints[PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE];
/**
\brief A constraint connector is necessary to connect each PxConstraint to a portion of the constraintStates array.
*/
PxVehicleConstraintConnector* constraintConnectors[PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE];
PX_FORCE_INLINE void setToDefault()
{
for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++)
{
constraintStates[i].setToDefault();
}
for(PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE; i++)
{
constraints[i] = NULL;
constraintConnectors[i] = NULL;
}
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 13,146 | C | 35.723464 | 141 | 0.754298 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.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 "foundation/PxPreprocessor.h"
/** \addtogroup vehicle2
@{
*/
#if !PX_DOXYGEN
namespace physx
{
class PxPhysics;
class PxRigidBody;
namespace vehicle2
{
#endif
struct PxVehicleAxleDescription;
struct PxVehiclePhysXConstraints;
/**
\brief Instantiate the PhysX custom constraints.
Custom constraints will resolve excess suspension compression and velocity constraints that serve as
a replacement low speed tire model.
\param[in] axleDescription describes the axles of the vehicle and the wheels on each axle.
\param[in] physics is a PxPhysics instance.
\param[in] physxActor is the vehicle's PhysX representation as a PxRigidBody
\param[in] vehicleConstraints is a wrapper class that holds pointers to PhysX objects required to implement the custom constraint.
*/
void PxVehicleConstraintsCreate
(const PxVehicleAxleDescription& axleDescription,
PxPhysics& physics, PxRigidBody& physxActor,
PxVehiclePhysXConstraints& vehicleConstraints);
/**
\brief To ensure the constraints are processed by the PhysX scene they are marked as dirty prior to each simulate step.
\param[in] vehicleConstraints is a wrapper class that holds pointers to PhysX objects required to implement the custom constraint.
@see PxVehicleConstraintsCreate
*/
void PxVehicleConstraintsDirtyStateUpdate
(PxVehiclePhysXConstraints& vehicleConstraints);
/**
\brief Destroy the PhysX custom constraints.
\param[in,out] vehicleConstraints describes the PhysX custom constraints to be released.
@see PxVehicleConstraintsCreate
*/
void PxVehicleConstraintsDestroy
(PxVehiclePhysXConstraints& vehicleConstraints);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 3,392 | C | 35.483871 | 130 | 0.786851 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxConstraints/PxVehiclePhysXConstraintComponents.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
/** \addtogroup vehicle2
@{
*/
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleComponent.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "PxVehiclePhysXConstraintFunctions.h"
#include "PxVehiclePhysXConstraintHelpers.h"
#include "PxVehiclePhysXConstraintStates.h"
#include "PxVehiclePhysXConstraintParams.h"
#include "common/PxProfileZone.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
class PxVehiclePhysXConstraintComponent : public PxVehicleComponent
{
public:
PxVehiclePhysXConstraintComponent() : PxVehicleComponent() {}
virtual ~PxVehiclePhysXConstraintComponent() {}
virtual void getDataForPhysXConstraintComponent(
const PxVehicleAxleDescription*& axleDescription,
const PxVehicleRigidBodyState*& rigidBodyState,
PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams,
PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& suspensionLimitParams,
PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates,
PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates,
PxVehicleArrayData<const PxVehicleRoadGeometryState>& wheelRoadGeomStates,
PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
PxVehiclePhysXConstraints*& constraints) = 0;
virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context)
{
PX_UNUSED(dt);
PX_UNUSED(context);
PX_PROFILE_ZONE("PxVehiclePhysXConstraintComponent::update", 0);
const PxVehicleAxleDescription* axleDescription;
const PxVehicleRigidBodyState* rigidBodyState;
PxVehicleArrayData<const PxVehicleSuspensionParams> suspensionParams;
PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams> suspensionLimitParams;
PxVehicleArrayData<const PxVehicleSuspensionState> suspensionStates;
PxVehicleArrayData<const PxVehicleSuspensionComplianceState> suspensionComplianceStates;
PxVehicleArrayData<const PxVehicleRoadGeometryState> wheelRoadGeomStates;
PxVehicleArrayData<const PxVehicleTireDirectionState> tireDirectionStates;
PxVehicleArrayData<const PxVehicleTireStickyState> tireStickyStates;
PxVehiclePhysXConstraints* constraints;
getDataForPhysXConstraintComponent(axleDescription, rigidBodyState,
suspensionParams, suspensionLimitParams, suspensionStates, suspensionComplianceStates,
wheelRoadGeomStates, tireDirectionStates, tireStickyStates,
constraints);
PxVehicleConstraintsDirtyStateUpdate(*constraints);
for (PxU32 i = 0; i < axleDescription->nbWheels; i++)
{
const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i];
PxVehiclePhysXConstraintStatesUpdate(
suspensionParams[wheelId], suspensionLimitParams[wheelId],
suspensionStates[wheelId], suspensionComplianceStates[wheelId],
wheelRoadGeomStates[wheelId].plane.n,
context.tireStickyParams.stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].damping,
context.tireStickyParams.stickyParams[PxVehicleTireDirectionModes::eLATERAL].damping,
tireDirectionStates[wheelId], tireStickyStates[wheelId],
*rigidBodyState,
constraints->constraintStates[wheelId]);
}
return true;
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,188 | C | 40.846774 | 97 | 0.809946 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxConstraints/PxVehiclePhysXConstraintFunctions.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxVec3.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehicleSuspensionParams;
struct PxVehiclePhysXSuspensionLimitConstraintParams;
struct PxVehicleSuspensionState;
struct PxVehicleSuspensionComplianceState;
struct PxVehicleTireDirectionState;
struct PxVehicleTireStickyState;
struct PxVehicleRigidBodyState;
struct PxVehiclePhysXConstraintState;
/**
\brief Read constraint data from the vehicle's internal state for a single wheel and write it to a
structure that will be read by the associated PxScene and used to impose the constraints during the next
PxScene::simulate() step.
\param[in] suspensionParams describes the suspension frame.
\param[in] suspensionLimitParams describes the restitution value applied to any constraint triggered by
the suspension travel limit.
\param[in] suspensionState describes the excess suspension compression beyond the suspension travel limit that will be
resolved with a constraint.
\param[in] suspensionComplianceState describes the effect of suspension compliance on the effective application point
of the suspension force.
\param[in] groundPlaneNormal The normal direction of the ground plane the wheel is driving on. A normalized vector is
expected.
\param[in] tireStickyDampingLong The damping coefficient to use in the constraint to approach a zero target velocity
along the longitudinal tire axis.
\param[in] tireStickyDampingLat Same concept as tireStickyDampingLong but for the lateral tire axis.
\param[in] tireDirectionState describes the longitudinal and lateral directions of the tire in the world frame.
\param[in] tireStickyState describes the low speed state of the tire in the longitudinal and lateral directions.
\param[in] rigidBodyState describes the pose of the rigid body.
\param[out] constraintState is the data structure that will be read by the associated PxScene in the next call to
PxScene::simulate().
\note Constraints include suspension constraints to account for suspension travel limit and sticky
tire constraints that bring the vehicle to rest at low longitudinal and lateral speed.
*/
void PxVehiclePhysXConstraintStatesUpdate
(const PxVehicleSuspensionParams& suspensionParams,
const PxVehiclePhysXSuspensionLimitConstraintParams& suspensionLimitParams,
const PxVehicleSuspensionState& suspensionState, const PxVehicleSuspensionComplianceState& suspensionComplianceState,
const PxVec3& groundPlaneNormal,
const PxReal tireStickyDampingLong, const PxReal tireStickyDampingLat,
const PxVehicleTireDirectionState& tireDirectionState, const PxVehicleTireStickyState& tireStickyState,
const PxVehicleRigidBodyState& rigidBodyState,
PxVehiclePhysXConstraintState& constraintState);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 4,563 | C | 48.075268 | 119 | 0.804734 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxFoundation.h"
#include "PxQueryFiltering.h"
#if !PX_DOXYGEN
namespace physx
{
class PxMaterial;
namespace vehicle2
{
#endif
struct PxVehicleFrame;
struct PxVehicleScale;
/**
\brief PhysX scene queries may be raycasts or sweeps.
\note eNONE will result in no PhysX scene query. This option will not overwrite the associated PxVehicleRoadGeometryState.
*/
struct PxVehiclePhysXRoadGeometryQueryType
{
enum Enum
{
eNONE = 0, //!< Info about the road geometry below the wheel is provided by the user
eRAYCAST, //!< The road geometry below the wheel is analyzed using a raycast query
eSWEEP, //!< The road geometry below the wheel is analyzed using a sweep query
eMAX_NB
};
};
/**
\brief A description of type of PhysX scene query and the filter data to apply to the query.
*/
struct PxVehiclePhysXRoadGeometryQueryParams
{
/**
\brief The default filter data to use for the physx scene query.
If per wheel filter data is provided in #filterDataEntries, then this member
will be ignored.
@see PxSceneQuerySystemBase::raycast
@see PxSceneQuerySystemBase::sweep
*/
PxQueryFilterData defaultFilterData;
/**
\brief Array of filter data entries (one per wheel) to use for the physx scene query.
A null pointer is allowed in which case #defaultFilterData will be used for all wheels.
@see PxSceneQuerySystemBase::raycast
@see PxSceneQuerySystemBase::sweep
*/
PxQueryFilterData* filterDataEntries;
/**
\brief A filter callback to be used by the physx scene query
\note A null pointer is allowed.
@see PxSceneQuerySystemBase::raycast
@see PxSceneQuerySystemBase::sweep
*/
PxQueryFilterCallback* filterCallback;
/**
\brief A description of the type of physx scene query to employ.
@see PxSceneQuerySystemBase::raycast
@see PxSceneQuerySystemBase::sweep
*/
PxVehiclePhysXRoadGeometryQueryType::Enum roadGeometryQueryType;
PX_FORCE_INLINE PxVehiclePhysXRoadGeometryQueryParams transformAndScale(
const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const
{
PX_UNUSED(srcFrame);
PX_UNUSED(trgFrame);
PX_UNUSED(srcScale);
PX_UNUSED(trgScale);
return *this;
}
PX_FORCE_INLINE bool isValid() const
{
PX_CHECK_AND_RETURN_VAL(roadGeometryQueryType < PxVehiclePhysXRoadGeometryQueryType::eMAX_NB, "PxVehiclePhysXRoadGeometryQueryParams.roadGeometryQueryType has illegal value", false);
return true;
}
};
/**
A mapping between PxMaterial and a friction value to be used by the tire model.
@see PxVehiclePhysXMaterialFrictionParams
*/
struct PxVehiclePhysXMaterialFriction
{
/**
\brief A PxMaterial instance that is to be mapped to a friction value.
*/
const PxMaterial* material;
/**
\brief A friction value that is to be mapped to a PxMaterial instance.
\note friction must have value greater than or equal to zero.
<b>Range:</b> [0, inf)<br>
@see PxVehicleTireGripState::friction
*/
PxReal friction;
PX_FORCE_INLINE bool isValid() const
{
PX_CHECK_AND_RETURN_VAL(friction >= 0.0f, "PxVehiclePhysXMaterialFriction.friction must be greater than or equal to zero", false);
return true;
}
};
/**
\brief A mappping between PxMaterial instance and friction for multiple PxMaterial intances.
*/
struct PxVehiclePhysXMaterialFrictionParams
{
PxVehiclePhysXMaterialFriction* materialFrictions; //!< An array of mappings between PxMaterial and friction.
PxU32 nbMaterialFrictions; //!< The number of mappings between PxMaterial and friction.
PxReal defaultFriction; //!< A default friction value to be used in the event that the PxMaterial under the tire is not found in the array #materialFrictions.
PX_FORCE_INLINE bool isValid() const
{
for (PxU32 i = 0; i < nbMaterialFrictions; i++)
{
if (!materialFrictions[i].isValid())
return false;
}
PX_CHECK_AND_RETURN_VAL(defaultFriction >= 0.0f, "PxVehiclePhysXMaterialFrictionParams.defaultFriction must be greater than or equal to zero", false);
return true;
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,835 | C | 31.603352 | 184 | 0.762982 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryComponents.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
/** \addtogroup vehicle2
@{
*/
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleComponent.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h"
#include "common/PxProfileZone.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
class PxVehiclePhysXRoadGeometrySceneQueryComponent : public PxVehicleComponent
{
public:
PxVehiclePhysXRoadGeometrySceneQueryComponent() : PxVehicleComponent() {}
virtual ~PxVehiclePhysXRoadGeometrySceneQueryComponent() {}
/**
\brief Provide vehicle data items for this component.
\param[out] axleDescription identifies the wheels on each axle.
\param[out] roadGeomParams The road geometry parameters of the vehicle.
\param[out] steerResponseStates The steer response state of the wheels.
\param[out] rigidBodyState The pose, velocity etc. of the vehicle rigid body.
\param[out] wheelParams The wheel parameters for the wheels.
\param[out] suspensionParams The suspension parameters for the wheels.
\param[out] materialFrictionParams The tire friction tables for the wheels.
\param[out] roadGeometryStates The detected ground surface plane, friction value etc. for the wheels.
\param[out] physxRoadGeometryStates Optional buffer to store additional information about the query (like actor/shape that got hit etc.).
Set to empty if not desired.
*/
virtual void getDataForPhysXRoadGeometrySceneQueryComponent(
const PxVehicleAxleDescription*& axleDescription,
const PxVehiclePhysXRoadGeometryQueryParams*& roadGeomParams,
PxVehicleArrayData<const PxReal>& steerResponseStates,
const PxVehicleRigidBodyState*& rigidBodyState,
PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams,
PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& materialFrictionParams,
PxVehicleArrayData<PxVehicleRoadGeometryState>& roadGeometryStates,
PxVehicleArrayData<PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeometryStates) = 0;
virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context)
{
PX_UNUSED(dt);
PX_PROFILE_ZONE("PxVehiclePhysXRoadGeometrySceneQueryComponent::update", 0);
const PxVehicleAxleDescription* axleDescription;
const PxVehiclePhysXRoadGeometryQueryParams* roadGeomParams;
PxVehicleArrayData<const PxReal> steerResponseStates;
const PxVehicleRigidBodyState* rigidBodyState;
PxVehicleArrayData<const PxVehicleWheelParams> wheelParams;
PxVehicleArrayData<const PxVehicleSuspensionParams> suspensionParams;
PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams> materialFrictionParams;
PxVehicleArrayData<PxVehicleRoadGeometryState> roadGeometryStates;
PxVehicleArrayData<PxVehiclePhysXRoadGeometryQueryState> physxRoadGeometryStates;
getDataForPhysXRoadGeometrySceneQueryComponent(axleDescription,
roadGeomParams, steerResponseStates, rigidBodyState,
wheelParams, suspensionParams, materialFrictionParams,
roadGeometryStates, physxRoadGeometryStates);
if (context.getType() == PxVehicleSimulationContextType::ePHYSX)
{
const PxVehiclePhysXSimulationContext& physxContext = static_cast<const PxVehiclePhysXSimulationContext&>(context);
for(PxU32 i = 0; i < axleDescription->nbWheels; i++)
{
const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i];
const PxQueryFilterData* fdPtr = roadGeomParams->filterDataEntries ? (roadGeomParams->filterDataEntries + wheelId) : &roadGeomParams->defaultFilterData;
PxVehiclePhysXRoadGeometryQueryUpdate(
wheelParams[wheelId], suspensionParams[wheelId],
roadGeomParams->roadGeometryQueryType, roadGeomParams->filterCallback, *fdPtr,
materialFrictionParams[wheelId],
steerResponseStates[wheelId], *rigidBodyState,
*physxContext.physxScene, physxContext.physxUnitCylinderSweepMesh, context.frame,
roadGeometryStates[wheelId],
!physxRoadGeometryStates.isEmpty() ? &physxRoadGeometryStates[wheelId] : NULL);
}
}
else
{
PX_ALWAYS_ASSERT();
for(PxU32 i = 0; i < axleDescription->nbWheels; i++)
{
const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i];
roadGeometryStates[wheelId].setToDefault();
}
}
return true;
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 6,419 | C | 42.087248 | 156 | 0.796697 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.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
/** \addtogroup vehicle2
@{
*/
#include "foundation/PxSimpleTypes.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h"
#if !PX_DOXYGEN
namespace physx
{
class PxScene;
class PxConvexMesh;
namespace vehicle2
{
#endif
struct PxVehicleWheelParams;
struct PxVehicleSuspensionParams;
struct PxVehiclePhysXRoadGeometryQueryState;
struct PxVehicleRigidBodyState;
struct PxVehicleFrame;
struct PxVehicleRoadGeometryState;
/**
\brief Compute the plane of the road geometry under a wheel and the tire friction of the contact.
\param[in] wheelParams describes the radius and halfwidth of the wheel.
\param[in] suspParams describes the frame of the suspension and wheel and the maximum suspension travel.
\param[in] queryType describes what type of PhysX scene query to use (see #PxVehiclePhysXRoadGeometryQueryType).
If PxVehiclePhysXRoadGeometryQueryType::eNONE is used, no work will be done.
\param[in] filterCallback describes the filter callback to use for the PhysX scene query. NULL is a valid input.
\param[in] filterData describes the filter data to use for the PhysX scene query.
\param[in] materialFrictionParams describes a mapping between PxMaterial and friction in order to compute a tire friction value.
\param[in] wheelYawAngle is the yaw angle (in radians) of the wheel.
\param[in] rigidBodyState describes the pose of the rigid body.
\param[in] scene is the PhysX scene that will be queried by the scene query.
\param[in] unitCylinderSweepMesh is a convex cylindrical mesh of unit radius and half-width to be used in
the event that a sweep query is to be used.
\param[in] frame describes the lateral, longitudinal and vertical axes and is used to scale unitCylinderSweepMesh
by the wheel's radius and half-width.
\param[out] roadGeomState contains the plane and friction of the road geometry under the wheel.
\param[out] physxRoadGeometryState Optional buffer to store additional information about the query (like actor/shape that got hit etc.).
Set to NULL if not needed.
\note PxVehicleRoadGeometryState::hitState will have value false in the event that the there is no reachable road geometry under the wheel and
true if there is reachable road geometry under the wheel. Road geometry is considered reachable if the suspension can elongate from its
reference pose far enough to place wheel on the ground.
*/
void PxVehiclePhysXRoadGeometryQueryUpdate
(const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspParams,
const PxVehiclePhysXRoadGeometryQueryType::Enum queryType,
PxQueryFilterCallback* filterCallback, const PxQueryFilterData& filterData,
const PxVehiclePhysXMaterialFrictionParams& materialFrictionParams,
const PxReal wheelYawAngle, const PxVehicleRigidBodyState& rigidBodyState,
const PxScene& scene, const PxConvexMesh* unitCylinderSweepMesh,
const PxVehicleFrame& frame,
PxVehicleRoadGeometryState& roadGeomState,
PxVehiclePhysXRoadGeometryQueryState* physxRoadGeometryState);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 4,783 | C | 48.833333 | 143 | 0.795317 |
NVIDIA-Omniverse/PhysX/physx/include/cudamanager/PxCudaContextManager.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.
#ifndef PX_CUDA_CONTEXT_MANAGER_H
#define PX_CUDA_CONTEXT_MANAGER_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxErrorCallback.h"
#include "foundation/PxFlags.h"
#include "PxCudaTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxCudaContext;
struct PxCudaInteropRegisterFlag
{
enum Enum
{
eNONE = 0x00,
eREAD_ONLY = 0x01,
eWRITE_DISCARD = 0x02,
eSURFACE_LDST = 0x04,
eTEXTURE_GATHER = 0x08
};
};
/**
\brief An interface class that the user can implement in order for PhysX to use a user-defined device memory allocator.
*/
class PxDeviceAllocatorCallback
{
public:
/**
\brief Allocated device memory.
\param[in] ptr Pointer to store the allocated address
\param[in] size The amount of memory required
\return A boolean indicates the operation succeed or fail
*/
virtual bool memAlloc(void** ptr, size_t size) = 0;
/**
\brief Frees device memory.
\param[in] ptr The memory to free
\return A boolean indicates the operation succeed or fail
*/
virtual bool memFree(void* ptr) = 0;
protected:
virtual ~PxDeviceAllocatorCallback() {}
};
/**
\brief collection of set bits defined in NxCudaInteropRegisterFlag.
@see NxCudaInteropRegisterFlag
*/
typedef PxFlags<PxCudaInteropRegisterFlag::Enum, uint32_t> PxCudaInteropRegisterFlags;
PX_FLAGS_OPERATORS(PxCudaInteropRegisterFlag::Enum, uint32_t)
//! \brief Descriptor used to create a PxCudaContextManager
class PxCudaContextManagerDesc
{
public:
/**
* \brief The CUDA context to manage
*
* If left NULL, the PxCudaContextManager will create a new context. If
* graphicsDevice is also not NULL, this new CUDA context will be bound to
* that graphics device, enabling the use of CUDA/Graphics interop features.
*
* If ctx is not NULL, the specified context must be applied to the thread
* that is allocating the PxCudaContextManager at creation time (aka, it
* cannot be popped). The PxCudaContextManager will take ownership of the
* context until the manager is released. All access to the context must be
* gated by lock acquisition.
*
* If the user provides a context for the PxCudaContextManager, the context
* _must_ have either been created on the GPU ordinal returned by
* PxGetSuggestedCudaDeviceOrdinal() or on your graphics device.
*/
CUcontext* ctx;
/**
* \brief D3D device pointer or OpenGl context handle
*
* Only applicable when ctx is NULL, thus forcing a new context to be
* created. In that case, the created context will be bound to this
* graphics device.
*/
void* graphicsDevice;
/**
* \brief Application-specific GUID
*
* If your application employs PhysX modules that use CUDA you need to use a GUID
* so that patches for new architectures can be released for your game.You can obtain a GUID for your
* application from Nvidia.
*/
const char* appGUID;
/**
* \brief Application-specific device memory allocator
*
* the application can implement an device memory allocator, which inherites PxDeviceAllocatorCallback, and
* pass that to the PxCudaContextManagerDesc. The SDK will use that allocator to allocate device memory instead of
* using the defaul CUDA device memory allocator.
*/
PxDeviceAllocatorCallback* deviceAllocator;
PX_INLINE PxCudaContextManagerDesc() :
ctx (NULL),
graphicsDevice (NULL),
appGUID (NULL),
deviceAllocator (NULL)
{
}
};
/**
\brief A cuda kernel index providing an index to the cuda module and the function name
*/
struct PxKernelIndex
{
PxU32 moduleIndex;
const char* functionName;
};
/**
* \brief Manages thread locks, and task scheduling for a CUDA context
*
* A PxCudaContextManager manages access to a single CUDA context, allowing it to
* be shared between multiple scenes.
* The context must be acquired from the manager before using any CUDA APIs unless stated differently.
*
* The PxCudaContextManager is based on the CUDA driver API and explicitly does not
* support the CUDA runtime API (aka, CUDART).
*/
class PxCudaContextManager
{
public:
/**
* \brief Schedules clear operation for a device memory buffer on the specified stream
*
* The cuda context will get acquired automatically
*/
template<typename T>
void clearDeviceBufferAsync(T* deviceBuffer, PxU32 numElements, CUstream stream, PxI32 value = 0)
{
clearDeviceBufferAsyncInternal(deviceBuffer, numElements * sizeof(T), stream, value);
}
/**
* \brief Copies a device buffer to the host
*
* The cuda context will get acquired automatically
*/
template<typename T>
void copyDToH(T* hostBuffer, const T* deviceBuffer, PxU32 numElements)
{
copyDToHInternal(hostBuffer, deviceBuffer, numElements * sizeof(T));
}
/**
* \brief Copies a host buffer to the device
*
* The cuda context will get acquired automatically
*/
template<typename T>
void copyHToD(T* deviceBuffer, const T* hostBuffer, PxU32 numElements)
{
copyHToDInternal(deviceBuffer, hostBuffer, numElements * sizeof(T));
}
/**
* \brief Schedules device to host copy operation on the specified stream
*
* The cuda context will get acquired automatically
*/
template<typename T>
void copyDToHAsync(T* hostBuffer, const T* deviceBuffer, PxU32 numElements, CUstream stream)
{
copyDToHAsyncInternal(hostBuffer, deviceBuffer, numElements * sizeof(T), stream);
}
/**
* \brief Schedules host to device copy operation on the specified stream
*
* The cuda context will get acquired automatically
*/
template<typename T>
void copyHToDAsync(T* deviceBuffer, const T* hostBuffer, PxU32 numElements, CUstream stream)
{
copyHToDAsyncInternal(deviceBuffer, hostBuffer, numElements * sizeof(T), stream);
}
/**
* \brief Schedules device to device copy operation on the specified stream
*
* The cuda context will get acquired automatically
*/
template<typename T>
void copyDToDAsync(T* dstDeviceBuffer, const T* srcDeviceBuffer, PxU32 numElements, CUstream stream)
{
copyDToDAsyncInternal(dstDeviceBuffer, srcDeviceBuffer, numElements * sizeof(T), stream);
}
/**
* \brief Schedules a memset operation on the device on the specified stream. Only supported for 1 byte or 4 byte data types.
*
* The cuda context will get acquired automatically
*/
template<typename T>
void memsetAsync(T* dstDeviceBuffer, const T& value, PxU32 numElements, CUstream stream)
{
PX_COMPILE_TIME_ASSERT(sizeof(value) == sizeof(PxU32) || sizeof(value) == sizeof(PxU8));
if (sizeof(value) == sizeof(PxU32))
memsetD32AsyncInternal(dstDeviceBuffer, reinterpret_cast<const PxU32&>(value), numElements, stream);
else
memsetD8AsyncInternal(dstDeviceBuffer, reinterpret_cast<const PxU8&>(value), numElements, stream);
}
/**
* \brief Allocates a device buffer
*
* The cuda context will get acquired automatically
*/
template<typename T>
void allocDeviceBuffer(T*& deviceBuffer, PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__)
{
void* ptr = allocDeviceBufferInternal(PxU64(numElements) * sizeof(T), filename, line);
deviceBuffer = reinterpret_cast<T*>(ptr);
}
/**
* \brief Allocates a device buffer and returns the pointer to the memory
*
* The cuda context will get acquired automatically
*/
template<typename T>
T* allocDeviceBuffer(PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__)
{
void* ptr = allocDeviceBufferInternal(PxU64(numElements) * sizeof(T), filename, line);
return reinterpret_cast<T*>(ptr);
}
/**
* \brief Frees a device buffer
*
* The cuda context will get acquired automatically
*/
template<typename T>
void freeDeviceBuffer(T*& deviceBuffer)
{
freeDeviceBufferInternal(deviceBuffer);
deviceBuffer = NULL;
}
/**
* \brief Allocates a pinned host buffer
*
* A pinned host buffer can be used on the gpu after getting a mapped device pointer from the pinned host buffer pointer, see getMappedDevicePtr
* The cuda context will get acquired automatically
* @see getMappedDevicePtr
*/
template<typename T>
void allocPinnedHostBuffer(T*& pinnedHostBuffer, PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__)
{
void* ptr = allocPinnedHostBufferInternal(PxU64(numElements) * sizeof(T), filename, line);
pinnedHostBuffer = reinterpret_cast<T*>(ptr);
}
/**
* \brief Allocates a pinned host buffer and returns the pointer to the memory
*
* A pinned host buffer can be used on the gpu after getting a mapped device pointer from the pinned host buffer pointer, see getMappedDevicePtr
* The cuda context will get acquired automatically
* @see getMappedDevicePtr
*/
template<typename T>
T* allocPinnedHostBuffer(PxU32 numElements, const char* filename = __FILE__, PxI32 line = __LINE__)
{
void* ptr = allocPinnedHostBufferInternal(PxU64(numElements) * sizeof(T), filename, line);
return reinterpret_cast<T*>(ptr);
}
/**
* \brief Frees a pinned host buffer
*
* The cuda context will get acquired automatically
*/
template<typename T>
void freePinnedHostBuffer(T*& pinnedHostBuffer)
{
freePinnedHostBufferInternal(pinnedHostBuffer);
pinnedHostBuffer = NULL;
}
/**
* \brief Gets a mapped pointer from a pinned host buffer that can be used in cuda kernels directly
*
* Data access performance with a mapped pinned host pointer will be slower than using a device pointer directly
* but the changes done in the kernel will be available on the host immediately.
* The cuda context will get acquired automatically
*/
virtual CUdeviceptr getMappedDevicePtr(void* pinnedHostBuffer) = 0;
/**
* \brief Acquire the CUDA context for the current thread
*
* Acquisitions are allowed to be recursive within a single thread.
* You can acquire the context multiple times so long as you release
* it the same count.
*
* The context must be acquired before using most CUDA functions.
*/
virtual void acquireContext() = 0;
/**
* \brief Release the CUDA context from the current thread
*
* The CUDA context should be released as soon as practically
* possible, to allow other CPU threads to work efficiently.
*/
virtual void releaseContext() = 0;
/**
* \brief Return the CUcontext
*/
virtual CUcontext getContext() = 0;
/**
* \brief Return the CudaContext
*/
virtual PxCudaContext* getCudaContext() = 0;
/**
* \brief Context manager has a valid CUDA context
*
* This method should be called after creating a PxCudaContextManager,
* especially if the manager was responsible for allocating its own
* CUDA context (desc.ctx == NULL).
*/
virtual bool contextIsValid() const = 0;
/* Query CUDA context and device properties, without acquiring context */
virtual bool supportsArchSM10() const = 0; //!< G80
virtual bool supportsArchSM11() const = 0; //!< G92
virtual bool supportsArchSM12() const = 0; //!< GT200
virtual bool supportsArchSM13() const = 0; //!< GT260
virtual bool supportsArchSM20() const = 0; //!< GF100
virtual bool supportsArchSM30() const = 0; //!< GK100
virtual bool supportsArchSM35() const = 0; //!< GK110
virtual bool supportsArchSM50() const = 0; //!< GM100
virtual bool supportsArchSM52() const = 0; //!< GM200
virtual bool supportsArchSM60() const = 0; //!< GP100
virtual bool isIntegrated() const = 0; //!< true if GPU is an integrated (MCP) part
virtual bool canMapHostMemory() const = 0; //!< true if GPU map host memory to GPU (0-copy)
virtual int getDriverVersion() const = 0; //!< returns cached value of cuGetDriverVersion()
virtual size_t getDeviceTotalMemBytes() const = 0; //!< returns cached value of device memory size
virtual int getMultiprocessorCount() const = 0; //!< returns cache value of SM unit count
virtual unsigned int getClockRate() const = 0; //!< returns cached value of SM clock frequency
virtual int getSharedMemPerBlock() const = 0; //!< returns total amount of shared memory available per block in bytes
virtual int getSharedMemPerMultiprocessor() const = 0; //!< returns total amount of shared memory available per multiprocessor in bytes
virtual unsigned int getMaxThreadsPerBlock() const = 0; //!< returns the maximum number of threads per block
virtual const char *getDeviceName() const = 0; //!< returns device name retrieved from driver
virtual CUdevice getDevice() const = 0; //!< returns device handle retrieved from driver
virtual void setUsingConcurrentStreams(bool) = 0; //!< turn on/off using concurrent streams for GPU work
virtual bool getUsingConcurrentStreams() const = 0; //!< true if GPU work can run in concurrent streams
/* End query methods that don't require context to be acquired */
virtual void getDeviceMemoryInfo(size_t& free, size_t& total) const = 0; //!< get currently available and total memory
/**
* \brief Determine if the user has configured a dedicated PhysX GPU in the NV Control Panel
* \note If using CUDA Interop, this will always return false
* \returns 1 if there is a dedicated GPU
* 0 if there is NOT a dedicated GPU
* -1 if the routine is not implemented
*/
virtual int usingDedicatedGPU() const = 0;
/**
* \brief Get the cuda modules that have been loaded into this context on construction
* \return Pointer to the cuda modules
*/
virtual CUmodule* getCuModules() = 0;
/**
* \brief Release the PxCudaContextManager
*
* If the PxCudaContextManager created the CUDA context it was
* responsible for, it also frees that context.
*
* Do not release the PxCudaContextManager if there are any scenes
* using it. Those scenes must be released first.
*
*/
virtual void release() = 0;
protected:
/**
* \brief protected destructor, use release() method
*/
virtual ~PxCudaContextManager() {}
virtual void* allocDeviceBufferInternal(PxU64 numBytes, const char* filename = NULL, PxI32 line = -1) = 0;
virtual void* allocPinnedHostBufferInternal(PxU64 numBytes, const char* filename = NULL, PxI32 line = -1) = 0;
virtual void freeDeviceBufferInternal(void* deviceBuffer) = 0;
virtual void freePinnedHostBufferInternal(void* pinnedHostBuffer) = 0;
virtual void clearDeviceBufferAsyncInternal(void* deviceBuffer, PxU32 numBytes, CUstream stream, PxI32 value) = 0;
virtual void copyDToHAsyncInternal(void* hostBuffer, const void* deviceBuffer, PxU32 numBytes, CUstream stream) = 0;
virtual void copyHToDAsyncInternal(void* deviceBuffer, const void* hostBuffer, PxU32 numBytes, CUstream stream) = 0;
virtual void copyDToDAsyncInternal(void* dstDeviceBuffer, const void* srcDeviceBuffer, PxU32 numBytes, CUstream stream) = 0;
virtual void copyDToHInternal(void* hostBuffer, const void* deviceBuffer, PxU32 numBytes) = 0;
virtual void copyHToDInternal(void* deviceBuffer, const void* hostBuffer, PxU32 numBytes) = 0;
virtual void memsetD8AsyncInternal(void* dstDeviceBuffer, const PxU8& value, PxU32 numBytes, CUstream stream) = 0;
virtual void memsetD32AsyncInternal(void* dstDeviceBuffer, const PxU32& value, PxU32 numIntegers, CUstream stream) = 0;
};
#define PX_DEVICE_ALLOC(cudaContextManager, deviceBuffer, numElements) cudaContextManager->allocDeviceBuffer(deviceBuffer, numElements, PX_FL)
#define PX_DEVICE_ALLOC_T(T, cudaContextManager, numElements) cudaContextManager->allocDeviceBuffer<T>(numElements, PX_FL)
#define PX_DEVICE_FREE(cudaContextManager, deviceBuffer) cudaContextManager->freeDeviceBuffer(deviceBuffer);
#define PX_PINNED_HOST_ALLOC(cudaContextManager, pinnedHostBuffer, numElements) cudaContextManager->allocPinnedHostBuffer(pinnedHostBuffer, numElements, PX_FL)
#define PX_PINNED_HOST_ALLOC_T(T, cudaContextManager, numElements) cudaContextManager->allocPinnedHostBuffer<T>(numElements, PX_FL)
#define PX_PINNED_HOST_FREE(cudaContextManager, pinnedHostBuffer) cudaContextManager->freePinnedHostBuffer(pinnedHostBuffer);
/**
* \brief Convenience class for holding CUDA lock within a scope
*/
class PxScopedCudaLock
{
public:
/**
* \brief ScopedCudaLock constructor
*/
PxScopedCudaLock(PxCudaContextManager& ctx) : mCtx(&ctx)
{
mCtx->acquireContext();
}
/**
* \brief ScopedCudaLock destructor
*/
~PxScopedCudaLock()
{
mCtx->releaseContext();
}
protected:
/**
* \brief CUDA context manager pointer (initialized in the constructor)
*/
PxCudaContextManager* mCtx;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif // PX_SUPPORT_GPU_PHYSX
#endif
| 18,190 | C | 35.021782 | 159 | 0.734634 |
NVIDIA-Omniverse/PhysX/physx/include/cudamanager/PxCudaContext.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.
#ifndef PX_CUDA_CONTEX_H
#define PX_CUDA_CONTEX_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxCudaTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxCudaKernelParam
{
void* data;
size_t size;
};
// workaround for not being able to forward declare enums in PxCudaTypes.h.
// provides different automatic casting depending on whether cuda.h was included beforehand or not.
template<typename CUenum>
struct PxCUenum
{
PxU32 value;
PxCUenum(CUenum e) { value = PxU32(e); }
operator CUenum() const { return CUenum(value); }
};
#ifdef CUDA_VERSION
typedef PxCUenum<CUjit_option> PxCUjit_option;
typedef PxCUenum<CUresult> PxCUresult;
#else
typedef PxCUenum<PxU32> PxCUjit_option;
typedef PxCUenum<PxU32> PxCUresult;
#endif
#define PX_CUDA_KERNEL_PARAM(X) { (void*)&X, sizeof(X) }
#define PX_CUDA_KERNEL_PARAM2(X) (void*)&X
class PxDeviceAllocatorCallback;
/**
Cuda Context
*/
class PxCudaContext
{
protected:
virtual ~PxCudaContext() {}
PxDeviceAllocatorCallback* mAllocatorCallback;
public:
virtual void release() = 0;
virtual PxCUresult memAlloc(CUdeviceptr *dptr, size_t bytesize) = 0;
virtual PxCUresult memFree(CUdeviceptr dptr) = 0;
virtual PxCUresult memHostAlloc(void **pp, size_t bytesize, unsigned int Flags) = 0;
virtual PxCUresult memFreeHost(void *p) = 0;
virtual PxCUresult memHostGetDevicePointer(CUdeviceptr *pdptr, void *p, unsigned int Flags) = 0;
virtual PxCUresult moduleLoadDataEx(CUmodule *module, const void *image, unsigned int numOptions, PxCUjit_option *options, void **optionValues) = 0;
virtual PxCUresult moduleGetFunction(CUfunction *hfunc, CUmodule hmod, const char *name) = 0;
virtual PxCUresult moduleUnload(CUmodule hmod) = 0;
virtual PxCUresult streamCreate(CUstream *phStream, unsigned int Flags) = 0;
virtual PxCUresult streamCreateWithPriority(CUstream *phStream, unsigned int flags, int priority) = 0;
virtual PxCUresult streamFlush(CUstream hStream) = 0;
virtual PxCUresult streamWaitEvent(CUstream hStream, CUevent hEvent, unsigned int Flags) = 0;
virtual PxCUresult streamDestroy(CUstream hStream) = 0;
virtual PxCUresult streamSynchronize(CUstream hStream) = 0;
virtual PxCUresult eventCreate(CUevent *phEvent, unsigned int Flags) = 0;
virtual PxCUresult eventRecord(CUevent hEvent, CUstream hStream) = 0;
virtual PxCUresult eventQuery(CUevent hEvent) = 0;
virtual PxCUresult eventSynchronize(CUevent hEvent) = 0;
virtual PxCUresult eventDestroy(CUevent hEvent) = 0;
virtual PxCUresult launchKernel(
CUfunction f,
unsigned int gridDimX,
unsigned int gridDimY,
unsigned int gridDimZ,
unsigned int blockDimX,
unsigned int blockDimY,
unsigned int blockDimZ,
unsigned int sharedMemBytes,
CUstream hStream,
PxCudaKernelParam* kernelParams,
size_t kernelParamsSizeInBytes,
void** extra,
const char* file,
int line
) = 0;
// PT: same as above but without copying the kernel params to a local stack before the launch
// i.e. the kernelParams data is passed directly to the kernel.
virtual PxCUresult launchKernel(
CUfunction f,
PxU32 gridDimX, PxU32 gridDimY, PxU32 gridDimZ,
PxU32 blockDimX, PxU32 blockDimY, PxU32 blockDimZ,
PxU32 sharedMemBytes,
CUstream hStream,
void** kernelParams,
void** extra,
const char* file,
int line
) = 0;
virtual PxCUresult memcpyDtoH(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount) = 0;
virtual PxCUresult memcpyDtoHAsync(void* dstHost, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream) = 0;
virtual PxCUresult memcpyHtoD(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount) = 0;
virtual PxCUresult memcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount, CUstream hStream) = 0;
virtual PxCUresult memcpyDtoDAsync(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream) = 0;
virtual PxCUresult memcpyDtoD(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount) = 0;
virtual PxCUresult memcpyPeerAsync(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount, CUstream hStream) = 0;
virtual PxCUresult memsetD32Async(CUdeviceptr dstDevice, unsigned int ui, size_t N, CUstream hStream) = 0;
virtual PxCUresult memsetD8Async(CUdeviceptr dstDevice, unsigned char uc, size_t N, CUstream hStream) = 0;
virtual PxCUresult memsetD32(CUdeviceptr dstDevice, unsigned int ui, size_t N) = 0;
virtual PxCUresult memsetD16(CUdeviceptr dstDevice, unsigned short uh, size_t N) = 0;
virtual PxCUresult memsetD8(CUdeviceptr dstDevice, unsigned char uc, size_t N) = 0;
virtual PxCUresult getLastError() = 0;
PxDeviceAllocatorCallback* getAllocatorCallback() { return mAllocatorCallback; }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif // PX_SUPPORT_GPU_PHYSX
#endif
| 6,486 | C | 33.689839 | 167 | 0.760099 |
NVIDIA-Omniverse/PhysX/physx/include/cudamanager/PxCudaTypes.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.
#ifndef PX_CUDA_TYPES_H
#define PX_CUDA_TYPES_H
//type definitions to avoid forced inclusion of cuda.h
//if cuda.h is needed anyway, please include it before PxCudaContextManager.h, PxCudaContext.h or PxCudaTypes.h
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#ifndef CUDA_VERSION
#include "foundation/PxSimpleTypes.h"
#if PX_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
#endif
#if PX_P64_FAMILY
typedef unsigned long long CUdeviceptr;
#else
typedef unsigned int CUdeviceptr;
#endif
#if PX_CLANG
#pragma clang diagnostic pop
#endif
typedef int CUdevice;
typedef struct CUctx_st* CUcontext;
typedef struct CUmod_st* CUmodule;
typedef struct CUfunc_st* CUfunction;
typedef struct CUstream_st* CUstream;
typedef struct CUevent_st* CUevent;
typedef struct CUgraphicsResource_st* CUgraphicsResource;
#endif
#else
typedef struct CUstream_st* CUstream; // We declare some callbacks taking CUstream as an argument even when building with PX_SUPPORT_GPU_PHYSX = 0.
typedef struct CUevent_st* CUevent;
#endif // PX_SUPPORT_GPU_PHYSX
#endif
| 2,674 | C | 36.152777 | 147 | 0.777487 |
NVIDIA-Omniverse/PhysX/physx/include/pvd/PxPvdTransport.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_PVD_TRANSPORT_H
#define PX_PVD_TRANSPORT_H
/** \addtogroup pvd
@{
*/
#include "foundation/PxErrors.h"
#include "foundation/PxFlags.h"
#include "pvd/PxPvd.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief PxPvdTransport is an interface representing the data transport mechanism.
This class defines all services associated with the transport: configuration, connection, reading, writing etc.
It is owned by the application, and can be realized as a file or a socket (using one-line PxDefault<...> methods in
PhysXExtensions) or in a custom implementation. This is a class that is intended for use by PVD, not by the
application, the application entry points are PxPvd and PvdClient.
*/
class PxPvdTransport
{
public:
// connect, isConnected, disconnect, read, write, flush
/**
Connects to the Visual Debugger application.
return True if success
*/
virtual bool connect() = 0;
/**
Disconnects from the Visual Debugger application.
If we are still connected, this will kill the entire debugger connection.
*/
virtual void disconnect() = 0;
/**
* Return if connection to PVD is created.
*/
virtual bool isConnected() = 0;
/**
* write bytes to the other endpoint of the connection. should lock before witre. If an error occurs
* this connection will assume to be dead.
*/
virtual bool write(const uint8_t* inBytes, uint32_t inLength) = 0;
/*
lock this transport and return it
*/
virtual PxPvdTransport& lock() = 0;
/*
unlock this transport
*/
virtual void unlock() = 0;
/**
* send any data and block until we know it is at least on the wire.
*/
virtual void flush() = 0;
/**
* Return size of written data.
*/
virtual uint64_t getWrittenDataSize() = 0;
virtual void release() = 0;
protected:
virtual ~PxPvdTransport()
{
}
};
/**
\brief Create a default socket transport.
\param host host address of the pvd application.
\param port ip port used for pvd, should same as the port setting in pvd application.
\param timeoutInMilliseconds timeout when connect to pvd host.
*/
PX_C_EXPORT PxPvdTransport* PX_CALL_CONV
PxDefaultPvdSocketTransportCreate(const char* host, int port, unsigned int timeoutInMilliseconds);
/**
\brief Create a default file transport.
\param name full path filename used save captured pvd data, or NULL for a fake/test file transport.
*/
PX_C_EXPORT PxPvdTransport* PX_CALL_CONV PxDefaultPvdFileTransportCreate(const char* name);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,203 | C | 31.338461 | 115 | 0.743279 |
NVIDIA-Omniverse/PhysX/physx/include/pvd/PxPvd.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_PVD_H
#define PX_PVD_H
/** \addtogroup pvd
@{
*/
#include "foundation/PxFlags.h"
#include "foundation/PxProfiler.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxFoundation;
class PxPvdTransport;
/**
\brief types of instrumentation that PVD can do.
*/
struct PxPvdInstrumentationFlag
{
enum Enum
{
/**
\brief Send debugging information to PVD.
This information is the actual object data of the rigid statics, shapes,
articulations, etc. Sending this information has a noticeable impact on
performance and thus this flag should not be set if you want an accurate
performance profile.
*/
eDEBUG = 1 << 0,
/**
\brief Send profile information to PVD.
This information populates PVD's profile view. It has (at this time) negligible
cost compared to Debug information and makes PVD *much* more useful so it is quite
highly recommended.
This flag works together with a PxCreatePhysics parameter.
Using it allows the SDK to send profile events to PVD.
*/
ePROFILE = 1 << 1,
/**
\brief Send memory information to PVD.
The PVD sdk side hooks into the Foundation memory controller and listens to
allocation/deallocation events. This has a noticable hit on the first frame,
however, this data is somewhat compressed and the PhysX SDK doesn't allocate much
once it hits a steady state. This information also has a fairly negligible
impact and thus is also highly recommended.
This flag works together with a PxCreatePhysics parameter,
trackOutstandingAllocations. Using both of them together allows users to have
an accurate view of the overall memory usage of the simulation at the cost of
a hashtable lookup per allocation/deallocation. Again, PhysX makes a best effort
attempt not to allocate or deallocate during simulation so this hashtable lookup
tends to have no effect past the first frame.
Sending memory information without tracking outstanding allocations means that
PVD will accurate information about the state of the memory system before the
actual connection happened.
*/
eMEMORY = 1 << 2,
eALL = (eDEBUG | ePROFILE | eMEMORY)
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxPvdInstrumentationFlag.
@see PxPvdInstrumentationFlag
*/
typedef PxFlags<PxPvdInstrumentationFlag::Enum, uint8_t> PxPvdInstrumentationFlags;
PX_FLAGS_OPERATORS(PxPvdInstrumentationFlag::Enum, uint8_t)
/**
\brief PxPvd is the top-level class for the PVD framework, and the main customer interface for PVD
configuration.It is a singleton class, instantiated and owned by the application.
*/
class PxPvd : public physx::PxProfilerCallback
{
public:
/**
Connects the SDK to the PhysX Visual Debugger application.
\param transport transport for pvd captured data.
\param flags Flags to set.
return True if success
*/
virtual bool connect(PxPvdTransport& transport, PxPvdInstrumentationFlags flags) = 0;
/**
Disconnects the SDK from the PhysX Visual Debugger application.
If we are still connected, this will kill the entire debugger connection.
*/
virtual void disconnect() = 0;
/**
* Return if connection to PVD is created.
\param useCachedStatus
1> When useCachedStaus is false, isConnected() checks the lowlevel network status.
This can be slow because it needs to lock the lowlevel network stream. If isConnected() is
called frequently, the expense of locking can be significant.
2> When useCachedStatus is true, isConnected() checks the highlevel cached status with atomic access.
It is faster than locking, but the status may be different from the lowlevel network with latency of up to
one frame.
The reason for this is that the cached status is changed inside socket listener, which is not
called immediately when the lowlevel connection status changes.
*/
virtual bool isConnected(bool useCachedStatus = true) = 0;
/**
returns the PVD data transport
returns NULL if no transport is present.
*/
virtual PxPvdTransport* getTransport() = 0;
/**
Retrieves the PVD flags. See PxPvdInstrumentationFlags.
*/
virtual PxPvdInstrumentationFlags getInstrumentationFlags() = 0;
/**
\brief Releases the pvd instance.
*/
virtual void release() = 0;
protected:
virtual ~PxPvd()
{
}
};
/**
\brief Create a pvd instance.
\param foundation is the foundation instance that stores the allocator and error callbacks.
*/
PX_C_EXPORT PxPvd* PX_CALL_CONV PxCreatePvd(PxFoundation& foundation);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,302 | C | 34.21229 | 114 | 0.749921 |
NVIDIA-Omniverse/PhysX/physx/include/pvd/PxPvdSceneClient.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_PVD_SCENE_CLIENT_H
#define PX_PVD_SCENE_CLIENT_H
/** \addtogroup pvd
@{
*/
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
namespace pvdsdk
{
class PvdClient;
}
struct PxDebugPoint;
struct PxDebugLine;
struct PxDebugTriangle;
struct PxDebugText;
#if !PX_DOXYGEN
} // namespace physx
#endif
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief PVD scene Flags. They are disabled by default, and only works if PxPvdInstrumentationFlag::eDEBUG is set.
*/
struct PxPvdSceneFlag
{
enum Enum
{
eTRANSMIT_CONTACTS = (1 << 0), //! Transmits contact stream to PVD.
eTRANSMIT_SCENEQUERIES = (1 << 1), //! Transmits scene query stream to PVD.
eTRANSMIT_CONSTRAINTS = (1 << 2) //! Transmits constraints visualize stream to PVD.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxPvdSceneFlag.
@see PxPvdSceneFlag
*/
typedef PxFlags<PxPvdSceneFlag::Enum, PxU8> PxPvdSceneFlags;
PX_FLAGS_OPERATORS(PxPvdSceneFlag::Enum, PxU8)
/**
\brief Special client for PxScene.
It provides access to the PxPvdSceneFlag.
It also provides simple user debug services that associated scene position such as immediate rendering and camera updates.
*/
class PxPvdSceneClient
{
public:
/**
Sets the PVD flag. See PxPvdSceneFlag.
\param flag Flag to set.
\param value value the flag gets set to.
*/
virtual void setScenePvdFlag(PxPvdSceneFlag::Enum flag, bool value) = 0;
/**
Sets the PVD flags. See PxPvdSceneFlags.
\param flags Flags to set.
*/
virtual void setScenePvdFlags(PxPvdSceneFlags flags) = 0;
/**
Retrieves the PVD flags. See PxPvdSceneFlags.
*/
virtual PxPvdSceneFlags getScenePvdFlags() const = 0;
/**
update camera on PVD application's render window
*/
virtual void updateCamera(const char* name, const PxVec3& origin, const PxVec3& up, const PxVec3& target) = 0;
/**
draw points on PVD application's render window
*/
virtual void drawPoints(const physx::PxDebugPoint* points, PxU32 count) = 0;
/**
draw lines on PVD application's render window
*/
virtual void drawLines(const physx::PxDebugLine* lines, PxU32 count) = 0;
/**
draw triangles on PVD application's render window
*/
virtual void drawTriangles(const physx::PxDebugTriangle* triangles, PxU32 count) = 0;
/**
draw text on PVD application's render window
*/
virtual void drawText(const physx::PxDebugText& text) = 0;
/**
get the underlying client, for advanced users
*/
virtual physx::pvdsdk::PvdClient* getClientInternal() = 0;
protected:
virtual ~PxPvdSceneClient(){}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,313 | C | 28.547945 | 122 | 0.743102 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleTireFriction.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_TIREFRICTION_H
#define PX_VEHICLE_TIREFRICTION_H
#include "foundation/PxSimpleTypes.h"
#include "common/PxSerialFramework.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxMaterial;
class PxCollection;
class PxOutputStream;
/**
\brief Driving surface type. Each PxMaterial is associated with a corresponding PxVehicleDrivableSurfaceType.
@see PxMaterial, PxVehicleDrivableSurfaceToTireFrictionPairs
*/
struct PX_DEPRECATED PxVehicleDrivableSurfaceType
{
enum
{
eSURFACE_TYPE_UNKNOWN=0xffffffff
};
PxU32 mType;
};
/**
\brief Friction for each combination of driving surface type and tire type.
@see PxVehicleDrivableSurfaceType, PxVehicleTireData::mType
*/
class PX_DEPRECATED PxVehicleDrivableSurfaceToTireFrictionPairs
{
public:
friend class VehicleSurfaceTypeHashTable;
enum
{
eMAX_NB_SURFACE_TYPES=256
};
/**
\brief Allocate the memory for a PxVehicleDrivableSurfaceToTireFrictionPairs instance
that can hold data for combinations of tire type and surface type with up to maxNbTireTypes types of tire and maxNbSurfaceTypes types of surface.
\param[in] maxNbTireTypes is the maximum number of allowed tire types.
\param[in] maxNbSurfaceTypes is the maximum number of allowed surface types. Must be less than or equal to eMAX_NB_SURFACE_TYPES
\return a PxVehicleDrivableSurfaceToTireFrictionPairs instance that can be reused later with new type and friction data.
@see setup
*/
static PxVehicleDrivableSurfaceToTireFrictionPairs* allocate
(const PxU32 maxNbTireTypes, const PxU32 maxNbSurfaceTypes);
/**
\brief Set up a PxVehicleDrivableSurfaceToTireFrictionPairs instance for combinations of nbTireTypes tire types and nbSurfaceTypes surface types.
\param[in] nbTireTypes is the number of different types of tire. This value must be less than or equal to maxNbTireTypes specified in allocate().
\param[in] nbSurfaceTypes is the number of different types of surface. This value must be less than or equal to maxNbSurfaceTypes specified in allocate().
\param[in] drivableSurfaceMaterials is an array of PxMaterial pointers of length nbSurfaceTypes.
\param[in] drivableSurfaceTypes is an array of PxVehicleDrivableSurfaceType instances of length nbSurfaceTypes.
\note If the pointer to the PxMaterial that touches the tire is found in drivableSurfaceMaterials[x] then the surface type is drivableSurfaceTypes[x].mType
and the friction is the value that is set with setTypePairFriction(drivableSurfaceTypes[x].mType, PxVehicleTireData::mType, frictionValue).
\note A friction value of 1.0 will be assigned as default to each combination of tire and surface type. To override this use setTypePairFriction.
@see release, setTypePairFriction, getTypePairFriction, PxVehicleTireData.mType
*/
void setup
(const PxU32 nbTireTypes, const PxU32 nbSurfaceTypes,
const PxMaterial** drivableSurfaceMaterials, const PxVehicleDrivableSurfaceType* drivableSurfaceTypes);
/**
\brief Deallocate a PxVehicleDrivableSurfaceToTireFrictionPairs instance
*/
void release();
/**
\brief Set the friction for a specified pair of tire type and drivable surface type.
\param[in] surfaceType describes the surface type
\param[in] tireType describes the tire type.
\param[in] value describes the friction coefficient for the combination of surface type and tire type.
*/
void setTypePairFriction(const PxU32 surfaceType, const PxU32 tireType, const PxReal value);
/**
\brief Compute the surface type associated with a specified PxMaterial instance.
\param[in] surfaceMaterial is the material to be queried for its associated surface type.
\note The surface type may be used to query the friction of a surface type/tire type pair using getTypePairFriction()
\return The surface type associated with a specified PxMaterial instance.
If surfaceMaterial is not referenced by the PxVehicleDrivableSurfaceToTireFrictionPairs a value of 0 will be returned.
@see setup
@see getTypePairFriction
*/
PxU32 getSurfaceType(const PxMaterial& surfaceMaterial) const;
/**
\brief Return the friction for a specified combination of surface type and tire type.
\return The friction for a specified combination of surface type and tire type.
\note The final friction value used by the tire model is the value returned by getTypePairFriction
multiplied by the value computed from PxVehicleTireData::mFrictionVsSlipGraph
\note The surface type is associated with a PxMaterial. The mapping between the two may be queried using getSurfaceType().
@see PxVehicleTireData::mFrictionVsSlipGraph
@see getSurfaceType
*/
PxReal getTypePairFriction(const PxU32 surfaceType, const PxU32 tireType) const;
/**
\brief Return the friction for a specified combination of PxMaterial and tire type.
\return The friction for a specified combination of PxMaterial and tire type.
\note The final friction value used by the tire model is the value returned by getTypePairFriction
multiplied by the value computed from PxVehicleTireData::mFrictionVsSlipGraph
\note If surfaceMaterial is not referenced by the PxVehicleDrivableSurfaceToTireFrictionPairs
a surfaceType of value 0 will be assumed and the corresponding friction value will be returned.
@see PxVehicleTireData::mFrictionVsSlipGraph
*/
PxReal getTypePairFriction(const PxMaterial& surfaceMaterial, const PxU32 tireType) const;
/**
\brief Return the maximum number of surface types
\return The maximum number of surface types
@see allocate
*/
PX_FORCE_INLINE PxU32 getMaxNbSurfaceTypes() const {return mMaxNbSurfaceTypes;}
/**
\brief Return the maximum number of tire types
\return The maximum number of tire types
@see allocate
*/
PX_FORCE_INLINE PxU32 getMaxNbTireTypes() const {return mMaxNbTireTypes;}
/**
\brief Binary serialization of a PxVehicleDrivableSurfaceToTireFrictionPairs instance.
The PxVehicleDrivableSurfaceToTireFrictionPairs instance is serialized to a PxOutputStream.
The materials referenced by the PxVehicleDrivableSurfaceToTireFrictionPairs instance are
serialized to a PxCollection.
\param[in] frictionTable is the PxVehicleDrivableSurfaceToTireFrictionPairs instance to be serialized.
\param[in] materialIds are unique ids that will be used to add the materials to the collection.
\param[in] nbMaterialIds is the length of the materialIds array. It must be sufficient to cover all materials.
\param[out] collection is the PxCollection instance that is to be used to serialize the PxMaterial instances referenced by the
PxVehicleDrivableSurfaceToTireFrictionPairs instance.
\param[out] stream contains the memory block for the binary serialized friction table.
\note If a material has already been added to the collection with a PxSerialObjectId, it will not be added again.
\note If all materials have already been added to the collection with a PxSerialObjectId, it is legal to pass a NULL ptr for the materialIds array.
\note frictionTable references PxMaterial instances, which are serialized using PxCollection.
The PxCollection instance may be used to serialize an entire scene that also references some or none of those material instances
or particular objects in a scene or nothing at all. The complementary deserialize() function requires the same collection instance
or more typically a deserialized copy of the collection to be passed as a function argument.
@see deserializeFromBinary
*/
static void serializeToBinary(const PxVehicleDrivableSurfaceToTireFrictionPairs& frictionTable, const PxSerialObjectId* materialIds, const PxU32 nbMaterialIds, PxCollection* collection, PxOutputStream& stream);
/**
\brief Deserialize from a memory block to create a PxVehicleDrivableSurfaceToTireFrictionPairs instance.
\param[in] collection contains the PxMaterial instances that will be referenced by the friction table.
\param[in] memBlock is a binary array that may be retrieved or copied from the stream in the complementary serializeToBinary function.
\return A PxVehicleDrivableSurfaceToTireFrictionPairs instance whose base address is equal to the memBlock ptr.
@see serializeToBinary
*/
static PxVehicleDrivableSurfaceToTireFrictionPairs* deserializeFromBinary(const PxCollection& collection, void* memBlock);
private:
/**
\brief Ptr to base address of a 2d PxReal array with dimensions [mNbSurfaceTypes][mNbTireTypes]
\note Each element of the array describes the maximum friction provided by a surface type-tire type combination.
eg the friction corresponding to a combination of surface type x and tire type y is mPairs[x][y]
*/
PxReal* mPairs;
/**
\brief Ptr to 1d array of material ptrs that is of length mNbSurfaceTypes.
\note If the PxMaterial that touches the tire corresponds to mDrivableSurfaceMaterials[x] then the drivable surface
type is mDrivableSurfaceTypes[x].mType and the friction for that contact is mPairs[mDrivableSurfaceTypes[x].mType][y],
assuming a tire type y.
\note If the PxMaterial that touches the tire is not found in mDrivableSurfaceMaterials then the friction is
mPairs[0][y], assuming a tire type y.
*/
const PxMaterial** mDrivableSurfaceMaterials;
/**
\brief Ptr to 1d array of PxVehicleDrivableSurfaceType that is of length mNbSurfaceTypes.
\note If the PxMaterial that touches the tire is found in mDrivableSurfaceMaterials[x] then the drivable surface
type is mDrivableSurfaceTypes[x].mType and the friction for that contact is mPairs[mDrivableSurfaceTypes[x].mType][y],
assuming a tire type y.
\note If the PxMaterial that touches the tire is not found in mDrivableSurfaceMaterials then the friction is
mPairs[0][y], assuming a tire type y.
*/
PxVehicleDrivableSurfaceType* mDrivableSurfaceTypes;
/**
\brief A PxSerialObjectId per surface type used internally for serialization.
*/
PxSerialObjectId* mMaterialSerialIds;
/**
\brief Number of different driving surface types.
\note mDrivableSurfaceMaterials and mDrivableSurfaceTypes are both 1d arrays of length mMaxNbSurfaceTypes.
\note mNbSurfaceTypes must be less than or equal to mMaxNbSurfaceTypes.
*/
PxU32 mNbSurfaceTypes;
/**
\brief Maximum number of different driving surface types.
\note mMaxNbSurfaceTypes must be less than or equal to eMAX_NB_SURFACE_TYPES.
*/
PxU32 mMaxNbSurfaceTypes;
/**
\brief Number of different tire types.
\note Tire types stored in PxVehicleTireData.mType
*/
PxU32 mNbTireTypes;
/**
\brief Maximum number of different tire types.
\note Tire types stored in PxVehicleTireData.mType
*/
PxU32 mMaxNbTireTypes;
PxVehicleDrivableSurfaceToTireFrictionPairs(){}
~PxVehicleDrivableSurfaceToTireFrictionPairs(){}
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDrivableSurfaceToTireFrictionPairs) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 12,491 | C | 44.425454 | 211 | 0.798175 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleDriveTank.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_DRIVE_TANK_H
#define PX_VEHICLE_DRIVE_TANK_H
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleComponents.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxFilterData;
class PxGeometry;
class PxPhysics;
class PxVehicleDrivableSurfaceToTireFrictionPairs;
class PxShape;
class PxMaterial;
class PxRigidDynamic;
/**
\brief The ordering of the wheels of a PxVehicleDriveTank.
@see PxVehicleWheelsSimData, PxVehicleWheelsDynData
*/
struct PX_DEPRECATED PxVehicleDriveTankWheelOrder
{
enum Enum
{
eFRONT_LEFT=0,
eFRONT_RIGHT,
e1ST_FROM_FRONT_LEFT,
e1ST_FROM_FRONT_RIGHT,
e2ND_FROM_FRONT_LEFT,
e2ND_FROM_FRONT_RIGHT,
e3RD_FROM_FRONT_LEFT,
e3RD_FROM_FRONT_RIGHT,
e4TH_FROM_FRONT_LEFT,
e4TH_FROM_FRONT_RIGHT,
e5TH_FROM_FRONT_LEFT,
e5TH_FROM_FRONT_RIGHT,
e6TH_FROM_FRONT_LEFT,
e6TH_FROM_FRONT_RIGHT,
e7TH_FROM_FRONT_LEFT,
e7TH_FROM_FRONT_RIGHT,
e8TH_FROM_FRONT_LEFT,
e8TH_FROM_FRONT_RIGHT,
e9TH_FROM_FRONT_LEFT,
e9TH_FROM_FRONT_RIGHT
};
};
/**
\brief The control inputs for a PxVehicleDriveTank.
\note The values of eANALOG_INPUT_THRUST_LEFT and eANALOG_INPUT_THRUST_RIGHT determine how much
of the total available drive torque is diverted to the left and right wheels. These entries in the
enumerated list represent the state of the left and right control sticks of a tank. The total available
drive torque available is controlled by eANALOG_INPUT_ACCEL, which represents the state of the acceleration
pedal and controls how much torque will be applied to the engine.
\note To accelerate forwards eANALOG_INPUT_ACCEL must be greater than zero so that torque is applied to drive the
engine, while eANALOG_INPUT_THRUST_LEFT and eANALOG_INPUT_THRUST_RIGHT must also be greater than zero
to divert the available drive torque to the left and wheels. If eANALOG_INPUT_THRUST_LEFT > eANALOG_INPUT_THRUST_RIGHT
the tank will turn to the right. If eANALOG_INPUT_THRUST_RIGHT > eANALOG_INPUT_THRUST_LEFT
the tank will turn to the left.
@see PxVehicleDriveDynData::setAnalogInput, PxVehicleDriveDynData::getAnalogInput
*/
struct PX_DEPRECATED PxVehicleDriveTankControl
{
enum Enum
{
eANALOG_INPUT_ACCEL=0,
eANALOG_INPUT_BRAKE_LEFT,
eANALOG_INPUT_BRAKE_RIGHT,
eANALOG_INPUT_THRUST_LEFT,
eANALOG_INPUT_THRUST_RIGHT,
eMAX_NB_DRIVETANK_ANALOG_INPUTS
};
};
/**
\brief Two driving models are supported.
\note If eSTANDARD is chosen the left and right wheels are always driven in the same direction. If the tank is in
a forward gear the left and right wheels will all be driven forwards, while in reverse gear the left and right wheels
will all be driven backwards. With eSTANDARD the legal range of left and right thrust is (0,1).
\note If eSPECIAL is chosen it is possible to drive the left and right wheels in different directions.
With eSPECIAL the legal range of left and right thrust is (-1,1). In forward(reverse) gear negative thrust values drive the wheels
backwards(forwards), while positive thrust values drives the wheels forwards(backwards).
\note A sharp left turn can be achieved in eSTANDARD mode by braking with the left wheels and thrusting forward with the
right wheels. A smaller turning circle can theoretically be achieved in eSPECIAL mode by applying negative thrust to the left wheels and positive
thrust to the right wheels.
\note In both modes the legal ranges of acceleration and left/right brake are all (0,1).
@see PxVehicleDriveTank::setDriveModel
*/
struct PX_DEPRECATED PxVehicleDriveTankControlModel
{
enum Enum
{
eSTANDARD=0,
eSPECIAL
};
};
/**
\brief Data structure with instanced dynamics data and configuration data of a tank.
*/
class PX_DEPRECATED PxVehicleDriveTank : public PxVehicleDrive
{
public:
friend class PxVehicleUpdate;
/**
\brief Allocate a PxVehicleTankDrive instance for a tank with nbWheels
\param[in] nbWheels is the number of wheels on the vehicle.
\note It is assumed that all wheels are driven wheels.
\return The instantiated vehicle.
@see free, setup
*/
static PxVehicleDriveTank* allocate(const PxU32 nbWheels);
/**
\brief Deallocate a PxVehicleDriveTank instance.
@see allocate
*/
void free();
/**
\brief Set up a tank using simulation data for the wheels and drive model.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the tank in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the tank. The tank instance takes a copy of this data.
\param[in] driveData describes the properties of the tank's drive model (gears/engine/clutch/autobox). The tank instance takes a copy of this data.
\param[in] nbDrivenWheels is the number of wheels on the tank.
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
\note nbDrivenWheels must be an even number
\note The wheels must be arranged according to PxVehicleDriveTankWheelOrder; that is,
the even wheels are on the left side of the tank and the odd wheels are on the right side of the tank.
*/
void setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData& driveData,
const PxU32 nbDrivenWheels);
/**
\brief Allocate and set up a tank using simulation data for the wheels and drive model.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the tank.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the tank in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the tank. The tank instance takes a copy of this data.
\param[in] driveData describes the properties of the tank's drive model (gears/engine/clutch/differential/autobox). The tank instance takes a copy of this data.
\param[in] nbDrivenWheels is the number of wheels on the tank.
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
\return The instantiated vehicle.
@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
*/
static PxVehicleDriveTank* create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData& driveData,
const PxU32 nbDrivenWheels);
/**
\brief Set the control model used by the tank.
\note eDRIVE_MODEL_STANDARD: turning achieved by braking on one side, accelerating on the other side.
\note eDRIVE_MODEL_SPECIAL: turning achieved by accelerating forwards on one side, accelerating backwards on the other side.
\note The default value is eDRIVE_MODEL_STANDARD
*/
void setDriveModel(const PxVehicleDriveTankControlModel::Enum driveModel)
{
mDriveModel=driveModel;
}
/**
\brief Return the control model used by the tank.
*/
PxVehicleDriveTankControlModel::Enum getDriveModel() const {return mDriveModel;}
/**
\brief Set a vehicle to its rest state. Aside from the rigid body transform, this will set the vehicle and rigid body
to the state they were in immediately after setup or create.
\note Calling setToRestState invalidates the cached raycast hit planes under each wheel meaning that suspension line
raycasts need to be performed at least once with PxVehicleSuspensionRaycasts before calling PxVehicleUpdates.
@see setup, create, PxVehicleSuspensionRaycasts, PxVehicleUpdates
*/
void setToRestState();
/**
\brief Simulation data that models vehicle components
@see setup, create
*/
PxVehicleDriveSimData mDriveSimData;
private:
/**
\brief Test if the instanced dynamics and configuration data has legal values.
*/
bool isValid() const;
/**
\brief Drive model
@see setDriveModel, getDriveModel, PxVehicleDriveTankControlModel
*/
PxVehicleDriveTankControlModel::Enum mDriveModel;
PxU32 mPad[3];
//serialization
public:
PxVehicleDriveTank(PxBaseFlags baseFlags) : PxVehicleDrive(baseFlags) {}
static PxVehicleDriveTank* createObject(PxU8*& address, PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
virtual const char* getConcreteTypeName() const { return "PxVehicleDriveTank"; }
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxVehicleDriveTank", PxVehicleDrive); }
protected:
PxVehicleDriveTank();
~PxVehicleDriveTank(){}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveTank) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 10,691 | C | 38.6 | 185 | 0.77598 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleComponents.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_COMPONENTS_H
#define PX_VEHICLE_COMPONENTS_H
#include "foundation/PxMemory.h"
#include "foundation/PxVec3.h"
#include "common/PxCoreUtilityTypes.h"
#include "vehicle/PxVehicleSDK.h"
#include "common/PxTypeInfo.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PX_DEPRECATED PxVehicleChassisData
{
public:
friend class PxVehicleDriveSimData4W;
PxVehicleChassisData()
: mMOI(PxVec3(0,0,0)),
mMass(1500),
mCMOffset(PxVec3(0,0,0))
{
}
/**
\brief Moment of inertia of vehicle rigid body actor.
\note Specified in kilograms metres-squared (kg m^2).
*/
PxVec3 mMOI;
/**
\brief Mass of vehicle rigid body actor.
\note Specified in kilograms (kg).
*/
PxReal mMass;
/**
\brief Center of mass offset of vehicle rigid body actor.
\note Specified in metres (m).
*/
PxVec3 mCMOffset;
private:
PxReal pad;
bool isValid() const;
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleChassisData)& 0x0f));
class PX_DEPRECATED PxVehicleEngineData
{
public:
friend class PxVehicleDriveSimData;
enum
{
eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES = 8
};
PxVehicleEngineData()
: mMOI(1.0f),
mPeakTorque(500.0f),
mMaxOmega(600.0f),
mDampingRateFullThrottle(0.15f),
mDampingRateZeroThrottleClutchEngaged(2.0f),
mDampingRateZeroThrottleClutchDisengaged(0.35f)
{
mTorqueCurve.addPair(0.0f, 0.8f);
mTorqueCurve.addPair(0.33f, 1.0f);
mTorqueCurve.addPair(1.0f, 0.8f);
mRecipMOI=1.0f/mMOI;
mRecipMaxOmega=1.0f/mMaxOmega;
}
/**
\brief Graph of normalized torque (torque/mPeakTorque) against normalized engine speed ( engineRotationSpeed / mMaxOmega ).
\note The normalized engine speed is the x-axis of the graph, while the normalized torque is the y-axis of the graph.
*/
PxFixedSizeLookupTable<eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES> mTorqueCurve;
/**
\brief Moment of inertia of the engine around the axis of rotation.
\note Specified in kilograms metres-squared (kg m^2)
*/
PxReal mMOI;
/**
\brief Maximum torque available to apply to the engine when the accelerator pedal is at maximum.
\note The torque available is the value of the accelerator pedal (in range [0, 1]) multiplied by the normalized torque as computed from mTorqueCurve multiplied by mPeakTorque.
\note Specified in kilograms metres-squared per second-squared (kg m^2 s^-2).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mPeakTorque;
/**
\brief Maximum rotation speed of the engine.
\note Specified in radians per second (s^-1).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMaxOmega;
/**
\brief Damping rate of engine when full throttle is applied.
\note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation
between mDampingRateZeroThrottleClutchEngaged and mDampingRateFullThrottle:
mDampingRateZeroThrottleClutchEngaged + (mDampingRateFullThrottle-mDampingRateZeroThrottleClutchEngaged)*acceleratorPedal;
\note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation
between mDampingRateZeroThrottleClutchDisengaged and mDampingRateFullThrottle:
mDampingRateZeroThrottleClutchDisengaged + (mDampingRateFullThrottle-mDampingRateZeroThrottleClutchDisengaged)*acceleratorPedal;
\note Specified in kilograms metres-squared per second (kg m^2 s^-1).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mDampingRateFullThrottle;
/**
\brief Damping rate of engine when full throttle is applied.
\note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation
between mDampingRateZeroThrottleClutchEngaged and mDampingRateFullThrottle:
mDampingRateZeroThrottleClutchEngaged + (mDampingRateFullThrottle-mDampingRateZeroThrottleClutchEngaged)*acceleratorPedal;
\note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation
between mDampingRateZeroThrottleClutchDisengaged and mDampingRateFullThrottle:
mDampingRateZeroThrottleClutchDisengaged + (mDampingRateFullThrottle-mDampingRateZeroThrottleClutchDisengaged)*acceleratorPedal;
\note Specified in kilograms metres-squared per second (kg m^2 s^-1).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mDampingRateZeroThrottleClutchEngaged;
/**
\brief Damping rate of engine when full throttle is applied.
\note If the clutch is engaged (any gear except neutral) then the damping rate applied at run-time is an interpolation
between mDampingRateZeroThrottleClutchEngaged and mDampingRateFullThrottle:
mDampingRateZeroThrottleClutchEngaged + (mDampingRateFullThrottle-mDampingRateZeroThrottleClutchEngaged)*acceleratorPedal;
\note If the clutch is disengaged (in neutral gear) the damping rate applied at run-time is an interpolation
between mDampingRateZeroThrottleClutchDisengaged and mDampingRateFullThrottle:
mDampingRateZeroThrottleClutchDisengaged + (mDampingRateFullThrottle-mDampingRateZeroThrottleClutchDisengaged)*acceleratorPedal;
\note Specified in kilograms metres-squared per second (kg m^2 s^-1).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mDampingRateZeroThrottleClutchDisengaged;
/**
\brief Return value of mRecipMOI(=1.0f/mMOI) that is automatically set by PxVehicleDriveSimData::setEngineData
*/
PX_FORCE_INLINE PxReal getRecipMOI() const {return mRecipMOI;}
/**
\brief Return value of mRecipMaxOmega( = 1.0f / mMaxOmega ) that is automatically set by PxVehicleDriveSimData::setEngineData
*/
PX_FORCE_INLINE PxReal getRecipMaxOmega() const {return mRecipMaxOmega;}
private:
/**
\brief Reciprocal of the engine moment of inertia.
\note Not necessary to set this value because it is set by PxVehicleDriveSimData::setEngineData
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mRecipMOI;
/**
\brief Reciprocal of the maximum rotation speed of the engine.
\note Not necessary to set this value because it is set by PxVehicleDriveSimData::setEngineData
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mRecipMaxOmega;
bool isValid() const;
//serialization
public:
PxVehicleEngineData(const PxEMPTY) : mTorqueCurve(PxEmpty) {}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleEngineData)& 0x0f));
class PX_DEPRECATED PxVehicleGearsData
{
public:
friend class PxVehicleDriveSimData;
enum Enum
{
eREVERSE=0,
eNEUTRAL,
eFIRST,
eSECOND,
eTHIRD,
eFOURTH,
eFIFTH,
eSIXTH,
eSEVENTH,
eEIGHTH,
eNINTH,
eTENTH,
eELEVENTH,
eTWELFTH,
eTHIRTEENTH,
eFOURTEENTH,
eFIFTEENTH,
eSIXTEENTH,
eSEVENTEENTH,
eEIGHTEENTH,
eNINETEENTH,
eTWENTIETH,
eTWENTYFIRST,
eTWENTYSECOND,
eTWENTYTHIRD,
eTWENTYFOURTH,
eTWENTYFIFTH,
eTWENTYSIXTH,
eTWENTYSEVENTH,
eTWENTYEIGHTH,
eTWENTYNINTH,
eTHIRTIETH,
eGEARSRATIO_COUNT
};
PxVehicleGearsData()
: mFinalRatio(4.0f),
mNbRatios(7),
mSwitchTime(0.5f)
{
mRatios[PxVehicleGearsData::eREVERSE]=-4.0f;
mRatios[PxVehicleGearsData::eNEUTRAL]=0.0f;
mRatios[PxVehicleGearsData::eFIRST]=4.0f;
mRatios[PxVehicleGearsData::eSECOND]=2.0f;
mRatios[PxVehicleGearsData::eTHIRD]=1.5f;
mRatios[PxVehicleGearsData::eFOURTH]=1.1f;
mRatios[PxVehicleGearsData::eFIFTH]=1.0f;
for(PxU32 i = PxVehicleGearsData::eSIXTH; i < PxVehicleGearsData::eGEARSRATIO_COUNT; ++i)
mRatios[i]=0.f;
}
/**
\brief Gear ratios
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mRatios[PxVehicleGearsData::eGEARSRATIO_COUNT];
/**
\brief Gear ratio applied is mRatios[currentGear]*finalRatio
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mFinalRatio;
/**
\brief Number of gears (including reverse and neutral).
<b>Range:</b> (0, MAX_NB_GEAR_RATIOS)<br>
*/
PxU32 mNbRatios;
/**
\brief Time it takes to switch gear.
\note Specified in seconds (s).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mSwitchTime;
private:
PxReal mPad;
bool isValid() const;
//serialization
public:
PxVehicleGearsData(const PxEMPTY) {}
PxReal getGearRatio(PxVehicleGearsData::Enum a) const {return mRatios[a];}
void setGearRatio(PxVehicleGearsData::Enum a, PxReal ratio) { mRatios[a] = ratio;}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleGearsData)& 0x0f));
class PX_DEPRECATED PxVehicleAutoBoxData
{
public:
friend class PxVehicleDriveSimData;
PxVehicleAutoBoxData()
{
for(PxU32 i=0;i<PxVehicleGearsData::eGEARSRATIO_COUNT;i++)
{
mUpRatios[i]=0.65f;
mDownRatios[i]=0.50f;
}
//Not sure how important this is but we want to kick out of neutral very quickly.
mUpRatios[PxVehicleGearsData::eNEUTRAL]=0.15f;
//Set the latency time in an unused element of one of the arrays.
mDownRatios[PxVehicleGearsData::eREVERSE]=2.0f;
}
/**
\brief Value of ( engineRotationSpeed / PxVehicleEngineData::mMaxOmega ) that is high enough to increment gear.
\note When ( engineRotationSpeed / PxVehicleEngineData::mMaxOmega ) > mUpRatios[currentGear] the autobox will begin
a transition to currentGear+1 unless currentGear is the highest possible gear or neutral or reverse.
<b>Range:</b> [0, 1]<br>
*/
PxReal mUpRatios[PxVehicleGearsData::eGEARSRATIO_COUNT];
/**
\brief Value of engineRevs/maxEngineRevs that is low enough to decrement gear.
\note When ( engineRotationSpeed / PxVehicleEngineData::mMaxOmega ) < mDownRatios[currentGear] the autobox will begin
a transition to currentGear-1 unless currentGear is first gear or neutral or reverse.
<b>Range:</b> [0, 1]<br>
*/
PxReal mDownRatios[PxVehicleGearsData::eGEARSRATIO_COUNT];
/**
\brief Set the latency time of the autobox.
\note Latency time is the minimum time that must pass between each gear change that is initiated by the autobox.
The auto-box will only attempt to initiate another gear change up or down if the simulation time that has passed since the most recent
automated gear change is greater than the specified latency.
\note Specified in seconds (s).
@see getLatency
*/
void setLatency(const PxReal latency)
{
mDownRatios[PxVehicleGearsData::eREVERSE]=latency;
}
/**
\brief Get the latency time of the autobox.
\note Specified in seconds (s).
@see setLatency
*/
PxReal getLatency() const
{
return mDownRatios[PxVehicleGearsData::eREVERSE];
}
private:
bool isValid() const;
//serialization
public:
PxVehicleAutoBoxData(const PxEMPTY) {}
PxReal getUpRatios(PxVehicleGearsData::Enum a) const {return mUpRatios[a];}
void setUpRatios(PxVehicleGearsData::Enum a, PxReal ratio) { mUpRatios[a] = ratio;}
PxReal getDownRatios(PxVehicleGearsData::Enum a) const {return mDownRatios[a];}
void setDownRatios(PxVehicleGearsData::Enum a, PxReal ratio) { mDownRatios[a] = ratio;}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleAutoBoxData)& 0x0f));
class PX_DEPRECATED PxVehicleDifferential4WData
{
public:
friend class PxVehicleDriveSimData4W;
enum Enum
{
eDIFF_TYPE_LS_4WD, //limited slip differential for car with 4 driven wheels
eDIFF_TYPE_LS_FRONTWD, //limited slip differential for car with front-wheel drive
eDIFF_TYPE_LS_REARWD, //limited slip differential for car with rear-wheel drive
eDIFF_TYPE_OPEN_4WD, //open differential for car with 4 driven wheels
eDIFF_TYPE_OPEN_FRONTWD, //open differential for car with front-wheel drive
eDIFF_TYPE_OPEN_REARWD, //open differential for car with rear-wheel drive
eMAX_NB_DIFF_TYPES
};
PxVehicleDifferential4WData()
: mFrontRearSplit(0.45f),
mFrontLeftRightSplit(0.5f),
mRearLeftRightSplit(0.5f),
mCentreBias(1.3f),
mFrontBias(1.3f),
mRearBias(1.3f),
mType(PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD)
{
}
/**
\brief Ratio of torque split between front and rear (>0.5 means more to front, <0.5 means more to rear).
\note Only applied to DIFF_TYPE_LS_4WD and eDIFF_TYPE_OPEN_4WD
<b>Range:</b> [0, 1]<br>
*/
PxReal mFrontRearSplit;
/**
\brief Ratio of torque split between front-left and front-right (>0.5 means more to front-left, <0.5 means more to front-right).
\note Only applied to DIFF_TYPE_LS_4WD and eDIFF_TYPE_OPEN_4WD and eDIFF_TYPE_LS_FRONTWD
<b>Range:</b> [0, 1]<br>
*/
PxReal mFrontLeftRightSplit;
/**
\brief Ratio of torque split between rear-left and rear-right (>0.5 means more to rear-left, <0.5 means more to rear-right).
\note Only applied to DIFF_TYPE_LS_4WD and eDIFF_TYPE_OPEN_4WD and eDIFF_TYPE_LS_REARWD
<b>Range:</b> [0, 1]<br>
*/
PxReal mRearLeftRightSplit;
/**
\brief Maximum allowed ratio of average front wheel rotation speed and rear wheel rotation speeds
The differential will divert more torque to the slower wheels when the bias is exceeded.
\note Only applied to DIFF_TYPE_LS_4WD
<b>Range:</b> [1, PX_MAX_F32)<br>
*/
PxReal mCentreBias;
/**
\brief Maximum allowed ratio of front-left and front-right wheel rotation speeds.
The differential will divert more torque to the slower wheel when the bias is exceeded.
\note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_FRONTWD
<b>Range:</b> [1, PX_MAX_F32)<br>
*/
PxReal mFrontBias;
/**
\brief Maximum allowed ratio of rear-left and rear-right wheel rotation speeds.
The differential will divert more torque to the slower wheel when the bias is exceeded.
\note Only applied to DIFF_TYPE_LS_4WD and DIFF_TYPE_LS_REARWD
<b>Range:</b> [1, PX_MAX_F32)<br>
*/
PxReal mRearBias;
/**
\brief Type of differential.
<b>Range:</b> [DIFF_TYPE_LS_4WD, DIFF_TYPE_OPEN_FRONTWD]<br>
*/
PxVehicleDifferential4WData::Enum mType;
private:
PxReal mPad[1];
bool isValid() const;
//serialization
public:
PxVehicleDifferential4WData(const PxEMPTY) {}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDifferential4WData)& 0x0f));
class PX_DEPRECATED PxVehicleDifferentialNWData
{
public:
friend class PxVehicleDriveSimDataNW;
friend class PxVehicleUpdate;
PxVehicleDifferentialNWData()
{
PxMemSet(mBitmapBuffer, 0, sizeof(PxU32) * (((PX_MAX_NB_WHEELS + 31) & ~31) >> 5));
mNbDrivenWheels=0;
mInvNbDrivenWheels=0.0f;
}
/**
\brief Set a specific wheel to be driven or non-driven by the differential.
\note The available drive torque will be split equally between all driven wheels.
Zero torque will be applied to non-driven wheels.
The default state of each wheel is to be uncoupled to the differential.
*/
void setDrivenWheel(const PxU32 wheelId, const bool drivenState);
/**
\brief Test if a specific wheel has been configured as a driven or non-driven wheel.
*/
bool getIsDrivenWheel(const PxU32 wheelId) const;
private:
PxU32 mBitmapBuffer[((PX_MAX_NB_WHEELS + 31) & ~31) >> 5];
PxU32 mNbDrivenWheels;
PxReal mInvNbDrivenWheels;
PxU32 mPad;
bool isValid() const;
//serialization
public:
PxVehicleDifferentialNWData(const PxEMPTY) {}
PxU32 getDrivenWheelStatus() const;
void setDrivenWheelStatus(PxU32 status);
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDifferentialNWData)& 0x0f));
class PX_DEPRECATED PxVehicleAckermannGeometryData
{
public:
friend class PxVehicleDriveSimData4W;
PxVehicleAckermannGeometryData()
: mAccuracy(1.0f),
mFrontWidth(0.0f), //Must be filled out
mRearWidth(0.0f), //Must be filled out
mAxleSeparation(0.0f) //Must be filled out
{
}
/**
\brief Accuracy of Ackermann steer calculation.
\note Accuracy with value 0.0 results in no Ackermann steer-correction, while
accuracy with value 1.0 results in perfect Ackermann steer-correction.
\note Perfect Ackermann steer correction modifies the steer angles applied to the front-left and
front-right wheels so that the perpendiculars to the wheels' longitudinal directions cross the
extended vector of the rear axle at the same point. It is also applied to any steer angle applied
to the rear wheels but instead using the extended vector of the front axle.
\note In general, more steer correction produces better cornering behavior.
<b>Range:</b> [0, 1]<br>
*/
PxReal mAccuracy;
/**
\brief Distance between center-point of the two front wheels.
\note Specified in metres (m).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mFrontWidth;
/**
\brief Distance between center-point of the two rear wheels.
\note Specified in metres (m).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mRearWidth;
/**
\brief Distance between center of front axle and center of rear axle.
\note Specified in metres (m).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mAxleSeparation;
private:
bool isValid() const;
//serialization
public:
PxVehicleAckermannGeometryData(const PxEMPTY) {}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleAckermannGeometryData)& 0x0f));
/**
\brief Choose between a potentially more expensive but more accurate solution to the clutch model or a potentially cheaper but less accurate solution.
@see PxVehicleClutchData
*/
struct PX_DEPRECATED PxVehicleClutchAccuracyMode
{
enum Enum
{
eESTIMATE = 0,
eBEST_POSSIBLE
};
};
class PX_DEPRECATED PxVehicleClutchData
{
public:
friend class PxVehicleDriveSimData;
PxVehicleClutchData()
: mStrength(10.0f),
mAccuracyMode(PxVehicleClutchAccuracyMode::eBEST_POSSIBLE),
mEstimateIterations(5)
{
}
/**
\brief Strength of clutch.
\note The clutch is the mechanism that couples the engine to the wheels.
A stronger clutch more strongly couples the engine to the wheels, while a
clutch of strength zero completely decouples the engine from the wheels.
Stronger clutches more quickly bring the wheels and engine into equilibrium, while weaker
clutches take longer, resulting in periods of clutch slip and delays in power transmission
from the engine to the wheels.
The torque generated by the clutch is proportional to the clutch strength and
the velocity difference between the engine's rotational speed and the rotational speed of the
driven wheels after accounting for the gear ratio.
The torque at the clutch is applied negatively to the engine and positively to the driven wheels.
\note Specified in kilograms metres-squared per second (kg m^2 s^-1)
<b>Range:</b> [0,PX_MAX_F32)<br>
*/
PxReal mStrength;
/**
\brief The engine and wheel rotation speeds that are coupled through the clutch can be updated by choosing
one of two modes: eESTIMATE and eBEST_POSSIBLE.
\note If eESTIMATE is chosen the vehicle sdk will update the wheel and engine rotation speeds
with estimated values to the implemented clutch model.
\note If eBEST_POSSIBLE is chosen the vehicle sdk will compute the best possible
solution (within floating point tolerance) to the implemented clutch model.
This is the recommended mode.
\note The clutch model remains the same if either eESTIMATE or eBEST_POSSIBLE is chosen but the accuracy and
computational cost of the solution to the model can be tuned as required.
*/
PxVehicleClutchAccuracyMode::Enum mAccuracyMode;
/**
\brief Tune the mathematical accuracy and computational cost of the computed estimate to the wheel and
engine rotation speeds if eESTIMATE is chosen.
\note As mEstimateIterations increases the computational cost of the clutch also increases and the solution
approaches the solution that would be computed if eBEST_POSSIBLE was chosen instead.
\note This has no effect if eBEST_POSSIBLE is chosen as the accuracy mode.
\note A value of zero is not allowed if eESTIMATE is chosen as the accuracy mode.
*/
PxU32 mEstimateIterations;
private:
PxU8 mPad[4];
bool isValid() const;
//serialization
public:
PxVehicleClutchData(const PxEMPTY) {}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleClutchData)& 0x0f));
/**
\brief Tire load variation can be strongly dependent on the time-step so it is a good idea to filter it
to give less jerky handling behavior.
\note The x-axis of the graph is normalized tire load, while the y-axis is the filtered normalized tire load.
\note The normalized load is the force acting downwards on the tire divided by the force experienced by the tire when the car is at rest on the ground.
\note The rest load is approximately the product of the value of gravitational acceleration and PxVehicleSuspensionData::mSprungMass.
\note The minimum possible normalized load is zero.
\note There are two points on the graph: (mMinNormalisedLoad, mMinNormalisedFilteredLoad) and (mMaxNormalisedLoad, mMaxFilteredNormalisedLoad).
\note Normalized loads less than mMinNormalisedLoad have filtered normalized load = mMinNormalisedFilteredLoad.
\note Normalized loads greater than mMaxNormalisedLoad have filtered normalized load = mMaxFilteredNormalisedLoad.
\note Normalized loads in-between are linearly interpolated between mMinNormalisedFilteredLoad and mMaxFilteredNormalisedLoad.
\note The tire load applied as input to the tire force computation is the filtered normalized load multiplied by the rest load.
*/
class PX_DEPRECATED PxVehicleTireLoadFilterData
{
public:
friend class PxVehicleWheelsSimData;
PxVehicleTireLoadFilterData()
: mMinNormalisedLoad(0),
mMinFilteredNormalisedLoad(0.2308f),
mMaxNormalisedLoad(3.0f),
mMaxFilteredNormalisedLoad(3.0f)
{
mDenominator=1.0f/(mMaxNormalisedLoad - mMinNormalisedLoad);
}
/**
\brief Graph point (mMinNormalisedLoad,mMinFilteredNormalisedLoad)
*/
PxReal mMinNormalisedLoad;
/**
\brief Graph point (mMinNormalisedLoad,mMinFilteredNormalisedLoad)
*/
PxReal mMinFilteredNormalisedLoad;
/**
\brief Graph point (mMaxNormalisedLoad,mMaxFilteredNormalisedLoad)
*/
PxReal mMaxNormalisedLoad;
/**
\brief Graph point (mMaxNormalisedLoad,mMaxFilteredNormalisedLoad)
*/
PxReal mMaxFilteredNormalisedLoad;
PX_FORCE_INLINE PxReal getDenominator() const {return mDenominator;}
private:
/**
\brief Not necessary to set this value.
*/
//1.0f/(mMaxNormalisedLoad-mMinNormalisedLoad) for quick calculations
PxReal mDenominator;
PxU32 mPad[3];
bool isValid() const;
//serialization
public:
PxVehicleTireLoadFilterData(const PxEMPTY) {}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleTireLoadFilterData)& 0x0f));
class PX_DEPRECATED PxVehicleWheelData
{
public:
friend class PxVehicleWheels4SimData;
PxVehicleWheelData()
: mRadius(0.0f), //Must be filled out
mWidth(0.0f),
mMass(20.0f),
mMOI(0.0f), //Must be filled out
mDampingRate(0.25f),
mMaxBrakeTorque(1500.0f),
mMaxHandBrakeTorque(0.0f),
mMaxSteer(0.0f),
mToeAngle(0.0f),
mRecipRadius(0.0f), //Must be filled out
mRecipMOI(0.0f) //Must be filled out
{
}
/**
\brief Radius of unit that includes metal wheel plus rubber tire.
\note Specified in metres (m).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mRadius;
/**
\brief Maximum width of unit that includes wheel plus tire.
\note Specified in metres (m).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mWidth;
/**
\brief Mass of unit that includes wheel plus tire.
\note Specified in kilograms (kg).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMass;
/**
\brief Moment of inertia of unit that includes wheel plus tire about the rolling axis.
\note Specified in kilograms metres-squared (kg m^2).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMOI;
/**
\brief Damping rate applied to wheel.
\note Specified in kilograms metres-squared per second (kg m^2 s^-1).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mDampingRate;
/**
\brief Max brake torque that can be applied to wheel.
\note Specified in kilograms metres-squared per second-squared (kg m^2 s^-2)
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMaxBrakeTorque;
/**
\brief Max handbrake torque that can be applied to wheel.
\note Specified in kilograms metres-squared per second-squared (kg m^2 s^-2)
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMaxHandBrakeTorque;
/**
\brief Max steer angle that can be achieved by the wheel.
\note Specified in radians.
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMaxSteer;
/**
\brief Wheel toe angle. This value is ignored by PxVehicleDriveTank and PxVehicleNoDrive.
\note Specified in radians.
<b>Range:</b> [0, Pi/2]<br>
*/
PxReal mToeAngle;//in radians
/**
\brief Return value equal to 1.0f/mRadius
@see PxVehicleWheelsSimData::setWheelData
*/
PX_FORCE_INLINE PxReal getRecipRadius() const {return mRecipRadius;}
/**
\brief Return value equal to 1.0f/mRecipMOI
@see PxVehicleWheelsSimData::setWheelData
*/
PX_FORCE_INLINE PxReal getRecipMOI() const {return mRecipMOI;}
private:
/**
\brief Reciprocal of radius of unit that includes metal wheel plus rubber tire.
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setWheelData
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mRecipRadius;
/**
\brief Reciprocal of moment of inertia of unit that includes wheel plus tire about single allowed axis of rotation.
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setWheelData
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mRecipMOI;
PxReal mPad[1];
bool isValid() const;
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleWheelData)& 0x0f));
class PX_DEPRECATED PxVehicleSuspensionData
{
public:
friend class PxVehicleWheels4SimData;
PxVehicleSuspensionData()
: mSpringStrength(0.0f),
mSpringDamperRate(0.0f),
mMaxCompression(0.3f),
mMaxDroop(0.1f),
mSprungMass(0.0f),
mCamberAtRest(0.0f),
mCamberAtMaxCompression(0.0f),
mCamberAtMaxDroop(0.0f),
mRecipMaxCompression(1.0f),
mRecipMaxDroop(1.0f)
{
}
/**
\brief Spring strength of suspension unit.
\note Specified in kilograms per second-squared (kg s^-2).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mSpringStrength;
/**
\brief Spring damper rate of suspension unit.
\note Specified in kilograms per second (kg s^-1).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mSpringDamperRate;
/**
\brief Maximum compression allowed by suspension spring.
\note Specified in metres (m).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMaxCompression;
/**
\brief Maximum elongation allowed by suspension spring.
\note Specified in metres (m).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mMaxDroop;
/**
\brief Mass of vehicle that is supported by suspension spring.
\note Specified in kilograms (kg).
\note Each suspension is guaranteed to generate an upwards force of |gravity|*mSprungMass along the suspension direction when the wheel is perfectly
at rest and sitting at the rest pose defined by the wheel centre offset.
\note The sum of the sprung masses of all suspensions of a vehicle should match the mass of the PxRigidDynamic associated with the vehicle.
When this condition is satisfied for a vehicle on a horizontal plane the wheels of the vehicle are guaranteed to sit at the rest pose
defined by the wheel centre offset. For special cases, where this condition can not be met easily, the flag
#PxVehicleWheelsSimFlag::eDISABLE_SPRUNG_MASS_SUM_CHECK allows to provide sprung mass values that do not sum up to the mass of the PxRigidDynamic.
\note As the wheel compresses or elongates along the suspension direction the force generated by the spring is
F = |gravity|*mSprungMass + deltaX*mSpringStrength + deltaXDot*mSpringDamperRate
where deltaX is the deviation from the defined rest pose and deltaXDot is the velocity of the sprung mass along the suspension direction.
In practice, deltaXDot is computed by comparing the current and previous deviation from the rest pose and dividing the difference
by the simulation timestep.
\note If a single suspension spring is hanging in the air and generates zero force the remaining springs of the vehicle will necessarily
sit in a compressed configuration. In summary, the sum of the remaining suspension forces cannot balance the downwards gravitational force
acting on the vehicle without extra force arising from the deltaX*mSpringStrength force term.
\note Theoretically, a suspension spring should generate zero force at maximum elongation and increase linearly as the suspension approaches the rest pose.
PxVehicleSuspensionData will only enforce this physical law if the spring is configured so that |gravity|*mSprungMass == mMaxDroop*mSpringStrength.
To help decouple vehicle handling from visual wheel positioning this condition is not enforced.
In practice, the value of |gravity|*mSprungMass + deltaX*mSpringStrength is clamped at zero to ensure it never falls negative.
@see PxVehicleComputeSprungMasses, PxVehicleWheelsSimData::setWheelCentreOffset, PxVehicleSuspensionData::mSpringStrength, PxVehicleSuspensionData::mSpringDamperRate, PxVehicleSuspensionData::mMaxDroop
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mSprungMass;
/**
\brief Camber angle (in radians) of wheel when the suspension is at its rest position.
\note Specified in radians.
<b>Range:</b> [-pi/2, pi/2]<br>
*/
PxReal mCamberAtRest;
/**
\brief Camber angle (in radians) of wheel when the suspension is at maximum compression.
\note For compressed suspensions the camber angle is a linear interpolation of
mCamberAngleAtRest and mCamberAtMaxCompression
\note Specified in radians.
<b>Range:</b> [-pi/2, pi/2]<br>
*/
PxReal mCamberAtMaxCompression;
/**
\brief Camber angle (in radians) of wheel when the suspension is at maximum droop.
\note For extended suspensions the camber angle is linearly interpolation of
mCamberAngleAtRest and mCamberAtMaxDroop
\note Specified in radians.
<b>Range:</b> [-pi/2, pi/2]<br>
*/
PxReal mCamberAtMaxDroop;
/**
\brief Reciprocal of maximum compression.
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setSuspensionData
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PX_FORCE_INLINE PxReal getRecipMaxCompression() const {return mRecipMaxCompression;}
/**
\brief Reciprocal of maximum droop.
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setSuspensionData
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PX_FORCE_INLINE PxReal getRecipMaxDroop() const {return mRecipMaxDroop;}
/**
\brief Set a new sprung mass for the suspension and modify the spring strength so that the natural frequency
of the spring is preserved.
\param[in] newSprungMass is the new mass that the suspension spring will support.
*/
void setMassAndPreserveNaturalFrequency(const PxReal newSprungMass)
{
const PxF32 oldStrength = mSpringStrength;
const PxF32 oldSprungMass = mSprungMass;
const PxF32 newStrength = oldStrength * (newSprungMass / oldSprungMass);
mSpringStrength = newStrength;
mSprungMass = newSprungMass;
}
private:
/**
\brief Cached value of 1.0f/mMaxCompression
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setSuspensionData
*/
PxReal mRecipMaxCompression;
/**
\brief Cached value of 1.0f/mMaxDroop
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setSuspensionData
*/
PxReal mRecipMaxDroop;
//padding
PxReal mPad[2];
bool isValid() const;
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleSuspensionData)& 0x0f));
class PX_DEPRECATED PxVehicleAntiRollBarData
{
public:
friend class PxVehicleWheelsSimData;
PxVehicleAntiRollBarData()
: mWheel0(0xffffffff),
mWheel1(0xffffffff),
mStiffness(0.0f)
{
}
/*
\brief The anti-roll bar connects two wheels with indices mWheel0 and mWheel1
*/
PxU32 mWheel0;
/*
\brief The anti-roll bar connects two wheels with indices mWheel0 and mWheel1
*/
PxU32 mWheel1;
/*
\brief The stiffness of the anti-roll bar.
\note Specified in kilograms per second-squared (kg s^-2).
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxF32 mStiffness;
private:
PxF32 mPad[1];
bool isValid() const;
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleAntiRollBarData)& 0x0f));
class PX_DEPRECATED PxVehicleTireData
{
public:
friend class PxVehicleWheels4SimData;
PxVehicleTireData()
: mLatStiffX(2.0f),
mLatStiffY(0.3125f*(180.0f / PxPi)),
mLongitudinalStiffnessPerUnitGravity(1000.0f),
mCamberStiffnessPerUnitGravity(0.1f*(180.0f / PxPi)),
mType(0)
{
mFrictionVsSlipGraph[0][0]=0.0f;
mFrictionVsSlipGraph[0][1]=1.0f;
mFrictionVsSlipGraph[1][0]=0.1f;
mFrictionVsSlipGraph[1][1]=1.0f;
mFrictionVsSlipGraph[2][0]=1.0f;
mFrictionVsSlipGraph[2][1]=1.0f;
mRecipLongitudinalStiffnessPerUnitGravity=1.0f/mLongitudinalStiffnessPerUnitGravity;
mFrictionVsSlipGraphRecipx1Minusx0=1.0f/(mFrictionVsSlipGraph[1][0]-mFrictionVsSlipGraph[0][0]);
mFrictionVsSlipGraphRecipx2Minusx1=1.0f/(mFrictionVsSlipGraph[2][0]-mFrictionVsSlipGraph[1][0]);
}
/**
\brief Tire lateral stiffness is a graph of tire load that has linear behavior near zero load and
flattens at large loads. mLatStiffX describes the minimum normalized load (load/restLoad) that gives a
flat lateral stiffness response to load.
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mLatStiffX;
/**
\brief Tire lateral stiffness is a graph of tire load that has linear behavior near zero load and
flattens at large loads. mLatStiffY describes the maximum possible value of lateralStiffness/restLoad that occurs
when (load/restLoad)>= mLatStiffX.
\note If load/restLoad is greater than mLatStiffX then the lateral stiffness is mLatStiffY*restLoad.
\note If load/restLoad is less than mLatStiffX then the lateral stiffness is mLastStiffY*(load/mLatStiffX)
\note Lateral force can be approximated as lateralStiffness * lateralSlip.
\note Specified in per radian.
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mLatStiffY;
/**
\brief Tire Longitudinal stiffness per unit gravitational acceleration.
\note Longitudinal stiffness of the tire is calculated as gravitationalAcceleration*mLongitudinalStiffnessPerUnitGravity.
\note Longitudinal force can be approximated as gravitationalAcceleration*mLongitudinalStiffnessPerUnitGravity*longitudinalSlip.
\note Specified in kilograms per radian.
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mLongitudinalStiffnessPerUnitGravity;
/**
\brief tire Tire camber stiffness per unity gravitational acceleration.
\note Camber stiffness of the tire is calculated as gravitationalAcceleration*mCamberStiffnessPerUnitGravity
\note Camber force can be approximated as gravitationalAcceleration*mCamberStiffnessPerUnitGravity*camberAngle.
\note Specified in kilograms per radian.
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mCamberStiffnessPerUnitGravity;
/**
\brief Graph of friction vs longitudinal slip with 3 points.
\note mFrictionVsSlipGraph[0][0] is always zero.
\note mFrictionVsSlipGraph[0][1] is the friction available at zero longitudinal slip.
\note mFrictionVsSlipGraph[1][0] is the value of longitudinal slip with maximum friction.
\note mFrictionVsSlipGraph[1][1] is the maximum friction.
\note mFrictionVsSlipGraph[2][0] is the end point of the graph.
\note mFrictionVsSlipGraph[2][1] is the value of friction for slips greater than mFrictionVsSlipGraph[2][0].
\note The friction value computed from the friction vs longitudinal slip graph is used to scale the friction
value for the combination of material and tire type (PxVehicleDrivableSurfaceToTireFrictionPairs).
\note mFrictionVsSlipGraph[2][0] > mFrictionVsSlipGraph[1][0] > mFrictionVsSlipGraph[0][0]
\note mFrictionVsSlipGraph[1][1] is typically greater than mFrictionVsSlipGraph[0][1]
\note mFrictionVsSlipGraph[2][1] is typically smaller than mFrictionVsSlipGraph[1][1]
\note longitudinal slips > mFrictionVsSlipGraph[2][0] use friction multiplier mFrictionVsSlipGraph[2][1]
\note The final friction value used by the tire model is the value returned by PxVehicleDrivableSurfaceToTireFrictionPairs
multiplied by the value computed from mFrictionVsSlipGraph.
@see PxVehicleDrivableSurfaceToTireFrictionPairs, PxVehicleComputeTireForce
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxReal mFrictionVsSlipGraph[3][2];
/**
\brief Tire type denoting slicks, wets, snow, winter, summer, all-terrain, mud etc.
@see PxVehicleDrivableSurfaceToTireFrictionPairs
<b>Range:</b> [0, PX_MAX_F32)<br>
*/
PxU32 mType;
/**
\brief Return Cached value of 1.0/mLongitudinalStiffnessPerUnitGravity
@see PxVehicleWheelsSimData::setTireData
*/
PX_FORCE_INLINE PxReal getRecipLongitudinalStiffnessPerUnitGravity() const {return mRecipLongitudinalStiffnessPerUnitGravity;}
/**
\brief Return Cached value of 1.0f/(mFrictionVsSlipGraph[1][0]-mFrictionVsSlipGraph[0][0])
@see PxVehicleWheelsSimData::setTireData
*/
PX_FORCE_INLINE PxReal getFrictionVsSlipGraphRecipx1Minusx0() const {return mFrictionVsSlipGraphRecipx1Minusx0;}
/**
\brief Return Cached value of 1.0f/(mFrictionVsSlipGraph[2][0]-mFrictionVsSlipGraph[1][0])
@see PxVehicleWheelsSimData::setTireData
*/
PX_FORCE_INLINE PxReal getFrictionVsSlipGraphRecipx2Minusx1() const {return mFrictionVsSlipGraphRecipx2Minusx1;}
private:
/**
\brief Cached value of 1.0/mLongitudinalStiffnessPerUnitGravity.
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setTireData
@see PxVehicleWheelsSimData::setTireData
*/
PxReal mRecipLongitudinalStiffnessPerUnitGravity;
/**
\brief Cached value of 1.0f/(mFrictionVsSlipGraph[1][0]-mFrictionVsSlipGraph[0][0])
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setTireData
@see PxVehicleWheelsSimData::setTireData
*/
PxReal mFrictionVsSlipGraphRecipx1Minusx0;
/**
\brief Cached value of 1.0f/(mFrictionVsSlipGraph[2][0]-mFrictionVsSlipGraph[1][0])
\note Not necessary to set this value because it is set by PxVehicleWheelsSimData::setTireData
@see PxVehicleWheelsSimData::setTireData
*/
PxReal mFrictionVsSlipGraphRecipx2Minusx1;
PxReal mPad[2];
bool isValid() const;
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleTireData)& 0x0f));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 39,557 | C | 28.172566 | 202 | 0.755618 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleUtilSetup.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_UTIL_SETUP_H
#define PX_VEHICLE_UTIL_SETUP_H
#include "foundation/PxSimpleTypes.h"
#include "vehicle/PxVehicleSDK.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxVehicleWheelsSimData;
class PxVehicleWheelsDynData;
class PxVehicleDriveSimData4W;
class PxVehicleWheels;
/**
\brief Reconfigure a PxVehicle4W instance as a three-wheeled car with tadpole config (2 front wheels, 1 rear wheel)
\note The rear-left wheel is removed and the rear-right wheel is positioned at the centre of the rear axle.
The suspension of the rear-right wheel is modified to support the entire mass of the front car while preserving its natural frequency and damping ratio.
\param[in,out] wheelsSimData is the data describing the wheels/suspensions/tires of the vehicle.
\param[in,out] wheelsDynData is the data describing the dynamic state of the wheels of the vehicle.
\param[in,out] driveSimData is the data describing the drive model of the vehicle.
\param[in] context the vehicle context to use for the setup.
*/
PX_DEPRECATED void PxVehicle4WEnable3WTadpoleMode(PxVehicleWheelsSimData& wheelsSimData, PxVehicleWheelsDynData& wheelsDynData, PxVehicleDriveSimData4W& driveSimData,
const PxVehicleContext& context = PxVehicleGetDefaultContext());
/**
\brief Reconfigure a PxVehicle4W instance as a three-wheeled car with delta config (1 front wheel, 2 rear wheels)
\note The front-left wheel is removed and the front-right wheel is positioned at the centre of the front axle.
The suspension of the front-right wheel is modified to support the entire mass of the front car while preserving its natural frequency and damping ratio.
\param[in,out] wheelsSimData is the data describing the wheels/suspensions/tires of the vehicle.
\param[in,out] wheelsDynData is the data describing the dynamic state of the wheels of the vehicle.
\param[in,out] driveSimData is the data describing the drive model of the vehicle.
\param[in] context the vehicle context to use for the setup.
*/
PX_DEPRECATED void PxVehicle4WEnable3WDeltaMode(PxVehicleWheelsSimData& wheelsSimData, PxVehicleWheelsDynData& wheelsDynData, PxVehicleDriveSimData4W& driveSimData,
const PxVehicleContext& context = PxVehicleGetDefaultContext());
/**
\brief Compute the sprung masses of the suspension springs given (i) the number of sprung masses,
(ii) coordinates of the sprung masses, (iii) the center of mass offset of the rigid body, (iv) the
total mass of the rigid body, and (v) the direction of gravity (0 for x-axis, 1 for y-axis, 2 for z-axis).
\param[in] nbSprungMasses is the number of sprung masses of the vehicle. This value corresponds to the number of wheels on the vehicle.
\param[in] sprungMassCoordinates are the coordinates of the sprung masses relative to the actor. The array sprungMassCoordinates must be of
length nbSprungMasses or greater.
\param[in] centreOfMass is the coordinate of the center of mass of the rigid body relative to the actor. This value corresponds to
the value set by PxRigidBody::setCMassLocalPose.
\param[in] totalMass is the total mass of all the sprung masses. This value corresponds to the value set by PxRigidBody::setMass.
\param[in] gravityDirection is an integer describing the direction of gravitational acceleration. A value of 0 corresponds to (-1,0,0),
a value of 1 corresponds to (0,-1,0) and a value of 2 corresponds to (0,0,-1).
\param[out] sprungMasses are the masses to set in the associated suspension data with PxVehicleSuspensionData::mSprungMass. The sprungMasses array must be of length
nbSprungMasses or greater. Each element in the sprungMasses array corresponds to the suspension located at the same array element in sprungMassCoordinates.
The center of mass of the masses in sprungMasses with the coordinates in sprungMassCoordinates satisfy the specified centerOfMass.
*/
PX_DEPRECATED void PxVehicleComputeSprungMasses(const PxU32 nbSprungMasses, const PxVec3* sprungMassCoordinates, const PxVec3& centreOfMass, const PxReal totalMass, const PxU32 gravityDirection, PxReal* sprungMasses);
/**
\brief Reconfigure the vehicle to reflect a new center of mass local pose that has been applied to the actor. The function requires
(i) the center of mass local pose that was last used to configure the vehicle and the vehicle's actor, (ii) the new center of mass local pose that
has been applied to the vehicle's actor and will now be applied to the vehicle, and (iii) the direction of gravity (0 for x-axis, 1 for y-axis, 2 for z-axis)
\param[in] oldCMassLocalPose is the center of mass local pose that was last used to configure the vehicle.
\param[in] newCMassLocalPose is the center of mass local pose that will be used to configure the vehicle so that it matches the vehicle's actor.
\param[in] gravityDirection is an integer describing the direction of gravitational acceleration. A value of 0 corresponds to (0,0,-1),
a value of 1 corresponds to (0,-1,0) and a value of 2 corresponds to (0,0,-1).
\param[in,out] vehicle is the vehicle to be updated with a new center of mass local pose.
\note This function does not update the center of mass of the vehicle actor. That needs to updated separately with PxRigidBody::setCMassLocalPose
\note The suspension sprung masses are updated so that the natural frequency and damping ratio of the springs are preserved. This involves altering the
stiffness and damping rate of the suspension springs.
*/
PX_DEPRECATED void PxVehicleUpdateCMassLocalPose(const PxTransform& oldCMassLocalPose, const PxTransform& newCMassLocalPose, const PxU32 gravityDirection, PxVehicleWheels* vehicle);
/**
\brief Used by PxVehicleCopyDynamicsData
@see PxVehicleCopyDynamicsData
*/
class PX_DEPRECATED PxVehicleCopyDynamicsMap
{
public:
PxVehicleCopyDynamicsMap()
{
for(PxU32 i = 0; i < PX_MAX_NB_WHEELS; i++)
{
sourceWheelIds[i] = PX_MAX_U8;
targetWheelIds[i] = PX_MAX_U8;
}
}
PxU8 sourceWheelIds[PX_MAX_NB_WHEELS];
PxU8 targetWheelIds[PX_MAX_NB_WHEELS];
};
/**
\brief Copy dynamics data from src to trg, including wheel rotation speed, wheel rotation angle, engine rotation speed etc.
\param[in] wheelMap - describes the mapping between the wheels in src and the wheels in trg.
\param[in] src - according to the wheel mapping stored in wheelMap, the dynamics data in src wheels are copied to the corresponding wheels in trg.
\param[out] trg - according to wheel mapping stored in wheelMap, the wheels in trg are given the dynamics data of the corresponding wheels in src.
\note wheelMap must specify a unique mapping between the wheels in src and the wheels in trg.
\note In the event that src has fewer wheels than trg, wheelMap must specify a unique mapping between each src wheel to a trg wheel.
\note In the event that src has more wheels than trg, wheelMap must specify a unique mapping to each trg wheel from a src wheel.
\note In the event that src has fewer wheels than trg, the trg wheels that are not mapped to a src wheel are given the average wheel rotation
speed of all enabled src wheels.
\note src and trg must be the same vehicle type.
*/
PX_DEPRECATED void PxVehicleCopyDynamicsData(const PxVehicleCopyDynamicsMap& wheelMap, const PxVehicleWheels& src, PxVehicleWheels* trg);
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 8,967 | C | 54.701863 | 217 | 0.787777 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleUtilControl.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_UTIL_CONTROL_H
#define PX_VEHICLE_UTIL_CONTROL_H
#include "vehicle/PxVehicleSDK.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveNW.h"
#include "vehicle/PxVehicleDriveTank.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_CHECKED
void testValidAnalogValue(const PxF32 actualValue, const PxF32 minVal, const PxF32 maxVal, const char* errorString);
#endif
/**
\brief Used to produce smooth steering values in the presence of discontinuities when a vehicle e.g. lands on the ground.
Use a zero sharpness value to disable the feature (backward compatibility with previous PhysX versions).
*/
struct PX_DEPRECATED PxVehicleSteerFilter
{
PxVehicleSteerFilter(float sharpness=0.0f) : mSharpness(sharpness), mFilteredMaxSteer(0.0f) {}
static PX_FORCE_INLINE float feedbackFilter(float val, float& memory, float sharpness)
{
if(sharpness<0.0f) sharpness = 0.0f;
else if(sharpness>1.0f) sharpness = 1.0f;
return memory = val * sharpness + memory * (1.0f - sharpness);
}
PX_FORCE_INLINE float computeMaxSteer(const bool isVehicleInAir, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxF32 vzAbs, const PxF32 timestep) const
{
const PxF32 targetMaxSteer = (isVehicleInAir ? 1.0f : steerVsForwardSpeedTable.getYVal(vzAbs));
if(mSharpness==0.0f)
return targetMaxSteer;
else
return feedbackFilter(targetMaxSteer, mFilteredMaxSteer, mSharpness*timestep);
}
PxReal mSharpness;
mutable PxReal mFilteredMaxSteer;
};
/**
\brief Used to produce smooth vehicle driving control values from key inputs.
@see PxVehicle4WSmoothDigitalRawInputsAndSetAnalogInputs, PxVehicle4WSmoothAnalogRawInputsAndSetAnalogInputs
*/
struct PX_DEPRECATED PxVehicleKeySmoothingData
{
/**
\brief Rise rate of each analog value if digital value is 1
*/
PxReal mRiseRates[PxVehicleDriveDynData::eMAX_NB_ANALOG_INPUTS];
/**
\brief Fall rate of each analog value if digital value is 0
*/
PxReal mFallRates[PxVehicleDriveDynData::eMAX_NB_ANALOG_INPUTS];
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleKeySmoothingData)& 0x0f));
/**
\brief Used to produce smooth analog vehicle control values from analog inputs.
@see PxVehicleDrive4WSmoothDigitalRawInputsAndSetAnalogInputs, PxVehicleDrive4WSmoothAnalogRawInputsAndSetAnalogInputs
*/
struct PX_DEPRECATED PxVehiclePadSmoothingData
{
/**
\brief Rise rate of each analog value from previous value towards target if target>previous
*/
PxReal mRiseRates[PxVehicleDriveDynData::eMAX_NB_ANALOG_INPUTS];
/**
\brief Rise rate of each analog value from previous value towards target if target<previous
*/
PxReal mFallRates[PxVehicleDriveDynData::eMAX_NB_ANALOG_INPUTS];
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehiclePadSmoothingData)& 0x0f));
/**
\brief Used to produce smooth vehicle driving control values from analog and digital inputs.
@see PxVehicleDrive4WSmoothDigitalRawInputsAndSetAnalogInputs, PxVehicleDrive4WSmoothAnalogRawInputsAndSetAnalogInputs
*/
class PX_DEPRECATED PxVehicleDrive4WRawInputData
{
public:
PxVehicleDrive4WRawInputData()
{
for(PxU32 i=0;i<PxVehicleDrive4WControl::eMAX_NB_DRIVE4W_ANALOG_INPUTS;i++)
{
mRawDigitalInputs[i]=false;
mRawAnalogInputs[i]=0.0f;
}
mGearUp = false;
mGearDown = false;
}
virtual ~PxVehicleDrive4WRawInputData()
{
}
/**
\brief Record if the accel button has been pressed on keyboard.
\param[in] accelKeyPressed is true if the accelerator key has been pressed and false otherwise.
*/
void setDigitalAccel(const bool accelKeyPressed) {mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL]=accelKeyPressed;}
/**
\brief Record if the brake button has been pressed on keyboard.
\param[in] brakeKeyPressed is true if the brake key has been pressed and false otherwise.
*/
void setDigitalBrake(const bool brakeKeyPressed) {mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE]=brakeKeyPressed;}
/**
\brief Record if the handbrake button has been pressed on keyboard.
\param[in] handbrakeKeyPressed is true if the handbrake key has been pressed and false otherwise.
*/
void setDigitalHandbrake(const bool handbrakeKeyPressed) {mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE]=handbrakeKeyPressed;}
/**
\brief Record if the left steer button has been pressed on keyboard.
\param[in] steerLeftKeyPressed is true if the steer-left key has been pressed and false otherwise.
*/
void setDigitalSteerLeft(const bool steerLeftKeyPressed) {mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT]=steerLeftKeyPressed;}
/**
\brief Record if the right steer button has been pressed on keyboard.
\param[in] steerRightKeyPressed is true if the steer-right key has been pressed and false otherwise.
*/
void setDigitalSteerRight(const bool steerRightKeyPressed) {mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]=steerRightKeyPressed;}
/**
\brief Return if the accel button has been pressed on keyboard.
\return True if the accel button has been pressed, false otherwise.
*/
bool getDigitalAccel() const {return mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];}
/**
\brief Return if the brake button has been pressed on keyboard.
\return True if the brake button has been pressed, false otherwise.
*/
bool getDigitalBrake() const {return mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE];}
/**
\brief Return if the handbrake button has been pressed on keyboard.
\return True if the handbrake button has been pressed, false otherwise.
*/
bool getDigitalHandbrake() const {return mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE];}
/**
\brief Return if the left steer button has been pressed on keyboard.
\return True if the steer-left button has been pressed, false otherwise.
*/
bool getDigitalSteerLeft() const {return mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT];}
/**
\brief Return if the right steer button has been pressed on keyboard.
\return True if the steer-right button has been pressed, false otherwise.
*/
bool getDigitalSteerRight() const {return mRawDigitalInputs[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT];}
/**
\brief Set the analog accel value from the gamepad
\param[in] accel is the analog accelerator pedal value in range(0,1) where 1 represents the pedal fully pressed and 0 represents the pedal in its rest state.
*/
void setAnalogAccel(const PxReal accel)
{
#if PX_CHECKED
testValidAnalogValue(accel, 0.0f, 1.0f, "Analog accel must be in range (0,1)");
#endif
mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL]=accel;
}
/**
\brief Set the analog brake value from the gamepad
\param[in] brake is the analog brake pedal value in range(0,1) where 1 represents the pedal fully pressed and 0 represents the pedal in its rest state.
*/
void setAnalogBrake(const PxReal brake)
{
#if PX_CHECKED
testValidAnalogValue(brake, 0.0f, 1.0f, "Analog brake must be in range (0,1)");
#endif
mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE]=brake;
}
/**
\brief Set the analog handbrake value from the gamepad
\param[in] handbrake is the analog handbrake value in range(0,1) where 1 represents the handbrake fully engaged and 0 represents the handbrake in its rest state.
*/
void setAnalogHandbrake(const PxReal handbrake)
{
#if PX_CHECKED
testValidAnalogValue(handbrake, 0.0f, 1.0f, "Analog handbrake must be in range (0,1)");
#endif
mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE]=handbrake;
}
/**
\brief Set the analog steer value from the gamepad
\param[in] steer is the analog steer value in range(-1,1) where -1 represents the steering wheel at left lock and +1 represents the steering wheel at right lock.
*/
void setAnalogSteer(const PxReal steer)
{
#if PX_CHECKED
testValidAnalogValue(steer, -1.0f, 1.0f, "Analog steer must be in range (-1,1)");
#endif
mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]=steer;
}
/**
\brief Return the analog accel value from the gamepad
\return The analog accel value.
*/
PxReal getAnalogAccel() const {return mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];}
/**
\brief Return the analog brake value from the gamepad
\return The analog brake value.
*/
PxReal getAnalogBrake() const {return mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE];}
/**
\brief Return the analog handbrake value from the gamepad
\return The analog handbrake value.
*/
PxReal getAnalogHandbrake() const {return mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE];}
/**
\brief Return the analog steer value from the gamepad
*/
PxReal getAnalogSteer() const {return mRawAnalogInputs[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT];}
/**
\brief Record if the gearup button has been pressed on keyboard or gamepad
\param[in] gearUpKeyPressed is true if the gear-up button has been pressed, false otherwise.
*/
void setGearUp(const bool gearUpKeyPressed) {mGearUp=gearUpKeyPressed;}
/**
\brief Record if the geardown button has been pressed on keyboard or gamepad
\param[in] gearDownKeyPressed is true if the gear-down button has been pressed, false otherwise.
*/
void setGearDown(const bool gearDownKeyPressed) {mGearDown=gearDownKeyPressed;}
/**
\brief Return if the gearup button has been pressed on keyboard or gamepad
\return The value of the gear-up button.
*/
bool getGearUp() const {return mGearUp;}
/**
\brief Record if the geardown button has been pressed on keyboard or gamepad
\return The value of the gear-down button.
*/
bool getGearDown() const {return mGearDown;}
private:
bool mRawDigitalInputs[PxVehicleDrive4WControl::eMAX_NB_DRIVE4W_ANALOG_INPUTS];
PxReal mRawAnalogInputs[PxVehicleDrive4WControl::eMAX_NB_DRIVE4W_ANALOG_INPUTS];
bool mGearUp;
bool mGearDown;
};
/**
\brief Used to smooth and set analog vehicle control values (accel,brake,handbrake,steer) from digital inputs (keyboard).
Also used to set boolean gearup, geardown values.
\param[in] keySmoothing describes the rise and fall rates of the corresponding analog values when keys are pressed on and off.
\param[in] steerVsForwardSpeedTable is a table of maximum allowed steer versus forward vehicle speed.
\param[in] rawInputData is the state of all digital inputs that control the vehicle.
\param[in] timestep is the time that has passed since the last call to PxVehicleDrive4WSmoothDigitalRawInputsAndSetAnalogInputs
\param[in] isVehicleInAir describes if the vehicle is in the air or on the ground and is used to decide whether or not to apply steerVsForwardSpeedTable.
\param[in] focusVehicle is the vehicle that will be given analog and gearup/geardown control values arising from the digital inputs.
\param[in] steerFilter is an optional smoothing filter for the steering angle.
\param[in] forwardAxis The axis denoting the local space forward direction of the vehicle.
*/
PX_DEPRECATED void PxVehicleDrive4WSmoothDigitalRawInputsAndSetAnalogInputs
(const PxVehicleKeySmoothingData& keySmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDrive4WRawInputData& rawInputData, const PxReal timestep, const bool isVehicleInAir,
PxVehicleDrive4W& focusVehicle, const PxVehicleSteerFilter& steerFilter = PxVehicleSteerFilter(),
const PxVec3& forwardAxis = PxVehicleGetDefaultContext().forwardAxis);
/**
\brief Used to smooth and set analog vehicle control values from analog inputs (gamepad).
Also used to set boolean gearup, geardown values.
\param[in] padSmoothing describes how quickly the control values applied to the vehicle blend from the current vehicle values towards the raw analog values from the gamepad.
\param[in] steerVsForwardSpeedTable is a table of maximum allowed steer versus forward vehicle speed.
\param[in] rawInputData is the state of all gamepad analog inputs that will be used control the vehicle.
\param[in] timestep is the time that has passed since the last call to PxVehicleDrive4WSmoothAnalogRawInputsAndSetAnalogInputs
\param[in] isVehicleInAir describes if the vehicle is in the air or on the ground and is used to decide whether or not to apply steerVsForwardSpeedTable.
\param[in] focusVehicle is the vehicle that will be given analog control values arising from the gamepad inputs.
\param[in] steerFilter is an optional smoothing filter for the steering angle.
\param[in] forwardAxis The axis denoting the local space forward direction of the vehicle.
*/
PX_DEPRECATED void PxVehicleDrive4WSmoothAnalogRawInputsAndSetAnalogInputs
(const PxVehiclePadSmoothingData& padSmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDrive4WRawInputData& rawInputData, const PxReal timestep, const bool isVehicleInAir,
PxVehicleDrive4W& focusVehicle, const PxVehicleSteerFilter& steerFilter = PxVehicleSteerFilter(),
const PxVec3& forwardAxis = PxVehicleGetDefaultContext().forwardAxis);
/**
\brief Used to produce smooth vehicle driving control values from analog and digital inputs.
@see PxVehicleDriveNWSmoothDigitalRawInputsAndSetAnalogInputs, PxVehicleDriveNWSmoothAnalogRawInputsAndSetAnalogInputs
*/
class PX_DEPRECATED PxVehicleDriveNWRawInputData : public PxVehicleDrive4WRawInputData
{
public:
PxVehicleDriveNWRawInputData() : PxVehicleDrive4WRawInputData(){}
~PxVehicleDriveNWRawInputData(){}
};
/**
\brief Used to smooth and set analog vehicle control values (accel,brake,handbrake,steer) from digital inputs (keyboard).
Also used to set boolean gearup, geardown values.
\param[in] keySmoothing describes the rise and fall rates of the corresponding analog values when keys are pressed on and off.
\param[in] steerVsForwardSpeedTable is a table of maximum allowed steer versus forward vehicle speed.
\param[in] rawInputData is the state of all digital inputs that control the vehicle.
\param[in] timestep is the time that has passed since the last call to PxVehicleDriveNWSmoothDigitalRawInputsAndSetAnalogInputs
\param[in] isVehicleInAir describes if the vehicle is in the air or on the ground and is used to decide whether or not to apply steerVsForwardSpeedTable.
\param[in] focusVehicle is the vehicle that will be given analog and gearup/geardown control values arising from the digital inputs.
\param[in] steerFilter is an optional smoothing filter for the steering angle.
\param[in] forwardAxis The axis denoting the local space forward direction of the vehicle.
*/
PX_DEPRECATED void PxVehicleDriveNWSmoothDigitalRawInputsAndSetAnalogInputs
(const PxVehicleKeySmoothingData& keySmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDriveNWRawInputData& rawInputData, const PxReal timestep, const bool isVehicleInAir,
PxVehicleDriveNW& focusVehicle, const PxVehicleSteerFilter& steerFilter = PxVehicleSteerFilter(),
const PxVec3& forwardAxis = PxVehicleGetDefaultContext().forwardAxis);
/**
\brief Used to smooth and set analog vehicle control values from analog inputs (gamepad).
Also used to set boolean gearup, geardown values.
\param[in] padSmoothing describes how quickly the control values applied to the vehicle blend from the current vehicle values towards the raw analog values from the gamepad.
\param[in] steerVsForwardSpeedTable is a table of maximum allowed steer versus forward vehicle speed.
\param[in] rawInputData is the state of all gamepad analog inputs that will be used control the vehicle.
\param[in] timestep is the time that has passed since the last call to PxVehicleDriveNWSmoothAnalogRawInputsAndSetAnalogInputs
\param[in] isVehicleInAir describes if the vehicle is in the air or on the ground and is used to decide whether or not to apply steerVsForwardSpeedTable.
\param[in] focusVehicle is the vehicle that will be given analog control values arising from the gamepad inputs.
\param[in] steerFilter is an optional smoothing filter for the steering angle.
\param[in] forwardAxis The axis denoting the local space forward direction of the vehicle.
*/
PX_DEPRECATED void PxVehicleDriveNWSmoothAnalogRawInputsAndSetAnalogInputs
(const PxVehiclePadSmoothingData& padSmoothing, const PxFixedSizeLookupTable<8>& steerVsForwardSpeedTable,
const PxVehicleDriveNWRawInputData& rawInputData, const PxReal timestep, const bool isVehicleInAir,
PxVehicleDriveNW& focusVehicle, const PxVehicleSteerFilter& steerFilter = PxVehicleSteerFilter(),
const PxVec3& forwardAxis = PxVehicleGetDefaultContext().forwardAxis);
/**
\brief Used to produce smooth analog tank control values from analog and digital inputs.
@see PxVehicleDriveTankSmoothDigitalRawInputsAndSetAnalogInputs, PxVehicleDriveTankSmoothAnalogRawInputsAndSetAnalogInputs
*/
class PX_DEPRECATED PxVehicleDriveTankRawInputData
{
public:
PxVehicleDriveTankRawInputData(const PxVehicleDriveTankControlModel::Enum mode)
: mMode(mode)
{
for(PxU32 i=0;i<PxVehicleDriveTankControl::eMAX_NB_DRIVETANK_ANALOG_INPUTS;i++)
{
mRawAnalogInputs[i]=0.0f;
mRawDigitalInputs[i]=false;
}
mGearUp=false;
mGearDown=false;
}
~PxVehicleDriveTankRawInputData()
{
}
/**
\brief Return the drive model (eDRIVE_MODEL_SPECIAL or eDRIVE_MODEL_STANDARD)
\return The chosen tank drive model.
*/
PxVehicleDriveTankControlModel::Enum getDriveModel() const
{
return mMode;
}
/**
\brief Set if the accel button has been pressed on the keyboard
\param[in] b is true if the digital accel button has been pressed, false otherwise.
*/
void setDigitalAccel(const bool b) {mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL]=b;}
/**
\brief Set if the left thrust button has been pressed on the keyboard
\param[in] b is true if the digital left thrust button has been pressed, false otherwise.
*/
void setDigitalLeftThrust(const bool b) {mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]=b;}
/**
\brief Set if the right thrust button has been pressed on the keyboard
\param[in] b is true if the digital right thrust button has been pressed, false otherwise.
*/
void setDigitalRightThrust(const bool b) {mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]=b;}
/**
\brief Set if the left brake button has been pressed on the keyboard
\param[in] b is true if the digital left brake button has been pressed, false otherwise.
*/
void setDigitalLeftBrake(const bool b) {mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT]=b;}
/**
\brief Set if the right brake button has been pressed on the keyboard
\param[in] b is true if the digital right brake button has been pressed, false otherwise.
*/
void setDigitalRightBrake(const bool b) {mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT]=b;}
/**
\brief Return if the accel button has been pressed on the keyboard
\return True if the accel button has been pressed, false otherwise.
*/
bool getDigitalAccel() const {return mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL];}
/**
\brief Return if the left thrust button has been pressed on the keyboard
\return True if the left thrust button has been pressed, false otherwise.
*/
bool getDigitalLeftThrust() const {return mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];}
/**
\brief Return if the right thrust button has been pressed on the keyboard
\return True if the right thrust button has been pressed, false otherwise.
*/
bool getDigitalRightThrust() const {return mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];}
/**
\brief Return if the left brake button has been pressed on the keyboard
\return True if the left brake button has been pressed, false otherwise.
*/
bool getDigitalLeftBrake() const {return mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT];}
/**
\brief Return if the right brake button has been pressed on the keyboard
\return True if the right brake button has been pressed, false otherwise.
*/
bool getDigitalRightBrake() const {return mRawDigitalInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT];}
/**
\brief Set the analog accel value from the gamepad
\param[in] accel is a value in range (0,1) where 1 represents the accelerator pedal fully pressed and 0 represents the pedal in its rest state.
In range (0,1).
*/
void setAnalogAccel(const PxF32 accel)
{
#if PX_CHECKED
testValidAnalogValue(accel, 0.0f, 1.0f, "Tank analog accel must be in range (-1,1)");
#endif
mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL]=accel;
}
/**
\brief Set the analog left thrust value from the gamepad
\param[in] leftThrust represents the state of the left stick.
\note In range (0,1) for standard mode (eSTANDARD), in range (-1,1) for special mode (eSPECIAL)
*/
void setAnalogLeftThrust(const PxF32 leftThrust)
{
#if PX_CHECKED
if(mMode == PxVehicleDriveTankControlModel::eSPECIAL)
{
testValidAnalogValue(leftThrust, -1.0f, 1.0f, "Tank left thrust must be in range (-1,1) in eSPECIAL mode.");
}
else
{
testValidAnalogValue(leftThrust, 0.0f, 1.0f, "Tank left thrust must be in range (0,1) in eSTANDARD mode.");
}
#endif
mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]=leftThrust;
}
/**
\brief Set the analog right thrust value from the gamepad
\param[in] rightThrust represents the state of the right stick.
\note In range (0,1) for standard mode (eSTANDARD), in range (-1,1) for special mode (eSPECIAL)
*/
void setAnalogRightThrust(const PxF32 rightThrust)
{
#if PX_CHECKED
if(mMode == PxVehicleDriveTankControlModel::eSPECIAL)
{
testValidAnalogValue(rightThrust, -1.0f, 1.0f, "Tank right thrust must be in range (-1,1) in eSPECIAL mode.");
}
else
{
testValidAnalogValue(rightThrust, 0.0f, 1.0f, "Tank right thrust must be in range (0,1) in eSTANDARD mode.");
}
#endif
mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]=rightThrust;
}
/**
\brief Set the analog left brake value from the gamepad
\param[in] leftBrake is a value in range (0,1) where 1 represents the left brake pedal fully pressed and 0 represents the left brake pedal in its rest state.
\note In range (0,1).
*/
void setAnalogLeftBrake(const PxF32 leftBrake)
{
#if PX_CHECKED
testValidAnalogValue(leftBrake, 0.0f, 1.0f, "Tank left brake must be in range (0,1).");
#endif
mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT]=leftBrake;
}
/**
\brief Set the analog right brake value from the gamepad
\param[in] rightBrake is a value in range (0,1) where 1 represents the right brake pedal fully pressed and 0 represents the right brake pedal in its rest state.
\note In range (0,1).
*/
void setAnalogRightBrake(const PxF32 rightBrake)
{
#if PX_CHECKED
testValidAnalogValue(rightBrake, 0.0f, 1.0f, "Tank right brake must be in range (0,1).");
#endif
mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT]=rightBrake;
}
/**
\brief Return the analog accel value from the gamepad
\return The analog accel value.
*/
PxF32 getAnalogAccel() const
{
return mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL];
}
/**
\brief Return the analog left thrust value from the gamepad
\return The analog left thrust value.
*/
PxF32 getAnalogLeftThrust() const
{
return mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];
}
/**
\brief Return the analog right thrust value from the gamepad
\return The analog right thrust value.
*/
PxF32 getAnalogRightThrust() const
{
return mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];
}
/**
\brief Return the analog left brake value from the gamepad
\return The analog left brake value.
*/
PxF32 getAnalogLeftBrake() const
{
return mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT];
}
/**
\brief Return the analog right brake value from the gamepad
\return The analog right brake value.
*/
PxF32 getAnalogRightBrake() const
{
return mRawAnalogInputs[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT];
}
/**
\brief Record if the gear-up button has been pressed on keyboard or gamepad
\param[in] gearUp is true if the gear-up button has been pressed, false otherwise.
*/
void setGearUp(const bool gearUp) {mGearUp=gearUp;}
/**
\brief Record if the gear-down button has been pressed on keyboard or gamepad
\param[in] gearDown is true if the gear-down button has been pressed, false otherwise.
*/
void setGearDown(const bool gearDown) {mGearDown=gearDown;}
/**
\brief Return if the gear-up button has been pressed on keyboard or gamepad
\return True if the gear-up button has been pressed, false otherwise.
*/
bool getGearUp() const {return mGearUp;}
/**
\brief Return if the gear-down button has been pressed on keyboard or gamepad
\return True if the gear-down button has been pressed, false otherwise.
*/
bool getGearDown() const {return mGearDown;}
private:
PxVehicleDriveTankControlModel::Enum mMode;
PxReal mRawAnalogInputs[PxVehicleDriveTankControl::eMAX_NB_DRIVETANK_ANALOG_INPUTS];
bool mRawDigitalInputs[PxVehicleDriveTankControl::eMAX_NB_DRIVETANK_ANALOG_INPUTS];
bool mGearUp;
bool mGearDown;
};
/**
\brief Used to smooth and set analog tank control values from digital inputs (keyboard).
Also used to set boolean gearup, geardown values.
\param[in] keySmoothing describes the rise and fall rates of the corresponding analog values when keys are pressed on and off.
\param[in] rawInputData is the state of all digital inputs that control the vehicle.
\param[in] timestep is the time that has passed since the last call to PxVehicleDriveTankSmoothDigitalRawInputsAndSetAnalogInputs
\param[in] focusVehicle is the vehicle that will be given analog and gearup/geardown control values arising from the digital inputs.
*/
PX_DEPRECATED void PxVehicleDriveTankSmoothDigitalRawInputsAndSetAnalogInputs
(const PxVehicleKeySmoothingData& keySmoothing,
const PxVehicleDriveTankRawInputData& rawInputData,
const PxReal timestep,
PxVehicleDriveTank& focusVehicle);
/**
\brief Used to smooth and set analog tank control values from analog inputs (gamepad).
Also used to set boolean gearup, geardown values.
\param[in] padSmoothing describes how quickly the control values applied to the vehicle blend from the current vehicle values towards the raw analog values from the gamepad.
\param[in] rawInputData is the state of all gamepad analog inputs that will be used control the vehicle.
\param[in] timestep is the time that has passed since the last call to PxVehicleDriveTankSmoothAnalogRawInputsAndSetAnalogInputs
\param[in] focusVehicle is the vehicle that will be given analog control values arising from the gamepad inputs.
*/
PX_DEPRECATED void PxVehicleDriveTankSmoothAnalogRawInputsAndSetAnalogInputs
(const PxVehiclePadSmoothingData& padSmoothing,
const PxVehicleDriveTankRawInputData& rawInputData,
const PxReal timestep,
PxVehicleDriveTank& focusVehicle);
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 29,013 | C | 41.856721 | 173 | 0.780857 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleNoDrive.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_NO_DRIVE_H
#define PX_VEHICLE_NO_DRIVE_H
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleComponents.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxFilterData;
class PxGeometry;
class PxPhysics;
class PxVehicleDrivableSurfaceToTireFrictionPairs;
class PxShape;
class PxMaterial;
class PxRigidDynamic;
/**
\brief Data structure with instanced dynamics data and configuration data of a vehicle with no drive model.
*/
class PX_DEPRECATED PxVehicleNoDrive : public PxVehicleWheels
{
public:
friend class PxVehicleUpdate;
/**
\brief Allocate a PxVehicleNoDrive instance for a vehicle without drive model and with nbWheels
\param[in] nbWheels is the number of wheels on the vehicle.
\return The instantiated vehicle.
@see free, setup
*/
static PxVehicleNoDrive* allocate(const PxU32 nbWheels);
/**
\brief Deallocate a PxVehicleNoDrive instance.
@see allocate
*/
void free();
/**
\brief Set up a vehicle using simulation data for the wheels.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheels::setWheelShapeMapping.
@see allocate, free, setToRestState, PxVehicleWheels::setWheelShapeMapping
*/
void setup
(PxPhysics* physics, PxRigidDynamic* vehActor, const PxVehicleWheelsSimData& wheelsData);
/**
\brief Allocate and set up a vehicle using simulation data for the wheels.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheels::setWheelShapeMapping.
\return The instantiated vehicle.
@see allocate, free, setToRestState, PxVehicleWheels::setWheelShapeMapping
*/
static PxVehicleNoDrive* create
(PxPhysics* physics, PxRigidDynamic* vehActor, const PxVehicleWheelsSimData& wheelsData);
/**
\brief Set a vehicle to its rest state. Aside from the rigid body transform, this will set the vehicle and rigid body
to the state they were in immediately after setup or create.
\note Calling setToRestState invalidates the cached raycast hit planes under each wheel meaning that suspension line
raycasts need to be performed at least once with PxVehicleSuspensionRaycasts before calling PxVehicleUpdates.
@see setup, create, PxVehicleSuspensionRaycasts, PxVehicleUpdates
*/
void setToRestState();
/**
\brief Set the brake torque to be applied to a specific wheel
\note The applied brakeTorque persists until the next call to setBrakeTorque
\note The brake torque is specified in Newton metres.
\param[in] id is the wheel being given the brake torque
\param[in] brakeTorque is the value of the brake torque
*/
void setBrakeTorque(const PxU32 id, const PxReal brakeTorque);
/**
\brief Set the drive torque to be applied to a specific wheel
\note The applied driveTorque persists until the next call to setDriveTorque
\note The brake torque is specified in Newton metres.
\param[in] id is the wheel being given the brake torque
\param[in] driveTorque is the value of the brake torque
*/
void setDriveTorque(const PxU32 id, const PxReal driveTorque);
/**
\brief Set the steer angle to be applied to a specific wheel
\note The applied steerAngle persists until the next call to setSteerAngle
\note The steer angle is specified in radians.
\param[in] id is the wheel being given the steer angle
\param[in] steerAngle is the value of the steer angle in radians.
*/
void setSteerAngle(const PxU32 id, const PxReal steerAngle);
/**
\brief Get the brake torque that has been applied to a specific wheel
\param[in] id is the wheel being queried for its brake torque
\return The brake torque applied to the queried wheel.
*/
PxReal getBrakeTorque(const PxU32 id) const;
/**
\brief Get the drive torque that has been applied to a specific wheel
\param[in] id is the wheel being queried for its drive torque
\return The drive torque applied to the queried wheel.
*/
PxReal getDriveTorque(const PxU32 id) const;
/**
\brief Get the steer angle that has been applied to a specific wheel
\param[in] id is the wheel being queried for its steer angle
\return The steer angle (in radians) applied to the queried wheel.
*/
PxReal getSteerAngle(const PxU32 id) const;
private:
PxReal* mSteerAngles;
PxReal* mDriveTorques;
PxReal* mBrakeTorques;
#if PX_P64_FAMILY
PxU32 mPad[2];
#else
PxU32 mPad[1];
#endif
/**
\brief Test if the instanced dynamics and configuration data has legal values.
*/
bool isValid() const;
//serialization
public:
PxVehicleNoDrive(PxBaseFlags baseFlags) : PxVehicleWheels(baseFlags) {}
virtual void exportExtraData(PxSerializationContext&);
void importExtraData(PxDeserializationContext&);
static PxVehicleNoDrive* createObject(PxU8*& address, PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
virtual const char* getConcreteTypeName() const { return "PxVehicleNoDrive"; }
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxVehicleNoDrive", PxVehicleWheels); }
PxU32 getNbSteerAngle() const { return mWheelsSimData.getNbWheels(); }
PxU32 getNbDriveTorque() const { return mWheelsSimData.getNbWheels(); }
PxU32 getNbBrakeTorque() const { return mWheelsSimData.getNbWheels(); }
protected:
PxVehicleNoDrive();
~PxVehicleNoDrive() {}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleNoDrive) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 8,036 | C | 38.014563 | 178 | 0.768417 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleUtilTelemetry.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_UTIL_TELEMETRY_H
#define PX_VEHICLE_UTIL_TELEMETRY_H
#include "vehicle/PxVehicleSDK.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_DEBUG_VEHICLE_ON
class PX_DEPRECATED PxVehicleGraphDesc
{
friend class PxVehicleGraph;
PxVehicleGraphDesc();
/**
\brief x-coord of graph centre.
<b>Range:</b> (0,1)<br>
*/
PxReal mPosX;
/**
\brief y-coord of graph centre.
<b>Range:</b> (0,1)<br>
*/
PxReal mPosY;
/**
\brief x-extents of graph (from mPosX-0.5f*mSizeX to mPosX+0.5f*mSizeX).
<b>Range:</b> (0,1)<br>
*/
PxReal mSizeX;
/**
\brief y-extents of graph (from mPosY-0.5f*mSizeY to mPosY+0.5f*mSizeY).
<b>Range:</b> (0,1)<br>
*/
PxReal mSizeY;
/**
\brief Background color of graph.
*/
PxVec3 mBackgroundColor;
/**
\brief Alpha value of background color.
*/
PxReal mAlpha;
private:
bool isValid() const;
};
struct PX_DEPRECATED PxVehicleGraphChannelDesc
{
public:
friend class PxVehicleGraph;
PxVehicleGraphChannelDesc();
/**
\brief Data values less than mMinY will be clamped at mMinY.
*/
PxReal mMinY;
/**
\brief Data values greater than mMaxY will be clamped at mMaxY.
*/
PxReal mMaxY;
/**
\brief Data values greater than mMidY will be drawn with color mColorHigh.
Data values less than mMidY will be drawn with color mColorLow.
*/
PxReal mMidY;
/**
\brief Color used to render data values lower than mMidY.
*/
PxVec3 mColorLow;
/**
\brief Color used to render data values greater than mMidY.
*/
PxVec3 mColorHigh;
/**
\brief String to describe data channel.
*/
char* mTitle;
private:
bool isValid() const;
};
struct PX_DEPRECATED PxVehicleWheelGraphChannel
{
enum Enum
{
eJOUNCE=0,
eSUSPFORCE,
eTIRELOAD,
eNORMALIZED_TIRELOAD,
eWHEEL_OMEGA,
eTIRE_FRICTION,
eTIRE_LONG_SLIP,
eNORM_TIRE_LONG_FORCE,
eTIRE_LAT_SLIP,
eNORM_TIRE_LAT_FORCE,
eNORM_TIRE_ALIGNING_MOMENT,
eMAX_NB_WHEEL_CHANNELS
};
};
struct PX_DEPRECATED PxVehicleDriveGraphChannel
{
enum Enum
{
eENGINE_REVS=0,
eENGINE_DRIVE_TORQUE,
eCLUTCH_SLIP,
eACCEL_CONTROL, //TANK_ACCEL
eBRAKE_CONTROL, //TANK_BRAKE_LEFT
eHANDBRAKE_CONTROL, //TANK_BRAKE_RIGHT
eSTEER_LEFT_CONTROL, //TANK_THRUST_LEFT
eSTEER_RIGHT_CONTROL, //TANK_THRUST_RIGHT
eGEAR_RATIO,
eMAX_NB_DRIVE_CHANNELS
};
};
struct PX_DEPRECATED PxVehicleGraphType
{
enum Enum
{
eWHEEL=0,
eDRIVE
};
};
class PX_DEPRECATED PxVehicleGraph
{
public:
friend class PxVehicleTelemetryData;
friend class PxVehicleUpdate;
enum
{
eMAX_NB_SAMPLES=256
};
enum
{
eMAX_NB_TITLE_CHARS=256
};
enum
{
eMAX_NB_CHANNELS=12
};
/**
\brief Setup a graph from a descriptor.
*/
void setup(const PxVehicleGraphDesc& desc, const PxVehicleGraphType::Enum graphType);
/**
\brief Clear all data recorded in a graph.
*/
void clearRecordedChannelData();
/**
\brief Get the color of the graph background. Used for rendering a graph.
*/
const PxVec3& getBackgroundColor() const {return mBackgroundColor;}
/**
\brief Get the alpha transparency of the color of the graph background. Used for rendering a graph.
*/
PxReal getBackgroundAlpha() const {return mBackgroundAlpha;}
/**
\brief Get the coordinates of the graph background. Used for rendering a graph
\param[out] xMin is the x-coord of the lower-left corner
\param[out] yMin is the y-coord of the lower-left corner
\param[out] xMax is the x-coord of the upper-right corner
\param[out] yMax is the y-coord of the upper-right corner
*/
void getBackgroundCoords(PxReal& xMin, PxReal& yMin, PxReal& xMax, PxReal& yMax) const {xMin = mBackgroundMinX;xMax = mBackgroundMaxX;yMin = mBackgroundMinY;yMax = mBackgroundMaxY;}
/**
\brief Compute the coordinates of the graph data of a specific graph channel.
\param[out] xy is an array of graph sample coordinates stored in order x0,y0,x1,y1,x2,y2...xn,yn.
\param[out] colors stores the color of each point on the graph.
\param[out] title is the title of the graph.
*/
void computeGraphChannel(const PxU32 channel, PxReal* xy, PxVec3* colors, char* title) const;
/**
\brief Return the latest value stored in the specified graph channel
*/
PxF32 getLatestValue(const PxU32 channel) const ;
/**
\brief Get the raw data of a specific graph channel.
\param[in] channel is the ID of the graph channel to get data from.
\param[out] values is the buffer to write the data to. Minimum required size is eMAX_NB_SAMPLES.
*/
void getRawData(const PxU32 channel, PxReal* values) const;
private:
//Min and max of each sample.
PxReal mChannelMinY[eMAX_NB_CHANNELS];
PxReal mChannelMaxY[eMAX_NB_CHANNELS];
//Discriminate between high and low values with different colors.
PxReal mChannelMidY[eMAX_NB_CHANNELS];
//Different colors for values than midY and less than midY.
PxVec3 mChannelColorLow[eMAX_NB_CHANNELS];
PxVec3 mChannelColorHigh[eMAX_NB_CHANNELS];
//Title of graph
char mChannelTitle[eMAX_NB_CHANNELS][eMAX_NB_TITLE_CHARS];
//Graph data.
PxReal mChannelSamples[eMAX_NB_CHANNELS][eMAX_NB_SAMPLES];
//Background color,alpha,coords
PxVec3 mBackgroundColor;
PxReal mBackgroundAlpha;
PxReal mBackgroundMinX;
PxReal mBackgroundMaxX;
PxReal mBackgroundMinY;
PxReal mBackgroundMaxY;
PxU32 mSampleTide;
PxU32 mNbChannels;
PxU32 mPad[2];
void 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);
void updateTimeSlice(const PxReal* const samples);
void setChannel(PxVehicleGraphChannelDesc& desc, const PxU32 channel);
void setupEngineGraph
(const PxF32 sizeX, const PxF32 sizeY, const PxF32 posX, const PxF32 posY,
const PxVec3& backgoundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow);
void setupWheelGraph
(const PxF32 sizeX, const PxF32 sizeY, const PxF32 posX, const PxF32 posY,
const PxVec3& backgoundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow);
PxVehicleGraph();
~PxVehicleGraph();
};
PX_COMPILE_TIME_ASSERT(PxU32(PxVehicleGraph::eMAX_NB_CHANNELS) >= PxU32(PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS) && PxU32(PxVehicleGraph::eMAX_NB_CHANNELS) >= PxU32(PxVehicleDriveGraphChannel::eMAX_NB_DRIVE_CHANNELS));
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleGraph) & 15));
class PX_DEPRECATED PxVehicleTelemetryData
{
public:
friend class PxVehicleUpdate;
/**
\brief Allocate a PxVehicleNWTelemetryData instance for a vehicle with nbWheels
@see PxVehicleNWTelemetryDataFree
*/
static PxVehicleTelemetryData* allocate(const PxU32 nbWheels);
/**
\brief Free a PxVehicleNWTelemetryData instance for a vehicle.
@see PxVehicleNWTelemetryDataAllocate
*/
void free();
/**
\brief Set up all the graphs so that they are ready to record data.
*/
void setup
(const PxReal graphSizeX, const PxReal graphSizeY,
const PxReal engineGraphPosX, const PxReal engineGraphPosY,
const PxReal* const wheelGraphPosX, const PxReal* const wheelGraphPosY,
const PxVec3& backGroundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow);
/**
\brief Clear the graphs of recorded data.
*/
void clear();
/**
\brief Get the graph data for the engine
*/
const PxVehicleGraph& getEngineGraph() const {return *mEngineGraph;}
/**
\brief Get the number of wheel graphs
*/
PxU32 getNbWheelGraphs() const {return mNbActiveWheels;}
/**
\brief Get the graph data for the kth wheel
*/
const PxVehicleGraph& getWheelGraph(const PxU32 k) const {return mWheelGraphs[k];}
/**
\brief Get the array of tire force application points so they can be rendered
*/
const PxVec3* getTireforceAppPoints() const {return mTireforceAppPoints;}
/**
\brief Get the array of susp force application points so they can be rendered
*/
const PxVec3* getSuspforceAppPoints() const {return mSuspforceAppPoints;}
private:
/**
\brief Graph data for engine.
Used for storing single timeslices of debug data for engine graph.
@see PxVehicleGraph
*/
PxVehicleGraph* mEngineGraph;
/**
\brief Graph data for each wheel.
Used for storing single timeslices of debug data for wheel graphs.
@see PxVehicleGraph
*/
PxVehicleGraph* mWheelGraphs;
/**
\brief Application point of tire forces.
*/
PxVec3* mTireforceAppPoints;
/**
\brief Application point of susp forces.
*/
PxVec3* mSuspforceAppPoints;
/**
\brief Total number of active wheels
*/
PxU32 mNbActiveWheels;
PxU32 mPad[3];
private:
PxVehicleTelemetryData(){}
~PxVehicleTelemetryData(){}
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleTelemetryData) & 15));
#endif //PX_DEBUG_VEHICLE_ON
//#endif // PX_DEBUG_VEHICLE_ON
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 10,565 | C | 24.521739 | 229 | 0.741316 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleSDK.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_SDK_H
#define PX_VEHICLE_SDK_H
#include "foundation/Px.h"
#include "foundation/PxVec3.h"
#include "common/PxTypeInfo.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxPhysics;
class PxSerializationRegistry;
/**
\brief Initialize the PhysXVehicle library.
Call this before using any of the vehicle functions.
\param physics The PxPhysics instance.
\param serializationRegistry PxSerializationRegistry instance, if NULL vehicle serialization is not supported.
\note This function must be called after PxFoundation and PxPhysics instances have been created.
\note If a PxSerializationRegistry instance is specified then PhysXVehicle is also dependent on PhysXExtensions.
@see PxCloseVehicleSDK
*/
PX_DEPRECATED PX_C_EXPORT bool PX_CALL_CONV PxInitVehicleSDK(PxPhysics& physics, PxSerializationRegistry* serializationRegistry = NULL);
/**
\brief Shut down the PhysXVehicle library.
Call this function as part of the physx shutdown process.
\param serializationRegistry PxSerializationRegistry instance, if non-NULL must be the same as passed into PxInitVehicleSDK.
\note This function must be called prior to shutdown of PxFoundation and PxPhysics.
\note If the PxSerializationRegistry instance is specified this function must additionally be called prior to shutdown of PhysXExtensions.
@see PxInitVehicleSDK
*/
PX_DEPRECATED PX_C_EXPORT void PX_CALL_CONV PxCloseVehicleSDK(PxSerializationRegistry* serializationRegistry = NULL);
/**
\brief This number is the maximum number of wheels allowed for a vehicle.
*/
#define PX_MAX_NB_WHEELS (20)
/**
\brief Compiler setting to enable recording of telemetry data
@see PxVehicleUpdateSingleVehicleAndStoreTelemetryData, PxVehicleTelemetryData
*/
#define PX_DEBUG_VEHICLE_ON (1)
/**
@see PxVehicleDrive4W, PxVehicleDriveTank, PxVehicleDriveNW, PxVehicleNoDrive, PxVehicleWheels::getVehicleType
*/
struct PX_DEPRECATED PxVehicleTypes
{
enum Enum
{
eDRIVE4W=0,
eDRIVENW,
eDRIVETANK,
eNODRIVE,
eUSER1,
eUSER2,
eUSER3,
eMAX_NB_VEHICLE_TYPES
};
};
/**
\brief An enumeration of concrete vehicle classes inheriting from PxBase.
\note This enum can be used to identify a vehicle object stored in a PxCollection.
@see PxBase, PxTypeInfo, PxBase::getConcreteType
*/
struct PX_DEPRECATED PxVehicleConcreteType
{
enum Enum
{
eVehicleNoDrive = PxConcreteType::eFIRST_VEHICLE_EXTENSION,
eVehicleDrive4W,
eVehicleDriveNW,
eVehicleDriveTank
};
};
/**
\brief Set the basis vectors of the vehicle simulation
See PxVehicleContext for the default values.
Call this function before using PxVehicleUpdates unless the default values are correct
or the settings structure is explicitly provided.
@see PxVehicleContext
*/
PX_DEPRECATED void PxVehicleSetBasisVectors(const PxVec3& up, const PxVec3& forward);
/**
@see PxVehicleSetUpdateMode
*/
struct PX_DEPRECATED PxVehicleUpdateMode
{
enum Enum
{
eVELOCITY_CHANGE,
eACCELERATION
};
};
/**
\brief Set the effect of PxVehicleUpdates to be either to modify each vehicle's rigid body actor
with an acceleration to be applied in the next PhysX SDK update or as an immediate velocity modification.
See PxVehicleContext for the default value.
Call this function before using PxVehicleUpdates for the first time if the default is not the desired behavior
or if the settings structure is not explicitly provided.
@see PxVehicleUpdates, PxVehicleContext
*/
PX_DEPRECATED void PxVehicleSetUpdateMode(PxVehicleUpdateMode::Enum vehicleUpdateMode);
/**
\brief Set threshold angles that are used to determine if a wheel hit is to be resolved by vehicle suspension or by rigid body collision.
\note ^
N ___
|**
**
**
%%% %%% **
%%% %%% ** /
/
%%% %%% /
/
%%% %%% /
C /
%%% | ** %%% /
| ** /
%%% | **%%%/
| X**
%%% | %%% / **_| ^
| / D
%%% | %%% /
| /
| /
| /
|
^ |
S \|/
The diagram above depicts a wheel centered at "C" that has hit an inclined plane at point "X".
The inclined plane has unit normal "N", while the suspension direction has unit vector "S".
The unit vector from the wheel center to the hit point is "D".
Hit points are analyzed by comparing the unit vectors D and N with the suspension direction S.
This analysis is performed in the contact modification callback PxVehicleModifyWheelContacts (when enabled) and in
PxVehicleUpdates (when non-blocking sweeps are enabled).
If the angle between D and S is less than pointRejectAngle the hit is accepted by the suspension in PxVehicleUpdates and rejected
by the contact modification callback PxVehicleModifyWheelContacts.
If the angle between -N and S is less than normalRejectAngle the hit is accepted by the suspension in PxVehicleUpdates and rejected
by the contact modification callback PxVehicleModifyWheelContacts.
\param pointRejectAngle is the threshold angle used when comparing the angle between D and S.
\param normalRejectAngle is the threshold angle used when comparing the angle between -N and S.
\note PxVehicleUpdates ignores the rejection angles for raycasts and for sweeps that return blocking hits.
\note Both angles have default values of Pi/4.
@see PxVehicleSuspensionSweeps, PxVehicleModifyWheelContacts, PxVehicleContext
*/
PX_DEPRECATED void PxVehicleSetSweepHitRejectionAngles(const PxF32 pointRejectAngle, const PxF32 normalRejectAngle);
/**
\brief Determine the maximum acceleration experienced by PxRigidDynamic instances that are found to be in contact
with a wheel.
\note Newton's Third Law states that every force has an equal and opposite force. As a consequence, forces applied to
the suspension must be applied to dynamic objects that lie under the wheel. This can lead to instabilities, particularly
when a heavy wheel is driving on a light object. The value of maxHitActorAcceleration clamps the applied force so that it never
generates an acceleration greater than the specified value.
See PxVehicleContext for the default value.
@see PxVehicleContext
*/
PX_DEPRECATED void PxVehicleSetMaxHitActorAcceleration(const PxF32 maxHitActorAcceleration);
/**
\brief Common parameters and settings used for the vehicle simulation.
To be passed into PxVehicleUpdates(), for example.
@see PxVehicleUpdates()
*/
class PX_DEPRECATED PxVehicleContext
{
public:
/**
\brief The axis denoting the up direction for vehicles.
<b>Range:</b> unit length vector<br>
<b>Default:</b> PxVec3(0,1,0)
@see PxVehicleSetBasisVectors()
*/
PxVec3 upAxis;
/**
\brief The axis denoting the forward direction for vehicles.
<b>Range:</b> unit length vector<br>
<b>Default:</b> PxVec3(0,0,1)
@see PxVehicleSetBasisVectors()
*/
PxVec3 forwardAxis;
/**
\brief The axis denoting the side direction for vehicles.
Has to be the cross product of the up- and forward-axis. The method
computeSideAxis() can be used to do that computation for you.
<b>Range:</b> unit length vector<br>
<b>Default:</b> PxVec3(1,0,0)
@see PxVehicleSetBasisVectors(), computeSideAxis()
*/
PxVec3 sideAxis;
/**
\brief Apply vehicle simulation results as acceleration or velocity modification.
See PxVehicleSetUpdateMode() for details.
<b>Default:</b> eVELOCITY_CHANGE
@see PxVehicleSetUpdateMode()
*/
PxVehicleUpdateMode::Enum updateMode;
/**
\brief Cosine of threshold angle for rejecting sweep hits.
See PxVehicleSetSweepHitRejectionAngles() for details.
<b>Range:</b> (1, -1)<br>
<b>Default:</b> 0.707f (cosine of 45 degrees)
@see PxVehicleSetSweepHitRejectionAngles()
*/
PxF32 pointRejectAngleThresholdCosine;
/**
\brief Cosine of threshold angle for rejecting sweep hits.
See PxVehicleSetSweepHitRejectionAngles() for details.
<b>Range:</b> (1, -1)<br>
<b>Default:</b> 0.707f (cosine of 45 degrees)
@see PxVehicleSetSweepHitRejectionAngles()
*/
PxF32 normalRejectAngleThresholdCosine;
/**
\brief Maximum acceleration experienced by PxRigidDynamic instances that are found to be in contact with a wheel.
See PxVehicleSetMaxHitActorAcceleration() for details.
<b>Range:</b> [0, PX_MAX_REAL]<br>
<b>Default:</b> PX_MAX_REAL
@see PxVehicleSetMaxHitActorAcceleration()
*/
PxF32 maxHitActorAcceleration;
public:
/**
\brief Constructor sets to default.
*/
PX_INLINE PxVehicleContext();
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault();
/**
\brief Check if the settings descriptor is valid.
\return True if the current settings are valid.
*/
PX_INLINE bool isValid() const;
/**
\brief Compute the side-axis from the up- and forward-axis
*/
PX_INLINE void computeSideAxis();
};
PX_INLINE PxVehicleContext::PxVehicleContext():
upAxis(0.0f, 1.0f, 0.0f),
forwardAxis(0.0f, 0.0f, 1.0f),
sideAxis(1.0f, 0.0f, 0.0f),
updateMode(PxVehicleUpdateMode::eVELOCITY_CHANGE),
pointRejectAngleThresholdCosine(0.707f), // cosine of 45 degrees
normalRejectAngleThresholdCosine(0.707f), // cosine of 45 degrees
maxHitActorAcceleration(PX_MAX_REAL)
{
}
PX_INLINE void PxVehicleContext::setToDefault()
{
*this = PxVehicleContext();
}
PX_INLINE bool PxVehicleContext::isValid() const
{
if (!upAxis.isNormalized())
return false;
if (!forwardAxis.isNormalized())
return false;
if (!sideAxis.isNormalized())
return false;
if (((upAxis.cross(forwardAxis)) - sideAxis).magnitude() > 0.02f) // somewhat above 1 degree assuming both have unit length
return false;
if ((pointRejectAngleThresholdCosine >= 1) || (pointRejectAngleThresholdCosine <= -1))
return false;
if ((normalRejectAngleThresholdCosine >= 1) || (normalRejectAngleThresholdCosine <= -1))
return false;
if (maxHitActorAcceleration < 0.0f)
return false;
return true;
}
PX_INLINE void PxVehicleContext::computeSideAxis()
{
sideAxis = upAxis.cross(forwardAxis);
}
/**
\brief Get the default vehicle context.
Will be used if the corresponding parameters are not specified in methods like
PxVehicleUpdates() etc.
To set the default values, see the methods PxVehicleSetBasisVectors(),
PxVehicleSetUpdateMode() etc.
\return The default vehicle context.
@see PxVehicleSetBasisVectors() PxVehicleSetUpdateMode()
*/
PX_DEPRECATED const PxVehicleContext& PxVehicleGetDefaultContext();
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 12,441 | C | 28.553444 | 138 | 0.728478 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleShaders.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_SHADERS_H
#define PX_VEHICLE_SHADERS_H
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Prototype of shader function that is used to compute wheel torque and tire forces.
\param[in] shaderData is the shader data for the tire being processed. The shader data describes the tire data in the format required by the tire model that is implemented by the shader function.
\param[in] tireFriction is the value of friction for the contact between the tire and the ground.
\param[in] longSlip is the value of longitudinal slip experienced by the tire.
\param[in] latSlip is the value of lateral slip experienced by the tire.
\param[in] camber is the camber angle of the tire in radians.
\param[in] wheelOmega is the rotational speed of the wheel.
\param[in] wheelRadius is the distance from the tire surface to the center of the wheel.
\param[in] recipWheelRadius is the reciprocal of wheelRadius.
\param[in] restTireLoad is the load force experienced by the tire when the vehicle is at rest.
\param[in] normalisedTireLoad is a pre-computed value equal to the load force on the tire divided by restTireLoad.
\param[in] tireLoad is the load force currently experienced by the tire (= restTireLoad*normalisedTireLoad)
\param[in] gravity is the magnitude of gravitational acceleration.
\param[in] recipGravity is the reciprocal of the magnitude of gravitational acceleration.
\param[out] wheelTorque is the torque that is to be applied to the wheel around the wheel's axle.
\param[out] tireLongForceMag is the magnitude of the longitudinal tire force to be applied to the vehicle's rigid body.
\param[out] tireLatForceMag is the magnitude of the lateral tire force to be applied to the vehicle's rigid body.
\param[out] tireAlignMoment is the aligning moment of the tire that is to be applied to the vehicle's rigid body (not currently used).
@see PxVehicleWheelsDynData::setTireForceShaderFunction, PxVehicleWheelsDynData::setTireForceShaderData
*/
PX_DEPRECATED typedef void (*PxVehicleComputeTireForce)
(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);
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 4,246 | C | 55.626666 | 197 | 0.784032 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleDrive.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_DRIVE_H
#define PX_VEHICLE_DRIVE_H
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleComponents.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxFilterData;
class PxGeometry;
class PxPhysics;
class PxVehicleDrivableSurfaceToTireFrictionPairs;
class PxShape;
class PxMaterial;
class PxRigidDynamic;
/**
\brief Data structure describing non-wheel configuration data of a vehicle that has engine, gears, clutch, and auto-box.
@see PxVehicleWheelsSimData for wheels configuration data.
*/
class PX_DEPRECATED PxVehicleDriveSimData
{
public:
friend class PxVehicleDriveTank;
/**
\brief Return the engine data
*/
PX_FORCE_INLINE const PxVehicleEngineData& getEngineData() const
{
return mEngine;
}
/**
\brief Set the engine data
\param[in] engine - the data stored in engine is copied to the vehicle's engine.
*/
void setEngineData(const PxVehicleEngineData& engine);
/**
\brief Return the gears data
*/
PX_FORCE_INLINE const PxVehicleGearsData& getGearsData() const
{
return mGears;
}
/**
\brief Set the gears data
\param[in] gears - the data stored in gears is copied to the vehicle's gears.
*/
void setGearsData(const PxVehicleGearsData& gears);
/**
\brief Return the clutch data
*/
PX_FORCE_INLINE const PxVehicleClutchData& getClutchData() const
{
return mClutch;
}
/**
\brief Set the clutch data
\param[in] clutch - the data stored in clutch is copied to the vehicle's clutch.
*/
void setClutchData(const PxVehicleClutchData& clutch);
/**
\brief Return the autobox data
*/
PX_FORCE_INLINE const PxVehicleAutoBoxData& getAutoBoxData() const
{
return mAutoBox;
}
/**
\brief Set the autobox data
\param[in] autobox - the data stored in autobox is copied to the vehicle's autobox.
*/
void setAutoBoxData(const PxVehicleAutoBoxData& autobox);
protected:
/*
\brief Engine simulation data
@see setEngineData, getEngineData
*/
PxVehicleEngineData mEngine;
/*
\brief Gear simulation data
@see setGearsData, getGearsData
*/
PxVehicleGearsData mGears;
/*
\brief Clutch simulation data
@see setClutchData, getClutchData
*/
PxVehicleClutchData mClutch;
/*
\brief Autobox simulation data
@see setAutoboxData, getAutoboxData
*/
PxVehicleAutoBoxData mAutoBox;
/**
\brief Test that a PxVehicleDriveSimData instance has been configured with legal data.
Call only after setting all components with setEngineData,setGearsData,setClutchData,setAutoBoxData
@see PxVehicleDrive4W::setup, PxVehicleDriveTank::setup
*/
bool isValid() const;
//serialization
public:
PxVehicleDriveSimData() {}
PxVehicleDriveSimData(const PxEMPTY) : mEngine(PxEmpty), mGears(PxEmpty), mClutch(PxEmpty), mAutoBox(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveSimData) & 15));
/**
\brief Data structure with instanced dynamics data for vehicle with engine, clutch, gears, autobox
@see PxVehicleWheelsDynData for wheels dynamics data.
*/
class PX_DEPRECATED PxVehicleDriveDynData
{
public:
enum
{
eMAX_NB_ANALOG_INPUTS=16
};
friend class PxVehicleDrive;
/**
\brief Set all dynamics data to zero to bring the vehicle to rest.
*/
void setToRestState();
/**
\brief Set an analog control value to drive the vehicle.
\param[in] type describes the type of analog control being modified
\param[in] analogVal is the new value of the specific analog control.
@see PxVehicleDrive4WControl, PxVehicleDriveNWControl, PxVehicleDriveTankControl
*/
void setAnalogInput(const PxU32 type, const PxReal analogVal);
/**
\brief Get the analog control value that has been applied to the vehicle.
\return The value of the specified analog control value.
@see PxVehicleDrive4WControl, PxVehicleDriveNWControl, PxVehicleDriveTankControl
*/
PxReal getAnalogInput(const PxU32 type) const;
/**
\brief Inform the vehicle that the gear-up button has been pressed.
\param[in] digitalVal is the state of the gear-up button.
\note If digitalVal is true the vehicle will attempt to initiate a gear change at the next call to PxVehicleUpdates.
\note The value of mGearUpPressed is not reset by PxVehicleUpdates
*/
void setGearUp(const bool digitalVal)
{
mGearUpPressed = digitalVal;
}
/**
\brief Set that the gear-down button has been pressed.
\param[in] digitalVal is the state of the gear-down button.
\note If digitalVal is true the vehicle will attempt to initiate a gear change at the next call to PxVehicleUpdates.
\note The value of mGearDownPressed is not reset by PxVehicleUpdates
*/
void setGearDown(const bool digitalVal)
{
mGearDownPressed = digitalVal;
}
/**
\brief Check if the gear-up button has been pressed
\return The state of the gear-up button.
*/
bool getGearUp() const
{
return mGearUpPressed;
}
/**
\brief Check if the gear-down button has been pressed
\return The state of the gear-down button.
*/
bool getGearDown() const
{
return mGearDownPressed;
}
/**
\brief Set the flag that will be used to select auto-gears
If useAutoGears is true the auto-box will be active.
\param[in] useAutoGears is the active state of the auto-box.
*/
PX_FORCE_INLINE void setUseAutoGears(const bool useAutoGears)
{
mUseAutoGears=useAutoGears;
}
/**
\brief Get the flag status that is used to select auto-gears
\return The active status of the auto-box.
*/
PX_FORCE_INLINE bool getUseAutoGears() const
{
return mUseAutoGears;
}
/**
\brief Toggle the auto-gears flag
If useAutoGears is true the auto-box will be active.
*/
PX_FORCE_INLINE void toggleAutoGears()
{
mUseAutoGears = !mUseAutoGears;
}
/**
\brief Set the current gear.
\param[in] currentGear is the vehicle's gear.
\note If the target gear is different from the current gear the vehicle will
attempt to start a gear change from the current gear that has just been set
towards the target gear at the next call to PxVehicleUpdates.
@see setTargetGear, PxVehicleGearsData
*/
PX_FORCE_INLINE void setCurrentGear(PxU32 currentGear)
{
mCurrentGear = currentGear;
}
/**
\brief Get the current gear.
\return The vehicle's current gear.
@see getTargetGear, PxVehicleGearsData
*/
PX_FORCE_INLINE PxU32 getCurrentGear() const
{
return mCurrentGear;
}
/**
\brief Set the target gear.
\param[in] targetGear is the vehicle's target gear.
\note If the target gear is different from the current gear the vehicle will
attempt to start a gear change towards the target gear at the next call to
PxVehicleUpdates.
@see PxVehicleGearsData
*/
PX_FORCE_INLINE void setTargetGear(PxU32 targetGear)
{
mTargetGear = targetGear;
}
/**
\brief Get the target gear.
\return The vehicle's target gear.
@see setTargetGear, PxVehicleGearsData
*/
PX_FORCE_INLINE PxU32 getTargetGear() const
{
return mTargetGear;
}
/**
\brief Start a gear change to a target gear.
\param[in] targetGear is the gear the vehicle will begin a transition towards.
\note The gear change will begin at the next call to PxVehicleUpadates.
@see PxVehicleGearsData
*/
PX_FORCE_INLINE void startGearChange(const PxU32 targetGear)
{
mTargetGear=targetGear;
}
/**
\brief Force an immediate gear change to a target gear
\param[in] targetGear is the gear the vehicle will be given immediately.
@see PxVehicleGearsData
*/
PX_FORCE_INLINE void forceGearChange(const PxU32 targetGear)
{
mTargetGear=targetGear;
mCurrentGear=targetGear;
}
/**
\brief Set the rotation speed of the engine (radians per second)
\param[in] speed is the rotational speed (radians per second) to apply to the engine.
*/
PX_FORCE_INLINE void setEngineRotationSpeed(const PxF32 speed)
{
mEnginespeed = speed;
}
/**
\brief Return the rotation speed of the engine (radians per second)
\return The rotational speed (radians per second) of the engine.
*/
PX_FORCE_INLINE PxReal getEngineRotationSpeed() const
{
return mEnginespeed;
}
/**
\brief Return the time that has passed since the current gear change was initiated.
\return The time that has passed since the current gear change was initiated.
\note If no gear change is in process the gear switch time will be zero.
@see PxVehicleGearsData.mSwitchTime
*/
PX_FORCE_INLINE PxReal getGearSwitchTime() const
{
return mGearSwitchTime;
}
/**
\brief Return the time that has passed since the autobox last initiated a gear change.
\return The time that has passed since the autobox last initiated a gear change.
@see PxVehicleAutoBoxData::setLatency, PxVehicleAutoBoxData::getLatency
*/
PX_FORCE_INLINE PxReal getAutoBoxSwitchTime() const
{
return mAutoBoxSwitchTime;
}
/**
\brief All dynamic data values are public for fast access.
*/
/**
\brief Analog control values used by vehicle simulation.
@see setAnalogInput, getAnalogInput, PxVehicleDrive4WControl, PxVehicleDriveNWControl, PxVehicleDriveTankControl
*/
PxReal mControlAnalogVals[eMAX_NB_ANALOG_INPUTS];
/**
\brief Auto-gear flag used by vehicle simulation. Set true to enable the autobox, false to disable the autobox.
@see setUseAutoGears, setUseAutoGears, toggleAutoGears, PxVehicleAutoBoxData
*/
bool mUseAutoGears;
/**
\brief Gear-up digital control value used by vehicle simulation.
\note If true a gear change will be initiated towards currentGear+1 (or to first gear if in reverse).
@see setDigitalInput, getDigitalInput
*/
bool mGearUpPressed;
/**
\brief Gear-down digital control value used by vehicle simulation.
\note If true a gear change will be initiated towards currentGear-1 (or to reverse if in first).
@see setDigitalInput, getDigitalInput
*/
bool mGearDownPressed;
/**
\brief Current gear
@see startGearChange, forceGearChange, getCurrentGear, PxVehicleGearsData
*/
PxU32 mCurrentGear;
/**
\brief Target gear (different from current gear if a gear change is underway)
@see startGearChange, forceGearChange, getTargetGear, PxVehicleGearsData
*/
PxU32 mTargetGear;
/**
\brief Rotation speed of engine
@see setToRestState, getEngineRotationSpeed
*/
PxReal mEnginespeed;
/**
\brief Reported time that has passed since gear change started.
@see setToRestState, startGearChange, PxVehicleGearsData::mSwitchTime
*/
PxReal mGearSwitchTime;
/**
\brief Reported time that has passed since last autobox gearup/geardown decision.
@see setToRestState, PxVehicleAutoBoxData::setLatency
*/
PxReal mAutoBoxSwitchTime;
private:
PxU32 mPad[2];
/**
\brief Test that a PxVehicleDriveDynData instance has legal values.
@see setToRestState
*/
bool isValid() const;
//serialization
public:
PxVehicleDriveDynData();
PxVehicleDriveDynData(const PxEMPTY) {}
PxU32 getNbAnalogInput() const { return eMAX_NB_ANALOG_INPUTS; }
PX_FORCE_INLINE void setGearChange(const PxU32 gearChange) { mTargetGear= gearChange; }
PX_FORCE_INLINE PxU32 getGearChange() const { return mTargetGear; }
PX_FORCE_INLINE void setGearSwitchTime(const PxReal switchTime) { mGearSwitchTime = switchTime; }
PX_FORCE_INLINE void setAutoBoxSwitchTime(const PxReal autoBoxSwitchTime) { mAutoBoxSwitchTime = autoBoxSwitchTime; }
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveDynData) & 15));
/**
\brief A complete vehicle with instance dynamics data and configuration data for wheels and engine,clutch,gears,autobox.
@see PxVehicleDrive4W, PxVehicleDriveTank
*/
class PX_DEPRECATED PxVehicleDrive : public PxVehicleWheels
{
public:
friend class PxVehicleUpdate;
/**
\brief Dynamics data of vehicle instance.
@see setup
*/
PxVehicleDriveDynData mDriveDynData;
protected:
/**
\brief Test that all instanced dynamics data and configuration data have legal values.
*/
bool isValid() const;
/**
\brief Set vehicle to rest.
*/
void setToRestState();
/**
@see PxVehicleDrive4W::allocate, PxVehicleDriveTank::allocate
*/
static PxU32 computeByteSize(const PxU32 numWheels);
static PxU8* patchupPointers(const PxU32 nbWheels, PxVehicleDrive* vehDrive, PxU8* ptr);
virtual void init(const PxU32 numWheels);
/**
\brief Deallocate a PxVehicle4WDrive instance.
@see PxVehicleDrive4W::free, PxVehicleDriveTank::free
*/
void free();
/**
@see PxVehicleDrive4W::setup, PxVehicleDriveTank::setup
*/
void setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData,
const PxU32 nbDrivenWheels, const PxU32 nbNonDrivenWheels);
//serialization
public:
static void getBinaryMetaData(PxOutputStream& stream);
PxVehicleDrive(PxBaseFlags baseFlags) : PxVehicleWheels(baseFlags), mDriveDynData(PxEmpty) {}
virtual const char* getConcreteTypeName() const { return "PxVehicleDrive"; }
protected:
PxVehicleDrive(PxType concreteType, PxBaseFlags baseFlags) : PxVehicleWheels(concreteType, baseFlags) {}
~PxVehicleDrive() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxVehicleDrive", PxVehicleWheels); }
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDrive) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 14,805 | C | 25.969035 | 120 | 0.757109 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleWheels.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_WHEELS_H
#define PX_VEHICLE_WHEELS_H
#include "foundation/PxSimpleTypes.h"
#include "vehicle/PxVehicleShaders.h"
#include "vehicle/PxVehicleComponents.h"
#include "common/PxBase.h"
#include "PxRigidDynamic.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxVehicleWheels4SimData;
class PxVehicleWheels4DynData;
class PxVehicleTireForceCalculator;
class PxShape;
class PxPhysics;
class PxMaterial;
/**
\brief Flags to configure the vehicle wheel simulation.
@see PxVehicleWheelsSimData::setFlags(), PxVehicleWheelsSimData::getFlags()
*/
struct PX_DEPRECATED PxVehicleWheelsSimFlag
{
enum Enum
{
/**
\brief Limit the suspension expansion velocity.
For extreme damping ratios, large damping forces might result in the vehicle sticking to the ground where
one would rather expect to see the vehicle lift off. While it is highly recommended to use somewhat realistic
damping ratios, this flag can be used to limit the velocity of the suspension. In more detail, the simulation
will check whether the suspension can extend to the target length in the given simulation time step. If that
is the case, the suspension force will be computed as usual, else the force will be set to zero. Enabling
this feature gives a slightly more realisitic behavior at the potential cost of more easily losing control
when steering the vehicle.
*/
eLIMIT_SUSPENSION_EXPANSION_VELOCITY = (1 << 0),
/**
\brief Disable internal cylinder-plane intersection test.
By default the internal code runs a post-process on sweep results, approximating the wheel shape with a
cylinder and tweaking the sweep hit results accordingly. This can produce artefacts in certain cases, in
particular when the swept shape is very different from a cylinder - e.g. with swept spheres. This flag
tells the system to disable this internal test, and reuse the direct user-provided sweep results.
The default code refines the sweep results in each substep. Enabling this flag makes the system partially
reuse the same sweep results over each substep, which could potentially create other artefacts.
*/
eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST = (1 << 1),
/**
\brief Disable suspension force projection.
By default the internal code modulates the suspension force with the contact normal, i.e. the more the contact
normal is aligned with the suspension direction, the bigger the force. This can create issues when using a
single blocking hit, whose unique contact normal sometimes does not accurately capture the reality of the
surrounding geometry. For example it can weaken the suspension force too much, which visually makes the wheel
move up and down against e.g. a kerb. Enabling this flag tells the system to disable the modulation of the
suspension force by the contact normal.
The rationale is that a real tire has a deformed contact patch containing multiple normals, and even if some
of these normals are bent when colliding against a kerb, there would still be a large area of the contact patch
touching the ground, and getting normals aligned with the suspension. This is difficult to capture with simple
sweep results, especially with a single sweep hit whose normal is computed by a less than accurate algorithm
like GJK. Using this flag shortcuts these issues, which can improves the behavior when driving over kerbs or
small obstacles.
*/
eDISABLE_SUSPENSION_FORCE_PROJECTION = (1 << 2),
/**
\brief Disable check for sprung mass values summing up to chassis mass.
Generally, the sum of the suspension sprung mass values should match the chassis mass. However, there can be
scenarios where this is not necessarily desired. Taking a semi-trailer truck as an example, a large part of
the trailer mass will rest on the tractor unit and not the trailer wheels. This flag allows the user to set
the values as desired without error messages being sent.
*/
eDISABLE_SPRUNG_MASS_SUM_CHECK = (1 << 3)
};
};
/**
\brief Collection of set bits defined in #PxVehicleWheelsSimFlag.
@see PxVehicleWheelsSimFlag
*/
typedef PxFlags<PxVehicleWheelsSimFlag::Enum, PxU32> PxVehicleWheelsSimFlags;
PX_FLAGS_OPERATORS(PxVehicleWheelsSimFlag::Enum, PxU32)
/**
\brief Data structure describing configuration data of a vehicle with up to 20 wheels.
*/
class PX_DEPRECATED PxVehicleWheelsSimData
{
public:
friend class PxVehicleWheels;
friend class PxVehicleNoDrive;
friend class PxVehicleDrive4W;
friend class PxVehicleDriveTank;
friend class PxVehicleUpdate;
/**
\brief Allocate a PxVehicleWheelsSimData instance for with nbWheels.
@see free
*/
static PxVehicleWheelsSimData* allocate(const PxU32 nbWheels);
/**
\brief Setup with mass information that can be applied to the default values of the suspensions, wheels, and tires
set in their respective constructors.
\param chassisMass is the mass of the chassis.
\note This function assumes that the suspensions equally share the load of the chassis mass. It also
assumes that the suspension will have a particular natural frequency and damping ratio that is typical
of a standard car. If either of these assumptions is broken then each suspension will need to
be individually configured with custom strength, damping rate, and sprung mass.
@see allocate
*/
void setChassisMass(const PxF32 chassisMass);
/**
\brief Free a PxVehicleWheelsSimData instance
@see allocate
*/
void free();
/**
\brief Copy wheel simulation data.
\note The number of wheels on both instances of PxVehicleWheelsSimData must match.
*/
PxVehicleWheelsSimData& operator=(const PxVehicleWheelsSimData& src);
/**
\brief Copy the data of a single wheel unit (wheel, suspension, tire) from srcWheel of src to trgWheel.
\param[in] src is the data to be copied.
\param[in] srcWheel is the wheel whose data will be copied from src.
\param[in] trgWheel is the wheel that will be assigned the copied data.
*/
void copy(const PxVehicleWheelsSimData& src, const PxU32 srcWheel, const PxU32 trgWheel);
/**
\brief Return the number of wheels
@see allocate
*/
PxU32 getNbWheels() const {return mNbActiveWheels;}
/**
\brief Return the suspension data of the idth wheel
*/
const PxVehicleSuspensionData& getSuspensionData(const PxU32 id) const;
/**
\brief Return the wheel data of the idth wheel
*/
const PxVehicleWheelData& getWheelData(const PxU32 id) const;
/**
\brief Return the tire data of the idth wheel
*/
const PxVehicleTireData& getTireData(const PxU32 id) const;
/**
\brief Return the direction of travel of the suspension of the idth wheel
*/
const PxVec3& getSuspTravelDirection(const PxU32 id) const;
/**
\brief Return the application point of the suspension force of the suspension of the idth wheel as an offset from the rigid body center of mass.
\note Specified relative to the center of mass of the rigid body
*/
const PxVec3& getSuspForceAppPointOffset(const PxU32 id) const;
/**
\brief Return the application point of the tire force of the tire of the idth wheel as an offset from the rigid body center of mass.
\note Specified relative to the centre of mass of the rigid body
*/
const PxVec3& getTireForceAppPointOffset(const PxU32 id) const;
/**
\brief Return the offset from the rigid body centre of mass to the centre of the idth wheel.
*/
const PxVec3& getWheelCentreOffset(const PxU32 id) const;
/**
\brief Return the wheel mapping for the ith wheel.
\note The return value is the element in the array of
shapes of the vehicle's PxRigidDynamic that corresponds to the ith wheel. A return value of -1 means
that the wheel is not mapped to a PxShape.
@see PxRigidActor.getShapes
*/
PxI32 getWheelShapeMapping(const PxU32 wheelId) const;
/**
\brief Return the scene query filter data used by the specified suspension line
*/
const PxFilterData& getSceneQueryFilterData(const PxU32 suspId) const;
/**
\brief Return the number of unique anti-roll bars that have been added with addAntiRollBarData
@see PxVehicleWheelsSimData::addAntiRollBarData
*/
PxU32 getNbAntiRollBars() const
{
return mNbActiveAntiRollBars;
}
/**
\brief Return a specific anti-roll bar.
\param antiRollId is the unique id of the anti-roll bar
\note The return value of addAntiRollBarData is a unique id for that specific anti-roll bar
and can be used as input parameter for getAntiRollBarData in order to query the same anti-roll bar.
Alternatively, it is possible to iterate over all anti-roll bars by choosing antiRollId
in range (0, getNbAntiRollBars()).
*/
const PxVehicleAntiRollBarData& getAntiRollBarData(const PxU32 antiRollId) const;
/**
\brief Return the data that describes the filtering of the tire load to produce smoother handling at large time-steps.
*/
PX_FORCE_INLINE const PxVehicleTireLoadFilterData& getTireLoadFilterData() const
{
return mNormalisedLoadFilter;
}
/**
\brief Set the suspension data of the idth wheel
\param[in] id is the wheel index.
\param[in] susp is the suspension data to be applied.
*/
void setSuspensionData(const PxU32 id, const PxVehicleSuspensionData& susp);
/**
\brief Set the wheel data of the idth wheel
\param[in] id is the wheel index.
\param[in] wheel is the wheel data to be applied.
*/
void setWheelData(const PxU32 id, const PxVehicleWheelData& wheel);
/**
\brief Set the tire data of the idth wheel
\param[in] id is the wheel index.
\param[in] tire is the tire data to be applied.
*/
void setTireData(const PxU32 id, const PxVehicleTireData& tire);
/**
\brief Set the direction of travel of the suspension of the idth wheel
\param[in] id is the wheel index
\param[in] dir is the suspension travel direction to be applied.
*/
void setSuspTravelDirection(const PxU32 id, const PxVec3& dir);
/**
\brief Set the application point of the suspension force of the suspension of the idth wheel.
\param[in] id is the wheel index
\param[in] offset is the offset from the rigid body center of mass to the application point of the suspension force.
\note Specified relative to the centre of mass of the rigid body
*/
void setSuspForceAppPointOffset(const PxU32 id, const PxVec3& offset);
/**
\brief Set the application point of the tire force of the tire of the idth wheel.
\param[in] id is the wheel index
\param[in] offset is the offset from the rigid body center of mass to the application point of the tire force.
\note Specified relative to the centre of mass of the rigid body
*/
void setTireForceAppPointOffset(const PxU32 id, const PxVec3& offset);
/**
\brief Set the offset from the rigid body centre of mass to the centre of the idth wheel.
\param[in] id is the wheel index
\param[in] offset is the offset from the rigid body center of mass to the center of the wheel at rest.
\note Specified relative to the centre of mass of the rigid body
*/
void setWheelCentreOffset(const PxU32 id, const PxVec3& offset);
/**
\brief Set mapping between wheel id and position of corresponding wheel shape in the list of actor shapes.
\note This mapping is used to pose the correct wheel shapes with the latest wheel rotation angle, steer angle, and suspension travel
while allowing arbitrary ordering of the wheel shapes in the actor's list of shapes.
\note Use setWheelShapeMapping(i,-1) to register that there is no wheel shape corresponding to the ith wheel
\note Set setWheelShapeMapping(i,k) to register that the ith wheel corresponds to the kth shape in the actor's list of shapes.
\note The default values correspond to setWheelShapeMapping(i,i) for all wheels.
\note Calling this function will also pose the relevant PxShape at the rest position of the wheel.
\param wheelId is the wheel index
\param shapeId is the shape index.
@see PxVehicleUpdates, PxVehicleDrive4W::setup, PxVehicleDriveTank::setup, PxVehicleNoDrive::setup, setSceneQueryFilterData, PxRigidActor::getShapes
*/
void setWheelShapeMapping(const PxU32 wheelId, const PxI32 shapeId);
/**
\brief Set the scene query filter data that will be used for raycasts along the travel
direction of the specified suspension. The default value is PxFilterData(0,0,0,0)
\param suspId is the wheel index
\param sqFilterData is the raycast filter data for the suspension raycast.
@see setWheelShapeMapping
*/
void setSceneQueryFilterData(const PxU32 suspId, const PxFilterData& sqFilterData);
/**
\brief Set the data that describes the filtering of the tire load to produce smoother handling at large timesteps.
\param tireLoadFilter is the smoothing function data.
*/
void setTireLoadFilterData(const PxVehicleTireLoadFilterData& tireLoadFilter);
/**
\brief Set the anti-roll suspension for a pair of wheels.
\param antiRoll is the anti-roll suspension.
\note If an anti-roll bar has already been set for the same logical wheel pair
(independent of wheel index order specified by PxVehicleAntiRollBar.mWheel0 and PxVehicleAntiRollBar.mWheel0)
then the existing anti-roll bar is updated with a new stiffness parameter antiRoll.mStiffness.
\note If the wheel pair specified by antiRoll does not yet have an anti-roll bar then antiRoll is added to
a list of anti-roll bars for the vehicle.
\return If antiRoll represents a new wheel pair then a unique id is assigned to the anti-roll bar and returned.
If antiRoll represents an existing wheel pair then the unique id of the existing anti-roll bar is returned.
The return value is always in range (0, getNbAntiRollBars()).
\note The return value can be used to query the anti-roll bar with getAntiRollBarData(id).
\note The number of possible anti-roll bars is limited to half the wheel count.
\note An existing anti-roll bar can be disabled by calling antiRoll.mStiffness to zero.
@see PxVehicleWheelsSimData::getAntiRollBarData, PxVehicleAntiRollBarData
*/
PxU32 addAntiRollBarData(const PxVehicleAntiRollBarData& antiRoll);
/**
\brief Disable a wheel so that zero suspension forces and zero tire forces are applied to the rigid body from this wheel.
\note If the vehicle has a differential (PxVehicleNW/PxVehicle4W) then the differential (PxVehicleDifferentialNWData/PxVehicleDifferential4WData)
needs to be configured so that no drive torque is delivered to the disabled wheel.
\note If the vehicle is of type PxVehicleNoDrive then zero drive torque must be applied to the disabled wheel.
\note For tanks (PxVehicleDriveTank) any drive torque that could be delivered to the wheel through the tank differential will be
re-directed to the remaining enabled wheels.
@see enableWheel
@see PxVehicleDifferentialNWData::setDrivenWheel
@see PxVehicleDifferential4WData::mFrontLeftRightSplit, PxVehicleDifferential4WData::mRearLeftRightSplit, PxVehicleDifferential4WData::mType
@see PxVehicleNoDrive::setDriveTorque
@see PxVehicle4WEnable3WTadpoleMode, PxVehicle4WEnable3WDeltaMode
\note If a PxShape is associated with the disabled wheel then the association must be broken by calling setWheelShapeMapping(wheelId, -1).
@see setWheelShapeMapping
\note A wheel that is disabled must also simultaneously be given zero wheel rotation speed.
@see PxVehicleWheelsDynData::setWheelRotationSpeed
\note Care must be taken with the sprung mass supported by the remaining enabled wheels. Depending on the desired effect, the mass of the rigid body
might need to be distributed among the remaining enabled wheels and suspensions.
\param[in] wheel is the wheel index.
*/
void disableWheel(const PxU32 wheel);
/**
\brief Enable a wheel so that suspension forces and tire forces are applied to the rigid body.
All wheels are enabled by default and remain enabled until they are disabled.
\param[in] wheel is the wheel index.
@see disableWheel
*/
void enableWheel(const PxU32 wheel);
/**
\brief Test if a wheel has been disabled.
\param[in] wheel is the wheel index.
*/
bool getIsWheelDisabled(const PxU32 wheel) const;
/**
\brief Set the number of vehicle sub-steps that will be performed when the vehicle's longitudinal
speed is below and above a threshold longitudinal speed.
\note More sub-steps provides better stability but with greater computational cost.
\note Typically, vehicles require more sub-steps at very low forward speeds.
\note The threshold longitudinal speed has a default value that is the equivalent of 5 metres per second after accounting for
the length scale set in PxTolerancesScale.
\note The sub-step count below the threshold longitudinal speed has a default of 3.
\note The sub-step count above the threshold longitudinal speed has a default of 1.
\note Each sub-step has time advancement equal to the time-step passed to PxVehicleUpdates divided by the number of required sub-steps.
\note The contact planes of the most recent suspension line raycast are reused across all sub-steps.
\note Each sub-step computes tire and suspension forces and then advances a velocity, angular velocity and transform.
\note At the end of all sub-steps the vehicle actor is given the velocity and angular velocity that would move the actor from its start transform prior
to the first sub-step to the transform computed at the end of the last substep, assuming it doesn't collide with anything along the way in the next PhysX SDK update.
\note The global pose of the actor is left unchanged throughout the sub-steps.
\param[in] thresholdLongitudinalSpeed is a threshold speed that is used to categorize vehicle speed as low speed or high speed.
\param[in] lowForwardSpeedSubStepCount is the number of sub-steps performed in PxVehicleUpates for vehicles that have longitudinal speed lower than thresholdLongitudinalSpeed.
\param[in] highForwardSpeedSubStepCount is the number of sub-steps performed in PxVehicleUpdates for vehicles that have longitudinal speed graeter than thresholdLongitudinalSpeed.
*/
void setSubStepCount(const PxReal thresholdLongitudinalSpeed, const PxU32 lowForwardSpeedSubStepCount, const PxU32 highForwardSpeedSubStepCount);
/**
\brief Set the minimum denominator used in the longitudinal slip calculation.
\note The longitudinal slip has a theoretical value of (w*r - vz)/|vz|, where w is the angular speed of the wheel; r is the radius of the wheel;
and vz is the component of rigid body velocity (computed at the wheel base) that lies along the longitudinal wheel direction. The term |vz|
normalizes the slip, while preserving the sign of the longitudinal tire slip. The difficulty here is that when |vz| approaches zero the
longitudinal slip approaches infinity. A solution to this problem is to replace the denominator (|vz|) with a value that never falls below a chosen threshold.
The longitudinal slip is then calculated with (w*r - vz)/PxMax(|vz|, minLongSlipDenominator).
\note The default value is the equivalent of 4 metres per second after accounting for the length scale set in PxTolerancesScale.
\note Adjust this value upwards if a vehicle has difficulty coming to rest.
\note Decreasing the timestep (or increasing the number of sub-steps at low longitudinal speed with setSubStepCount) should allow stable stable
behavior with smaller values of minLongSlipDenominator.
*/
void setMinLongSlipDenominator(const PxReal minLongSlipDenominator);
/**
\brief Set the vehicle wheel simulation flags.
\param[in] flags The flags to set (see #PxVehicleWheelsSimFlags).
<b>Default:</b> no flag set
@see PxVehicleWheelsSimFlag
*/
void setFlags(PxVehicleWheelsSimFlags flags);
/**
\brief Return the vehicle wheel simulation flags.
\return The values of the flags.
@see PxVehicleWheelsSimFlag
*/
PxVehicleWheelsSimFlags getFlags() const;
private:
/**
\brief Graph to filter normalised load
@see setTireLoadFilterData, getTireLoadFilterData
*/
PxVehicleTireLoadFilterData mNormalisedLoadFilter;
/**
\brief Wheels data organised in blocks of 4 wheels.
*/
PxVehicleWheels4SimData* mWheels4SimData;
/**
\brief Number of blocks of 4 wheels.
*/
PxU32 mNbWheels4;
/**
\brief Number of actual wheels (<=(mNbWheels4*4))
*/
PxU32 mNbActiveWheels;
/**
\brief Anti-roll bars
*/
PxVehicleAntiRollBarData* mAntiRollBars;
/**
\brief 2 anti-rollbars allocated for each block of 4 wheels.
*/
PxU32 mNbAntiRollBars4;
/**
\brief Number of active anti-roll bars.
*/
PxU32 mNbActiveAntiRollBars;
/**
\brief Which of the mNbActiveWheels are active or disabled?
The default is that all mNbActiveWheels wheels are active.
*/
PxU32 mActiveWheelsBitmapBuffer[((PX_MAX_NB_WHEELS + 31) & ~31) >> 5];
/**
\brief Threshold longitudinal speed used to decide whether to use
mLowForwardSpeedSubStepCount or mHighForwardSpeedSubStepCount as the
number of sub-steps that will be peformed.
*/
PxF32 mThresholdLongitudinalSpeed;
/**
\brief Number of sub-steps that will be performed if the longitudinal speed
of the vehicle is smaller than mThresholdLongitudinalSpeed.
*/
PxU32 mLowForwardSpeedSubStepCount;
/**
\brief Number of sub-steps that will be performed if the longitudinal speed
of the vehicle is greater than or equal to mThresholdLongitudinalSpeed.
*/
PxU32 mHighForwardSpeedSubStepCount;
/**
\brief Minimum long slip denominator
*/
PxF32 mMinLongSlipDenominator;
/**
\brief The vehicle wheel simulation flags.
@see PxVehicleWheelsSimFlags
*/
PxU32 mFlags;
#if PX_P64_FAMILY
PxU32 mPad[1];
#endif
/**
\brief Test if wheel simulation data has been setup with legal values.
*/
bool isValid() const;
/**
\brief see PxVehicleWheels::allocate
*/
static PxU32 computeByteSize(const PxU32 numWheels);
static PxU8* patchUpPointers(const PxU32 numWheels, PxVehicleWheelsSimData* simData, PxU8* ptrIn);
PxVehicleWheelsSimData(const PxU32 numWheels);
//serialization
public:
PxVehicleWheelsSimData(const PxEMPTY) : mNormalisedLoadFilter(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
PxU32 getNbWheels4() const { return mNbWheels4; }
PxU32 getNbSuspensionData() const { return mNbActiveWheels; }
PxU32 getNbWheelData() const { return mNbActiveWheels; }
PxU32 getNbSuspTravelDirection() const { return mNbActiveWheels; }
PxU32 getNbTireData() const { return mNbActiveWheels; }
PxU32 getNbSuspForceAppPointOffset() const { return mNbActiveWheels; }
PxU32 getNbTireForceAppPointOffset() const { return mNbActiveWheels; }
PxU32 getNbWheelCentreOffset() const { return mNbActiveWheels; }
PxU32 getNbWheelShapeMapping() const { return mNbActiveWheels; }
PxU32 getNbSceneQueryFilterData() const { return mNbActiveWheels; }
PxF32 getMinLongSlipDenominator() const {return mMinLongSlipDenominator;}
void setThresholdLongSpeed(const PxF32 f) {mThresholdLongitudinalSpeed = f;}
PxF32 getThresholdLongSpeed() const {return mThresholdLongitudinalSpeed;}
void setLowForwardSpeedSubStepCount(const PxU32 f) {mLowForwardSpeedSubStepCount = f;}
PxU32 getLowForwardSpeedSubStepCount() const {return mLowForwardSpeedSubStepCount;}
void setHighForwardSpeedSubStepCount(const PxU32 f) {mHighForwardSpeedSubStepCount = f;}
PxU32 getHighForwardSpeedSubStepCount() const {return mHighForwardSpeedSubStepCount;}
void setWheelEnabledState(const PxU32 wheel, const bool state) {if(state) {enableWheel(wheel);} else {disableWheel(wheel);}}
bool getWheelEnabledState(const PxU32 wheel) const {return !getIsWheelDisabled(wheel);}
PxU32 getNbWheelEnabledState() const {return mNbActiveWheels;}
PxU32 getNbAntiRollBars4() const { return mNbAntiRollBars4; }
PxU32 getNbAntiRollBarData() const {return mNbActiveAntiRollBars;}
void setAntiRollBarData(const PxU32 id, const PxVehicleAntiRollBarData& antiRoll);
PxVehicleWheelsSimData(){}
~PxVehicleWheelsSimData(){}
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleWheelsSimData) & 15));
/**
\brief Description of the per wheel intersection method to be used by PxVehicleWheelsDynData::setTireContacts()
*/
struct PX_DEPRECATED PxTireContactIntersectionMethod
{
enum Enum
{
eRAY = 0,
eCYLINDER
};
};
/**
\brief Data structure with instanced dynamics data for wheels
*/
class PX_DEPRECATED PxVehicleWheelsDynData
{
public:
friend class PxVehicleWheels;
friend class PxVehicleDrive4W;
friend class PxVehicleDriveTank;
friend class PxVehicleUpdate;
PxVehicleWheelsDynData(){}
~PxVehicleWheelsDynData(){}
/**
\brief Set all wheels to their rest state.
@see setup
*/
void setToRestState();
/**
\brief Set the tire force shader function
\param[in] tireForceShaderFn is the shader function that will be used to compute tire forces.
*/
void setTireForceShaderFunction(PxVehicleComputeTireForce tireForceShaderFn);
/**
\brief Set the tire force shader data for a specific tire
\param[in] tireId is the wheel index
\param[in] tireForceShaderData is the data describing the tire.
*/
void setTireForceShaderData(const PxU32 tireId, const void* tireForceShaderData);
/**
\brief Get the tire force shader data for a specific tire
*/
const void* getTireForceShaderData(const PxU32 tireId) const;
/**
\brief Set the wheel rotation speed (radians per second) about the rolling axis for the specified wheel.
\param[in] wheelIdx is the wheel index
\param[in] speed is the rotation speed to be applied to the wheel.
*/
void setWheelRotationSpeed(const PxU32 wheelIdx, const PxReal speed);
/**
\brief Return the rotation speed about the rolling axis of a specified wheel .
*/
PxReal getWheelRotationSpeed(const PxU32 wheelIdx) const;
/**
\brief Set the wheel rotation angle (radians) about the rolling axis of the specified wheel.
\param[in] wheelIdx is the wheel index
\param[in] angle is the rotation angle to be applied to the wheel.
*/
void setWheelRotationAngle(const PxU32 wheelIdx, const PxReal angle);
/**
\brief Return the rotation angle about the rolling axis for the specified wheel.
*/
PxReal getWheelRotationAngle(const PxU32 wheelIdx) const;
/**
\brief Set the user data pointer for the specified wheel
It has a default value of NULL.
\param[in] tireIdx is the wheel index
\param[in] userData is the data to be associated with the wheel.
*/
void setUserData(const PxU32 tireIdx, void* userData);
/**
\brief Get the user data pointer that was set for the specified wheel
*/
void* getUserData(const PxU32 tireIdx) const;
/**
\brief Copy the dynamics data of a single wheel unit (wheel, suspension, tire) from srcWheel of src to trgWheel.
\param[in] src is the data to be copied.
\param[in] srcWheel is the wheel whose data will be copied from src.
\param[in] trgWheel is the wheel that will be assigned the copied data.
*/
void copy(const PxVehicleWheelsDynData& src, const PxU32 srcWheel, const PxU32 trgWheel);
/**
\brief Directly set tire contact plane and friction for all tires on the vehicle as an alternative to using PxVehicleSuspensionSweeps() or PxVehicleSuspensionRaycasts().
\param[in] nbHits is an array describing whether each tire has a contact plane or not. Each element of the array is either 0 (no contact) or 1 (contact).
\param[in] contactPlanes is an array of contact planes describing the contact plane per tire.
\param[in] contactFrictions is the friction value of each tire contact with the drivable surface.
\param[in] intersectionMethods describes how each tire will individually interact with its contact plane in order to compute the spring
compression that places the tire on the contact plane. A value of eCYLINDER will compute the spring compression by intersecting the wheel's
cylindrical shape with the contact plane. A value of eRAY will compute the spring compression by casting a ray through the wheel center
and along the suspension direction until it hits the contact plane.
\param[in] nbWheels is the length of the arrays nbContacts, contactPlanes, contactFrictions and intersectionMethods.
\note Each contact plane (n, d) obeys the rule that all points P on the plane satisfy n.dot(P) + d = 0.0.
\note The contact planes specified by setTireContacts() will persist as driving surfaces until either the next call to setTireContacts() or the next call to
\note The friction values are scaled by PxVehicleTireData::mFrictionVsSlipGraph before being applied to the tire.
\note The vehicle model assumes that the tire contacts are with static objects.
PxVehicleSuspensionSweeps() or PxVehicleSuspensionRaycasts().
*/
void setTireContacts(const PxU32* nbHits, const PxPlane* contactPlanes, const PxReal* contactFrictions, const PxTireContactIntersectionMethod::Enum* intersectionMethods, const PxU32 nbWheels);
private:
/**
\brief Dynamics data arranged in blocks of 4 wheels.
*/
PxVehicleWheels4DynData* mWheels4DynData;
/**
\brief Test if wheel dynamics data have legal values.
*/
bool isValid() const;
/**
\brief Shader data and function for tire force calculations.
*/
PxVehicleTireForceCalculator* mTireForceCalculators;
/**
\brief A userData pointer can be stored for each wheel.
@see setUserData, getUserData
*/
void** mUserDatas;
/**
\brief Number of blocks of 4 wheels.
*/
PxU32 mNbWheels4;
/**
\brief Number of wheels (mNbActiveWheels <= (mNbWheels4*4))
*/
PxU32 mNbActiveWheels;
PxU32 mPad[3];
/**
\brief see PxVehicleWheels::allocate
*/
static PxU32 computeByteSize(const PxU32 numWheels);
static PxU8* patchUpPointers(const PxU32 numWheels, PxVehicleWheelsDynData* dynData, PxU8* ptr);
PxVehicleWheelsDynData(const PxU32 numWheels);
//serialization
public:
static void getBinaryMetaData(PxOutputStream& stream);
PxU32 getNbWheelRotationSpeed() const { return mNbActiveWheels; }
PxU32 getNbWheelRotationAngle() const { return mNbActiveWheels; }
PxVehicleWheels4DynData* getWheel4DynData() const { return mWheels4DynData; }
//~serialization
/**
\brief Retrieve the number of PxConstraint objects associated with the vehicle.
You can use #getConstraints() to retrieve the constraint pointers.
\return Number of constraints associated with this vehicle.
@see PxConstraint getConstraints()
*/
PxU32 getNbConstraints() const { return mNbWheels4; }
/**
\brief Retrieve all the PxConstraint objects associated with the vehicle.
There is one PxConstraint per block of 4 wheels. The count can be extracted through #getNbConstraints()
\param[out] userBuffer The buffer to store the constraint pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first constraint pointer to be retrieved
\return Number of constraint pointers written to the buffer.
@see PxConstraint getNbConstraints()
*/
PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const;
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleWheelsDynData) & 15));
/**
\brief Data structure with instanced dynamics data and configuration data of a vehicle with just wheels
@see PxVehicleDrive, PxVehicleDrive4W, PxVehicleDriveTank
*/
class PX_DEPRECATED PxVehicleWheels : public PxBase
{
public:
friend class PxVehicleUpdate;
friend class PxVehicleConstraintShader;
/**
\brief Return the type of vehicle
@see PxVehicleTypes
*/
PX_FORCE_INLINE PxU32 getVehicleType() const {return mType;}
/**
\brief Get non-const ptr to PxRigidDynamic instance that is the vehicle's physx representation
*/
PX_FORCE_INLINE PxRigidDynamic* getRigidDynamicActor() {return mActor;}
/**
\brief Get const ptr to PxRigidDynamic instance that is the vehicle's physx representation
*/
PX_FORCE_INLINE const PxRigidDynamic* getRigidDynamicActor() const {return mActor;}
/**
\brief Compute the rigid body velocity component along the forward vector of the rigid body transform.
\param[in] forwardAxis The axis denoting the local space forward direction of the vehicle.
@see PxVehicleSetBasisVectors
*/
PxReal computeForwardSpeed(const PxVec3& forwardAxis = PxVehicleGetDefaultContext().forwardAxis) const;
/**
\brief Compute the rigid body velocity component along the right vector of the rigid body transform.
\param[in] sideAxis The axis denoting the local space side direction of the vehicle.
@see PxVehicleSetBasisVectors
*/
PxReal computeSidewaysSpeed(const PxVec3& sideAxis = PxVehicleGetDefaultContext().sideAxis) const;
/**
\brief Data describing the setup of all the wheels/suspensions/tires.
*/
PxVehicleWheelsSimData mWheelsSimData;
/**
\brief Data describing the dynamic state of all wheels/suspension/tires.
*/
PxVehicleWheelsDynData mWheelsDynData;
protected:
/**
\brief Set all wheels to their rest state
*/
void setToRestState();
/**
\brief Test that all configuration and instanced dynamics data is valid.
*/
bool isValid() const;
/**
@see PxVehicleDrive4W::allocate, PxVehicleDriveTank::allocate
*/
static PxU32 computeByteSize(const PxU32 nbWheels);
static PxU8* patchupPointers(const PxU32 nbWheels, PxVehicleWheels* vehWheels, PxU8* ptr);
virtual void init(const PxU32 numWheels);
/**
\brief Deallocate a PxVehicleWheels instance.
@see PxVehicleDrive4W::free, PxVehicleDriveTank::free
*/
void free();
/*
\brief Deferred deletion.
*/
void onConstraintRelease();
/**
@see PxVehicleDrive4W::setup, PxVehicleDriveTank::setup
*/
void setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData,
const PxU32 nbDrivenWheels, const PxU32 nbNonDrivenWheels);
/**
\brief The rigid body actor that represents the vehicle in the PhysX SDK.
*/
PxRigidDynamic* mActor;
private:
/**
\brief Count the number of constraint connectors that have hit their callback when deleting a vehicle.
Can only delete the vehicle's memory when all constraint connectors have hit their callback.
*/
PxU32 mNbNonDrivenWheels;
PxU8 mOnConstraintReleaseCounter;
protected:
/**
\brief Vehicle type (eVehicleDriveTypes)
*/
PxU8 mType;
#if PX_P64_FAMILY
PxU8 mPad0[14];
#else
PxU8 mPad0[8];
#endif
//serialization
public:
virtual void requiresObjects(PxProcessPxBaseCallback& c);
virtual const char* getConcreteTypeName() const { return "PxVehicleWheels"; }
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxVehicleWheels", PxBase); }
virtual void preExportDataReset() {}
virtual void exportExtraData(PxSerializationContext&);
void importExtraData(PxDeserializationContext&);
void resolveReferences(PxDeserializationContext&);
static void getBinaryMetaData(PxOutputStream& stream);
PX_FORCE_INLINE PxU32 getNbNonDrivenWheels() const { return mNbNonDrivenWheels; }
PxVehicleWheels(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PxVehicleWheels(PxBaseFlags baseFlags) : PxBase(baseFlags), mWheelsSimData(PxEmpty) {}
virtual ~PxVehicleWheels() {}
virtual void release() { free(); }
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleWheels) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 36,587 | C | 37.312042 | 193 | 0.776095 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleDrive4W.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_4WDRIVE_H
#define PX_VEHICLE_4WDRIVE_H
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleComponents.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxFilterData;
class PxGeometry;
class PxPhysics;
class PxVehicleDrivableSurfaceToTireFrictionPairs;
class PxShape;
class PxMaterial;
class PxRigidDynamic;
/**
\brief Data structure describing the drive model components of a vehicle with up to 4 driven wheels and up to 16 un-driven wheels.
The drive model incorporates engine, clutch, gears, autobox, differential, and Ackermann steer correction.
@see PxVehicleDriveSimData
*/
class PX_DEPRECATED PxVehicleDriveSimData4W : public PxVehicleDriveSimData
{
public:
friend class PxVehicleDrive4W;
PxVehicleDriveSimData4W()
: PxVehicleDriveSimData()
{
}
/**
\brief Return the data describing the differential.
@see PxVehicleDifferential4WData
*/
PX_FORCE_INLINE const PxVehicleDifferential4WData& getDiffData() const
{
return mDiff;
}
/**
\brief Return the data describing the Ackermann steer-correction.
@see PxVehicleAckermannGeometryData
*/
PX_FORCE_INLINE const PxVehicleAckermannGeometryData& getAckermannGeometryData() const
{
return mAckermannGeometry;
}
/**
\brief Set the data describing the differential.
@see PxVehicleDifferential4WData
*/
void setDiffData(const PxVehicleDifferential4WData& diff);
/**
\brief Set the data describing the Ackermann steer-correction.
@see PxVehicleAckermannGeometryData
*/
void setAckermannGeometryData(const PxVehicleAckermannGeometryData& ackermannData);
private:
/**
\brief Differential simulation data
@see setDiffData, getDiffData
*/
PxVehicleDifferential4WData mDiff;
/**
\brief Data for ackermann steer angle computation.
@see setAckermannGeometryData, getAckermannGeometryData
*/
PxVehicleAckermannGeometryData mAckermannGeometry;
/**
\brief Test if the 4W-drive simulation data has been setup with legal data.
\note Call only after setting all components.
@see setEnginedata, setClutchData, setGearsData, setAutoboxData, setDiffData, setAckermannGeometryData
*/
bool isValid() const;
//serialization
public:
PxVehicleDriveSimData4W(const PxEMPTY) : PxVehicleDriveSimData(PxEmpty), mDiff(PxEmpty), mAckermannGeometry(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveSimData4W) & 15));
/**
\brief The ordering of the driven and steered wheels of a PxVehicleDrive4W.
@see PxVehicleWheelsSimData, PxVehicleWheelsDynData
*/
struct PX_DEPRECATED PxVehicleDrive4WWheelOrder
{
enum Enum
{
eFRONT_LEFT=0,
eFRONT_RIGHT,
eREAR_LEFT,
eREAR_RIGHT
};
};
/**
\brief The control inputs for a PxVehicleDrive4W.
@see PxVehicleDriveDynData::setAnalogInput, PxVehicleDriveDynData::getAnalogInput
*/
struct PX_DEPRECATED PxVehicleDrive4WControl
{
enum Enum
{
eANALOG_INPUT_ACCEL=0,
eANALOG_INPUT_BRAKE,
eANALOG_INPUT_HANDBRAKE,
eANALOG_INPUT_STEER_LEFT,
eANALOG_INPUT_STEER_RIGHT,
eMAX_NB_DRIVE4W_ANALOG_INPUTS
};
};
/**
\brief Data structure with instanced dynamics data and configuration data of a vehicle with up to 4 driven wheels and up to 16 non-driven wheels.
*/
class PX_DEPRECATED PxVehicleDrive4W : public PxVehicleDrive
{
public:
friend class PxVehicleUpdate;
/**
\brief Allocate a PxVehicleDrive4W instance for a 4WDrive vehicle with nbWheels (= 4 + number of un-driven wheels)
\param[in] nbWheels is the number of vehicle wheels (= 4 + number of un-driven wheels)
\return The instantiated vehicle.
@see free, setup
*/
static PxVehicleDrive4W* allocate(const PxU32 nbWheels);
/**
\brief Deallocate a PxVehicleDrive4W instance.
@see allocate
*/
void free();
/**
\brief Set up a vehicle using simulation data for the wheels and drive model.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
\param[in] driveData describes the properties of the vehicle's drive model (gears/engine/clutch/differential/autobox). The vehicle instance takes a copy of this data.
\param[in] nbNonDrivenWheels is the number of wheels on the vehicle that cannot be connected to the differential (= numWheels - 4).
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
\note wheelsData must contain data for at least 4 wheels. Unwanted wheels can be disabled with PxVehicleWheelsSimData::disableWheel after calling setup.
@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
*/
void setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData,
const PxU32 nbNonDrivenWheels);
/**
\brief Allocate and set up a vehicle using simulation data for the wheels and drive model.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
\param[in] driveData describes the properties of the vehicle's drive model (gears/engine/clutch/differential/autobox). The vehicle instance takes a copy of this data.
\param[in] nbNonDrivenWheels is the number of wheels on the vehicle that cannot be connected to the differential (= numWheels - 4).
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
\note wheelsData must contain data for at least 4 wheels. Unwanted wheels can be disabled with PxVehicleWheelsSimData::disableWheel after calling setup.
\return The instantiated vehicle.
@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
*/
static PxVehicleDrive4W* create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData,
const PxU32 nbNonDrivenWheels);
/**
\brief Set a vehicle to its rest state. Aside from the rigid body transform, this will set the vehicle and rigid body
to the state they were in immediately after setup or create.
\note Calling setToRestState invalidates the cached raycast hit planes under each wheel meaning that suspension line
raycasts need to be performed at least once with PxVehicleSuspensionRaycasts before calling PxVehicleUpdates.
@see setup, create, PxVehicleSuspensionRaycasts, PxVehicleUpdates
*/
void setToRestState();
/**
\brief Simulation data that describes the configuration of the vehicle's drive model.
@see setup, create
*/
PxVehicleDriveSimData4W mDriveSimData;
private:
/**
\brief Test if the instanced dynamics and configuration data has legal values.
*/
bool isValid() const;
//serialization
protected:
PxVehicleDrive4W();
~PxVehicleDrive4W(){}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxVehicleDrive4W", PxVehicleDrive); }
public:
static PxVehicleDrive4W* createObject(PxU8*& address, PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
PxVehicleDrive4W(PxBaseFlags baseFlags) : PxVehicleDrive(baseFlags), mDriveSimData(PxEmpty) {}
virtual const char* getConcreteTypeName() const { return "PxVehicleDrive4W"; }
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDrive4W) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 9,797 | C | 36.396946 | 185 | 0.780443 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleUpdate.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_UPDATE_H
#define PX_VEHICLE_UPDATE_H
#include "vehicle/PxVehicleSDK.h"
#include "vehicle/PxVehicleTireFriction.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxMemory.h"
#include "foundation/PxTransform.h"
#include "PxQueryFiltering.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxContactModifyPair;
class PxVehicleWheels;
class PxVehicleDrivableSurfaceToTireFrictionPairs;
class PxVehicleTelemetryData;
class PxBatchQueryExt;
/**
\brief Structure containing data describing the non-persistent state of each suspension/wheel/tire unit.
This structure is filled out in PxVehicleUpdates and PxVehicleUpdateSingleVehicleAndStoreTelemetryData
@see PxVehicleUpdates, PxVehicleUpdateSingleVehicleAndStoreTelemetryData
*/
struct PX_DEPRECATED PxWheelQueryResult
{
PxWheelQueryResult()
{
PxMemZero(this, sizeof(PxWheelQueryResult));
isInAir=true;
tireSurfaceType = PxU32(PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN);
localPose = PxTransform(PxIdentity);
}
/**
\brief Start point of suspension line raycast/sweep used in the raycast/sweep completed immediately before PxVehicleUpdates.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then (0,0,0) is stored.
@see PxVehicleSuspensionRaycasts, PxVehicleSuspensionRaycasts
*/
PxVec3 suspLineStart;
/**
\brief Directions of suspension line raycast/sweep used in the raycast/sweep completed immediately before PxVehicleUpdates.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then (0,0,0) is stored.
@see PxVehicleSuspensionRaycasts, PxVehicleSuspensionRaycasts
*/
PxVec3 suspLineDir;
/**
\brief Lengths of suspension line raycast/sweep used in raycast/sweep completed immediately before PxVehicleUpdates.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then 0 is stored.
@see PxVehicleSuspensionRaycasts, PxVehicleSuspensionRaycasts
*/
PxReal suspLineLength;
/**
\brief If suspension travel limits forbid the wheel from touching the drivable surface then isInAir is true.
\note If the wheel can be placed on the contact plane of the most recent suspension line raycast/sweep then isInAir is false.
\note If #PxVehicleWheelsSimFlag::eLIMIT_SUSPENSION_EXPANSION_VELOCITY is set, then isInAir will also be true if the suspension
force is not large enough to expand to the target length in the given simulation time step.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then isInAir
is computed using the contact plane that was hit by the most recent suspension line raycast/sweep.
*/
bool isInAir;
/**
\brief PxActor instance of the driving surface under the corresponding vehicle wheel.
\note If suspension travel limits forbid the wheel from touching the drivable surface then tireContactActor is NULL.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then NULL is stored.
*/
PxActor* tireContactActor;
/**
\brief PxShape instance of the driving surface under the corresponding vehicle wheel.
\note If suspension travel limits forbid the wheel from touching the drivable surface then tireContactShape is NULL.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then NULL is stored.
*/
PxShape* tireContactShape;
/**
\brief PxMaterial instance of the driving surface under the corresponding vehicle wheel.
\note If suspension travel limits forbid the wheel from touching the drivable surface then tireSurfaceMaterial is NULL.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then NULL is stored.
*/
const PxMaterial* tireSurfaceMaterial;
/**
\brief Surface type integer that corresponds to the mapping between tireSurfaceMaterial and integer as
described in PxVehicleDrivableSurfaceToTireFrictionPairs.
\note If suspension travel limits forbid the wheel from touching the drivable surface then tireSurfaceType is
PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN.
\note If no raycast/sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then
PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN is stored.
@see PxVehicleDrivableSurfaceToTireFrictionPairs
*/
PxU32 tireSurfaceType;
/**
\brief Point on the drivable surface hit by the most recent suspension raycast or sweep.
\note If suspension travel limits forbid the wheel from touching the drivable surface then the contact point is (0,0,0).
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then (0,0,0) is stored.
*/
PxVec3 tireContactPoint;
/**
\brief Normal on the drivable surface at the hit point of the most recent suspension raycast or sweep.
\note If suspension travel limits forbid the wheel from touching the drivable surface then the contact normal is (0,0,0).
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then (0,0,0) is stored.
*/
PxVec3 tireContactNormal;
/**
\brief Friction experienced by the tire for the combination of tire type and surface type after accounting
for the friction vs slip graph.
\note If suspension travel limits forbid the wheel from touching the drivable surface then the tire friction is 0.
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then the
stored tire friction is the value computed in PxVehicleUpdates that immediately followed the last raycast or sweep.
@see PxVehicleDrivableSurfaceToTireFrictionPairs, PxVehicleTireData
*/
PxReal tireFriction;
/**
\brief Compression of the suspension spring.
\note If suspension travel limits forbid the wheel from touching the drivable surface then the jounce is -PxVehicleSuspensionData.mMaxDroop
The jounce can never exceed PxVehicleSuspensionData.mMaxCompression. Positive values result when the suspension is compressed from
the rest position, while negative values mean the suspension is elongated from the rest position.
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then the
suspension compression is computed using the contact plane that was hit by the most recent suspension line raycast or sweep.
*/
PxReal suspJounce;
/**
\brief Magnitude of force applied by the suspension spring along the direction of suspension travel.
\note If suspension travel limits forbid the wheel from touching the drivable surface then the force is 0
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then the
suspension spring force is computed using the contact plane that was hit by the most recent suspension line raycast or sweep.
@see PxVehicleWheelsSimData::getSuspTravelDirection
*/
PxReal suspSpringForce;
/**
\brief Forward direction of the wheel/tire accounting for steer/toe/camber angle projected on to the contact plane of the drivable surface.
\note If suspension travel limits forbid the wheel from touching the drivable surface then tireLongitudinalDir is (0,0,0)
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then the
tire longitudinal direction is computed using the contact plane that was hit by the most recent suspension line raycast or sweep.
*/
PxVec3 tireLongitudinalDir;
/**
\brief Lateral direction of the wheel/tire accounting for steer/toe/camber angle projected on to the contact plan of the drivable surface.
\note If suspension travel limits forbid the wheel from touching the drivable surface then tireLateralDir is (0,0,0)
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then the
tire lateral direction is computed using the contact plane that was hit by the most recent suspension line raycast or sweep.
*/
PxVec3 tireLateralDir;
/**
\brief Longitudinal slip of the tire.
\note If suspension travel limits forbid the wheel from touching the drivable surface then longitudinalSlip is 0.0
\note The longitudinal slip is approximately (w*r - vz) / PxAbs(vz) where w is the angular speed of the wheel, r is the radius of the wheel, and
vz component of rigid body velocity computed at the wheel base along the longitudinal direction of the tire.
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then the
tire longitudinal slip is computed using the contact plane that was hit by the most recent suspension line raycast or sweep.
*/
PxReal longitudinalSlip;
/**
\brief Lateral slip of the tire.
\note If suspension travel limits forbid the wheel from touching the drivable surface then lateralSlip is 0.0
\note The lateral slip angle is approximately PxAtan(vx / PxAbs(vz)) where vx and vz are the components of rigid body velocity at the wheel base
along the wheel's lateral and longitudinal directions, respectively.
\note If no raycast or sweep for the corresponding suspension was performed immediately prior to PxVehicleUpdates then the
tire lateral slip is computed using the contact plane that was hit by the most recent suspension line raycast or sweep.
*/
PxReal lateralSlip;
/**
\brief Steer angle of the wheel about the "up" vector accounting for input steer and toe and, if applicable, Ackermann steer correction.
@see PxVehicleWheelData::mToeAngle
*/
PxReal steerAngle;
/**
\brief Local pose of the wheel.
*/
PxTransform localPose;
};
struct PX_DEPRECATED PxVehicleWheelQueryResult
{
/**
\brief Pointer to an PxWheelQueryResult buffer of length nbWheelQueryResults
The wheelQueryResults buffer must persist until the end of PxVehicleUpdates
A NULL pointer is permitted.
The wheelQueryResults buffer is left unmodified in PxVehicleUpdates for vehicles with sleeping rigid bodies
whose control inputs indicate they should remain inert.
@see PxVehicleUpdates
*/
PxWheelQueryResult* wheelQueryResults;
/**
\brief The length of the wheelQueryResults buffer. This value corresponds to the
number of wheels in the associated vehicle in PxVehicleUpdates.
*/
PxU32 nbWheelQueryResults;
};
/**
\brief Structure containing data that is computed for a wheel during concurrent calls to PxVehicleUpdates or
PxVehicleUpdateSingleVehicleAndStoreTelemetryData but which cannot be safely concurrently applied.
@see PxVehicleUpdates, PxVehicleUpdateSingleVehicleAndStoreTelemetryData, PxVehiclePostUpdates, PxVehicleConcurrentUpdate
*/
struct PX_DEPRECATED PxVehicleWheelConcurrentUpdateData
{
friend class PxVehicleUpdate;
PxVehicleWheelConcurrentUpdateData()
: localPose(PxTransform(PxIdentity)),
hitActor(NULL),
hitActorForce(PxVec3(0,0,0)),
hitActorForcePosition(PxVec3(0,0,0))
{
}
private:
PxTransform localPose;
PxRigidDynamic* hitActor;
PxVec3 hitActorForce;
PxVec3 hitActorForcePosition;
};
/**
\brief Structure containing data that is computed for a vehicle and its wheels during concurrent calls to PxVehicleUpdates or
PxVehicleUpdateSingleVehicleAndStoreTelemetryData but which cannot be safely concurrently applied.
@see PxVehicleUpdates, PxVehicleUpdateSingleVehicleAndStoreTelemetryData, PxVehiclePostUpdates, PxVehicleWheelConcurrentUpdateData
*/
struct PX_DEPRECATED PxVehicleConcurrentUpdateData
{
friend class PxVehicleUpdate;
PxVehicleConcurrentUpdateData()
: concurrentWheelUpdates(NULL),
nbConcurrentWheelUpdates(0),
linearMomentumChange(PxVec3(0,0,0)),
angularMomentumChange(PxVec3(0,0,0)),
staySleeping(false),
wakeup(false)
{
}
/**
\brief Pointer to an PxVehicleWheelConcurrentUpdate buffer of length nbConcurrentWheelUpdates
The concurrentWheelUpdates buffer must persist until the end of PxVehiclePostUpdates
A NULL pointer is not permitted.
@see PxVehicleUpdates, PxVehiclePostUpdates
*/
PxVehicleWheelConcurrentUpdateData* concurrentWheelUpdates;
/**
\brief The length of the concurrentWheelUpdates buffer. This value corresponds to the
number of wheels in the associated vehicle passed to PxVehicleUpdates.
*/
PxU32 nbConcurrentWheelUpdates;
private:
PxVec3 linearMomentumChange;
PxVec3 angularMomentumChange;
bool staySleeping;
bool wakeup;
};
/**
\brief Perform raycasts for all suspension lines for all vehicles.
\param[in] batchQuery is a PxBatchQueryExt instance used to specify shader data and functions for the raycast scene queries.
\param[in] nbVehicles is the number of vehicles in the vehicles array.
\param[in] vehicles is an array of all vehicles that are to have a raycast issued from each wheel.
\param[in] vehiclesToRaycast is an array of bools of length nbVehicles that is used to decide if raycasts will be performed for the corresponding vehicle
in the vehicles array. If vehiclesToRaycast[i] is true then suspension line raycasts will be performed for vehicles[i]. If vehiclesToRaycast[i] is
false then suspension line raycasts will not be performed for vehicles[i].
\param[in] queryFlags filter flags for the batched scene queries
\note If vehiclesToRaycast is NULL then raycasts are performed for all vehicles in the vehicles array.
\note If vehiclesToRaycast[i] is false then the vehicle stored in vehicles[i] will automatically use the raycast or sweep hit planes recorded by the most recent
suspension sweeps or raycasts for that vehicle. For vehicles far from the camera or not visible on the screen it can be
optimal to only perform suspension line raycasts every Nth update rather than every single update. The accuracy of the cached contact plane
naturally diminishes as N increase, meaning that wheels might start to hover or intersect the ground for large values of N or even with values close to 1 in
conjunction with large vehicle speeds and/or geometry that has low spatial coherence.
\note Calling setToRestState invalidates any cached hit planes. Prior to calling PxVehicleUpdates each vehicle needs to perform suspension line raycasts
or sweeps at least once after instantiation and at least once after calling setToRestState.
\note Each raycast casts along the suspension travel direction from the position of the top of the wheel at maximum suspension compression
to the position of the base of the wheel at maximum droop. Raycasts that start inside a PxShape are subsequently ignored by the
corresponding vehicle.
\note Only blocking hits are supported (PxQueryHitType::eBLOCK).
@see PxVehicleDrive4W::setToRestState, PxVehicleDriveNW::setToRestState, PxVehicleDriveTank::setToRestState, PxVehicleNoDrive::setToRestState
@see PxBatchQueryExt::raycast
*/
PX_DEPRECATED void PxVehicleSuspensionRaycasts( PxBatchQueryExt* batchQuery,
const PxU32 nbVehicles, PxVehicleWheels** vehicles,
const bool* vehiclesToRaycast = NULL,
const PxQueryFlags queryFlags = PxQueryFlag::eSTATIC | PxQueryFlag::eDYNAMIC | PxQueryFlag::ePREFILTER);
/**
\brief Perform sweeps for all suspension lines for all vehicles.
\param[in] batchQuery is a PxBatchQueryExt instance used to specify shader data and functions for the sweep scene queries.
\param[in] nbVehicles is the number of vehicles in the vehicles array.
\param[in] vehicles is an array of all vehicles that are to have a sweep issued from each wheel.
\param[in] nbHitsPerQuery is the maximum numbers of hits that will be returned for each query.
\param[in] vehiclesToSweep is an array of bools of length nbVehicles that is used to decide if sweeps will be performed for the corresponding vehicle
in the vehicles array. If vehiclesToSweep[i] is true then suspension sweeps will be performed for vehicles[i]. If vehiclesToSweep[i] is
false then suspension sweeps will not be performed for vehicles[i].
\param[in] sweepWidthScale scales the geometry of the wheel used in the sweep. Values < 1 result in a thinner swept wheel, while values > 1 result in a fatter swept wheel.
\param[in] sweepRadiusScale scales the geometry of the wheel used in the sweep. Values < 1 result in a smaller swept wheel, while values > 1 result in a larger swept wheel.
\param[in] sweepInflation Inflation parameter for sweeps. This is the inflation parameter from PxScene::sweep(). It inflates the shape and makes it rounder,
which gives smoother and more reliable normals.
\param[in] queryFlags filter flags for the batched scene queries
\param[in] context the vehicle context to use for the suspension sweeps.
\note If vehiclesToSweep is NULL then sweeps are performed for all vehicles in the vehicles array.
\note If vehiclesToSweep[i] is false then the vehicle stored in vehicles[i] will automatically use the most recent sweep or raycast hit planes
recorded by the most recent suspension sweeps or raycasts for that vehicle. For vehicles far from the camera or not visible on the screen it can be
optimal to only perform suspension queries every Nth update rather than every single update. The accuracy of the cached contact plane
naturally diminishes as N increase, meaning that wheels might start to hover or intersect the ground for large values of N or even with values close to 1 in
conjunction with large vehicle speeds and/or geometry that has low spatial coherence.
\note Calling setToRestState invalidates any cached hit planes. Prior to calling PxVehicleUpdates each vehicle needs to perform suspension raycasts
or sweeps at least once after instantiation and at least once after calling setToRestState.
\note Each sweep casts the wheel's shape along the suspension travel direction from the position of the top of the wheel at maximum suspension compression
to the position of the base of the wheel at maximum droop. Sweeps that start inside a PxShape are subsequently ignored by the
corresponding vehicle.
\note A scale can be applied to the shape so that a modified shape is swept through the scene. The parameters sweepWidthScale and sweepRadiusScale scale the
swept wheel shape in the width and radial directions. It is sometimes a good idea to sweep a thinner wheel to allow contact with other dynamic actors to be resolved
first before attempting to drive on them.
\note Blocking hits (PxQueryHitType::eBLOCK) and non-blocking hits (PxQueryHitType::TOUCH) are supported. If the pre-and post-filter functions of the PxBatchQuery
instance are set up to return blocking hits it is recommended to set nbHitsPerQuery = 1. If the filter functions returns touch hits then it is recommended to
set nbHitsPerQuery > 1. The exact value depends on the expected complexity of the geometry that lies under the wheel. For complex geometry, especially with dynamic
objects, it is recommended to use non-blocking hits. The vehicle update function will analyze all returned hits and choose the most appropriate using the thresholds
set in PxVehicleSetSweepHitRejectionAngles.
@see PxVehicleDrive4W::setToRestState, PxVehicleDriveNW::setToRestState, PxVehicleDriveTank::setToRestState, PxVehicleNoDrive::setToRestState
@see PxBatchQueryExt::sweep PxScene::sweep()
@see PxVehicleSetSweepHitRejectionAngles
*/
PX_DEPRECATED void PxVehicleSuspensionSweeps( PxBatchQueryExt* batchQuery,
const PxU32 nbVehicles, PxVehicleWheels** vehicles,
const PxU16 nbHitsPerQuery,
const bool* vehiclesToSweep = NULL,
const PxF32 sweepWidthScale = 1.0f, const PxF32 sweepRadiusScale = 1.0f, const PxF32 sweepInflation = 0.0f,
const PxQueryFlags queryFlags = PxQueryFlag::eSTATIC | PxQueryFlag::eDYNAMIC | PxQueryFlag::ePREFILTER,
const PxVehicleContext& context = PxVehicleGetDefaultContext());
/**
\brief A function called from PxContactModifyCallback::onContactModify. The function determines if rigid body contact points
recorded for the wheel's PxShape are likely to be duplicated and resolved by the wheel's suspension raycast. Contact points that will be
resolved by the suspension are ignored. Contact points that are accepted (rather than ignored) are modified to account for the effect of the
suspension geometry and the angular speed of the wheel.
\param[in] vehicle is a reference to the PxVehicleWheels instance that owns the wheel
\param[in] wheelId is the id of the wheel
\param[in] wheelTangentVelocityMultiplier determines the amount of wheel angular velocity that is used to modify the target relative velocity of the contact.
The target relative velocity is modified by adding a vector equal to the tangent velocity of the rotating wheel at the contact point and scaled by
wheelTangentVelocityMultiplier. The value of wheelTangentVelocityMultiplier is limited to the range (0,1). Higher values mimic higher values of friction
and tire load, while lower values mimic lower values of friction and tire load.
\param[in] maxImpulse determines the maximum impulse strength that the contacts can apply when a wheel is in contact with a PxRigidDynamic. This value is ignored for
contacts with PxRigidStatic instances.
\param[in,out] contactModifyPair describes the set of contacts involving the PxShape of the specified wheel and one other shape. The contacts in the contact set are
ignored or modified as required.
\param[in] context the vehicle context to use for the contact modification.
\note Contact points are accepted or rejected using the threshold angles specified in the function PxVehicleSetSweepHitRejectionAngles.
\note If a contact point is not rejected it is modified to account for the wheel rotation speed.
\note Set maxImpulse to PX_MAX_F32 to allow any impulse value to be applied.
\note Reduce maxImpulse if the wheels are frequently colliding with light objects with mass much less than the vehicle's mass.
Reducing this value encourages numerical stability.
@see PxContactModifyCallback::onContactModify, PxVehicleSetSweepHitRejectionAngles, PxVehicleContext
*/
PX_DEPRECATED PxU32 PxVehicleModifyWheelContacts
(const PxVehicleWheels& vehicle, const PxU32 wheelId,
const PxF32 wheelTangentVelocityMultiplier, const PxReal maxImpulse,
PxContactModifyPair& contactModifyPair,
const PxVehicleContext& context = PxVehicleGetDefaultContext());
/**
\brief Update an array of vehicles by either applying an acceleration to the rigid body actor associated with
each vehicle or by an immediate update of the velocity of the actor.
\note The update mode (acceleration or velocity change) can be selected with PxVehicleSetUpdateMode.
\param[in] timestep is the timestep of the update
\param[in] gravity is the value of gravitational acceleration
\param[in] vehicleDrivableSurfaceToTireFrictionPairs describes the mapping between each PxMaterial ptr and an integer representing a
surface type. It also stores the friction value for each combination of surface and tire type.
\param[in] nbVehicles is the number of vehicles pointers in the vehicles array
\param[in,out] vehicles is an array of length nbVehicles containing all vehicles to be updated by the specified timestep
\param[out] vehicleWheelQueryResults is an array of length nbVehicles storing the wheel query results of each corresponding vehicle and wheel in the
vehicles array. A NULL pointer is permitted.
\param[out] vehicleConcurrentUpdates is an array of length nbVehicles. It is only necessary to specify vehicleConcurrentUpdates if PxVehicleUpdates is
called concurrently (also concurrently with PxVehicleUpdateSingleVehicleAndStoreTelemetryData). The element vehicleConcurrentUpdates[i] of the array
stores data that is computed for vehicle[i] during PxVehicleUpdates but which cannot be safely written when concurrently called. The data computed and
stored in vehicleConcurrentUpdates must be passed to PxVehiclePostUpdates, where it is applied to all relevant actors in sequence. A NULL pointer is permitted.
\param[in] context the vehicle context to use for the vehicle update.
\note The vehicleWheelQueryResults buffer must persist until the end of PxVehicleUpdates.
\note The vehicleWheelQueryResults buffer is left unmodified for vehicles with sleeping rigid bodies whose control inputs indicate they should remain inert.
\note If PxVehicleUpdates is called concurrently then vehicleConcurrentUpdates must be specified. Do not specify vehicleConcurrentUpdates if PxVehicleUpdates
is not called concurrently.
\note The vehicleConcurrentUpdates buffer must persist until the end of PxVehiclePostUpdate.
\note If any vehicle has one or more disabled wheels (PxVehicleWheelsSimData::disableWheel) then the disabled wheels must not be associated
with a PxShape (PxVehicleWheelsSimData::setWheelShapeMapping); the differential of the vehicle must be configured so that no drive torque
is delivered to a disabled wheel; and the wheel must have zero rotation speed (PxVehicleWheelsDynData::setWheelRotationSpeed)
\note Concurrent calls to PxVehicleUpdates and PxVehicleUpdateSingleVehicleAndStoreTelemetryData are permitted if the parameter
vehicleConcurrentUpdates is used.
@see PxVehicleSetUpdateMode, PxVehicleWheelsSimData::disableWheel, PxVehicleWheelsSimData::setWheelShapeMapping, PxVehicleWheelsDynData::setWheelRotationSpeed,
PxVehiclePostUpdates
*/
PX_DEPRECATED void PxVehicleUpdates(
const PxReal timestep, const PxVec3& gravity,
const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
const PxU32 nbVehicles, PxVehicleWheels** vehicles, PxVehicleWheelQueryResult* vehicleWheelQueryResults, PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates = NULL,
const PxVehicleContext& context = PxVehicleGetDefaultContext());
/**
\brief Apply actor changes that were computed in concurrent calls to PxVehicleUpdates or PxVehicleUpdateSingleVehicleAndStoreTelemetryData but
which could not be safely applied due to the concurrency.
\param[in] vehicleConcurrentUpdates is an array of length nbVehicles where vehicleConcurrentUpdates[i] contains data describing actor changes that
were computed for vehicles[i] during concurrent calls to PxVehicleUpdates or PxVehicleUpdateSingleVehicleAndStoreTelemetryData.
\param[in] nbVehicles is the number of vehicles pointers in the vehicles array
\param[in,out] vehicles is an array of length nbVehicles containing all vehicles that were partially updated in concurrent calls to PxVehicleUpdates or
PxVehicleUpdateSingleVehicleAndStoreTelemetryData.
\param[in] context the vehicle context to use for the vehicle post update.
@see PxVehicleUpdates, PxVehicleUpdateSingleVehicleAndStoreTelemetryData
*/
PX_DEPRECATED void PxVehiclePostUpdates(
const PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxU32 nbVehicles, PxVehicleWheels** vehicles,
const PxVehicleContext& context = PxVehicleGetDefaultContext());
/**
\brief Shift the origin of vehicles by the specified vector.
Call this method to adjust the internal data structures of vehicles to reflect the shifted origin location
(the shift vector will get subtracted from all world space spatial data).
\note It is the user's responsibility to keep track of the summed total origin shift and adjust all input/output to/from PhysXVehicle accordingly.
\note This call will not automatically shift the PhysX scene and its objects. You need to call PxScene::shiftOrigin() seperately to keep the systems in sync.
\param[in] shift is the translation vector to shift the origin by.
\param[in] nbVehicles is the number of vehicles in the vehicles array.
\param[in,out] vehicles is an array of all vehicles that should be updated to map to the new scene origin.
*/
PX_DEPRECATED void PxVehicleShiftOrigin(const PxVec3& shift, const PxU32 nbVehicles, PxVehicleWheels** vehicles);
#if PX_DEBUG_VEHICLE_ON
/**
\brief Update an single vehicle by either applying an acceleration to the rigid body actor associated with
each vehicle or by an immediate update of the velocity of the actor. Also record telemetry data from the
vehicle so that it may be visualized or queried.
\note The update mode (acceleration or velocity change) can be selected with PxVehicleSetUpdateMode.
\param[in] timestep is the timestep of the update
\param[in] gravity is the value of gravitational acceleration
\param[in] vehicleDrivableSurfaceToTireFrictionPairs describes the mapping between each PxMaterial ptr and an integer representing a
surface type. It also stores the friction value for each combination of surface and tire type.
\param[in,out] focusVehicle is the vehicle to be updated and have its telemetry data recorded
\param[out] vehicleWheelQueryResults is an array of length 1 storing the wheel query results of each wheel of the vehicle/
A NULL pointer is permitted.
\param[out] telemetryData is the data structure used to record telemetry data during the update for later query or visualization
\param[out] vehicleConcurrentUpdates is an array of length 1. It is only necessary to specify vehicleConcurrentUpdates if
PxVehicleUpdateSingleVehicleAndStoreTelemetryData is called concurrently (also concurrently with PxVehicleUpdates). The
PxVehicleConcurrentUpdateData struct stores data that cannot be safely written when concurrently called. The data computed and
stored in vehicleConcurrentUpdates must be passed to PxVehiclePostUpdates, where it is applied to the vehicle actor. A NULL
pointer is permitted.
\param[in] context the vehicle context to use for the vehicle update.
\note The vehicleWheelQueryResults buffer must persist until the end of PxVehicleUpdateSingleVehicleAndStoreTelemetryData
\note The vehicleWheelQueryResults buffer is left unmodified for vehicles with sleeping rigid bodies whose control inputs indicate they should remain inert.
\note Concurrent calls to PxVehicleUpdateSingleVehicleAndStoreTelemetryData and PxVehicleUpdates are permitted if the parameter
vehicleConcurrentUpdates is used.
@see PxVehiclePostUpdates, PxVehicleSetUpdateMode, PxVehicleTelemetryData
*/
PX_DEPRECATED void PxVehicleUpdateSingleVehicleAndStoreTelemetryData
(const PxReal timestep, const PxVec3& gravity,
const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
PxVehicleWheels* focusVehicle, PxVehicleWheelQueryResult* vehicleWheelQueryResults,
PxVehicleTelemetryData& telemetryData,
PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates = NULL,
const PxVehicleContext& context = PxVehicleGetDefaultContext());
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 32,818 | C | 53.789649 | 174 | 0.80209 |
NVIDIA-Omniverse/PhysX/physx/include/vehicle/PxVehicleDriveNW.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_NWDRIVE_H
#define PX_VEHICLE_NWDRIVE_H
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleComponents.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxFilterData;
class PxGeometry;
class PxPhysics;
class PxVehicleDrivableSurfaceToTireFrictionPairs;
class PxShape;
class PxMaterial;
class PxRigidDynamic;
/**
\brief Data structure describing configuration data of a vehicle with up to PX_MAX_NB_WHEELS driven equally through the differential. The vehicle has an
engine, clutch, gears, autobox, differential.
@see PxVehicleDriveSimData
*/
class PX_DEPRECATED PxVehicleDriveSimDataNW : public PxVehicleDriveSimData
{
public:
friend class PxVehicleDriveNW;
PxVehicleDriveSimDataNW()
: PxVehicleDriveSimData()
{
}
/**
\brief Return the data describing the differential of a vehicle with up to PX_MAX_NB_WHEELS driven wheels.
*/
const PxVehicleDifferentialNWData& getDiffData() const
{
return mDiff;
}
/**
\brief Set the data describing the differential of a vehicle with up to PX_MAX_NB_WHEELS driven wheels.
The differential data describes the set of wheels that are driven by the differential.
*/
void setDiffData(const PxVehicleDifferentialNWData& diff);
private:
/**
\brief Differential simulation data
@see setDiffData, getDiffData
*/
PxVehicleDifferentialNWData mDiff;
/**
\brief Test if the NW-drive simulation data has been setup with legal data.
Call only after setting all components.
@see setEngineData, setClutchData, setGearsData, setAutoboxData, setDiffData, setAckermannGeometryData
*/
bool isValid() const;
//serialization
public:
PxVehicleDriveSimDataNW(const PxEMPTY) : PxVehicleDriveSimData(PxEmpty), mDiff(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveSimDataNW) & 15));
/**
\brief The control inputs for a PxVehicleDriveNW.
@see PxVehicleDriveDynData::setAnalogInput, PxVehicleDriveDynData::getAnalogInput
*/
struct PX_DEPRECATED PxVehicleDriveNWControl
{
enum Enum
{
eANALOG_INPUT_ACCEL=0,
eANALOG_INPUT_BRAKE,
eANALOG_INPUT_HANDBRAKE,
eANALOG_INPUT_STEER_LEFT,
eANALOG_INPUT_STEER_RIGHT,
eMAX_NB_DRIVENW_ANALOG_INPUTS
};
};
/**
\brief Data structure with instanced dynamics data and configuration data of a vehicle with up to PX_MAX_NB_WHEELS driven wheels.
*/
class PX_DEPRECATED PxVehicleDriveNW : public PxVehicleDrive
{
public:
friend class PxVehicleUpdate;
/**
\brief Allocate a PxVehicleDriveNW instance for a NWDrive vehicle with nbWheels
\param[in] nbWheels is the number of wheels on the vehicle.
\return The instantiated vehicle.
@see free, setup
*/
static PxVehicleDriveNW* allocate(const PxU32 nbWheels);
/**
\brief Deallocate a PxVehicleDriveNW instance.
@see allocate
*/
void free();
/**
\brief Set up a vehicle using simulation data for the wheels and drive model.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
\param[in] driveData describes the properties of the vehicle's drive model (gears/engine/clutch/differential/autobox). The vehicle instance takes a copy of this data.
\param[in] nbWheels is the number of wheels on the vehicle.
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
*/
void setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
const PxU32 nbWheels);
/**
\brief Allocate and set up a vehicle using simulation data for the wheels and drive model.
\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
\param[in] driveData describes the properties of the vehicle's drive model (gears/engine/clutch/differential/autobox). The vehicle instance takes a copy of this data.
\param[in] nbWheels is the number of wheels on the vehicle.
\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes. To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
\return The instantiated vehicle.
@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
*/
static PxVehicleDriveNW* create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
const PxU32 nbWheels);
/**
\brief Set a vehicle to its rest state. Aside from the rigid body transform, this will set the vehicle and rigid body
to the state they were in immediately after setup or create.
\note Calling setToRestState invalidates the cached raycast hit planes under each wheel meaning that suspension line
raycasts need to be performed at least once with PxVehicleSuspensionRaycasts before calling PxVehicleUpdates.
@see setup, create, PxVehicleSuspensionRaycasts, PxVehicleUpdates
*/
void setToRestState();
/**
\brief Simulation data that describes the configuration of the vehicle's drive model.
@see setup, create
*/
PxVehicleDriveSimDataNW mDriveSimData;
private:
/**
\brief Test if the instanced dynamics and configuration data has legal values.
*/
bool isValid() const;
//serialization
public:
PxVehicleDriveNW(PxBaseFlags baseFlags) : PxVehicleDrive(baseFlags), mDriveSimData(PxEmpty) {}
PxVehicleDriveNW();
~PxVehicleDriveNW(){}
static PxVehicleDriveNW* createObject(PxU8*& address, PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
virtual const char* getConcreteTypeName() const { return "PxVehicleDriveNW"; }
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxVehicleDriveNW", PxVehicleDrive); }
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveNW) & 15));
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 8,388 | C | 37.131818 | 185 | 0.778255 |
NVIDIA-Omniverse/PhysX/physx/include/task/PxTask.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.
#ifndef PX_TASK_H
#define PX_TASK_H
#include "task/PxTaskManager.h"
#include "task/PxCpuDispatcher.h"
#include "foundation/PxAssert.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
* \brief Base class of all task types
*
* PxBaseTask defines a runnable reference counted task with built-in profiling.
*/
class PxBaseTask
{
public:
PxBaseTask() : mContextID(0), mTm(NULL) {}
virtual ~PxBaseTask() {}
/**
* \brief The user-implemented run method where the task's work should be performed
*
* run() methods must be thread safe, stack friendly (no alloca, etc), and
* must never block.
*/
virtual void run() = 0;
/**
* \brief Return a user-provided task name for profiling purposes.
*
* It does not have to be unique, but unique names are helpful.
*
* \return The name of this task
*/
virtual const char* getName() const = 0;
//! \brief Implemented by derived implementation classes
virtual void addReference() = 0;
//! \brief Implemented by derived implementation classes
virtual void removeReference() = 0;
//! \brief Implemented by derived implementation classes
virtual int32_t getReference() const = 0;
/** \brief Implemented by derived implementation classes
*
* A task may assume in its release() method that the task system no longer holds
* references to it - so it may safely run its destructor, recycle itself, etc.
* provided no additional user references to the task exist
*/
virtual void release() = 0;
/**
* \brief Return PxTaskManager to which this task was submitted
*
* Note, can return NULL if task was not submitted, or has been
* completed.
*/
PX_FORCE_INLINE PxTaskManager* getTaskManager() const
{
return mTm;
}
PX_FORCE_INLINE void setContextId(PxU64 id) { mContextID = id; }
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
protected:
PxU64 mContextID; //!< Context ID for profiler interface
PxTaskManager* mTm; //!< Owning PxTaskManager instance
friend class PxTaskMgr;
};
/**
* \brief A PxBaseTask implementation with deferred execution and full dependencies
*
* A PxTask must be submitted to a PxTaskManager to to be executed, Tasks may
* optionally be named when they are submitted.
*/
class PxTask : public PxBaseTask
{
public:
PxTask() : mTaskID(0) {}
virtual ~PxTask() {}
//! \brief Release method implementation
virtual void release() PX_OVERRIDE
{
PX_ASSERT(mTm);
// clear mTm before calling taskCompleted() for safety
PxTaskManager* save = mTm;
mTm = NULL;
save->taskCompleted(*this);
}
//! \brief Inform the PxTaskManager this task must finish before the given
// task is allowed to start.
PX_INLINE void finishBefore(PxTaskID taskID)
{
PX_ASSERT(mTm);
mTm->finishBefore(*this, taskID);
}
//! \brief Inform the PxTaskManager this task cannot start until the given
// task has completed.
PX_INLINE void startAfter(PxTaskID taskID)
{
PX_ASSERT(mTm);
mTm->startAfter(*this, taskID);
}
/**
* \brief Manually increment this task's reference count. The task will
* not be allowed to run until removeReference() is called.
*/
virtual void addReference() PX_OVERRIDE
{
PX_ASSERT(mTm);
mTm->addReference(mTaskID);
}
/**
* \brief Manually decrement this task's reference count. If the reference
* count reaches zero, the task will be dispatched.
*/
virtual void removeReference() PX_OVERRIDE
{
PX_ASSERT(mTm);
mTm->decrReference(mTaskID);
}
/**
* \brief Return the ref-count for this task
*/
virtual int32_t getReference() const PX_OVERRIDE
{
return mTm->getReference(mTaskID);
}
/**
* \brief Return the unique ID for this task
*/
PX_INLINE PxTaskID getTaskID() const
{
return mTaskID;
}
/**
* \brief Called by PxTaskManager at submission time for initialization
*
* Perform simulation step initialization here.
*/
virtual void submitted()
{
}
protected:
PxTaskID mTaskID; //!< ID assigned at submission
friend class PxTaskMgr;
};
/**
* \brief A PxBaseTask implementation with immediate execution and simple dependencies
*
* A PxLightCpuTask bypasses the PxTaskManager launch dependencies and will be
* submitted directly to your scene's CpuDispatcher. When the run() function
* completes, it will decrement the reference count of the specified
* continuation task.
*
* You must use a full-blown PxTask if you want your task to be resolved
* by another PxTask, or you need more than a single dependency to be
* resolved when your task completes, or your task will not run on the
* CpuDispatcher.
*/
class PxLightCpuTask : public PxBaseTask
{
public:
PxLightCpuTask()
: mCont( NULL )
, mRefCount( 0 )
{
}
virtual ~PxLightCpuTask()
{
mTm = NULL;
}
/**
* \brief Initialize this task and specify the task that will have its ref count decremented on completion.
*
* Submission is deferred until the task's mRefCount is decremented to zero.
* Note that we only use the PxTaskManager to query the appropriate dispatcher.
*
* \param[in] tm The PxTaskManager this task is managed by
* \param[in] c The task to be executed when this task has finished running
*/
PX_INLINE void setContinuation(PxTaskManager& tm, PxBaseTask* c)
{
PX_ASSERT(mRefCount == 0);
mRefCount = 1;
mCont = c;
mTm = &tm;
if(mCont)
mCont->addReference();
}
/**
* \brief Initialize this task and specify the task that will have its ref count decremented on completion.
*
* This overload of setContinuation() queries the PxTaskManager from the continuation
* task, which cannot be NULL.
* \param[in] c The task to be executed after this task has finished running
*/
PX_INLINE void setContinuation(PxBaseTask* c)
{
PX_ASSERT(c);
PX_ASSERT(mRefCount == 0);
mRefCount = 1;
mCont = c;
if(mCont)
{
mCont->addReference();
mTm = mCont->getTaskManager();
PX_ASSERT(mTm);
}
}
/**
* \brief Retrieves continuation task
*/
PX_INLINE PxBaseTask* getContinuation() const
{
return mCont;
}
/**
* \brief Manually decrement this task's reference count. If the reference
* count reaches zero, the task will be dispatched.
*/
virtual void removeReference() PX_OVERRIDE
{
mTm->decrReference(*this);
}
/** \brief Return the ref-count for this task */
virtual int32_t getReference() const PX_OVERRIDE
{
return mRefCount;
}
/**
* \brief Manually increment this task's reference count. The task will
* not be allowed to run until removeReference() is called.
*/
virtual void addReference() PX_OVERRIDE
{
mTm->addReference(*this);
}
/**
* \brief called by CpuDispatcher after run method has completed
*
* Decrements the continuation task's reference count, if specified.
*/
virtual void release() PX_OVERRIDE
{
if(mCont)
mCont->removeReference();
}
protected:
PxBaseTask* mCont; //!< Continuation task, can be NULL
volatile int32_t mRefCount; //!< PxTask is dispatched when reaches 0
friend class PxTaskMgr;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 8,843 | C | 26.6375 | 111 | 0.695465 |
NVIDIA-Omniverse/PhysX/physx/include/task/PxTaskManager.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.
#ifndef PX_TASK_MANAGER_H
#define PX_TASK_MANAGER_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxErrorCallback.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBaseTask;
class PxTask;
class PxLightCpuTask;
typedef unsigned int PxTaskID;
/**
\brief Identifies the type of each heavyweight PxTask object
\note This enum type is only used by PxTask objects, PxLightCpuTasks do not use this enum.
@see PxTask
@see PxLightCpuTask
*/
struct PxTaskType
{
/**
* \brief Identifies the type of each heavyweight PxTask object
*/
enum Enum
{
eCPU, //!< PxTask will be run on the CPU
eNOT_PRESENT, //!< Return code when attempting to find a task that does not exist
eCOMPLETED //!< PxTask execution has been completed
};
};
class PxCpuDispatcher;
/**
\brief The PxTaskManager interface
A PxTaskManager instance holds references to user-provided dispatcher objects. When tasks are
submitted the PxTaskManager routes them to the appropriate dispatcher and handles task profiling if enabled.
Users should not implement the PxTaskManager interface, the SDK creates its own concrete PxTaskManager object
per-scene which users can configure by passing dispatcher objects into the PxSceneDesc.
@see PxCpuDispatcher
*/
class PxTaskManager
{
public:
/**
\brief Set the user-provided dispatcher object for CPU tasks
\param[in] ref The dispatcher object.
@see PxCpuDispatcher
*/
virtual void setCpuDispatcher(PxCpuDispatcher& ref) = 0;
/**
\brief Get the user-provided dispatcher object for CPU tasks
\return The CPU dispatcher object.
@see PxCpuDispatcher
*/
virtual PxCpuDispatcher* getCpuDispatcher() const = 0;
/**
\brief Reset any dependencies between Tasks
\note Will be called at the start of every frame before tasks are submitted.
@see PxTask
*/
virtual void resetDependencies() = 0;
/**
\brief Called by the owning scene to start the task graph.
\note All tasks with ref count of 1 will be dispatched.
@see PxTask
*/
virtual void startSimulation() = 0;
/**
\brief Called by the owning scene at the end of a simulation step.
*/
virtual void stopSimulation() = 0;
/**
\brief Called by the worker threads to inform the PxTaskManager that a task has completed processing.
\param[in] task The task which has been completed
*/
virtual void taskCompleted(PxTask& task) = 0;
/**
\brief Retrieve a task by name
\param[in] name The unique name of a task
\return The ID of the task with that name, or eNOT_PRESENT if not found
*/
virtual PxTaskID getNamedTask(const char* name) = 0;
/**
\brief Submit a task with a unique name.
\param[in] task The task to be executed
\param[in] name The unique name of a task
\param[in] type The type of the task (default eCPU)
\return The ID of the task with that name, or eNOT_PRESENT if not found
*/
virtual PxTaskID submitNamedTask(PxTask* task, const char* name, PxTaskType::Enum type = PxTaskType::eCPU) = 0;
/**
\brief Submit an unnamed task.
\param[in] task The task to be executed
\param[in] type The type of the task (default eCPU)
\return The ID of the task with that name, or eNOT_PRESENT if not found
*/
virtual PxTaskID submitUnnamedTask(PxTask& task, PxTaskType::Enum type = PxTaskType::eCPU) = 0;
/**
\brief Retrieve a task given a task ID
\param[in] id The ID of the task to return, a valid ID must be passed or results are undefined
\return The task associated with the ID
*/
virtual PxTask* getTaskFromID(PxTaskID id) = 0;
/**
\brief Release the PxTaskManager object, referenced dispatchers will not be released
*/
virtual void release() = 0;
/**
\brief Construct a new PxTaskManager instance with the given [optional] dispatchers
*/
static PxTaskManager* createTaskManager(PxErrorCallback& errorCallback, PxCpuDispatcher* = NULL);
protected:
virtual ~PxTaskManager() {}
/*! \cond PRIVATE */
virtual void finishBefore(PxTask& task, PxTaskID taskID) = 0;
virtual void startAfter(PxTask& task, PxTaskID taskID) = 0;
virtual void addReference(PxTaskID taskID) = 0;
virtual void decrReference(PxTaskID taskID) = 0;
virtual int32_t getReference(PxTaskID taskID) const = 0;
virtual void decrReference(PxLightCpuTask&) = 0;
virtual void addReference(PxLightCpuTask&) = 0;
/*! \endcond */
friend class PxBaseTask;
friend class PxTask;
friend class PxLightCpuTask;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 5,997 | C | 28.401961 | 113 | 0.745539 |
NVIDIA-Omniverse/PhysX/physx/include/task/PxCpuDispatcher.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.
#ifndef PX_CPU_DISPATCHER_H
#define PX_CPU_DISPATCHER_H
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBaseTask;
/**
\brief A CpuDispatcher is responsible for scheduling the execution of tasks passed to it by the SDK.
A typical implementation would for example use a thread pool with the dispatcher
pushing tasks onto worker thread queues or a global queue.
@see PxBaseTask
@see PxTask
@see PxTaskManager
*/
class PxCpuDispatcher
{
public:
/**
\brief Called by the TaskManager when a task is to be queued for execution.
Upon receiving a task, the dispatcher should schedule the task to run.
After the task has been run, it should call the release() method and
discard its pointer.
\param[in] task The task to be run.
@see PxBaseTask
*/
virtual void submitTask(PxBaseTask& task) = 0;
/**
\brief Returns the number of available worker threads for this dispatcher.
The SDK will use this count to control how many tasks are submitted. By
matching the number of tasks with the number of execution units task
overhead can be reduced.
*/
virtual uint32_t getWorkerCount() const = 0;
virtual ~PxCpuDispatcher() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 2,808 | C | 32.843373 | 101 | 0.759259 |
NVIDIA-Omniverse/PhysX/physx/include/geomutils/PxContactPoint.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_CONTACT_POINT_H
#define PX_CONTACT_POINT_H
#include "foundation/PxVec3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxContactPoint
{
/**
\brief The normal of the contacting surfaces at the contact point.
For two shapes s0 and s1, the normal points in the direction that s0 needs to move in to resolve the contact with s1.
*/
PX_ALIGN(16, PxVec3 normal);
/**
\brief The separation of the shapes at the contact point. A negative separation denotes a penetration.
*/
PxReal separation;
/**
\brief The point of contact between the shapes, in world space.
*/
PX_ALIGN(16, PxVec3 point);
/**
\brief The max impulse permitted at this point
*/
PxReal maxImpulse;
PX_ALIGN(16, PxVec3 targetVel);
/**
\brief The static friction coefficient
*/
PxReal staticFriction;
/**
\brief Material flags for this contact (eDISABLE_FRICTION, eDISABLE_STRONG_FRICTION). @see PxMaterialFlag
*/
PxU8 materialFlags;
/**
\brief The surface index of shape 1 at the contact point. This is used to identify the surface material.
\note This field is only supported by triangle meshes and heightfields, else it will be set to PXC_CONTACT_NO_FACE_INDEX.
*/
PxU32 internalFaceIndex1;
/**
\brief The dynamic friction coefficient
*/
PxReal dynamicFriction;
/**
\brief The restitution coefficient
*/
PxReal restitution;
/**
\brief Damping coefficient (for compliant contacts)
*/
PxReal damping;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,236 | C | 30.427184 | 123 | 0.737021 |
NVIDIA-Omniverse/PhysX/physx/include/omnipvd/PxOmniPvd.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_OMNI_PVD_H
#define PX_OMNI_PVD_H
#include "PxPhysXConfig.h"
class OmniPvdWriter;
class OmniPvdFileWriteStream;
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxFoundation;
class PxOmniPvd
{
public:
class ScopedExclusiveWriter
{
public:
PX_FORCE_INLINE ScopedExclusiveWriter(PxOmniPvd* omniPvd)
{
mOmniPvd = omniPvd;
mWriter = NULL;
if (mOmniPvd) {
mWriter = mOmniPvd->acquireExclusiveWriterAccess();
}
}
PX_FORCE_INLINE ~ScopedExclusiveWriter()
{
if (mOmniPvd && mWriter) {
mOmniPvd->releaseExclusiveWriterAccess();
}
}
PX_FORCE_INLINE OmniPvdWriter* operator-> ()
{
return mWriter;
}
PX_FORCE_INLINE OmniPvdWriter* getWriter()
{
return mWriter;
}
private:
OmniPvdWriter* mWriter;
PxOmniPvd* mOmniPvd;
};
virtual ~PxOmniPvd()
{
}
/**
\brief Get the OmniPvd writer.
Gets an instance of the OmniPvd writer. The writer access will not be thread safe since the OmniPVD API is not thread safe itself. Writing concurrently and simultaneously using the OmniPVD API is undefined.
For thread safe exlcusive access use the mechanism acquireExclusiveWriterAccess/releaseExclusiveWriterAccess.
\return OmniPvdWriter instance on succes, NULL otherwise.
*/
virtual OmniPvdWriter* getWriter() = 0;
/**
\brief Acquires an exclusive writer access.
This call blocks until exclusive access to the writer can be acquired. Once access has been granted, it is guaranteed that no other caller can access the writer through this method until releaseExclusiveWriterAccess() has been called.
This allows to safely write PVD data in environments with concurrent processing workflows.
\return OmniPvdWriter instance on succes, NULL otherwise.
*/
virtual OmniPvdWriter* acquireExclusiveWriterAccess() = 0;
/**
\brief Releases the exclusive writer access
Releases the access to the writer that was previously acquired using acquireExclusiveWriterAccess.
*/
virtual void releaseExclusiveWriterAccess() = 0;
/**
\brief Gets an instance to the OmniPvd file write stream
\return OmniPvdFileWriteStream instance on succes, NULL otherwise.
*/
virtual OmniPvdFileWriteStream* getFileWriteStream() = 0;
/**
\brief Starts the OmniPvd sampling
\return True if sampling started correctly, false if not.
*/
virtual bool startSampling() = 0;
/**
\brief Releases the PxOmniPvd object
*/
virtual void release() = 0;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/**
\brief Creates an instance of the OmniPvd object
Creates an instance of the OmniPvd class. There may be only one instance of this class per process. Calling this method after an instance
has been created already will return the same instance over and over.
\param foundation Foundation instance (see PxFoundation)
\return PxOmniPvd instance on succes, NULL otherwise.
*/
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxOmniPvd* PX_CALL_CONV PxCreateOmniPvd(physx::PxFoundation& foundation);
#endif
| 4,671 | C | 29.736842 | 235 | 0.756369 |
NVIDIA-Omniverse/PhysX/physx/include/collision/PxCollisionDefs.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_COLLISION_DEFS_H
#define PX_COLLISION_DEFS_H
#include "PxPhysXConfig.h"
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A callback class to allocate memory to cache information used in contact generation.
*/
class PxCacheAllocator
{
public:
/**
\brief Allocates cache data for contact generation. This data is stored inside PxCache objects.
The application can retain and provide this information for future contact generation passes
for a given pair to improve contact generation performance. It is the application's responsibility
to release this memory appropriately. If the memory is released, the application must ensure that
this memory is no longer referenced by any PxCache objects passed to PxGenerateContacts.
\param byteSize [in] size of the allocation in bytes
\return the newly-allocated memory. The returned address must be 16-byte aligned.
@see PxCache, PxGenerateContacts
*/
virtual PxU8* allocateCacheData(const PxU32 byteSize) = 0;
virtual ~PxCacheAllocator() {}
};
/**
\brief A structure to cache contact information produced by low-level contact generation functions.
*/
struct PxCache
{
PxU8* mCachedData; //!< Cached data pointer. Allocated via PxCacheAllocator
PxU16 mCachedSize; //!< The total size of the cached data
PxU8 mPairData; //!< Pair data information used and cached internally by some contact generation functions to accelerate performance.
PxU8 mManifoldFlags; //!< Manifold flags used to identify the format the cached data is stored in. @see Gu::ManifoldFlags
PX_FORCE_INLINE PxCache() : mCachedData(NULL), mCachedSize(0), mPairData(0), mManifoldFlags(0)
{
}
PX_FORCE_INLINE void reset()
{
mCachedData = NULL;
mCachedSize = 0;
mPairData = 0;
mManifoldFlags = 0;
}
};
#if !PX_DOXYGEN
}
#endif
#endif
| 3,535 | C | 37.021505 | 136 | 0.765205 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxPhysXCommonConfig.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_PHYSX_COMMON_CONFIG_H
#define PX_PHYSX_COMMON_CONFIG_H
/** \addtogroup common
@{ */
#include "foundation/Px.h"
//Fills almost all allocated (host and device memory) with 0xcdcdcdcd (=3452816845)
#define PX_STOMP_ALLOCATED_MEMORY 0
/*Disable support for VS2017 prior version 15.5.1 for windows platform, because of a compiler bug:
https://developercommunity.visualstudio.com/content/problem/66047/possible-compiler-bug.html
*/
#if (PX_VC == 15) && PX_WINDOWS && (_MSC_FULL_VER < 191225830)
#error Visual studio 2017 prior to 15.5.1 is not supported because of a compiler bug.
#endif
// define API function declaration (public API only needed because of extensions)
#if defined PX_PHYSX_STATIC_LIB
#define PX_PHYSX_CORE_API
#else
#if PX_WINDOWS_FAMILY
#if defined PX_PHYSX_CORE_EXPORTS
#define PX_PHYSX_CORE_API __declspec(dllexport)
#else
#define PX_PHYSX_CORE_API __declspec(dllimport)
#endif
#elif PX_UNIX_FAMILY
#define PX_PHYSX_CORE_API PX_UNIX_EXPORT
#else
#define PX_PHYSX_CORE_API
#endif
#endif
#if PX_SUPPORT_GPU_PHYSX
// define API function declaration
#if defined PX_PHYSX_GPU_STATIC
#define PX_PHYSX_GPU_API
#else
#if PX_WINDOWS
#if defined PX_PHYSX_GPU_EXPORTS
#define PX_PHYSX_GPU_API __declspec(dllexport)
#else
#define PX_PHYSX_GPU_API __declspec(dllimport)
#endif
#elif PX_UNIX_FAMILY
#define PX_PHYSX_GPU_API PX_UNIX_EXPORT
#else
#define PX_PHYSX_GPU_API
#endif
#endif
#else // PX_SUPPORT_GPU_PHYSX
#define PX_PHYSX_GPU_API
#endif // PX_SUPPORT_GPU_PHYSX
#if defined PX_PHYSX_STATIC_LIB
#define PX_PHYSX_COMMON_API
#else
#if PX_WINDOWS_FAMILY && !defined(__CUDACC__)
#if defined PX_PHYSX_COMMON_EXPORTS
#define PX_PHYSX_COMMON_API __declspec(dllexport)
#else
#define PX_PHYSX_COMMON_API __declspec(dllimport)
#endif
#elif PX_UNIX_FAMILY
#define PX_PHYSX_COMMON_API PX_UNIX_EXPORT
#else
#define PX_PHYSX_COMMON_API
#endif
#endif
// PT: typical "invalid" value in various CD algorithms
#define PX_INVALID_U32 0xffffffff
#define PX_INVALID_U16 0xffff
// Changing these parameters requires recompilation of the SDK
// Enable debug visualization
#define PX_ENABLE_DEBUG_VISUALIZATION 1
#define PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION
// Enable simulation statistics generation
#define PX_ENABLE_SIM_STATS 1
#define PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#if !PX_DOXYGEN
namespace physx
{
#endif
typedef PxU32 PxTriangleID;
typedef PxU16 PxMaterialTableIndex;
typedef PxU16 PxFEMMaterialTableIndex;
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,265 | C | 31.815384 | 98 | 0.753107 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxCollection.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_COLLECTION_H
#define PX_COLLECTION_H
#include "common/PxSerialFramework.h"
/** \addtogroup common
@{
*/
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBase;
/**
\brief Collection class for serialization.
A collection is a set of PxBase objects. PxBase objects can be added to the collection
regardless of other objects they depend on. Objects may be named using PxSerialObjectId values in order
to resolve dependencies between objects of different collections.
Serialization and deserialization only work through collections.
A scene is typically serialized using the following steps:
-# create a serialization registry
-# create a collection for scene objects
-# complete the scene objects (adds all dependent objects, e.g. meshes)
-# serialize collection
-# release collection
-# release serialization registry
For example the code may look like this:
\code
PxPhysics* physics; // The physics
PxScene* scene; // The physics scene
SerialStream s; // The user-defined stream doing the actual write to disk
PxSerializationRegistry* registry = PxSerialization::createSerializationRegistry(*physics); // step 1)
PxCollection* collection = PxSerialization::createCollection(*scene); // step 2)
PxSerialization::complete(*collection, *registry); // step 3)
PxSerialization::serializeCollectionToBinary(s, *collection, *registry); // step 4)
collection->release(); // step 5)
registry->release(); // step 6)
\endcode
A scene is typically deserialized using the following steps:
-# load a serialized collection into memory
-# create a serialization registry
-# create a collection by passing the serialized memory block
-# add collected objects to scene
-# release collection
-# release serialization registry
For example the code may look like this:
\code
PxPhysics* physics; // The physics
PxScene* scene; // The physics scene
void* memory128; // a 128-byte aligned buffer previously loaded from disk by the user - step 1)
PxSerializationRegistry* registry = PxSerialization::createSerializationRegistry(*physics); // step 2)
PxCollection* collection = PxSerialization::createCollectionFromBinary(memory128, *registry); // step 3)
scene->addCollection(*collection); // step 4)
collection->release(); // step 5)
registry->release(); // step 6)
\endcode
@see PxBase, PxCreateCollection()
*/
class PxCollection
{
public:
/**
\brief Adds a PxBase object to the collection.
Adds a PxBase object to the collection. Optionally a PxSerialObjectId can be provided
in order to resolve dependencies between collections. A PxSerialObjectId value of PX_SERIAL_OBJECT_ID_INVALID
means the object remains without id. Objects can be added regardless of other objects they require. If the object
is already in the collection, the ID will be set if it was PX_SERIAL_OBJECT_ID_INVALID previously, otherwise the
operation fails.
\param[in] object Object to be added to the collection
\param[in] id Optional PxSerialObjectId id
*/
virtual void add(PxBase& object, PxSerialObjectId id = PX_SERIAL_OBJECT_ID_INVALID) = 0;
/**
\brief Removes a PxBase member object from the collection.
Object needs to be contained by the collection.
\param[in] object PxBase object to be removed
*/
virtual void remove(PxBase& object) = 0;
/**
\brief Returns whether the collection contains a certain PxBase object.
\param[in] object PxBase object
\return Whether object is contained.
*/
virtual bool contains(PxBase& object) const = 0;
/**
\brief Adds an id to a member PxBase object.
If the object is already associated with an id within the collection, the id is replaced.
May only be called for objects that are members of the collection. The id needs to be unique
within the collection.
\param[in] object Member PxBase object
\param[in] id PxSerialObjectId id to be given to the object
*/
virtual void addId(PxBase& object, PxSerialObjectId id) = 0;
/**
\brief Removes id from a contained PxBase object.
May only be called for ids that are associated with an object in the collection.
\param[in] id PxSerialObjectId value
*/
virtual void removeId(PxSerialObjectId id) = 0;
/**
\brief Adds all PxBase objects and their ids of collection to this collection.
PxBase objects already in this collection are ignored. Object ids need to be conflict
free, i.e. the same object may not have two different ids within the two collections.
\param[in] collection Collection to be added
*/
virtual void add(PxCollection& collection) = 0;
/**
\brief Removes all PxBase objects of collection from this collection.
PxBase objects not present in this collection are ignored. Ids of objects
which are removed are also removed.
\param[in] collection Collection to be removed
*/
virtual void remove(PxCollection& collection) = 0;
/**
\brief Gets number of PxBase objects in this collection.
\return Number of objects in this collection
*/
virtual PxU32 getNbObjects() const = 0;
/**
\brief Gets the PxBase object of this collection given its index.
\param[in] index PxBase index in [0, getNbObjects())
\return PxBase object at index index
*/
virtual PxBase& getObject(PxU32 index) const = 0;
/**
\brief Copies member PxBase pointers to a user specified buffer.
\param[out] userBuffer Array of PxBase pointers
\param[in] bufferSize Capacity of userBuffer
\param[in] startIndex Offset into list of member PxBase objects
\return number of members PxBase objects that have been written to the userBuffer
*/
virtual PxU32 getObjects(PxBase** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Looks for a PxBase object given a PxSerialObjectId value.
If there is no PxBase object in the collection with the given id, NULL is returned.
\param[in] id PxSerialObjectId value to look for
\return PxBase object with the given id value or NULL
*/
virtual PxBase* find(PxSerialObjectId id) const = 0;
/**
\brief Gets number of PxSerialObjectId names in this collection.
\return Number of PxSerialObjectId names in this collection
*/
virtual PxU32 getNbIds() const = 0;
/**
\brief Copies member PxSerialObjectId values to a user specified buffer.
\param[out] userBuffer Array of PxSerialObjectId values
\param[in] bufferSize Capacity of userBuffer
\param[in] startIndex Offset into list of member PxSerialObjectId values
\return number of members PxSerialObjectId values that have been written to the userBuffer
*/
virtual PxU32 getIds(PxSerialObjectId* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Gets the PxSerialObjectId name of a PxBase object within the collection.
The PxBase object needs to be a member of the collection.
\param[in] object PxBase object to get id for
\return PxSerialObjectId name of the object or PX_SERIAL_OBJECT_ID_INVALID if the object is unnamed
*/
virtual PxSerialObjectId getId(const PxBase& object) const = 0;
/**
\brief Deletes a collection object.
This function only deletes the collection object, i.e. the container class. It doesn't delete objects
that are part of the collection.
@see PxCreateCollection()
*/
virtual void release() = 0;
protected:
PxCollection() {}
virtual ~PxCollection() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/**
\brief Creates a collection object.
Objects can only be serialized or deserialized through a collection.
For serialization, users must add objects to the collection and serialize the collection as a whole.
For deserialization, the system gives back a collection of deserialized objects to users.
\return The new collection object.
@see PxCollection, PxCollection::release()
*/
PX_C_EXPORT PX_PHYSX_COMMON_API physx::PxCollection* PX_CALL_CONV PxCreateCollection();
/** @} */
#endif
| 9,674 | C | 33.802158 | 114 | 0.74478 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxBase.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_BASE_H
#define PX_BASE_H
/** \addtogroup common
@{
*/
#include "foundation/PxFlags.h"
#include "foundation/PxString.h"
#include "foundation/PxFoundation.h"
#include "common/PxSerialFramework.h"
#include "common/PxCollection.h"
#include "common/PxTypeInfo.h"
#include "foundation/PxAssert.h"
#define PX_IS_KIND_OF(query, classname, baseclass) \
PX_ASSERT(query != NULL); \
if(query == NULL) \
{ \
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "isKindOf called with invalid string"); \
return false; \
} \
return !Pxstrcmp(classname, query) || baseclass::isKindOf(query)
#if !PX_DOXYGEN
namespace physx
{
#endif
typedef PxU16 PxType;
/**
\brief Flags for PxBase.
*/
struct PxBaseFlag
{
enum Enum
{
eOWNS_MEMORY = (1<<0),
eIS_RELEASABLE = (1<<1)
};
};
typedef PxFlags<PxBaseFlag::Enum, PxU16> PxBaseFlags;
PX_FLAGS_OPERATORS(PxBaseFlag::Enum, PxU16)
/**
\brief Base class for objects that can be members of a PxCollection.
All PxBase sub-classes can be serialized.
@see PxCollection
*/
class PxBase
{
public:
/**
\brief Releases the PxBase instance, please check documentation of release in derived class.
*/
virtual void release() = 0;
/**
\brief Returns string name of dynamic type.
\return Class name of most derived type of this object.
*/
virtual const char* getConcreteTypeName() const = 0;
/* brief Implements dynamic cast functionality.
Example use:
if(actor->is<PxRigidDynamic>()) {...}
\return A pointer to the specified type if object matches, otherwise NULL
*/
template<class T> T* is() { return typeMatch<T>() ? static_cast<T*>(this) : NULL; }
/* brief Implements dynamic cast functionality for const objects.
Example use:
if(actor->is<PxRigidDynamic>()) {...}
\return A pointer to the specified type if object matches, otherwise NULL
*/
template<class T> const T* is() const { return typeMatch<T>() ? static_cast<const T*>(this) : NULL; }
/**
\brief Returns concrete type of object.
\return PxConcreteType::Enum of serialized object
@see PxConcreteType
*/
PX_FORCE_INLINE PxType getConcreteType() const { return mConcreteType; }
/**
\brief Set PxBaseFlag
\param[in] flag The flag to be set
\param[in] value The flags new value
*/
PX_FORCE_INLINE void setBaseFlag(PxBaseFlag::Enum flag, bool value) { mBaseFlags = value ? mBaseFlags|flag : mBaseFlags&~flag; }
/**
\brief Set PxBaseFlags
\param[in] inFlags The flags to be set
@see PxBaseFlags
*/
PX_FORCE_INLINE void setBaseFlags(PxBaseFlags inFlags) { mBaseFlags = inFlags; }
/**
\brief Returns PxBaseFlags
\return PxBaseFlags
@see PxBaseFlags
*/
PX_FORCE_INLINE PxBaseFlags getBaseFlags() const { return mBaseFlags; }
/**
\brief Whether the object is subordinate.
A class is subordinate, if it can only be instantiated in the context of another class.
\return Whether the class is subordinate
@see PxSerialization::isSerializable
*/
virtual bool isReleasable() const { return mBaseFlags & PxBaseFlag::eIS_RELEASABLE; }
protected:
/**
\brief Constructor setting concrete type and base flags.
*/
PX_INLINE PxBase(PxType concreteType, PxBaseFlags baseFlags)
: mConcreteType(concreteType), mBaseFlags(baseFlags), mBuiltInRefCount(1) {}
/**
\brief Deserialization constructor setting base flags.
*/
PX_INLINE PxBase(PxBaseFlags baseFlags) : mBaseFlags(baseFlags)
{
PX_ASSERT(mBuiltInRefCount == 1);
}
/**
\brief Destructor.
*/
virtual ~PxBase() {}
/**
\brief Returns whether a given type name matches with the type of this instance
*/
virtual bool isKindOf(const char* superClass) const { return !Pxstrcmp(superClass, "PxBase"); }
template<class T> bool typeMatch() const
{
return PxU32(PxTypeInfo<T>::eFastTypeId)!=PxU32(PxConcreteType::eUNDEFINED) ?
PxU32(getConcreteType()) == PxU32(PxTypeInfo<T>::eFastTypeId) : isKindOf(PxTypeInfo<T>::name());
}
private:
friend void getBinaryMetaData_PxBase(PxOutputStream& stream);
protected:
PxType mConcreteType; // concrete type identifier - see PxConcreteType.
PxBaseFlags mBaseFlags; // internal flags
PxU32 mBuiltInRefCount;
};
/**
\brief Base class for ref-counted objects.
*/
class PxRefCounted : public PxBase
{
public:
/**
\brief Decrements the reference count of the object and releases it if the new reference count is zero.
*/
virtual void release() = 0;
/**
\brief Returns the reference count of the object.
At creation, the reference count of the object is 1. Every other object referencing this object increments the
count by 1. When the reference count reaches 0, and only then, the object gets destroyed automatically.
\return the current reference count.
*/
virtual PxU32 getReferenceCount() const = 0;
/**
\brief Acquires a counted reference to this object.
This method increases the reference count of the object by 1. Decrement the reference count by calling release()
*/
virtual void acquireReference() = 0;
protected:
virtual void onRefCountZero() { delete this; }
PX_INLINE PxRefCounted(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxRefCounted(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxRefCounted() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRefCounted", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 7,921 | C | 31.467213 | 131 | 0.655599 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxRenderBuffer.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_RENDER_BUFFER_H
#define PX_RENDER_BUFFER_H
/** \addtogroup common
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVec3.h"
#include "foundation/PxMat33.h"
#include "foundation/PxBounds3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Default color values used for debug rendering.
*/
struct PxDebugColor
{
enum Enum
{
eARGB_BLACK = 0xff000000,
eARGB_RED = 0xffff0000,
eARGB_GREEN = 0xff00ff00,
eARGB_BLUE = 0xff0000ff,
eARGB_YELLOW = 0xffffff00,
eARGB_MAGENTA = 0xffff00ff,
eARGB_CYAN = 0xff00ffff,
eARGB_WHITE = 0xffffffff,
eARGB_GREY = 0xff808080,
eARGB_DARKRED = 0xff880000,
eARGB_DARKGREEN = 0xff008800,
eARGB_DARKBLUE = 0xff000088
};
};
/**
\brief Used to store a single point and colour for debug rendering.
*/
struct PxDebugPoint
{
PxDebugPoint(const PxVec3& p, const PxU32& c)
: pos(p), color(c) {}
PxVec3 pos;
PxU32 color;
};
/**
\brief Used to store a single line and colour for debug rendering.
*/
struct PxDebugLine
{
PxDebugLine(const PxVec3& p0, const PxVec3& p1, const PxU32& c)
: pos0(p0), color0(c), pos1(p1), color1(c) {}
PxVec3 pos0;
PxU32 color0;
PxVec3 pos1;
PxU32 color1;
};
/**
\brief Used to store a single triangle and colour for debug rendering.
*/
struct PxDebugTriangle
{
PxDebugTriangle(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxU32& c)
: pos0(p0), color0(c), pos1(p1), color1(c), pos2(p2), color2(c) {}
PxVec3 pos0;
PxU32 color0;
PxVec3 pos1;
PxU32 color1;
PxVec3 pos2;
PxU32 color2;
};
/**
\brief Used to store a text for debug rendering. Doesn't own 'string' array.
*/
struct PxDebugText
{
PxDebugText() : string(0)
{
}
PxDebugText(const PxVec3& pos, const PxReal& sz, const PxU32& clr, const char* str)
: position(pos), size(sz), color(clr), string(str)
{
}
PxVec3 position;
PxReal size;
PxU32 color;
const char* string;
};
/**
\brief Interface for points, lines, triangles, and text buffer.
*/
class PxRenderBuffer
{
public:
virtual ~PxRenderBuffer() {}
virtual PxU32 getNbPoints() const = 0;
virtual const PxDebugPoint* getPoints() const = 0;
virtual void addPoint(const PxDebugPoint& point) = 0;
virtual PxU32 getNbLines() const = 0;
virtual const PxDebugLine* getLines() const = 0;
virtual void addLine(const PxDebugLine& line) = 0;
virtual PxDebugLine* reserveLines(const PxU32 nbLines) = 0;
virtual PxDebugPoint* reservePoints(const PxU32 nbLines) = 0;
virtual PxU32 getNbTriangles() const = 0;
virtual const PxDebugTriangle* getTriangles() const = 0;
virtual void addTriangle(const PxDebugTriangle& triangle) = 0;
virtual void append(const PxRenderBuffer& other) = 0;
virtual void clear() = 0;
virtual void shift(const PxVec3& delta) = 0;
virtual bool empty() const = 0;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,538 | C | 26.017857 | 86 | 0.728515 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxSerializer.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_SERIALIZER_H
#define PX_SERIALIZER_H
/** \addtogroup extensions
@{
*/
#include "foundation/PxAssert.h"
#include "foundation/PxAllocatorCallback.h"
#include "foundation/PxFoundation.h"
#include "common/PxSerialFramework.h"
#include "common/PxCollection.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Serialization interface class.
PxSerializer is used to extend serializable PxBase classes with serialization functionality. The
interface is structured such that per-class adapter instances can be used as opposed to per-object
adapter instances, avoiding per object allocations. Hence the methods take a reference to PxBase as a parameter.
The PxSerializer interface needs to be implemented for binary or RepX serialization to work on custom
types. If only RepX serialization is needed, some methods can be left empty, as they are only needed
for binary serialization.
A default implementation is available as a template adapter (PxSerializerDefaultAdapter).
@see PxSerializerDefaultAdapter, PX_NEW_SERIALIZER_ADAPTER, PxSerializationRegistry::registerSerializer
*/
class PxSerializer
{
public:
/**********************************************************************************************************************/
/** @name Basics needed for Binary- and RepX-Serialization
*/
//@{
/**
\brief Returns string name of dynamic type.
\return Class name of most derived type of this object.
*/
virtual const char* getConcreteTypeName() const = 0;
/**
\brief Adds required objects to the collection.
This method does not add the required objects recursively, e.g. objects required by required objects.
@see PxCollection, PxSerialization::complete
*/
virtual void requiresObjects(PxBase&, PxProcessPxBaseCallback&) const = 0;
/**
\brief Whether the object is subordinate.
A class is subordinate, if it can only be instantiated in the context of another class.
\return Whether the class is subordinate
@see PxSerialization::isSerializable
*/
virtual bool isSubordinate() const = 0;
//@}
/**********************************************************************************************************************/
/**********************************************************************************************************************/
/** @name Functionality needed for Binary Serialization only
*/
//@{
/**
\brief Exports object's extra data to stream.
*/
virtual void exportExtraData(PxBase&, PxSerializationContext&) const = 0;
/**
\brief Exports object's data to stream.
*/
virtual void exportData(PxBase&, PxSerializationContext&) const = 0;
/**
\brief Register references that the object maintains to other objects.
*/
virtual void registerReferences(PxBase& obj, PxSerializationContext& s) const = 0;
/**
\brief Returns size needed to create the class instance.
\return sizeof class instance.
*/
virtual size_t getClassSize() const = 0;
/**
\brief Create object at a given address, resolve references and import extra data.
\param address Location at which object is created. Address is increased by the size of the created object.
\param context Context for reading external data and resolving references.
\return Created PxBase pointer (needs to be identical to address before increment).
*/
virtual PxBase* createObject(PxU8*& address, PxDeserializationContext& context) const = 0;
//@}
/**********************************************************************************************************************/
virtual ~PxSerializer() {}
};
/**
\brief Default PxSerializer implementation.
*/
template<class T>
class PxSerializerDefaultAdapter : public PxSerializer
{
public:
/************************************************************************************************/
/** @name Basics needed for Binary- and RepX-Serialization
*/
//@{
PxSerializerDefaultAdapter(const char* name) : mTypeName(name){}
virtual const char* getConcreteTypeName() const
{
return mTypeName;
}
virtual void requiresObjects(PxBase& obj, PxProcessPxBaseCallback& c) const
{
T& t = static_cast<T&>(obj);
t.requiresObjects(c);
}
virtual bool isSubordinate() const
{
return false;
}
//@}
/************************************************************************************************/
/** @name Functionality needed for Binary Serialization only
*/
//@{
// object methods
virtual void exportExtraData(PxBase& obj, PxSerializationContext& s) const
{
T& t = static_cast<T&>(obj);
t.exportExtraData(s);
}
virtual void exportData(PxBase& obj, PxSerializationContext& s) const
{
PxAllocatorCallback& allocator = *PxGetAllocatorCallback();
T* copy = reinterpret_cast<T*>(allocator.allocate(sizeof(T), "TmpAllocExportData", PX_FL));
PxMemCopy(copy, &obj, sizeof(T));
copy->preExportDataReset();
s.writeData(copy, sizeof(T));
allocator.deallocate(copy);
}
virtual void registerReferences(PxBase& obj, PxSerializationContext& s) const
{
T& t = static_cast<T&>(obj);
s.registerReference(obj, PX_SERIAL_REF_KIND_PXBASE, size_t(&obj));
struct RequiresCallback : public PxProcessPxBaseCallback
{
RequiresCallback(PxSerializationContext& c) : context(c) {}
RequiresCallback& operator=(RequiresCallback&) { PX_ASSERT(0); return *this; }
void process(physx::PxBase& base)
{
context.registerReference(base, PX_SERIAL_REF_KIND_PXBASE, size_t(&base));
}
PxSerializationContext& context;
};
RequiresCallback callback(s);
t.requiresObjects(callback);
}
// class methods
virtual size_t getClassSize() const
{
return sizeof(T);
}
virtual PxBase* createObject(PxU8*& address, PxDeserializationContext& context) const
{
return T::createObject(address, context);
}
//@}
/************************************************************************************************/
private:
const char* mTypeName;
};
/**
\brief Preprocessor Macro to simplify adapter creation.
Note: that the allocator used for creation needs to match with the one used in PX_DELETE_SERIALIZER_ADAPTER.
*/
#define PX_NEW_SERIALIZER_ADAPTER(x) \
*new( PxGetAllocatorCallback()->allocate(sizeof(PxSerializerDefaultAdapter<x>), \
"PxSerializerDefaultAdapter", PX_FL)) PxSerializerDefaultAdapter<x>(#x)
/**
\brief Preprocessor Macro to simplify adapter deletion.
*/
#define PX_DELETE_SERIALIZER_ADAPTER(x) \
{ PxSerializer* s = x; if (s) { s->~PxSerializer(); PxGetAllocatorCallback()->deallocate(s); } }
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 8,397 | C | 30.810606 | 121 | 0.660831 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxMetaDataFlags.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_METADATA_FLAGS_H
#define PX_METADATA_FLAGS_H
#include "foundation/Px.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Flags used to configure binary meta data entries, typically set through PX_DEF_BIN_METADATA defines.
@see PxMetaDataEntry
*/
struct PxMetaDataFlag
{
enum Enum
{
eCLASS = (1<<0), //!< declares a class
eVIRTUAL = (1<<1), //!< declares class to be virtual
eTYPEDEF = (1<<2), //!< declares a typedef
ePTR = (1<<3), //!< declares a pointer
eHANDLE = (1<<4), //!< declares a handle
eEXTRA_DATA = (1<<5), //!< declares extra data exported with PxSerializer::exportExtraData
eEXTRA_ITEM = (1<<6), //!< specifies one element of extra data
eEXTRA_ITEMS = (1<<7), //!< specifies an array of extra data
eEXTRA_NAME = (1<<8), //!< specifies a name of extra data
eUNION = (1<<9), //!< declares a union
ePADDING = (1<<10), //!< declares explicit padding data
eALIGNMENT = (1<<11), //!< declares aligned data
eCOUNT_MASK_MSB = (1<<12), //!< specifies that the count value's most significant bit needs to be masked out
eCOUNT_SKIP_IF_ONE = (1<<13), //!< specifies that the count value is treated as zero for a variable value of one - special case for single triangle meshes
eCONTROL_FLIP = (1<<14), //!< specifies that the control value is the negate of the variable value
eCONTROL_MASK = (1<<15), //!< specifies that the control value is masked - mask bits are assumed to be within eCONTROL_MASK_RANGE
eCONTROL_MASK_RANGE = 0x000000FF, //!< mask range allowed for eCONTROL_MASK
eFORCE_DWORD = 0x7fffffff
};
};
#if !PX_DOXYGEN
}
#endif
#endif
| 3,415 | C | 45.162162 | 159 | 0.702196 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxTolerancesScale.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_TOLERANCES_SCALE_H
#define PX_TOLERANCES_SCALE_H
/** \addtogroup common
@{
*/
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Class to define the scale at which simulation runs. Most simulation tolerances are
calculated in terms of the values here.
\note if you change the simulation scale, you will probably also wish to change the scene's
default value of gravity, and stable simulation will probably require changes to the scene's
bounceThreshold also.
*/
class PxTolerancesScale
{
public:
/**
\brief The approximate size of objects in the simulation.
For simulating roughly human-sized in metric units, 1 is a good choice.
If simulation is done in centimetres, use 100 instead. This is used to
estimate certain length-related tolerances.
*/
PxReal length;
/**
\brief The typical magnitude of velocities of objects in simulation. This is used to estimate
whether a contact should be treated as bouncing or resting based on its impact velocity,
and a kinetic energy threshold below which the simulation may put objects to sleep.
For normal physical environments, a good choice is the approximate speed of an object falling
under gravity for one second.
*/
PxReal speed;
/**
\brief constructor sets to default
\param[in] defaultLength Default length
\param[in] defaultSpeed Default speed
*/
PX_INLINE explicit PxTolerancesScale(float defaultLength=1.0f, float defaultSpeed=10.0f);
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid (returns always true).
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxTolerancesScale::PxTolerancesScale(float defaultLength, float defaultSpeed) :
length (defaultLength),
speed (defaultSpeed)
{
}
PX_INLINE bool PxTolerancesScale::isValid() const
{
return length>0.0f;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,629 | C | 32.611111 | 95 | 0.761091 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxRenderOutput.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_RENDER_OUTPUT_H
#define PX_RENDER_OUTPUT_H
#include "foundation/PxMat44.h"
#include "foundation/PxBasicTemplates.h"
#include "PxRenderBuffer.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class
#endif
/**
Output stream to fill RenderBuffer
*/
class PxRenderOutput
{
public:
enum Primitive
{
POINTS,
LINES,
LINESTRIP,
TRIANGLES,
TRIANGLESTRIP
};
PxRenderOutput(PxRenderBuffer& buffer)
: mPrim(POINTS),
mColor(0),
mVertex0(0.0f),
mVertex1(0.0f),
mVertexCount(0),
mTransform(PxIdentity),
mBuffer(buffer)
{
}
PX_INLINE PxRenderOutput& operator<<(Primitive prim);
PX_INLINE PxRenderOutput& operator<<(PxU32 color) ;
PX_INLINE PxRenderOutput& operator<<(const PxMat44& transform);
PX_INLINE PxRenderOutput& operator<<(const PxTransform& t);
PX_INLINE PxRenderOutput& operator<<(const PxVec3& vertex); //AM: Don't use this! Slow! Deprecated!
PX_INLINE PxDebugLine* reserveSegments(PxU32 nbSegments);
PX_INLINE PxDebugPoint* reservePoints(PxU32 nbSegments);
PX_INLINE void outputSegment(const PxVec3& v0, const PxVec3& v1);
PX_INLINE PxRenderOutput& outputCapsule(PxF32 radius, PxF32 halfHeight, const PxMat44& absPose);
private:
PxRenderOutput& operator=(const PxRenderOutput&);
Primitive mPrim;
PxU32 mColor;
PxVec3 mVertex0, mVertex1;
PxU32 mVertexCount;
PxMat44 mTransform;
PxRenderBuffer& mBuffer;
};
struct PxDebugBox
{
explicit PxDebugBox(const PxVec3& extents, bool wireframe_ = true)
: minimum(-extents), maximum(extents), wireframe(wireframe_) {}
explicit PxDebugBox(const PxVec3& pos, const PxVec3& extents, bool wireframe_ = true)
: minimum(pos - extents), maximum(pos + extents), wireframe(wireframe_) {}
explicit PxDebugBox(const PxBounds3& bounds, bool wireframe_ = true)
: minimum(bounds.minimum), maximum(bounds.maximum), wireframe(wireframe_) {}
PxVec3 minimum, maximum;
bool wireframe;
};
PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugBox& box)
{
if (box.wireframe)
{
out << PxRenderOutput::LINESTRIP;
out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z);
out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z);
out << PxVec3(box.maximum.x, box.maximum.y, box.minimum.z);
out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z);
out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z);
out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z);
out << PxVec3(box.maximum.x, box.minimum.y, box.maximum.z);
out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z);
out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z);
out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z);
out << PxRenderOutput::LINES;
out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z);
out << PxVec3(box.maximum.x, box.minimum.y, box.maximum.z);
out << PxVec3(box.maximum.x, box.maximum.y, box.minimum.z);
out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z);
out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z);
out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z);
}
else
{
out << PxRenderOutput::TRIANGLESTRIP;
out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z); // 0
out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z); // 2
out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z); // 1
out << PxVec3(box.maximum.x, box.maximum.y, box.minimum.z); // 3
out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z); // 7
out << PxVec3(box.minimum.x, box.maximum.y, box.minimum.z); // 2
out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z); // 6
out << PxVec3(box.minimum.x, box.minimum.y, box.minimum.z); // 0
out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z); // 4
out << PxVec3(box.maximum.x, box.minimum.y, box.minimum.z); // 1
out << PxVec3(box.maximum.x, box.minimum.y, box.maximum.z); // 5
out << PxVec3(box.maximum.x, box.maximum.y, box.maximum.z); // 7
out << PxVec3(box.minimum.x, box.minimum.y, box.maximum.z); // 4
out << PxVec3(box.minimum.x, box.maximum.y, box.maximum.z); // 6
}
return out;
}
struct PxDebugArrow
{
PxDebugArrow(const PxVec3& pos, const PxVec3& vec)
: base(pos), tip(pos + vec), headLength(vec.magnitude()*0.15f) {}
PxDebugArrow(const PxVec3& pos, const PxVec3& vec, PxReal headLength_)
: base(pos), tip(pos + vec), headLength(headLength_) {}
PxVec3 base, tip;
PxReal headLength;
};
PX_FORCE_INLINE void normalToTangents(const PxVec3& normal, PxVec3& tangent0, PxVec3& tangent1)
{
tangent0 = PxAbs(normal.x) < 0.70710678f ? PxVec3(0, -normal.z, normal.y) : PxVec3(-normal.y, normal.x, 0);
tangent0.normalize();
tangent1 = normal.cross(tangent0);
}
PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugArrow& arrow)
{
PxVec3 t0 = arrow.tip - arrow.base, t1, t2;
t0.normalize();
normalToTangents(t0, t1, t2);
const PxReal tipAngle = 0.25f;
t1 *= arrow.headLength * tipAngle;
t2 *= arrow.headLength * tipAngle * PxSqrt(3.0f);
PxVec3 headBase = arrow.tip - t0 * arrow.headLength;
out << PxRenderOutput::LINES;
out << arrow.base << arrow.tip;
out << PxRenderOutput::TRIANGLESTRIP;
out << arrow.tip;
out << headBase + t1 + t1;
out << headBase - t1 - t2;
out << headBase - t1 + t2;
out << arrow.tip;
out << headBase + t1 + t1;
return out;
}
struct PxDebugBasis
{
PxDebugBasis(const PxVec3& ext, PxU32 cX = PxU32(PxDebugColor::eARGB_RED),
PxU32 cY = PxU32(PxDebugColor::eARGB_GREEN), PxU32 cZ = PxU32(PxDebugColor::eARGB_BLUE))
: extends(ext), colorX(cX), colorY(cY), colorZ(cZ) {}
PxVec3 extends;
PxU32 colorX, colorY, colorZ;
};
PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugBasis& basis)
{
const PxReal headLength = basis.extends.magnitude() * 0.15f;
out << basis.colorX << PxDebugArrow(PxVec3(0.0f), PxVec3(basis.extends.x, 0, 0), headLength);
out << basis.colorY << PxDebugArrow(PxVec3(0.0f), PxVec3(0, basis.extends.y, 0), headLength);
out << basis.colorZ << PxDebugArrow(PxVec3(0.0f), PxVec3(0, 0, basis.extends.z), headLength);
return out;
}
struct PxDebugCircle
{
PxDebugCircle(PxU32 s, PxReal r)
: nSegments(s), radius(r) {}
PxU32 nSegments;
PxReal radius;
};
PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugCircle& circle)
{
const PxF32 step = PxTwoPi / PxF32(circle.nSegments);
PxF32 angle = 0;
out << PxRenderOutput::LINESTRIP;
for (PxU32 i = 0; i < circle.nSegments; i++, angle += step)
out << PxVec3(circle.radius * PxSin(angle), circle.radius * PxCos(angle), 0);
out << PxVec3(0, circle.radius, 0);
return out;
}
struct PxDebugArc
{
PxDebugArc(PxU32 s, PxReal r, PxReal minAng, PxReal maxAng)
: nSegments(s), radius(r), minAngle(minAng), maxAngle(maxAng) {}
PxU32 nSegments;
PxReal radius;
PxReal minAngle, maxAngle;
};
PX_FORCE_INLINE PxRenderOutput& operator<<(PxRenderOutput& out, const PxDebugArc& arc)
{
const PxF32 step = (arc.maxAngle - arc.minAngle) / PxF32(arc.nSegments);
PxF32 angle = arc.minAngle;
out << PxRenderOutput::LINESTRIP;
for (PxU32 i = 0; i < arc.nSegments; i++, angle += step)
out << PxVec3(arc.radius * PxSin(angle), arc.radius * PxCos(angle), 0);
out << PxVec3(arc.radius * PxSin(arc.maxAngle), arc.radius * PxCos(arc.maxAngle), 0);
return out;
}
PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(Primitive prim)
{
mPrim = prim;
mVertexCount = 0;
return *this;
}
PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(PxU32 color)
{
mColor = color;
return *this;
}
PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(const PxMat44& transform)
{
mTransform = transform;
return *this;
}
PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(const PxTransform& t)
{
mTransform = PxMat44(t);
return *this;
}
PX_INLINE PxRenderOutput& PxRenderOutput::operator<<(const PxVec3& vertexIn)
{
// apply transformation
const PxVec3 vertex = mTransform.transform(vertexIn);
++mVertexCount;
// add primitive to render buffer
switch (mPrim)
{
case POINTS:
mBuffer.addPoint(PxDebugPoint(vertex, mColor)); break;
case LINES:
if (mVertexCount == 2)
{
mBuffer.addLine(PxDebugLine(mVertex0, vertex, mColor));
mVertexCount = 0;
}
break;
case LINESTRIP:
if (mVertexCount >= 2)
mBuffer.addLine(PxDebugLine(mVertex0, vertex, mColor));
break;
case TRIANGLES:
if (mVertexCount == 3)
{
mBuffer.addTriangle(PxDebugTriangle(mVertex1, mVertex0, vertex, mColor));
mVertexCount = 0;
}
break;
case TRIANGLESTRIP:
if (mVertexCount >= 3)
mBuffer.addTriangle(PxDebugTriangle(
(mVertexCount & 0x1) ? mVertex0 : mVertex1,
(mVertexCount & 0x1) ? mVertex1 : mVertex0, vertex, mColor));
break;
}
// cache the last 2 vertices (for strips)
if (1 < mVertexCount)
{
mVertex1 = mVertex0;
mVertex0 = vertex;
}
else
{
mVertex0 = vertex;
}
return *this;
}
PX_INLINE PxDebugLine* PxRenderOutput::reserveSegments(PxU32 nbSegments)
{
return mBuffer.reserveLines(nbSegments);
}
PX_INLINE PxDebugPoint* PxRenderOutput::reservePoints(PxU32 nbPoints)
{
return mBuffer.reservePoints(nbPoints);
}
// PT: using the operators is just too slow.
PX_INLINE void PxRenderOutput::outputSegment(const PxVec3& v0, const PxVec3& v1)
{
PxDebugLine* segment = mBuffer.reserveLines(1);
segment->pos0 = v0;
segment->pos1 = v1;
segment->color0 = segment->color1 = mColor;
}
PX_INLINE PxRenderOutput& PxRenderOutput::outputCapsule(PxF32 radius, PxF32 halfHeight, const PxMat44& absPose)
{
PxRenderOutput& out = *this;
const PxVec3 vleft2(-halfHeight, 0.0f, 0.0f);
PxMat44 left2 = absPose;
left2.column3 += PxVec4(left2.rotate(vleft2), 0.0f);
out << left2 << PxDebugArc(100, radius, PxPi, PxTwoPi);
PxMat44 rotPose = left2;
PxSwap(rotPose.column1, rotPose.column2);
rotPose.column1 = -rotPose.column1;
out << rotPose << PxDebugArc(100, radius, PxPi, PxTwoPi);
PxSwap(rotPose.column0, rotPose.column2);
rotPose.column0 = -rotPose.column0;
out << rotPose << PxDebugCircle(100, radius);
const PxVec3 vright2(halfHeight, 0.0f, 0.0f);
PxMat44 right2 = absPose;
right2.column3 += PxVec4(right2.rotate(vright2), 0.0f);
out << right2 << PxDebugArc(100, radius, 0.0f, PxPi);
rotPose = right2;
PxSwap(rotPose.column1, rotPose.column2);
rotPose.column1 = -rotPose.column1;
out << rotPose << PxDebugArc(100, radius, 0.0f, PxPi);
PxSwap(rotPose.column0, rotPose.column2);
rotPose.column0 = -rotPose.column0;
out << rotPose << PxDebugCircle(100, radius);
out << absPose;
out.outputSegment(absPose.transform(PxVec3(-halfHeight, radius, 0)),
absPose.transform(PxVec3(halfHeight, radius, 0)));
out.outputSegment(absPose.transform(PxVec3(-halfHeight, -radius, 0)),
absPose.transform(PxVec3(halfHeight, -radius, 0)));
out.outputSegment(absPose.transform(PxVec3(-halfHeight, 0, radius)),
absPose.transform(PxVec3(halfHeight, 0, radius)));
out.outputSegment(absPose.transform(PxVec3(-halfHeight, 0, -radius)),
absPose.transform(PxVec3(halfHeight, 0, -radius)));
return *this;
}
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 13,153 | C | 31.479012 | 112 | 0.699156 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxMetaData.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_METADATA_H
#define PX_METADATA_H
/** \addtogroup physics
@{
*/
#include "foundation/Px.h"
#include "foundation/PxIO.h"
#include "PxMetaDataFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Struct to store meta data definitions.
Note: The individual fields have different meaning depending on the meta data entry configuration.
*/
struct PxMetaDataEntry
{
const char* type; //!< Field type (bool, byte, quaternion, etc)
const char* name; //!< Field name (appears exactly as in the source file)
PxU32 offset; //!< Offset from the start of the class (ie from "this", field is located at "this"+Offset)
PxU32 size; //!< sizeof(Type)
PxU32 count; //!< Number of items of type Type (0 for dynamic sizes)
PxU32 offsetSize; //!< Offset of dynamic size param, for dynamic arrays
PxU32 flags; //!< Field parameters
PxU32 alignment; //!< Explicit alignment
};
#define PX_STORE_METADATA(stream, metaData) stream.write(&metaData, sizeof(PxMetaDataEntry))
#define PX_SIZE_OF(Class, Member) sizeof((reinterpret_cast<Class*>(0))->Member)
/**
\brief specifies a binary metadata entry for a member variable of a class
*/
#define PX_DEF_BIN_METADATA_ITEM(stream, Class, type, name, flags) \
{ \
PxMetaDataEntry tmp = { #type, #name, PxU32(PX_OFFSET_OF_RT(Class, name)), PX_SIZE_OF(Class, name), \
1, 0, flags, 0}; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for a member array variable of a class
\details similar to PX_DEF_BIN_METADATA_ITEMS_AUTO but for cases with mismatch between specified type and array type
*/
#define PX_DEF_BIN_METADATA_ITEMS(stream, Class, type, name, flags, count) \
{ \
PxMetaDataEntry tmp = { #type, #name, PxU32(PX_OFFSET_OF_RT(Class, name)), PX_SIZE_OF(Class, name), \
count, 0, flags, 0}; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for a member array variable of a class
\details similar to PX_DEF_BIN_METADATA_ITEMS but automatically detects the array length, which only works when the specified
type matches the type of the array - does not support PxMetaDataFlag::ePTR
*/
#define PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Class, type, name, flags) \
{ \
PxMetaDataEntry tmp = { #type, #name, PxU32(PX_OFFSET_OF_RT(Class, name)), PX_SIZE_OF(Class, name), \
sizeof((reinterpret_cast<Class*>(0))->name)/sizeof(type), 0, flags, 0}; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for a class
*/
#define PX_DEF_BIN_METADATA_CLASS(stream, Class) \
{ \
PxMetaDataEntry tmp = { #Class, 0, 0, sizeof(Class), 0, 0, PxMetaDataFlag::eCLASS, 0 }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for a virtual class
*/
#define PX_DEF_BIN_METADATA_VCLASS(stream, Class) \
{ \
PxMetaDataEntry tmp = { #Class, 0, 0, sizeof(Class), 0, 0, PxMetaDataFlag::eCLASS|PxMetaDataFlag::eVIRTUAL, 0}; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for a typedef
*/
#define PX_DEF_BIN_METADATA_TYPEDEF(stream, newType, oldType) \
{ \
PxMetaDataEntry tmp = { #newType, #oldType, 0, 0, 0, 0, PxMetaDataFlag::eTYPEDEF, 0 }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for declaring a base class
*/
#define PX_DEF_BIN_METADATA_BASE_CLASS(stream, Class, BaseClass) \
{ \
Class* myClass = reinterpret_cast<Class*>(42); \
BaseClass* s = static_cast<BaseClass*>(myClass); \
const PxU32 offset = PxU32(size_t(s) - size_t(myClass)); \
PxMetaDataEntry tmp = { #Class, #BaseClass, offset, sizeof(Class), 0, 0, PxMetaDataFlag::eCLASS, 0 }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for a union
*/
#define PX_DEF_BIN_METADATA_UNION(stream, Class, name) \
{ \
PxMetaDataEntry tmp = { #Class, 0, PxU32(PX_OFFSET_OF_RT(Class, name)), PX_SIZE_OF(Class, name), \
1, 0, PxMetaDataFlag::eUNION, 0 }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for a particular member type of a union
*/
#define PX_DEF_BIN_METADATA_UNION_TYPE(stream, Class, type, enumValue) \
{ \
PxMetaDataEntry tmp = { #Class, #type, enumValue, 0, 0, 0, PxMetaDataFlag::eUNION, 0 }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for extra data
*/
#define PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, Class, type, control, align) \
{ \
PxMetaDataEntry tmp = { #type, 0, PxU32(PX_OFFSET_OF_RT(Class, control)), sizeof(type), 0, PxU32(PX_SIZE_OF(Class, control)), \
PxMetaDataFlag::eEXTRA_DATA|PxMetaDataFlag::eEXTRA_ITEM, align }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for an array of extra data
*/
#define PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, Class, type, control, count, flags, align) \
{ \
PxMetaDataEntry tmp = { #type, 0, PxU32(PX_OFFSET_OF_RT(Class, control)), PxU32(PX_SIZE_OF(Class, control)), \
PxU32(PX_OFFSET_OF_RT(Class, count)), PxU32(PX_SIZE_OF(Class, count)), \
PxMetaDataFlag::eEXTRA_DATA|PxMetaDataFlag::eEXTRA_ITEMS|flags, align }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for an array of extra data
additional to PX_DEF_BIN_METADATA_EXTRA_ITEMS a mask can be specified to interpret the control value
@see PxMetaDataFlag::eCONTROL_MASK
*/
#define PX_DEF_BIN_METADATA_EXTRA_ITEMS_MASKED_CONTROL(stream, Class, type, control, controlMask ,count, flags, align) \
{ \
PxMetaDataEntry tmp = { #type, 0, PxU32(PX_OFFSET_OF_RT(Class, control)), PxU32(PX_SIZE_OF(Class, control)), \
PxU32(PX_OFFSET_OF_RT(Class, count)), PxU32(PX_SIZE_OF(Class, count)), \
PxMetaDataFlag::eCONTROL_MASK|PxMetaDataFlag::eEXTRA_DATA|PxMetaDataFlag::eEXTRA_ITEMS|flags|(controlMask & PxMetaDataFlag::eCONTROL_MASK_RANGE) << 16, \
align}; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for an array of extra data
\details similar to PX_DEF_BIN_METADATA_EXTRA_ITEMS, but supporting no control - PxMetaDataFlag::ePTR is also not supported
*/
#define PX_DEF_BIN_METADATA_EXTRA_ARRAY(stream, Class, type, dyn_count, align, flags) \
{ \
PxMetaDataEntry tmp = { #type, 0, PxU32(PX_OFFSET_OF_RT(Class, dyn_count)), PX_SIZE_OF(Class, dyn_count), align, 0, \
PxMetaDataFlag::eEXTRA_DATA|flags, align }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry for an string of extra data
*/
#define PX_DEF_BIN_METADATA_EXTRA_NAME(stream, Class, control, align) \
{ \
PxMetaDataEntry tmp = { "char", "string", 0, 0, 0, 0, PxMetaDataFlag::eEXTRA_DATA|PxMetaDataFlag::eEXTRA_NAME, align }; \
PX_STORE_METADATA(stream, tmp); \
}
/**
\brief specifies a binary metadata entry declaring an extra data alignment for a class
*/
#define PX_DEF_BIN_METADATA_EXTRA_ALIGN(stream, Class, align) \
{ \
PxMetaDataEntry tmp = { "PxU8", "Alignment", 0, 0, 0, 0, PxMetaDataFlag::eEXTRA_DATA|PxMetaDataFlag::eALIGNMENT, align}; \
PX_STORE_METADATA(stream, tmp); \
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,013 | C | 38.709251 | 160 | 0.695329 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxTypeInfo.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_TYPE_INFO_H
#define PX_TYPE_INFO_H
/** \addtogroup common
@{
*/
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief an enumeration of concrete classes inheriting from PxBase
Enumeration space is reserved for future PhysX core types, PhysXExtensions,
PhysXVehicle and Custom application types.
@see PxBase, PxTypeInfo
*/
struct PxConcreteType
{
enum Enum
{
eUNDEFINED,
eHEIGHTFIELD,
eCONVEX_MESH,
eTRIANGLE_MESH_BVH33, // PX_DEPRECATED
eTRIANGLE_MESH_BVH34,
eTETRAHEDRON_MESH,
eSOFTBODY_MESH,
eRIGID_DYNAMIC,
eRIGID_STATIC,
eSHAPE,
eMATERIAL,
eSOFTBODY_MATERIAL,
eCLOTH_MATERIAL,
ePBD_MATERIAL,
eFLIP_MATERIAL,
eMPM_MATERIAL,
eCONSTRAINT,
eAGGREGATE,
eARTICULATION_REDUCED_COORDINATE,
eARTICULATION_LINK,
eARTICULATION_JOINT_REDUCED_COORDINATE,
eARTICULATION_SENSOR,
eARTICULATION_SPATIAL_TENDON,
eARTICULATION_FIXED_TENDON,
eARTICULATION_ATTACHMENT,
eARTICULATION_TENDON_JOINT,
ePRUNING_STRUCTURE,
eBVH,
eSOFT_BODY,
eSOFT_BODY_STATE,
ePBD_PARTICLESYSTEM,
eFLIP_PARTICLESYSTEM,
eMPM_PARTICLESYSTEM,
eFEM_CLOTH,
eHAIR_SYSTEM,
ePARTICLE_BUFFER,
ePARTICLE_DIFFUSE_BUFFER,
ePARTICLE_CLOTH_BUFFER,
ePARTICLE_RIGID_BUFFER,
ePHYSX_CORE_COUNT,
eFIRST_PHYSX_EXTENSION = 256,
eFIRST_VEHICLE_EXTENSION = 512,
eFIRST_USER_EXTENSION = 1024
};
};
/**
\brief a structure containing per-type information for types inheriting from PxBase
@see PxBase, PxConcreteType
*/
template<typename T> struct PxTypeInfo {};
#define PX_DEFINE_TYPEINFO(_name, _fastType) \
class _name; \
template <> struct PxTypeInfo<_name> { static const char* name() { return #_name; } enum { eFastTypeId = _fastType }; };
/* the semantics of the fastType are as follows: an object A can be cast to a type B if B's fastType is defined, and A has the same fastType.
* This implies that B has no concrete subclasses or superclasses.
*/
PX_DEFINE_TYPEINFO(PxBase, PxConcreteType::eUNDEFINED)
PX_DEFINE_TYPEINFO(PxMaterial, PxConcreteType::eMATERIAL)
PX_DEFINE_TYPEINFO(PxFEMSoftBodyMaterial, PxConcreteType::eSOFTBODY_MATERIAL)
PX_DEFINE_TYPEINFO(PxFEMClothMaterial, PxConcreteType::eCLOTH_MATERIAL)
PX_DEFINE_TYPEINFO(PxPBDMaterial, PxConcreteType::ePBD_MATERIAL)
PX_DEFINE_TYPEINFO(PxFLIPMaterial, PxConcreteType::eFLIP_MATERIAL)
PX_DEFINE_TYPEINFO(PxMPMMaterial, PxConcreteType::eMPM_MATERIAL)
PX_DEFINE_TYPEINFO(PxConvexMesh, PxConcreteType::eCONVEX_MESH)
PX_DEFINE_TYPEINFO(PxTriangleMesh, PxConcreteType::eUNDEFINED)
PX_DEFINE_TYPEINFO(PxBVH33TriangleMesh, PxConcreteType::eTRIANGLE_MESH_BVH33)
PX_DEFINE_TYPEINFO(PxBVH34TriangleMesh, PxConcreteType::eTRIANGLE_MESH_BVH34)
PX_DEFINE_TYPEINFO(PxTetrahedronMesh, PxConcreteType::eTETRAHEDRON_MESH)
PX_DEFINE_TYPEINFO(PxHeightField, PxConcreteType::eHEIGHTFIELD)
PX_DEFINE_TYPEINFO(PxActor, PxConcreteType::eUNDEFINED)
PX_DEFINE_TYPEINFO(PxRigidActor, PxConcreteType::eUNDEFINED)
PX_DEFINE_TYPEINFO(PxRigidBody, PxConcreteType::eUNDEFINED)
PX_DEFINE_TYPEINFO(PxRigidDynamic, PxConcreteType::eRIGID_DYNAMIC)
PX_DEFINE_TYPEINFO(PxRigidStatic, PxConcreteType::eRIGID_STATIC)
PX_DEFINE_TYPEINFO(PxArticulationLink, PxConcreteType::eARTICULATION_LINK)
PX_DEFINE_TYPEINFO(PxArticulationJointReducedCoordinate, PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE)
PX_DEFINE_TYPEINFO(PxArticulationReducedCoordinate, PxConcreteType::eARTICULATION_REDUCED_COORDINATE)
PX_DEFINE_TYPEINFO(PxAggregate, PxConcreteType::eAGGREGATE)
PX_DEFINE_TYPEINFO(PxConstraint, PxConcreteType::eCONSTRAINT)
PX_DEFINE_TYPEINFO(PxShape, PxConcreteType::eSHAPE)
PX_DEFINE_TYPEINFO(PxPruningStructure, PxConcreteType::ePRUNING_STRUCTURE)
PX_DEFINE_TYPEINFO(PxParticleSystem, PxConcreteType::eUNDEFINED)
PX_DEFINE_TYPEINFO(PxPBDParticleSystem, PxConcreteType::ePBD_PARTICLESYSTEM)
PX_DEFINE_TYPEINFO(PxFLIPParticleSystem, PxConcreteType::eFLIP_PARTICLESYSTEM)
PX_DEFINE_TYPEINFO(PxMPMParticleSystem, PxConcreteType::eMPM_PARTICLESYSTEM)
PX_DEFINE_TYPEINFO(PxSoftBody, PxConcreteType::eSOFT_BODY)
PX_DEFINE_TYPEINFO(PxFEMCloth, PxConcreteType::eFEM_CLOTH)
PX_DEFINE_TYPEINFO(PxHairSystem, PxConcreteType::eHAIR_SYSTEM)
PX_DEFINE_TYPEINFO(PxParticleBuffer, PxConcreteType::ePARTICLE_BUFFER)
PX_DEFINE_TYPEINFO(PxParticleAndDiffuseBuffer, PxConcreteType::ePARTICLE_DIFFUSE_BUFFER)
PX_DEFINE_TYPEINFO(PxParticleClothBuffer, PxConcreteType::ePARTICLE_CLOTH_BUFFER)
PX_DEFINE_TYPEINFO(PxParticleRigidBuffer, PxConcreteType::ePARTICLE_RIGID_BUFFER)
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,469 | C | 38.451219 | 141 | 0.765652 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxStringTable.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_STRING_TABLE_H
#define PX_STRING_TABLE_H
#include "foundation/PxPreprocessor.h"
/** \addtogroup physics
@{
*/
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
* \brief a table to manage strings. Strings allocated through this object are expected to be owned by this object.
*/
class PxStringTable
{
protected:
virtual ~PxStringTable(){}
public:
/**
* \brief Allocate a new string.
*
* \param[in] inSrc Source string, null terminated or null.
*
* \return *Always* a valid null terminated string. "" is returned if "" or null is passed in.
*/
virtual const char* allocateStr( const char* inSrc ) = 0;
/**
* Release the string table and all the strings associated with it.
*/
virtual void release() = 0;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,503 | C | 33.777777 | 116 | 0.737515 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxSerialFramework.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_SERIAL_FRAMEWORK_H
#define PX_SERIAL_FRAMEWORK_H
/** \addtogroup common
@{
*/
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
typedef PxU16 PxType;
class PxBase;
class PxSerializationContext;
class PxRepXSerializer;
class PxSerializer;
class PxPhysics;
class PxCollection;
//! Default serialization alignment
#define PX_SERIAL_ALIGN 16
//! Serialized input data must be aligned to this value
#define PX_SERIAL_FILE_ALIGN 128
//! PxSerialObjectId value for objects that do not have an ID
#define PX_SERIAL_OBJECT_ID_INVALID 0
//! ID type for PxBase objects in a PxCollection
typedef PxU64 PxSerialObjectId;
//! Bit to mark pointer type references, @see PxDeserializationContext
#define PX_SERIAL_REF_KIND_PTR_TYPE_BIT (1u<<31)
//! Reference kind value for PxBase objects
#define PX_SERIAL_REF_KIND_PXBASE (0 | PX_SERIAL_REF_KIND_PTR_TYPE_BIT)
//! Reference kind value for material indices
#define PX_SERIAL_REF_KIND_MATERIAL_IDX (1)
//! Used to fix multi-byte characters warning from gcc for situations like: PxU32 foo = 'CCTS';
#define PX_MAKE_FOURCC(a, b, c, d) ( (a) | ((b)<<8) | ((c)<<16) | ((d)<<24) )
/**
\brief Callback class used to process PxBase objects.
@see PxSerializer::requires
*/
class PxProcessPxBaseCallback
{
public:
virtual ~PxProcessPxBaseCallback() {}
virtual void process(PxBase&) = 0;
};
/**
\brief Binary serialization context class.
This class is used to register reference values and write object
and object extra data during serialization.
It is mainly used by the serialization framework. Except for custom
serializable types, users should not have to worry about it.
@see PxDeserializationContext
*/
class PxSerializationContext
{
public:
/**
\brief Registers a reference value corresponding to a PxBase object.
This method is assumed to be called in the implementation of PxSerializer::registerReferences for serialized
references that need to be resolved on deserialization.
A reference needs to be associated with exactly one PxBase object in either the collection or the
external references collection.
Different kinds of references are supported and need to be specified. In the most common case
(PX_SERIAL_REF_KIND_PXBASE) the PxBase object matches the reference value (which is the pointer
to the PxBase object). Integer references maybe registered as well (used for internal material
indices with PX_SERIAL_REF_KIND_MATERIAL_IDX). Other kinds could be added with the restriction that
for pointer types the kind value needs to be marked with the PX_SERIAL_REF_KIND_PTR_TYPE_BIT.
\param[in] base PxBase object associated with the reference
\param[in] kind What kind of reference this is (PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX or custom kind)
\param[in] reference Value of reference
@see PxDeserializationContext::resolveReference, PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX, PxSerializer::registerReferences
*/
virtual void registerReference(PxBase& base, PxU32 kind, size_t reference) = 0;
/**
\brief Returns the collection that is being serialized.
*/
virtual const PxCollection& getCollection() const = 0;
/**
\brief Serializes object data and object extra data.
This function is assumed to be called within the implementation of PxSerializer::exportData and PxSerializer::exportExtraData.
@see PxSerializer::exportData, PxSerializer::exportExtraData, PxSerializer::createObject, PxDeserializationContext::readExtraData
*/
virtual void writeData(const void* data, PxU32 size) = 0;
/**
\brief Aligns the serialized data.
This function is assumed to be called within the implementation of PxSerializer::exportData and PxSerializer::exportExtraData.
@see PxSerializer::exportData, PxSerializer::exportExtraData, PxDeserializationContext::alignExtraData
*/
virtual void alignData(PxU32 alignment = PX_SERIAL_ALIGN) = 0;
/**
\brief Helper function to write a name to the extraData if serialization is configured to save names.
This function is assumed to be called within the implementation of PxSerializer::exportExtraData.
@see PxSerialization::serializeCollectionToBinary, PxDeserializationContext::readName
*/
virtual void writeName(const char* name) = 0;
protected:
PxSerializationContext() {}
virtual ~PxSerializationContext() {}
};
/**
\brief Binary deserialization context class.
This class is used to resolve references and access extra data during deserialization.
It is mainly used by the serialization framework. Except for custom
serializable types, users should not have to worry about it.
@see PxSerializationContext
*/
class PxDeserializationContext
{
public:
/**
\brief Retrieves a pointer to a deserialized PxBase object given a corresponding deserialized reference value
This method is assumed to be called in the implementation of PxSerializer::createObject in order
to update reference values on deserialization.
To update a PxBase reference the corresponding deserialized pointer value needs to be provided in order to retrieve
the location of the corresponding deserialized PxBase object. (PxDeserializationContext::translatePxBase simplifies
this common case).
For other kinds of references the reverence values need to be updated by deduction given the corresponding PxBase instance.
\param[in] kind What kind of reference this is (PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX or custom kind)
\param[in] reference Deserialized reference value
\return PxBase object associated with the reference value
@see PxSerializationContext::registerReference, PX_SERIAL_REF_KIND_PXBASE, PX_SERIAL_REF_KIND_MATERIAL_IDX, translatePxBase
*/
virtual PxBase* resolveReference(PxU32 kind, size_t reference) const = 0;
/**
\brief Helper function to update PxBase pointer on deserialization
@see resolveReference, PX_SERIAL_REF_KIND_PXBASE
*/
template<typename T>
void translatePxBase(T*& base) { if (base) { base = static_cast<T*>(resolveReference(PX_SERIAL_REF_KIND_PXBASE, size_t(base))); } }
/**
\brief Helper function to read a name from the extra data during deserialization.
This function is assumed to be called within the implementation of PxSerializer::createObject.
@see PxSerializationContext::writeName
*/
PX_INLINE void readName(const char*& name)
{
PxU32 len = *reinterpret_cast<PxU32*>(mExtraDataAddress);
mExtraDataAddress += sizeof(len);
name = len ? reinterpret_cast<const char*>(mExtraDataAddress) : NULL;
mExtraDataAddress += len;
}
/**
\brief Function to read extra data during deserialization.
This function is assumed to be called within the implementation of PxSerializer::createObject.
@see PxSerializationContext::writeData, PxSerializer::createObject
*/
template<typename T>
PX_INLINE T* readExtraData(PxU32 count=1)
{
T* data = reinterpret_cast<T*>(mExtraDataAddress);
mExtraDataAddress += sizeof(T)*count;
return data;
}
/**
\brief Function to read extra data during deserialization optionally aligning the extra data stream before reading.
This function is assumed to be called within the implementation of PxSerializer::createObject.
@see PxSerializationContext::writeData, PxDeserializationContext::alignExtraData, PxSerializer::createObject
*/
template<typename T, PxU32 alignment>
PX_INLINE T* readExtraData(PxU32 count=1)
{
alignExtraData(alignment);
return readExtraData<T>(count);
}
/**
\brief Function to align the extra data stream to a power of 2 alignment
This function is assumed to be called within the implementation of PxSerializer::createObject.
@see PxSerializationContext::alignData, PxSerializer::createObject
*/
PX_INLINE void alignExtraData(PxU32 alignment = PX_SERIAL_ALIGN)
{
size_t addr = size_t(mExtraDataAddress);
addr = (addr+alignment-1)&~size_t(alignment-1);
mExtraDataAddress = reinterpret_cast<PxU8*>(addr);
}
protected:
PxDeserializationContext() {}
virtual ~PxDeserializationContext() {}
PxU8* mExtraDataAddress;
};
/**
\brief Callback type for exporting binary meta data for a serializable type.
\deprecated Binary conversion and binary meta data are deprecated.
@see PxSerializationRegistry::registerBinaryMetaDataCallback
\param stream Stream to store binary meta data.
*/
typedef PX_DEPRECATED void (*PxBinaryMetaDataCallback)(PxOutputStream& stream);
/**
\brief Class serving as a registry for XML (RepX) and binary serializable types.
In order to serialize and deserialize objects the application needs
to maintain an instance of this class. It can be created with
PxSerialization::createSerializationRegistry() and released with
PxSerializationRegistry::release().
@see PxSerialization::createSerializationRegistry
*/
class PxSerializationRegistry
{
public:
/************************************************************************************************/
/** @name Binary Serialization Functionality
*/
//@{
/**
\brief Register a serializer for a concrete type
\param type PxConcreteType corresponding to the serializer
\param serializer The PxSerializer to be registered
@see PxConcreteType, PxSerializer, PxSerializationRegistry::unregisterSerializer
*/
virtual void registerSerializer(PxType type, PxSerializer& serializer) = 0;
/**
\brief Unregister a serializer for a concrete type, and retrieves the corresponding serializer object.
\param type PxConcreteType for which the serializer should be unregistered
\return Unregistered serializer corresponding to type, NULL for types for which no serializer has been registered.
@see PxConcreteType, PxSerializationRegistry::registerSerializer, PxSerializationRegistry::release
*/
virtual PxSerializer* unregisterSerializer(PxType type) = 0;
/**
\brief Register binary meta data callback
\deprecated Binary conversion and binary meta data are deprecated.
The callback is executed when calling PxSerialization::dumpBinaryMetaData.
\param callback PxBinaryMetaDataCallback to be registered.
@see PxBinaryMetaDataCallback, PxSerialization::dumpBinaryMetaData
*/
PX_DEPRECATED virtual void registerBinaryMetaDataCallback(PxBinaryMetaDataCallback callback) = 0;
/**
\brief Returns PxSerializer corresponding to type
\param type PxConcreteType of the serializer requested.
\return Registered PxSerializer object corresponding to type
@see PxConcreteType
*/
virtual const PxSerializer* getSerializer(PxType type) const = 0;
//@}
/************************************************************************************************/
/** @name RepX (XML) Serialization Functionality
*/
//@{
/**
\brief Register a RepX serializer for a concrete type
\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics.
\param type PxConcreteType corresponding to the RepX serializer
\param serializer The PxRepXSerializer to be registered
@see PxConcreteType, PxRepXSerializer
*/
PX_DEPRECATED virtual void registerRepXSerializer(PxType type, PxRepXSerializer& serializer) = 0;
/**
\brief Unregister a RepX serializer for a concrete type, and retrieves the corresponding serializer object.
\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics.
\param type PxConcreteType for which the RepX serializer should be unregistered
\return Unregistered PxRepxSerializer corresponding to type, NULL for types for which no RepX serializer has been registered.
@see PxConcreteType, PxSerializationRegistry::registerRepXSerializer, PxSerializationRegistry::release
*/
PX_DEPRECATED virtual PxRepXSerializer* unregisterRepXSerializer(PxType type) = 0;
/**
\brief Returns RepX serializer given the corresponding type name
\deprecated Xml serialization is deprecated. An alternative serialization system is provided through USD Physics.
\param typeName Name of the type
\return Registered PxRepXSerializer object corresponding to type name
@see PxRepXSerializer, PxTypeInfo, PX_DEFINE_TYPEINFO
*/
PX_DEPRECATED virtual PxRepXSerializer* getRepXSerializer(const char* typeName) const = 0;
//@}
/************************************************************************************************/
/**
\brief Releases PxSerializationRegistry instance.
This unregisters all PhysX and PhysXExtension serializers. Make sure to unregister all custom type
serializers before releasing the PxSerializationRegistry.
@see PxSerializationRegistry::unregisterSerializer, PxSerializationRegistry::unregisterRepXSerializer
*/
virtual void release() = 0;
protected:
virtual ~PxSerializationRegistry(){}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 14,566 | C | 34.616137 | 142 | 0.758204 |
NVIDIA-Omniverse/PhysX/physx/include/common/PxCoreUtilityTypes.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_CORE_UTILITY_TYPES_H
#define PX_CORE_UTILITY_TYPES_H
/** \addtogroup common
@{
*/
#include "foundation/PxAssert.h"
#include "foundation/PxMemory.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxStridedData
{
/**
\brief The offset in bytes between consecutive samples in the data.
<b>Default:</b> 0
*/
PxU32 stride;
const void* data;
PxStridedData() : stride( 0 ), data( NULL ) {}
template<typename TDataType>
PX_INLINE const TDataType& at( PxU32 idx ) const
{
PxU32 theStride( stride );
if ( theStride == 0 )
theStride = sizeof( TDataType );
PxU32 offset( theStride * idx );
return *(reinterpret_cast<const TDataType*>( reinterpret_cast< const PxU8* >( data ) + offset ));
}
};
template<typename TDataType>
struct PxTypedStridedData
{
PxU32 stride;
const TDataType* data;
PxTypedStridedData()
: stride( 0 )
, data( NULL )
{
}
PxTypedStridedData(const TDataType* data_, PxU32 stride_ = 0)
: stride(stride_)
, data(data_)
{
}
PX_INLINE const TDataType& at(PxU32 idx) const
{
PxU32 theStride(stride);
if (theStride == 0)
theStride = sizeof(TDataType);
PxU32 offset(theStride * idx);
return *(reinterpret_cast<const TDataType*>(reinterpret_cast<const PxU8*>(data) + offset));
}
};
struct PxBoundedData : public PxStridedData
{
PxU32 count;
PxBoundedData() : count( 0 ) {}
};
template<PxU8 TNumBytes>
struct PxPadding
{
PxU8 mPadding[TNumBytes];
PxPadding()
{
for ( PxU8 idx =0; idx < TNumBytes; ++idx )
mPadding[idx] = 0;
}
};
template <PxU32 NB_ELEMENTS> class PxFixedSizeLookupTable
{
public:
PxFixedSizeLookupTable()
: mNbDataPairs(0)
{
}
PxFixedSizeLookupTable(const PxEMPTY) {}
PxFixedSizeLookupTable(const PxReal* dataPairs, const PxU32 numDataPairs)
{
PxMemCopy(mDataPairs,dataPairs,sizeof(PxReal)*2*numDataPairs);
mNbDataPairs=numDataPairs;
}
PxFixedSizeLookupTable(const PxFixedSizeLookupTable& src)
{
PxMemCopy(mDataPairs,src.mDataPairs,sizeof(PxReal)*2*src.mNbDataPairs);
mNbDataPairs=src.mNbDataPairs;
}
~PxFixedSizeLookupTable()
{
}
PxFixedSizeLookupTable& operator=(const PxFixedSizeLookupTable& src)
{
PxMemCopy(mDataPairs,src.mDataPairs,sizeof(PxReal)*2*src.mNbDataPairs);
mNbDataPairs=src.mNbDataPairs;
return *this;
}
PX_FORCE_INLINE void addPair(const PxReal x, const PxReal y)
{
PX_ASSERT(mNbDataPairs<NB_ELEMENTS);
mDataPairs[2*mNbDataPairs+0]=x;
mDataPairs[2*mNbDataPairs+1]=y;
mNbDataPairs++;
}
PX_FORCE_INLINE PxReal getYVal(const PxReal x) const
{
if(0==mNbDataPairs)
{
PX_ASSERT(false);
return 0;
}
if(1==mNbDataPairs || x<getX(0))
{
return getY(0);
}
PxReal x0=getX(0);
PxReal y0=getY(0);
for(PxU32 i=1;i<mNbDataPairs;i++)
{
const PxReal x1=getX(i);
const PxReal y1=getY(i);
if((x>=x0)&&(x<x1))
{
return (y0+(y1-y0)*(x-x0)/(x1-x0));
}
x0=x1;
y0=y1;
}
PX_ASSERT(x>=getX(mNbDataPairs-1));
return getY(mNbDataPairs-1);
}
PxU32 getNbDataPairs() const {return mNbDataPairs;}
void clear()
{
PxMemSet(mDataPairs, 0, NB_ELEMENTS*2*sizeof(PxReal));
mNbDataPairs = 0;
}
PX_FORCE_INLINE PxReal getX(const PxU32 i) const
{
return mDataPairs[2*i];
}
PX_FORCE_INLINE PxReal getY(const PxU32 i) const
{
return mDataPairs[2*i+1];
}
PxReal mDataPairs[2*NB_ELEMENTS];
PxU32 mNbDataPairs;
PxU32 mPad[3];
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 5,116 | C | 22.472477 | 99 | 0.712275 |
NVIDIA-Omniverse/PhysX/physx/include/common/windows/PxWindowsDelayLoadHook.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_WINDOWS_DELAY_LOAD_HOOK_H
#define PX_WINDOWS_DELAY_LOAD_HOOK_H
#include "foundation/PxPreprocessor.h"
#include "common/PxPhysXCommonConfig.h"
/** \addtogroup foundation
@{
*/
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief PxDelayLoadHook
This is a helper class for delay loading the PhysXCommon dll and PhysXFoundation dll.
If a PhysXCommon dll or PhysXFoundation dll with a non-default file name needs to be loaded,
PxDelayLoadHook can be sub-classed to provide the custom filenames.
Once the names are set, the instance must be set for use by PhysX.dll using PxSetPhysXDelayLoadHook(),
PhysXCooking.dll using PxSetPhysXCookingDelayLoadHook() or by PhysXCommon.dll using PxSetPhysXCommonDelayLoadHook().
@see PxSetPhysXDelayLoadHook(), PxSetPhysXCookingDelayLoadHook(), PxSetPhysXCommonDelayLoadHook()
*/
class PxDelayLoadHook
{
public:
PxDelayLoadHook() {}
virtual ~PxDelayLoadHook() {}
virtual const char* getPhysXFoundationDllName() const = 0;
virtual const char* getPhysXCommonDllName() const = 0;
protected:
private:
};
/**
\brief Sets delay load hook instance for PhysX dll.
\param[in] hook Delay load hook.
@see PxDelayLoadHook
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXDelayLoadHook(const physx::PxDelayLoadHook* hook);
/**
\brief Sets delay load hook instance for PhysXCooking dll.
\param[in] hook Delay load hook.
@see PxDelayLoadHook
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXCookingDelayLoadHook(const physx::PxDelayLoadHook* hook);
/**
\brief Sets delay load hook instance for PhysXCommon dll.
\param[in] hook Delay load hook.
@see PxDelayLoadHook
*/
PX_C_EXPORT PX_PHYSX_COMMON_API void PX_CALL_CONV PxSetPhysXCommonDelayLoadHook(const physx::PxDelayLoadHook* hook);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,560 | C | 34.257425 | 117 | 0.76236 |
NVIDIA-Omniverse/PhysX/physx/include/characterkinematic/PxController.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_CONTROLLER_H
#define PX_CONTROLLER_H
/** \addtogroup character
@{
*/
#include "characterkinematic/PxExtended.h"
#include "characterkinematic/PxControllerObstacles.h"
#include "PxQueryFiltering.h"
#include "foundation/PxErrorCallback.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief The type of controller, eg box, sphere or capsule.
*/
struct PxControllerShapeType
{
enum Enum
{
/**
\brief A box controller.
@see PxBoxController PxBoxControllerDesc
*/
eBOX,
/**
\brief A capsule controller
@see PxCapsuleController PxCapsuleControllerDesc
*/
eCAPSULE,
eFORCE_DWORD = 0x7fffffff
};
};
class PxShape;
class PxScene;
class PxController;
class PxRigidDynamic;
class PxMaterial;
struct PxFilterData;
class PxQueryFilterCallback;
class PxControllerBehaviorCallback;
class PxObstacleContext;
class PxObstacle;
/**
\brief specifies how a CCT interacts with non-walkable parts.
This is only used when slopeLimit is non zero. It is currently enabled for static actors only, and not supported for spheres or capsules.
*/
struct PxControllerNonWalkableMode
{
enum Enum
{
ePREVENT_CLIMBING, //!< Stops character from climbing up non-walkable slopes, but doesn't move it otherwise
ePREVENT_CLIMBING_AND_FORCE_SLIDING //!< Stops character from climbing up non-walkable slopes, and forces it to slide down those slopes
};
};
/**
\brief specifies which sides a character is colliding with.
*/
struct PxControllerCollisionFlag
{
enum Enum
{
eCOLLISION_SIDES = (1<<0), //!< Character is colliding to the sides.
eCOLLISION_UP = (1<<1), //!< Character has collision above.
eCOLLISION_DOWN = (1<<2) //!< Character has collision below.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxControllerCollisionFlag.
@see PxControllerCollisionFlag
*/
typedef PxFlags<PxControllerCollisionFlag::Enum, PxU8> PxControllerCollisionFlags;
PX_FLAGS_OPERATORS(PxControllerCollisionFlag::Enum, PxU8)
/**
\brief Describes a controller's internal state.
*/
struct PxControllerState
{
PxVec3 deltaXP; //!< delta position vector for the object the CCT is standing/riding on. Not always match the CCT delta when variable timesteps are used.
PxShape* touchedShape; //!< Shape on which the CCT is standing
PxRigidActor* touchedActor; //!< Actor owning 'touchedShape'
PxObstacleHandle touchedObstacleHandle; // Obstacle on which the CCT is standing
PxU32 collisionFlags; //!< Last known collision flags (PxControllerCollisionFlag)
bool standOnAnotherCCT; //!< Are we standing on another CCT?
bool standOnObstacle; //!< Are we standing on a user-defined obstacle?
bool isMovingUp; //!< is CCT moving up or not? (i.e. explicit jumping)
};
/**
\brief Describes a controller's internal statistics.
*/
struct PxControllerStats
{
PxU16 nbIterations;
PxU16 nbFullUpdates;
PxU16 nbPartialUpdates;
PxU16 nbTessellation;
};
/**
\brief Describes a generic CCT hit.
*/
struct PxControllerHit
{
PxController* controller; //!< Current controller
PxExtendedVec3 worldPos; //!< Contact position in world space
PxVec3 worldNormal; //!< Contact normal in world space
PxVec3 dir; //!< Motion direction
PxF32 length; //!< Motion length
};
/**
\brief Describes a hit between a CCT and a shape. Passed to onShapeHit()
@see PxUserControllerHitReport.onShapeHit()
*/
struct PxControllerShapeHit : public PxControllerHit
{
PxShape* shape; //!< Touched shape
PxRigidActor* actor; //!< Touched actor
PxU32 triangleIndex; //!< touched triangle index (only for meshes/heightfields)
};
/**
\brief Describes a hit between a CCT and another CCT. Passed to onControllerHit().
@see PxUserControllerHitReport.onControllerHit()
*/
struct PxControllersHit : public PxControllerHit
{
PxController* other; //!< Touched controller
};
/**
\brief Describes a hit between a CCT and a user-defined obstacle. Passed to onObstacleHit().
@see PxUserControllerHitReport.onObstacleHit() PxObstacleContext
*/
struct PxControllerObstacleHit : public PxControllerHit
{
const void* userData;
};
/**
\brief User callback class for character controller events.
\note Character controller hit reports are only generated when move is called.
@see PxControllerDesc.callback
*/
class PxUserControllerHitReport
{
public:
/**
\brief Called when current controller hits a shape.
This is called when the CCT moves and hits a shape. This will not be called when a moving shape hits a non-moving CCT.
\param[in] hit Provides information about the hit.
@see PxControllerShapeHit
*/
virtual void onShapeHit(const PxControllerShapeHit& hit) = 0;
/**
\brief Called when current controller hits another controller.
\param[in] hit Provides information about the hit.
@see PxControllersHit
*/
virtual void onControllerHit(const PxControllersHit& hit) = 0;
/**
\brief Called when current controller hits a user-defined obstacle.
\param[in] hit Provides information about the hit.
@see PxControllerObstacleHit PxObstacleContext
*/
virtual void onObstacleHit(const PxControllerObstacleHit& hit) = 0;
protected:
virtual ~PxUserControllerHitReport(){}
};
/**
\brief Dedicated filtering callback for CCT vs CCT.
This controls collisions between CCTs (one CCT vs anoter CCT).
To make each CCT collide against all other CCTs, just return true - or simply avoid defining a callback.
To make each CCT freely go through all other CCTs, just return false.
Otherwise create a custom filtering logic in this callback.
@see PxControllerFilters
*/
class PxControllerFilterCallback
{
public:
virtual ~PxControllerFilterCallback(){}
/**
\brief Filtering method for CCT-vs-CCT.
\param[in] a First CCT
\param[in] b Second CCT
\return true to keep the pair, false to filter it out
*/
virtual bool filter(const PxController& a, const PxController& b) = 0;
};
/**
\brief Filtering data for "move" call.
This class contains all filtering-related parameters for the PxController::move() call.
Collisions between a CCT and the world are filtered using the mFilterData, mFilterCallback and mFilterFlags
members. These parameters are internally passed to PxScene::overlap() to find objects touched by the CCT.
Please refer to the PxScene::overlap() documentation for details.
Collisions between a CCT and another CCT are filtered using the mCCTFilterCallback member. If this filter
callback is not defined, none of the CCT-vs-CCT collisions are filtered, and each CCT will collide against
all other CCTs.
\note PxQueryFlag::eANY_HIT and PxQueryFlag::eNO_BLOCK are ignored in mFilterFlags.
@see PxController.move() PxControllerFilterCallback
*/
class PxControllerFilters
{
public:
PX_INLINE PxControllerFilters(const PxFilterData* filterData=NULL, PxQueryFilterCallback* cb=NULL, PxControllerFilterCallback* cctFilterCb=NULL) :
mFilterData (filterData),
mFilterCallback (cb),
mFilterFlags (PxQueryFlag::eSTATIC|PxQueryFlag::eDYNAMIC|PxQueryFlag::ePREFILTER),
mCCTFilterCallback (cctFilterCb)
{}
// CCT-vs-shapes:
const PxFilterData* mFilterData; //!< Data for internal PxQueryFilterData structure. Passed to PxScene::overlap() call.
//!< This can be NULL, in which case a default PxFilterData is used.
PxQueryFilterCallback* mFilterCallback; //!< Custom filter logic (can be NULL). Passed to PxScene::overlap() call.
PxQueryFlags mFilterFlags; //!< Flags for internal PxQueryFilterData structure. Passed to PxScene::overlap() call.
// CCT-vs-CCT:
PxControllerFilterCallback* mCCTFilterCallback; //!< CCT-vs-CCT filter callback. If NULL, all CCT-vs-CCT collisions are kept.
};
/**
\brief Descriptor class for a character controller.
@see PxBoxController PxCapsuleController
*/
class PxControllerDesc
{
public:
/**
\brief returns true if the current settings are valid
\return True if the descriptor is valid.
*/
PX_INLINE virtual bool isValid() const;
/**
\brief Returns the character controller type
\return The controllers type.
@see PxControllerType PxCapsuleControllerDesc PxBoxControllerDesc
*/
PX_INLINE PxControllerShapeType::Enum getType() const { return mType; }
/**
\brief The position of the character
\note The character's initial position must be such that it does not overlap the static geometry.
<b>Default:</b> Zero
*/
PxExtendedVec3 position;
/**
\brief Specifies the 'up' direction
In order to provide stepping functionality the SDK must be informed about the up direction.
<b>Default:</b> (0, 1, 0)
*/
PxVec3 upDirection;
/**
\brief The maximum slope which the character can walk up.
In general it is desirable to limit where the character can walk, in particular it is unrealistic
for the character to be able to climb arbitary slopes.
The limit is expressed as the cosine of desired limit angle. A value of 0 disables this feature.
\warning It is currently enabled for static actors only (not for dynamic/kinematic actors), and not supported for spheres or capsules.
<b>Default:</b> 0.707
@see upDirection invisibleWallHeight maxJumpHeight
*/
PxF32 slopeLimit;
/**
\brief Height of invisible walls created around non-walkable triangles
The library can automatically create invisible walls around non-walkable triangles defined
by the 'slopeLimit' parameter. This defines the height of those walls. If it is 0.0, then
no extra triangles are created.
<b>Default:</b> 0.0
@see upDirection slopeLimit maxJumpHeight
*/
PxF32 invisibleWallHeight;
/**
\brief Maximum height a jumping character can reach
This is only used if invisible walls are created ('invisibleWallHeight' is non zero).
When a character jumps, the non-walkable triangles he might fly over are not found
by the collision queries (since the character's bounding volume does not touch them).
Thus those non-walkable triangles do not create invisible walls, and it is possible
for a jumping character to land on a non-walkable triangle, while he wouldn't have
reached that place by just walking.
The 'maxJumpHeight' variable is used to extend the size of the collision volume
downward. This way, all the non-walkable triangles are properly found by the collision
queries and it becomes impossible to 'jump over' invisible walls.
If the character in your game can not jump, it is safe to use 0.0 here. Otherwise it
is best to keep this value as small as possible, since a larger collision volume
means more triangles to process.
<b>Default:</b> 0.0
@see upDirection slopeLimit invisibleWallHeight
*/
PxF32 maxJumpHeight;
/**
\brief The contact offset used by the controller.
Specifies a skin around the object within which contacts will be generated.
Use it to avoid numerical precision issues.
This is dependant on the scale of the users world, but should be a small, positive
non zero value.
<b>Default:</b> 0.1
*/
PxF32 contactOffset;
/**
\brief Defines the maximum height of an obstacle which the character can climb.
A small value will mean that the character gets stuck and cannot walk up stairs etc,
a value which is too large will mean that the character can climb over unrealistically
high obstacles.
<b>Default:</b> 0.5
@see upDirection
*/
PxF32 stepOffset;
/**
\brief Density of underlying kinematic actor
The CCT creates a PhysX's kinematic actor under the hood. This controls its density.
<b>Default:</b> 10.0
*/
PxF32 density;
/**
\brief Scale coefficient for underlying kinematic actor
The CCT creates a PhysX's kinematic actor under the hood. This controls its scale factor.
This should be a number a bit smaller than 1.0.
<b>Default:</b> 0.8
*/
PxF32 scaleCoeff;
/**
\brief Cached volume growth
Amount of space around the controller we cache to improve performance. This is a scale factor
that should be higher than 1.0f but not too big, ideally lower than 2.0f.
<b>Default:</b> 1.5
*/
PxF32 volumeGrowth;
/**
\brief Specifies a user report callback.
This report callback is called when the character collides with shapes and other characters.
Setting this to NULL disables the callback.
<b>Default:</b> NULL
@see PxUserControllerHitReport
*/
PxUserControllerHitReport* reportCallback;
/**
\brief Specifies a user behavior callback.
This behavior callback is called to customize the controller's behavior w.r.t. touched shapes.
Setting this to NULL disables the callback.
<b>Default:</b> NULL
@see PxControllerBehaviorCallback
*/
PxControllerBehaviorCallback* behaviorCallback;
/**
\brief The non-walkable mode controls if a character controller slides or not on a non-walkable part.
This is only used when slopeLimit is non zero.
<b>Default:</b> PxControllerNonWalkableMode::ePREVENT_CLIMBING
@see PxControllerNonWalkableMode
*/
PxControllerNonWalkableMode::Enum nonWalkableMode;
/**
\brief The material for the actor associated with the controller.
The controller internally creates a rigid body actor. This parameter specifies the material of the actor.
<b>Default:</b> NULL
@see PxMaterial
*/
PxMaterial* material;
/**
\brief Use a deletion listener to get informed about released objects and clear internal caches if needed.
If a character controller registers a deletion listener, it will get informed about released objects. That allows the
controller to invalidate cached data that connects to a released object. If a deletion listener is not
registered, PxController::invalidateCache has to be called manually after objects have been released.
@see PxController::invalidateCache
<b>Default:</b> true
*/
bool registerDeletionListener;
/**
\brief Client ID for associated actor.
@see PxClientID PxActor::setOwnerClient
<b>Default:</b> PX_DEFAULT_CLIENT
*/
PxClientID clientID;
/**
\brief User specified data associated with the controller.
<b>Default:</b> NULL
*/
void* userData;
protected:
const PxControllerShapeType::Enum mType; //!< The type of the controller. This gets set by the derived class' ctor, the user should not have to change it.
/**
\brief constructor sets to default.
*/
PX_INLINE PxControllerDesc(PxControllerShapeType::Enum);
PX_INLINE virtual ~PxControllerDesc();
/**
\brief copy constructor.
*/
PX_INLINE PxControllerDesc(const PxControllerDesc&);
/**
\brief assignment operator.
*/
PX_INLINE PxControllerDesc& operator=(const PxControllerDesc&);
PX_INLINE void copy(const PxControllerDesc&);
};
PX_INLINE PxControllerDesc::PxControllerDesc(PxControllerShapeType::Enum t) :
position (PxExtended(0.0), PxExtended(0.0), PxExtended(0.0)),
upDirection (0.0f, 1.0f, 0.0f),
slopeLimit (0.707f),
invisibleWallHeight (0.0f),
maxJumpHeight (0.0f),
contactOffset (0.1f),
stepOffset (0.5f),
density (10.0f),
scaleCoeff (0.8f),
volumeGrowth (1.5f),
reportCallback (NULL),
behaviorCallback (NULL),
nonWalkableMode (PxControllerNonWalkableMode::ePREVENT_CLIMBING),
material (NULL),
registerDeletionListener (true),
clientID (PX_DEFAULT_CLIENT),
userData (NULL),
mType (t)
{
}
PX_INLINE PxControllerDesc::PxControllerDesc(const PxControllerDesc& other) : mType(other.mType)
{
copy(other);
}
PX_INLINE PxControllerDesc& PxControllerDesc::operator=(const PxControllerDesc& other)
{
copy(other);
return *this;
}
PX_INLINE void PxControllerDesc::copy(const PxControllerDesc& other)
{
upDirection = other.upDirection;
slopeLimit = other.slopeLimit;
contactOffset = other.contactOffset;
stepOffset = other.stepOffset;
density = other.density;
scaleCoeff = other.scaleCoeff;
volumeGrowth = other.volumeGrowth;
reportCallback = other.reportCallback;
behaviorCallback = other.behaviorCallback;
userData = other.userData;
nonWalkableMode = other.nonWalkableMode;
position.x = other.position.x;
position.y = other.position.y;
position.z = other.position.z;
material = other.material;
invisibleWallHeight = other.invisibleWallHeight;
maxJumpHeight = other.maxJumpHeight;
registerDeletionListener = other.registerDeletionListener;
clientID = other.clientID;
}
PX_INLINE PxControllerDesc::~PxControllerDesc()
{
}
PX_INLINE bool PxControllerDesc::isValid() const
{
if( mType!=PxControllerShapeType::eBOX
&& mType!=PxControllerShapeType::eCAPSULE)
return false;
if(scaleCoeff<0.0f)
return false;
if(volumeGrowth<1.0f)
return false;
if(density<0.0f)
return false;
if(slopeLimit<0.0f)
return false;
if(stepOffset<0.0f)
return false;
if(contactOffset<=0.0f)
return false;
if(!material)
return false;
if(!toVec3(position).isFinite())
return false; //the float version needs to be finite otherwise actor creation will fail.
return true;
}
/**
\brief Base class for character controllers.
@see PxCapsuleController PxBoxController
*/
class PxController
{
public:
/**
\brief Return the type of controller
@see PxControllerType
*/
virtual PxControllerShapeType::Enum getType() const = 0;
/**
\brief Releases the controller.
*/
virtual void release() = 0;
/**
\brief Moves the character using a "collide-and-slide" algorithm.
\param[in] disp Displacement vector
\param[in] minDist The minimum travelled distance to consider. If travelled distance is smaller, the character doesn't move.
This is used to stop the recursive motion algorithm when remaining distance to travel is small.
\param[in] elapsedTime Time elapsed since last call
\param[in] filters User-defined filters for this move
\param[in] obstacles Potential additional obstacles the CCT should collide with.
\return Collision flags, collection of ::PxControllerCollisionFlags
*/
virtual PxControllerCollisionFlags move(const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles=NULL) = 0;
/**
\brief Sets controller's position.
The position controlled by this function is the center of the collision shape.
\warning This is a 'teleport' function, it doesn't check for collisions.
\warning The character's position must be such that it does not overlap the static geometry.
To move the character under normal conditions use the #move() function.
\param[in] position The new (center) positon for the controller.
\return Currently always returns true.
@see PxControllerDesc.position getPosition() getFootPosition() setFootPosition() move()
*/
virtual bool setPosition(const PxExtendedVec3& position) = 0;
/**
\brief Retrieve the raw position of the controller.
The position retrieved by this function is the center of the collision shape. To retrieve the bottom position of the shape,
a.k.a. the foot position, use the getFootPosition() function.
The position is updated by calls to move(). Calling this method without calling
move() will return the last position or the initial position of the controller.
\return The controller's center position
@see PxControllerDesc.position setPosition() getFootPosition() setFootPosition() move()
*/
virtual const PxExtendedVec3& getPosition() const = 0;
/**
\brief Set controller's foot position.
The position controlled by this function is the bottom of the collision shape, a.k.a. the foot position.
\note The foot position takes the contact offset into account
\warning This is a 'teleport' function, it doesn't check for collisions.
To move the character under normal conditions use the #move() function.
\param[in] position The new (bottom) positon for the controller.
\return Currently always returns true.
@see PxControllerDesc.position setPosition() getPosition() getFootPosition() move()
*/
virtual bool setFootPosition(const PxExtendedVec3& position) = 0;
/**
\brief Retrieve the "foot" position of the controller, i.e. the position of the bottom of the CCT's shape.
\note The foot position takes the contact offset into account
\return The controller's foot position
@see PxControllerDesc.position setPosition() getPosition() setFootPosition() move()
*/
virtual PxExtendedVec3 getFootPosition() const = 0;
/**
\brief Get the rigid body actor associated with this controller (see PhysX documentation).
The behavior upon manually altering this actor is undefined, you should primarily
use it for reading const properties.
\return the actor associated with the controller.
*/
virtual PxRigidDynamic* getActor() const = 0;
/**
\brief The step height.
\param[in] offset The new step offset for the controller.
@see PxControllerDesc.stepOffset
*/
virtual void setStepOffset(const PxF32 offset) =0;
/**
\brief Retrieve the step height.
\return The step offset for the controller.
@see setStepOffset()
*/
virtual PxF32 getStepOffset() const =0;
/**
\brief Sets the non-walkable mode for the CCT.
\param[in] flag The new value of the non-walkable mode.
@see PxControllerNonWalkableMode
*/
virtual void setNonWalkableMode(PxControllerNonWalkableMode::Enum flag) = 0;
/**
\brief Retrieves the non-walkable mode for the CCT.
\return The current non-walkable mode.
@see PxControllerNonWalkableMode
*/
virtual PxControllerNonWalkableMode::Enum getNonWalkableMode() const = 0;
/**
\brief Retrieve the contact offset.
\return The contact offset for the controller.
@see PxControllerDesc.contactOffset
*/
virtual PxF32 getContactOffset() const =0;
/**
\brief Sets the contact offset.
\param[in] offset The contact offset for the controller.
@see PxControllerDesc.contactOffset
*/
virtual void setContactOffset(PxF32 offset) =0;
/**
\brief Retrieve the 'up' direction.
\return The up direction for the controller.
@see PxControllerDesc.upDirection
*/
virtual PxVec3 getUpDirection() const =0;
/**
\brief Sets the 'up' direction.
\param[in] up The up direction for the controller.
@see PxControllerDesc.upDirection
*/
virtual void setUpDirection(const PxVec3& up) =0;
/**
\brief Retrieve the slope limit.
\return The slope limit for the controller.
@see PxControllerDesc.slopeLimit
*/
virtual PxF32 getSlopeLimit() const =0;
/**
\brief Sets the slope limit.
\note This feature can not be enabled at runtime, i.e. if the slope limit is zero when creating the CCT
(which disables the feature) then changing the slope limit at runtime will not have any effect, and the call
will be ignored.
\param[in] slopeLimit The slope limit for the controller.
@see PxControllerDesc.slopeLimit
*/
virtual void setSlopeLimit(PxF32 slopeLimit) =0;
/**
\brief Flushes internal geometry cache.
The character controller uses caching in order to speed up collision testing. The cache is
automatically flushed when a change to static objects is detected in the scene. For example when a
static shape is added, updated, or removed from the scene, the cache is automatically invalidated.
However there may be situations that cannot be automatically detected, and those require manual
invalidation of the cache. Currently the user must call this when the filtering behavior changes (the
PxControllerFilters parameter of the PxController::move call). While the controller in principle
could detect a change in these parameters, it cannot detect a change in the behavior of the filtering
function.
@see PxController.move
*/
virtual void invalidateCache() = 0;
/**
\brief Retrieve the scene associated with the controller.
\return The physics scene
*/
virtual PxScene* getScene() = 0;
/**
\brief Returns the user data associated with this controller.
\return The user pointer associated with the controller.
@see PxControllerDesc.userData
*/
virtual void* getUserData() const = 0;
/**
\brief Sets the user data associated with this controller.
\param[in] userData The user pointer associated with the controller.
@see PxControllerDesc.userData
*/
virtual void setUserData(void* userData) = 0;
/**
\brief Returns information about the controller's internal state.
\param[out] state The controller's internal state
@see PxControllerState
*/
virtual void getState(PxControllerState& state) const = 0;
/**
\brief Returns the controller's internal statistics.
\param[out] stats The controller's internal statistics
@see PxControllerStats
*/
virtual void getStats(PxControllerStats& stats) const = 0;
/**
\brief Resizes the controller.
This function attempts to resize the controller to a given size, while making sure the bottom
position of the controller remains constant. In other words the function modifies both the
height and the (center) position of the controller. This is a helper function that can be used
to implement a 'crouch' functionality for example.
\param[in] height Desired controller's height
*/
virtual void resize(PxReal height) = 0;
protected:
PX_INLINE PxController() {}
virtual ~PxController() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 26,944 | C | 28.544956 | 177 | 0.745064 |
NVIDIA-Omniverse/PhysX/physx/include/characterkinematic/PxControllerManager.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_CONTROLLER_MANAGER_H
#define PX_CONTROLLER_MANAGER_H
/** \addtogroup character
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#include "foundation/PxErrorCallback.h"
#include "common/PxRenderBuffer.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxPhysics;
class PxScene;
class PxController;
class PxControllerDesc;
class PxObstacleContext;
class PxControllerFilterCallback;
/**
\brief specifies debug-rendering flags
*/
struct PxControllerDebugRenderFlag
{
enum Enum
{
eTEMPORAL_BV = (1<<0), //!< Temporal bounding volume around controllers
eCACHED_BV = (1<<1), //!< Cached bounding volume around controllers
eOBSTACLES = (1<<2), //!< User-defined obstacles
eNONE = 0,
eALL = 0xffffffff
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxControllerDebugRenderFlag.
@see PxControllerDebugRenderFlag
*/
typedef PxFlags<PxControllerDebugRenderFlag::Enum, PxU32> PxControllerDebugRenderFlags;
PX_FLAGS_OPERATORS(PxControllerDebugRenderFlag::Enum, PxU32)
/**
\brief Manages an array of character controllers.
@see PxController PxBoxController PxCapsuleController
*/
class PxControllerManager
{
public:
/**
\brief Releases the controller manager.
\note This will release all associated controllers and obstacle contexts.
\note This function is required to be called to release foundation usage.
*/
virtual void release() = 0;
/**
\brief Returns the scene the manager is adding the controllers to.
\return The associated physics scene.
*/
virtual PxScene& getScene() const = 0;
/**
\brief Returns the number of controllers that are being managed.
\return The number of controllers.
*/
virtual PxU32 getNbControllers() const = 0;
/**
\brief Retrieve one of the controllers in the manager.
\param index the index of the controller to return
\return The controller with the specified index.
*/
virtual PxController* getController(PxU32 index) = 0;
/**
\brief Creates a new character controller.
\param[in] desc The controllers descriptor
\return The new controller
@see PxController PxController.release() PxControllerDesc
*/
virtual PxController* createController(const PxControllerDesc& desc) = 0;
/**
\brief Releases all the controllers that are being managed.
*/
virtual void purgeControllers() = 0;
/**
\brief Retrieves debug data.
\return The render buffer filled with debug-render data
@see PxControllerManager.setDebugRenderingFlags()
*/
virtual PxRenderBuffer& getRenderBuffer() = 0;
/**
\brief Sets debug rendering flags
\param[in] flags The debug rendering flags (combination of PxControllerDebugRenderFlags)
@see PxControllerManager.getRenderBuffer() PxControllerDebugRenderFlags
*/
virtual void setDebugRenderingFlags(PxControllerDebugRenderFlags flags) = 0;
/**
\brief Returns the number of obstacle contexts that are being managed.
\return The number of obstacle contexts.
*/
virtual PxU32 getNbObstacleContexts() const = 0;
/**
\brief Retrieve one of the obstacle contexts in the manager.
\param index The index of the obstacle context to retrieve.
\return The obstacle context with the specified index.
*/
virtual PxObstacleContext* getObstacleContext(PxU32 index) = 0;
/**
\brief Creates an obstacle context.
\return New obstacle context
@see PxObstacleContext
*/
virtual PxObstacleContext* createObstacleContext() = 0;
/**
\brief Computes character-character interactions.
This function is an optional helper to properly resolve interactions between characters, in case they overlap (which can happen for gameplay reasons, etc).
You should call this once per frame, before your PxController::move() calls. The function will not move the characters directly, but it will
compute overlap information for each character that will be used in the next move() call.
You need to provide a proper time value here so that interactions are resolved in a way that do not depend on the framerate.
If you only have one character in the scene, or if you can guarantee your characters will never overlap, then you do not need to call this function.
\note Releasing the manager will automatically release all the associated obstacle contexts.
\param[in] elapsedTime Elapsed time since last call
\param[in] cctFilterCb Filtering callback for CCT-vs-CCT interactions
*/
virtual void computeInteractions(PxF32 elapsedTime, PxControllerFilterCallback* cctFilterCb=NULL) = 0;
/**
\brief Enables or disables runtime tessellation.
Large triangles can create accuracy issues in the sweep code, which in turn can lead to characters not sliding smoothly
against geometries, or even penetrating them. This feature allows one to reduce those issues by tessellating large
triangles at runtime, before performing sweeps against them. The amount of tessellation is controlled by the 'maxEdgeLength' parameter.
Any triangle with at least one edge length greater than the maxEdgeLength will get recursively tessellated, until resulting triangles are small enough.
This features only applies to triangle meshes, convex meshes, heightfields and boxes.
\param[in] flag True/false to enable/disable runtime tessellation.
\param[in] maxEdgeLength Max edge length allowed before tessellation kicks in.
*/
virtual void setTessellation(bool flag, float maxEdgeLength) = 0;
/**
\brief Enables or disables the overlap recovery module.
The overlap recovery module can be used to depenetrate CCTs from static objects when an overlap is detected. This can happen
in three main cases:
- when the CCT is directly spawned or teleported in another object
- when the CCT algorithm fails due to limited FPU accuracy
- when the "up vector" is modified, making the rotated CCT shape overlap surrounding objects
When activated, the CCT module will automatically try to resolve the penetration, and move the CCT to a safe place where it does
not overlap other objects anymore. This only concerns static objects, dynamic objects are ignored by the recovery module.
When the recovery module is not activated, it is possible for the CCTs to go through static objects. By default, the recovery
module is enabled.
The recovery module currently works with all geometries except heightfields.
\param[in] flag True/false to enable/disable overlap recovery module.
*/
virtual void setOverlapRecoveryModule(bool flag) = 0;
/**
\brief Enables or disables the precise sweeps.
Precise sweeps are more accurate, but also potentially slower than regular sweeps.
By default, precise sweeps are enabled.
\param[in] flag True/false to enable/disable precise sweeps.
*/
virtual void setPreciseSweeps(bool flag) = 0;
/**
\brief Enables or disables vertical sliding against ceilings.
Geometry is seen as "ceilings" when the following condition is met:
dot product(contact normal, up direction)<0.0f
This flag controls whether characters should slide vertically along the geometry in that case.
By default, sliding is allowed.
\param[in] flag True/false to enable/disable sliding.
*/
virtual void setPreventVerticalSlidingAgainstCeiling(bool flag) = 0;
/**
\brief Shift the origin of the character controllers and obstacle objects by the specified vector.
The positions of all character controllers, obstacle objects and the corresponding data structures will get adjusted to reflect the shifted origin location
(the shift vector will get subtracted from all character controller and obstacle object positions).
\note It is the user's responsibility to keep track of the summed total origin shift and adjust all input/output to/from PhysXCharacterKinematic accordingly.
\note This call will not automatically shift the PhysX scene and its objects. You need to call PxScene::shiftOrigin() seperately to keep the systems in sync.
\param[in] shift Translation vector to shift the origin by.
*/
virtual void shiftOrigin(const PxVec3& shift) = 0;
protected:
PxControllerManager() {}
virtual ~PxControllerManager() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/**
\brief Creates the controller manager.
\param[in] scene PhysX scene. You can only create one PxControllerManager per scene.
\param[in] lockingEnabled Enables/disables internal locking.
\return New controller manager, or NULL in case of failure (e.g. when a manager has already been created for that scene)
The character controller is informed by #PxDeletionListener::onRelease() when actors or shapes are released, and updates its internal
caches accordingly. If character controller movement or a call to #PxControllerManager::shiftOrigin() may overlap with actor/shape releases,
internal data structures must be guarded against concurrent access.
Locking guarantees thread safety in such scenarios.
\note locking may result in significant slowdown for release of actors or shapes.
By default, locking is disabled.
*/
PX_C_EXPORT physx::PxControllerManager* PX_CALL_CONV PxCreateControllerManager(physx::PxScene& scene, bool lockingEnabled = false);
/** @} */
#endif
| 10,813 | C | 34.92691 | 158 | 0.772589 |
NVIDIA-Omniverse/PhysX/physx/include/characterkinematic/PxCapsuleController.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_CAPSULE_CONTROLLER_H
#define PX_CAPSULE_CONTROLLER_H
/** \addtogroup character
@{
*/
#include "characterkinematic/PxController.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxCapsuleClimbingMode
{
enum Enum
{
eEASY, //!< Standard mode, let the capsule climb over surfaces according to impact normal
eCONSTRAINED, //!< Constrained mode, try to limit climbing according to the step offset
eLAST
};
};
/**
\brief A descriptor for a capsule character controller.
@see PxCapsuleController PxControllerDesc
*/
class PxCapsuleControllerDesc : public PxControllerDesc
{
public:
/**
\brief constructor sets to default.
*/
PX_INLINE PxCapsuleControllerDesc ();
PX_INLINE virtual ~PxCapsuleControllerDesc () {}
/**
\brief copy constructor.
*/
PX_INLINE PxCapsuleControllerDesc(const PxCapsuleControllerDesc&);
/**
\brief assignment operator.
*/
PX_INLINE PxCapsuleControllerDesc& operator=(const PxCapsuleControllerDesc&);
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE virtual void setToDefault();
/**
\brief returns true if the current settings are valid
\return True if the descriptor is valid.
*/
PX_INLINE virtual bool isValid() const;
/**
\brief The radius of the capsule
<b>Default:</b> 0.0
@see PxCapsuleController
*/
PxF32 radius;
/**
\brief The height of the controller
<b>Default:</b> 0.0
@see PxCapsuleController
*/
PxF32 height;
/**
\brief The climbing mode
<b>Default:</b> PxCapsuleClimbingMode::eEASY
@see PxCapsuleController
*/
PxCapsuleClimbingMode::Enum climbingMode;
protected:
PX_INLINE void copy(const PxCapsuleControllerDesc&);
};
PX_INLINE PxCapsuleControllerDesc::PxCapsuleControllerDesc () : PxControllerDesc(PxControllerShapeType::eCAPSULE)
{
radius = height = 0.0f;
climbingMode = PxCapsuleClimbingMode::eEASY;
}
PX_INLINE PxCapsuleControllerDesc::PxCapsuleControllerDesc(const PxCapsuleControllerDesc& other) : PxControllerDesc(other)
{
copy(other);
}
PX_INLINE PxCapsuleControllerDesc& PxCapsuleControllerDesc::operator=(const PxCapsuleControllerDesc& other)
{
PxControllerDesc::operator=(other);
copy(other);
return *this;
}
PX_INLINE void PxCapsuleControllerDesc::copy(const PxCapsuleControllerDesc& other)
{
radius = other.radius;
height = other.height;
climbingMode = other.climbingMode;
}
PX_INLINE void PxCapsuleControllerDesc::setToDefault()
{
*this = PxCapsuleControllerDesc();
}
PX_INLINE bool PxCapsuleControllerDesc::isValid() const
{
if(!PxControllerDesc::isValid()) return false;
if(radius<=0.0f) return false;
if(height<=0.0f) return false;
if(stepOffset>height+radius*2.0f) return false; // Prevents obvious mistakes
return true;
}
/**
\brief A capsule character controller.
The capsule is defined as a position, a vertical height, and a radius.
The height is the distance between the two sphere centers at the end of the capsule.
In other words:
p = pos (returned by controller)<br>
h = height<br>
r = radius<br>
p = center of capsule<br>
top sphere center = p.y + h*0.5<br>
bottom sphere center = p.y - h*0.5<br>
top capsule point = p.y + h*0.5 + r<br>
bottom capsule point = p.y - h*0.5 - r<br>
*/
class PxCapsuleController : public PxController
{
public:
/**
\brief Gets controller's radius.
\return The radius of the controller.
@see PxCapsuleControllerDesc.radius setRadius()
*/
virtual PxF32 getRadius() const = 0;
/**
\brief Sets controller's radius.
\warning this doesn't check for collisions.
\param[in] radius The new radius for the controller.
\return Currently always true.
@see PxCapsuleControllerDesc.radius getRadius()
*/
virtual bool setRadius(PxF32 radius) = 0;
/**
\brief Gets controller's height.
\return The height of the capsule controller.
@see PxCapsuleControllerDesc.height setHeight()
*/
virtual PxF32 getHeight() const = 0;
/**
\brief Resets controller's height.
\warning this doesn't check for collisions.
\param[in] height The new height for the controller.
\return Currently always true.
@see PxCapsuleControllerDesc.height getHeight()
*/
virtual bool setHeight(PxF32 height) = 0;
/**
\brief Gets controller's climbing mode.
\return The capsule controller's climbing mode.
@see PxCapsuleControllerDesc.climbingMode setClimbingMode()
*/
virtual PxCapsuleClimbingMode::Enum getClimbingMode() const = 0;
/**
\brief Sets controller's climbing mode.
\param[in] mode The capsule controller's climbing mode.
@see PxCapsuleControllerDesc.climbingMode getClimbingMode()
*/
virtual bool setClimbingMode(PxCapsuleClimbingMode::Enum mode) = 0;
protected:
PX_INLINE PxCapsuleController() {}
virtual ~PxCapsuleController() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,517 | C | 25.176707 | 122 | 0.739144 |
NVIDIA-Omniverse/PhysX/physx/include/characterkinematic/PxControllerBehavior.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_CONTROLLER_BEHAVIOR_H
#define PX_CONTROLLER_BEHAVIOR_H
/** \addtogroup character
@{
*/
#include "PxFiltering.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxObstacle;
class PxController;
/**
\brief specifies controller behavior
*/
struct PxControllerBehaviorFlag
{
enum Enum
{
eCCT_CAN_RIDE_ON_OBJECT = (1<<0), //!< Controller can ride on touched object (i.e. when this touched object is moving horizontally). \note The CCT vs. CCT case is not supported.
eCCT_SLIDE = (1<<1), //!< Controller should slide on touched object
eCCT_USER_DEFINED_RIDE = (1<<2) //!< Disable all code dealing with controllers riding on objects, let users define it outside of the SDK.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxControllerBehaviorFlag.
@see PxControllerBehaviorFlag
*/
typedef PxFlags<PxControllerBehaviorFlag::Enum, PxU8> PxControllerBehaviorFlags;
PX_FLAGS_OPERATORS(PxControllerBehaviorFlag::Enum, PxU8)
/**
\brief User behavior callback.
This behavior callback is called to customize the controller's behavior w.r.t. touched shapes.
*/
class PxControllerBehaviorCallback
{
public:
/**
\brief Retrieve behavior flags for a shape.
When the CCT touches a shape, the CCT's behavior w.r.t. this shape can be customized by users.
This function retrieves the desired PxControllerBehaviorFlag flags capturing the desired behavior.
\note See comments about deprecated functions at the start of this class
\param[in] shape The shape the CCT is currently touching
\param[in] actor The actor owning the shape
\return Desired behavior flags for the given shape
@see PxControllerBehaviorFlag
*/
virtual PxControllerBehaviorFlags getBehaviorFlags(const PxShape& shape, const PxActor& actor) = 0;
/**
\brief Retrieve behavior flags for a controller.
When the CCT touches a controller, the CCT's behavior w.r.t. this controller can be customized by users.
This function retrieves the desired PxControllerBehaviorFlag flags capturing the desired behavior.
\note The flag PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT is not supported.
\note See comments about deprecated functions at the start of this class
\param[in] controller The controller the CCT is currently touching
\return Desired behavior flags for the given controller
@see PxControllerBehaviorFlag
*/
virtual PxControllerBehaviorFlags getBehaviorFlags(const PxController& controller) = 0;
/**
\brief Retrieve behavior flags for an obstacle.
When the CCT touches an obstacle, the CCT's behavior w.r.t. this obstacle can be customized by users.
This function retrieves the desired PxControllerBehaviorFlag flags capturing the desired behavior.
\note See comments about deprecated functions at the start of this class
\param[in] obstacle The obstacle the CCT is currently touching
\return Desired behavior flags for the given obstacle
@see PxControllerBehaviorFlag
*/
virtual PxControllerBehaviorFlags getBehaviorFlags(const PxObstacle& obstacle) = 0;
protected:
virtual ~PxControllerBehaviorCallback(){}
};
#if !PX_DOXYGEN
}
#endif
/** @} */
#endif
| 4,894 | C | 35.259259 | 181 | 0.762158 |
NVIDIA-Omniverse/PhysX/physx/include/characterkinematic/PxBoxController.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_BOX_CONTROLLER_H
#define PX_BOX_CONTROLLER_H
/** \addtogroup character
@{
*/
#include "characterkinematic/PxController.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Descriptor for a box character controller.
@see PxBoxController PxControllerDesc
*/
class PxBoxControllerDesc : public PxControllerDesc
{
public:
/**
\brief constructor sets to default.
*/
PX_INLINE PxBoxControllerDesc();
PX_INLINE virtual ~PxBoxControllerDesc() {}
/**
\brief copy constructor.
*/
PX_INLINE PxBoxControllerDesc(const PxBoxControllerDesc&);
/**
\brief assignment operator.
*/
PX_INLINE PxBoxControllerDesc& operator=(const PxBoxControllerDesc&);
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE virtual void setToDefault();
/**
\brief returns true if the current settings are valid
\return True if the descriptor is valid.
*/
PX_INLINE virtual bool isValid() const;
/**
\brief Half height
<b>Default:</b> 1.0
*/
PxF32 halfHeight; // Half-height in the "up" direction
/**
\brief Half side extent
<b>Default:</b> 0.5
*/
PxF32 halfSideExtent; // Half-extent in the "side" direction
/**
\brief Half forward extent
<b>Default:</b> 0.5
*/
PxF32 halfForwardExtent; // Half-extent in the "forward" direction
protected:
PX_INLINE void copy(const PxBoxControllerDesc&);
};
PX_INLINE PxBoxControllerDesc::PxBoxControllerDesc() :
PxControllerDesc (PxControllerShapeType::eBOX),
halfHeight (1.0f),
halfSideExtent (0.5f),
halfForwardExtent (0.5f)
{
}
PX_INLINE PxBoxControllerDesc::PxBoxControllerDesc(const PxBoxControllerDesc& other) : PxControllerDesc(other)
{
copy(other);
}
PX_INLINE PxBoxControllerDesc& PxBoxControllerDesc::operator=(const PxBoxControllerDesc& other)
{
PxControllerDesc::operator=(other);
copy(other);
return *this;
}
PX_INLINE void PxBoxControllerDesc::copy(const PxBoxControllerDesc& other)
{
halfHeight = other.halfHeight;
halfSideExtent = other.halfSideExtent;
halfForwardExtent = other.halfForwardExtent;
}
PX_INLINE void PxBoxControllerDesc::setToDefault()
{
*this = PxBoxControllerDesc();
}
PX_INLINE bool PxBoxControllerDesc::isValid() const
{
if(!PxControllerDesc::isValid()) return false;
if(halfHeight<=0.0f) return false;
if(halfSideExtent<=0.0f) return false;
if(halfForwardExtent<=0.0f) return false;
if(stepOffset>2.0f*halfHeight) return false; // Prevents obvious mistakes
return true;
}
/**
\brief Box character controller.
@see PxBoxControllerDesc PxController
*/
class PxBoxController : public PxController
{
public:
/**
\brief Gets controller's half height.
\return The half height of the controller.
@see PxBoxControllerDesc.halfHeight setHalfHeight()
*/
virtual PxF32 getHalfHeight() const = 0;
/**
\brief Gets controller's half side extent.
\return The half side extent of the controller.
@see PxBoxControllerDesc.halfSideExtent setHalfSideExtent()
*/
virtual PxF32 getHalfSideExtent() const = 0;
/**
\brief Gets controller's half forward extent.
\return The half forward extent of the controller.
@see PxBoxControllerDesc.halfForwardExtent setHalfForwardExtent()
*/
virtual PxF32 getHalfForwardExtent() const = 0;
/**
\brief Sets controller's half height.
\warning this doesn't check for collisions.
\param[in] halfHeight The new half height for the controller.
\return Currently always true.
@see PxBoxControllerDesc.halfHeight getHalfHeight()
*/
virtual bool setHalfHeight(PxF32 halfHeight) = 0;
/**
\brief Sets controller's half side extent.
\warning this doesn't check for collisions.
\param[in] halfSideExtent The new half side extent for the controller.
\return Currently always true.
@see PxBoxControllerDesc.halfSideExtent getHalfSideExtent()
*/
virtual bool setHalfSideExtent(PxF32 halfSideExtent) = 0;
/**
\brief Sets controller's half forward extent.
\warning this doesn't check for collisions.
\param[in] halfForwardExtent The new half forward extent for the controller.
\return Currently always true.
@see PxBoxControllerDesc.halfForwardExtent getHalfForwardExtent()
*/
virtual bool setHalfForwardExtent(PxF32 halfForwardExtent) = 0;
protected:
PX_INLINE PxBoxController() {}
virtual ~PxBoxController() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,070 | C | 25.627193 | 110 | 0.742834 |
NVIDIA-Omniverse/PhysX/physx/include/characterkinematic/PxControllerObstacles.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_CONTROLLER_OBSTACLES_H
#define PX_CONTROLLER_OBSTACLES_H
/** \addtogroup character
@{
*/
#include "characterkinematic/PxExtended.h"
#include "geometry/PxGeometry.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxControllerManager;
#define PX_INVALID_OBSTACLE_HANDLE 0xffffffff
/**
\brief Base class for obstacles.
@see PxBoxObstacle PxCapsuleObstacle PxObstacleContext
*/
class PxObstacle
{
protected:
PxObstacle() :
mType (PxGeometryType::eINVALID),
mUserData (NULL),
mPos (0.0, 0.0, 0.0),
mRot (PxQuat(PxIdentity))
{}
PxGeometryType::Enum mType;
public:
PX_FORCE_INLINE PxGeometryType::Enum getType() const { return mType; }
void* mUserData;
PxExtendedVec3 mPos;
PxQuat mRot;
};
/**
\brief A box obstacle.
@see PxObstacle PxCapsuleObstacle PxObstacleContext
*/
class PxBoxObstacle : public PxObstacle
{
public:
PxBoxObstacle() :
mHalfExtents(0.0f)
{ mType = PxGeometryType::eBOX; }
PxVec3 mHalfExtents;
};
/**
\brief A capsule obstacle.
@see PxBoxObstacle PxObstacle PxObstacleContext
*/
class PxCapsuleObstacle : public PxObstacle
{
public:
PxCapsuleObstacle() :
mHalfHeight (0.0f),
mRadius (0.0f)
{ mType = PxGeometryType::eCAPSULE; }
PxReal mHalfHeight;
PxReal mRadius;
};
typedef PxU32 PxObstacleHandle;
/**
\brief Context class for obstacles.
An obstacle context class contains and manages a set of user-defined obstacles.
@see PxBoxObstacle PxCapsuleObstacle PxObstacle
*/
class PxObstacleContext
{
public:
PxObstacleContext() {}
virtual ~PxObstacleContext() {}
/**
\brief Releases the context.
*/
virtual void release() = 0;
/**
\brief Retrieves the controller manager associated with this context.
\return The associated controller manager
*/
virtual PxControllerManager& getControllerManager() const = 0;
/**
\brief Adds an obstacle to the context.
\param [in] obstacle Obstacle data for the new obstacle. The data gets copied.
\return Handle for newly-added obstacle
*/
virtual PxObstacleHandle addObstacle(const PxObstacle& obstacle) = 0;
/**
\brief Removes an obstacle from the context.
\param [in] handle Handle for the obstacle object that needs to be removed.
\return True if success
*/
virtual bool removeObstacle(PxObstacleHandle handle) = 0;
/**
\brief Updates data for an existing obstacle.
\param [in] handle Handle for the obstacle object that needs to be updated.
\param [in] obstacle New obstacle data
\return True if success
*/
virtual bool updateObstacle(PxObstacleHandle handle, const PxObstacle& obstacle) = 0;
/**
\brief Retrieves number of obstacles in the context.
\return Number of obstacles in the context
*/
virtual PxU32 getNbObstacles() const = 0;
/**
\brief Retrieves desired obstacle.
\param [in] i Obstacle index
\return Desired obstacle
*/
virtual const PxObstacle* getObstacle(PxU32 i) const = 0;
/**
\brief Retrieves desired obstacle by given handle.
\param [in] handle Obstacle handle
\return Desired obstacle
*/
virtual const PxObstacle* getObstacleByHandle(PxObstacleHandle handle) const = 0;
};
#if !PX_DOXYGEN
}
#endif
/** @} */
#endif
| 5,199 | C | 26.225131 | 90 | 0.693403 |
NVIDIA-Omniverse/PhysX/physx/include/gpu/PxPhysicsGpu.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_PHYSICS_GPU_H
#define PX_PHYSICS_GPU_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
class PxSceneDesc;
class PxIsosurfaceExtractor;
class PxSparseGridIsosurfaceExtractor;
class PxAnisotropyGenerator;
class PxSmoothedPositionGenerator;
class PxParticleNeighborhoodProvider;
class PxArrayConverter;
class PxLineStripSkinning;
class PxSoftBodyEmbedding;
class PxSDFBuilder;
struct PxIsosurfaceParams;
struct PxSparseGridParams;
class PxPhysicsGpu
{
public:
/**
\brief Creates an isosurface extractor operating on a dense grid
\param[in] cudaContextManager A cuda context manager
\param[in] worldBounds The bounds of the internally used dense grid. The isosurface can only be generated inside those bounds.
\param[in] cellSize The size of a single grid cell
\param[in] isosurfaceParams The isosurface parameters to control the isolevel etc.
\param[in] maxNumParticles The maximal number of particles that can be processed
\param[in] maxNumVertices The maximal number of vertices the output buffer can hold
\param[in] maxNumTriangles The maximal number of triangles the output buffer can hold
*/
virtual PxIsosurfaceExtractor* createDenseGridIsosurfaceExtractor(PxCudaContextManager* cudaContextManager, const PxBounds3& worldBounds,
PxReal cellSize, const PxIsosurfaceParams& isosurfaceParams, PxU32 maxNumParticles, PxU32 maxNumVertices = 512 * 1024, PxU32 maxNumTriangles = 1024 * 1024) = 0;
/**
\brief Creates an isosurface extractor operating on a sparse grid
\param[in] cudaContextManager A cuda context manager
\param[in] sparseGridParams The sparse grid parameters defining the cell size etc.
\param[in] isosurfaceParams The isosurface parameters to control the isolevel etc.
\param[in] maxNumParticles The maximal number of particles that can be processed
\param[in] maxNumVertices The maximal number of vertices the output buffer can hold
\param[in] maxNumTriangles The maximal number of triangles the output buffer can hold
*/
virtual PxSparseGridIsosurfaceExtractor* createSparseGridIsosurfaceExtractor(PxCudaContextManager* cudaContextManager, const PxSparseGridParams& sparseGridParams,
const PxIsosurfaceParams& isosurfaceParams, PxU32 maxNumParticles, PxU32 maxNumVertices = 512 * 1024, PxU32 maxNumTriangles = 1024 * 1024) = 0;
/**
\brief Creates an anisotropy generator
\param[in] cudaContextManager A cuda context manager
\param[in] maxNumParticles The number of particles
\param[in] anisotropyScale A uniform scaling factor to increase or decrease anisotropy
\param[in] minAnisotropy The minimum scaling factor in any dimension that anisotropy can have
\param[in] maxAnisotropy The maximum scaling factor in any dimension that anisotropy can have
*/
virtual PxAnisotropyGenerator* createAnisotropyGenerator(PxCudaContextManager* cudaContextManager, PxU32 maxNumParticles,
PxReal anisotropyScale = 1.0f, PxReal minAnisotropy = 0.1f, PxReal maxAnisotropy = 2.0f) = 0;
/**
\brief Creates a smoothed position generator
\param[in] cudaContextManager A cuda context manager
\param[in] maxNumParticles The number of particles
\param[in] smoothingStrength Controls the strength of the smoothing effect
*/
virtual PxSmoothedPositionGenerator* createSmoothedPositionGenerator(PxCudaContextManager* cudaContextManager, PxU32 maxNumParticles, PxReal smoothingStrength = 0.5f) = 0;
/**
\brief Creates a neighborhood provider
\param[in] cudaContextManager A cuda context manager
\param[in] maxNumParticles The number of particles
\param[in] cellSize The grid cell size. Should be equal to 2*contactOffset for PBD particle systems.
\param[in] maxNumSparseGridCells The maximal number of cells the internally used sparse grid can provide
*/
virtual PxParticleNeighborhoodProvider* createParticleNeighborhoodProvider(PxCudaContextManager* cudaContextManager, const PxU32 maxNumParticles,
const PxReal cellSize, const PxU32 maxNumSparseGridCells = 262144) = 0;
/**
\brief Creates an array converter. If not used anymore, the caller needs to delete the returned pointer.
\param[in] cudaContextManager A cuda context manager
*/
virtual PxArrayConverter* createArrayConverter(PxCudaContextManager* cudaContextManager) = 0;
/**
\brief Creates an line strip embedding helper. If not used anymore, the caller needs to delete the returned pointer.
\param[in] cudaContextManager A cuda context manager
\return Pointer to a new instance of a PxLineStripSkinning
*/
virtual PxLineStripSkinning* createLineStripSkinning(PxCudaContextManager* cudaContextManager) = 0;
/**
\brief Creates sdf builder to construct sdfs quickly on the GPU. If not used anymore, the caller needs to delete the returned pointer.
\param[in] cudaContextManager A cuda context manager
\return Pointer to a new instance of a PxSDFBuilder
*/
virtual PxSDFBuilder* createSDFBuilder(PxCudaContextManager* cudaContextManager) = 0;
/**
\brief Estimates the amount of GPU memory needed to create a scene for the given descriptor.
\param[in] sceneDesc a valid scene desriptor
\note While this is a conservative estimate, scene allocation may still fail even though there is
enough memory - this function does not contain the potential overhead coming from the CUDA allocator.
Additionally, there may be fragmentation issues. Generally, this is not an issue for
scene allocation sizes < 500Mb, but may become problematic for larger scenes.
\return A conservative estimate for the amount of GPU memory needed to create a scene for the given descriptor.
*/
virtual PxU64 estimateSceneCreationGpuMemoryRequirements(const PxSceneDesc& sceneDesc) = 0;
virtual void release() = 0;
virtual ~PxPhysicsGpu() {}
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 7,853 | C | 41.454054 | 173 | 0.784414 |
NVIDIA-Omniverse/PhysX/physx/include/gpu/PxGpu.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.
#ifndef PX_GPU_H
#define PX_GPU_H
#include "PxPhysXConfig.h"
#if PX_SUPPORT_GPU_PHYSX
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/Px.h"
#include "foundation/PxPreprocessor.h"
#include "foundation/PxFoundation.h"
#include "common/PxPhysXCommonConfig.h"
/**
\brief PxGpuLoadHook
This is a helper class for loading the PhysXGpu dll.
If a PhysXGpu dll with a non-default file name needs to be loaded,
PxGpuLoadHook can be sub-classed to provide the custom filenames.
Once the names are set, the instance must be set for use by PhysX.dll using PxSetPhysXGpuLoadHook(),
@see PxSetPhysXGpuLoadHook()
*/
class PxGpuLoadHook
{
public:
PxGpuLoadHook() {}
virtual ~PxGpuLoadHook() {}
virtual const char* getPhysXGpuDllName() const = 0;
protected:
private:
};
/**
\brief Sets GPU load hook instance for PhysX dll.
\param[in] hook GPU load hook.
@see PxGpuLoadHook
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXGpuLoadHook(const PxGpuLoadHook* hook);
/**
* \brief Ask the NVIDIA control panel which GPU has been selected for use by
* PhysX. Returns -1 if no PhysX capable GPU is found or GPU PhysX has
* been disabled.
*/
PX_C_EXPORT PX_PHYSX_CORE_API int PX_CALL_CONV PxGetSuggestedCudaDeviceOrdinal(physx::PxErrorCallback& errc);
/**
* \brief Allocate a CUDA Context manager, complete with heaps.
* You only need one CUDA context manager per GPU device you intend to use for
* CUDA tasks.
\param[in] foundation PhysXFoundation instance.
\param[in] desc Cuda context manager desc.
\param[in] profilerCallback PhysX profiler callback instance.
\param[in] launchSynchronous Set launchSynchronous to true for CUDA to report the actual point of failure.
@see PxGetProfilerCallback()
*/
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxCudaContextManager* PX_CALL_CONV PxCreateCudaContextManager(physx::PxFoundation& foundation, const physx::PxCudaContextManagerDesc& desc, physx::PxProfilerCallback* profilerCallback = NULL, bool launchSynchronous = false);
/**
* \brief Sets profiler callback to PhysX GPU
\param[in] profilerCallback PhysX profiler callback instance.
@see PxGetProfilerCallback()
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxSetPhysXGpuProfilerCallback(physx::PxProfilerCallback* profilerCallback);
/**
\brief Internally used callback to register function names of cuda kernels
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxCudaRegisterFunction(int moduleIndex, const char* functionName);
/**
\brief Internally used callback to register cuda modules at load time
*/
PX_C_EXPORT PX_PHYSX_CORE_API void** PX_CALL_CONV PxCudaRegisterFatBinary(void*);
/**
\brief Access to the registered cuda modules
*/
PX_C_EXPORT PX_PHYSX_CORE_API void** PX_CALL_CONV PxGetCudaModuleTable();
/**
\brief Number of registered cuda modules
*/
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxU32 PX_CALL_CONV PxGetCudaModuleTableSize();
/**
\brief Access to the loaded cuda functions (kernels)
*/
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxKernelIndex* PX_CALL_CONV PxGetCudaFunctionTable();
/**
\brief Number of loaded cuda functions (kernels)
*/
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxU32 PX_CALL_CONV PxGetCudaFunctionTableSize();
namespace physx
{
class PxPhysicsGpu;
}
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxPhysicsGpu* PX_CALL_CONV PxGetPhysicsGpu();
#endif // PX_SUPPORT_GPU_PHYSX
#endif
| 4,927 | C | 33.222222 | 261 | 0.768419 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxConvexMeshGeometry.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_CONVEX_MESH_GEOMETRY_H
#define PX_CONVEX_MESH_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#include "geometry/PxMeshScale.h"
#include "common/PxCoreUtilityTypes.h"
#include "geometry/PxConvexMesh.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxConvexMesh;
/**
\brief Flags controlling the simulated behavior of the convex mesh geometry.
Used in ::PxConvexMeshGeometryFlags.
*/
struct PxConvexMeshGeometryFlag
{
enum Enum
{
eTIGHT_BOUNDS = (1<<0) //!< Use tighter (but more expensive to compute) bounds around the convex geometry.
};
};
/**
\brief collection of set bits defined in PxConvexMeshGeometryFlag.
@see PxConvexMeshGeometryFlag
*/
typedef PxFlags<PxConvexMeshGeometryFlag::Enum,PxU8> PxConvexMeshGeometryFlags;
PX_FLAGS_OPERATORS(PxConvexMeshGeometryFlag::Enum,PxU8)
/**
\brief Convex mesh geometry class.
This class unifies a convex mesh object with a scaling transform, and
lets the combined object be used anywhere a PxGeometry is needed.
The scaling is a transform along arbitrary axes contained in the scale object.
The vertices of the mesh in geometry (or shape) space is the
PxMeshScale::toMat33() transform, multiplied by the vertex space vertices
in the PxConvexMesh object.
*/
class PxConvexMeshGeometry : public PxGeometry
{
public:
/**
\brief Constructor. By default creates an empty object with a NULL mesh and identity scale.
\param[in] mesh Mesh pointer. May be NULL, though this will not make the object valid for shape construction.
\param[in] scaling Scale factor.
\param[in] flags Mesh flags.
\
*/
PX_INLINE PxConvexMeshGeometry( PxConvexMesh* mesh = NULL,
const PxMeshScale& scaling = PxMeshScale(),
PxConvexMeshGeometryFlags flags = PxConvexMeshGeometryFlag::eTIGHT_BOUNDS) :
PxGeometry (PxGeometryType::eCONVEXMESH),
scale (scaling),
convexMesh (mesh),
meshFlags (flags)
{
}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxConvexMeshGeometry(const PxConvexMeshGeometry& that) :
PxGeometry (that),
scale (that.scale),
convexMesh (that.convexMesh),
meshFlags (that.meshFlags)
{
}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxConvexMeshGeometry& that)
{
mType = that.mType;
scale = that.scale;
convexMesh = that.convexMesh;
meshFlags = that.meshFlags;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid for shape creation.
\note A valid convex mesh has a positive scale value in each direction (scale.x > 0, scale.y > 0, scale.z > 0).
It is illegal to call PxRigidActor::createShape and PxPhysics::createShape with a convex that has zero extent in any direction.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
public:
PxMeshScale scale; //!< The scaling transformation (from vertex space to shape space).
PxConvexMesh* convexMesh; //!< A reference to the convex mesh object.
PxConvexMeshGeometryFlags meshFlags; //!< Mesh flags.
PxPadding<3> paddingFromFlags; //!< padding for mesh flags
};
PX_INLINE bool PxConvexMeshGeometry::isValid() const
{
if(mType != PxGeometryType::eCONVEXMESH)
return false;
if(!scale.scale.isFinite() || !scale.rotation.isUnit())
return false;
if(!scale.isValidForConvexMesh())
return false;
if(!convexMesh)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 5,179 | C | 30.779141 | 128 | 0.748793 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxSphereGeometry.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_SPHERE_GEOMETRY_H
#define PX_SPHERE_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A class representing the geometry of a sphere.
Spheres are defined by their radius.
\note The scaling of the sphere is expected to be baked into this value, there is no additional scaling parameter.
*/
class PxSphereGeometry : public PxGeometry
{
public:
/**
\brief Constructor.
*/
PX_INLINE PxSphereGeometry(PxReal ir=0.0f) : PxGeometry(PxGeometryType::eSPHERE), radius(ir) {}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxSphereGeometry(const PxSphereGeometry& that) : PxGeometry(that), radius(that.radius) {}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxSphereGeometry& that)
{
mType = that.mType;
radius = that.radius;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid
\note A valid sphere has radius > 0.
It is illegal to call PxRigidActor::createShape and PxPhysics::createShape with a sphere that has zero radius.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
public:
/**
\brief The radius of the sphere.
*/
PxReal radius;
};
PX_INLINE bool PxSphereGeometry::isValid() const
{
if(mType != PxGeometryType::eSPHERE)
return false;
if(!PxIsFinite(radius))
return false;
if(radius <= 0.0f)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,260 | C | 28.917431 | 114 | 0.741718 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxMeshScale.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_MESH_SCALE_H
#define PX_MESH_SCALE_H
/** \addtogroup geomutils
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxMat33.h"
#include "foundation/PxAssert.h"
/** \brief Minimum allowed absolute magnitude for each of mesh scale's components (x,y,z).
\note Only positive scale values are allowed for convex meshes. */
#define PX_MESH_SCALE_MIN 1e-6f
/** \brief Maximum allowed absolute magnitude for each of mesh scale's components (x,y,z).
\note Only positive scale values are allowed for convex meshes. */
#define PX_MESH_SCALE_MAX 1e6f
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A class expressing a nonuniform scaling transformation.
The scaling is along arbitrary axes that are specified by PxMeshScale::rotation. Specifically, PxMeshScale::rotation
describes the rotation from the scaling-axes frame to the mesh-local frame, i.e. PxMeshScale::rotation.rotate(v) transforms
the coordinates of vertex v from the mesh-local frame to the scaling-axes frame.
\note Negative scale values are supported for PxTriangleMeshGeometry
with absolute values for each component within [PX_MIN_ABS_MESH_SCALE, PX_MAX_ABS_MESH_SCALE] range.
Negative scale causes a reflection around the specified axis, in addition PhysX will flip the normals
for mesh triangles when scale.x*scale.y*scale.z < 0.
\note Only positive scale values are supported for PxConvexMeshGeometry
with values for each component within [PX_MIN_ABS_MESH_SCALE, PX_MAX_ABS_MESH_SCALE] range).
@see PxConvexMeshGeometry PxTriangleMeshGeometry
*/
class PxMeshScale
{
public:
/**
\brief Constructor initializes to identity scale.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(): scale(1.0f), rotation(PxIdentity)
{
}
/**
\brief Constructor from scalar.
*/
explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(PxReal r): scale(r), rotation(PxIdentity)
{
}
/**
\brief Constructor to initialize to arbitrary scale and identity scale rotation.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(const PxVec3& s)
{
scale = s;
rotation = PxQuat(PxIdentity);
}
/**
\brief Constructor to initialize to arbitrary scaling.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale(const PxVec3& s, const PxQuat& r)
{
PX_ASSERT(r.isUnit());
scale = s;
rotation = r;
}
/**
\brief Returns true if the scaling is an identity transformation.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isIdentity() const
{
return (scale.x == 1.0f && scale.y == 1.0f && scale.z == 1.0f);
}
/**
\brief Returns the inverse of this scaling transformation.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxMeshScale getInverse() const
{
return PxMeshScale(PxVec3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z), rotation);
}
/**
\brief Converts this transformation to a 3x3 matrix representation.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33 toMat33() const
{
PxMat33 rot(rotation);
PxMat33 trans = rot.getTranspose();
trans.column0 *= scale[0];
trans.column1 *= scale[1];
trans.column2 *= scale[2];
return trans * rot;
}
/**
\brief Returns true if combination of negative scale components will cause the triangle normal to flip. The SDK will flip the normals internally.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNegativeDeterminant() const
{
return (scale.x * scale.y * scale.z < 0.0f);
}
PxVec3 transform(const PxVec3& v) const
{
return rotation.rotateInv(scale.multiply(rotation.rotate(v)));
}
bool isValidForTriangleMesh() const
{
PxVec3 absXYZ = scale.abs();
return (absXYZ.maxElement() <= PX_MESH_SCALE_MAX) && (absXYZ.minElement() >= PX_MESH_SCALE_MIN);
}
bool isValidForConvexMesh() const
{
return (scale.maxElement() <= PX_MESH_SCALE_MAX) && (scale.minElement() >= PX_MESH_SCALE_MIN);
}
PxVec3 scale; //!< A nonuniform scaling
PxQuat rotation; //!< The orientation of the scaling axes
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 5,615 | C | 32.628742 | 146 | 0.738557 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxTriangleMeshGeometry.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_TRIANGLE_MESH_GEOMETRY_H
#define PX_TRIANGLE_MESH_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#include "geometry/PxMeshScale.h"
#include "common/PxCoreUtilityTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxTriangleMesh;
/**
\brief Flags controlling the simulated behavior of the triangle mesh geometry.
Used in ::PxMeshGeometryFlags.
*/
struct PxMeshGeometryFlag
{
enum Enum
{
eTIGHT_BOUNDS = (1<<0), //!< Use tighter (but more expensive to compute) bounds around the triangle mesh geometry.
eDOUBLE_SIDED = (1<<1) //!< Meshes with this flag set are treated as double-sided.
//!< This flag is currently only used for raycasts and sweeps (it is ignored for overlap queries).
//!< For detailed specifications of this flag for meshes and heightfields please refer to the Geometry Query section of the user guide.
};
};
/**
\brief collection of set bits defined in PxMeshGeometryFlag.
@see PxMeshGeometryFlag
*/
typedef PxFlags<PxMeshGeometryFlag::Enum,PxU8> PxMeshGeometryFlags;
PX_FLAGS_OPERATORS(PxMeshGeometryFlag::Enum,PxU8)
/**
\brief Triangle mesh geometry class.
This class unifies a mesh object with a scaling transform, and
lets the combined object be used anywhere a PxGeometry is needed.
The scaling is a transform along arbitrary axes contained in the scale object.
The vertices of the mesh in geometry (or shape) space is the
PxMeshScale::toMat33() transform, multiplied by the vertex space vertices
in the PxTriangleMeshGeometry object.
*/
class PxTriangleMeshGeometry : public PxGeometry
{
public:
/**
\brief Constructor. By default creates an empty object with a NULL mesh and identity scale.
\param[in] mesh Mesh pointer. May be NULL, though this will not make the object valid for shape construction.
\param[in] scaling Scale factor.
\param[in] flags Mesh flags.
*/
PX_INLINE PxTriangleMeshGeometry( PxTriangleMesh* mesh = NULL,
const PxMeshScale& scaling = PxMeshScale(),
PxMeshGeometryFlags flags = PxMeshGeometryFlags()) :
PxGeometry (PxGeometryType::eTRIANGLEMESH),
scale (scaling),
meshFlags (flags),
triangleMesh(mesh)
{}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxTriangleMeshGeometry(const PxTriangleMeshGeometry& that) :
PxGeometry (that),
scale (that.scale),
meshFlags (that.meshFlags),
triangleMesh(that.triangleMesh)
{}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxTriangleMeshGeometry& that)
{
mType = that.mType;
scale = that.scale;
meshFlags = that.meshFlags;
triangleMesh = that.triangleMesh;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid for shape creation.
\note A valid triangle mesh has a positive scale value in each direction (scale.scale.x > 0, scale.scale.y > 0, scale.scale.z > 0).
It is illegal to call PxRigidActor::createShape and PxPhysics::createShape with a triangle mesh that has zero extents in any direction.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
public:
PxMeshScale scale; //!< The scaling transformation.
PxMeshGeometryFlags meshFlags; //!< Mesh flags.
PxPadding<3> paddingFromFlags; //!< padding for mesh flags
PxTriangleMesh* triangleMesh; //!< A reference to the mesh object.
};
PX_INLINE bool PxTriangleMeshGeometry::isValid() const
{
if(mType != PxGeometryType::eTRIANGLEMESH)
return false;
if(!scale.scale.isFinite() || !scale.rotation.isUnit())
return false;
if(!scale.isValidForTriangleMesh())
return false;
if(!triangleMesh)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 5,436 | C | 32.770186 | 143 | 0.748344 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxPlaneGeometry.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_PLANE_GEOMETRY_H
#define PX_PLANE_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#include "foundation/PxFoundationConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Class describing a plane geometry.
The plane geometry specifies the half-space volume x<=0. As with other geometry types,
when used in a PxShape the collision volume is obtained by transforming the halfspace
by the shape local pose and the actor global pose.
To generate a PxPlane from a PxTransform, transform PxPlane(1,0,0,0).
To generate a PxTransform from a PxPlane, use PxTransformFromPlaneEquation.
@see PxShape.setGeometry() PxShape.getPlaneGeometry() PxTransformFromPlaneEquation
*/
class PxPlaneGeometry : public PxGeometry
{
public:
/**
\brief Constructor.
*/
PX_INLINE PxPlaneGeometry() : PxGeometry(PxGeometryType::ePLANE) {}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxPlaneGeometry(const PxPlaneGeometry& that) : PxGeometry(that) {}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxPlaneGeometry& that)
{
mType = that.mType;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid
*/
PX_INLINE bool isValid() const;
};
PX_INLINE bool PxPlaneGeometry::isValid() const
{
if(mType != PxGeometryType::ePLANE)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,159 | C | 30.6 | 87 | 0.752453 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxConvexMesh.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_CONVEX_MESH_H
#define PX_CONVEX_MESH_H
/** \addtogroup geomutils
@{
*/
#include "foundation/Px.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Polygon data
Plane format: (mPlane[0],mPlane[1],mPlane[2]).dot(x) + mPlane[3] = 0
With the normal outward-facing from the hull.
*/
struct PxHullPolygon
{
PxReal mPlane[4]; //!< Plane equation for this polygon
PxU16 mNbVerts; //!< Number of vertices/edges in the polygon
PxU16 mIndexBase; //!< Offset in index buffer
};
/**
\brief A convex mesh.
Internally represented as a list of convex polygons. The number
of polygons is limited to 256.
To avoid duplicating data when you have several instances of a particular
mesh positioned differently, you do not use this class to represent a
convex object directly. Instead, you create an instance of this mesh via
the PxConvexMeshGeometry and PxShape classes.
<h3>Creation</h3>
To create an instance of this class call PxPhysics::createConvexMesh(),
and PxConvexMesh::release() to delete it. This is only possible
once you have released all of its #PxShape instances.
<h3>Visualizations:</h3>
\li #PxVisualizationParameter::eCOLLISION_AABBS
\li #PxVisualizationParameter::eCOLLISION_SHAPES
\li #PxVisualizationParameter::eCOLLISION_AXES
\li #PxVisualizationParameter::eCOLLISION_FNORMALS
\li #PxVisualizationParameter::eCOLLISION_EDGES
@see PxConvexMeshDesc PxPhysics.createConvexMesh()
*/
class PxConvexMesh : public PxRefCounted
{
public:
/**
\brief Returns the number of vertices.
\return Number of vertices.
@see getVertices()
*/
virtual PxU32 getNbVertices() const = 0;
/**
\brief Returns the vertices.
\return Array of vertices.
@see getNbVertices()
*/
virtual const PxVec3* getVertices() const = 0;
/**
\brief Returns the index buffer.
\return Index buffer.
@see getNbPolygons() getPolygonData()
*/
virtual const PxU8* getIndexBuffer() const = 0;
/**
\brief Returns the number of polygons.
\return Number of polygons.
@see getIndexBuffer() getPolygonData()
*/
virtual PxU32 getNbPolygons() const = 0;
/**
\brief Returns the polygon data.
\param[in] index Polygon index in [0 ; getNbPolygons()[.
\param[out] data Polygon data.
\return True if success.
@see getIndexBuffer() getNbPolygons()
*/
virtual bool getPolygonData(PxU32 index, PxHullPolygon& data) const = 0;
/**
\brief Decrements the reference count of a convex mesh and releases it if the new reference count is zero.
@see PxPhysics.createConvexMesh() PxConvexMeshGeometry PxShape
*/
virtual void release() = 0;
/**
\brief Returns the mass properties of the mesh assuming unit density.
The following relationship holds between mass and volume:
mass = volume * density
The mass of a unit density mesh is equal to its volume, so this function returns the volume of the mesh.
Similarly, to obtain the localInertia of an identically shaped object with a uniform density of d, simply multiply the
localInertia of the unit density mesh by d.
\param[out] mass The mass of the mesh assuming unit density.
\param[out] localInertia The inertia tensor in mesh local space assuming unit density.
\param[out] localCenterOfMass Position of center of mass (or centroid) in mesh local space.
*/
virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const = 0;
/**
\brief Returns the local-space (vertex space) AABB from the convex mesh.
\return local-space bounds
*/
virtual PxBounds3 getLocalBounds() const = 0;
/**
\brief Returns the local-space Signed Distance Field for this mesh if it has one.
\return local-space SDF.
*/
virtual const PxReal* getSDF() const = 0;
virtual const char* getConcreteTypeName() const { return "PxConvexMesh"; }
/**
\brief This method decides whether a convex mesh is gpu compatible. If the total number of vertices are more than 64 or any number of vertices in a polygon is more than 32, or
convex hull data was not cooked with GPU data enabled during cooking or was loaded from a serialized collection, the convex hull is incompatible with GPU collision detection. Otherwise
it is compatible.
\return True if the convex hull is gpu compatible
*/
virtual bool isGpuCompatible() const = 0;
protected:
PX_INLINE PxConvexMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {}
PX_INLINE PxConvexMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxConvexMesh() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxConvexMesh", PxRefCounted); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,361 | C | 33.02139 | 185 | 0.753655 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxHeightFieldSample.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_HEIGHT_FIELD_SAMPLE_H
#define PX_HEIGHT_FIELD_SAMPLE_H
/** \addtogroup geomutils
@{ */
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxBitAndData.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Special material index values for height field samples.
@see PxHeightFieldSample.materialIndex0 PxHeightFieldSample.materialIndex1
*/
struct PxHeightFieldMaterial
{
enum Enum
{
eHOLE = 127 //!< A material indicating that the triangle should be treated as a hole in the mesh.
};
};
/**
\brief Heightfield sample format.
This format corresponds to the #PxHeightFieldFormat member PxHeightFieldFormat::eS16_TM.
An array of heightfield samples are used when creating a PxHeightField to specify
the elevation of the heightfield points. In addition the material and tessellation of the adjacent
triangles are specified.
@see PxHeightField PxHeightFieldDesc PxHeightFieldDesc.samples
*/
struct PxHeightFieldSample
{
/**
\brief The height of the heightfield sample
This value is scaled by PxHeightFieldGeometry::heightScale.
@see PxHeightFieldGeometry
*/
PxI16 height;
/**
\brief The triangle material index of the quad's lower triangle + tesselation flag
An index pointing into the material table of the shape which instantiates the heightfield.
This index determines the material of the lower of the quad's two triangles (i.e. the quad whose
upper-left corner is this sample, see the Guide for illustrations).
Special values of the 7 data bits are defined by PxHeightFieldMaterial
The tesselation flag specifies which way the quad is split whose upper left corner is this sample.
If the flag is set, the diagonal of the quad will run from this sample to the opposite vertex; if not,
it will run between the other two vertices (see the Guide for illustrations).
@see PxHeightFieldGeometry materialIndex1 PxShape.setmaterials() PxShape.getMaterials()
*/
PxBitAndByte materialIndex0;
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU8 tessFlag() const { return PxU8(materialIndex0.isBitSet() ? 1 : 0); } // PT: explicit conversion to make sure we don't break the code
PX_CUDA_CALLABLE PX_FORCE_INLINE void setTessFlag() { materialIndex0.setBit(); }
PX_CUDA_CALLABLE PX_FORCE_INLINE void clearTessFlag() { materialIndex0.clearBit(); }
/**
\brief The triangle material index of the quad's upper triangle + reserved flag
An index pointing into the material table of the shape which instantiates the heightfield.
This index determines the material of the upper of the quad's two triangles (i.e. the quad whose
upper-left corner is this sample, see the Guide for illustrations).
@see PxHeightFieldGeometry materialIndex0 PxShape.setmaterials() PxShape.getMaterials()
*/
PxBitAndByte materialIndex1;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,535 | C | 38.103448 | 172 | 0.770232 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxBVH.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_BVH_H
#define PX_BVH_H
/** \addtogroup geomutils
@{
*/
#include "common/PxBase.h"
#include "foundation/PxTransform.h"
#include "foundation/PxBounds3.h"
#include "geometry/PxGeometryQueryFlags.h"
#include "geometry/PxReportCallback.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxGeometry;
/**
\brief Class representing a bounding volume hierarchy.
PxBVH can be provided to PxScene::addActor. In this case the scene query
pruning structure inside PhysX SDK will store/update one bound per actor.
The scene queries against such an actor will query actor bounds and then
make a local space query against the provided BVH, which is in actor's
local space.
PxBVH can also be used as a standalone data-structure for arbitrary
purposes, unrelated to PxScene / PxActor.
@see PxScene::addActor
*/
class PxBVH : public PxBase
{
public:
struct RaycastCallback
{
RaycastCallback() {}
virtual ~RaycastCallback() {}
// Reports one raycast or sweep hit.
// boundsIndex [in] Index of touched bounds
// distance [in/out] Impact distance. Shrinks the ray if written out.
// return false to abort the query
virtual bool reportHit(PxU32 boundsIndex, PxReal& distance) = 0;
};
struct OverlapCallback
{
OverlapCallback() {}
virtual ~OverlapCallback() {}
// Reports one overlap hit.
// boundsIndex [in] Index of touched bounds
// return false to abort the query
virtual bool reportHit(PxU32 boundsIndex) = 0;
};
struct TraversalCallback
{
TraversalCallback() {}
virtual ~TraversalCallback() {}
// Reports one visited node.
// bounds [in] node bounds
// return true to continue traversing this branch
virtual bool visitNode(const PxBounds3& bounds) = 0;
// Reports one validated leaf node. Called on leaf nodes after visitNode returns true on them.
// nbPrims [in] number of primitives in the node
// prims [in] primitives in the node (nbPrims entries)
// return false to abort the query
virtual bool reportLeaf(PxU32 nbPrims, const PxU32* prims) = 0;
};
/**
\brief Raycast test against a BVH.
\param[in] origin The origin of the ray.
\param[in] unitDir Normalized direction of the ray.
\param[in] maxDist Maximum ray length, has to be in the [0, inf) range
\param[in] cb Raycast callback, called once per hit
\param[in] queryFlags Optional flags controlling the query.
\return false if query has been aborted
*/
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, RaycastCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Sweep test against a BVH.
\param[in] geom The query volume
\param[in] pose The pose of the query volume
\param[in] unitDir Normalized direction of the sweep.
\param[in] maxDist Maximum sweep length, has to be in the [0, inf) range
\param[in] cb Raycast callback, called once per hit
\param[in] queryFlags Optional flags controlling the query.
\return false if query has been aborted
*/
virtual bool sweep(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, RaycastCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Overlap test against a BVH.
\param[in] geom The query volume
\param[in] pose The pose of the query volume
\param[in] cb Overlap callback, called once per hit
\param[in] queryFlags Optional flags controlling the query.
\return false if query has been aborted
*/
virtual bool overlap(const PxGeometry& geom, const PxTransform& pose, OverlapCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Frustum culling test against a BVH.
This is similar in spirit to an overlap query using a convex object around the frustum.
However this specialized query has better performance, and can support more than the 6 planes
of a frustum, which can be useful in portal-based engines.
On the other hand this test only returns a conservative number of bounds, i.e. some of the returned
bounds may actually be outside the frustum volume, close to it but not touching it. This is usually
an ok performance trade-off when the function is used for view-frustum culling.
\param[in] nbPlanes Number of planes. Only 32 planes max are supported.
\param[in] planes Array of planes, should be in the same space as the BVH.
\param[in] cb Overlap callback, called once per visible object
\param[in] queryFlags Optional flags controlling the query.
\return false if query has been aborted
*/
virtual bool cull(PxU32 nbPlanes, const PxPlane* planes, OverlapCallback& cb, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Returns the number of bounds in the BVH.
You can use #getBounds() to retrieve the bounds.
\note These are the user-defined bounds passed to the BVH builder, not the internal bounds around each BVH node.
\return Number of bounds in the BVH.
@see getBounds() getBoundsForModification()
*/
virtual PxU32 getNbBounds() const = 0;
/**
\brief Retrieve the read-only bounds in the BVH.
\note These are the user-defined bounds passed to the BVH builder, not the internal bounds around each BVH node.
@see PxBounds3 getNbBounds() getBoundsForModification()
*/
virtual const PxBounds3* getBounds() const = 0;
/**
\brief Retrieve the bounds in the BVH.
These bounds can be modified. Call refit() after modifications are done.
\note These are the user-defined bounds passed to the BVH builder, not the internal bounds around each BVH node.
@see PxBounds3 getNbBounds() getBounds() refit() updateBounds() partialRefit()
*/
PX_FORCE_INLINE PxBounds3* getBoundsForModification()
{
return const_cast<PxBounds3*>(getBounds());
}
/**
\brief Refit the BVH.
This function "refits" the tree, i.e. takes the new (leaf) bounding boxes into account and
recomputes all the BVH bounds accordingly. This is an O(n) operation with n = number of bounds in the BVH.
This works best with minor bounds modifications, i.e. when the bounds remain close to their initial values.
With large modifications the tree quality degrades more and more, and subsequent query performance suffers.
It might be a better strategy to create a brand new BVH if bounds change drastically.
This function refits the whole tree after an arbitrary number of bounds have potentially been modified by
users (via getBoundsForModification()). If you only have a small number of bounds to update, it might be
more efficient to use setBounds() and partialRefit() instead.
@see getNbBounds() getBoundsForModification() updateBounds() partialRefit()
*/
virtual void refit() = 0;
/**
\brief Update single bounds.
This is an alternative to getBoundsForModification() / refit(). If you only have a small set of bounds to
update, it can be inefficient to call the refit() function, because it refits the whole BVH.
Instead, one can update individual bounds with this updateBounds() function. It sets the new bounds and
marks the corresponding BVH nodes for partial refit. Once all the individual bounds have been updated,
call partialRefit() to only refit the subset of marked nodes.
\param[in] boundsIndex Index of updated bounds. Valid range is between 0 and getNbBounds().
\param[in] newBounds Updated bounds.
\return true if success
@see getNbBounds() getBoundsForModification() refit() partialRefit()
*/
virtual bool updateBounds(PxU32 boundsIndex, const PxBounds3& newBounds) = 0;
/**
\brief Refits subset of marked nodes.
This is an alternative to the refit() function, to be called after updateBounds() calls.
See updateBounds() for details.
@see getNbBounds() getBoundsForModification() refit() updateBounds()
*/
virtual void partialRefit() = 0;
/**
\brief Generic BVH traversal function.
This can be used to implement custom BVH traversal functions if provided ones are not enough.
In particular this can be used to visualize the tree's bounds.
\param[in] cb Traversal callback, called for each visited node
\return false if query has been aborted
*/
virtual bool traverse(TraversalCallback& cb) const = 0;
virtual const char* getConcreteTypeName() const { return "PxBVH"; }
protected:
PX_INLINE PxBVH(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxBVH(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxBVH() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBVH", PxBase); }
};
struct PxGeomIndexPair;
/**
\brief BVH-vs-BVH overlap test
This function returns pairs of box indices that belong to both the first & second input bvhs.
\param[in] callback The callback object used to report results
\param[in] bvh0 First bvh
\param[in] bvh1 Second bvh
\return true if an overlap has been detected
@see PxBVH PxReportCallback
*/
PX_C_EXPORT PX_PHYSX_COMMON_API bool PX_CALL_CONV PxFindOverlap(PxReportCallback<PxGeomIndexPair>& callback, const PxBVH& bvh0, const PxBVH& bvh1);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 10,915 | C | 37.167832 | 206 | 0.745854 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxGeometryHelpers.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_GEOMETRY_HELPERS_H
#define PX_GEOMETRY_HELPERS_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxPlane.h"
#include "foundation/PxTransform.h"
#include "foundation/PxUnionCast.h"
#include "common/PxPhysXCommonConfig.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxPlaneGeometry.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxHeightFieldGeometry.h"
#include "geometry/PxParticleSystemGeometry.h"
#include "geometry/PxHairSystemGeometry.h"
#include "geometry/PxTetrahedronMeshGeometry.h"
#include "geometry/PxCustomGeometry.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Geometry holder class
This class contains enough space to hold a value of any PxGeometry subtype.
Its principal use is as a convenience class to allow geometries to be returned polymorphically from functions.
*/
PX_ALIGN_PREFIX(4)
class PxGeometryHolder
{
class PxInvalidGeometry : public PxGeometry
{
public:
PX_INLINE PxInvalidGeometry() : PxGeometry(PxGeometryType::eINVALID) {}
};
public:
PX_FORCE_INLINE PxGeometryType::Enum getType() const
{
return any().getType();
}
PX_FORCE_INLINE PxGeometry& any()
{
return *PxUnionCast<PxGeometry*>(&bytes.geometry);
}
PX_FORCE_INLINE const PxGeometry& any() const
{
return *PxUnionCast<const PxGeometry*>(&bytes.geometry);
}
//! @cond
PX_FORCE_INLINE PxSphereGeometry& sphere() { return get<PxSphereGeometry, PxGeometryType::eSPHERE>(); }
PX_FORCE_INLINE const PxSphereGeometry& sphere() const { return get<const PxSphereGeometry, PxGeometryType::eSPHERE>(); }
PX_FORCE_INLINE PxPlaneGeometry& plane() { return get<PxPlaneGeometry, PxGeometryType::ePLANE>(); }
PX_FORCE_INLINE const PxPlaneGeometry& plane() const { return get<const PxPlaneGeometry, PxGeometryType::ePLANE>(); }
PX_FORCE_INLINE PxCapsuleGeometry& capsule() { return get<PxCapsuleGeometry, PxGeometryType::eCAPSULE>(); }
PX_FORCE_INLINE const PxCapsuleGeometry& capsule() const { return get<const PxCapsuleGeometry, PxGeometryType::eCAPSULE>(); }
PX_FORCE_INLINE PxBoxGeometry& box() { return get<PxBoxGeometry, PxGeometryType::eBOX>(); }
PX_FORCE_INLINE const PxBoxGeometry& box() const { return get<const PxBoxGeometry, PxGeometryType::eBOX>(); }
PX_FORCE_INLINE PxConvexMeshGeometry& convexMesh() { return get<PxConvexMeshGeometry, PxGeometryType::eCONVEXMESH>(); }
PX_FORCE_INLINE const PxConvexMeshGeometry& convexMesh() const { return get<const PxConvexMeshGeometry, PxGeometryType::eCONVEXMESH>(); }
PX_FORCE_INLINE PxTetrahedronMeshGeometry& tetMesh() { return get<PxTetrahedronMeshGeometry, PxGeometryType::eTETRAHEDRONMESH>(); }
PX_FORCE_INLINE const PxTetrahedronMeshGeometry& tetMesh() const { return get<const PxTetrahedronMeshGeometry, PxGeometryType::eTETRAHEDRONMESH>(); }
PX_FORCE_INLINE PxTriangleMeshGeometry& triangleMesh() { return get<PxTriangleMeshGeometry, PxGeometryType::eTRIANGLEMESH>(); }
PX_FORCE_INLINE const PxTriangleMeshGeometry& triangleMesh() const { return get<const PxTriangleMeshGeometry, PxGeometryType::eTRIANGLEMESH>(); }
PX_FORCE_INLINE PxHeightFieldGeometry& heightField() { return get<PxHeightFieldGeometry, PxGeometryType::eHEIGHTFIELD>(); }
PX_FORCE_INLINE const PxHeightFieldGeometry& heightField() const { return get<const PxHeightFieldGeometry, PxGeometryType::eHEIGHTFIELD>(); }
PX_FORCE_INLINE PxParticleSystemGeometry& particleSystem() { return get<PxParticleSystemGeometry, PxGeometryType::ePARTICLESYSTEM>(); }
PX_FORCE_INLINE const PxParticleSystemGeometry& particleSystem() const { return get<const PxParticleSystemGeometry, PxGeometryType::ePARTICLESYSTEM>(); }
PX_FORCE_INLINE PxHairSystemGeometry& hairSystem() { return get<PxHairSystemGeometry, PxGeometryType::eHAIRSYSTEM>(); }
PX_FORCE_INLINE const PxHairSystemGeometry& hairSystem() const { return get<const PxHairSystemGeometry, PxGeometryType::eHAIRSYSTEM>(); }
PX_FORCE_INLINE PxCustomGeometry& custom() { return get<PxCustomGeometry, PxGeometryType::eCUSTOM>(); }
PX_FORCE_INLINE const PxCustomGeometry& custom() const { return get<const PxCustomGeometry, PxGeometryType::eCUSTOM>(); }
//! @endcond
PX_FORCE_INLINE void storeAny(const PxGeometry& geometry)
{
PX_ASSERT_WITH_MESSAGE( (geometry.getType() >= PxGeometryType::eSPHERE) &&
(geometry.getType() < PxGeometryType::eGEOMETRY_COUNT),
"Unexpected GeometryType in PxGeometryHolder::storeAny");
switch(geometry.getType())
{
case PxGeometryType::eSPHERE: put<PxSphereGeometry>(geometry); break;
case PxGeometryType::ePLANE: put<PxPlaneGeometry>(geometry); break;
case PxGeometryType::eCAPSULE: put<PxCapsuleGeometry>(geometry); break;
case PxGeometryType::eBOX: put<PxBoxGeometry>(geometry); break;
case PxGeometryType::eCONVEXMESH: put<PxConvexMeshGeometry>(geometry); break;
case PxGeometryType::eTRIANGLEMESH: put<PxTriangleMeshGeometry>(geometry); break;
case PxGeometryType::eTETRAHEDRONMESH: put<PxTetrahedronMeshGeometry>(geometry); break;
case PxGeometryType::eHEIGHTFIELD: put<PxHeightFieldGeometry>(geometry); break;
case PxGeometryType::ePARTICLESYSTEM: put<PxParticleSystemGeometry>(geometry); break;
case PxGeometryType::eHAIRSYSTEM: put<PxHairSystemGeometry>(geometry); break;
case PxGeometryType::eCUSTOM: put<PxCustomGeometry>(geometry); break;
case PxGeometryType::eGEOMETRY_COUNT:
case PxGeometryType::eINVALID: break;
}
}
PX_FORCE_INLINE PxGeometryHolder() { put<PxInvalidGeometry>(PxInvalidGeometry()); }
PX_FORCE_INLINE PxGeometryHolder(const PxGeometry& geometry){ storeAny(geometry); }
private:
template<typename T> void put(const PxGeometry& geometry)
{
static_cast<T&>(any()) = static_cast<const T&>(geometry);
}
template<typename T, PxGeometryType::Enum type> T& get()
{
PX_ASSERT(getType() == type);
return static_cast<T&>(any());
}
template<typename T, PxGeometryType::Enum type> T& get() const
{
PX_ASSERT(getType() == type);
return static_cast<T&>(any());
}
union {
PxU8 geometry[sizeof(PxGeometry)];
PxU8 box[sizeof(PxBoxGeometry)];
PxU8 sphere[sizeof(PxSphereGeometry)];
PxU8 capsule[sizeof(PxCapsuleGeometry)];
PxU8 plane[sizeof(PxPlaneGeometry)];
PxU8 convex[sizeof(PxConvexMeshGeometry)];
PxU8 tetMesh[sizeof(PxTetrahedronMeshGeometry)];
PxU8 mesh[sizeof(PxTriangleMeshGeometry)];
PxU8 heightfield[sizeof(PxHeightFieldGeometry)];
PxU8 particleSystem[sizeof(PxParticleSystemGeometry)];
PxU8 hairSystem[sizeof(PxHairSystemGeometry)];
PxU8 custom[sizeof(PxCustomGeometry)];
} bytes;
}
PX_ALIGN_SUFFIX(4);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 8,630 | C | 43.953125 | 155 | 0.749826 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxHeightFieldGeometry.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_HEIGHT_FIELD_GEOMETRY_H
#define PX_HEIGHT_FIELD_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxTriangleMeshGeometry.h"
#include "common/PxCoreUtilityTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#define PX_MIN_HEIGHTFIELD_XZ_SCALE 1e-8f
#define PX_MIN_HEIGHTFIELD_Y_SCALE (0.0001f / PxReal(0xFFFF))
class PxHeightField;
/**
\brief Height field geometry class.
This class allows to create a scaled height field geometry instance.
There is a minimum allowed value for Y and XZ scaling - PX_MIN_HEIGHTFIELD_XZ_SCALE, heightfield creation will fail if XZ value is below this value.
*/
class PxHeightFieldGeometry : public PxGeometry
{
public:
/**
\brief Constructor.
*/
PX_INLINE PxHeightFieldGeometry(PxHeightField* hf = NULL,
PxMeshGeometryFlags flags = PxMeshGeometryFlag::Enum(0),
PxReal heightScale_ = 1.0f,
PxReal rowScale_ = 1.0f,
PxReal columnScale_ = 1.0f) :
PxGeometry (PxGeometryType::eHEIGHTFIELD),
heightField (hf),
heightScale (heightScale_),
rowScale (rowScale_),
columnScale (columnScale_),
heightFieldFlags (flags)
{
}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxHeightFieldGeometry(const PxHeightFieldGeometry& that) :
PxGeometry (that),
heightField (that.heightField),
heightScale (that.heightScale),
rowScale (that.rowScale),
columnScale (that.columnScale),
heightFieldFlags (that.heightFieldFlags)
{
}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxHeightFieldGeometry& that)
{
mType = that.mType;
heightField = that.heightField;
heightScale = that.heightScale;
rowScale = that.rowScale;
columnScale = that.columnScale;
heightFieldFlags = that.heightFieldFlags;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid
\note A valid height field has a positive scale value in each direction (heightScale > 0, rowScale > 0, columnScale > 0).
It is illegal to call PxRigidActor::createShape and PxPhysics::createShape with a height field that has zero extents in any direction.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
public:
/**
\brief The height field data.
*/
PxHeightField* heightField;
/**
\brief The scaling factor for the height field in vertical direction (y direction in local space).
*/
PxReal heightScale;
/**
\brief The scaling factor for the height field in the row direction (x direction in local space).
*/
PxReal rowScale;
/**
\brief The scaling factor for the height field in the column direction (z direction in local space).
*/
PxReal columnScale;
/**
\brief Flags to specify some collision properties for the height field.
*/
PxMeshGeometryFlags heightFieldFlags;
PxPadding<3> paddingFromFlags; //!< padding for mesh flags.
};
PX_INLINE bool PxHeightFieldGeometry::isValid() const
{
if(mType != PxGeometryType::eHEIGHTFIELD)
return false;
if(!PxIsFinite(heightScale) || !PxIsFinite(rowScale) || !PxIsFinite(columnScale))
return false;
if(rowScale < PX_MIN_HEIGHTFIELD_XZ_SCALE || columnScale < PX_MIN_HEIGHTFIELD_XZ_SCALE || heightScale < PX_MIN_HEIGHTFIELD_Y_SCALE)
return false;
if(!heightField)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 5,090 | C | 30.042683 | 148 | 0.738114 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxTriangle.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_TRIANGLE_H
#define PX_TRIANGLE_H
/** \addtogroup geomutils
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVec3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Triangle class.
*/
class PxTriangle
{
public:
/**
\brief Constructor
*/
PX_FORCE_INLINE PxTriangle() {}
/**
\brief Constructor
\param[in] p0 Point 0
\param[in] p1 Point 1
\param[in] p2 Point 2
*/
PX_FORCE_INLINE PxTriangle(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2)
{
verts[0] = p0;
verts[1] = p1;
verts[2] = p2;
}
/**
\brief Copy constructor
\param[in] triangle Tri to copy
*/
PX_FORCE_INLINE PxTriangle(const PxTriangle& triangle)
{
verts[0] = triangle.verts[0];
verts[1] = triangle.verts[1];
verts[2] = triangle.verts[2];
}
/**
\brief Destructor
*/
PX_FORCE_INLINE ~PxTriangle() {}
/**
\brief Assignment operator
*/
PX_FORCE_INLINE void operator=(const PxTriangle& triangle)
{
verts[0] = triangle.verts[0];
verts[1] = triangle.verts[1];
verts[2] = triangle.verts[2];
}
/**
\brief Compute the normal of the Triangle.
\param[out] _normal Triangle normal.
*/
PX_FORCE_INLINE void normal(PxVec3& _normal) const
{
_normal = (verts[1]-verts[0]).cross(verts[2]-verts[0]);
_normal.normalize();
}
/**
\brief Compute the unnormalized normal of the triangle.
\param[out] _normal Triangle normal (not normalized).
*/
PX_FORCE_INLINE void denormalizedNormal(PxVec3& _normal) const
{
_normal = (verts[1]-verts[0]).cross(verts[2]-verts[0]);
}
/**
\brief Compute the area of the triangle.
\return Area of the triangle.
*/
PX_FORCE_INLINE PxReal area() const
{
const PxVec3& p0 = verts[0];
const PxVec3& p1 = verts[1];
const PxVec3& p2 = verts[2];
return ((p0 - p1).cross(p0 - p2)).magnitude() * 0.5f;
}
/**
\return Computes a point on the triangle from u and v barycentric coordinates.
*/
PX_FORCE_INLINE PxVec3 pointFromUV(PxReal u, PxReal v) const
{
return (1.0f-u-v)*verts[0] + u*verts[1] + v*verts[2];
}
/**
\brief Array of Vertices.
*/
PxVec3 verts[3];
};
//! A padded version of PxTriangle, to safely load its data using SIMD
class PxTrianglePadded : public PxTriangle
{
public:
PX_FORCE_INLINE PxTrianglePadded() {}
PX_FORCE_INLINE ~PxTrianglePadded() {}
PxU32 padding;
};
#if !PX_DOXYGEN
}
#endif
/** @} */
#endif
| 4,047 | C | 24.620253 | 83 | 0.703237 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxGeometryInternal.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_GEOMETRY_INTERNAL_H
#define PX_GEOMETRY_INTERNAL_H
/** \addtogroup geomutils
@{ */
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVec3.h"
#include "geometry/PxTriangleMesh.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxTriangleMesh;
struct PxTriangleMeshInternalData
{
PxU32 mNbVertices;
PxU32 mNbTriangles;
PxVec3* mVertices;
void* mTriangles;
PxU32* mFaceRemap;
PxVec3 mAABB_Center;
PxVec3 mAABB_Extents;
PxReal mGeomEpsilon;
PxU8 mFlags;
//
PxU32 mNbNodes;
PxU32 mNodeSize;
void* mNodes;
PxU32 mInitData;
PxVec3 mCenterOrMinCoeff;
PxVec3 mExtentsOrMaxCoeff;
bool mQuantized;
PX_FORCE_INLINE PxU32 getSizeofVerticesInBytes() const
{
return mNbVertices * sizeof(PxVec3);
}
PX_FORCE_INLINE PxU32 getSizeofTrianglesInBytes() const
{
const PxU32 triangleSize = mFlags & PxTriangleMeshFlag::e16_BIT_INDICES ? sizeof(PxU16) : sizeof(PxU32);
return mNbTriangles * 3 * triangleSize;
}
PX_FORCE_INLINE PxU32 getSizeofFaceRemapInBytes() const
{
return mNbTriangles * sizeof(PxU32);
}
PX_FORCE_INLINE PxU32 getSizeofNodesInBytes() const
{
return mNbNodes * mNodeSize;
}
};
PX_C_EXPORT PX_PHYSX_COMMON_API bool PX_CALL_CONV PxGetTriangleMeshInternalData(PxTriangleMeshInternalData& data, const PxTriangleMesh& mesh, bool takeOwnership);
class PxBVH;
struct PxBVHInternalData
{
PxU32 mNbIndices;
PxU32 mNbNodes;
PxU32 mNodeSize;
void* mNodes;
PxU32* mIndices; // Can be null
void* mBounds;
PX_FORCE_INLINE PxU32 getSizeofNodesInBytes() const
{
return mNbNodes * mNodeSize;
}
PX_FORCE_INLINE PxU32 getSizeofIndicesInBytes() const
{
return mNbIndices * sizeof(PxU32);
}
PX_FORCE_INLINE PxU32 getSizeofBoundsInBytes() const
{
return (mNbIndices+1)*6;
}
};
PX_C_EXPORT PX_PHYSX_COMMON_API bool PX_CALL_CONV PxGetBVHInternalData(PxBVHInternalData& data, const PxBVH& bvh, bool takeOwnership);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,708 | C | 28.91129 | 163 | 0.748112 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxHairSystemDesc.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.
#ifndef PX_HAIRSYSTEM_DESC_H
#define PX_HAIRSYSTEM_DESC_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxFlags.h"
#include "common/PxCoreUtilityTypes.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxHairSystemDescFlag
{
enum Enum
{
/**
Determines whether or not to allocate memory on device (GPU) or on Host (CPU)
*/
eDEVICE_MEMORY = (1<<0)
};
};
/**
\brief collection of set bits defined in PxHairSystemDescFlag
\see PxHairSystemDescFlag
*/
typedef PxFlags<PxHairSystemDescFlag::Enum, PxU16> PxHairSystemDescFlags;
PX_FLAGS_OPERATORS(PxHairSystemDescFlag::Enum, PxU16)
/**
\brief Descriptor class for #PxHairSystem
\note The data is *copied* when a PxHairSystem object is created from this
descriptor. The user may discard the data after the call.
\see PxHairSystem PxHairSystemGeometry PxShape PxPhysics.createHairSystem()
PxCooking.createHairSystem()
*/
class PxHairSystemDesc
{
public:
/**
\brief The number of strands in this hair system
<b>Default:</b> 0
*/
PxU32 numStrands;
/**
\brief The length of a hair segment
<b>Default:</b> 0.1
*/
PxReal segmentLength;
/**
\brief The radius of a hair segment
<b>Default:</b> 0.01
*/
PxReal segmentRadius;
/**
\brief Specifies the number of vertices each strand is composed of.
Length must be equal to numStrands, elements assumed to be of
type PxU32. Number of segments = numVerticesPerStrand - 1.
<b>Default:</b> NULL
*/
PxBoundedData numVerticesPerStrand;
/**
\brief Vertex positions and inverse mass [x,y,z,1/m] in PxBoundedData format.
If count equal to numStrands, assumed to be strand root positions,
otherwise positions of all vertices sorted by strands and increasing
from root towards tip of strand.
Type assumed to be of PxReal.
<b>Default:</b> NULL
*/
PxBoundedData vertices;
/**
\brief Vertex velocities in PxBoundedData format.
If NULL, zero velocity is assumed.
Type assumed to be of PxReal.
<b>Default:</b> NULL
*/
PxBoundedData velocities;
/**
\brief Flags bits, combined from values of the enum ::PxHairSystemDesc
<b>Default:</b> 0
*/
PxHairSystemDescFlags flags;
/**
\brief Constructor with default initialization
*/
PX_INLINE PxHairSystemDesc();
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault();
/**
\brief Check whether the descriptor is valid
\return True if the current settings are valid
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxHairSystemDesc::PxHairSystemDesc()
{
numStrands = 0;
segmentLength = 0.1f;
segmentRadius = 0.01f;
}
PX_INLINE void PxHairSystemDesc::setToDefault()
{
*this = PxHairSystemDesc();
}
PX_INLINE bool PxHairSystemDesc::isValid() const
{
if (segmentLength < 0.0f || segmentRadius < 0.0f)
return false;
if (2.0f * segmentRadius >= segmentLength)
return false;
if (numStrands == 0)
return false;
if (numVerticesPerStrand.count != numStrands)
return false;
PxU32 totalNumVertices = 0;
for (PxU32 i = 0; i < numVerticesPerStrand.count; i++)
{
const PxU32 numVertices = numVerticesPerStrand.at<PxU32>(i);
totalNumVertices += numVertices;
if (numVertices < 2)
{
return false;
}
}
if (vertices.count != totalNumVertices && vertices.count != numStrands)
return false;
if (velocities.count != totalNumVertices && velocities.count != 0)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
/** @} */
#endif
| 5,151 | C | 24.631841 | 80 | 0.717919 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxGeometryQuery.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_GEOMETRY_QUERY_H
#define PX_GEOMETRY_QUERY_H
/**
\brief Maximum sweep distance for scene sweeps. The distance parameter for sweep functions will be clamped to this value.
The reason for this is GJK support cannot be evaluated near infinity. A viable alternative can be a sweep followed by an infinite raycast.
@see PxScene
*/
#define PX_MAX_SWEEP_DISTANCE 1e8f
/** \addtogroup geomutils
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryFlags.h"
#include "geometry/PxGeometryQueryContext.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxGeometry;
class PxContactBuffer;
/**
\brief Collection of geometry object queries (sweeps, raycasts, overlaps, ...).
*/
class PxGeometryQuery
{
public:
/**
\brief Raycast test against a geometry object.
All geometry types are supported except PxParticleSystemGeometry, PxTetrahedronMeshGeometry and PxHairSystemGeometry.
\param[in] origin The origin of the ray to test the geometry object against
\param[in] unitDir Normalized direction of the ray to test the geometry object against
\param[in] geom The geometry object to test the ray against
\param[in] pose Pose of the geometry object
\param[in] maxDist Maximum ray length, has to be in the [0, inf) range
\param[in] hitFlags Specification of the kind of information to retrieve on hit. Combination of #PxHitFlag flags
\param[in] maxHits max number of returned hits = size of 'rayHits' buffer
\param[out] rayHits Raycast hits information
\param[in] stride Stride value (in number of bytes) for rayHits array. Typically sizeof(PxGeomRaycastHit) for packed arrays.
\param[in] queryFlags Optional flags controlling the query.
\param[in] threadContext Optional user-defined per-thread context.
\return Number of hits between the ray and the geometry object
@see PxGeomRaycastHit PxGeometry PxTransform
*/
PX_PHYSX_COMMON_API static PxU32 raycast( const PxVec3& origin, const PxVec3& unitDir,
const PxGeometry& geom, const PxTransform& pose,
PxReal maxDist, PxHitFlags hitFlags,
PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT rayHits, PxU32 stride = sizeof(PxGeomRaycastHit), PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT,
PxRaycastThreadContext* threadContext = NULL);
/**
\brief Overlap test for two geometry objects.
All combinations are supported except:
\li PxPlaneGeometry vs. {PxPlaneGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry}
\li PxTriangleMeshGeometry vs. PxHeightFieldGeometry
\li PxHeightFieldGeometry vs. PxHeightFieldGeometry
\li Anything involving PxParticleSystemGeometry, PxTetrahedronMeshGeometry or PxHairSystemGeometry.
\param[in] geom0 The first geometry object
\param[in] pose0 Pose of the first geometry object
\param[in] geom1 The second geometry object
\param[in] pose1 Pose of the second geometry object
\param[in] queryFlags Optional flags controlling the query.
\param[in] threadContext Optional user-defined per-thread context.
\return True if the two geometry objects overlap
@see PxGeometry PxTransform
*/
PX_PHYSX_COMMON_API static bool overlap(const PxGeometry& geom0, const PxTransform& pose0,
const PxGeometry& geom1, const PxTransform& pose1,
PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT, PxOverlapThreadContext* threadContext=NULL);
/**
\brief Sweep a specified geometry object in space and test for collision with a given object.
The following combinations are supported.
\li PxSphereGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry}
\li PxCapsuleGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry}
\li PxBoxGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry}
\li PxConvexMeshGeometry vs. {PxSphereGeometry, PxPlaneGeometry, PxCapsuleGeometry, PxBoxGeometry, PxConvexMeshGeometry, PxTriangleMeshGeometry, PxHeightFieldGeometry}
\param[in] unitDir Normalized direction along which object geom0 should be swept
\param[in] maxDist Maximum sweep distance, has to be in the [0, inf) range
\param[in] geom0 The geometry object to sweep. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry, #PxBoxGeometry and #PxConvexMeshGeometry
\param[in] pose0 Pose of the geometry object to sweep
\param[in] geom1 The geometry object to test the sweep against
\param[in] pose1 Pose of the geometry object to sweep against
\param[out] sweepHit The sweep hit information. Only valid if this method returns true.
\param[in] hitFlags Specify which properties per hit should be computed and written to result hit array. Combination of #PxHitFlag flags
\param[in] inflation Surface of the swept shape is additively extruded in the normal direction, rounding corners and edges.
\param[in] queryFlags Optional flags controlling the query.
\param[in] threadContext Optional user-defined per-thread context.
\return True if the swept geometry object geom0 hits the object geom1
@see PxGeomSweepHit PxGeometry PxTransform
*/
PX_PHYSX_COMMON_API static bool sweep( const PxVec3& unitDir, const PxReal maxDist,
const PxGeometry& geom0, const PxTransform& pose0,
const PxGeometry& geom1, const PxTransform& pose1,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxReal inflation = 0.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT,
PxSweepThreadContext* threadContext = NULL);
/**
\brief Compute minimum translational distance (MTD) between two geometry objects.
All combinations of geom objects are supported except:
- plane/plane
- plane/mesh
- plane/heightfield
- mesh/mesh
- mesh/heightfield
- heightfield/heightfield
- anything involving PxParticleSystemGeometry, PxTetrahedronMeshGeometry or PxHairSystemGeometry
The function returns a unit vector ('direction') and a penetration depth ('depth').
The depenetration vector D = direction * depth should be applied to the first object, to
get out of the second object.
Returned depth should always be positive or null.
If objects do not overlap, the function can not compute the MTD and returns false.
\param[out] direction Computed MTD unit direction
\param[out] depth Penetration depth. Always positive or null.
\param[in] geom0 The first geometry object
\param[in] pose0 Pose of the first geometry object
\param[in] geom1 The second geometry object
\param[in] pose1 Pose of the second geometry object
\param[in] queryFlags Optional flags controlling the query.
\return True if the MTD has successfully been computed, i.e. if objects do overlap.
@see PxGeometry PxTransform
*/
PX_PHYSX_COMMON_API static bool computePenetration( PxVec3& direction, PxF32& depth,
const PxGeometry& geom0, const PxTransform& pose0,
const PxGeometry& geom1, const PxTransform& pose1,
PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT);
/**
\brief Computes distance between a point and a geometry object.
Currently supported geometry objects: box, sphere, capsule, convex, mesh.
\note For meshes, only the BVH34 midphase data-structure is supported.
\param[in] point The point P
\param[in] geom The geometry object
\param[in] pose Pose of the geometry object
\param[out] closestPoint Optionally returned closest point to P on the geom object. Only valid when returned distance is strictly positive.
\param[out] closestIndex Optionally returned closest (triangle) index. Only valid for triangle meshes.
\param[in] queryFlags Optional flags controlling the query.
\return Square distance between the point and the geom object, or 0.0 if the point is inside the object, or -1.0 if an error occured (geometry type is not supported, or invalid pose)
@see PxGeometry PxTransform
*/
PX_PHYSX_COMMON_API static PxReal pointDistance(const PxVec3& point, const PxGeometry& geom, const PxTransform& pose,
PxVec3* closestPoint=NULL, PxU32* closestIndex=NULL,
PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT);
/**
\brief computes the bounds for a geometry object
\param[out] bounds Returned computed bounds
\param[in] geom The geometry object
\param[in] pose Pose of the geometry object
\param[in] offset Offset for computed bounds. This value is added to the geom's extents.
\param[in] inflation Scale factor for computed bounds. The geom's extents are multiplied by this value.
\param[in] queryFlags Optional flags controlling the query.
@see PxGeometry PxTransform
*/
PX_PHYSX_COMMON_API static void computeGeomBounds(PxBounds3& bounds, const PxGeometry& geom, const PxTransform& pose, float offset=0.0f, float inflation=1.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT);
/**
\brief Generate collision contacts between a convex geometry and a single triangle
\param[in] geom The geometry object. Can be a capsule, a box or a convex mesh
\param[in] pose Pose of the geometry object
\param[in] triangleVertices Triangle vertices in local space
\param[in] triangleIndex Triangle index
\param[in] contactDistance The distance at which contacts begin to be generated between the pairs
\param[in] meshContactMargin The mesh contact margin.
\param[in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units
\param[out] contactBuffer A buffer to write contacts to.
\return True if there was collision
*/
PX_PHYSX_COMMON_API static bool generateTriangleContacts(const PxGeometry& geom, const PxTransform& pose, const PxVec3 triangleVertices[3], PxU32 triangleIndex, PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength, PxContactBuffer& contactBuffer);
/**
\brief Checks if provided geometry is valid.
\param[in] geom The geometry object.
\return True if geometry is valid.
@see PxGeometry
*/
PX_PHYSX_COMMON_API static bool isValid(const PxGeometry& geom);
};
#if !PX_DOXYGEN
}
#endif
/** @} */
#endif
| 12,120 | C | 46.909091 | 268 | 0.77401 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxGeometryQueryContext.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_GEOMETRY_QUERY_CONTEXT_H
#define PX_GEOMETRY_QUERY_CONTEXT_H
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A per-thread context passed to low-level query functions.
This is a user-defined optional parameter that gets passed down to low-level query functions (raycast / overlap / sweep).
This is not used directly in PhysX, although the context in this case is the PxHitCallback used in the query. This allows
user-defined query functions, such as the ones from PxCustomGeometry, to get some additional data about the query. In this
case this is a 'per-query' context rather than 'per-thread', but the initial goal of this parameter is to give custom
query callbacks access to per-thread data structures (e.g. caches) that could be needed to implement the callbacks.
In any case this is mostly for user-controlled query systems.
*/
struct PxQueryThreadContext
{
};
/**
\brief A per-thread context passed to low-level raycast functions.
*/
typedef PxQueryThreadContext PxRaycastThreadContext;
/**
\brief A per-thread context passed to low-level overlap functions.
*/
typedef PxQueryThreadContext PxOverlapThreadContext;
/**
\brief A per-thread context passed to low-level sweep functions.
*/
typedef PxQueryThreadContext PxSweepThreadContext;
#if !PX_DOXYGEN
}
#endif
#endif
| 3,063 | C | 39.853333 | 123 | 0.768528 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxGjkQuery.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_GJK_QUERY_H
#define PX_GJK_QUERY_H
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Collection of GJK query functions (sweeps, raycasts, overlaps, ...).
*/
class PxGjkQuery
{
public:
/**
\brief Abstract interface for a user defined shape GJK mapping support.
A user defined shape consists of a core shape and a margin. If the distance
between two shapes' cores is equal to the sum of their margins, these shapes are
considered touching.
*/
struct Support
{
/* Virtual destructor */
virtual ~Support() {}
/**
\brief Return the user defined shape margin. Margin should be greater than or equal to 0
\return Margin.
*/
virtual PxReal getMargin() const = 0;
/**
\brief Return the farthest point on the user defined shape's core in given direction.
\param[in] dir Direction
\return Farthest point in given direction.
*/
virtual PxVec3 supportLocal(const PxVec3& dir) const = 0;
};
/**
\brief Computes proximity information for two shapes using GJK-EPA algorithm
\param[in] a Shape A support mapping
\param[in] b Shape B support mapping
\param[in] poseA Shape A transformation
\param[in] poseB Shape B transformation
\param[in] contactDistance The distance at which proximity info begins to be computed between the shapes
\param[in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units
\param[out] pointA The closest/deepest point on shape A surface
\param[out] pointB The closest/deepest point on shape B surface
\param[out] separatingAxis Translating shape B along 'separatingAxis' by 'separation' makes the shapes touching
\param[out] separation Translating shape B along 'separatingAxis' by 'separation' makes the shapes touching
\return False if the distance greater than contactDistance.
*/
PX_PHYSX_COMMON_API static bool proximityInfo(const Support& a, const Support& b, const PxTransform& poseA, const PxTransform& poseB,
PxReal contactDistance, PxReal toleranceLength, PxVec3& pointA, PxVec3& pointB, PxVec3& separatingAxis, PxReal& separation);
/**
\brief Raycast test against the given shape.
\param[in] shape Shape support mapping
\param[in] pose Shape transformation
\param[in] rayStart The start point of the ray to test the shape against
\param[in] unitDir Normalized direction of the ray to test the shape against
\param[in] maxDist Maximum ray length, has to be in the [0, inf) range
\param[out] t Hit distance
\param[out] n Hit normal
\param[out] p Hit point
\return True if there is a hit.
*/
PX_PHYSX_COMMON_API static bool raycast(const Support& shape, const PxTransform& pose, const PxVec3& rayStart,
const PxVec3& unitDir, PxReal maxDist, PxReal& t, PxVec3& n, PxVec3& p);
/**
\brief Overlap test for two shapes.
\param[in] a Shape A support mapping
\param[in] b Shape B support mapping
\param[in] poseA Shape A transformation
\param[in] poseB Shape B transformation
\return True if the shapes overlap.
*/
PX_PHYSX_COMMON_API static bool overlap(const Support& a, const Support& b, const PxTransform& poseA, const PxTransform& poseB);
/**
\brief Sweep the shape B in space and test for collision with the shape A.
\param[in] a Shape A support mapping
\param[in] b Shape B support mapping
\param[in] poseA Shape A transformation
\param[in] poseB Shape B transformation
\param[in] unitDir Normalized direction of the ray to test the shape against
\param[in] maxDist Maximum ray length, has to be in the [0, inf) range
\param[out] t Hit distance
\param[out] n Hit normal
\param[out] p Hit point
\return True if there is a hit.
*/
PX_PHYSX_COMMON_API static bool sweep(const Support& a, const Support& b, const PxTransform& poseA, const PxTransform& poseB,
const PxVec3& unitDir, PxReal maxDist, PxReal& t, PxVec3& n, PxVec3& p);
};
#if !PX_DOXYGEN
}
#endif
#endif
| 5,789 | C | 38.657534 | 170 | 0.744515 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxTetrahedronMeshGeometry.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_TETRAHEDRON_GEOMETRY_H
#define PX_TETRAHEDRON_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#include "geometry/PxMeshScale.h"
#include "common/PxCoreUtilityTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxTetrahedronMesh;
/**
\brief Tetrahedron mesh geometry class.
This class wraps a tetrahedron mesh such that it can be used in contexts where a PxGeometry type is needed.
*/
class PxTetrahedronMeshGeometry : public PxGeometry
{
public:
/**
\brief Constructor. By default creates an empty object with a NULL mesh and identity scale.
*/
PX_INLINE PxTetrahedronMeshGeometry(PxTetrahedronMesh* mesh = NULL) :
PxGeometry(PxGeometryType::eTETRAHEDRONMESH),
tetrahedronMesh(mesh)
{}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxTetrahedronMeshGeometry(const PxTetrahedronMeshGeometry& that) :
PxGeometry(that),
tetrahedronMesh(that.tetrahedronMesh)
{}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxTetrahedronMeshGeometry& that)
{
mType = that.mType;
tetrahedronMesh = that.tetrahedronMesh;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid for shape creation.
\note A valid tetrahedron mesh has a positive scale value in each direction (scale.scale.x > 0, scale.scale.y > 0, scale.scale.z > 0).
It is illegal to call PxRigidActor::createShape and PxPhysics::createShape with a tetrahedron mesh that has zero extents in any direction.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
public:
PxTetrahedronMesh* tetrahedronMesh; //!< A reference to the mesh object.
};
PX_INLINE bool PxTetrahedronMeshGeometry::isValid() const
{
if(mType != PxGeometryType::eTETRAHEDRONMESH)
return false;
if(!tetrahedronMesh)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,699 | C | 32.035714 | 140 | 0.747229 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxMeshQuery.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_MESH_QUERY_H
#define PX_MESH_QUERY_H
/** \addtogroup geomutils
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryFlags.h"
#include "geometry/PxReportCallback.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxGeometry;
class PxConvexMeshGeometry;
class PxTriangleMeshGeometry;
class PxHeightFieldGeometry;
class PxTriangle;
struct PxMeshMeshQueryFlag
{
enum Enum
{
eDEFAULT = 0, //!< Report all overlaps
eDISCARD_COPLANAR = (1<<0), //!< Ignore coplanar triangle-triangle overlaps
eRESERVED = (1<<1), //!< Reserved flag
eRESERVED1 = (1<<1), //!< Reserved flag
eRESERVED2 = (1<<2), //!< Reserved flag
eRESERVED3 = (1<<3) //!< Reserved flag
};
};
PX_FLAGS_TYPEDEF(PxMeshMeshQueryFlag, PxU32)
class PxMeshQuery
{
public:
/**
\brief Retrieves triangle data from a triangle ID.
This function can be used together with #findOverlapTriangleMesh() to retrieve triangle properties.
\param[in] triGeom Geometry of the triangle mesh to extract the triangle from.
\param[in] transform Transform for the triangle mesh
\param[in] triangleIndex The index of the triangle to retrieve.
\param[out] triangle Triangle points in world space.
\param[out] vertexIndices Returned vertex indices for given triangle
\param[out] adjacencyIndices Returned 3 triangle adjacency internal face indices (0xFFFFFFFF if no adjacency). The mesh must be cooked with cooking param buildTriangleAdjacencies enabled.
\note This function will flip the triangle normal whenever triGeom.scale.hasNegativeDeterminant() is true.
@see PxTriangle PxTriangleFlags PxTriangleID findOverlapTriangleMesh()
*/
PX_PHYSX_COMMON_API static void getTriangle(const PxTriangleMeshGeometry& triGeom, const PxTransform& transform, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices=NULL, PxU32* adjacencyIndices=NULL);
/**
\brief Retrieves triangle data from a triangle ID.
This function can be used together with #findOverlapHeightField() to retrieve triangle properties.
\param[in] hfGeom Geometry of the height field to extract the triangle from.
\param[in] transform Transform for the height field.
\param[in] triangleIndex The index of the triangle to retrieve.
\param[out] triangle Triangle points in world space.
\param[out] vertexIndices Returned vertex indices for given triangle
\param[out] adjacencyIndices Returned 3 triangle adjacency triangle indices (0xFFFFFFFF if no adjacency).
\note This function will flip the triangle normal whenever triGeom.scale.hasNegativeDeterminant() is true.
\note TriangleIndex is an index used in internal format, which does have an index out of the bounds in last row.
To traverse all tri indices in the HF, the following code can be applied:
for (PxU32 row = 0; row < (nbRows - 1); row++)
{
for (PxU32 col = 0; col < (nbCols - 1); col++)
{
for (PxU32 k = 0; k < 2; k++)
{
const PxU32 triIndex = 2 * (row*nbCols + col) + k;
....
}
}
}
@see PxTriangle PxTriangleFlags PxTriangleID findOverlapHeightField()
*/
PX_PHYSX_COMMON_API static void getTriangle(const PxHeightFieldGeometry& hfGeom, const PxTransform& transform, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices=NULL, PxU32* adjacencyIndices=NULL);
/**
\brief Find the mesh triangles which touch the specified geometry object.
For mesh-vs-mesh overlap tests, please use the specialized function below.
Returned triangle indices can be used with #getTriangle() to retrieve the triangle properties.
\param[in] geom The geometry object to test for mesh triangle overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry
\param[in] geomPose Pose of the geometry object
\param[in] meshGeom The triangle mesh geometry to check overlap against
\param[in] meshPose Pose of the triangle mesh
\param[out] results Indices of overlapping triangles
\param[in] maxResults Size of 'results' buffer
\param[in] startIndex Index of first result to be retrieved. Previous indices are skipped.
\param[out] overflow True if a buffer overflow occurred
\param[in] queryFlags Optional flags controlling the query.
\return Number of overlaps found, i.e. number of elements written to the results buffer
@see PxTriangleMeshGeometry getTriangle() PxGeometryQueryFlags
*/
PX_PHYSX_COMMON_API static PxU32 findOverlapTriangleMesh( const PxGeometry& geom, const PxTransform& geomPose,
const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose,
PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow,
PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT);
/**
\brief Mesh-vs-mesh overlap test
A specialized findOverlapTriangleMesh function for mesh-vs-mesh. The other findOverlapTriangleMesh() function above cannot be used
directly since it only returns a single set of triangle indices that belongs to one of the meshes only. This function returns pairs
of triangle indices that belong to both the first & second input meshes.
Returned triangle indices can be used with #getTriangle() to retrieve the triangle properties.
\note This is only implemented for the PxMeshMidPhase::eBVH34 data structure.
\param[in] callback The callback object used to report results
\param[in] meshGeom0 First triangle mesh geometry
\param[in] meshPose0 Pose of first triangle mesh geometry
\param[in] meshGeom1 Second triangle mesh geometry
\param[in] meshPose1 Pose of second triangle mesh geometry
\param[in] queryFlags Optional flags controlling the query.
\param[in] meshMeshFlags Optional flags controlling the query.
\param[in] tolerance Optional tolerance distance
\return true if an overlap has been detected, false if the meshes are disjoint
@see PxTriangleMeshGeometry getTriangle() PxReportCallback PxGeometryQueryFlags PxMeshMeshQueryFlags
*/
PX_PHYSX_COMMON_API static bool findOverlapTriangleMesh(PxReportCallback<PxGeomIndexPair>& callback,
const PxTriangleMeshGeometry& meshGeom0, const PxTransform& meshPose0,
const PxTriangleMeshGeometry& meshGeom1, const PxTransform& meshPose1,
PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT,
PxMeshMeshQueryFlags meshMeshFlags = PxMeshMeshQueryFlag::eDEFAULT,
float tolerance = 0.0f);
/**
\brief Find the height field triangles which touch the specified geometry object.
Returned triangle indices can be used with #getTriangle() to retrieve the triangle properties.
\param[in] geom The geometry object to test for height field overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry. The sphere and capsule queries are currently conservative estimates.
\param[in] geomPose Pose of the geometry object
\param[in] hfGeom The height field geometry to check overlap against
\param[in] hfPose Pose of the height field
\param[out] results Indices of overlapping triangles
\param[in] maxResults Size of 'results' buffer
\param[in] startIndex Index of first result to be retrieved. Previous indices are skipped.
\param[out] overflow True if a buffer overflow occurred
\param[in] queryFlags Optional flags controlling the query.
\return Number of overlaps found, i.e. number of elements written to the results buffer
@see PxHeightFieldGeometry getTriangle() PxGeometryQueryFlags
*/
PX_PHYSX_COMMON_API static PxU32 findOverlapHeightField(const PxGeometry& geom, const PxTransform& geomPose,
const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose,
PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow,
PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT);
/**
\brief Sweep a specified geometry object in space and test for collision with a set of given triangles.
This function simply sweeps input geometry against each input triangle, in the order they are given.
This is an O(N) operation with N = number of input triangles. It does not use any particular acceleration structure.
\param[in] unitDir Normalized direction of the sweep.
\param[in] distance Sweep distance. Needs to be larger than 0. Clamped to PX_MAX_SWEEP_DISTANCE.
\param[in] geom The geometry object to sweep. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry
\param[in] pose Pose of the geometry object to sweep.
\param[in] triangleCount Number of specified triangles
\param[in] triangles Array of triangles to sweep against
\param[out] sweepHit The sweep hit information. See the notes below for limitations about returned results.
\param[in] hitFlags Specification of the kind of information to retrieve on hit. Combination of #PxHitFlag flags. See the notes below for limitations about supported flags.
\param[in] cachedIndex Cached triangle index for subsequent calls. Cached triangle is tested first. Optional parameter.
\param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal.
\param[in] doubleSided Counterpart of PxMeshGeometryFlag::eDOUBLE_SIDED for input triangles.
\param[in] queryFlags Optional flags controlling the query.
\return True if the swept geometry object hits the specified triangles
\note Only the following geometry types are currently supported: PxSphereGeometry, PxCapsuleGeometry, PxBoxGeometry
\note If a shape from the scene is already overlapping with the query shape in its starting position, the hit is returned unless eASSUME_NO_INITIAL_OVERLAP was specified.
\note This function returns a single closest hit across all the input triangles. Multiple hits are not supported.
\note Supported hitFlags are PxHitFlag::eDEFAULT, PxHitFlag::eASSUME_NO_INITIAL_OVERLAP, PxHitFlag::ePRECISE_SWEEP, PxHitFlag::eMESH_BOTH_SIDES, PxHitFlag::eMESH_ANY.
\note ePOSITION is only defined when there is no initial overlap (sweepHit.hadInitialOverlap() == false)
\note The returned normal for initially overlapping sweeps is set to -unitDir.
\note Otherwise the returned normal is the front normal of the triangle even if PxHitFlag::eMESH_BOTH_SIDES is set.
\note The returned PxGeomSweepHit::faceIndex parameter will hold the index of the hit triangle in input array, i.e. the range is [0; triangleCount). For initially overlapping sweeps, this is the index of overlapping triangle.
\note The inflation parameter is not compatible with PxHitFlag::ePRECISE_SWEEP.
@see PxTriangle PxSweepHit PxGeometry PxTransform PxGeometryQueryFlags
*/
PX_PHYSX_COMMON_API static bool sweep(const PxVec3& unitDir,
const PxReal distance,
const PxGeometry& geom,
const PxTransform& pose,
PxU32 triangleCount,
const PxTriangle* triangles,
PxGeomSweepHit& sweepHit,
PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxU32* cachedIndex = NULL,
const PxReal inflation = 0.0f,
bool doubleSided = false,
PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT);
};
#if !PX_DOXYGEN
}
#endif
/** @} */
#endif
| 13,051 | C | 50.385827 | 242 | 0.767144 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxReportCallback.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_REPORT_CALLBACK_H
#define PX_REPORT_CALLBACK_H
/** \addtogroup geomutils
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxArray.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Base class for callback reporting an unknown number of items to users.
This can be used as-is and customized by users, or several pre-designed callbacks can be used instead (see below).
This design lets users decide how to retrieve the results of a query:
- either one by one via a regular callback
- or one batch at a time via a callback
- or written out directly to their own C-style buffer
- or pushed back to their own PxArray
- etc
@see PxRegularReportCallback PxLocalStorageReportCallback PxExternalStorageReportCallback PxDynamicArrayReportCallback
*/
template<class T>
class PxReportCallback
{
public:
PxReportCallback(T* buffer=NULL, PxU32 capacity=0) : mBuffer(buffer), mCapacity(capacity), mSize(0) {}
virtual ~PxReportCallback() {}
T* mBuffer; // Destination buffer for writing results. if NULL, the system will use its internal buffer and set that pointer as it sees fit.
// Otherwise users can set it to where they want the results to be written.
PxU32 mCapacity; // Capacity of mBuffer. If mBuffer is NULL, this controls how many items are reported to users at the same time (with a limit of 256).
PxU32 mSize; //!< Current number of items in the buffer. This is entirely managed by the system.
/**
\brief Reports query results to users.
This will be called by the system as many times as necessary to report all results.
\param[in] nbItems Number of reported items
\param[in] items array of reported items
\return true to continue the query, false to abort the query
*/
virtual bool flushResults(PxU32 nbItems, const T* items) = 0;
};
/**
\brief Regular report callback
This reports results like a regular callback would:
- without explicit buffer management from users
- by default, one item at a time
This customized callback sends results to users via the processResults() function.
The capacity parameter dictates how many items can be reported at a time,
i.e. how many times the flushResults/processResults function will be called by the system.
@see PxReportCallback
*/
template<class T>
class PxRegularReportCallback : public PxReportCallback<T>
{
public:
PxRegularReportCallback(const PxU32 capacity=1)
{
PX_ASSERT(capacity<=256);
this->mCapacity = capacity;
}
virtual bool flushResults(PxU32 nbItems, const T* items)
{
PX_ASSERT(nbItems<=this->mCapacity);
PX_ASSERT(items==this->mBuffer);
return processResults(nbItems, items);
}
/**
\brief Reports query results to users.
\param[in] nbItems Number of reported items
\param[in] items array of reported items
\return true to continue the query, false to abort the query
*/
virtual bool processResults(PxU32 nbItems, const T* items) = 0;
};
/**
\brief Local storage report callback
This is the same as a regular callback, except the destination buffer is a local buffer within the class.
This customized callback sends results to users via the processResults() function.
The capacity of the embedded buffer (determined by a template parameter) dictates how many items can be reported at a time,
i.e. how many times the flushResults/processResults function will be called by the system.
@see PxReportCallback
*/
template<class T, const PxU32 capacityT>
class PxLocalStorageReportCallback : public PxReportCallback<T>
{
T mLocalStorage[capacityT];
public:
PxLocalStorageReportCallback()
{
this->mBuffer = mLocalStorage;
this->mCapacity = capacityT;
}
virtual bool flushResults(PxU32 nbItems, const T* items)
{
PX_ASSERT(items==mLocalStorage);
PX_ASSERT(nbItems<=this->mCapacity);
return processResults(nbItems, items);
}
/**
\brief Reports query results to users.
\param[in] nbItems Number of reported items
\param[in] items array of reported items
\return true to continue the query, false to abort the query
*/
virtual bool processResults(PxU32 nbItems, const T* items) = 0;
};
/**
\brief External storage report callback
This is the same as a regular callback, except the destination buffer is a user-provided external buffer.
Typically the provided buffer can be larger here than for PxLocalStorageReportCallback, and it could
even be a scratchpad-kind of memory shared by multiple sub-systems.
This would be the same as having a C-style buffer to write out results in the query interface.
This customized callback sends results to users via the processResults() function.
The capacity parameter dictates how many items can be reported at a time,
i.e. how many times the flushResults/processResults function will be called by the system.
@see PxReportCallback
*/
template<class T>
class PxExternalStorageReportCallback : public PxReportCallback<T>
{
public:
PxExternalStorageReportCallback(T* buffer, PxU32 capacity)
{
this->mBuffer = buffer;
this->mCapacity = capacity;
}
virtual bool flushResults(PxU32 nbItems, const T* items)
{
PX_ASSERT(items==this->mBuffer);
PX_ASSERT(nbItems<=this->mCapacity);
return processResults(nbItems, items);
}
/**
\brief Reports query results to users.
\param[in] nbItems Number of reported items
\param[in] items array of reported items
\return true to continue the query, false to abort the query
*/
virtual bool processResults(PxU32 nbItems, const T* items) = 0;
};
/**
\brief Dynamic array report callback
This callback emulates the behavior of pushing results to a (user-provided) dynamic array.
This customized callback does not actually call users back during the query, results are
available afterwards in the provided dynamic array. This would be the same as having a PxArray
directly in the query interface.
@see PxReportCallback
*/
template<class T>
class PxDynamicArrayReportCallback : public PxReportCallback<T>
{
public:
PxDynamicArrayReportCallback(PxArray<T>& results) : mResults(results)
{
mResults.reserve(32);
this->mBuffer = mResults.begin();
this->mCapacity = mResults.capacity();
}
virtual bool flushResults(PxU32 nbItems, const T* /*items*/)
{
const PxU32 size = mResults.size();
const PxU32 capa = mResults.capacity();
const PxU32 newSize = size+nbItems;
PX_ASSERT(newSize<=capa);
mResults.forceSize_Unsafe(newSize);
if(newSize==capa)
{
const PxU32 newCapa = capa*2;
mResults.reserve(newCapa);
this->mBuffer = mResults.begin() + newSize;
this->mCapacity = mResults.capacity() - newSize;
}
return true;
}
PxArray<T>& mResults;
};
#if !PX_DOXYGEN
}
#endif
/** @} */
#endif
| 8,721 | C | 32.546154 | 155 | 0.723082 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxTetrahedronMesh.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_TETRAHEDRON_MESH_H
#define PX_TETRAHEDRON_MESH_H
/** \addtogroup geomutils
@{ */
#include "foundation/PxVec3.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxUserAllocated.h"
#include "common/PxPhysXCommonConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxTetrahedronMeshFlag
{
enum Enum
{
e16_BIT_INDICES = (1 << 1) //!< The tetrahedron mesh has 16bits vertex indices
};
};
/**
\brief collection of set bits defined in PxTetrahedronMeshFlag.
@see PxTetrahedronMeshFlag
*/
typedef PxFlags<PxTetrahedronMeshFlag::Enum, PxU8> PxTetrahedronMeshFlags;
PX_FLAGS_OPERATORS(PxTetrahedronMeshFlag::Enum, PxU8)
/**
\brief A data container providing mass, rest pose and other information required for softbody simulation
Stores properties of softbody like inverse mass per node, rest pose matrix per tetrahedral element etc.
Mainly used internally to store runtime data.
*/
class PxSoftBodyAuxData : public PxRefCounted
{
public:
/**
\brief Decrements the reference count of a tetrahedron mesh and releases it if the new reference count is zero.
@see PxPhysics.createTetrahedronMesh()
*/
virtual void release() = 0;
/**
\brief Get the inverse mass of each vertex of the tetrahedron mesh.
\return PxReal* A pointer to an array of inverse mass for each vertex of the tetrahedron mesh. Size: number of vertices * sizeof(PxReal).
*/
virtual PxReal* getGridModelInvMass() = 0;
protected:
PX_INLINE PxSoftBodyAuxData(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {}
PX_INLINE PxSoftBodyAuxData(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxSoftBodyAuxData() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxSoftBodyAuxData", PxRefCounted); }
};
/**
\brief A tetramedron mesh, also called a 'tetrahedron soup'.
It is represented as an indexed tetrahedron list. There are no restrictions on the
tetrahedron data.
To avoid duplicating data when you have several instances of a particular
mesh positioned differently, you do not use this class to represent a
mesh object directly. Instead, you create an instance of this mesh via
the PxTetrahedronMeshGeometry and PxShape classes.
<h3>Creation</h3>
To create an instance of this class call PxPhysics::createTetrahedronMesh(),
and release() to delete it. This is only possible
once you have released all of its PxShape instances.
<h3>Visualizations:</h3>
\li #PxVisualizationParameter::eCOLLISION_AABBS
\li #PxVisualizationParameter::eCOLLISION_SHAPES
\li #PxVisualizationParameter::eCOLLISION_AXES
\li #PxVisualizationParameter::eCOLLISION_FNORMALS
\li #PxVisualizationParameter::eCOLLISION_EDGES
@see PxTetrahedronMeshDesc PxTetrahedronMeshGeometry PxShape PxPhysics.createTetrahedronMesh()
*/
class PxTetrahedronMesh : public PxRefCounted
{
public:
/**
\brief Returns the number of vertices.
\return number of vertices
@see getVertices()
*/
virtual PxU32 getNbVertices() const = 0;
/**
\brief Returns the vertices
\return array of vertices
@see getNbVertices()
*/
virtual const PxVec3* getVertices() const = 0;
/**
\brief Returns the number of tetrahedrons.
\return number of tetrahedrons
@see getTetrahedrons()
*/
virtual PxU32 getNbTetrahedrons() const = 0;
/**
\brief Returns the tetrahedron indices.
The indices can be 16 or 32bit depending on the number of tetrahedrons in the mesh.
Call getTetrahedronMeshFlags() to know if the indices are 16 or 32 bits.
The number of indices is the number of tetrahedrons * 4.
\return array of tetrahedrons
@see getNbTetrahedron() getTetrahedronMeshFlags() getTetrahedraRemap()
*/
virtual const void* getTetrahedrons() const = 0;
/**
\brief Reads the PxTetrahedronMesh flags.
See the list of flags #PxTetrahedronMeshFlags
\return The values of the PxTetrahedronMesh flags.
*/
virtual PxTetrahedronMeshFlags getTetrahedronMeshFlags() const = 0;
/**
\brief Returns the tetrahedra remapping table.
The tetrahedra are internally sorted according to various criteria. Hence the internal tetrahedron order
does not always match the original (user-defined) order. The remapping table helps finding the old
indices knowing the new ones:
remapTable[ internalTetrahedronIndex ] = originalTetrahedronIndex
\return the remapping table (or NULL if 'PxCookingParams::suppressTriangleMeshRemapTable' has been used)
@see getNbTetrahedron() getTetrahedrons() PxCookingParams::suppressTriangleMeshRemapTable
*/
virtual const PxU32* getTetrahedraRemap() const = 0;
/**
\brief Returns the local-space (vertex space) AABB from the tetrahedron mesh.
\return local-space bounds
*/
virtual PxBounds3 getLocalBounds() const = 0;
/**
\brief Decrements the reference count of a tetrahedron mesh and releases it if the new reference count is zero.
@see PxPhysics.createTetrahedronMesh()
*/
virtual void release() = 0;
protected:
PX_INLINE PxTetrahedronMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {}
PX_INLINE PxTetrahedronMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxTetrahedronMesh() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxTetrahedronMesh", PxRefCounted); }
};
/**
\brief A softbody mesh, containing structures to store collision shape, simulation shape and deformation state
The class bundles shapes and deformation state of a softbody that is simulated using FEM. The meshes used for
collision detection and for the FEM calculations are both tetrahedral meshes. While collision detection requires
a mesh that matches the surface of the simulated body as exactly as possible, the simulation mesh has more freedom
such that it can be optimized for tetrahedra without small angles and nodes that aren't shared by too many elements.
<h3>Creation</h3>
To create an instance of this class call PxPhysics::createSoftBodyMesh(),
and release() to delete it. This is only possible
once you have released all of its PxShape instances.
*/
class PxSoftBodyMesh : public PxRefCounted
{
public:
/**
\brief Const accecssor to the softbody's collision mesh.
@see PxTetrahedronMesh
*/
virtual const PxTetrahedronMesh* getCollisionMesh() const = 0;
/**
\brief Accecssor to the softbody's collision mesh.
@see PxTetrahedronMesh
*/
virtual PxTetrahedronMesh* getCollisionMesh() = 0;
/**
\brief Const accessor to the softbody's simulation mesh.
@see PxTetrahedronMesh
*/
virtual const PxTetrahedronMesh* getSimulationMesh() const = 0;
/**
\brief Accecssor to the softbody's simulation mesh.
@see PxTetrahedronMesh
*/
virtual PxTetrahedronMesh* getSimulationMesh() = 0;
/**
\brief Const accessor to the softbodies simulation state.
@see PxSoftBodyAuxData
*/
virtual const PxSoftBodyAuxData* getSoftBodyAuxData() const = 0;
/**
\brief Accessor to the softbody's auxilary data like mass and rest pose information
@see PxSoftBodyAuxData
*/
virtual PxSoftBodyAuxData* getSoftBodyAuxData() = 0;
/**
\brief Decrements the reference count of a tetrahedron mesh and releases it if the new reference count is zero.
@see PxPhysics.createTetrahedronMesh()
*/
virtual void release() = 0;
protected:
PX_INLINE PxSoftBodyMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {}
PX_INLINE PxSoftBodyMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxSoftBodyMesh() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxSoftBodyMesh", PxRefCounted); }
};
/**
\brief Contains information about how to update the collision mesh's vertices given a deformed simulation tetmesh.
@see PxTetrahedronMeshData
*/
class PxCollisionMeshMappingData : public PxUserAllocated
{
public:
virtual void release() = 0;
virtual ~PxCollisionMeshMappingData() {}
};
/**
\brief Stores data to accelerate collision detection of a tetrahedral mesh
@see PxTetrahedronMeshData
*/
class PxSoftBodyCollisionData : public PxUserAllocated
{
};
/**
\brief Contains raw geometry information describing the tetmesh's vertices and its elements (tetrahedra)
@see PxTetrahedronMeshData
*/
class PxTetrahedronMeshData : public PxUserAllocated
{
};
/**
\brief Stores data to compute and store the state of a deformed tetrahedral mesh
@see PxTetrahedronMeshData
*/
class PxSoftBodySimulationData : public PxUserAllocated
{
};
/**
\brief Conbines PxTetrahedronMeshData and PxSoftBodyCollisionData
@see PxTetrahedronMeshData PxSoftBodyCollisionData
*/
class PxCollisionTetrahedronMeshData : public PxUserAllocated
{
public:
virtual const PxTetrahedronMeshData* getMesh() const = 0;
virtual PxTetrahedronMeshData* getMesh() = 0;
virtual const PxSoftBodyCollisionData* getData() const = 0;
virtual PxSoftBodyCollisionData* getData() = 0;
virtual void release() = 0;
virtual ~PxCollisionTetrahedronMeshData() {}
};
/**
\brief Conbines PxTetrahedronMeshData and PxSoftBodyCollisionData
@see PxTetrahedronMeshData PxSoftBodySimulationData
*/
class PxSimulationTetrahedronMeshData : public PxUserAllocated
{
public:
virtual PxTetrahedronMeshData* getMesh() = 0;
virtual PxSoftBodySimulationData* getData() = 0;
virtual void release() = 0;
virtual ~PxSimulationTetrahedronMeshData() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 11,417 | C | 29.859459 | 139 | 0.748883 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxHeightFieldDesc.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_HEIGHTFIELD_DESC_H
#define PX_HEIGHTFIELD_DESC_H
/** \addtogroup geomutils
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "geometry/PxHeightFieldFlag.h"
#include "common/PxCoreUtilityTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Descriptor class for #PxHeightField.
\note The heightfield data is *copied* when a PxHeightField object is created from this descriptor. After the call the
user may discard the height data.
@see PxHeightField PxHeightFieldGeometry PxShape PxPhysics.createHeightField() PxCooking.createHeightField()
*/
class PxHeightFieldDesc
{
public:
/**
\brief Number of sample rows in the height field samples array.
\note Local space X-axis corresponds to rows.
<b>Range:</b> >1<br>
<b>Default:</b> 0
*/
PxU32 nbRows;
/**
\brief Number of sample columns in the height field samples array.
\note Local space Z-axis corresponds to columns.
<b>Range:</b> >1<br>
<b>Default:</b> 0
*/
PxU32 nbColumns;
/**
\brief Format of the sample data.
Currently the only supported format is PxHeightFieldFormat::eS16_TM:
<b>Default:</b> PxHeightFieldFormat::eS16_TM
@see PxHeightFormat PxHeightFieldDesc.samples
*/
PxHeightFieldFormat::Enum format;
/**
\brief The samples array.
It is copied to the SDK's storage at creation time.
There are nbRows * nbColumn samples in the array,
which define nbRows * nbColumn vertices and cells,
of which (nbRows - 1) * (nbColumns - 1) cells are actually used.
The array index of sample(row, column) = row * nbColumns + column.
The byte offset of sample(row, column) = sampleStride * (row * nbColumns + column).
The sample data follows at the offset and spans the number of bytes defined by the format.
Then there are zero or more unused bytes depending on sampleStride before the next sample.
<b>Default:</b> NULL
@see PxHeightFormat
*/
PxStridedData samples;
/**
This threshold is used by the collision detection to determine if a height field edge is convex
and can generate contact points.
Usually the convexity of an edge is determined from the angle (or cosine of the angle) between
the normals of the faces sharing that edge.
The height field allows a more efficient approach by comparing height values of neighboring vertices.
This parameter offsets the comparison. Smaller changes than 0.5 will not alter the set of convex edges.
The rule of thumb is that larger values will result in fewer edge contacts.
This parameter is ignored in contact generation with sphere and capsule primitives.
<b>Range:</b> [0, PX_MAX_F32)<br>
<b>Default:</b> 0
*/
PxReal convexEdgeThreshold;
/**
\brief Flags bits, combined from values of the enum ::PxHeightFieldFlag.
<b>Default:</b> 0
@see PxHeightFieldFlag PxHeightFieldFlags
*/
PxHeightFieldFlags flags;
/**
\brief Constructor sets to default.
*/
PX_INLINE PxHeightFieldDesc();
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault();
/**
\brief Returns true if the descriptor is valid.
\return True if the current settings are valid.
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxHeightFieldDesc::PxHeightFieldDesc() //constructor sets to default
{
nbColumns = 0;
nbRows = 0;
format = PxHeightFieldFormat::eS16_TM;
convexEdgeThreshold = 0.0f;
flags = PxHeightFieldFlags();
}
PX_INLINE void PxHeightFieldDesc::setToDefault()
{
*this = PxHeightFieldDesc();
}
PX_INLINE bool PxHeightFieldDesc::isValid() const
{
if (nbColumns < 2)
return false;
if (nbRows < 2)
return false;
if(format != PxHeightFieldFormat::eS16_TM)
return false;
if (samples.stride < 4)
return false;
if (convexEdgeThreshold < 0)
return false;
if ((flags & PxHeightFieldFlag::eNO_BOUNDARY_EDGES) != flags)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 5,585 | C | 29.032258 | 118 | 0.739481 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxCapsuleGeometry.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_CAPSULE_GEOMETRY_H
#define PX_CAPSULE_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#include "foundation/PxFoundationConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Class representing the geometry of a capsule.
Capsules are shaped as the union of a cylinder of length 2 * halfHeight and with the
given radius centered at the origin and extending along the x axis, and two hemispherical ends.
\note The scaling of the capsule is expected to be baked into these values, there is no additional scaling parameter.
The function PxTransformFromSegment is a helper for generating an appropriate transform for the capsule from the capsule's interior line segment.
@see PxTransformFromSegment
*/
class PxCapsuleGeometry : public PxGeometry
{
public:
/**
\brief Constructor, initializes to a capsule with passed radius and half height.
*/
PX_INLINE PxCapsuleGeometry(PxReal radius_=0.0f, PxReal halfHeight_=0.0f) : PxGeometry(PxGeometryType::eCAPSULE), radius(radius_), halfHeight(halfHeight_) {}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxCapsuleGeometry(const PxCapsuleGeometry& that) : PxGeometry(that), radius(that.radius), halfHeight(that.halfHeight) {}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxCapsuleGeometry& that)
{
mType = that.mType;
radius = that.radius;
halfHeight = that.halfHeight;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid.
\note A valid capsule has radius > 0, halfHeight >= 0.
It is illegal to call PxRigidActor::createShape and PxPhysics::createShape with a capsule that has zero radius or height.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
public:
/**
\brief The radius of the capsule.
*/
PxReal radius;
/**
\brief half of the capsule's height, measured between the centers of the hemispherical ends.
*/
PxReal halfHeight;
};
PX_INLINE bool PxCapsuleGeometry::isValid() const
{
if(mType != PxGeometryType::eCAPSULE)
return false;
if(!PxIsFinite(radius) || !PxIsFinite(halfHeight))
return false;
if(radius <= 0.0f || halfHeight < 0.0f)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,028 | C | 32.575 | 158 | 0.750248 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxBoxGeometry.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_BOX_GEOMETRY_H
#define PX_BOX_GEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#include "foundation/PxVec3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Class representing the geometry of a box.
The geometry of a box can be fully specified by its half extents. This is the half of its width, height, and depth.
\note The scaling of the box is expected to be baked into these values, there is no additional scaling parameter.
*/
class PxBoxGeometry : public PxGeometry
{
public:
/**
\brief Constructor to initialize half extents from scalar parameters.
\param hx Initial half extents' x component.
\param hy Initial half extents' y component.
\param hz Initial half extents' z component.
*/
PX_INLINE PxBoxGeometry(PxReal hx=0.0f, PxReal hy=0.0f, PxReal hz=0.0f) : PxGeometry(PxGeometryType::eBOX), halfExtents(hx, hy, hz) {}
/**
\brief Constructor to initialize half extents from vector parameter.
\param halfExtents_ Initial half extents.
*/
PX_INLINE PxBoxGeometry(PxVec3 halfExtents_) : PxGeometry(PxGeometryType::eBOX), halfExtents(halfExtents_) {}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxBoxGeometry(const PxBoxGeometry& that) : PxGeometry(that), halfExtents(that.halfExtents) {}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxBoxGeometry& that)
{
mType = that.mType;
halfExtents = that.halfExtents;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid
\note A valid box has a positive extent in each direction (halfExtents.x > 0, halfExtents.y > 0, halfExtents.z > 0).
It is illegal to call PxRigidActor::createShape and PxPhysics::createShape with a box that has zero extent in any direction.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
public:
/**
\brief Half of the width, height, and depth of the box.
*/
PxVec3 halfExtents;
};
PX_INLINE bool PxBoxGeometry::isValid() const
{
if(mType != PxGeometryType::eBOX)
return false;
if(!halfExtents.isFinite())
return false;
if(halfExtents.x <= 0.0f || halfExtents.y <= 0.0f || halfExtents.z <= 0.0f)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,004 | C | 32.940678 | 135 | 0.743007 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxGeometryQueryFlags.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_GEOMETRY_QUERY_FLAGS_H
#define PX_GEOMETRY_QUERY_FLAGS_H
#include "foundation/PxFlags.h"
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Geometry-level query flags.
@see PxScene::raycast PxScene::overlap PxScene::sweep PxBVH::raycast PxBVH::overlap PxBVH::sweep PxGeometryQuery::raycast PxGeometryQuery::overlap PxGeometryQuery::sweep
@see PxGeometryQuery::computePenetration PxGeometryQuery::pointDistance PxGeometryQuery::computeGeomBounds
@see PxMeshQuery::findOverlapTriangleMesh PxMeshQuery::findOverlapHeightField PxMeshQuery::sweep
*/
struct PxGeometryQueryFlag
{
enum Enum
{
eSIMD_GUARD = (1<<0), //!< Saves/restores SIMD control word for each query (safer but slower). Omit this if you took care of it yourself in your app.
eDEFAULT = eSIMD_GUARD
};
};
/**
\brief collection of set bits defined in PxGeometryQueryFlag.
@see PxGeometryQueryFlag
*/
PX_FLAGS_TYPEDEF(PxGeometryQueryFlag, PxU32)
#if !PX_DOXYGEN
}
#endif
#endif
| 2,721 | C | 38.449275 | 170 | 0.76663 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxSimpleTriangleMesh.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_SIMPLE_TRIANGLE_MESH_H
#define PX_SIMPLE_TRIANGLE_MESH_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxFlags.h"
#include "common/PxCoreUtilityTypes.h"
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Enum with flag values to be used in PxSimpleTriangleMesh::flags.
*/
struct PxMeshFlag
{
enum Enum
{
/**
\brief Specifies if the SDK should flip normals.
The PhysX libraries assume that the face normal of a triangle with vertices [a,b,c] can be computed as:
edge1 = b-a
edge2 = c-a
face_normal = edge1 x edge2.
Note: This is the same as a counterclockwise winding in a right handed coordinate system or
alternatively a clockwise winding order in a left handed coordinate system.
If this does not match the winding order for your triangles, raise the below flag.
*/
eFLIPNORMALS = (1<<0),
e16_BIT_INDICES = (1<<1) //!< Denotes the use of 16-bit vertex indices
};
};
/**
\brief collection of set bits defined in PxMeshFlag.
@see PxMeshFlag
*/
typedef PxFlags<PxMeshFlag::Enum,PxU16> PxMeshFlags;
PX_FLAGS_OPERATORS(PxMeshFlag::Enum,PxU16)
/**
\brief A structure describing a triangle mesh.
*/
class PxSimpleTriangleMesh
{
public:
/**
\brief Pointer to first vertex point.
*/
PxBoundedData points;
/**
\brief Pointer to first triangle.
Caller may add triangleStrideBytes bytes to the pointer to access the next triangle.
These are triplets of 0 based indices:
vert0 vert1 vert2
vert0 vert1 vert2
vert0 vert1 vert2
...
where vertex is either a 32 or 16 bit unsigned integer. There are numTriangles*3 indices.
This is declared as a void pointer because it is actually either an PxU16 or a PxU32 pointer.
*/
PxBoundedData triangles;
/**
\brief Flags bits, combined from values of the enum ::PxMeshFlag
*/
PxMeshFlags flags;
/**
\brief constructor sets to default.
*/
PX_INLINE PxSimpleTriangleMesh();
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault();
/**
\brief returns true if the current settings are valid
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxSimpleTriangleMesh::PxSimpleTriangleMesh()
{
}
PX_INLINE void PxSimpleTriangleMesh::setToDefault()
{
*this = PxSimpleTriangleMesh();
}
PX_INLINE bool PxSimpleTriangleMesh::isValid() const
{
// Check geometry
if(points.count > 0xffff && flags & PxMeshFlag::e16_BIT_INDICES)
return false;
if(!points.data)
return false;
if(points.stride < sizeof(PxVec3)) //should be at least one point's worth of data
return false;
// Check topology
// The triangles pointer is not mandatory
if(triangles.data)
{
// Indexed mesh
PxU32 limit = (flags & PxMeshFlag::e16_BIT_INDICES) ? sizeof(PxU16)*3 : sizeof(PxU32)*3;
if(triangles.stride < limit)
return false;
}
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,636 | C | 27.10303 | 105 | 0.734901 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxHeightFieldFlag.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_HEIGHT_FIELD_FLAG_H
#define PX_HEIGHT_FIELD_FLAG_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Describes the format of height field samples.
@see PxHeightFieldDesc.format PxHeightFieldDesc.samples
*/
struct PxHeightFieldFormat
{
enum Enum
{
/**
\brief Height field height data is 16 bit signed integers, followed by triangle materials.
Each sample is 32 bits wide arranged as follows:
\image html heightFieldFormat_S16_TM.png
1) First there is a 16 bit height value.
2) Next, two one byte material indices, with the high bit of each byte reserved for special use.
(so the material index is only 7 bits).
The high bit of material0 is the tess-flag.
The high bit of material1 is reserved for future use.
There are zero or more unused bytes before the next sample depending on PxHeightFieldDesc.sampleStride,
where the application may eventually keep its own data.
This is the only format supported at the moment.
@see PxHeightFieldDesc.format PxHeightFieldDesc.samples
*/
eS16_TM = (1 << 0)
};
};
/**
\brief Determines the tessellation of height field cells.
@see PxHeightFieldDesc.format PxHeightFieldDesc.samples
*/
struct PxHeightFieldTessFlag
{
enum Enum
{
/**
\brief This flag determines which way each quad cell is subdivided.
The flag lowered indicates subdivision like this: (the 0th vertex is referenced by only one triangle)
\image html heightfieldTriMat2.PNG
<pre>
+--+--+--+---> column
| /| /| /|
|/ |/ |/ |
+--+--+--+
| /| /| /|
|/ |/ |/ |
+--+--+--+
|
|
V row
</pre>
The flag raised indicates subdivision like this: (the 0th vertex is shared by two triangles)
\image html heightfieldTriMat1.PNG
<pre>
+--+--+--+---> column
|\ |\ |\ |
| \| \| \|
+--+--+--+
|\ |\ |\ |
| \| \| \|
+--+--+--+
|
|
V row
</pre>
@see PxHeightFieldDesc.format PxHeightFieldDesc.samples
*/
e0TH_VERTEX_SHARED = (1 << 0)
};
};
/**
\brief Enum with flag values to be used in PxHeightFieldDesc.flags.
*/
struct PxHeightFieldFlag
{
enum Enum
{
/**
\brief Disable collisions with height field with boundary edges.
Raise this flag if several terrain patches are going to be placed adjacent to each other,
to avoid a bump when sliding across.
This flag is ignored in contact generation with sphere and capsule shapes.
@see PxHeightFieldDesc.flags
*/
eNO_BOUNDARY_EDGES = (1 << 0)
};
};
/**
\brief collection of set bits defined in PxHeightFieldFlag.
@see PxHeightFieldFlag
*/
typedef PxFlags<PxHeightFieldFlag::Enum,PxU16> PxHeightFieldFlags;
PX_FLAGS_OPERATORS(PxHeightFieldFlag::Enum,PxU16)
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,482 | C | 26.84472 | 106 | 0.713075 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxGeometryHit.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_GEOMETRY_HIT_H
#define PX_GEOMETRY_HIT_H
/** \addtogroup scenequery
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxFlags.h"
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Scene query and geometry query behavior flags.
PxHitFlags are used for 3 different purposes:
1) To request hit fields to be filled in by scene queries (such as hit position, normal, face index or UVs).
2) Once query is completed, to indicate which fields are valid (note that a query may produce more valid fields than requested).
3) To specify additional options for the narrow phase and mid-phase intersection routines.
All these flags apply to both scene queries and geometry queries (PxGeometryQuery).
@see PxRaycastHit PxSweepHit PxOverlapHit PxScene.raycast PxScene.sweep PxScene.overlap PxGeometryQuery PxFindFaceIndex
*/
struct PxHitFlag
{
enum Enum
{
ePOSITION = (1<<0), //!< "position" member of #PxQueryHit is valid
eNORMAL = (1<<1), //!< "normal" member of #PxQueryHit is valid
eUV = (1<<3), //!< "u" and "v" barycentric coordinates of #PxQueryHit are valid. Not applicable to sweep queries.
eASSUME_NO_INITIAL_OVERLAP = (1<<4), //!< Performance hint flag for sweeps when it is known upfront there's no initial overlap.
//!< NOTE: using this flag may cause undefined results if shapes are initially overlapping.
eANY_HIT = (1<<5), //!< Report any first hit. Used for geometries that contain more than one primitive. For meshes,
//!< if neither eMESH_MULTIPLE nor eANY_HIT is specified, a single closest hit will be reported.
eMESH_MULTIPLE = (1<<6), //!< Report all hits for meshes rather than just the first. Not applicable to sweep queries.
eMESH_ANY = eANY_HIT, //!< @deprecated Deprecated, please use eANY_HIT instead.
eMESH_BOTH_SIDES = (1<<7), //!< Report hits with back faces of mesh triangles. Also report hits for raycast
//!< originating on mesh surface and facing away from the surface normal. Not applicable to sweep queries.
//!< Please refer to the user guide for heightfield-specific differences.
ePRECISE_SWEEP = (1<<8), //!< Use more accurate but slower narrow phase sweep tests.
//!< May provide better compatibility with PhysX 3.2 sweep behavior.
eMTD = (1<<9), //!< Report the minimum translation depth, normal and contact point.
eFACE_INDEX = (1<<10), //!< "face index" member of #PxQueryHit is valid
eDEFAULT = ePOSITION|eNORMAL|eFACE_INDEX,
/** \brief Only this subset of flags can be modified by pre-filter. Other modifications will be discarded. */
eMODIFIABLE_FLAGS = eMESH_MULTIPLE|eMESH_BOTH_SIDES|eASSUME_NO_INITIAL_OVERLAP|ePRECISE_SWEEP
};
};
/**
\brief collection of set bits defined in PxHitFlag.
@see PxHitFlag
*/
PX_FLAGS_TYPEDEF(PxHitFlag, PxU16)
/**
\brief Scene query hit information.
*/
struct PxQueryHit
{
PX_INLINE PxQueryHit() : faceIndex(0xFFFFffff) {}
/**
Face index of touched triangle, for triangle meshes, convex meshes and height fields.
\note This index will default to 0xFFFFffff value for overlap queries.
\note Please refer to the user guide for more details for sweep queries.
\note This index is remapped by mesh cooking. Use #PxTriangleMesh::getTrianglesRemap() to convert to original mesh index.
\note For convex meshes use #PxConvexMesh::getPolygonData() to retrieve touched polygon data.
*/
PxU32 faceIndex;
};
/**
\brief Scene query hit information for raycasts and sweeps returning hit position and normal information.
::PxHitFlag flags can be passed to scene query functions, as an optimization, to cause the SDK to
only generate specific members of this structure.
*/
struct PxLocationHit : PxQueryHit
{
PX_INLINE PxLocationHit() : flags(0), position(PxVec3(0)), normal(PxVec3(0)), distance(PX_MAX_REAL) {}
/**
\note For raycast hits: true for shapes overlapping with raycast origin.
\note For sweep hits: true for shapes overlapping at zero sweep distance.
@see PxRaycastHit PxSweepHit
*/
PX_INLINE bool hadInitialOverlap() const { return (distance <= 0.0f); }
// the following fields are set in accordance with the #PxHitFlags
PxHitFlags flags; //!< Hit flags specifying which members contain valid values.
PxVec3 position; //!< World-space hit position (flag: #PxHitFlag::ePOSITION)
PxVec3 normal; //!< World-space hit normal (flag: #PxHitFlag::eNORMAL)
/**
\brief Distance to hit.
\note If the eMTD flag is used, distance will be a negative value if shapes are overlapping indicating the penetration depth.
\note Otherwise, this value will be >= 0 */
PxF32 distance;
};
/**
\brief Stores results of raycast queries.
::PxHitFlag flags can be passed to raycast function, as an optimization, to cause the SDK to only compute specified members of this
structure.
Some members like barycentric coordinates are currently only computed for triangle meshes and height fields, but next versions
might provide them in other cases. The client code should check #flags to make sure returned values are valid.
@see PxScene.raycast
*/
struct PxGeomRaycastHit : PxLocationHit
{
PX_INLINE PxGeomRaycastHit() : u(0.0f), v(0.0f) {}
// the following fields are set in accordance with the #PxHitFlags
PxReal u, v; //!< barycentric coordinates of hit point, for triangle mesh and height field (flag: #PxHitFlag::eUV)
};
/**
\brief Stores results of overlap queries.
@see PxScene.overlap
*/
struct PxGeomOverlapHit : PxQueryHit
{
PX_INLINE PxGeomOverlapHit() {}
};
/**
\brief Stores results of sweep queries.
@see PxScene.sweep
*/
struct PxGeomSweepHit : PxLocationHit
{
PX_INLINE PxGeomSweepHit() {}
};
/**
\brief Pair of indices, typically either object or triangle indices.
*/
struct PxGeomIndexPair
{
PX_FORCE_INLINE PxGeomIndexPair() {}
PX_FORCE_INLINE PxGeomIndexPair(PxU32 _id0, PxU32 _id1) : id0(_id0), id1(_id1) {}
PxU32 id0, id1;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 7,749 | C | 38.540816 | 131 | 0.734288 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxHeightField.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_HEIGHTFIELD_H
#define PX_HEIGHTFIELD_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxHeightFieldFlag.h"
#include "geometry/PxHeightFieldSample.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxHeightFieldDesc;
/**
\brief A height field class.
Height fields work in a similar way as triangle meshes specified to act as
height fields, with some important differences:
Triangle meshes can be made of nonuniform geometry, while height fields are
regular, rectangular grids. This means that with PxHeightField, you sacrifice
flexibility in return for improved performance and decreased memory consumption.
In local space rows extend in X direction, columns in Z direction and height in Y direction.
Like Convexes and TriangleMeshes, HeightFields are referenced by shape instances
(see #PxHeightFieldGeometry, #PxShape).
To avoid duplicating data when you have several instances of a particular
height field differently, you do not use this class to represent a
height field object directly. Instead, you create an instance of this height field
via the PxHeightFieldGeometry and PxShape classes.
<h3>Creation</h3>
To create an instance of this class call PxPhysics::createHeightField() or
PxCooking::createHeightField(const PxHeightFieldDesc&, PxInsertionCallback&).
To delete it call release(). This is only possible
once you have released all of its PxHeightFiedShape instances.
<h3>Visualizations:</h3>
\li #PxVisualizationParameter::eCOLLISION_AABBS
\li #PxVisualizationParameter::eCOLLISION_SHAPES
\li #PxVisualizationParameter::eCOLLISION_AXES
\li #PxVisualizationParameter::eCOLLISION_FNORMALS
\li #PxVisualizationParameter::eCOLLISION_EDGES
@see PxHeightFieldDesc PxHeightFieldGeometry PxShape PxPhysics.createHeightField() PxCooking.createHeightField()
*/
class PxHeightField : public PxRefCounted
{
public:
/**
\brief Decrements the reference count of a height field and releases it if the new reference count is zero.
@see PxPhysics.createHeightField() PxHeightFieldDesc PxHeightFieldGeometry PxShape
*/
virtual void release() = 0;
/**
\brief Writes out the sample data array.
The user provides destBufferSize bytes storage at destBuffer.
The data is formatted and arranged as PxHeightFieldDesc.samples.
\param[out] destBuffer The destination buffer for the sample data.
\param[in] destBufferSize The size of the destination buffer.
\return The number of bytes written.
@see PxHeightFieldDesc.samples
*/
virtual PxU32 saveCells(void* destBuffer, PxU32 destBufferSize) const = 0;
/**
\brief Replaces a rectangular subfield in the sample data array.
The user provides the description of a rectangular subfield in subfieldDesc.
The data is formatted and arranged as PxHeightFieldDesc.samples.
\param[in] startCol First cell in the destination heightfield to be modified. Can be negative.
\param[in] startRow First row in the destination heightfield to be modified. Can be negative.
\param[in] subfieldDesc Description of the source subfield to read the samples from.
\param[in] shrinkBounds If left as false, the bounds will never shrink but only grow. If set to true the bounds will be recomputed from all HF samples at O(nbColums*nbRows) perf cost.
\return True on success, false on failure. Failure can occur due to format mismatch.
\note Modified samples are constrained to the same height quantization range as the original heightfield.
Source samples that are out of range of target heightfield will be clipped with no error.
PhysX does not keep a mapping from the heightfield to heightfield shapes that reference it.
Call PxShape::setGeometry on each shape which references the height field, to ensure that internal data structures are updated to reflect the new geometry.
Please note that PxShape::setGeometry does not guarantee correct/continuous behavior when objects are resting on top of old or new geometry.
@see PxHeightFieldDesc.samples PxShape.setGeometry
*/
virtual bool modifySamples(PxI32 startCol, PxI32 startRow, const PxHeightFieldDesc& subfieldDesc, bool shrinkBounds = false) = 0;
/**
\brief Retrieves the number of sample rows in the samples array.
\return The number of sample rows in the samples array.
@see PxHeightFieldDesc.nbRows
*/
virtual PxU32 getNbRows() const = 0;
/**
\brief Retrieves the number of sample columns in the samples array.
\return The number of sample columns in the samples array.
@see PxHeightFieldDesc.nbColumns
*/
virtual PxU32 getNbColumns() const = 0;
/**
\brief Retrieves the format of the sample data.
\return The format of the sample data.
@see PxHeightFieldDesc.format PxHeightFieldFormat
*/
virtual PxHeightFieldFormat::Enum getFormat() const = 0;
/**
\brief Retrieves the offset in bytes between consecutive samples in the array.
\return The offset in bytes between consecutive samples in the array.
@see PxHeightFieldDesc.sampleStride
*/
virtual PxU32 getSampleStride() const = 0;
/**
\brief Retrieves the convex edge threshold.
\return The convex edge threshold.
@see PxHeightFieldDesc.convexEdgeThreshold
*/
virtual PxReal getConvexEdgeThreshold() const = 0;
/**
\brief Retrieves the flags bits, combined from values of the enum ::PxHeightFieldFlag.
\return The flags bits, combined from values of the enum ::PxHeightFieldFlag.
@see PxHeightFieldDesc.flags PxHeightFieldFlag
*/
virtual PxHeightFieldFlags getFlags() const = 0;
/**
\brief Retrieves the height at the given coordinates in grid space.
\return The height at the given coordinates or 0 if the coordinates are out of range.
*/
virtual PxReal getHeight(PxReal x, PxReal z) const = 0;
/**
\brief Returns material table index of given triangle
\note This function takes a post cooking triangle index.
\param[in] triangleIndex (internal) index of desired triangle
\return Material table index, or 0xffff if no per-triangle materials are used
*/
virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const = 0;
/**
\brief Returns a triangle face normal for a given triangle index
\note This function takes a post cooking triangle index.
\param[in] triangleIndex (internal) index of desired triangle
\return Triangle normal for a given triangle index
*/
virtual PxVec3 getTriangleNormal(PxTriangleID triangleIndex) const = 0;
/**
\brief Returns heightfield sample of given row and column
\param[in] row Given heightfield row
\param[in] column Given heightfield column
\return Heightfield sample
*/
virtual const PxHeightFieldSample& getSample(PxU32 row, PxU32 column) const = 0;
/**
\brief Returns the number of times the heightfield data has been modified
This method returns the number of times modifySamples has been called on this heightfield, so that code that has
retained state that depends on the heightfield can efficiently determine whether it has been modified.
\return the number of times the heightfield sample data has been modified.
*/
virtual PxU32 getTimestamp() const = 0;
virtual const char* getConcreteTypeName() const { return "PxHeightField"; }
protected:
PX_INLINE PxHeightField(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {}
PX_INLINE PxHeightField(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxHeightField() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxHeightField", PxRefCounted); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,251 | C | 36.918033 | 184 | 0.778619 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxTriangleMesh.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_TRIANGLE_MESH_H
#define PX_TRIANGLE_MESH_H
/** \addtogroup geomutils
@{ */
#include "foundation/PxVec3.h"
#include "foundation/PxBounds3.h"
#include "common/PxPhysXCommonConfig.h"
#include "common/PxBase.h"
#include "foundation/PxUserAllocated.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Mesh midphase structure. This enum is used to select the desired acceleration structure for midphase queries
(i.e. raycasts, overlaps, sweeps vs triangle meshes).
The PxMeshMidPhase::eBVH33 structure is the one used in recent PhysX versions (up to PhysX 3.3). It has great performance and is
supported on all platforms. It is deprecated since PhysX 5.x.
The PxMeshMidPhase::eBVH34 structure is a revisited implementation introduced in PhysX 3.4. It can be significantly faster both
in terms of cooking performance and runtime performance.
*/
struct PxMeshMidPhase
{
enum Enum
{
eBVH33 = 0, //!< Default midphase mesh structure, as used up to PhysX 3.3 (deprecated)
eBVH34 = 1, //!< New midphase mesh structure, introduced in PhysX 3.4
eLAST
};
};
/**
\brief Flags for the mesh geometry properties.
Used in ::PxTriangleMeshFlags.
*/
struct PxTriangleMeshFlag
{
enum Enum
{
e16_BIT_INDICES = (1<<1), //!< The triangle mesh has 16bits vertex indices.
eADJACENCY_INFO = (1<<2), //!< The triangle mesh has adjacency information build.
ePREFER_NO_SDF_PROJ = (1<<3)//!< Indicates that this mesh would preferably not be the mesh projected for mesh-mesh collision. This can indicate that the mesh is not well tessellated.
};
};
/**
\brief collection of set bits defined in PxTriangleMeshFlag.
@see PxTriangleMeshFlag
*/
typedef PxFlags<PxTriangleMeshFlag::Enum,PxU8> PxTriangleMeshFlags;
PX_FLAGS_OPERATORS(PxTriangleMeshFlag::Enum,PxU8)
/**
\brief A triangle mesh, also called a 'polygon soup'.
It is represented as an indexed triangle list. There are no restrictions on the
triangle data.
To avoid duplicating data when you have several instances of a particular
mesh positioned differently, you do not use this class to represent a
mesh object directly. Instead, you create an instance of this mesh via
the PxTriangleMeshGeometry and PxShape classes.
<h3>Creation</h3>
To create an instance of this class call PxPhysics::createTriangleMesh(),
and release() to delete it. This is only possible
once you have released all of its PxShape instances.
<h3>Visualizations:</h3>
\li #PxVisualizationParameter::eCOLLISION_AABBS
\li #PxVisualizationParameter::eCOLLISION_SHAPES
\li #PxVisualizationParameter::eCOLLISION_AXES
\li #PxVisualizationParameter::eCOLLISION_FNORMALS
\li #PxVisualizationParameter::eCOLLISION_EDGES
@see PxTriangleMeshDesc PxTriangleMeshGeometry PxShape PxPhysics.createTriangleMesh()
*/
class PxTriangleMesh : public PxRefCounted
{
public:
/**
\brief Returns the number of vertices.
\return number of vertices
@see getVertices()
*/
virtual PxU32 getNbVertices() const = 0;
/**
\brief Returns the vertices.
\return array of vertices
@see getNbVertices()
*/
virtual const PxVec3* getVertices() const = 0;
/**
\brief Returns all mesh vertices for modification.
This function will return the vertices of the mesh so that their positions can be changed in place.
After modifying the vertices you must call refitBVH for the refitting to actually take place.
This function maintains the old mesh topology (triangle indices).
\return inplace vertex coordinates for each existing mesh vertex.
\note It is recommended to use this feature for scene queries only.
\note Size of array returned is equal to the number returned by getNbVertices().
\note This function operates on cooked vertex indices.
\note This means the index mapping and vertex count can be different from what was provided as an input to the cooking routine.
\note To achieve unchanged 1-to-1 index mapping with orignal mesh data (before cooking) please use the following cooking flags:
\note eWELD_VERTICES = 0, eDISABLE_CLEAN_MESH = 1.
\note It is also recommended to make sure that a call to validateTriangleMesh returns true if mesh cleaning is disabled.
@see getNbVertices()
@see refitBVH()
*/
virtual PxVec3* getVerticesForModification() = 0;
/**
\brief Refits BVH for mesh vertices.
This function will refit the mesh BVH to correctly enclose the new positions updated by getVerticesForModification.
Mesh BVH will not be reoptimized by this function so significantly different new positions will cause significantly reduced performance.
\return New bounds for the entire mesh.
\note For PxMeshMidPhase::eBVH34 trees the refit operation is only available on non-quantized trees (see PxBVH34MidphaseDesc::quantized)
\note PhysX does not keep a mapping from the mesh to mesh shapes that reference it.
\note Call PxShape::setGeometry on each shape which references the mesh, to ensure that internal data structures are updated to reflect the new geometry.
\note PxShape::setGeometry does not guarantee correct/continuous behavior when objects are resting on top of old or new geometry.
\note It is also recommended to make sure that a call to validateTriangleMesh returns true if mesh cleaning is disabled.
\note Active edges information will be lost during refit, the rigid body mesh contact generation might not perform as expected.
@see getNbVertices()
@see getVerticesForModification()
@see PxBVH34MidphaseDesc::quantized
*/
virtual PxBounds3 refitBVH() = 0;
/**
\brief Returns the number of triangles.
\return number of triangles
@see getTriangles() getTrianglesRemap()
*/
virtual PxU32 getNbTriangles() const = 0;
/**
\brief Returns the triangle indices.
The indices can be 16 or 32bit depending on the number of triangles in the mesh.
Call getTriangleMeshFlags() to know if the indices are 16 or 32 bits.
The number of indices is the number of triangles * 3.
\return array of triangles
@see getNbTriangles() getTriangleMeshFlags() getTrianglesRemap()
*/
virtual const void* getTriangles() const = 0;
/**
\brief Reads the PxTriangleMesh flags.
See the list of flags #PxTriangleMeshFlag
\return The values of the PxTriangleMesh flags.
@see PxTriangleMesh
*/
virtual PxTriangleMeshFlags getTriangleMeshFlags() const = 0;
/**
\brief Returns the triangle remapping table.
The triangles are internally sorted according to various criteria. Hence the internal triangle order
does not always match the original (user-defined) order. The remapping table helps finding the old
indices knowing the new ones:
remapTable[ internalTriangleIndex ] = originalTriangleIndex
\return the remapping table (or NULL if 'PxCookingParams::suppressTriangleMeshRemapTable' has been used)
@see getNbTriangles() getTriangles() PxCookingParams::suppressTriangleMeshRemapTable
*/
virtual const PxU32* getTrianglesRemap() const = 0;
/**
\brief Decrements the reference count of a triangle mesh and releases it if the new reference count is zero.
@see PxPhysics.createTriangleMesh()
*/
virtual void release() = 0;
/**
\brief Returns material table index of given triangle
This function takes a post cooking triangle index.
\param[in] triangleIndex (internal) index of desired triangle
\return Material table index, or 0xffff if no per-triangle materials are used
*/
virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const = 0;
/**
\brief Returns the local-space (vertex space) AABB from the triangle mesh.
\return local-space bounds
*/
virtual PxBounds3 getLocalBounds() const = 0;
/**
\brief Returns the local-space Signed Distance Field for this mesh if it has one.
\return local-space SDF.
*/
virtual const PxReal* getSDF() const = 0;
/**
\brief Returns the resolution of the local-space dense SDF.
*/
virtual void getSDFDimensions(PxU32& numX, PxU32& numY, PxU32& numZ) const = 0;
/**
\brief Sets whether this mesh should be preferred for SDF projection.
By default, meshes are flagged as preferring projection and the decisions on which mesh to project is based on the triangle and vertex
count. The model with the fewer triangles is projected onto the SDF of the more detailed mesh.
If one of the meshes is set to prefer SDF projection (default) and the other is set to not prefer SDF projection, model flagged as
preferring SDF projection will be projected onto the model flagged as not preferring, regardless of the detail of the respective meshes.
Where both models are flagged as preferring no projection, the less detailed model will be projected as before.
\param[in] preferProjection Indicates if projection is preferred
*/
virtual void setPreferSDFProjection(bool preferProjection) = 0;
/**
\brief Returns whether this mesh prefers SDF projection.
\return whether this mesh prefers SDF projection.
*/
virtual bool getPreferSDFProjection() const = 0;
/**
\brief Returns the mass properties of the mesh assuming unit density.
The following relationship holds between mass and volume:
mass = volume * density
The mass of a unit density mesh is equal to its volume, so this function returns the volume of the mesh.
Similarly, to obtain the localInertia of an identically shaped object with a uniform density of d, simply multiply the
localInertia of the unit density mesh by d.
\param[out] mass The mass of the mesh assuming unit density.
\param[out] localInertia The inertia tensor in mesh local space assuming unit density.
\param[out] localCenterOfMass Position of center of mass (or centroid) in mesh local space.
*/
virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const = 0;
protected:
PX_INLINE PxTriangleMesh(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags) {}
PX_INLINE PxTriangleMesh(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxTriangleMesh() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxTriangleMesh", PxRefCounted); }
};
/**
\brief A triangle mesh containing the PxMeshMidPhase::eBVH33 structure.
@see PxMeshMidPhase
@deprecated
*/
class PX_DEPRECATED PxBVH33TriangleMesh : public PxTriangleMesh
{
public:
protected:
PX_INLINE PxBVH33TriangleMesh(PxType concreteType, PxBaseFlags baseFlags) : PxTriangleMesh(concreteType, baseFlags) {}
PX_INLINE PxBVH33TriangleMesh(PxBaseFlags baseFlags) : PxTriangleMesh(baseFlags) {}
virtual ~PxBVH33TriangleMesh() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBVH33TriangleMesh", PxTriangleMesh); }
};
/**
\brief A triangle mesh containing the PxMeshMidPhase::eBVH34 structure.
@see PxMeshMidPhase
*/
class PxBVH34TriangleMesh : public PxTriangleMesh
{
public:
protected:
PX_INLINE PxBVH34TriangleMesh(PxType concreteType, PxBaseFlags baseFlags) : PxTriangleMesh(concreteType, baseFlags) {}
PX_INLINE PxBVH34TriangleMesh(PxBaseFlags baseFlags) : PxTriangleMesh(baseFlags) {}
virtual ~PxBVH34TriangleMesh() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBVH34TriangleMesh", PxTriangleMesh); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 12,874 | C | 36.979351 | 184 | 0.771167 |
NVIDIA-Omniverse/PhysX/physx/include/geometry/PxCustomGeometry.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_CUSTOMGEOMETRY_H
#define PX_CUSTOMGEOMETRY_H
/** \addtogroup geomutils
@{
*/
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
#include "foundation/PxFoundationConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxContactBuffer;
class PxRenderOutput;
class PxMassProperties;
/**
\brief Custom geometry class. This class allows user to create custom geometries by providing a set of virtual callback functions.
*/
class PxCustomGeometry : public PxGeometry
{
public:
/**
\brief For internal use
*/
PX_PHYSX_COMMON_API static PxU32 getUniqueID();
/**
\brief The type of a custom geometry. Allows to identify a particular kind of it.
*/
struct Type
{
/**
\brief Default constructor
*/
PX_INLINE Type() : mID(getUniqueID()) {}
/**
\brief Default constructor
*/
PX_INLINE Type(const Type& t) : mID(t.mID) {}
/**
\brief Assigment operator
*/
PX_INLINE Type& operator = (const Type& t) { mID = t.mID; return *this; }
/**
\brief Equality operator
*/
PX_INLINE bool operator == (const Type& t) const { return mID == t.mID; }
/**
\brief Inequality operator
*/
PX_INLINE bool operator != (const Type& t) const { return mID != t.mID; }
/**
\brief Invalid type
*/
PX_INLINE static Type INVALID() { PxU32 z(0); return reinterpret_cast<const Type&>(z); }
private:
PxU32 mID;
};
/**
\brief Custom geometry callbacks structure. User should inherit this and implement all pure virtual functions.
*/
struct Callbacks
{
/**
\brief Return custom type. The type purpose is for user to differentiate custom geometries. Not used by PhysX.
\return Unique ID of a custom geometry type.
\note User should use DECLARE_CUSTOM_GEOMETRY_TYPE and IMPLEMENT_CUSTOM_GEOMETRY_TYPE intead of overwriting this function.
*/
virtual Type getCustomType() const = 0;
/**
\brief Return local bounds.
\param[in] geometry This geometry.
\return Bounding box in the geometry local space.
*/
virtual PxBounds3 getLocalBounds(const PxGeometry& geometry) const = 0;
/**
\brief Contacts generation. Generate collision contacts between two geometries in given poses.
\param[in] geom0 This custom geometry
\param[in] geom1 The other geometry
\param[in] pose0 This custom geometry pose
\param[in] pose1 The other geometry pose
\param[in] contactDistance The distance at which contacts begin to be generated between the pairs
\param[in] meshContactMargin The mesh contact margin.
\param[in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units
\param[out] contactBuffer A buffer to write contacts to.
\return True if there are contacts. False otherwise.
*/
virtual bool generateContacts(const PxGeometry& geom0, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1,
const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength,
PxContactBuffer& contactBuffer) const = 0;
/**
\brief Raycast. Cast a ray against the geometry in given pose.
\param[in] origin Origin of the ray.
\param[in] unitDir Normalized direction of the ray.
\param[in] geom This custom geometry
\param[in] pose This custom geometry pose
\param[in] maxDist Length of the ray. Has to be in the [0, inf) range.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] maxHits max number of returned hits = size of 'rayHits' buffer
\param[out] rayHits Ray hits.
\param[in] stride Ray hit structure stride.
\param[in] threadContext Optional user-defined per-thread context.
\return Number of hits.
*/
virtual PxU32 raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose,
PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* rayHits, PxU32 stride, PxRaycastThreadContext* threadContext) const = 0;
/**
\brief Overlap. Test if geometries overlap.
\param[in] geom0 This custom geometry
\param[in] pose0 This custom geometry pose
\param[in] geom1 The other geometry
\param[in] pose1 The other geometry pose
\param[in] threadContext Optional user-defined per-thread context.
\return True if there is overlap. False otherwise.
*/
virtual bool overlap(const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext* threadContext) const = 0;
/**
\brief Sweep. Sweep geom1 against geom0.
\param[in] unitDir Normalized direction of the sweep. geom1 is swept along this direction.
\param[in] maxDist Length of the sweep. Has to be in the [0, inf) range.
\param[in] geom0 This custom geometry
\param[in] pose0 This custom geometry pose
\param[in] geom1 The other geometry
\param[in] pose1 The other geometry pose
\param[out] sweepHit Used to report the sweep hit.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping.
\param[in] threadContext Optional user-defined per-thread context.
\return True if there is hit. False otherwise.
*/
virtual bool sweep(const PxVec3& unitDir, const PxReal maxDist,
const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext* threadContext) const = 0;
/**
\brief Visualize custom geometry for debugging. Optional.
\param[in] geometry This geometry.
\param[in] out Render output.
\param[in] absPose Geometry absolute transform.
\param[in] cullbox Region to visualize.
*/
virtual void visualize(const PxGeometry& geometry, PxRenderOutput& out, const PxTransform& absPose, const PxBounds3& cullbox) const = 0;
/**
\brief Compute custom geometry mass properties. For geometries usable with dynamic rigidbodies.
\param[in] geometry This geometry.
\param[out] massProperties Mass properties to compute.
*/
virtual void computeMassProperties(const PxGeometry& geometry, PxMassProperties& massProperties) const = 0;
/**
\brief Compatible with PhysX's PCM feature. Allows to optimize contact generation.
\param[in] geometry This geometry.
\param[out] breakingThreshold The threshold to trigger contacts re-generation.
*/
virtual bool usePersistentContactManifold(const PxGeometry& geometry, PxReal& breakingThreshold) const = 0;
/* Destructor */
virtual ~Callbacks() {}
};
/**
\brief Default constructor.
Creates an empty object with a NULL callbacks pointer.
*/
PX_INLINE PxCustomGeometry() :
PxGeometry(PxGeometryType::eCUSTOM),
callbacks(NULL)
{}
/**
\brief Constructor.
*/
PX_INLINE PxCustomGeometry(Callbacks& _callbacks) :
PxGeometry(PxGeometryType::eCUSTOM),
callbacks(&_callbacks)
{}
/**
\brief Copy constructor.
\param[in] that Other object
*/
PX_INLINE PxCustomGeometry(const PxCustomGeometry& that) :
PxGeometry(that),
callbacks(that.callbacks)
{}
/**
\brief Assignment operator
*/
PX_INLINE void operator=(const PxCustomGeometry& that)
{
mType = that.mType;
callbacks = that.callbacks;
}
/**
\brief Returns true if the geometry is valid.
\return True if the current settings are valid for shape creation.
@see PxRigidActor::createShape, PxPhysics::createShape
*/
PX_INLINE bool isValid() const;
/**
\brief Returns the custom type of the custom geometry.
*/
PX_INLINE Type getCustomType() const
{
return callbacks ? callbacks->getCustomType() : Type::INVALID();
}
public:
Callbacks* callbacks; //!< A reference to the callbacks object.
};
PX_INLINE bool PxCustomGeometry::isValid() const
{
return mType == PxGeometryType::eCUSTOM && callbacks != NULL;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/**
\brief Used in pair with IMPLEMENT_CUSTOM_GEOMETRY_TYPE to overwrite Callbacks::getCustomType() callback.
*/
#define DECLARE_CUSTOM_GEOMETRY_TYPE \
static ::physx::PxCustomGeometry::Type TYPE(); \
virtual ::physx::PxCustomGeometry::Type getCustomType() const;
/**
\brief Used in pair with DECLARE_CUSTOM_GEOMETRY_TYPE to overwrite Callbacks::getCustomType() callback.
*/
#define IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CLASS) \
::physx::PxCustomGeometry::Type CLASS::TYPE() \
{ \
static ::physx::PxCustomGeometry::Type customType; \
return customType; \
} \
::physx::PxCustomGeometry::Type CLASS::getCustomType() const \
{ \
return TYPE(); \
}
/** @} */
#endif
| 10,755 | C | 33.585209 | 175 | 0.716969 |
NVIDIA-Omniverse/PhysX/physx/include/solver/PxSolverDefs.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_SOLVER_DEFS_H
#define PX_SOLVER_DEFS_H
#include "PxPhysXConfig.h"
#include "foundation/PxVec3.h"
#include "foundation/PxMat33.h"
#include "foundation/PxTransform.h"
#include "PxConstraintDesc.h"
#include "geomutils/PxContactPoint.h"
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4324) // structure was padded due to alignment
#endif
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxTGSSolverBodyVel;
/**
\brief Struct that the solver uses to store velocity updates for a body
*/
struct PxSolverBody
{
PX_ALIGN(16, PxVec3) linearVelocity; //!< Delta linear velocity computed by the solver
PxU16 maxSolverNormalProgress; //!< Progress counter used by constraint batching and parallel island solver.
PxU16 maxSolverFrictionProgress; //!< Progress counter used by constraint batching and parallel island solver.
PxVec3 angularState; //!< Delta angular velocity state computed by the solver.
PxU32 solverProgress; //!< Progress counter used by constraint batching and parallel island solver
PxSolverBody() : linearVelocity(0.f), maxSolverNormalProgress(0), maxSolverFrictionProgress(0), angularState(0), solverProgress(0)
{
}
};
PX_COMPILE_TIME_ASSERT(sizeof(PxSolverBody) == 32);
/**
\brief Struct that the solver uses to store the state and other properties of a body
*/
struct PxSolverBodyData
{
PX_ALIGN(16, PxVec3 linearVelocity); //!< 12 Pre-solver linear velocity
PxReal invMass; //!< 16 inverse mass
PxVec3 angularVelocity; //!< 28 Pre-solver angular velocity
PxReal reportThreshold; //!< 32 contact force threshold
PxMat33 sqrtInvInertia; //!< 68 inverse inertia in world space
PxReal penBiasClamp; //!< 72 the penetration bias clamp
PxU32 nodeIndex; //!< 76 the node idx of this solverBodyData. Used by solver to reference between solver bodies and island bodies. Not required by immediate mode
PxReal maxContactImpulse; //!< 80 the max contact impulse
PxTransform body2World; //!< 108 the body's transform
PxU16 pad; //!< 112 pad
PX_FORCE_INLINE PxReal projectVelocity(const PxVec3& lin, const PxVec3& ang) const
{
return linearVelocity.dot(lin) + angularVelocity.dot(ang);
}
};
PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxSolverBodyData) & 15));
//----------------------------------
/**
\brief A header that defines the size of a specific batch of constraints (of same type and without dependencies)
*/
struct PxConstraintBatchHeader
{
PxU32 startIndex; //!< Start index for this batch
PxU16 stride; //!< Number of constraints in this batch (range: 1-4)
PxU16 constraintType; //!< The type of constraint this batch references
};
/**
\brief Constraint descriptor used inside the solver
*/
struct PxSolverConstraintDesc
{
static const PxU16 RIGID_BODY = 0xffff;
enum ConstraintType
{
eCONTACT_CONSTRAINT, //!< Defines this pair is a contact constraint
eJOINT_CONSTRAINT //!< Defines this pair is a joint constraint
};
union
{
PxSolverBody* bodyA; //!< bodyA pointer
PxTGSSolverBodyVel* tgsBodyA; //!< bodyA pointer
void* articulationA; //!< Articulation pointer for body A
};
union
{
PxSolverBody* bodyB; //!< BodyB pointer
PxTGSSolverBodyVel* tgsBodyB; //!< BodyB pointer
void* articulationB; //!< Articulation pointer for body B
};
PxU32 bodyADataIndex; //!< Body A's index into the SolverBodyData array
PxU32 bodyBDataIndex; //!< Body B's index into the SolverBodyData array
PxU32 linkIndexA; //!< Link index defining which link in Articulation A this constraint affects. If not an articulation, must be PxSolverConstraintDesc::RIGID_BODY
PxU32 linkIndexB; //!< Link index defining which link in Articulation B this constraint affects. If not an articulation, must be PxSolverConstraintDesc::RIGID_BODY
PxU8* constraint; //!< Pointer to the constraint rows to be solved
void* writeBack; //!< Pointer to the writeback structure results for this given constraint are to be written to
PxU16 progressA; //!< Internal progress counter
PxU16 progressB; //!< Internal progress counter
PxU16 constraintLengthOver16; //!< constraintLength/16, max constraint length is 1MB
PxU8 padding[10];
};
/**
\brief Data structure used for preparing constraints before solving them
*/
struct PxSolverConstraintPrepDescBase
{
enum BodyState
{
eDYNAMIC_BODY = 1 << 0,
eSTATIC_BODY = 1 << 1,
eKINEMATIC_BODY = 1 << 2,
eARTICULATION = 1 << 3
};
PxConstraintInvMassScale invMassScales; //!< In: The local mass scaling for this pair.
PxSolverConstraintDesc* desc; //!< Output: The PxSolverConstraintDesc filled in by contact prep
const PxSolverBody* body0; //!< In: The first body. Stores velocity information. Unused unless contact involves articulations.
const PxSolverBody* body1; //!< In: The second body. Stores velocity information. Unused unless contact involves articulations.
const PxSolverBodyData* data0; //!< In: The first PxSolverBodyData. Stores mass and miscellaneous information for the first body.
const PxSolverBodyData* data1; //!< In: The second PxSolverBodyData. Stores mass and miscellaneous information for the second body
PxTransform bodyFrame0; //!< In: The world-space transform of the first body.
PxTransform bodyFrame1; //!< In: The world-space transform of the second body.
BodyState bodyState0; //!< In: Defines what kind of actor the first body is
BodyState bodyState1; //!< In: Defines what kind of actor the second body is
};
/**
\brief Data structure used for preparing constraints before solving them
*/
struct PxSolverConstraintPrepDesc : public PxSolverConstraintPrepDescBase
{
PX_ALIGN(16, Px1DConstraint* rows); //!< The start of the constraint rows
PxU32 numRows; //!< The number of rows
PxReal linBreakForce, angBreakForce; //!< Break forces
PxReal minResponseThreshold; //!< The minimum response threshold
void* writeback; //!< Pointer to constraint writeback structure. Reports back joint breaking. If not required, set to NULL.
bool disablePreprocessing; //!< Disable joint pre-processing. Pre-processing can improve stability but under certain circumstances, e.g. when some invInertia rows are zero/almost zero, can cause instabilities.
bool improvedSlerp; //!< Use improved slerp model
bool driveLimitsAreForces; //!< Indicates whether drive limits are forces
bool extendedLimits; //!< Indicates whether we want to use extended limits
bool disableConstraint; //!< Disables constraint
PxVec3p body0WorldOffset; //!< Body0 world offset
};
/**
\brief Data structure used for preparing constraints before solving them
*/
struct PxSolverContactDesc : public PxSolverConstraintPrepDescBase
{
void* shapeInteraction; //!< Pointer to shape interaction. Used for force threshold reports in solver. Set to NULL if using immediate mode.
PxContactPoint* contacts; //!< The start of the contacts for this pair
PxU32 numContacts; //!< The total number of contacts this pair references.
bool hasMaxImpulse; //!< Defines whether this pairs has maxImpulses clamping enabled
bool disableStrongFriction; //!< Defines whether this pair disables strong friction (sticky friction correlation)
bool hasForceThresholds; //!< Defines whether this pair requires force thresholds
PxReal restDistance; //!< A distance at which the solver should aim to hold the bodies separated. Default is 0
PxReal maxCCDSeparation; //!< A distance used to configure speculative CCD behavior. Default is PX_MAX_F32. Set internally in PhysX for bodies with eENABLE_SPECULATIVE_CCD on. Do not set directly!
PxU8* frictionPtr; //!< InOut: Friction patch correlation data. Set each frame by solver. Can be retained for improved behavior or discarded each frame.
PxU8 frictionCount; //!< The total number of friction patches in this pair
PxReal* contactForces; //!< Out: A buffer for the solver to write applied contact forces to.
PxU32 startFrictionPatchIndex; //!< Start index of friction patch in the correlation buffer. Set by friction correlation
PxU32 numFrictionPatches; //!< Total number of friction patches in this pair. Set by friction correlation
PxU32 startContactPatchIndex; //!< The start index of this pair's contact patches in the correlation buffer. For internal use only
PxU16 numContactPatches; //!< Total number of contact patches.
PxU16 axisConstraintCount; //!< Axis constraint count. Defines how many constraint rows this pair has produced. Useful for statistical purposes.
PxReal offsetSlop; //!< Slop value used to snap contact line of action back in-line with the COM.
//PxU8 pad[16 - sizeof(void*)];
};
class PxConstraintAllocator
{
public:
/**
\brief Allocates constraint data. It is the application's responsibility to release this memory after PxSolveConstraints has completed.
\param[in] byteSize Allocation size in bytes
\return The allocated memory. This address must be 16-byte aligned.
*/
virtual PxU8* reserveConstraintData(const PxU32 byteSize) = 0;
/**
\brief Allocates friction data. Friction data can be retained by the application for a given pair and provided as an input to PxSolverContactDesc to improve simulation stability.
It is the application's responsibility to release this memory. If this memory is released, the application should ensure it does not pass pointers to this memory to PxSolverContactDesc.
\param[in] byteSize Allocation size in bytes
\return The allocated memory. This address must be 4-byte aligned.
*/
virtual PxU8* reserveFrictionData(const PxU32 byteSize) = 0;
virtual ~PxConstraintAllocator() {}
};
/** \addtogroup physics
@{ */
struct PxArticulationAxis
{
enum Enum
{
eTWIST = 0, //!< Rotational about eX
eSWING1 = 1, //!< Rotational about eY
eSWING2 = 2, //!< Rotational about eZ
eX = 3, //!< Linear in eX
eY = 4, //!< Linear in eY
eZ = 5, //!< Linear in eZ
eCOUNT = 6
};
};
PX_FLAGS_OPERATORS(PxArticulationAxis::Enum, PxU8)
struct PxArticulationMotion
{
enum Enum
{
eLOCKED = 0, //!< Locked axis, i.e. degree of freedom (DOF)
eLIMITED = 1, //!< Limited DOF - set limits of joint DOF together with this flag, see PxArticulationJointReducedCoordinate::setLimitParams
eFREE = 2 //!< Free DOF
};
};
typedef PxFlags<PxArticulationMotion::Enum, PxU8> PxArticulationMotions;
PX_FLAGS_OPERATORS(PxArticulationMotion::Enum, PxU8)
struct PxArticulationJointType
{
enum Enum
{
eFIX = 0, //!< All joint axes, i.e. degrees of freedom (DOFs) locked
ePRISMATIC = 1, //!< Single linear DOF, e.g. cart on a rail
eREVOLUTE = 2, //!< Single rotational DOF, e.g. an elbow joint or a rotational motor, position wrapped at 2pi radians
eREVOLUTE_UNWRAPPED = 3, //!< Single rotational DOF, e.g. an elbow joint or a rotational motor, position not wrapped
eSPHERICAL = 4, //!< Ball and socket joint with two or three DOFs
eUNDEFINED = 5
};
};
struct PxArticulationFlag
{
enum Enum
{
eFIX_BASE = (1 << 0), //!< Set articulation base to be fixed.
eDRIVE_LIMITS_ARE_FORCES = (1<<1), //!< Limits for drive effort are forces and torques rather than impulses, see PxArticulationDrive::maxForce.
eDISABLE_SELF_COLLISION = (1<<2), //!< Disable collisions between the articulation's links (note that parent/child collisions are disabled internally in either case).
eCOMPUTE_JOINT_FORCES = (1<<3) //!< @deprecated Enable in order to be able to query joint solver (i.e. constraint) forces using PxArticulationCache::jointSolverForces.
};
};
typedef PxFlags<PxArticulationFlag::Enum, PxU8> PxArticulationFlags;
PX_FLAGS_OPERATORS(PxArticulationFlag::Enum, PxU8)
struct PxArticulationDriveType
{
enum Enum
{
eFORCE = 0, //!< The output of the implicit spring drive controller is a force/torque.
eACCELERATION = 1, //!< The output of the implicit spring drive controller is a joint acceleration (use this to get (spatial)-inertia-invariant behavior of the drive).
eTARGET = 2, //!< Sets the drive gains internally to track a target position almost kinematically (i.e. with very high drive gains).
eVELOCITY = 3, //!< Sets the drive gains internally to track a target velocity almost kinematically (i.e. with very high drive gains).
eNONE = 4
};
};
/**
\brief Data structure to set articulation joint limits.
- The lower limit should be strictly smaller than the higher limit. If the limits should be equal, use PxArticulationMotion::eLOCKED
and an appropriate offset in the parent/child joint frames.
- The limit units are linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis.
@see PxArticulationJointReducedCoordinate::setLimitParams, PxArticulationReducedCoordinate
*/
struct PxArticulationLimit
{
PxArticulationLimit(){}
PxArticulationLimit(const PxReal low_, const PxReal high_)
{
low = low_;
high = high_;
}
/**
\brief The lower limit on the joint axis position.
<b>Range:</b> [-PX_MAX_F32, high)<br>
<b>Default:</b> 0.0f<br>
*/
PxReal low;
/**
\brief The higher limit on the joint axis position.
<b>Range:</b> (low, PX_MAX_F32]<br>
<b>Default:</b> 0.0f<br>
*/
PxReal high;
};
/**
\brief Data structure for articulation joint drive configuration.
@see PxArticulationJointReducedCoordinate::setDriveParams, PxArticulationReducedCoordinate
*/
struct PxArticulationDrive
{
PxArticulationDrive(){}
PxArticulationDrive(const PxReal stiffness_, const PxReal damping_, const PxReal maxForce_, PxArticulationDriveType::Enum driveType_=PxArticulationDriveType::eFORCE)
{
stiffness = stiffness_;
damping = damping_;
maxForce = maxForce_;
driveType = driveType_;
}
/**
\brief The drive stiffness, i.e. the proportional gain of the implicit PD controller.
See manual for further information, and the drives' implicit spring-damper (i.e. PD control) implementation in particular.
<b>Units:</b> (distance = linear scene units)<br>
Rotational axis: torque/rad if driveType = PxArticulationDriveType::eFORCE; or (rad/s^2)/rad if driveType = PxArticulationDriveType::eACCELERATION<br>
Translational axis: force/distance if driveType = PxArticulationDriveType::eFORCE; or (distance/s^2)/distance if driveType = PxArticulationDriveType::eACCELERATION<br>
<b>Range:</b> [0, PX_MAX_F32]<br>
<b>Default:</b> 0.0f<br>
*/
PxReal stiffness;
/**
\brief The drive damping, i.e. the derivative gain of the implicit PD controller.
See manual for further information, and the drives' implicit spring-damper (i.e. PD control) implementation in particular.
<b>Units:</b> (distance = linear scene units)<br>
Rotational axis: torque/(rad/s) if driveType = PxArticulationDriveType::eFORCE; or (rad/s^2)/(rad/s) if driveType = PxArticulationDriveType::eACCELERATION<br>
Translational axis: force/(distance/s) if driveType = PxArticulationDriveType::eFORCE; or (distance/s^2)/(distance/s) if driveType = PxArticulationDriveType::eACCELERATION<br>
<b>Range:</b> [0, PX_MAX_F32]<br>
<b>Default:</b> 0.0f<br>
*/
PxReal damping;
/**
\brief The drive force limit.
- The limit is enforced regardless of the drive type #PxArticulationDriveType.
- The limit corresponds to a force (linear axis) or torque (rotational axis) if PxArticulationFlag::eDRIVE_LIMITS_ARE_FORCES is set, and to an impulse (force|torque * dt) otherwise.
<b>Range:</b> [0, PX_MAX_F32]<br>
<b>Default:</b> 0.0f<br>
@see PxArticulationFlag::eDRIVE_LIMITS_ARE_FORCES
*/
PxReal maxForce;
/**
\brief The drive type.
@see PxArticulationDriveType
*/
PxArticulationDriveType::Enum driveType;
};
/** @} */
struct PxTGSSolverBodyVel
{
PX_ALIGN(16, PxVec3) linearVelocity; //12
PxU16 nbStaticInteractions; //14 Used to accumulate the number of static interactions
PxU16 maxDynamicPartition; //16 Used to accumulate the max partition of dynamic interactions
PxVec3 angularVelocity; //28
PxU32 partitionMask; //32 Used in partitioning as a bit-field
PxVec3 deltaAngDt; //44
PxReal maxAngVel; //48
PxVec3 deltaLinDt; //60
PxU16 lockFlags; //62
bool isKinematic; //63
PxU8 pad; //64
PX_FORCE_INLINE PxReal projectVelocity(const PxVec3& lin, const PxVec3& ang) const
{
return linearVelocity.dot(lin) + angularVelocity.dot(ang);
}
};
//Needed only by prep, integration and 1D constraints
struct PxTGSSolverBodyTxInertia
{
PxTransform deltaBody2World;
PxMat33 sqrtInvInertia; //!< inverse inertia in world space
};
struct PxTGSSolverBodyData
{
PX_ALIGN(16, PxVec3) originalLinearVelocity; //!< Pre-solver linear velocity.
PxReal maxContactImpulse; //!< The max contact impulse.
PxVec3 originalAngularVelocity; //!< Pre-solver angular velocity
PxReal penBiasClamp; //!< The penetration bias clamp.
PxReal invMass; //!< Inverse mass.
PxU32 nodeIndex; //!< The node idx of this solverBodyData. Used by solver to reference between solver bodies and island bodies. Not required by immediate mode.
PxReal reportThreshold; //!< Contact force threshold.
PxU32 pad;
PxReal projectVelocity(const PxVec3& linear, const PxVec3& angular) const
{
return originalLinearVelocity.dot(linear) + originalAngularVelocity.dot(angular);
}
};
struct PxTGSSolverConstraintPrepDescBase
{
PxConstraintInvMassScale invMassScales; //!< In: The local mass scaling for this pair.
PxSolverConstraintDesc* desc; //!< Output: The PxSolverConstraintDesc filled in by contact prep
const PxTGSSolverBodyVel* body0; //!< In: The first body. Stores velocity information. Unused unless contact involves articulations.
const PxTGSSolverBodyVel* body1; //!< In: The second body. Stores velocity information. Unused unless contact involves articulations.
const PxTGSSolverBodyTxInertia* body0TxI; //!< In: The first PxTGSSolverBodyTxInertia. Stores the delta body to world transform and sqrtInvInertia for first body.
const PxTGSSolverBodyTxInertia* body1TxI; //!< In: The second PxTGSSolverBodyTxInertia. Stores the delta body to world transform and sqrtInvInertia for second body.
const PxTGSSolverBodyData* bodyData0; //!< In: The first PxTGSSolverBodyData. Stores mass and miscellaneous information for the first body.
const PxTGSSolverBodyData* bodyData1; //!< In: The second PxTGSSolverBodyData. Stores mass and miscellaneous information for the second body.
PxTransform bodyFrame0; //!< In: The world-space transform of the first body.
PxTransform bodyFrame1; //!< In: The world-space transform of the second body.
PxSolverContactDesc::BodyState bodyState0; //!< In: Defines what kind of actor the first body is
PxSolverContactDesc::BodyState bodyState1; //!< In: Defines what kind of actor the second body is
};
struct PxTGSSolverConstraintPrepDesc : public PxTGSSolverConstraintPrepDescBase
{
Px1DConstraint* rows; //!< The start of the constraint rows
PxU32 numRows; //!< The number of rows
PxReal linBreakForce, angBreakForce; //!< Break forces
PxReal minResponseThreshold; //!< The minimum response threshold
void* writeback; //!< Pointer to constraint writeback structure. Reports back joint breaking. If not required, set to NULL.
bool disablePreprocessing; //!< Disable joint pre-processing. Pre-processing can improve stability but under certain circumstances, e.g. when some invInertia rows are zero/almost zero, can cause instabilities.
bool improvedSlerp; //!< Use improved slerp model
bool driveLimitsAreForces; //!< Indicates whether drive limits are forces
bool extendedLimits; //!< Indicates whether extended limits are used
bool disableConstraint; //!< Disables constraint
PxVec3p body0WorldOffset; //!< Body0 world offset
PxVec3p cA2w; //!< Location of anchor point A in world space
PxVec3p cB2w; //!< Location of anchor point B in world space
};
struct PxTGSSolverContactDesc : public PxTGSSolverConstraintPrepDescBase
{
void* shapeInteraction; //!< Pointer to shape interaction. Used for force threshold reports in solver. Set to NULL if using immediate mode.
PxContactPoint* contacts; //!< The start of the contacts for this pair
PxU32 numContacts; //!< The total number of contacts this pair references.
bool hasMaxImpulse; //!< Defines whether this pairs has maxImpulses clamping enabled
bool disableStrongFriction; //!< Defines whether this pair disables strong friction (sticky friction correlation)
bool hasForceThresholds; //!< Defines whether this pair requires force thresholds
PxReal restDistance; //!< A distance at which the solver should aim to hold the bodies separated. Default is 0
PxReal maxCCDSeparation; //!< A distance used to configure speculative CCD behavior. Default is PX_MAX_F32. Set internally in PhysX for bodies with eENABLE_SPECULATIVE_CCD on. Do not set directly!
PxU8* frictionPtr; //!< InOut: Friction patch correlation data. Set each frame by solver. Can be retained for improved behavior or discarded each frame.
PxU8 frictionCount; //!< The total number of friction patches in this pair
PxReal* contactForces; //!< Out: A buffer for the solver to write applied contact forces to.
PxU32 startFrictionPatchIndex; //!< Start index of friction patch in the correlation buffer. Set by friction correlation
PxU32 numFrictionPatches; //!< Total number of friction patches in this pair. Set by friction correlation
PxU32 startContactPatchIndex; //!< The start index of this pair's contact patches in the correlation buffer. For internal use only
PxU16 numContactPatches; //!< Total number of contact patches.
PxU16 axisConstraintCount; //!< Axis constraint count. Defines how many constraint rows this pair has produced. Useful for statistical purposes.
PxReal maxImpulse; //!< The maximum impulse the solver is allowed to introduce for this pair of bodies.
PxReal torsionalPatchRadius; //!< This defines the radius of the contact patch used to apply torsional friction.
PxReal minTorsionalPatchRadius; //!< This defines the minimum radius of the contact patch used to apply torsional friction.
PxReal offsetSlop; //!< Slop value used to snap contact line of action back in-line with the COM.
};
#if !PX_DOXYGEN
}
#endif
#if PX_VC
#pragma warning(pop)
#endif
#endif
| 23,999 | C | 42.956044 | 214 | 0.744823 |
NVIDIA-Omniverse/PhysX/physx/buildtools/cmake_generate_projects.py | import sys
import os
import glob
import os.path
import shutil
import subprocess
import xml.etree.ElementTree
def packmanExt():
if sys.platform == 'win32':
return 'cmd'
return 'sh'
def cmakeExt():
if sys.platform == 'win32':
return '.exe'
return ''
def filterPreset(presetName):
winPresetFilter = ['win','switch','crosscompile']
if sys.platform == 'win32':
if any(presetName.find(elem) != -1 for elem in winPresetFilter):
return True
else:
if all(presetName.find(elem) == -1 for elem in winPresetFilter):
return True
return False
def noPresetProvided():
global input
print('Preset parameter required, available presets:')
presetfiles = []
for file in glob.glob("buildtools/presets/*.xml"):
presetfiles.append(file)
if len(presetfiles) == 0:
for file in glob.glob("buildtools/presets/public/*.xml"):
presetfiles.append(file)
counter = 0
presetList = []
for preset in presetfiles:
if filterPreset(preset):
presetXml = xml.etree.ElementTree.parse(preset).getroot()
if(preset.find('user') == -1):
print('(' + str(counter) + ') ' + presetXml.get('name') +
' <--- ' + presetXml.get('comment'))
presetList.append(presetXml.get('name'))
else:
print('(' + str(counter) + ') ' + presetXml.get('name') +
'.user <--- ' + presetXml.get('comment'))
presetList.append(presetXml.get('name') + '.user')
counter = counter + 1
# Fix Python 2.x.
try:
input = raw_input
except NameError:
pass
mode = int(eval(input('Enter preset number: ')))
return presetList[mode]
class CMakePreset:
presetName = ''
targetPlatform = ''
compiler = ''
generator = ''
cmakeSwitches = []
cmakeParams = []
def __init__(self, presetName):
xmlPath = "buildtools/presets/"+presetName+'.xml'
if os.path.isfile(xmlPath):
print('Using preset xml: '+xmlPath)
else:
xmlPath = "buildtools/presets/public/"+presetName+'.xml'
if os.path.isfile(xmlPath):
print('Using preset xml: '+xmlPath)
else:
print('Preset xml file: '+xmlPath+' not found')
exit()
# get the xml
presetNode = xml.etree.ElementTree.parse(xmlPath).getroot()
self.presetName = presetNode.attrib['name']
for platform in presetNode.findall('platform'):
self.targetPlatform = platform.attrib['targetPlatform']
self.compiler = platform.attrib['compiler']
self.generator = platform.get('generator')
print('Target platform: ' + self.targetPlatform +
' using compiler: ' + self.compiler)
if self.generator is not None:
print(' using generator: ' + self.generator)
for cmakeSwitch in presetNode.find('CMakeSwitches'):
cmSwitch = '-D' + \
cmakeSwitch.attrib['name'] + '=' + \
cmakeSwitch.attrib['value'].upper()
self.cmakeSwitches.append(cmSwitch)
for cmakeParam in presetNode.find('CMakeParams'):
if cmakeParam.attrib['name'] == 'CMAKE_INSTALL_PREFIX' or cmakeParam.attrib['name'] == 'PX_OUTPUT_LIB_DIR' or cmakeParam.attrib['name'] == 'PX_OUTPUT_EXE_DIR' or cmakeParam.attrib['name'] == 'PX_OUTPUT_DLL_DIR':
cmParam = '-D' + cmakeParam.attrib['name'] + '=\"' + \
os.environ['PHYSX_ROOT_DIR'] + '/' + \
cmakeParam.attrib['value'] + '\"'
else:
cmParam = '-D' + \
cmakeParam.attrib['name'] + '=' + \
cmakeParam.attrib['value']
self.cmakeParams.append(cmParam)
pass
def isMultiConfigPlatform(self):
if self.targetPlatform == 'linux':
return False
elif self.targetPlatform == 'linuxAarch64':
return False
return True
def getCMakeSwitches(self):
outString = ''
# We need gpuProjectsFound flag to avoid issues when we have both
# PX_GENERATE_GPU_PROJECTS and PX_GENERATE_GPU_PROJECTS_ONLY switches
gpuProjectsFound = False # initialize flag
for cmakeSwitch in self.cmakeSwitches:
outString = outString + ' ' + cmakeSwitch
if not gpuProjectsFound and cmakeSwitch.find('PX_GENERATE_GPU_PROJECTS') != -1:
gpuProjectsFound = True # set flag to True when keyword found
if os.environ.get('PM_CUDA_PATH') is not None:
outString = outString + ' -DCUDAToolkit_ROOT_DIR=' + \
os.environ['PM_CUDA_PATH']
if self.compiler in ['vc15', 'vc16', 'vc17'] and self.generator != 'ninja':
outString = outString + ' -T cuda=' + os.environ['PM_CUDA_PATH']
# TODO: Need to do the same for gcc (aarch64) when we package it with Packman
elif self.compiler == 'clang':
if os.environ.get('PM_clang_PATH') is not None:
outString = outString + ' -DCMAKE_CUDA_HOST_COMPILER=' + \
os.environ['PM_clang_PATH'] + '/bin/clang++'
return outString
def getCMakeParams(self):
outString = ''
for cmakeParam in self.cmakeParams:
outString = outString + ' ' + cmakeParam # + ' --trace'
return outString
def getPlatformCMakeParams(self):
cmake_modules_root = os.environ['PHYSX_ROOT_DIR'] + '/source/compiler/cmake/modules'
outString = ' '
vs_versions = {
'vc15': '\"Visual Studio 15 2017\"',
'vc16': '\"Visual Studio 16 2019\"',
'vc17': '\"Visual Studio 17 2022\"'
}
# Visual studio
if self.compiler in vs_versions:
generator = '-G \"Ninja Multi-Config\"' if self.generator == 'ninja' else '-G ' + vs_versions[self.compiler]
outString += generator
# mac
elif self.compiler == 'xcode':
outString = outString + '-G Xcode'
# Linux
elif self.targetPlatform in ['linux', 'linuxAarch64']:
if self.generator is not None and self.generator == 'ninja':
outString = outString + '-G \"Ninja\"'
outString = outString + ' -DCMAKE_MAKE_PROGRAM=' + os.environ['PM_ninja_PATH'] + '/ninja'
else:
outString = outString + '-G \"Unix Makefiles\"'
if self.targetPlatform == 'win64':
if self.generator != 'ninja':
outString = outString + ' -Ax64'
outString = outString + ' -DTARGET_BUILD_PLATFORM=windows'
outString = outString + ' -DPX_OUTPUT_ARCH=x86'
return outString
elif self.targetPlatform == 'switch64':
outString = outString + ' -DTARGET_BUILD_PLATFORM=switch'
outString = outString + ' -DCMAKE_TOOLCHAIN_FILE=' + \
cmake_modules_root + '/switch/NX64Toolchain.txt'
outString = outString + ' -DCMAKE_GENERATOR_PLATFORM=NX64'
return outString
elif self.targetPlatform == 'linux':
outString = outString + ' -DTARGET_BUILD_PLATFORM=linux'
outString = outString + ' -DPX_OUTPUT_ARCH=x86'
if self.compiler == 'clang-crosscompile':
outString = outString + ' -DCMAKE_TOOLCHAIN_FILE=' + \
cmake_modules_root + '/linux/LinuxCrossToolchain.x86_64-unknown-linux-gnu.cmake'
outString = outString + ' -DCMAKE_MAKE_PROGRAM=' + os.environ.get('PM_MinGW_PATH') + '/bin/mingw32-make.exe'
elif self.compiler == 'clang':
if os.environ.get('PM_clang_PATH') is not None:
outString = outString + ' -DCMAKE_C_COMPILER=' + \
os.environ['PM_clang_PATH'] + '/bin/clang'
outString = outString + ' -DCMAKE_CXX_COMPILER=' + \
os.environ['PM_clang_PATH'] + '/bin/clang++'
else:
outString = outString + ' -DCMAKE_C_COMPILER=clang'
outString = outString + ' -DCMAKE_CXX_COMPILER=clang++'
return outString
elif self.targetPlatform == 'linuxAarch64':
outString = outString + ' -DTARGET_BUILD_PLATFORM=linux'
outString = outString + ' -DPX_OUTPUT_ARCH=arm'
if self.compiler == 'clang-crosscompile':
outString = outString + ' -DCMAKE_TOOLCHAIN_FILE=' + \
cmake_modules_root + '/linux/LinuxCrossToolchain.aarch64-unknown-linux-gnueabihf.cmake'
outString = outString + ' -DCMAKE_MAKE_PROGRAM=' + os.environ.get('PM_MinGW_PATH') + '/bin/mingw32-make.exe'
elif self.compiler == 'gcc':
# TODO: To change so it uses Packman's compiler. Then add it as
# host compiler for CUDA above.
outString = outString + ' -DCMAKE_TOOLCHAIN_FILE=\"' + \
cmake_modules_root + '/linux/LinuxAarch64.cmake\"'
return outString
elif self.targetPlatform == 'mac64':
outString = outString + ' -DTARGET_BUILD_PLATFORM=mac'
outString = outString + ' -DPX_OUTPUT_ARCH=x86'
return outString
return ''
def getCommonParams():
outString = '--no-warn-unused-cli'
outString = outString + ' -DCMAKE_PREFIX_PATH=\"' + os.environ['PM_PATHS'] + '\"'
outString = outString + ' -DPHYSX_ROOT_DIR=\"' + \
os.environ['PHYSX_ROOT_DIR'] + '\"'
outString = outString + ' -DPX_OUTPUT_LIB_DIR=\"' + \
os.environ['PHYSX_ROOT_DIR'] + '\"'
outString = outString + ' -DPX_OUTPUT_BIN_DIR=\"' + \
os.environ['PHYSX_ROOT_DIR'] + '\"'
if os.environ.get('GENERATE_SOURCE_DISTRO') == '1':
outString = outString + ' -DPX_GENERATE_SOURCE_DISTRO=1'
return outString
def cleanupCompilerDir(compilerDirName):
if os.path.exists(compilerDirName):
if sys.platform == 'win32':
os.system('rmdir /S /Q ' + compilerDirName)
else:
shutil.rmtree(compilerDirName, True)
if os.path.exists(compilerDirName) == False:
os.makedirs(compilerDirName)
def presetProvided(pName):
parsedPreset = CMakePreset(pName)
print('PM_PATHS: ' + os.environ['PM_PATHS'])
if os.environ.get('PM_cmake_PATH') is not None:
cmakeExec = os.environ['PM_cmake_PATH'] + '/bin/cmake' + cmakeExt()
else:
cmakeExec = 'cmake' + cmakeExt()
print('Cmake: ' + cmakeExec)
# gather cmake parameters
cmakeParams = parsedPreset.getPlatformCMakeParams()
cmakeParams = cmakeParams + ' ' + getCommonParams()
cmakeParams = cmakeParams + ' ' + parsedPreset.getCMakeSwitches()
cmakeParams = cmakeParams + ' ' + parsedPreset.getCMakeParams()
# print(cmakeParams)
if os.path.isfile(os.environ['PHYSX_ROOT_DIR'] + '/compiler/internal/CMakeLists.txt'):
cmakeMasterDir = 'internal'
else:
cmakeMasterDir = 'public'
if parsedPreset.isMultiConfigPlatform():
# cleanup and create output directory
outputDir = os.path.join('compiler', parsedPreset.presetName)
cleanupCompilerDir(outputDir)
# run the cmake script
#print('Cmake params:' + cmakeParams)
os.chdir(os.path.join(os.environ['PHYSX_ROOT_DIR'], outputDir))
os.system(cmakeExec + ' \"' +
os.environ['PHYSX_ROOT_DIR'] + '/compiler/' + cmakeMasterDir + '\"' + cmakeParams)
os.chdir(os.environ['PHYSX_ROOT_DIR'])
else:
configs = ['debug', 'checked', 'profile', 'release']
for config in configs:
# cleanup and create output directory
outputDir = os.path.join('compiler', parsedPreset.presetName + '-' + config)
cleanupCompilerDir(outputDir)
# run the cmake script
#print('Cmake params:' + cmakeParams)
os.chdir(os.path.join(os.environ['PHYSX_ROOT_DIR'], outputDir))
# print(cmakeExec + ' \"' + os.environ['PHYSX_ROOT_DIR'] + '/compiler/' + cmakeMasterDir + '\"' + cmakeParams + ' -DCMAKE_BUILD_TYPE=' + config)
os.system(cmakeExec + ' \"' + os.environ['PHYSX_ROOT_DIR'] + '/compiler/' +
cmakeMasterDir + '\"' + cmakeParams + ' -DCMAKE_BUILD_TYPE=' + config)
os.chdir(os.environ['PHYSX_ROOT_DIR'])
pass
def main():
if (sys.version_info[0] < 3) or (sys.version_info[0] == 3 and sys.version_info[1] < 5):
print("You are using Python {}. You must use Python 3.5 and up. Please read README.md for requirements.").format(sys.version)
exit()
physx_root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
os.environ['PHYSX_ROOT_DIR'] = physx_root_dir.replace("\\", "/")
if len(sys.argv) != 2:
presetName = noPresetProvided()
if sys.platform == 'win32':
print('Running generate_projects.bat ' + presetName)
cmd = 'generate_projects.bat {}'.format(presetName)
result = subprocess.run(cmd, cwd=os.environ['PHYSX_ROOT_DIR'], check=True, universal_newlines=True)
# TODO: catch exception and add capture errors
else:
print('Running generate_projects.sh ' + presetName)
# TODO: once we have Python 3.7.2 for linux, add the text=True instead of universal_newlines
cmd = './generate_projects.sh {}'.format(presetName)
result = subprocess.run(['bash', './generate_projects.sh', presetName], cwd=os.environ['PHYSX_ROOT_DIR'], check=True, universal_newlines=True)
# TODO: catch exception and add capture errors
else:
presetName = sys.argv[1]
if filterPreset(presetName):
presetProvided(presetName)
else:
print('Preset not supported on this build platform.')
main()
| 14,130 | Python | 42.885093 | 223 | 0.573107 |
NVIDIA-Omniverse/PhysX/physx/buildtools/templates/PxIncludeTemplate.h | ${BOILERPLATE_CONTENT}
#ifndef PX_${HEADER_GUARD_NAME}
#define PX_${HEADER_GUARD_NAME}
${HEADER_CONTENT}
#endif // PX_${HEADER_GUARD_NAME}
| 143 | C | 14.999998 | 34 | 0.692308 |
NVIDIA-Omniverse/PhysX/blast/PACKAGE-INFO.yaml | Package : blast-sdk
Maintainers : Bryan Galdrikian, Eric Arnold
Description : Blast destruction SDK
SWIPAT NvBug :
Repository : https://gitlab-master.nvidia.com/omniverse/blast-sdk
License Type : NVIDIA | 203 | YAML | 32.999995 | 65 | 0.79803 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.