Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1229 lines
54 KiB

  1. //===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose: Public interfaces to vphysics DLL
  4. //
  5. // $NoKeywords: $
  6. //===========================================================================//
  7. #ifndef VPHYSICS_INTERFACE_H
  8. #define VPHYSICS_INTERFACE_H
  9. #ifdef _WIN32
  10. #pragma once
  11. #endif
  12. #include "tier1/interface.h"
  13. #include "appframework/iappsystem.h"
  14. #include "mathlib/vector.h"
  15. #include "mathlib/vector4d.h"
  16. #include "vcollide.h"
  17. #include "tier3/tier3.h"
  18. #include "SoundEmitterSystem/isoundemittersystembase.h"
  19. // ------------------------------------------------------------------------------------
  20. // UNITS:
  21. // ------------------------------------------------------------------------------------
  22. // NOTE: Coordinates are in HL units. 1 unit == 1 inch. X is east (forward), Y is north (left), Z is up (up)
  23. // QAngle are pitch (around y), Yaw (around Z), Roll (around X)
  24. // AngularImpulse are exponetial maps (an axis in HL units scaled by a "twist" angle in degrees)
  25. // They can be transformed like normals/covectors and added linearly
  26. // mass is kg, volume is in^3, acceleration is in/s^2, velocity is in/s
  27. // density is kg/m^3 (water ~= 998 at room temperature)
  28. // preferably, these would be in kg/in^3, but the range of those numbers makes them not very human readable
  29. // having water be about 1000 is really convenient for data entry.
  30. // Since volume is in in^3 and density is in kg/m^3:
  31. // density = (mass / volume) * CUBIC_METERS_PER_CUBIC_INCH
  32. // Force is applied using impulses (kg*in/s)
  33. // Torque is applied using impulses (kg*degrees/s)
  34. // ------------------------------------------------------------------------------------
  35. #define METERS_PER_INCH (0.0254f)
  36. #define CUBIC_METERS_PER_CUBIC_INCH (METERS_PER_INCH*METERS_PER_INCH*METERS_PER_INCH)
  37. // 2.2 lbs / kg
  38. #define POUNDS_PER_KG (2.2f)
  39. #define KG_PER_POUND (1.0f/POUNDS_PER_KG)
  40. // convert from pounds to kg
  41. #define lbs2kg(x) ((x)*KG_PER_POUND)
  42. #define kg2lbs(x) ((x)*POUNDS_PER_KG)
  43. const float VPHYSICS_MIN_MASS = 0.1f;
  44. const float VPHYSICS_MAX_MASS = 5e4f;
  45. class IPhysicsObject;
  46. class IPhysicsEnvironment;
  47. class IPhysicsSurfaceProps;
  48. class IPhysicsConstraint;
  49. class IPhysicsConstraintGroup;
  50. class IPhysicsFluidController;
  51. class IPhysicsSpring;
  52. class IPhysicsVehicleController;
  53. class IConvexInfo;
  54. class IPhysicsObjectPairHash;
  55. class IPhysicsCollisionSet;
  56. class IPhysicsPlayerController;
  57. class IPhysicsFrictionSnapshot;
  58. struct Ray_t;
  59. struct constraint_ragdollparams_t;
  60. struct constraint_hingeparams_t;
  61. struct constraint_fixedparams_t;
  62. struct constraint_ballsocketparams_t;
  63. struct constraint_slidingparams_t;
  64. struct constraint_pulleyparams_t;
  65. struct constraint_lengthparams_t;
  66. struct constraint_groupparams_t;
  67. struct vehicleparams_t;
  68. struct matrix3x4_t;
  69. struct fluidparams_t;
  70. struct springparams_t;
  71. struct objectparams_t;
  72. struct debugcollide_t;
  73. class CGameTrace;
  74. typedef CGameTrace trace_t;
  75. struct physics_stats_t;
  76. struct physics_performanceparams_t;
  77. struct virtualmeshparams_t;
  78. //enum PhysInterfaceId_t;
  79. struct physsaveparams_t;
  80. struct physrestoreparams_t;
  81. struct physprerestoreparams_t;
  82. enum PhysInterfaceId_t
  83. {
  84. PIID_UNKNOWN,
  85. PIID_IPHYSICSOBJECT,
  86. PIID_IPHYSICSFLUIDCONTROLLER,
  87. PIID_IPHYSICSSPRING,
  88. PIID_IPHYSICSCONSTRAINTGROUP,
  89. PIID_IPHYSICSCONSTRAINT,
  90. PIID_IPHYSICSSHADOWCONTROLLER,
  91. PIID_IPHYSICSPLAYERCONTROLLER,
  92. PIID_IPHYSICSMOTIONCONTROLLER,
  93. PIID_IPHYSICSVEHICLECONTROLLER,
  94. PIID_IPHYSICSGAMETRACE,
  95. PIID_NUM_TYPES
  96. };
  97. class ISave;
  98. class IRestore;
  99. #define VPHYSICS_DEBUG_OVERLAY_INTERFACE_VERSION "VPhysicsDebugOverlay001"
  100. abstract_class IVPhysicsDebugOverlay
  101. {
  102. public:
  103. virtual void AddEntityTextOverlay(int ent_index, int line_offset, float duration, int r, int g, int b, int a, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  104. virtual void AddBoxOverlay(const Vector& origin, const Vector& mins, const Vector& max, QAngle const& orientation, int r, int g, int b, int a, float duration) = 0;
  105. virtual void AddTriangleOverlay(const Vector& p1, const Vector& p2, const Vector& p3, int r, int g, int b, int a, bool noDepthTest, float duration) = 0;
  106. virtual void AddLineOverlay(const Vector& origin, const Vector& dest, int r, int g, int b,bool noDepthTest, float duration) = 0;
  107. virtual void AddTextOverlay(const Vector& origin, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  108. virtual void AddTextOverlay(const Vector& origin, int line_offset, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  109. virtual void AddScreenTextOverlay(float flXPos, float flYPos,float flDuration, int r, int g, int b, int a, const char *text) = 0;
  110. virtual void AddSweptBoxOverlay(const Vector& start, const Vector& end, const Vector& mins, const Vector& max, const QAngle & angles, int r, int g, int b, int a, float flDuration) = 0;
  111. virtual void AddTextOverlayRGB(const Vector& origin, int line_offset, float duration, float r, float g, float b, float alpha, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  112. };
  113. #define VPHYSICS_INTERFACE_VERSION "VPhysics031"
  114. abstract_class IPhysics : public IAppSystem
  115. {
  116. public:
  117. virtual IPhysicsEnvironment *CreateEnvironment( void ) = 0;
  118. virtual void DestroyEnvironment( IPhysicsEnvironment * ) = 0;
  119. virtual IPhysicsEnvironment *GetActiveEnvironmentByIndex( int index ) = 0;
  120. // Creates a fast hash of pairs of objects
  121. // Useful for maintaining a table of object relationships like pairs that do not collide.
  122. virtual IPhysicsObjectPairHash *CreateObjectPairHash() = 0;
  123. virtual void DestroyObjectPairHash( IPhysicsObjectPairHash *pHash ) = 0;
  124. // holds a cache of these by id. So you can get by id to search for the previously created set
  125. // UNDONE: Sets are currently limited to 32 elements. More elements will return NULL in create.
  126. // NOTE: id is not allowed to be zero.
  127. virtual IPhysicsCollisionSet *FindOrCreateCollisionSet( unsigned int id, int maxElementCount ) = 0;
  128. virtual IPhysicsCollisionSet *FindCollisionSet( unsigned int id ) = 0;
  129. virtual void DestroyAllCollisionSets() = 0;
  130. };
  131. // CPhysConvex is a single convex solid
  132. class CPhysConvex;
  133. // CPhysPolysoup is an abstract triangle soup mesh
  134. class CPhysPolysoup;
  135. class ICollisionQuery;
  136. class IVPhysicsKeyParser;
  137. struct convertconvexparams_t;
  138. class CPackedPhysicsDescription;
  139. class CPolyhedron;
  140. // UNDONE: Find a better place for this? Should be in collisionutils, but it's needs VPHYSICS' solver.
  141. struct truncatedcone_t
  142. {
  143. Vector origin;
  144. Vector normal;
  145. float h; // height of the cone (hl units)
  146. float theta; // cone angle (degrees)
  147. };
  148. abstract_class IPhysicsCollision
  149. {
  150. public:
  151. virtual ~IPhysicsCollision( void ) {}
  152. // produce a convex element from verts (convex hull around verts)
  153. virtual CPhysConvex *ConvexFromVerts( Vector **pVerts, int vertCount ) = 0;
  154. // produce a convex element from planes (csg of planes)
  155. virtual CPhysConvex *ConvexFromPlanes( float *pPlanes, int planeCount, float mergeDistance ) = 0;
  156. // calculate volume of a convex element
  157. virtual float ConvexVolume( CPhysConvex *pConvex ) = 0;
  158. virtual float ConvexSurfaceArea( CPhysConvex *pConvex ) = 0;
  159. // store game-specific data in a convex solid
  160. virtual void SetConvexGameData( CPhysConvex *pConvex, unsigned int gameData ) = 0;
  161. // If not converted, free the convex elements with this call
  162. virtual void ConvexFree( CPhysConvex *pConvex ) = 0;
  163. virtual CPhysConvex *BBoxToConvex( const Vector &mins, const Vector &maxs ) = 0;
  164. // produce a convex element from a convex polyhedron
  165. virtual CPhysConvex *ConvexFromConvexPolyhedron( const CPolyhedron &ConvexPolyhedron ) = 0;
  166. // produce a set of convex triangles from a convex polygon, normal is assumed to be on the side with forward point ordering, which should be clockwise, output will need to be able to hold exactly (iPointCount-2) convexes
  167. virtual void ConvexesFromConvexPolygon( const Vector &vPolyNormal, const Vector *pPoints, int iPointCount, CPhysConvex **pOutput ) = 0;
  168. // concave objects
  169. // create a triangle soup
  170. virtual CPhysPolysoup *PolysoupCreate( void ) = 0;
  171. // destroy the container and memory
  172. virtual void PolysoupDestroy( CPhysPolysoup *pSoup ) = 0;
  173. // add a triangle to the soup
  174. virtual void PolysoupAddTriangle( CPhysPolysoup *pSoup, const Vector &a, const Vector &b, const Vector &c, int materialIndex7bits ) = 0;
  175. // convert the convex into a compiled collision model
  176. virtual CPhysCollide *ConvertPolysoupToCollide( CPhysPolysoup *pSoup, bool useMOPP ) = 0;
  177. // Convert an array of convex elements to a compiled collision model (this deletes the convex elements)
  178. virtual CPhysCollide *ConvertConvexToCollide( CPhysConvex **pConvex, int convexCount ) = 0;
  179. virtual CPhysCollide *ConvertConvexToCollideParams( CPhysConvex **pConvex, int convexCount, const convertconvexparams_t &convertParams ) = 0;
  180. // Free a collide that was created with ConvertConvexToCollide()
  181. virtual void DestroyCollide( CPhysCollide *pCollide ) = 0;
  182. // Get the memory size in bytes of the collision model for serialization
  183. virtual int CollideSize( CPhysCollide *pCollide ) = 0;
  184. // serialize the collide to a block of memory
  185. virtual int CollideWrite( char *pDest, CPhysCollide *pCollide, bool bSwap = false ) = 0;
  186. // unserialize the collide from a block of memory
  187. virtual CPhysCollide *UnserializeCollide( char *pBuffer, int size, int index ) = 0;
  188. // compute the volume of a collide
  189. virtual float CollideVolume( CPhysCollide *pCollide ) = 0;
  190. // compute surface area for tools
  191. virtual float CollideSurfaceArea( CPhysCollide *pCollide ) = 0;
  192. // Get the support map for a collide in the given direction
  193. virtual Vector CollideGetExtent( const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, const Vector &direction ) = 0;
  194. // Get an AABB for an oriented collision model
  195. virtual void CollideGetAABB( Vector *pMins, Vector *pMaxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles ) = 0;
  196. virtual void CollideGetMassCenter( CPhysCollide *pCollide, Vector *pOutMassCenter ) = 0;
  197. virtual void CollideSetMassCenter( CPhysCollide *pCollide, const Vector &massCenter ) = 0;
  198. // get the approximate cross-sectional area projected orthographically on the bbox of the collide
  199. // NOTE: These are fractional areas - unitless. Basically this is the fraction of the OBB on each axis that
  200. // would be visible if the object were rendered orthographically.
  201. // NOTE: This has been precomputed when the collide was built or this function will return 1,1,1
  202. virtual Vector CollideGetOrthographicAreas( const CPhysCollide *pCollide ) = 0;
  203. virtual void CollideSetOrthographicAreas( CPhysCollide *pCollide, const Vector &areas ) = 0;
  204. // query the vcollide index in the physics model for the instance
  205. virtual int CollideIndex( const CPhysCollide *pCollide ) = 0;
  206. // Convert a bbox to a collide
  207. virtual CPhysCollide *BBoxToCollide( const Vector &mins, const Vector &maxs ) = 0;
  208. virtual int GetConvexesUsedInCollideable( const CPhysCollide *pCollideable, CPhysConvex **pOutputArray, int iOutputArrayLimit ) = 0;
  209. // Trace an AABB against a collide
  210. virtual void TraceBox( const Vector &start, const Vector &end, const Vector &mins, const Vector &maxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  211. virtual void TraceBox( const Ray_t &ray, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  212. virtual void TraceBox( const Ray_t &ray, unsigned int contentsMask, IConvexInfo *pConvexInfo, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  213. // Trace one collide against another
  214. virtual void TraceCollide( const Vector &start, const Vector &end, const CPhysCollide *pSweepCollide, const QAngle &sweepAngles, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  215. // relatively slow test for box vs. truncated cone
  216. virtual bool IsBoxIntersectingCone( const Vector &boxAbsMins, const Vector &boxAbsMaxs, const truncatedcone_t &cone ) = 0;
  217. // loads a set of solids into a vcollide_t
  218. virtual void VCollideLoad( vcollide_t *pOutput, int solidCount, const char *pBuffer, int size, bool swap = false ) = 0;
  219. // destroyts the set of solids created by VCollideLoad
  220. virtual void VCollideUnload( vcollide_t *pVCollide ) = 0;
  221. // begins parsing a vcollide. NOTE: This keeps pointers to the text
  222. // If you free the text and call members of IVPhysicsKeyParser, it will crash
  223. virtual IVPhysicsKeyParser *VPhysicsKeyParserCreate( const char *pKeyData ) = 0;
  224. virtual IVPhysicsKeyParser *VPhysicsKeyParserCreate( vcollide_t *pVCollide ) = 0;
  225. // Free the parser created by VPhysicsKeyParserCreate
  226. virtual void VPhysicsKeyParserDestroy( IVPhysicsKeyParser *pParser ) = 0;
  227. // creates a list of verts from a collision mesh
  228. virtual int CreateDebugMesh( CPhysCollide const *pCollisionModel, Vector **outVerts ) = 0;
  229. // destroy the list of verts created by CreateDebugMesh
  230. virtual void DestroyDebugMesh( int vertCount, Vector *outVerts ) = 0;
  231. // create a queryable version of the collision model
  232. virtual ICollisionQuery *CreateQueryModel( CPhysCollide *pCollide ) = 0;
  233. // destroy the queryable version
  234. virtual void DestroyQueryModel( ICollisionQuery *pQuery ) = 0;
  235. virtual IPhysicsCollision *ThreadContextCreate( void ) = 0;
  236. virtual void ThreadContextDestroy( IPhysicsCollision *pThreadContex ) = 0;
  237. virtual CPhysCollide *CreateVirtualMesh( const virtualmeshparams_t &params ) = 0;
  238. virtual bool SupportsVirtualMesh() = 0;
  239. virtual bool GetBBoxCacheSize( int *pCachedSize, int *pCachedCount ) = 0;
  240. // extracts a polyhedron that defines a CPhysConvex's shape
  241. virtual CPolyhedron *PolyhedronFromConvex( CPhysConvex * const pConvex, bool bUseTempPolyhedron ) = 0;
  242. // dumps info about the collide to Msg()
  243. virtual void OutputDebugInfo( const CPhysCollide *pCollide ) = 0;
  244. virtual unsigned int ReadStat( int statID ) = 0;
  245. // Get an AABB for an oriented collision model
  246. virtual float CollideGetRadius( const CPhysCollide *pCollide ) = 0;
  247. virtual void *VCollideAllocUserData( vcollide_t *pVCollide, size_t userDataSize ) = 0;
  248. virtual void VCollideFreeUserData( vcollide_t *pVCollide ) = 0;
  249. virtual void VCollideCheck( vcollide_t *pVCollide, const char *pName ) = 0;
  250. virtual bool TraceBoxAA( const Ray_t &ray, const CPhysCollide *pCollide, trace_t *ptr ) = 0;
  251. };
  252. // this can be used to post-process a collision model
  253. abstract_class ICollisionQuery
  254. {
  255. public:
  256. virtual ~ICollisionQuery() {}
  257. // number of convex pieces in the whole solid
  258. virtual int ConvexCount( void ) = 0;
  259. // triangle count for this convex piece
  260. virtual int TriangleCount( int convexIndex ) = 0;
  261. // get the stored game data
  262. virtual unsigned int GetGameData( int convexIndex ) = 0;
  263. // Gets the triangle's verts to an array
  264. virtual void GetTriangleVerts( int convexIndex, int triangleIndex, Vector *verts ) = 0;
  265. // UNDONE: This doesn't work!!!
  266. virtual void SetTriangleVerts( int convexIndex, int triangleIndex, const Vector *verts ) = 0;
  267. // returns the 7-bit material index
  268. virtual int GetTriangleMaterialIndex( int convexIndex, int triangleIndex ) = 0;
  269. // sets a 7-bit material index for this triangle
  270. virtual void SetTriangleMaterialIndex( int convexIndex, int triangleIndex, int index7bits ) = 0;
  271. };
  272. //-----------------------------------------------------------------------------
  273. // Purpose: Ray traces from game engine.
  274. //-----------------------------------------------------------------------------
  275. abstract_class IPhysicsGameTrace
  276. {
  277. public:
  278. virtual void VehicleTraceRay( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0;
  279. virtual void VehicleTraceRayWithWater( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0;
  280. virtual bool VehiclePointInWater( const Vector &vecPoint ) = 0;
  281. };
  282. // The caller should implement this to return contents masks per convex on a collide
  283. abstract_class IConvexInfo
  284. {
  285. public:
  286. virtual unsigned int GetContents( int convexGameData ) = 0;
  287. };
  288. class CPhysicsEventHandler;
  289. abstract_class IPhysicsCollisionData
  290. {
  291. public:
  292. virtual void GetSurfaceNormal( Vector &out ) = 0; // normal points toward second object (object index 1)
  293. virtual void GetContactPoint( Vector &out ) = 0; // contact point of collision (in world space)
  294. virtual void GetContactSpeed( Vector &out ) = 0; // speed of surface 1 relative to surface 0 (in world space)
  295. };
  296. struct vcollisionevent_t
  297. {
  298. IPhysicsObject *pObjects[2];
  299. int surfaceProps[2];
  300. bool isCollision;
  301. bool isShadowCollision;
  302. float deltaCollisionTime;
  303. float collisionSpeed; // only valid at postCollision
  304. IPhysicsCollisionData *pInternalData; // may change pre/post collision
  305. };
  306. abstract_class IPhysicsCollisionEvent
  307. {
  308. public:
  309. // returns the two objects that collided, time between last collision of these objects
  310. // and an opaque data block of collision information
  311. // NOTE: PreCollision/PostCollision ALWAYS come in matched pairs!!!
  312. virtual void PreCollision( vcollisionevent_t *pEvent ) = 0;
  313. virtual void PostCollision( vcollisionevent_t *pEvent ) = 0;
  314. // This is a scrape event. The object has scraped across another object consuming the indicated energy
  315. virtual void Friction( IPhysicsObject *pObject, float energy, int surfaceProps, int surfacePropsHit, IPhysicsCollisionData *pData ) = 0;
  316. virtual void StartTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0;
  317. virtual void EndTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0;
  318. virtual void FluidStartTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0;
  319. virtual void FluidEndTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0;
  320. virtual void PostSimulationFrame() = 0;
  321. virtual void ObjectEnterTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {}
  322. virtual void ObjectLeaveTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {}
  323. };
  324. abstract_class IPhysicsObjectEvent
  325. {
  326. public:
  327. // these can be used to optimize out queries on sleeping objects
  328. // Called when an object is woken after sleeping
  329. virtual void ObjectWake( IPhysicsObject *pObject ) = 0;
  330. // called when an object goes to sleep (no longer simulating)
  331. virtual void ObjectSleep( IPhysicsObject *pObject ) = 0;
  332. };
  333. abstract_class IPhysicsConstraintEvent
  334. {
  335. public:
  336. // the constraint is now inactive, the game code is required to delete it or re-activate it.
  337. virtual void ConstraintBroken( IPhysicsConstraint * ) = 0;
  338. };
  339. struct hlshadowcontrol_params_t
  340. {
  341. Vector targetPosition;
  342. QAngle targetRotation;
  343. float maxAngular;
  344. float maxDampAngular;
  345. float maxSpeed;
  346. float maxDampSpeed;
  347. float dampFactor;
  348. float teleportDistance;
  349. };
  350. // UNDONE: At some point allow this to be parameterized using hlshadowcontrol_params_t.
  351. // All of the infrastructure is in place to do that.
  352. abstract_class IPhysicsShadowController
  353. {
  354. public:
  355. virtual ~IPhysicsShadowController( void ) {}
  356. virtual void Update( const Vector &position, const QAngle &angles, float timeOffset ) = 0;
  357. virtual void MaxSpeed( float maxSpeed, float maxAngularSpeed ) = 0;
  358. virtual void StepUp( float height ) = 0;
  359. // If the teleport distance is non-zero, the object will be teleported to
  360. // the target location when the error exceeds this quantity.
  361. virtual void SetTeleportDistance( float teleportDistance ) = 0;
  362. virtual bool AllowsTranslation() = 0;
  363. virtual bool AllowsRotation() = 0;
  364. // There are two classes of shadow objects:
  365. // 1) Game physics controlled, shadow follows game physics (this is the default)
  366. // 2) Physically controlled - shadow position is a target, but the game hasn't guaranteed that the space can be occupied by this object
  367. virtual void SetPhysicallyControlled( bool isPhysicallyControlled ) = 0;
  368. virtual bool IsPhysicallyControlled() = 0;
  369. virtual void GetLastImpulse( Vector *pOut ) = 0;
  370. virtual void UseShadowMaterial( bool bUseShadowMaterial ) = 0;
  371. virtual void ObjectMaterialChanged( int materialIndex ) = 0;
  372. //Basically get the last inputs to IPhysicsShadowController::Update(), returns last input to timeOffset in Update()
  373. virtual float GetTargetPosition( Vector *pPositionOut, QAngle *pAnglesOut ) = 0;
  374. virtual float GetTeleportDistance( void ) = 0;
  375. virtual void GetMaxSpeed( float *pMaxSpeedOut, float *pMaxAngularSpeedOut ) = 0;
  376. };
  377. class CPhysicsSimObject;
  378. class IPhysicsMotionController;
  379. // Callback for simulation
  380. class IMotionEvent
  381. {
  382. public:
  383. // These constants instruct the simulator as to how to apply the values copied to linear & angular
  384. // GLOBAL/LOCAL refer to the coordinate system of the values, whereas acceleration/force determine whether or not
  385. // mass is divided out (forces must be divided by mass to compute acceleration)
  386. enum simresult_e { SIM_NOTHING = 0, SIM_LOCAL_ACCELERATION, SIM_LOCAL_FORCE, SIM_GLOBAL_ACCELERATION, SIM_GLOBAL_FORCE };
  387. virtual simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ) = 0;
  388. };
  389. abstract_class IPhysicsMotionController
  390. {
  391. public:
  392. virtual ~IPhysicsMotionController( void ) {}
  393. virtual void SetEventHandler( IMotionEvent *handler ) = 0;
  394. virtual void AttachObject( IPhysicsObject *pObject, bool checkIfAlreadyAttached ) = 0;
  395. virtual void DetachObject( IPhysicsObject *pObject ) = 0;
  396. // returns the number of objects currently attached to the controller
  397. virtual int CountObjects( void ) = 0;
  398. // NOTE: pObjectList is an array with at least CountObjects() allocated
  399. virtual void GetObjects( IPhysicsObject **pObjectList ) = 0;
  400. // detaches all attached objects
  401. virtual void ClearObjects( void ) = 0;
  402. // wakes up all attached objects
  403. virtual void WakeObjects( void ) = 0;
  404. enum priority_t
  405. {
  406. LOW_PRIORITY = 0,
  407. MEDIUM_PRIORITY = 1,
  408. HIGH_PRIORITY = 2,
  409. };
  410. virtual void SetPriority( priority_t priority ) = 0;
  411. };
  412. // -------------------
  413. // Collision filter function. Return 0 if objects should not be tested for collisions, nonzero otherwise
  414. // Install with IPhysicsEnvironment::SetCollisionFilter()
  415. // -------------------
  416. abstract_class IPhysicsCollisionSolver
  417. {
  418. public:
  419. virtual int ShouldCollide( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1 ) = 0;
  420. virtual int ShouldSolvePenetration( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1, float dt ) = 0;
  421. // pObject has already done the max number of collisions this tick, should we freeze it to save CPU?
  422. virtual bool ShouldFreezeObject( IPhysicsObject *pObject ) = 0;
  423. // The system has already done too many collision checks, performance will suffer.
  424. // How many more should it do?
  425. virtual int AdditionalCollisionChecksThisTick( int currentChecksDone ) = 0;
  426. // This list of objects is in a connected contact graph that is too large to solve quickly
  427. // return true to freeze the system, false to solve it
  428. virtual bool ShouldFreezeContacts( IPhysicsObject **pObjectList, int objectCount ) = 0;
  429. };
  430. enum PhysicsTraceType_t
  431. {
  432. VPHYSICS_TRACE_EVERYTHING = 0,
  433. VPHYSICS_TRACE_STATIC_ONLY,
  434. VPHYSICS_TRACE_MOVING_ONLY,
  435. VPHYSICS_TRACE_TRIGGERS_ONLY,
  436. VPHYSICS_TRACE_STATIC_AND_MOVING,
  437. };
  438. abstract_class IPhysicsTraceFilter
  439. {
  440. public:
  441. virtual bool ShouldHitObject( IPhysicsObject *pObject, int contentsMask ) = 0;
  442. virtual PhysicsTraceType_t GetTraceType() const = 0;
  443. };
  444. abstract_class IPhysicsEnvironment
  445. {
  446. public:
  447. virtual ~IPhysicsEnvironment( void ) {}
  448. virtual void SetDebugOverlay( CreateInterfaceFn debugOverlayFactory ) = 0;
  449. virtual IVPhysicsDebugOverlay *GetDebugOverlay( void ) = 0;
  450. // gravity is a 3-vector in in/s^2
  451. virtual void SetGravity( const Vector &gravityVector ) = 0;
  452. virtual void GetGravity( Vector *pGravityVector ) const = 0;
  453. // air density is in kg / m^3 (water is 1000)
  454. // This controls drag, air that is more dense has more drag.
  455. virtual void SetAirDensity( float density ) = 0;
  456. virtual float GetAirDensity( void ) const = 0;
  457. // object creation
  458. // create a polygonal object. pCollisionModel was created by the physics builder DLL in a pre-process.
  459. virtual IPhysicsObject *CreatePolyObject( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0;
  460. // same as above, but this one cannot move or rotate (infinite mass/inertia)
  461. virtual IPhysicsObject *CreatePolyObjectStatic( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0;
  462. // Create a perfectly spherical object
  463. virtual IPhysicsObject *CreateSphereObject( float radius, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams, bool isStatic ) = 0;
  464. // destroy an object created with CreatePolyObject() or CreatePolyObjectStatic()
  465. virtual void DestroyObject( IPhysicsObject * ) = 0;
  466. // Create a polygonal fluid body out of the specified collision model
  467. // This object will affect any other objects that collide with the collision model
  468. virtual IPhysicsFluidController *CreateFluidController( IPhysicsObject *pFluidObject, fluidparams_t *pParams ) = 0;
  469. // Destroy an object created with CreateFluidController()
  470. virtual void DestroyFluidController( IPhysicsFluidController * ) = 0;
  471. // Create a simulated spring that connects 2 objects
  472. virtual IPhysicsSpring *CreateSpring( IPhysicsObject *pObjectStart, IPhysicsObject *pObjectEnd, springparams_t *pParams ) = 0;
  473. virtual void DestroySpring( IPhysicsSpring * ) = 0;
  474. // Create a constraint in the space of pReferenceObject which is attached by the constraint to pAttachedObject
  475. virtual IPhysicsConstraint *CreateRagdollConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ragdollparams_t &ragdoll ) = 0;
  476. virtual IPhysicsConstraint *CreateHingeConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_hingeparams_t &hinge ) = 0;
  477. virtual IPhysicsConstraint *CreateFixedConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_fixedparams_t &fixed ) = 0;
  478. virtual IPhysicsConstraint *CreateSlidingConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_slidingparams_t &sliding ) = 0;
  479. virtual IPhysicsConstraint *CreateBallsocketConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ballsocketparams_t &ballsocket ) = 0;
  480. virtual IPhysicsConstraint *CreatePulleyConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_pulleyparams_t &pulley ) = 0;
  481. virtual IPhysicsConstraint *CreateLengthConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_lengthparams_t &length ) = 0;
  482. virtual void DestroyConstraint( IPhysicsConstraint * ) = 0;
  483. virtual IPhysicsConstraintGroup *CreateConstraintGroup( const constraint_groupparams_t &groupParams ) = 0;
  484. virtual void DestroyConstraintGroup( IPhysicsConstraintGroup *pGroup ) = 0;
  485. virtual IPhysicsShadowController *CreateShadowController( IPhysicsObject *pObject, bool allowTranslation, bool allowRotation ) = 0;
  486. virtual void DestroyShadowController( IPhysicsShadowController * ) = 0;
  487. virtual IPhysicsPlayerController *CreatePlayerController( IPhysicsObject *pObject ) = 0;
  488. virtual void DestroyPlayerController( IPhysicsPlayerController * ) = 0;
  489. virtual IPhysicsMotionController *CreateMotionController( IMotionEvent *pHandler ) = 0;
  490. virtual void DestroyMotionController( IPhysicsMotionController *pController ) = 0;
  491. virtual IPhysicsVehicleController *CreateVehicleController( IPhysicsObject *pVehicleBodyObject, const vehicleparams_t &params, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace ) = 0;
  492. virtual void DestroyVehicleController( IPhysicsVehicleController * ) = 0;
  493. // install a function to filter collisions/penentration
  494. virtual void SetCollisionSolver( IPhysicsCollisionSolver *pSolver ) = 0;
  495. // run the simulator for deltaTime seconds
  496. virtual void Simulate( float deltaTime ) = 0;
  497. // true if currently running the simulator (i.e. in a callback during physenv->Simulate())
  498. virtual bool IsInSimulation() const = 0;
  499. // Manage the timestep (period) of the simulator. The main functions are all integrated with
  500. // this period as dt.
  501. virtual float GetSimulationTimestep() const = 0;
  502. virtual void SetSimulationTimestep( float timestep ) = 0;
  503. // returns the current simulation clock's value. This is an absolute time.
  504. virtual float GetSimulationTime() const = 0;
  505. virtual void ResetSimulationClock() = 0;
  506. // returns the current simulation clock's value at the next frame. This is an absolute time.
  507. virtual float GetNextFrameTime( void ) const = 0;
  508. // Collision callbacks (game code collision response)
  509. virtual void SetCollisionEventHandler( IPhysicsCollisionEvent *pCollisionEvents ) = 0;
  510. virtual void SetObjectEventHandler( IPhysicsObjectEvent *pObjectEvents ) = 0;
  511. virtual void SetConstraintEventHandler( IPhysicsConstraintEvent *pConstraintEvents ) = 0;
  512. virtual void SetQuickDelete( bool bQuick ) = 0;
  513. virtual int GetActiveObjectCount() const = 0;
  514. virtual void GetActiveObjects( IPhysicsObject **pOutputObjectList ) const = 0;
  515. virtual const IPhysicsObject **GetObjectList( int *pOutputObjectCount ) const = 0;
  516. virtual bool TransferObject( IPhysicsObject *pObject, IPhysicsEnvironment *pDestinationEnvironment ) = 0;
  517. virtual void CleanupDeleteList( void ) = 0;
  518. virtual void EnableDeleteQueue( bool enable ) = 0;
  519. // Save/Restore methods
  520. virtual bool Save( const physsaveparams_t &params ) = 0;
  521. virtual void PreRestore( const physprerestoreparams_t &params ) = 0;
  522. virtual bool Restore( const physrestoreparams_t &params ) = 0;
  523. virtual void PostRestore() = 0;
  524. // Debugging:
  525. virtual bool IsCollisionModelUsed( CPhysCollide *pCollide ) const = 0;
  526. // Physics world version of the enginetrace API:
  527. virtual void TraceRay( const Ray_t &ray, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
  528. virtual void SweepCollideable( const CPhysCollide *pCollide, const Vector &vecAbsStart, const Vector &vecAbsEnd,
  529. const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
  530. // performance tuning
  531. virtual void GetPerformanceSettings( physics_performanceparams_t *pOutput ) const = 0;
  532. virtual void SetPerformanceSettings( const physics_performanceparams_t *pSettings ) = 0;
  533. // perf/cost statistics
  534. virtual void ReadStats( physics_stats_t *pOutput ) = 0;
  535. virtual void ClearStats() = 0;
  536. virtual unsigned int GetObjectSerializeSize( IPhysicsObject *pObject ) const = 0;
  537. virtual void SerializeObjectToBuffer( IPhysicsObject *pObject, unsigned char *pBuffer, unsigned int bufferSize ) = 0;
  538. virtual IPhysicsObject *UnserializeObjectFromBuffer( void *pGameData, unsigned char *pBuffer, unsigned int bufferSize, bool enableCollisions ) = 0;
  539. virtual void EnableConstraintNotify( bool bEnable ) = 0;
  540. virtual void DebugCheckContacts(void) = 0;
  541. virtual void SetAlternateGravity( const Vector &gravityVector ) = 0;
  542. virtual void GetAlternateGravity( Vector *pGravityVector ) const = 0;
  543. virtual float GetDeltaFrameTime( int maxTicks ) const = 0;
  544. virtual void ForceObjectsToSleep( IPhysicsObject **pList, int listCount ) = 0;
  545. //Network prediction related functions
  546. virtual void SetPredicted( bool bPredicted ) = 0; //Interaction with this system and it's objects may not always march forward, sometimes it will get/set data in the past.
  547. virtual bool IsPredicted( void ) = 0;
  548. virtual void SetPredictionCommandNum( int iCommandNum ) = 0; //what command the client is working on right now
  549. virtual int GetPredictionCommandNum( void ) = 0;
  550. virtual void DoneReferencingPreviousCommands( int iCommandNum ) = 0; //won't need data from commands before this one any more
  551. virtual void RestorePredictedSimulation( void ) = 0; //called to restore results from a previous simulation with the same predicted timestamp set
  552. // destroy a CPhysCollide used in CreatePolyObject()/CreatePolyObjectStatic() when any owning IPhysicsObject is flushed from the queued deletion list.
  553. virtual void DestroyCollideOnDeadObjectFlush( CPhysCollide * ) = 0; //should only be used after calling DestroyObject() on all IPhysicsObjects created with it.
  554. };
  555. enum callbackflags
  556. {
  557. CALLBACK_GLOBAL_COLLISION = 0x0001,
  558. CALLBACK_GLOBAL_FRICTION = 0x0002,
  559. CALLBACK_GLOBAL_TOUCH = 0x0004,
  560. CALLBACK_GLOBAL_TOUCH_STATIC = 0x0008,
  561. CALLBACK_SHADOW_COLLISION = 0x0010,
  562. CALLBACK_GLOBAL_COLLIDE_STATIC = 0x0020,
  563. CALLBACK_IS_VEHICLE_WHEEL = 0x0040,
  564. CALLBACK_FLUID_TOUCH = 0x0100,
  565. CALLBACK_NEVER_DELETED = 0x0200, // HACKHACK: This means this object will never be deleted (set on the world)
  566. CALLBACK_MARKED_FOR_DELETE = 0x0400, // This allows vphysics to skip some work for this object since it will be
  567. // deleted later this frame. (Set automatically by destroy calls)
  568. CALLBACK_ENABLING_COLLISION = 0x0800, // This is active during the time an object is enabling collisions
  569. // allows us to skip collisions between "new" objects and objects marked for delete
  570. CALLBACK_DO_FLUID_SIMULATION = 0x1000, // remove this to opt out of fluid simulations
  571. CALLBACK_IS_PLAYER_CONTROLLER= 0x2000, // HACKHACK: Set this on players until player cotrollers are unified with shadow controllers
  572. CALLBACK_CHECK_COLLISION_DISABLE = 0x4000,
  573. CALLBACK_MARKED_FOR_TEST = 0x8000, // debug -- marked object is being debugged
  574. };
  575. enum collisionhints
  576. {
  577. COLLISION_HINT_DEBRIS = 0x0001,
  578. COLLISION_HINT_STATICSOLID = 0x0002,
  579. };
  580. class IPredictedPhysicsObject;
  581. abstract_class IPhysicsObject
  582. {
  583. public:
  584. virtual ~IPhysicsObject( void ) {}
  585. // returns true if this object is static/unmoveable
  586. // NOTE: returns false for objects that are not created static, but set EnableMotion(false);
  587. // Call IsMoveable() to find if the object is static OR has motion disabled
  588. virtual bool IsStatic() const = 0;
  589. virtual bool IsAsleep() const = 0;
  590. virtual bool IsTrigger() const = 0;
  591. virtual bool IsFluid() const = 0; // fluids are special triggers with fluid controllers attached, they return true to IsTrigger() as well!
  592. virtual bool IsHinged() const = 0;
  593. virtual bool IsCollisionEnabled() const = 0;
  594. virtual bool IsGravityEnabled() const = 0;
  595. virtual bool IsDragEnabled() const = 0;
  596. virtual bool IsMotionEnabled() const = 0;
  597. virtual bool IsMoveable() const = 0; // legacy: IsMotionEnabled() && !IsStatic()
  598. virtual bool IsAttachedToConstraint(bool bExternalOnly) const = 0;
  599. // Enable / disable collisions for this object
  600. virtual void EnableCollisions( bool enable ) = 0;
  601. // Enable / disable gravity for this object
  602. virtual void EnableGravity( bool enable ) = 0;
  603. // Enable / disable air friction / drag for this object
  604. virtual void EnableDrag( bool enable ) = 0;
  605. // Enable / disable motion (pin / unpin the object)
  606. virtual void EnableMotion( bool enable ) = 0;
  607. // Game can store data in each object (link back to game object)
  608. virtual void SetGameData( void *pGameData ) = 0;
  609. virtual void *GetGameData( void ) const = 0;
  610. // This flags word can be defined by the game as well
  611. virtual void SetGameFlags( unsigned short userFlags ) = 0;
  612. virtual unsigned short GetGameFlags( void ) const = 0;
  613. virtual void SetGameIndex( unsigned short gameIndex ) = 0;
  614. virtual unsigned short GetGameIndex( void ) const = 0;
  615. // setup various callbacks for this object
  616. virtual void SetCallbackFlags( unsigned short callbackflags ) = 0;
  617. // get the current callback state for this object
  618. virtual unsigned short GetCallbackFlags( void ) const = 0;
  619. // "wakes up" an object
  620. // NOTE: ALL OBJECTS ARE "Asleep" WHEN CREATED
  621. virtual void Wake( void ) = 0;
  622. virtual void Sleep( void ) = 0;
  623. // call this when the collision filter conditions change due to this
  624. // object's state (e.g. changing solid type or collision group)
  625. virtual void RecheckCollisionFilter() = 0;
  626. // NOTE: Contact points aren't updated when collision rules change, call this to force an update
  627. // UNDONE: Force this in RecheckCollisionFilter() ?
  628. virtual void RecheckContactPoints( bool bSearchForNewContacts = false ) = 0;
  629. // mass accessors
  630. virtual void SetMass( float mass ) = 0;
  631. virtual float GetMass( void ) const = 0;
  632. // get 1/mass (it's cached)
  633. virtual float GetInvMass( void ) const = 0;
  634. virtual Vector GetInertia( void ) const = 0;
  635. virtual Vector GetInvInertia( void ) const = 0;
  636. virtual void SetInertia( const Vector &inertia ) = 0;
  637. virtual void SetDamping( const float *speed, const float *rot ) = 0;
  638. virtual void GetDamping( float *speed, float *rot ) const = 0;
  639. // coefficients are optional, pass either
  640. virtual void SetDragCoefficient( float *pDrag, float *pAngularDrag ) = 0;
  641. virtual void SetBuoyancyRatio( float ratio ) = 0; // Override bouyancy
  642. // material index
  643. virtual int GetMaterialIndex() const = 0;
  644. virtual void SetMaterialIndex( int materialIndex ) = 0;
  645. // contents bits
  646. virtual unsigned int GetContents() const = 0;
  647. virtual void SetContents( unsigned int contents ) = 0;
  648. // Get the radius if this is a sphere object (zero if this is a polygonal mesh)
  649. virtual float GetSphereRadius() const = 0;
  650. // Set the radius on a sphere. May need to force recalculation of contact points
  651. virtual void SetSphereRadius(float radius) = 0;
  652. virtual float GetEnergy() const = 0;
  653. virtual Vector GetMassCenterLocalSpace() const = 0;
  654. // NOTE: This will teleport the object
  655. virtual void SetPosition( const Vector &worldPosition, const QAngle &angles, bool isTeleport ) = 0;
  656. virtual void SetPositionMatrix( const matrix3x4_t&matrix, bool isTeleport ) = 0;
  657. virtual void GetPosition( Vector *worldPosition, QAngle *angles ) const = 0;
  658. virtual void GetPositionMatrix( matrix3x4_t *positionMatrix ) const = 0;
  659. // force the velocity to a new value
  660. // NOTE: velocity is in worldspace, angularVelocity is relative to the object's
  661. // local axes (just like pev->velocity, pev->avelocity)
  662. virtual void SetVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
  663. // like the above, but force the change into the simulator immediately
  664. virtual void SetVelocityInstantaneous( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
  665. // NOTE: velocity is in worldspace, angularVelocity is relative to the object's
  666. // local axes (just like pev->velocity, pev->avelocity)
  667. virtual void GetVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0;
  668. // NOTE: These are velocities, not forces. i.e. They will have the same effect regardless of
  669. // the object's mass or inertia
  670. virtual void AddVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
  671. // gets a velocity in the object's local frame of reference at a specific point
  672. virtual void GetVelocityAtPoint( const Vector &worldPosition, Vector *pVelocity ) const = 0;
  673. // gets the velocity actually moved by the object in the last simulation update
  674. virtual void GetImplicitVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0;
  675. // NOTE: These are here for convenience, but you can do them yourself by using the matrix
  676. // returned from GetPositionMatrix()
  677. // convenient coordinate system transformations (params - dest, src)
  678. virtual void LocalToWorld( Vector *worldPosition, const Vector &localPosition ) const = 0;
  679. virtual void WorldToLocal( Vector *localPosition, const Vector &worldPosition ) const = 0;
  680. // transforms a vector (no translation) from object-local to world space
  681. virtual void LocalToWorldVector( Vector *worldVector, const Vector &localVector ) const = 0;
  682. // transforms a vector (no translation) from world to object-local space
  683. virtual void WorldToLocalVector( Vector *localVector, const Vector &worldVector ) const = 0;
  684. // push on an object
  685. // force vector is direction & magnitude of impulse kg in / s
  686. virtual void ApplyForceCenter( const Vector &forceVector ) = 0;
  687. virtual void ApplyForceOffset( const Vector &forceVector, const Vector &worldPosition ) = 0;
  688. // apply torque impulse. This will change the angular velocity on the object.
  689. // HL Axes, kg degrees / s
  690. virtual void ApplyTorqueCenter( const AngularImpulse &torque ) = 0;
  691. // Calculates the force/torque on the center of mass for an offset force impulse (pass output to ApplyForceCenter / ApplyTorqueCenter)
  692. virtual void CalculateForceOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerForce, AngularImpulse *centerTorque ) const = 0;
  693. // Calculates the linear/angular velocities on the center of mass for an offset force impulse (pass output to AddVelocity)
  694. virtual void CalculateVelocityOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerVelocity, AngularImpulse *centerAngularVelocity ) const = 0;
  695. // calculate drag scale
  696. virtual float CalculateLinearDrag( const Vector &unitDirection ) const = 0;
  697. virtual float CalculateAngularDrag( const Vector &objectSpaceRotationAxis ) const = 0;
  698. // returns true if the object is in contact with another object
  699. // if true, puts a point on the contact surface in contactPoint, and
  700. // a pointer to the object in contactObject
  701. // NOTE: You can pass NULL for either to avoid computations
  702. // BUGBUG: Use CreateFrictionSnapshot instead of this - this is a simple hack
  703. virtual bool GetContactPoint( Vector *contactPoint, IPhysicsObject **contactObject ) const = 0;
  704. // refactor this a bit - move some of this to IPhysicsShadowController
  705. virtual void SetShadow( float maxSpeed, float maxAngularSpeed, bool allowPhysicsMovement, bool allowPhysicsRotation ) = 0;
  706. virtual void UpdateShadow( const Vector &targetPosition, const QAngle &targetAngles, bool tempDisableGravity, float timeOffset ) = 0;
  707. // returns number of ticks since last Update() call
  708. virtual int GetShadowPosition( Vector *position, QAngle *angles ) const = 0;
  709. virtual IPhysicsShadowController *GetShadowController( void ) const = 0;
  710. virtual void RemoveShadowController() = 0;
  711. // applies the math of the shadow controller to this object.
  712. // for use in your own controllers
  713. // returns the new value of secondsToArrival with dt time elapsed
  714. virtual float ComputeShadowControl( const hlshadowcontrol_params_t &params, float secondsToArrival, float dt ) = 0;
  715. virtual const CPhysCollide *GetCollide( void ) const = 0;
  716. virtual const char *GetName() const = 0;
  717. virtual void BecomeTrigger() = 0;
  718. virtual void RemoveTrigger() = 0;
  719. // sets the object to be hinged. Fixed it place, but able to rotate around one axis.
  720. virtual void BecomeHinged( int localAxis ) = 0;
  721. // resets the object to original state
  722. virtual void RemoveHinged() = 0;
  723. // used to iterate the contact points of an object
  724. virtual IPhysicsFrictionSnapshot *CreateFrictionSnapshot() = 0;
  725. virtual void DestroyFrictionSnapshot( IPhysicsFrictionSnapshot *pSnapshot ) = 0;
  726. // dumps info about the object to Msg()
  727. virtual void OutputDebugInfo() const = 0;
  728. #if OBJECT_WELDING
  729. virtual void WeldToObject( IPhysicsObject *pParent ) = 0;
  730. virtual void RemoveWeld( IPhysicsObject *pOther ) = 0;
  731. virtual void RemoveAllWelds( void ) = 0;
  732. #endif
  733. // EnableGravity still determines whether to apply gravity
  734. // This flag determines which gravity constant to use for an alternate gravity effect
  735. virtual void SetUseAlternateGravity( bool bSet ) = 0;
  736. virtual void SetCollisionHints( uint32 collisionHints ) = 0;
  737. virtual uint32 GetCollisionHints() const = 0;
  738. inline bool IsPredicted( void ) const { return GetPredictedInterface() != NULL; } //true if class has an IPredictedPhysicsObject interface
  739. virtual IPredictedPhysicsObject *GetPredictedInterface( void ) const = 0;
  740. virtual void SyncWith( IPhysicsObject *pOther ) = 0;
  741. };
  742. abstract_class IPredictedPhysicsObject : public IPhysicsObject
  743. {
  744. public:
  745. virtual ~IPredictedPhysicsObject( void ) {}
  746. virtual void SetErrorDelta_Position( const Vector &vPosition ) = 0;
  747. virtual void SetErrorDelta_Velocity( const Vector &vVelocity ) = 0;
  748. };
  749. abstract_class IPhysicsSpring
  750. {
  751. public:
  752. virtual ~IPhysicsSpring( void ) {}
  753. virtual void GetEndpoints( Vector *worldPositionStart, Vector *worldPositionEnd ) = 0;
  754. virtual void SetSpringConstant( float flSpringContant) = 0;
  755. virtual void SetSpringDamping( float flSpringDamping) = 0;
  756. virtual void SetSpringLength( float flSpringLenght) = 0;
  757. // Get the starting object
  758. virtual IPhysicsObject *GetStartObject( void ) = 0;
  759. // Get the end object
  760. virtual IPhysicsObject *GetEndObject( void ) = 0;
  761. };
  762. //-----------------------------------------------------------------------------
  763. // Purpose: These properties are defined per-material. This is accessible at
  764. // each triangle in a collision mesh
  765. //-----------------------------------------------------------------------------
  766. struct surfacephysicsparams_t
  767. {
  768. // vphysics physical properties
  769. float friction;
  770. float elasticity; // collision elasticity - used to compute coefficient of restitution
  771. float density; // physical density (in kg / m^3)
  772. float thickness; // material thickness if not solid (sheet materials) in inches
  773. float dampening;
  774. };
  775. struct surfaceaudioparams_t
  776. {
  777. // sounds / audio data
  778. float reflectivity; // like elasticity, but how much sound should be reflected by this surface
  779. float hardnessFactor; // like elasticity, but only affects impact sound choices
  780. float roughnessFactor; // like friction, but only affects scrape sound choices
  781. // audio thresholds
  782. float roughThreshold; // surface roughness > this causes "rough" scrapes, < this causes "smooth" scrapes
  783. float hardThreshold; // surface hardness > this causes "hard" impacts, < this causes "soft" impacts
  784. float hardVelocityThreshold; // collision velocity > this causes "hard" impacts, < this causes "soft" impacts
  785. // NOTE: Hard impacts must meet both hardnessFactor AND velocity thresholds
  786. };
  787. struct surfacesoundnames_t
  788. {
  789. unsigned short walkStepLeft;
  790. unsigned short walkStepRight;
  791. unsigned short runStepLeft;
  792. unsigned short runStepRight;
  793. unsigned short impactSoft;
  794. unsigned short impactHard;
  795. unsigned short scrapeSmooth;
  796. unsigned short scrapeRough;
  797. unsigned short bulletImpact;
  798. unsigned short rolling;
  799. unsigned short breakSound;
  800. unsigned short strainSound;
  801. };
  802. struct surfacesoundhandles_t
  803. {
  804. HSOUNDSCRIPTHASH walkStepLeft;
  805. HSOUNDSCRIPTHASH walkStepRight;
  806. HSOUNDSCRIPTHASH runStepLeft;
  807. HSOUNDSCRIPTHASH runStepRight;
  808. HSOUNDSCRIPTHASH impactSoft;
  809. HSOUNDSCRIPTHASH impactHard;
  810. HSOUNDSCRIPTHASH scrapeSmooth;
  811. HSOUNDSCRIPTHASH scrapeRough;
  812. HSOUNDSCRIPTHASH bulletImpact;
  813. HSOUNDSCRIPTHASH rolling;
  814. HSOUNDSCRIPTHASH breakSound;
  815. HSOUNDSCRIPTHASH strainSound;
  816. };
  817. struct surfacegameprops_t
  818. {
  819. // game movement data
  820. float maxSpeedFactor; // Modulates player max speed when walking on this surface
  821. float jumpFactor; // Indicates how much higher the player should jump when on the surface
  822. // Game-specific data
  823. float penetrationModifier;
  824. float damageModifier;
  825. unsigned short material;
  826. // Indicates whether or not the player is on a ladder.
  827. unsigned char climbable;
  828. unsigned char pad;
  829. };
  830. //-----------------------------------------------------------------------------
  831. // Purpose: Each different material has an entry like this
  832. //-----------------------------------------------------------------------------
  833. struct surfacedata_t
  834. {
  835. surfacephysicsparams_t physics; // physics parameters
  836. surfaceaudioparams_t audio; // audio parameters
  837. surfacesoundnames_t sounds; // names of linked sounds
  838. surfacegameprops_t game; // Game data / properties
  839. surfacesoundhandles_t soundhandles;
  840. };
  841. class ISaveRestoreOps;
  842. #define VPHYSICS_SURFACEPROPS_INTERFACE_VERSION "VPhysicsSurfaceProps001"
  843. abstract_class IPhysicsSurfaceProps
  844. {
  845. public:
  846. virtual ~IPhysicsSurfaceProps( void ) {}
  847. // parses a text file containing surface prop keys
  848. virtual int ParseSurfaceData( const char *pFilename, const char *pTextfile ) = 0;
  849. // current number of entries in the database
  850. virtual int SurfacePropCount( void ) const = 0;
  851. virtual int GetSurfaceIndex( const char *pSurfacePropName ) const = 0;
  852. virtual void GetPhysicsProperties( int surfaceDataIndex, float *density, float *thickness, float *friction, float *elasticity ) const = 0;
  853. virtual surfacedata_t *GetSurfaceData( int surfaceDataIndex ) = 0;
  854. virtual const char *GetString( unsigned short stringTableIndex ) const = 0;
  855. virtual const char *GetPropName( int surfaceDataIndex ) const = 0;
  856. // sets the global index table for world materials
  857. // UNDONE: Make this per-CPhysCollide
  858. virtual void SetWorldMaterialIndexTable( int *pMapArray, int mapSize ) = 0;
  859. // NOTE: Same as GetPhysicsProperties, but maybe more convenient
  860. virtual void GetPhysicsParameters( int surfaceDataIndex, surfacephysicsparams_t *pParamsOut ) const = 0;
  861. virtual ISaveRestoreOps* GetMaterialIndexDataOps() const = 0;
  862. };
  863. abstract_class IPhysicsFluidController
  864. {
  865. public:
  866. virtual ~IPhysicsFluidController( void ) {}
  867. virtual void SetGameData( void *pGameData ) = 0;
  868. virtual void *GetGameData( void ) const = 0;
  869. virtual void GetSurfacePlane( Vector *pNormal, float *pDist ) const = 0;
  870. virtual float GetDensity() const = 0;
  871. virtual void WakeAllSleepingObjects() = 0;
  872. virtual int GetContents() const = 0;
  873. };
  874. //-----------------------------------------------------------------------------
  875. // Purpose: parameter block for creating fluid dynamic motion
  876. // UNDONE: Expose additional fluid model paramters?
  877. //-----------------------------------------------------------------------------
  878. struct fluidparams_t
  879. {
  880. Vector4D surfacePlane; // x,y,z normal, dist (plane constant) fluid surface
  881. Vector currentVelocity; // velocity of the current in inches/second
  882. float damping; // damping factor for buoyancy (tweak)
  883. float torqueFactor;
  884. float viscosityFactor;
  885. void *pGameData;
  886. bool useAerodynamics;// true if this controller should calculate surface pressure
  887. int contents;
  888. fluidparams_t() {}
  889. fluidparams_t( fluidparams_t const& src )
  890. {
  891. Vector4DCopy( src.surfacePlane, surfacePlane );
  892. VectorCopy( src.currentVelocity, currentVelocity );
  893. damping = src.damping;
  894. torqueFactor = src.torqueFactor;
  895. viscosityFactor = src.viscosityFactor;
  896. contents = src.contents;
  897. }
  898. };
  899. //-----------------------------------------------------------------------------
  900. // Purpose: parameter block for creating linear springs
  901. // UNDONE: Expose additional spring model paramters?
  902. //-----------------------------------------------------------------------------
  903. struct springparams_t
  904. {
  905. springparams_t()
  906. {
  907. memset( this, 0, sizeof(*this) );
  908. }
  909. float constant; // spring constant
  910. float naturalLength;// relaxed length
  911. float damping; // damping factor
  912. float relativeDamping; // relative damping (damping proportional to the change in the relative position of the objects)
  913. Vector startPosition;
  914. Vector endPosition;
  915. bool useLocalPositions; // start & end Position are in local space to start and end objects if this is true
  916. bool onlyStretch; // only apply forces when the length is greater than the natural length
  917. };
  918. //-----------------------------------------------------------------------------
  919. // Purpose: parameter block for creating polygonal objects
  920. //-----------------------------------------------------------------------------
  921. struct objectparams_t
  922. {
  923. Vector *massCenterOverride;
  924. float mass;
  925. float inertia;
  926. float damping;
  927. float rotdamping;
  928. float rotInertiaLimit;
  929. const char *pName; // used only for debugging
  930. void *pGameData;
  931. float volume;
  932. float dragCoefficient;
  933. bool enableCollisions;
  934. };
  935. struct convertconvexparams_t
  936. {
  937. bool buildOuterConvexHull;
  938. bool buildDragAxisAreas;
  939. bool buildOptimizedTraceTables;
  940. bool checkOptimalTracing;
  941. bool bUseFastApproximateInertiaTensor;
  942. bool bBuildAABBTree;
  943. float dragAreaEpsilon;
  944. CPhysConvex *pForcedOuterHull;
  945. void Defaults()
  946. {
  947. dragAreaEpsilon = 0.25f; // 0.5in x 0.5in square
  948. buildOuterConvexHull = false;
  949. buildDragAxisAreas = false;
  950. buildOptimizedTraceTables = false;
  951. checkOptimalTracing = false;
  952. bUseFastApproximateInertiaTensor = false;
  953. bBuildAABBTree = false;
  954. pForcedOuterHull = NULL;
  955. }
  956. };
  957. //-----------------------------------------------------------------------------
  958. // Physics interface IDs
  959. //
  960. // Note that right now the order of the enum also defines the order of save/load
  961. //-----------------------------------------------------------------------------
  962. // Purpose: parameter blocks for save and load operations
  963. //-----------------------------------------------------------------------------
  964. struct physsaveparams_t
  965. {
  966. ISave *pSave;
  967. void *pObject;
  968. PhysInterfaceId_t type;
  969. };
  970. struct physrestoreparams_t
  971. {
  972. IRestore *pRestore;
  973. void **ppObject;
  974. PhysInterfaceId_t type;
  975. void *pGameData;
  976. const char *pName; // used only for debugging
  977. const CPhysCollide *pCollisionModel;
  978. IPhysicsEnvironment *pEnvironment;
  979. IPhysicsGameTrace *pGameTrace;
  980. };
  981. struct physrecreateparams_t
  982. {
  983. void *pOldObject;
  984. void *pNewObject;
  985. };
  986. struct physprerestoreparams_t
  987. {
  988. int recreatedObjectCount;
  989. physrecreateparams_t recreatedObjectList[1];
  990. };
  991. //-------------------------------------
  992. #define DEFINE_PIID( type, enumval ) \
  993. template <> inline PhysInterfaceId_t GetPhysIID<type>( type ** ) { return enumval; }
  994. template <class PHYSPTR> inline PhysInterfaceId_t GetPhysIID(PHYSPTR **); // will get link error if no match
  995. DEFINE_PIID( IPhysicsObject, PIID_IPHYSICSOBJECT );
  996. DEFINE_PIID( IPhysicsFluidController, PIID_IPHYSICSFLUIDCONTROLLER );
  997. DEFINE_PIID( IPhysicsSpring, PIID_IPHYSICSSPRING );
  998. DEFINE_PIID( IPhysicsConstraintGroup, PIID_IPHYSICSCONSTRAINTGROUP );
  999. DEFINE_PIID( IPhysicsConstraint, PIID_IPHYSICSCONSTRAINT );
  1000. DEFINE_PIID( IPhysicsShadowController, PIID_IPHYSICSSHADOWCONTROLLER );
  1001. DEFINE_PIID( IPhysicsPlayerController, PIID_IPHYSICSPLAYERCONTROLLER );
  1002. DEFINE_PIID( IPhysicsMotionController, PIID_IPHYSICSMOTIONCONTROLLER );
  1003. DEFINE_PIID( IPhysicsVehicleController, PIID_IPHYSICSVEHICLECONTROLLER );
  1004. DEFINE_PIID( IPhysicsGameTrace, PIID_IPHYSICSGAMETRACE );
  1005. //-----------------------------------------------------------------------------
  1006. #endif // VPHYSICS_INTERFACE_H