From b079e5d43f6c3e84d52a7bde8af47df0cd600276 Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Sat, 24 Oct 2026 16:13:20 -0700 Subject: [PATCH] better joint drawing --- include/box3d/types.h | 261 ++++++++++++++++++++++++------------------ src/mover_joint.c | 94 +++++++-------- src/pogo_joint.c | 6 +- 3 files changed, 198 insertions(+), 163 deletions(-) diff --git a/include/box3d/types.h b/include/box3d/types.h index 8be3369..20fd0ce 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -15,50 +15,57 @@ #define B3_DEFAULT_MASK_BITS UINT64_MAX /// Task interface -/// This is the prototype for a Box3D task. Your task system is expected to run this callback on a worker thread, -/// exactly once per enqueue, passing back the same taskContext pointer supplied to b3EnqueueTaskCallback. +/// This is the prototype for a Box3D task. Your task system is expected to run this callback on a +/// worker thread, exactly once per enqueue, passing back the same taskContext pointer supplied to +/// b3EnqueueTaskCallback. /// @ingroup world typedef void b3TaskCallback( void* taskContext ); /// These functions can be provided to Box3D to invoke a task system. -/// Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box3D that the work was executed -/// serially within the callback and there is no need to call b3FinishTaskCallback. Otherwise the returned -/// value must be non-null will be passed to b3FinishTaskCallback as the userTask. +/// Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box3D that +/// the work was executed serially within the callback and there is no need to call +/// b3FinishTaskCallback. Otherwise the returned value must be non-null will be passed to +/// b3FinishTaskCallback as the userTask. /// @param task the Box3D task to be called by the scheduler /// @param taskContext the Box3D context object that the scheduler must pass to the task /// @param userContext the scheduler context object that is opaque to Box3D /// @param taskName the Box3D task name that the scheduler can use for diagnostics /// @ingroup world -typedef void* b3EnqueueTaskCallback( b3TaskCallback* task, void* taskContext, void* userContext, const char* taskName ); +typedef void* b3EnqueueTaskCallback( b3TaskCallback* task, void* taskContext, void* userContext, + const char* taskName ); -/// Finishes a user task object that wraps a Box3D task. This must block until the task has completed. -/// The step blocks here on the tasks it spawned, so b3World_Step holds its stack across every -/// fork/join. Drive it from a thread you can dedicate to the step, or from a fiber this callback can -/// park to free the underlying thread. In a job system that cannot park a job's stack, do not call -/// b3World_Step from inside a job: a job that blocks on its own sub-jobs without yielding its thread -/// can deadlock. The in-tree scheduler instead runs other pending tasks on the waiting thread. +/// Finishes a user task object that wraps a Box3D task. This must block until the task has +/// completed. The step blocks here on the tasks it spawned, so b3World_Step holds its stack across +/// every fork/join. Drive it from a thread you can dedicate to the step, or from a fiber this +/// callback can park to free the underlying thread. In a job system that cannot park a job's stack, +/// do not call b3World_Step from inside a job: a job that blocks on its own sub-jobs without +/// yielding its thread can deadlock. The in-tree scheduler instead runs other pending tasks on the +/// waiting thread. /// @ingroup world typedef void b3FinishTaskCallback( void* userTask, void* userContext ); typedef struct b3DebugShape b3DebugShape; -/// The user needs to be able to create debug draw shapes for multi-pass rendering to work efficiently. -/// These user shapes are created and destroyed via callback so they can be bound to shape lifetime and scaling updates. +/// The user needs to be able to create debug draw shapes for multi-pass rendering to work +/// efficiently. These user shapes are created and destroyed via callback so they can be bound to +/// shape lifetime and scaling updates. /// @ingroup debug_draw typedef void* b3CreateDebugShapeCallback( const b3DebugShape* debugShape, void* userContext ); typedef void b3DestroyDebugShapeCallback( void* userShape, void* userContext ); -/// Optional friction mixing callback. This intentionally provides no context objects because this is called -/// from a worker thread. +/// Optional friction mixing callback. This intentionally provides no context objects because this +/// is called from a worker thread. /// @warning This function should not attempt to modify Box3D state or user application state. /// @ingroup world -typedef float b3FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB ); +typedef float b3FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB, + uint64_t userMaterialIdB ); -/// Optional restitution mixing callback. This intentionally provides no context objects because this is called -/// from a worker thread. +/// Optional restitution mixing callback. This intentionally provides no context objects because +/// this is called from a worker thread. /// @warning This function should not attempt to modify Box3D state or user application state. /// @ingroup world -typedef float b3RestitutionCallback( float restitutionA, uint64_t userMaterialIdA, float restitutionB, uint64_t userMaterialIdB ); +typedef float b3RestitutionCallback( float restitutionA, uint64_t userMaterialIdA, + float restitutionB, uint64_t userMaterialIdB ); /// Prototype for a contact filter callback. /// This is called when a contact pair is considered for collision. This allows you to @@ -86,7 +93,8 @@ typedef bool b3CustomFilterFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, void* co /// full contact manifold. /// @warning Do not attempt to modify the world inside this callback /// @ingroup world -typedef bool b3PreSolveFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point, b3Vec3 normal, void* context ); +typedef bool b3PreSolveFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point, b3Vec3 normal, + void* context ); /// Prototype callback for overlap queries. /// Called for each shape found in the query. @@ -107,14 +115,16 @@ typedef bool b3OverlapResultFcn( b3ShapeId shapeId, void* context ); /// @param normal the normal vector at the point of intersection /// @param fraction the fraction along the ray at the point of intersection /// @param userMaterialId the shape or triangle surface type -/// @param triangleIndex the triangle index for mesh or height field shapes or -1 for other shape types +/// @param triangleIndex the triangle index for mesh or height field shapes or -1 for other shape +/// types /// @param childIndex the child shape index for compound shapes /// @param context the user context /// @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue /// @see b3World_CastRay /// @ingroup world -typedef float b3CastResultFcn( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, - int triangleIndex, int childIndex, void* context ); +typedef float b3CastResultFcn( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, + uint64_t userMaterialId, int triangleIndex, int childIndex, + void* context ); /// Optional world capacities that can be use to avoid run-time allocations /// @ingroup world @@ -147,7 +157,8 @@ typedef struct b3WorldDef /// speed have restitution applied (will bounce). float restitutionThreshold; - /// Number of iterations of the restitution solver. More iterations can lead to less box spinning. + /// Number of iterations of the restitution solver. More iterations can lead to less box + /// spinning. /// @see B3_MAX_RESTITUTION_ITERATIONS int restitutionIterations; @@ -158,16 +169,17 @@ typedef struct b3WorldDef /// speed can generate hit events if the shape also enables hit events. float hitEventThreshold; - /// Contact stiffness. Cycles per second. Increasing this increases the speed of overlap recovery, but can introduce jitter. + /// Contact stiffness. Cycles per second. Increasing this increases the speed of overlap + /// recovery, but can introduce jitter. float contactHertz; - /// Contact bounciness. Non-dimensional. You can speed up overlap recovery by decreasing this with - /// the trade-off that overlap resolution becomes more energetic. + /// Contact bounciness. Non-dimensional. You can speed up overlap recovery by decreasing this + /// with the trade-off that overlap resolution becomes more energetic. float contactDampingRatio; - /// This parameter controls how fast overlap is resolved and usually has units of meters per second. This only - /// puts a cap on the resolution speed. The resolution speed is increased by increasing the hertz and/or - /// decreasing the damping ratio. + /// This parameter controls how fast overlap is resolved and usually has units of meters per + /// second. This only puts a cap on the resolution speed. The resolution speed is increased by + /// increasing the hertz and/or decreasing the damping ratio. float contactSpeed; /// Maximum linear speed. Usually meters per second. @@ -190,11 +202,11 @@ typedef struct b3WorldDef bool enableContinuous; /// Number of workers to use with the provided task system. Box3D performs best when using only - /// performance cores and accessing a single L2 cache. Efficiency cores and hyper-threading provide - /// little benefit and may even harm performance. - /// This is clamped to the range [1, B3_MAX_WORKERS]. Using a value above 1 will turn on multithreading. - /// If task callbacks are provided then Box3D will use the user provided task system. Otherwise Box3D - /// will create threads and use an internal scheduler. + /// performance cores and accessing a single L2 cache. Efficiency cores and hyper-threading + /// provide little benefit and may even harm performance. This is clamped to the range [1, + /// B3_MAX_WORKERS]. Using a value above 1 will turn on multithreading. If task callbacks are + /// provided then Box3D will use the user provided task system. Otherwise Box3D will create + /// threads and use an internal scheduler. uint32_t workerCount; /// function to spawn task @@ -231,7 +243,8 @@ typedef struct b3WorldDef B3_API b3WorldDef b3DefaultWorldDef( void ); /// The body simulation type. -/// Each body is one of these three types. The type determines how the body behaves in the simulation. +/// Each body is one of these three types. The type determines how the body behaves in the +/// simulation. /// @ingroup body typedef enum b3BodyType { @@ -282,8 +295,8 @@ typedef struct b3BodyDef b3BodyType type; /// The initial world position of the body. Bodies should be created with the desired position. - /// @note Creating bodies at the origin and then moving them nearly doubles the cost of body creation, especially - /// if the body is moved after shapes have been added. + /// @note Creating bodies at the origin and then moving them nearly doubles the cost of body + /// creation, especially if the body is moved after shapes have been added. b3Pos position; /// The initial world rotation of the body. @@ -315,10 +328,11 @@ typedef struct b3BodyDef float sleepThreshold; /// Continuous collision safety factor. The solver only uses continuous collision if there is a - /// risk of tunneling. If the body is moving fast enough to risk tunneling then it is considered a "fast body". - /// This improves performance and prevents movement hitches. If a body moving N meter risks tunneling, then the - /// body will be considered fast if it moves more than a safetyFactor times N meters over one full time step. - /// Non-dimensional. Recommended range [0.01, 0.5]. Default is 0.5 for high performance with low tunneling risk. + /// risk of tunneling. If the body is moving fast enough to risk tunneling then it is considered + /// a "fast body". This improves performance and prevents movement hitches. If a body moving N + /// meter risks tunneling, then the body will be considered fast if it moves more than a + /// safetyFactor times N meters over one full time step. Non-dimensional. Recommended range + /// [0.01, 0.5]. Default is 0.5 for high performance with low tunneling risk. float safetyFactor; /// Optional body name for debugging. @@ -338,18 +352,19 @@ typedef struct b3BodyDef /// Treat this body as a high speed object that performs continuous collision detection /// against dynamic and kinematic bodies, but not other bullet bodies. - /// @warning Bullets should be used sparingly. They are not a solution for general dynamic-versus-dynamic - /// continuous collision. They do not guarantee accurate collision if both bodies are fast moving because - /// the bullet does a continuous check after all non-bullet bodies have moved. You could get unlucky and have - /// the bullet body end a time step very close to a non-bullet body and the non-bullet body then moves over - /// the bullet body. In continuous collision, initial overlap is ignored to avoid freezing bodies in place. - /// I do not recommend using them for game projectiles if precise collision timing is needed. Instead consider - /// using a ray or shape cast. You can use a marching ray or shape cast for projectile that moves over time. - /// If you want a fast moving projectile to collide with a fast moving target, you need to consider the relative - /// movement in your ray or shape cast. This is out of the scope of Box3D. - /// So what are good use cases for bullets? Pinball games or games with dynamic containers that hold other objects. - /// It should be a use case where it doesn't break the game if there is a collision missed, but having them - /// captured improves the quality of the game. + /// @warning Bullets should be used sparingly. They are not a solution for general + /// dynamic-versus-dynamic continuous collision. They do not guarantee accurate collision if + /// both bodies are fast moving because the bullet does a continuous check after all non-bullet + /// bodies have moved. You could get unlucky and have the bullet body end a time step very close + /// to a non-bullet body and the non-bullet body then moves over the bullet body. In continuous + /// collision, initial overlap is ignored to avoid freezing bodies in place. I do not recommend + /// using them for game projectiles if precise collision timing is needed. Instead consider + /// using a ray or shape cast. You can use a marching ray or shape cast for projectile that + /// moves over time. If you want a fast moving projectile to collide with a fast moving target, + /// you need to consider the relative movement in your ray or shape cast. This is out of the + /// scope of Box3D. So what are good use cases for bullets? Pinball games or games with dynamic + /// containers that hold other objects. It should be a use case where it doesn't break the game + /// if there is a collision missed, but having them captured improves the quality of the game. bool isBullet; /// Used to disable a body. A disabled body does not move or collide. @@ -403,8 +418,8 @@ typedef struct b3Filter /// or always collide (positive). A group index of zero has no effect. Non-zero group filtering /// always wins against the mask bits. /// For example, you may want ragdolls to collide with other ragdolls but you don't want - /// ragdoll self-collision. In this case you would give each ragdoll a unique negative group index - /// and apply that group index to all shapes on the ragdoll. + /// ragdoll self-collision. In this case you would give each ragdoll a unique negative group + /// index and apply that group index to all shapes on the ragdoll. int groupIndex; } b3Filter; @@ -423,7 +438,8 @@ typedef struct b3SurfaceMaterial /// https://en.wikipedia.org/wiki/Coefficient_of_restitution float restitution; - /// The rolling resistance usually in the range [0,1]. This is only used for spheres and capsules. + /// The rolling resistance usually in the range [0,1]. This is only used for spheres and + /// capsules. float rollingResistance; /// The tangent velocity for conveyor belts. This is local to the shape and will be projected @@ -483,7 +499,8 @@ typedef struct b3ShapeDef /// Use this to store application specific shape data. void* userData; - /// Surface material used on mesh shapes per triangle. Ignored for convex shapes. Ignored for compound shapes. + /// Surface material used on mesh shapes per triangle. Ignored for convex shapes. Ignored for + /// compound shapes. b3SurfaceMaterial* materials; /// Surface material count. @@ -501,42 +518,49 @@ typedef struct b3ShapeDef /// Contact filtering data. b3Filter filter; - /// Enable custom filtering. Only one of the two shapes needs to enable custom filtering. See b3WorldDef. + /// Enable custom filtering. Only one of the two shapes needs to enable custom filtering. See + /// b3WorldDef. bool enableCustomFiltering; /// A sensor shape generates overlap events but never generates a collision response. - /// Sensors do not have continuous collision. Instead, use a ray or shape cast for those scenarios. - /// Sensors still contribute to the body mass if they have non-zero density. + /// Sensors do not have continuous collision. Instead, use a ray or shape cast for those + /// scenarios. Sensors still contribute to the body mass if they have non-zero density. /// @note Sensor events are disabled by default. /// @see enableSensorEvents bool isSensor; - /// Enable sensor events for this shape. This applies to sensors and non-sensors. False by default, even for sensors. - /// Only convex shapes may act as sensor visitors. + /// Enable sensor events for this shape. This applies to sensors and non-sensors. False by + /// default, even for sensors. Only convex shapes may act as sensor visitors. bool enableSensorEvents; - /// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. False by default. + /// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored + /// for sensors. False by default. bool enableContactEvents; - /// Enable hit events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. False by default. + /// Enable hit events for this shape. Only applies to kinematic and dynamic bodies. Ignored for + /// sensors. False by default. bool enableHitEvents; - /// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive + /// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are + /// expensive /// and must be carefully handled due to multithreading. Ignored for sensors. bool enablePreSolveEvents; - /// When shapes are created they will scan the environment for collision the next time step. This can significantly slow down - /// static body creation when there are many static shapes. - /// This is flag is ignored for dynamic and kinematic shapes which always invoke contact creation. + /// When shapes are created they will scan the environment for collision the next time step. + /// This can significantly slow down static body creation when there are many static shapes. + /// This is flag is ignored for dynamic and kinematic shapes which always invoke contact + /// creation. bool invokeContactCreation; /// Should the body update the mass properties when this shape is created. Default is true. - /// Warning: if this is false, you MUST call b3Body_ApplyMassFromShapes or b3Body_SetMassData before simulating the world. + /// Warning: if this is false, you MUST call b3Body_ApplyMassFromShapes or b3Body_SetMassData + /// before simulating the world. bool updateBodyMass; /// Enable speculative collision. Leave this true unless you care about reducing ghost collision /// more than continuous collision under rotation. - /// Experimental: this can only disable speculative contact between hulls and triangles (meshes and height fields). + /// Experimental: this can only disable speculative contact between hulls and triangles (meshes + /// and height fields). bool enableSpeculativeContact; /// Used internally to detect a valid definition. DO NOT SET. @@ -788,7 +812,8 @@ typedef struct b3MoverJointDef /// @ingroup mover_joint B3_API b3MoverJointDef b3DefaultMoverJointDef( void ); -/// Pogo joint definition +/// The pogo joint is used for the dynamic character mover. The pogo axis is along the frame B +/// y-axis. /// @ingroup pogo_joint typedef struct b3PogoJointDef { @@ -1134,8 +1159,9 @@ B3_API b3ExplosionDef b3DefaultExplosionDef( void ); * Also when events occur in the simulation step it may be problematic to modify the world, which is * often what applications want to do when events occur. * - * With event arrays, you can scan the events in a loop and modify the world. However, you need to be careful - * that some event data may become invalid. There are several samples that show how to do this safely. + * With event arrays, you can scan the events in a loop and modify the world. However, you need to + * be careful that some event data may become invalid. There are several samples that show how to do + * this safely. * * @{ */ @@ -1194,8 +1220,8 @@ typedef struct b3ContactBeginTouchEvent /// Id of the second shape b3ShapeId shapeIdB; - /// The transient contact id. This contact may be destroyed automatically when the world is modified or simulated. - /// Use b3Contact_IsValid before using this id. + /// The transient contact id. This contact may be destroyed automatically when the world is + /// modified or simulated. Use b3Contact_IsValid before using this id. b3ContactId contactId; } b3ContactBeginTouchEvent; @@ -1221,8 +1247,8 @@ typedef struct b3ContactEndTouchEvent b3ContactId contactId; } b3ContactEndTouchEvent; -/// A hit touch event is generated when two shapes collide with a speed faster than the hit speed threshold. -/// This may be reported for speculative contacts that have a confirmed impulse. +/// A hit touch event is generated when two shapes collide with a speed faster than the hit speed +/// threshold. This may be reported for speculative contacts that have a confirmed impulse. typedef struct b3ContactHitEvent { /// Id of the first shape @@ -1286,8 +1312,8 @@ typedef struct b3ContactEvents /// On the other hand if the flag does not indicate the body went to sleep then the application /// can treat the actor/entity/object associated with the body as awake. /// This is an efficient way for an application to update game object transforms rather than -/// calling functions such as b3Body_GetTransform() because this data is delivered as a contiguous array -/// and it is only populated with bodies that have moved. +/// calling functions such as b3Body_GetTransform() because this data is delivered as a contiguous +/// array and it is only populated with bodies that have moved. /// @note If sleeping is disabled all dynamic and kinematic bodies will trigger move events. typedef struct b3BodyMoveEvent { @@ -1358,7 +1384,8 @@ typedef struct b3ContactData /// this pointer. const struct b3Manifold* manifolds; - /// The number of contact manifolds. For mesh and height-field collision there can be multiple manifolds. + /// The number of contact manifolds. For mesh and height-field collision there can be multiple + /// manifolds. int manifoldCount; } b3ContactData; @@ -1384,14 +1411,15 @@ typedef struct b3QueryFilter /// query would accept for collision. uint64_t maskBits; - /// Optional id combined with @ref name to identify this query in a recording, e.g. an entity id. - /// Need not be unique on its own. 0 with a null name means untagged. Ignored when not recording. + /// Optional id combined with @ref name to identify this query in a recording, e.g. an entity + /// id. Need not be unique on its own. 0 with a null name means untagged. Ignored when not + /// recording. uint64_t id; - /// Optional label combined with @ref id to identify this query, e.g. "bullet". Need not be unique - /// on its own. The recorder hashes (id, name) into one stable key the viewer tracks the query by, - /// so the same id and name pair identifies the same query across frames. NULL means none. Ignored - /// when not recording. + /// Optional label combined with @ref id to identify this query, e.g. "bullet". Need not be + /// unique on its own. The recorder hashes (id, name) into one stable key the viewer tracks the + /// query by, so the same id and name pair identifies the same query across frames. NULL means + /// none. Ignored when not recording. const char* name; } b3QueryFilter; @@ -1475,7 +1503,8 @@ typedef struct b3ShapeCastInput /// The maximum fraction of the translation to consider, typically 1. float maxFraction; - /// Allow shape cast to encroach when initially touching. This only works if the radius is greater than zero. + /// Allow shape cast to encroach when initially touching. This only works if the radius is + /// greater than zero. bool canEncroach; } b3ShapeCastInput; @@ -1621,7 +1650,7 @@ typedef struct b3ShapeCastPairInput b3Transform transform; ///< Transform of shape B in shape A's frame, the relative pose B in A b3Vec3 translationB; ///< The translation of shape B, in A's frame float maxFraction; ///< The fraction of the translation to consider, typically 1 - bool canEncroach; ///< Allows shapes with a radius to move slightly closer if already touching + bool canEncroach; ///< Allows shapes with a radius to move slightly closer if already touching } b3ShapeCastPairInput; /// Input for b3ShapeDistance @@ -1634,7 +1663,8 @@ typedef struct b3DistanceInput b3ShapeProxy proxyB; /// Transform of shape B in shape A's frame, the relative pose B in A - /// (b3InvMulWorldTransforms( worldA, worldB )). The query is origin independent and runs in frame A. + /// (b3InvMulWorldTransforms( worldA, worldB )). The query is origin independent and runs in + /// frame A. b3Transform transform; /// Should the proxy radius be considered? @@ -1670,9 +1700,9 @@ typedef struct b3Simplex int count; ///< number of valid vertices } b3Simplex; -/// This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, -/// which may not coincide with the center of mass. However, to support dynamics we must interpolate the center of mass -/// position. +/// This describes the motion of a body/shape for TOI computation. Shapes are defined with respect +/// to the body origin, which may not coincide with the center of mass. However, to support dynamics +/// we must interpolate the center of mass position. typedef struct b3Sweep { b3Vec3 localCenter; ///< Local center of mass position @@ -1741,9 +1771,9 @@ typedef struct b3TOIOutput * @defgroup tree Dynamic Tree * The dynamic tree is a binary AABB tree to organize and query large numbers of geometric objects * - * Box3D uses the dynamic tree internally to sort collision shapes into a binary bounding volume hierarchy. - * This data structure may have uses in games for organizing other geometry data and may be used independently - * of Box3D rigid body simulation. + * Box3D uses the dynamic tree internally to sort collision shapes into a binary bounding volume + * hierarchy. This data structure may have uses in games for organizing other geometry data and may + * be used independently of Box3D rigid body simulation. * * A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. * A dynamic tree arranges data in a binary tree to accelerate @@ -1872,23 +1902,27 @@ typedef struct b3TreeStats /// @return true if the query should continue typedef bool b3TreeQueryCallbackFcn( int proxyId, uint64_t userData, void* context ); -/// This function receives the minimum distance squared so far and proxy to check in the closest query. +/// This function receives the minimum distance squared so far and proxy to check in the closest +/// query. /// @return minimum distance squared to user objects in the proxy -typedef float b3TreeQueryClosestCallbackFcn( float distanceSqrMin, int proxyId, uint64_t userData, void* context ); +typedef float b3TreeQueryClosestCallbackFcn( float distanceSqrMin, int proxyId, uint64_t userData, + void* context ); /// This function receives clipped AABB cast input for a proxy. The function returns the new cast /// fraction. /// - return a value of 0 to terminate the cast /// - return a value less than input->maxFraction to clip the cast /// - return a value of input->maxFraction to continue the cast without clipping -typedef float b3TreeBoxCastCallbackFcn( const b3BoxCastInput* input, int proxyId, uint64_t userData, void* context ); +typedef float b3TreeBoxCastCallbackFcn( const b3BoxCastInput* input, int proxyId, uint64_t userData, + void* context ); /// This function receives clipped ray cast input for a proxy. The function /// returns the new ray fraction. /// - return a value of 0 to terminate the ray cast /// - return a value less than input->maxFraction to clip the ray /// - return a value of input->maxFraction to continue the ray cast without clipping -typedef float b3TreeRayCastCallbackFcn( const b3RayCastInput* input, int proxyId, uint64_t userData, void* context ); +typedef float b3TreeRayCastCallbackFcn( const b3RayCastInput* input, int proxyId, uint64_t userData, + void* context ); /**@}*/ // tree @@ -1932,7 +1966,8 @@ typedef struct b3CollisionPlane /// The push on the mover determined by b3SolvePlanes. Usually in meters. float push; - /// Indicates if b3ClipVector should clip against this plane. Should be false for soft collision. + /// Indicates if b3ClipVector should clip against this plane. Should be false for soft + /// collision. bool clipVelocity; } b3CollisionPlane; @@ -1974,7 +2009,8 @@ typedef struct b3BodyTOIResult /// Used to collect collision planes for character movers. /// Return true to continue gathering planes. -typedef bool b3PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* plane, int planeCount, void* context ); +typedef bool b3PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* plane, int planeCount, + void* context ); /// Used to filter shapes for shape casting character movers. /// Return true to accept the collision @@ -3091,8 +3127,8 @@ B3_INLINE uint32_t b3MakeDebugColor( b3HexColor rgb, b3DebugMaterial material ) /// (B3_GRAPH_COLOR_COUNT - 1) is the overflow color. B3_API b3HexColor b3GetGraphColor( int index ); -/// This is sent to the user for debug shape creation. The user should know the type in case they have -/// custom sphere or capsule rendering. +/// This is sent to the user for debug shape creation. The user should know the type in case they +/// have custom sphere or capsule rendering. typedef struct b3DebugShape { /// Shape id. @@ -3118,10 +3154,11 @@ typedef struct b3DebugShape /// it stays accurate far from the origin. Shift into your own camera frame inside the callbacks. typedef struct b3DebugDraw { - /// Draws a user shape. The userShape pointer is owned by the application and is known to Box3D as - /// an opaque pointer returned from b3CreateDebugShapeCallback. When this is called the drawn shape has - /// passed a culling test against drawingBounds below. - void ( *DrawShapeFcn )( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ); + /// Draws a user shape. The userShape pointer is owned by the application and is known to Box3D + /// as an opaque pointer returned from b3CreateDebugShapeCallback. When this is called the drawn + /// shape has passed a culling test against drawingBounds below. + void ( *DrawShapeFcn )( void* userShape, b3WorldTransform transform, b3HexColor color, + void* context ); /// Draw a line segment. void ( *DrawSegmentFcn )( b3Pos p1, b3Pos p2, b3HexColor color, void* context ); @@ -3136,13 +3173,15 @@ typedef struct b3DebugDraw void ( *DrawSphereFcn )( b3Pos p, float radius, b3HexColor color, float alpha, void* context ); /// Draw a capsule. - void ( *DrawCapsuleFcn )( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha, void* context ); + void ( *DrawCapsuleFcn )( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha, + void* context ); /// Draw a bounding box. void ( *DrawBoundsFcn )( b3AABB aabb, b3HexColor color, void* context ); /// Draw an oriented box. - void ( *DrawBoxFcn )( b3Vec3 extents, b3WorldTransform transform, b3HexColor color, void* context ); + void ( *DrawBoxFcn )( b3Vec3 extents, b3WorldTransform transform, b3HexColor color, + void* context ); /// Draw a string in world space void ( *DrawStringFcn )( b3Pos p, const char* s, b3HexColor color, void* context ); diff --git a/src/mover_joint.c b/src/mover_joint.c index d0686c3..3f269e5 100644 --- a/src/mover_joint.c +++ b/src/mover_joint.c @@ -192,16 +192,31 @@ void b3SolveMoverJoint( b3JointSim* base, b3StepContext* context ) } } -void b3DrawMoverJoint( b3DebugDraw* draw, b3World* world, b3JointSim* base, - b3WorldTransform transformA, b3WorldTransform transformB ) +static b3HexColor b3LerpColor( b3HexColor a, b3HexColor b, float t ) { - B3_UNUSED( draw, world, base, transformA, transformB ); - B3_ASSERT( base->type == b3_moverJoint ); + uint32_t result = 0; + for ( int shift = 0; shift < 24; shift += 8 ) + { + float ca = (float)( ( (uint32_t)a >> shift ) & 0xFF ); + float cb = (float)( ( (uint32_t)b >> shift ) & 0xFF ); + uint32_t c = (uint32_t)( b3LerpFloat( ca, cb, t ) + 0.5f ); + result |= c << shift; + } + return (b3HexColor)result; +} + +void b3DrawMoverJoint( b3DebugDraw* draw, b3World* world, b3JointSim* base, b3WorldTransform transformA, + b3WorldTransform transformB ) +{ + B3_ASSERT( base->type == b3_moverJoint ); + B3_UNUSED( transformA ); -#if 0 b3MoverJoint* joint = &base->moverJoint; - b3Pos pB = b3TransformWorldPoint( transformB, base->localFrameB.p ); + b3WorldTransform frameB = b3MulWorldTransforms( transformB, base->localFrameB ); + b3Matrix3 matrixB = b3MakeMatrixFromQuat( frameB.q ); + b3Vec3 axisX = matrixB.cx; + b3Vec3 axisZ = matrixB.cz; b3Body* bodyA = b3Array_Get( world->bodies, base->bodyIdA ); b3Body* bodyB = b3Array_Get( world->bodies, base->bodyIdB ); @@ -209,54 +224,33 @@ void b3DrawMoverJoint( b3DebugDraw* draw, b3World* world, b3JointSim* base, b3BodyState* stateB = b3GetBodyState( world, bodyB ); b3Vec3 vA = stateA != NULL ? stateA->linearVelocity : b3Vec3_zero; b3Vec3 vB = stateB != NULL ? stateB->linearVelocity : b3Vec3_zero; - b3Vec3 relativeVelocity = b3Sub( vB, vA ); - b3Vec3 maxForce = joint->maxForce; - b3Vec3 force = b3MulSV( world->inv_h, joint->impulse ); + b3Vec3 error = b3Sub( b3Sub( vB, vA ), joint->linearVelocity ); + b3Vec2 planeError = { b3Dot( error, axisX ), b3Dot( error, axisZ ) }; + b3Vec2 planeTarget = { b3Dot( joint->linearVelocity, axisX ), b3Dot( joint->linearVelocity, axisZ ) }; - // todo comment - float saturation = 0.999f; - bool saturated = ( maxForce.x > 0.0f && b3AbsFloat( force.x ) >= saturation * maxForce.x ) || - ( maxForce.y > 0.0f && b3AbsFloat( force.y ) >= saturation * maxForce.y ) || - ( maxForce.z > 0.0f && b3AbsFloat( force.z ) >= saturation * maxForce.z ); + // Colorize ring by ratio of actual speed to target speed. + float referenceSpeed = b3MaxFloat( b3Length2( planeTarget ), 1.0f ); + float t = b3ClampFloat( b3Length2( planeError ) / referenceSpeed, 0.0f, 1.0f ); + b3HexColor color = b3LerpColor( b3_colorLimeGreen, b3_colorRed, t ); - // todo comment - b3Vec3 target = { - maxForce.x > 0.0f ? joint->linearVelocity.x : relativeVelocity.x, - maxForce.y > 0.0f ? joint->linearVelocity.y : relativeVelocity.y, - maxForce.z > 0.0f ? joint->linearVelocity.z : relativeVelocity.z, - }; - - b3HexColor targetColor = saturated ? b3_colorRed : b3_colorLimeGreen; - b3Pos targetTip = b3OffsetPos( pB, target ); - draw->DrawSegmentFcn( pB, targetTip, targetColor, draw->context ); - draw->DrawPointFcn( targetTip, 6.0f, targetColor, draw->context ); - - b3Pos velocityTip = b3OffsetPos( pB, relativeVelocity ); - draw->DrawSegmentFcn( pB, velocityTip, b3_colorLightSkyBlue, draw->context ); - draw->DrawPointFcn( velocityTip, 4.0f, b3_colorLightSkyBlue, draw->context ); - - draw->DrawPointFcn( pB, 8.0f, b3_colorPlum, draw->context ); - - if ( draw->drawJointExtras ) + const int segmentCount = 32; + b3Pos p1 = b3OffsetPos( frameB.p, axisX ); + for ( int i = 1; i <= segmentCount; ++i ) { - if ( bodyA->type != b3_staticBody ) - { - draw->DrawSegmentFcn( pB, transformA.p, b3_colorDimGray, draw->context ); - } - - b3WorldTransform boxTransform = { pB, b3Quat_identity }; - draw->DrawBoxFcn( b3MulSV( draw->forceScale, maxForce ), boxTransform, b3_colorGray, - draw->context ); - - b3HexColor forceColor = saturated ? b3_colorRed : b3_colorAzure; - draw->DrawSegmentFcn( pB, b3OffsetPos( pB, b3MulSV( draw->forceScale, force ) ), forceColor, - draw->context ); - - char buffer[96]; - snprintf( buffer, 96, "f = (%.1f, %.1f, %.1f)", force.x, force.y, force.z ); - draw->DrawStringFcn( pB, buffer, forceColor, draw->context ); + float angle = 2.0f * B3_PI * i / segmentCount; + b3CosSin cs = b3ComputeCosSin( angle ); + b3Pos p2 = b3OffsetPos( frameB.p, b3Blend2( cs.cosine, axisX, cs.sine, axisZ ) ); + draw->DrawSegmentFcn( p1, p2, color, draw->context ); + p1 = p2; } -#endif + if ( joint->maxForce > 0.0f ) + { + float scale = world->inv_h / joint->maxForce; + b3Vec3 force = b3Blend2( scale * joint->impulse.x, axisX, scale * joint->impulse.y, axisZ ); + b3Pos tip = b3OffsetPos( frameB.p, force ); + draw->DrawSegmentFcn( frameB.p, tip, b3_colorAzure, draw->context ); + draw->DrawPointFcn( tip, 6.0f, b3_colorAzure, draw->context ); + } } diff --git a/src/pogo_joint.c b/src/pogo_joint.c index d2643ce..bc69e92 100644 --- a/src/pogo_joint.c +++ b/src/pogo_joint.c @@ -300,8 +300,8 @@ void b3DrawPogoJoint( b3DebugDraw* draw, b3World* world, b3JointSim* base, b3Wor float force = world->inv_h * joint->impulse; - // todo comment - float saturation = 0.999f; + // Tolerance for reaching max force. + float saturation = 0.99f; b3HexColor color; if ( joint->hertz == 0.0f ) @@ -329,6 +329,7 @@ void b3DrawPogoJoint( b3DebugDraw* draw, b3World* world, b3JointSim* base, b3Wor color = b3_colorLightGray; } + // Spring int segmentCount = 12; float width = 0.1f * scale; b3Pos p1 = pB; @@ -341,6 +342,7 @@ void b3DrawPogoJoint( b3DebugDraw* draw, b3World* world, b3JointSim* base, b3Wor p1 = p2; } + // Ground plane b3Pos rest = b3OffsetPos( pB, b3MulSV( -joint->restLength, axis ) ); float tick = 1.5f * width; draw->DrawSegmentFcn( b3OffsetPos( rest, b3MulSV( -tick, perp1 ) ), b3OffsetPos( rest, b3MulSV( tick, perp1 ) ),