Newton Game Dynamics 1.5

Advanced physics engine for real-time simulation of rigid bodies.

Created by Julio Jerez 2003 - 2005. All rights reserved.

World interface

NewtonCreate

NewtonWorld* NewtonCreate(
NewtonAllocMemory mallocFnt,
NewtonFreeMemory mfreeFnt)
Create an instance of the Newton world.

Parameters

NewtonAllocMemory mallocFnt | - | is a pointer to the memory allocator callback function. If this parameter is NULL the standard malloc function is used.
NewtonFreeMemory mfreeFnt | - | is a pointer to the memory release callback function. If this parameter is NULL the standard free function is used.

Return

a pointer to an instance of the Newton world.

Remarks

this function must be called before any of the other API functions.

See also

NewtonDestroy, NewtonDestroyAllBodies

NewtonDestroy

void NewtonDestroy(const NewtonWorld* newtonWorld)
Destroy an instance of the Newton world.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world.

Return

Nothing.

Remarks

This function will destroy the entire Newton world.

See also

NewtonCreate, NewtonDestroyAllBodies

NewtonGetGlobalScale

dFloat NewtonGetGlobalScale(const NewtonWorld* newtonWorld)
Get the global scale factor.

Remarks

the physics system in theory should be dimensionless, however in practice the engine have to be implemented with limited precision floating numbers and is also built for real-time simulation, it is inevitable that tolerances have to be used in order to increase performance, and reduce instabilities. These tolerances make the engine dimension dependent, for example let say a rigid body is considered at rest when its velocity is less than 0.01 units per second for some frames. For a program using meters as unit this translate to 0.01 meters per second, however for a program using centimeter this translate to 0.0001 meter per second, since the precession of speed is independent of the unit system, this means that in the second system the engine has to work much harder to bring the body to rest. A solution for this is to scale all tolerances to match the unit system. The argument globalScale must be a constant to convert the unit system in the game to meters, for example if in your game you are using 39 units is a meter, the globaScale must be 39. The exact conversion factor does not have to be exact, but the closer it is to reality the better performance the application will get. Applications that are already using meters as the unit system must pass 1.0 as globalScale.

See also

NewtonCreate dFloat NewtonGetGlobalScale(const NewtonWorld* newtonWorld) { Newton *world; world = (Newton *) newtonWorld; return world->GetGlobalScale(); return dgFloat32(1.0f); }

NewtonSetPlatformArchitecture

void NewtonSetPlatformArchitecture(
const NewtonWorld* newtonWorld,
int mode)
Set the current platform hardware architecture.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int model | - | model of operation 0 = default, 1 = medium, n = best.

Return

Nothing

Remarks

This function allows the application to configure the Newton to take advantage for specific hardware architecture in the same platform.

0

force the hardware lower common denominator for the running platform.

1

will try to use common floating point enhancement like spacial instruction set on the specific architecture. This mode made lead to result that differ from mode 1 and 2 as the accumulation round off errors maybe different.

2

the engine will try to use the best possible hardware setting found in the current platform this is the default configuration. This mode made lead to result that differ from mode 1 and 2 as the accumulation round off errors maybe different.

Remarks

the only hardware mode guarantee to work is mode 0. all other are only hints to the engine, for example setting mode 1 will take not effect on CPUs without specially floating point instructions set.

NewtonSetSolverModel

void NewtonSetSolverModel(
const NewtonWorld* newtonWorld,
int model)
Set the solver precision mode.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int model | - | model of operation 0 = exact, 1 = adaptive, n = linear. The default is exact.

Return

Nothing

Remarks

This function allows the application to configure the Newton solver to work in three different modes.

0

Is the exact mode. This is good for application where precision is more important than speed, ex: realistic simulation.

1

Is the adaptive mode, the solver is not as exact but the simulation will still maintain a high degree of accuracy. This mode is good for applications were a good degree of stability is important but not as important as speed.

n

Linear mode. The solver will not try to reduce the joints relative acceleration errors to below some limit, instead it will perform up to n passes over the joint configuration each time reducing the acceleration error, but it will terminate when the number of passes is exhausted regardless of the error magnitude. In general this is the fastest mode and is is good for applications where speed is the only important factor, ex: video games.

Remarks

the adaptive friction model combined with the linear model make for the fastest possible configuration of the Newton solver. This setup is best for games. If you need the best realistic behavior, we recommend the use of the exact solver and exact friction model which are the defaults.

See also

NewtonSetFrictionModel

NewtonSetFrictionModel

void NewtonSetFrictionModel(
const NewtonWorld* newtonWorld,
int model)
Set coulomb model of friction.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int model | - | friction model; 0 = exact coulomb, 1 = adaptive coulomb, The default is exact.

Return

Nothing.

Remarks

This function allows the application to chose between and exact or an adaptive coulomb friction model

0

Is the exact model. Friction forces are calculated in each frame. This model is good for applications where precision is more important than speed, ex: realistic simulation.

1

Is the adaptive model. Here values from previous frames are used to determine the maximum friction values of the current frame. This is about 10% faster than the exact model however it may introduce strange friction behaviors. For example a bouncing object tumbling down a ramp will act as a friction less object because the contacts do not have continuity. In general each time a new contact is generated the friction value is zero, only if the contact persist a non zero friction values is used. The second effect is that if a normal force is very strong, and if the contact is suddenly destroyed, a very strong friction force will be generated at the contact point making the object react in a non-familiar way.

Remarks

the adaptive friction model combined with the linear model make for the fastest possible configuration of the Newton solver. This setup is best for games. If you need the best realistic behavior, we recommend the use of the exact solver and exact friction model which are the defaults.

See also

NewtonSetSolverModel

NewtonUpdate

void NewtonUpdate(
const NewtonWorld* newtonWorld,
dFloat timestep)
Advance the simulation by an amount of time.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
dFloat timestep | - | time step in seconds

Return

Nothing

Remarks

This function will advance the simulation by the amount of time specified by timestep. The Newton Engine does not perform sub-steps, and does not need tuning parameters. It is the responsibility of the application to ensure that timestep is small enough to guarantee physics stability.

NewtonSetMinimumFrameRate

void NewtonSetMinimumFrameRate(
const NewtonWorld* newtonWorld,
dFloat frameRate)
Set the minimum frame rate at which the simulation can run.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
dFloat frameRate | - | minimum frame rate of the simulation in frame per second. This value is clamped between 60fps and 1000fps

Return

nothing

Remarks

the default minimum frame rate of the simulation is 60 frame per second. When the simulation falls below the specified minimum frame, Newton will perform sub steps in order to meet the desired minimum FPS.

NewtonGetTimeStep

dFloat NewtonGetTimeStep(const NewtonWorld* newtonWorld)
Return the correct time step for this simulation update.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world.

Remark

This application can used this function to get the currect siulation time step.

Return

correct update timestep.

NewtonDestroyAllBodies

void NewtonDestroyAllBodies(const NewtonWorld* newtonWorld)
Remove all bodies and joints from the newton world.

Parameters

const NewtonWorld *newtonWorld - is a pointer to the Newton world

Return

Nothing

Remarks

This function will destroy all bodies and all joints in the Newton world, but it will retain group IDs. Use this function for when you want to clear the world but preserve all the group IDs and material pairs.

See also

NewtonMaterialDestroyAllGroupID

NewtonSetWorldSize

void NewtonSetWorldSize(
const NewtonWorld* newtonWorld,
const dFloat* minPtr,
const dFloat* maxPtr)
Set the size of the Newton world.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
const dFloat *minPtr | - | is the minimum point of the world bounding box
const dFloat *maxPtr | - | is the maximum point of the world bounding box

Return

Nothing.

Remarks

The Newton world must have a finite size. The size of the world is set to a box +- 100 units in all three dimensions at creation time and after a call to the function NewtonRemoveAllBodies

See also

NewtonSetBodyLeaveWorldEvent

NewtonSetBodyLeaveWorldEvent

void NewtonSetBodyLeaveWorldEvent(
const NewtonWorld* newtonWorld,
NewtonBodyLeaveWorld callback)
Set the event callback function to be called in the event a body is escaping the limits of the world during simulation time.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
NewtonBodyLeaveWorld callback | - | is the pointer to the function callback

Return

Nothing

Remarks

When a body moves outside the bounding box that defines the world space the body is automatically disabled and Newton calls the application defined callback function NewtonBodyLeaveWorld callback. The application should decide how to handle the event, because Newton will make the callback once. The only options available to the application are: do nothing or destroy the object.

Remarks

if the application wants to reinitialize the body, it will have to used the function NewtonBodySetMatrixRecursive, this is because it is possible that the rigid body is part of a set of articulate bodies and only one part leave the world while the others are still inside the world volume, and in and situation like this the function NewtonSetMatrix will lead to unpredictable results.

See also

NewtonSetWorldSize, NewtonBodySetMatrixRecursive

NewtonWorldFreezeBody

void NewtonWorldFreezeBody(
const NewtonWorld* newtonWorld,
const NewtonBody* body)
Remove the body from the active simulation list.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
const NewtonBody *body | - | is the pointer to the body to be frozen

Return

Nothing.

Remarks

When a body is created it is automatically placed in the active simulation list. As an optimization for large scenes, you may use this function to put background bodies in an inactive equilibrium state.

Remarks

This function tells Newton that this body does not currently need to be simulated. However, if the body is part of a larger configuration it may be affected indirectly by the reaction forces of objects that it is connected to.

See also

NewtonWorldUnfreezeBody, NewtonBodySetAutoFreeze, NewtonBodyGetAutoFreeze

NewtonWorldUnfreezeBody

void NewtonWorldUnfreezeBody(
const NewtonWorld* newtonWorld,
const NewtonBody* body)
Add the body to the active simulation list.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
const NewtonBody *body | - | is the pointer to the body to be activated

Return

Nothing

Remarks

This function tells Newton to simulate the rigid body body.

See also

NewtonWorldFreezeBody, NewtonBodySetAutoFreeze, NewtonBodyGetAutoFreeze

NewtonWorldForEachBodyDo

void NewtonWorldForEachBodyDo(
const NewtonWorld* newtonWorld,
NewtonBodyIterator callback)
Iterate thought every body in the world calling the function callback.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
NewtonBodyIterator callback | - | application define callback

Return

nothing

Remarks

The application can call this function to iterate thought every body in the world. the application should provide the function NewtonBodyIterator callback to be called by Newton for every body in the world

Remarks

this function affect severally the performance of Newton. The application should call this function only for debugging purpose See also: NewtonBodyForEachPolygonDo

NewtonGetVersion

Return the current library version number.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the newton world.

Return

release decimal three digit value x.xx the first digit: is mayor version number (interface changes among other things) the second digit: is mayor patch number (new features, and bug fixes) third digit: is minor bug fixed patch.

NewtonWorldSetUserData

void NewtonWorldSetUserData(
const NewtonWorld* newtonWorld,
void* userData)
Store a user defined data value with the world.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the newton world.
void *userDataPtr | - | pointer to the user defined user data value.

Return

Nothing.

Remarks

The application can store a user defined value with the Newton world. The user data is useful for application developing object oriented classes based on the Newton API.

See also

NewtonWorldGetUserData

NewtonWorldGetUserData

void* NewtonWorldGetUserData(const NewtonWorld* newtonWorld)
Retrieve a user previously stored user define value with the world.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world.

Return

user data value.

Remarks

The application can store a user defined value with the Newton world. The user data is useful for application developing object oriented classes based on the Newton API.

See also

NewtonWorldGetUserData

NewtonWorldRayCast

void NewtonWorldRayCast(
const NewtonWorld* newtonWorld,
const dFloat* p0,
const dFloat* p1,
NewtonWorldRayFilterCallback filter,
void* userData)
Shoot a ray from p0 to p1 and call the application callback with each ray intersection.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the world.
const dFloat *p0 | - | pointer to an array of at least three floats containing the beginning of the ray in global space.
const dFloat *p1 | - | pointer to an array of at least three floats containing the end of the ray in global space.
NewtonWorldRayFilterCallback filter | - | user define function to be called for each body hit during the ray scan.
void *userData | - | user data to be passed to the filter callback.

Return

nothing

Remarks

The ray cast function will call the application with each body intersecting the line segment. By writing the callback filter function in different ways the application can implement different flavors of ray casting. For example an all body ray cast can be easily implemented by having the filter function always returning 1.0, and copying each rigid body into an array of pointers; a closest hit ray cast can be implemented by saving the body with the smaller intersection parameter and returning the parameter t; and a report the first body hit can be implemented by having the filter function returning zero after the first call and saving the pointer to the rigid body.

Remarks

The most common use for the ray cast function is the closest body hit, In this case it is important, for performance reasons, that the filter function returns the intersection parameter. If the filter function returns a value of zero the ray cast will terminate immediately.

Remarks

The ray cast function is provided as an utility function, this means that even thought the function is very high performance by function standards, it can not by batched and therefore it can not be an incremental function. For example the cost of calling 1000 ray cast is 1000 times the cost of calling one ray cast. This is much different than the collision system where the cost of calculating collision for 1000 pairs in much, much less that the 1000 times the cost of one pair. Therefore this function must be used with care, as excessive use of it can degrade performance.

GroupID interface

NewtonMaterialGetDefaultGroupID

int NewtonMaterialGetDefaultGroupID(const NewtonWorld* newtonWorld)
Get the value of the default MaterialGroupID.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world

Return

The ID number for the default Group ID.

Remarks

Group IDs can be interpreted as the nodes of a dense graph. The edges of the graph are the physics materials. When the Newton world is created, the default Group ID is created by the engine. When bodies are created the application assigns a group ID to the body.

NewtonMaterialCreateGroupID

int NewtonMaterialCreateGroupID(const NewtonWorld* newtonWorld)
Create a new MaterialGroupID.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world

Return

The ID of a new GroupID.

Remarks

Group IDs can be interpreted as the nodes of a dense graph. The edges of the graph are the physics materials. When the Newton world is created, the default Group ID is created by the engine. When bodies are created the application assigns a group ID to the body.

Note

The only way to destroy a Group ID after its creation is by destroying all the bodies and calling the function *NewtonMaterialDestroyAllGroupID*.

See also

NewtonMaterialDestroyAllGroupID

NewtonMaterialDestroyAllGroupID

void NewtonMaterialDestroyAllGroupID(const NewtonWorld* newtonWorld)
Remove all groups ID from the Newton world.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world

Return

Nothing.

Remarks

This function removes all groups ID from the Newton world. This function must be called after there are no more rigid bodies in the word.

See also

NewtonDestroyAllBodies

Material setup interface

NewtonMaterialSetDefaultCollidable

void NewtonMaterialSetDefaultCollidable(
const NewtonWorld* newtonWorld,
int id0,
int id1,
int state)
Set the material defined by the interaction between two physics groups to be collidable or non-collidable by default.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int id0 | - | group id0
int id1 | - | group id1
int state | - | state for this material: 1 = collidable; 0 = non collidable

Return

Nothing.

NewtonMaterialSetContinuousCollisionMode

void NewtonMaterialSetContinuousCollisionMode(
const NewtonWorld* newtonWorld,
int id0,
int id1,
int state)
Set the material defined by the interaction between two physics groups to enable or desable continue collision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int id0 | - | group id0
int id1 | - | group id1
int state | - | state for this material: 1 = continue collision on; 0 = continue collision off, default mode is on

Return

Nothing.

Remarks

continue collision mode enable allow the engine to predict colliding contact on rigid bodies Moving at high speed of subject to strong forces.

Remarks

continue collision mode does not prevent rigid bodies from interpenetration instead it prevent bodies from passing trough each others by extrapolating contact points when the bodies normal contact calculation determine the bodies are not colliding.

Remarks

for performance reason the bodies angular velocities is only use on the broad face of the collision, but not on the contact calculation.

Remarks

continue collision does not perform back tracking to determine time of contact, instead it extrapolate contact by incrementally extruding the collision geometries of the two colliding bodies along the linear velocity of the bodies during the time step, if during the extrusion colliding contact are found, a collision is declared and the normal contact resolution is called.

Remarks

for continue collision to be active the continue collision mode must on the material pair of the colliding bodies as well as on at least one of the two colliding bodies.

Remarks

Because there is penalty of about 40% to 80% depending of the shape complexity of the collision geometry, this feature is set off by default. It is the job of the application to determine what bodies need this feature on. Good guidelines are: very small objects, and bodies that move a height speed.

See also

NewtonBodySetContinuousCollisionMode

NewtonMaterialSetDefaultFriction

void NewtonMaterialSetDefaultFriction(
const NewtonWorld* newtonWorld,
int id0,
int id1,
dFloat staticFriction,
dFloat kineticFriction)
Set the default coefficients of friction for the material defined by the interaction between two physics groups.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int id0 | - | group id0
int id1 | - | group id1
dFloat staticFriction | - | static friction coefients
dFloat kineticFriction | - | dynamic coefficient of friction

Return

Nothing.

Remarks

staticFriction and kineticFriction must be positive values. kineticFriction must be lower than staticFriction. It is recommended that staticFriction and kineticFriction be set to a value lower or equal to 1.0, however because some synthetic materials can have higher than one coeficient of friction Newton allows for the coeficient of friction to be as high as 2.0.

NewtonMaterialSetDefaultElasticity

void NewtonMaterialSetDefaultElasticity(
const NewtonWorld* newtonWorld,
int id0,
int id1,
dFloat elasticCoef)
Set the default coefficients of restitution (elasticity) for the material defined by the interaction between two physics groups.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int id0 | - | group id0
int id1 | - | group id1
dFloat elasticCoef | - | static friction coefficients

Return

Nothing.

Remarks

elasticCoef must be a positive value. It is recommended that elasticCoef be set to a value lower or equal to 1.0

NewtonMaterialSetDefaultSoftness

void NewtonMaterialSetDefaultSoftness(
const NewtonWorld* newtonWorld,
int id0,
int id1,
dFloat softnessCoef)
Set the default softness coefficients for the material defined by the interaction between two physics groups.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world
int id0 | - | group id0
int id1 | - | group id1
dFloat softnessCoef | - | softness coefficient

Return

Nothing.

Remarks

softnessCoef must be a positive value. It is recommended that softnessCoef be set to value lower or equal to 1.0 A low value for softnessCoef will make the material soft. A typical value for softnessCoef is 0.15

NewtonMaterialSetCollisionCallback

void NewtonMaterialSetCollisionCallback(
const NewtonWorld* newtonWorld,
int id0,
int id1,
void *userData,
NewtonContactBegin beginCallback,
NewtonContactProcess processCallback,
NewtonContactEnd endCallback)
Set userData and the functions event handlers for the material defined by the interaction between two physics groups.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
int id0 | - | group id0.
int id1 | - | group id1.
void *userData | - | user data value.
NewtonContactBegin beginCallback | - | address of the event function called before contact calculation for collision. This parameter can be NULL.
NewtonContactProcess processCallback | - | address of the event function called for every contact resulting from contact calculation. This parameter can be NULL.
NewtonContactEnd endCallback | - | address of the event function called after all contacts are processed. This parameter can be NULL.

Return

Nothing.

Remarks

When the AABB extend of the collision geometry of two bodies overlap, Newton collision system retrieves the material interaction that defines the behavior between the pair of bodies. The material interaction is collected from a database of materials, indexed by the material gruopID assigned to the bodies. If the material is tagged as non collidable, then no action is taken and the simulation continues. If the material is tagged as collidable, and a beginCallback was set for this material, then the beginCallback function is called. If the function *beginCallback* returns 0, no further action is taken for this material (this can be use to ignore the interaction under certain conditions). If the function *beginCallback* returns 1, Newton proceeds to calculate the array of contacts for the pair of colliding bodies. If the function processCallback was set, the application receives a callback for every contact found between the two colliding bodies. Here the application can perform fine grain control over the behavior of the collision system. For example, rejecting the contact, making the contact frictionless, applying special effects to the surface etc. After all contacts are processed and if the function endCallback was set, Newton calls endCallback. Here the application can collect information gathered during the contact-processing phase and provide some feedback to the player. A typical use for the material callback is to play sound effects. The application passes the address of structure in the userData along with three event function callbacks. When the function beginCallback is called by Newton, the application resets a variable say maximumImpactSpeed. Then for every call to the function processCallback, the application compares the impact speed for this contact with the value of maximumImpactSpeed, if the value is larger, then the application stores the new value along with the position, and any other quantity desired. When the application receives the call to endCallback the application plays a 3d sound based in the position and strength of the contact.

NewtonMaterialGetUserData

Get userData associated with this material.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
int id0 | - | group id0.
int id1 | - | group id1.

Return

Nothing.

Contact behavior control interface

NewtonMaterialDisableContact

void NewtonMaterialDisableContact(const NewtonMaterial* materialHandle)
Disable processing for the contact.

Parameters

const NewtonMaterial materialHandle - pointer to a material pair

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetMaterialPairUserData

void* NewtonMaterialGetMaterialPairUserData(const NewtonMaterial* materialHandle)
Get the userData set by the application when it created this material pair.

Parameters

const NewtonMaterial materialHandle - pointer to a material pair

Return

Application user data.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetContactFaceAttribute

unsigned NewtonMaterialGetContactFaceAttribute(const NewtonMaterial* materialHandle)
Return the face attribute assigned to this face when for a user defined collision or a Newton collision tree.

Parameters

const NewtonMaterial materialHandle - pointer to a material pair

Return

face attribute for collision trees. Zero if the contact was generated by two convex collisions.

Remarks

This function can only be called from a material callback event handler.

Remarks

this function can be used by the application to retrieve the face id of a polygon for a collision tree.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetCurrentTimestep

dFloat NewtonMaterialGetCurrentTimestep(const NewtonMaterial* materialHandle)
Get the current time step.

Parameters

const NewtonMaterial materialHandle - pointer to a material pair

Return

the current time step.

Remarks

This function can only be called from a material callback event handler. The function can be useful for the implementation of powered contacts.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetContactNormalSpeed

dFloat NewtonMaterialGetContactNormalSpeed(
const NewtonMaterial* materialHandle,
const NewtonContact* contactlHandle)
Calculate the speed of this contact along the normal vector of the contact.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair
const NewtonContact contactlHandle | - | pointer to the contact data

Return

Contact speed. A positive value means the contact is repulsive.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetContactTangentSpeed

dFloat NewtonMaterialGetContactTangentSpeed(
const NewtonMaterial* materialHandle,
const NewtonContact* contactlHandle,
int index)
Calculate the speed of this contact along the tangent vector of the contact.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
const NewtonContact contactlHandle | - | pointer to the contact data.
int index | - | index to the tangent vector. This value can be 0 for primary tangent direction or 1 for the secondary tangent direction.

Return

Contact tangent speed.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetContactPositionAndNormal

void NewtonMaterialGetContactPositionAndNormal(
const NewtonMaterial* materialHandle,
dFloat* positPtr,
dFloat* normalPtr)
Get the contact position and normal in global space.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat *positPtr, | - | pointer to an array of at least three floats to hold the contact position.
dFloat *normalPtr | - | pointer to an array of at least three floats to hold the contact normal.

Return

Nothing.

Remarks

This function can only be called from a material callback event handle.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetContactForce

void NewtonMaterialGetContactForce(
const NewtonMaterial* materialHandle,
dFloat* forcePtr)
Get the contact force vector in global space.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat *forcePtr, | - | pointer to an array of at least three floats to hold the force vector in global space.

Return

Nothing.

Remarks

The contact force value is only valid when calculating resting contacts. This means if two bodies collide with non zero relative velocity, the reaction force will be an impulse, which is not a reaction force, this will return zero vector. this function will only return meaningful values when the colliding bodies are at rest.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetContactTangentDirections

void NewtonMaterialGetContactTangentDirections(
const NewtonMaterial* materialHandle,
dFloat* dir0,
dFloat* dir1)
Get the contact tangent vector to the contact point.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat *dir0 | - | pointer to an array of at least three floats to hold the contact primary tangent vector.
dFloat *dir1 | - | pointer to an array of at least three floats to hold the contact secondary tangent vector.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialGetBodyCollisionID

unsigned NewtonMaterialGetBodyCollisionID(
const NewtonMaterial* material,
const NewtonBody* body)
Retrieve a user defined value stored with a convex collision primitive.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
const NewtonBody *bodyPtr | - | is the pointer to the body.

Return

a user defined value. Zero if not id was stored with the collision primitive.

Remarks

the application can store an id with any collision primitive. This id can be used to identify what type of collision primitive generated a contact. This function can only be called from a contact callback,

Remarks

this function can only be called from a contact process callback. If called from contact callback begin this function will crash the application.

See also

NewtonConvexCollisionSetUserID, NewtonCreateBox, NewtonCreateSphere

NewtonMaterialSetContactSoftness

void NewtonMaterialSetContactSoftness(
const NewtonMaterial* materialHandle,
dFloat softness)
Override the default softness value for the contact.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat softness | - | softness value, must be positive.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback, NewtonMaterialSetDefaultSoftness

NewtonMaterialSetContactElasticity

void NewtonMaterialSetContactElasticity(
const NewtonMaterial* materialHandle,
dFloat restitution)
Override the default elasticity (coefficient of restitution) value for the contact.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat restitution | - | elasticity value, must be positive.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback, NewtonMaterialSetDefaultElasticity

NewtonMaterialSetContactFrictionState

void NewtonMaterialSetContactFrictionState(
const NewtonMaterial* materialHandle,
int state,
int index)
Enable or disable friction calculation for this contact.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
int state* | - | new state. 0 makes the contact frictionless along the index tangent vector.
int index | - | index to the tangent vector. 0 for primary tangent vector or 1 for the secondary tangent vector.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialSetContactStaticFrictionCoef

void NewtonMaterialSetContactStaticFrictionCoef(
const NewtonMaterial* materialHandle,
dFloat coef,
int index)
Override the default value of the static coefficient of friction for this contact.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat coef | - | static friction coeficient. Must be positive.
int index | - | index to the tangent vector. 0 for primary tangent vector or 1 for the secondary tangent vector.

Return

nothing

Remarks

this function can only be called from a material callback event handler.

Remarks

It is recommended that coef be set to a value lower or equal to 1.0, however because some synthetic materials can have hight than one coeficient of friction Newton allows for the coeficient of friction to be as high as 2.0.

Remarks

the value coef will be clamped between the current kinetic friction and 2.0 (the maximum friction allowed). If the application wants to set a static friction lower than the current kinetic friction it must decrease the kinetic friction first.

See also

NewtonMaterialSetCollisionCallback, NewtonMaterialSetDefaultFriction, NewtonMaterialSetContactKineticFrictionCoef

NewtonMaterialSetContactKineticFrictionCoef

void NewtonMaterialSetContactKineticFrictionCoef(
const NewtonMaterial* materialHandle,
dFloat coef,
int index)
Override the default value of the kinetic coefficient of friction for this contact.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat coef | - | static friction coefficient. Must be positive.
int index | - | index to the tangent vector. 0 for primary tangent vector or 1 for the secondary tangent vector.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

Remarks

It is recommended that coef be set to a value lower or equal to 1.0, however because some synthetic materials can have hight than one coeficient of friction Newton allows for the coeficient of friction to be as high as 2.0.

Remarks

the value coef will be clamped between 0.01f (minimum friction value) and that of the current static friction. If the application wants to set a kinetic friction higher than the current static friction it must increase the static friction first.

See also

NewtonMaterialSetCollisionCallback, NewtonMaterialSetDefaultFriction, NewtonMaterialSetContactStaticFrictionCoef

NewtonMaterialSetContactNormalAcceleration

void NewtonMaterialSetContactNormalAcceleration(
const NewtonMaterial* materialHandle,
dFloat accel)
Force the contact point to have a non-zero acceleration aligned this the contact normal.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat accel | - | desired contact acceleration, Must be a positive value

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

Remarks

This function can be used for spacial effects like implementing jump, of explosive contact in a call back.

See also

NewtonMaterialSetCollisionCallback

NewtonMaterialSetContactTangentAcceleration

void NewtonMaterialSetContactTangentAcceleration(
const NewtonMaterial* materialHandle,
dFloat accel,
int index)
Force the contact point to have a non-zero acceleration along the surface plane.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
dFloat accel | - | desired contact acceleration.
int index | - | index to the tangent vector. 0 for primary tangent vector or 1 for the secondary tangent vector.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler.

See also

NewtonMaterialSetCollisionCallback, NewtonMaterialContactRotateTangentDirections

NewtonMaterialSetContactNormalDirection

void NewtonMaterialSetContactNormalDirection(
const NewtonMaterial* materialHandle,
const dFloat* direction)
Set the new direction of the for this contact point.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
const dFloat *direction | - | pointer to an array of at least three floats holding the direction vector.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler. This function changes the basis of the contact point to one where the contact normal is alinend to the new direction vector and the tangent direction are recalculated to be perpendicular to teh new contact normal.

Remarks

In 99.9% of the cases the collision system can calculates a very good contact normal. however this algorithm that calculate the contact normal use as criteria the normal direction that will resolve the interpenetration with the least amount on motion. There are situations however when this solution is not the best. Take for example a rolling ball over a texelated floor, when the ball is over a flat polygon, the contact normal is always perpendicular to the floor and pass by the origin of the sphere, however when the sphere is going across two adjacent polygons, the contact normal is now perpendicular to the polygons edge and this does not guarantee they it will pass bay the origin of the sphere, but we know that the best normal is always the one passing by the origin of the sphere.

See also

NewtonMaterialSetCollisionCallback, NewtonMaterialContactRotateTangentDirections

NewtonMaterialContactRotateTangentDirections

void NewtonMaterialContactRotateTangentDirections(
const NewtonMaterial* materialHandle,
const dFloat* alignVector)
Rotate the tangent direction of the contacts until the primary direction is aligned with the alignVector.

Parameters

const NewtonMaterial materialHandle | - | pointer to a material pair.
const dFloat *alignVector | - | pointer to an array of at least three floats holding the aligning vector.

Return

Nothing.

Remarks

This function can only be called from a material callback event handler. This function rotates the tangent vectors of the contact point until the primary tangent vector and the align vector are perpendicular (ex. when the dot product between the primary tangent vector and the alignVector is 1.0). This function can be used in conjunction with NewtonMaterialSetContactTangentAcceleration in order to create special effects. For example, conveyor belts, cheap low lod vehicles, slippery surfaces, etc.

See also

NewtonMaterialSetCollisionCallback, NewtonMaterialSetContactNormalDirection

Convex collision primitives interface

NewtonCreateNull

NewtonCollision* NewtonCreateNull(const NewtonWorld* newtonWorld)
Create a transparent collision primitive.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world.

Return

Pointer to the collision object.

Remarks

Some times the application needs to create helper rigid bodies that will never collide with other bodies, for example the neck of a rag doll, or an internal part of an articulated structure. This can be done by using the material system but it too much work and it will increase unnecessarily the material count, and therefore the project complexity. The Null collision is a collision object that satisfy all this conditions without having to change the engine philosophy.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the objects. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used by the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision

NewtonCreateBox

NewtonCollision* NewtonCreateBox(
const NewtonWorld* newtonWorld,
dFloat dx,
dFloat dy,
dFloat dz,
const dFloat *offsetMatrix)
Create a box primitive for collision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat dx | - | box side one x dimension.
dFloat dy | - | box side one y dimension.
dFloat dz | - | box side one z dimension.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body.

Return

Pointer to the box

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision, NewtonCreateConvexHullModifier

NewtonCreateSphere

NewtonCollision* NewtonCreateSphere(
const NewtonWorld* newtonWorld,
dFloat radiusX,
dFloat radiusY,
dFloat radiusZ,
const dFloat *offsetMatrix)
Create a generalized ellipsoid primitive..

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat radiusX | - | sphere radius along x axis.
dFloat radiusY | - | sphere radius along x axis.
dFloat radiusZ | - | sphere radius along x axis.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix of the sphere relative to the body. If this parameter is NULL then the sphere is centered at the origin of the body.

Return

Pointer to the generalized sphere.

Remarks

Sphere collision are generalized ellipsoids, the application can create many different kind of objects by just playing with dimensions of the radius. for example to make a sphere set all tree radius to the same value, to make a ellipse of revolution just set two of the tree radius to the same value.

Remarks

General ellipsoids are very good hull geometries to represent the outer shell of avatars in a game.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision, NewtonCreateConvexHullModifier

NewtonCreateCone

NewtonCollision* NewtonCreateCone(
const NewtonWorld* newtonWorld,
dFloat radius,
dFloat height,
const dFloat *offsetMatrix)
Create a cone primitive for collision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat radius | - | cone radius at the base.
dFloat height | - | cone height along the x local axis from base to tip.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body.

Return

Pointer to the box

Remark

the cone height must equal of larger than the sum of the cap radius. if this is not the case the height will be clamped the 2 * radius.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision, NewtonCreateConvexHullModifier

NewtonCreateCapsule

NewtonCollision* NewtonCreateCapsule(
const NewtonWorld* newtonWorld,
dFloat radius,
dFloat height,
const dFloat *offsetMatrix)
Create a capsule primitive for collision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat radius | - | capsule radius at the base.
dFloat height | - | capsule height along the x local axis from tip to tip.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body.

Return

Pointer to the box

Remark

the capsule height must equal of larger than the sum of the cap radius. If this is not the case the height will be clamped the 2 * radius.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision, NewtonCreateConvexHullModifier

NewtonCreateCylinder

NewtonCollision* NewtonCreateCylinder(
const NewtonWorld* newtonWorld,
dFloat radius,
dFloat height,
const dFloat *offsetMatrix)
Create a cylinder primitive for collision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat radius | - | cylinder radius at the base.
dFloat height | - | cylinder height along the x local axis.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body.

Return

Pointer to the box

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision, NewtonCreateConvexHullModifier

NewtonCreateChamferCylinder

NewtonCollision* NewtonCreateChamferCylinder(
const NewtonWorld* newtonWorld,
dFloat radius,
dFloat height,
const dFloat *offsetMatrix)
Create a ChamferCylinder primitive for collision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat radius | - | ChamferCylinder radius at the base.
dFloat height | - | ChamferCylinder height along the x local axis.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body.

Return

Pointer to the box

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision, NewtonCreateConvexHullModifier

NewtonCreateConvexHull

NewtonCollision* NewtonCreateConvexHull(
const NewtonWorld* newtonWorld,
int count,
dFloat* vertexCloud,
int strideInBytes,
dFloat *offsetMatrix)
Create a ConvexHull primitive for collision from a cloud of points.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat count | - | number of consecutive point to follow must be at least 4.
dFloat vertexCloud | - | pointer to and array of point.
dFloat strideInBytes | - | vertex size in bytes, must be at least 12.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body.

Return

Pointer to the box

Remarks

Convex hulls are the solution to collision primitive that can not be easily represented by and implicit solid. The implicit solid primitives (spheres, cubes, cylinders, capsules, cones, etc.), have constant time complexity for contact calculation and are also extremely efficient on memory usage, therefore the application get perfect smooth behavior. However for cases where the shape is too difficult or a polygonal representation is desired convex hulls are the ultimate solution. For example it is a mistake to model a 10000 point sphere as a convex hull, when the perfect sphere is available.

Remarks

There is not upper limit as to how many vertex the application can pass to Newton to make a hull shape, however for performance and memory usage concern it is the application responsibility to keep the max vertex at the possible minimum. The minimum number of vertex should be equal or larger than 4 and it is the application responsibility that the points are part of a solid geometry. Unpredictable results will occur if all points happen to be collinear or coplanar.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision, NewtonCreateConvexHullModifier

NewtonCreateConvexHullModifier

NewtonCollision* NewtonCreateConvexHullModifier(
const NewtonWorld* newtonWorld,
const NewtonCollision* convexHullCollision)
Create a collision modifier for any convex collision part.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world. NewtonCollision convexHullCollision.

Return

Pointer to the collision modifier

Remarks

The matrix should be arranged in row-major order (this is the way directX stores matrices). a collision modifier can take any type of transformation matrix, as long as the matrix can be invertible by straight Gaussian elimination process. Typical uses are non-uniform scaling, translation and skewing.

Remarks

Collision modifier can be used by the application to achieve effects like animating collision geometry at run time, however care must taken as animation of a collision primitive could result in unwanted penetrations.

See also

NewtonReleaseCollision, NewtonConvexHullModifierSetMatrix, NewtonConvexHullModifierGetMatrix

NewtonConvexHullModifierGetMatrix

Get the transformation matrix of a convex hull modifier collision.

Parameters

const NewtonCollision *convexHullModifier | - | pointer to the body.
dFloat *matrixPtr | - | pointer to an array of 16 floats containing the global matrix of the collision modifier.

Return

Nothing.

Remarks

The matrix should be arranged in row-major order (this is the way directX stores matrices). a collision modifier can take any type of transformation matrix, as long as the matrix can be invertible by straight Gaussian elimination process. Typical uses are non-uniform scaling, translation and skewing.

Remarks

Collision modifier can be used by the application to achieve effects like animating collision geometry at run time, however care must taken as animation of a collision primitive could result into unwanted penetrations.

See also

NewtonCreateConvexHullModifier, NewtonConvexHullModifierSetMatrix

NewtonConvexHullModifierSetMatrix

void NewtonConvexHullModifierSetMatrix(
const NewtonCollision* convexHullModifier,
const dFloat* matrixPtr)
Set the transformation matrix of a convex hull modifier collision.

Parameters

const NewtonCollision *convexHullModifier | - | pointer to the body.
const dFloat *matrixPtr | - | pointer to an array of 16 floats containing the global matrix of the collision modifier.

Return

Nothing.

Remarks

The matrix should be arranged in row-major order (this is the way directX stores matrices). a collision modifier can take any type of transformation matrix, as long as the matrix can be invertible by straight Gaussian elimination process. Typical uses are non-uniform scaling, translation and skewing.

Remarks

Collision modifier can be used by the application to achieve effects like animating collision geometry at run time, however care must taken as animation of a collision primitive could result into unwanted penetrations.

See also

NewtonCreateConvexHullModifier, NewtonConvexHullModifierGetMatrix

NewtonCreateCompoundCollision

NewtonCollision* NewtonCreateCompoundCollision(
const NewtonWorld* newtonWorld,
int count,
NewtonCollision* const collisionPrimitiveArray[])
Create a container to hold an array of convex collision primitives.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
int count | - | number of primitives in the array.
const NewtonCollision **collisionPrimitiveArray | - | pointer to an array of convex collision primitives. This array must be filled with convex collision primitives before this function is called.

Return

Pointer to the compound collision.

Remarks

Compound collision primitives can only be made of convex collision primitives and they can not contain compound collision. Therefore they are treated as convex primitives.

Remarks

Compound collision primitives are treated as instance collision objects that can not shared by multiples rigid bodies.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks.

See also

NewtonReleaseCollision

NewtonConvexCollisionSetUserID

void NewtonConvexCollisionSetUserID(
const NewtonCollision* convexCollision,
unsigned id)
Store a user defined value with a convex collision primitive.

Parameters

const NewtonCollision convexCollision | - | is the pointer to a convex collision primitive.
unsigned id | - | value to store with the collision primitive.

Return

nothing

Remarks

the application can store an id with any collision primitive. This id can be used to identify what type of collision primitive generated a contact.

See also

NewtonMaterialGetBodyCollisionID, NewtonConvexCollisionGetUserID, NewtonCreateBox, NewtonCreateSphere

NewtonConvexCollisionGetUserID

unsigned NewtonConvexCollisionGetUserID(const NewtonCollision* convexCollision)
Return a user define value with a convex collision primitive.

Parameters

const NewtonCollision convexCollision - is the pointer to a convex collision primitive.

Return

user id

Remarks

the application can store an id with any collision primitive. This id can be used to identify what type of collision primitive generated a contact.

See also

NewtonMaterialGetBodyCollisionID, NewtonMaterialGetBodyCollisionID, NewtonCreateBox, NewtonCreateSphere

NewtonConvexCollisionCalculateVolume

dFloat NewtonConvexCollisionCalculateVolume(const NewtonCollision* convexCollision)
calculate the total volume defined by a convex collision geometry.

Parameters

const NewtonCollision *convexCollision - pointer to the collision.

Return

collision geometry volume. This function will return zero if the body collision geometry is no convex.

Remarks

The total volume calculated by the function is only an approximation of the ideal volume. This is not an error, it is a fact resulting from the polygonal representation of convex solids.

Remarks

This function can be used to assist the application in calibrating features like fluid density weigh factor when calibrating buoyancy forces for more realistic result.

See also

NewtonBodyAddBuoyancyForce

NewtonConvexCollisionCalculateInertialMatrix

void NewtonConvexCollisionCalculateInertialMatrix(
const NewtonCollision* convexCollision,
dFloat* inertia,
dFloat* origin)
Calculate the three principal axis and the the values of the inertia matrix of a convex collision objects.

Parameters

const NewtonCollision convexCollision | - | is the pointer to a convex collision primitive.
dFloat *inertia | - | pointer to and array of a least 3 floats to hold the values of the principal inertia.
dFloat *origin | - | pointer to and array of a least 3 floats to hold the values of the center of mass for the principal inertia.

Remarks

This function calculate a general inertial matrix for arbitrary convex collision including compound collisions.

See also

NewtonBodySetMassMatrix, NewtonBodyGetMassMatrix, NewtonBodySetCentreOfMass, NewtonBodyGetCentreOfMass

Complex collision primitives interface

NewtonCreateUserMeshCollision

NewtonCollision* NewtonCreateUserMeshCollision(
const NewtonWorld* newtonWorld,
const dFloat *minBox,
const dFloat *maxBox,
void *userData,
NewtonUserMeshCollisionCollideCallback collideCallback,
NewtonUserMeshCollisionRayHitCallback rayHitCallBack,
NewtonUserMeshCollisionDestroyCallback destroyCallback)
Create a complex collision geometry to be controlled by the application.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const dFloat *minBox | - | pointer to an array of at least three floats to hold minimum value for the box relative to the collision.
const dFloat *maxBox | - | pointer to an array of at least three floats to hold maximum value for the box relative to the collision.
void *userData | - | pointer to user data to be used as context for event callback.
NewtonUserMeshCollisionCollideCallback collideCallback | - | pointer to an event function for providing Newton with the polygon inside a given box region.
NewtonUserMeshCollisionRayHitCallback rayHitCallBack | - | pointer to an event function for providing Newton with ray intersection information.
NewtonUserMeshCollisionDestroyCallback destroyCallback | - | pointer to an event function for destroying any data allocated for use by the application.

Return

Pointer to the user collision.

Remarks

UserMeshCollision provides the application with a method of overloading the built-in collision system for background objects. UserMeshCollision can be used for implementing collisions with height maps, collisions with BSP, and any other collision structure the application supports and wishes to preserve. However, UserMeshCollision can not take advantage of the efficient and sophisticated algorithms and data structures of the built-in TreeCollision. We suggest you experiment with both methods and use the method best suited to your situation.

Remarks

When a UserMeshCollision is assigned to a body, the mass of the body is ignored in all dynamics calculations. This make the body behave as a static body.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well as speed up some calculations.

See also

NewtonReleaseCollision

NewtonCreateTreeCollision

NewtonCollision* NewtonCreateTreeCollision(
const NewtonWorld* newtonWorld,
NewtonTreeCollisionCallback userCallback)
Create an empty complex collision geometry tree.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
NewtonTreeCollisionCallback *userCallback | - | pointer to an event function to call before Newton evaluates the polygons colliding with a body. This parameter can be NULL.

Return

Pointer to the collision tree.

Remarks

TreeCollision is the preferred method within Newton for collision with polygonal meshes of arbitrary complexity. The mesh must be made of flat non-intersecting polygons, but they do not explicitly need to be triangles. TreeCollision can be serialized by the application to/from an arbitrary storage device.

Remarks

When a TreeCollision is assigned to a body the mass of the body is ignored in all dynamics calculations. This makes the body behave as a static body.

Remarks

Collision primitives are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks. Collision primitives can be reused with more than one body. This will reduce the amount of memory used by the engine, as well as speed up some calculations.

See also

NewtonTreeCollisionBeginBuild, NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild, NewtonTreeCollisionSerialize, NewtonCreateTreeCollisionFromSerialization, NewtonTreeCollisionGetFaceAtribute, NewtonTreeCollisionSetFaceAtribute, NewtonReleaseCollision

NewtonTreeCollisionBeginBuild

void NewtonTreeCollisionBeginBuild(const NewtonCollision* treeCollision)
Prepare a TreeCollision to begin to accept the polygons that comprise the collision mesh.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world.

Return

Nothing.

See also

NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild

NewtonTreeCollisionAddFace

void NewtonTreeCollisionAddFace(
const NewtonCollision* treeCollision,
int vertexCount,
const dFloat* vertexPtr,
int strideInBytes,
int faceAttribute)
Add an individual polygon to a TreeCollision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
int vertexCount | - | number of vertex in vertexPtr
const dFloat *vertexPtr | - | pointer to an array of vertex. The vertex should consist of at least 3 floats each.
int strideInBytes | - | size of each vertex in bytes. This value should be 12 or larger.
int faceAttribute | - | id that identifies the polygon. The application can use this value to customize the behavior of the collision geometry.

Return

Nothing.

Remarks

After the call to NewtonTreeCollisionBeginBuild the TreeCollision is ready to accept polygons. The application should iterate through the application's mesh, adding the mesh polygons to the TreeCollision one at a time. The polygons must be flat and non-self intersecting.

See also

NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild

NewtonTreeCollisionEndBuild

void NewtonTreeCollisionEndBuild(
const NewtonCollision* treeCollision,
int optimize)
Finalize the construction of the polygonal mesh.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
int optimize | - | flag that indicates to Newton whether it should optimize this mesh. Set to 1 to optimize the mesh, otherwise 0.

Return

Nothing.

Remarks

After the application has finished adding polygons to the TreeCollision, it must call this function to finalize the construction of the collision mesh. If concave polygons are added to the TreeCollision, the application must call this function with the parameter optimize set to 1. With the optimize parameter set to 1, Newton will optimize the collision mesh by removing non essential edges from adjacent flat polygons. Newton will not change the topology of the mesh but significantly reduces the number of polygons in the mesh. The reduction factor of the number of polygons in the mesh depends upon the irregularity of the mesh topology. A reduction factor of 1.5 to 2.0 is common. Calling this function with the parameter optimize set to zero, will leave the mesh geometry unaltered.

See also

NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild

NewtonTreeCollisionSerialize

void NewtonTreeCollisionSerialize(
const NewtonCollision* treeCollision,
NewtonSerialize callback,
void* serializeHandle)
Serialize a TreeCollision.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
NewtonSerialize callback | - | pointer to the event function that will do the serialization.
void *serializeHandle | - | user data that will be passed to the NewtonSerialize callback.

Return

Nothing.

Remarks

Small and medium size TreeCollision objects (under 50000 polygons) can be constructed at application startup without significant processing overhead. However, for very large polygons sets (over 50000 polygons) it is recommended that the application use NewtonCreateTreeCollision in an off-line tool. Then the application can call this function to store the TreeCollision to a file or any file packer system the application is using. At run time the application can use the function NewtonCreateTreeCollisionFromSerialization to create and load a pre-made TreeCollision

See also

NewtonCreateTreeCollisionFromSerialization

NewtonCreateTreeCollisionFromSerialization

NewtonCollision* NewtonCreateTreeCollisionFromSerialization(
const NewtonWorld* newtonWorld,
NewtonTreeCollisionCallback userCallback,
NewtonDeserialize deserializeFunction,
void* serializeHandle)
Create a tree collision and load the polygon mesh via a serialization function.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
NewtonTreeCollisionCallback *userCallback | - | pointer to an event function to call before Newton is begins collecting polygons that are colliding with a body. This parameter can be NULL.
NewtonSerialize callback | - | pointer to the callback function that will handle the serialization.
void *userData | - | user data that will be passed as the argument to NewtonSerialize callback.

Return

Nothing.

Remarks

Small and medium size TreeCollision objects (under 50000 polygons) can be constructed at application startup without significant processing overhead. However, for very large polygons sets (over 50000 polygons) it is recommended that the application use NewtonCreateTreeCollision in an off-line tool. Then the application can call this function to store the TreeCollision to a file or any file packer system the application is using. At run time the application can use the function NewtonCreateTreeCollisionFromSerialization to create and load a pre-made TreeCollision

See also

NewtonTreeCollisionSerialize, NewtonReleaseCollision

NewtonTreeCollisionGetFaceAtribute

int NewtonTreeCollisionGetFaceAtribute(
const NewtonCollision* treeCollision,
const int* faceIndexArray)
Get the user defined collision attributes stored with each face of the collision mesh.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const int *faceIndexArray | - | pointer to the face index list passed to the function NewtonTreeCollisionCallback userCallback

Return

User id of the face.

Remarks

This function is used to obtain the user data stored in faces of the collision geometry. The application can use this user data to achieve per polygon material behavior in large static collision meshes.

See also

NewtonTreeCollisionSetFaceAtribute, NewtonCreateTreeCollision, NewtonCreateTreeCollisionFromSerialization

NewtonTreeCollisionSetFaceAtribute

void NewtonTreeCollisionSetFaceAtribute(
const NewtonCollision* treeCollision,
const int* faceIndexArray,
int attribute)
Change the user defined collision attribute stored with faces of the collision mesh.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const int *faceIndexArray | - | pointer to the face index list passed to the function NewtonTreeCollisionCallback userCallback
int attribute | - | value of the user defined attribute to be stored with the face.

Return

User id of the face.

Remarks

This function is used to obtain the user data stored in faces of the collision geometry. The application can use this user data to achieve per polygon material behavior in large static collision meshes. By changing the value of this user data the application can achieve modifiable surface behavior with the collision geometry. For example, in a driving game, the surface of a polygon that represents the street can changed from pavement to oily or wet after some collision event occurs.

See also

NewtonTreeCollisionGetFaceAtribute, NewtonCreateTreeCollision, NewtonCreateTreeCollisionFromSerialization

Generic collision library functions

NewtonCollisionPointDistance

int NewtonCollisionPointDistance(
const NewtonWorld* newtonWorld,
const float *point,
const NewtonCollision* collision,
const dFloat* matrix,
dFloat* contact,
dFloat* normal)
Calculate the closest point between a point and convex collision primitive.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
dFloat *point | - | pointer to and array of a least 3 floats representing the origin.
const NewtonCollision *collision | - | pointer to collision primitive.
const dFloat *matrix | - | pointer to an array of 16 floats containing the offset matrix of collision primitiveA.
dFloat *contact | - | pointer to and array of a least 3 floats to contain the closest point to collisioA.
dFloat *normal | - | pointer to and array of a least 3 floats to contain the separating vector normal.

Return

one if the two bodies are disjoint and the closest point could be found, zero if the point is inside the convex primitive.

Remarks

This function can be used as a low-level building block for a stand-alone collision system. Applications that have already there own physics system, and only want and quick and fast collision solution, can use Newton advanced collision engine as the low level collision detection part. To do this the application only needs to initialize Newton, create the collision primitives at application discretion, and just call this function when the objects are in close proximity. Applications using Newton as a collision system only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. Also the application should implement their own trivial aabb test, before calling this function .

Remarks

the current implementation of this function do work on collision trees, or user define collision.

See also

NewtonCollisionCollideContinue, NewtonCollisionClosestPoint, NewtonCollisionCollide, NewtonCollisionRayCast, NewtonCollisionCalculateAABB

NewtonCollisionClosestPoint

int NewtonCollisionClosestPoint(
const NewtonWorld* newtonWorld,
const NewtonCollision* collisionA,
const dFloat* matrixA,
const NewtonCollision* collisionB,
const dFloat* matrixB,
dFloat* contactA,
dFloat* contactB,
dFloat* normalAB)
Calculate the closest points between two disjoint convex collision primitive.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *collisionA | - | pointer to collision primitive A.
const dFloat *matrixA | - | pointer to an array of 16 floats containing the offset matrix of collision primitiveA.
const NewtonCollision *collisionB | - | pointer to collision primitive B.
const dFloat *matrixB | - | pointer to an array of 16 floats containing the offset matrix of collision primitiveB.
dFloat *contactA | - | pointer to and array of a least 3 floats to contain the closest point to collisionA.
dFloat *contactB | - | pointer to and array of a least 3 floats to contain the closest point to collisionB.
dFloat *normalAB | - | pointer to and array of a least 3 floats to contain the separating vector normal.

Return

one if the tow bodies are disjoint and he closest point could be found, zero if the two collision primitives are intersecting.

Remarks

This function can be used as a low-level building block for a stand-alone collision system. Applications that have already there own physics system, and only want and quick and fast collision solution, can use Newton advanced collision engine as the low level collision detection part. To do this the application only needs to initialize Newton, create the collision primitives at application discretion, and just call this function when the objects are in close proximity. Applications using Newton as a collision system only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. Also the application should implement their own trivial aabb test, before calling this function .

Remarks

the current implementation of this function does not work on collision trees, or user define collision.

See also

NewtonCollisionCollideContinue, NewtonCollisionPointDistance, NewtonCollisionCollide, NewtonCollisionRayCast, NewtonCollisionCalculateAABB

NewtonCollisionCollide

int NewtonCollisionCollide(
const NewtonWorld* newtonWorld,
int maxSize,
const NewtonCollision* collisionA,
const dFloat* matrixA,
const NewtonCollision* collisionB,
const dFloat* matrixB,
dFloat* contacts,
dFloat* normals,
dFloat* penetration)
Calculate contact points between two collision primitive.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
int maxSize | - | size of maximum number of elements in contacts, normals, and penetration.
const NewtonCollision *collisionA | - | pointer to collision primitive A.
const dFloat *matrixA | - | pointer to an array of 16 floats containing the offset matrix of collision primitiveA.
const NewtonCollision *collisionB | - | pointer to collision primitive B.
const dFloat *matrixB | - | pointer to an array of 16 floats containing the offset matrix of collision primitiveB.
dFloat *contacts | - | pointer to and array of a least 3 times maxSize floats to contain the collision contact points.
dFloat *normals | - | pointer to and array of a least 3 times maxSize floats to contain the collision contact normals.
dFloat *penetration | - | pointer to and array of a least maxSize floats to contain the collision penetration at each contact.

Return

the number of contact points.

Remarks

This function can be used as a low-level building block for a stand-alone collision system. Applications that have already there own physics system, and only want and quick and fast collision solution, can use Newton advanced collision engine as the low level collision detection part. To do this the application only needs to initialize Newton, create the collision primitives at application discretion, and just call this function when the objects are in close proximity. Applications using Newton as a collision system only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. Also the application should implement their own trivial aabb test, before calling this function .

See also

NewtonCollisionCollideContinue, NewtonCollisionClosestPoint, NewtonCollisionPointDistance, NewtonCollisionRayCast, NewtonCollisionCalculateAABB

NewtonCollisionCollideContinue

int NewtonCollisionCollideContinue(
const NewtonWorld* newtonWorld,
int maxSize,
const dFloat timestep,
const NewtonCollision* collisionA,
const dFloat* matrixA,
const dFloat* velocA,
const dFloat* omegaA,
const NewtonCollision* collisionB,
const dFloat* matrixB,
const dFloat* velocB,
const dFloat* omegaB,
dFloat* timeOfImpact,
dFloat* contacts,
dFloat* normals,
dFloat* penetration)
Calculate time of impact of impact and contact points between two collision primitive.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
int maxSize | - | size of maximum number of elements in contacts, normals, and penetration.
const dFloat timestep | - | maximum time interval consided for the continue collision claculation.
const NewtonCollision *collisionA | - | pointer to collision primitive A.
const dFloat *matrixA | - | pointer to an array of 16 floats containing the offset matrix of collision primitiveA.
const dFloat *velocA | - | pointer to and array of a least 3 times maxSize floats containing the linear velocity of collision primitiveA.
const dFloat *omegaA | - | pointer to and array of a least 3 times maxSize floats containing the angular velocity of collision primitiveA.
const NewtonCollision *collisionB | - | pointer to collision primitive B.
const dFloat *matrixB | - | pointer to an array of 16 floats containing the offset matrix of collision primitiveB.
const dFloat *velocB | - | pointer to and array of a least 3 times maxSize floats containing the linear velocity of collision primitiveB.
const dFloat *omegaB | - | pointer to and array of a least 3 times maxSize floats containing the angular velocity of collision primitiveB.
dFloat *timeOfImpact | - | pointer to least 1 float variable to contain the time of the intersection.
dFloat *contacts | - | pointer to and array of a least 3 times maxSize floats to contain the collision contact points.
dFloat *normals | - | pointer to and array of a least 3 times maxSize floats to contain the collision contact normals.
dFloat *penetration | - | pointer to and array of a least maxSize floats to contain the collision penetration at each contact.

Return

the number of contact points.

Remarks

by passing zero as maxSize not contact will be calculated and the function will just determine the time of impact is any.

Remarks

if the body are interpenetrating the time of impact will be zero.

Remarks

if the bodies do not collide time of impact will be set to timestep

Remarks

This function can be used as a low-level building block for a stand-alone collision system. Applications that have already there own physics system, and only want and quick and fast collision solution, can use Newton advanced collision engine as the low level collision detection part. To do this the application only needs to initialize Newton, create the collision primitives at application discretion, and just call this function when the objects are in close proximity. Applications using Newton as a collision system only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. Also the application should implement their own trivial aabb test, before calling this function .

See also

NewtonCollisionCollide, NewtonCollisionClosestPoint, NewtonCollisionPointDistance, NewtonCollisionRayCast, NewtonCollisionCalculateAABB

NewtonCollisionRayCast

dFloat NewtonCollisionRayCast(
const NewtonCollision* collisionPtr,
const dFloat* p0,
const dFloat* p1,
dFloat* normal,
int* attribute)
Ray cast specific collision object.

Parameters

const NewtonCollision *collisionPtr | - | pointer to the collision object.
dFloat *p0 | - | pointer to an array of at least three floats representing the ray origin in the local space of the geometry.
dFloat *p1 | - | pointer to an array of at least three floats representing the ray end in the local space of the geometry.
dFloat *normal | - | pointer to an array of at least three floats to hold the normal at the intersection point.
int *attribute | - | pointer to an array of at least one floats to hold the ID of the face hit by the ray.

Return

the parametric value of the intersection, between 0.0 and 1.0, an value larger than 1.0 if the ray miss.

Remarks

This function is intended for applications using newton collision system separate from the dynamics system, also for applications implementing any king of special purpose logic like sensing distance to another object.

Remarks

the ray most be local to the collisions geometry, for example and application ray casting the collision geometry of of a rigid body, must first take the points p0, and p1 to the local space of the rigid body by multiplying the points by the inverse of he rigid body transformation matrix.

See also

NewtonCollisionClosestPoint, NewtonCollisionPointDistance, NewtonCollisionCollide, NewtonCollisionCalculateAABB

NewtonCollisionCalculateAABB

void NewtonCollisionCalculateAABB(
const NewtonCollision* collisionPtr,
const dFloat offsetMatrix,
dFloat p0,
dFloat* p1)
Calculate an axis-aligned bounding box for this collision, the box is calculated relative to offsetMatrix.

Parameters

const NewtonCollision *collisionPtr | - | pointer to the collision object.
const dFloat *offsetMatrix | - | pointer to an array of 16 floats containing the offset matrix used as the coordinate system and center of the AABB.
dFloat *p0 | - | pointer to an array of at least three floats to hold minimum value for the AABB.
dFloat *p1 | - | pointer to an array of at least three floats to hold maximum value for the AABB.

Return

Nothing.

See also

NewtonCollisionClosestPoint, NewtonCollisionPointDistance, NewtonCollisionCollide, NewtonCollisionRayCast

NewtonCollisionMakeUnique

void NewtonCollisionMakeUnique(
const NewtonWorld* newtonWorld,
const NewtonCollision* collisionPtr)
Convert a collision primitive to a unique instance by removing it for the collision cache.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *collisionPtr | - | pointer to the collision object

Return

Nothing.

Remarks

This function will not make preexisting collision object unique instances, so for best result this function should be call immediately after the creation of the collision object.

Remarks

Collision objects are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks.

NewtonReleaseCollision

void NewtonReleaseCollision(
const NewtonWorld* newtonWorld,
const NewtonCollision* collisionPtr)
Release a reference from this collision object returning control to Newton.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *collisionPtr | - | pointer to the collision object

Return

Nothing.

Remarks

Collision objects are reference counted objects. The application should call NewtonReleaseCollision in order to release references to the object. Neglecting to release references to collision primitives is a common cause of memory leaks.

Transform utility functions

NewtonGetEulerAngle

void NewtonGetEulerAngle(
const dFloat* matrix,
dFloat* angles)
Get the three Euler angles from a 4x4 rotation matrix arranged in row-major order.

Parameters

const dFloat matrix | - | pointer to the 4x4 rotation matrix.
dFloat angles | - | pointer to an array of at least three floats to hold the Euler angles.

Return

Nothing.

Remarks

The motivation for this function is that many graphics engines still use Euler angles to represent the orientation of graphics entities. The angles are expressed in radians and represent:

angle[0] | - | rotation about first matrix row
angle[1] | - | rotation about second matrix row
angle[2] | - | rotation about third matrix row

See also

NewtonSetEulerAngle

NewtonSetEulerAngle

void NewtonSetEulerAngle(
const dFloat* angles,
dFloat* matrix)
Build a rotation matrix from the Euler angles in radians.

Parameters

dFloat matrix | - | pointer to the 4x4 rotation matrix.
const dFloat angles | - | pointer to an array of at least three floats to hold the Euler angles.

Return

Nothing.

Remarks

The motivation for this function is that many graphics engines still use Euler angles to represent the orientation of graphics entities. The angles are expressed in radians and represent:

angle[0] | - | rotation about first matrix row
angle[1] | - | rotation about second matrix row
angle[2] | - | rotation about third matrix row

See also

NewtonGetEulerAngle

Rigid body interface

NewtonCreateBody

NewtonBody* NewtonCreateBody(
const NewtonWorld* newtonWorld,
const NewtonCollision* collisionPtr)
Create a rigid body.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *collisionPtr | - | pointer to the collision object.

Return

Pointer to the rigid body.

Remarks

This function creates a Newton rigid body and assigns a collisionPtr as the collision geometry representing the rigid body. This function increments the reference count of the collision geometry. All event functions are set to NULL and the material gruopID of the body is set to the default GroupID.

See also

NewtonDestroyBody

NewtonDestroyBody

void NewtonDestroyBody(
const NewtonWorld* newtonWorld,
const NewtonBody* bodyPtr)
Destroy a rigid body.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonBody *bodyPtr | - | pointer to the body to be destroyed.

Return

Nothing.

Remarks

If this function is called from inside a simulation step the destruction of the body will be delayed until end of the time step. This function will decrease the reference count of the collision geometry by one. If the reference count reaches zero, then the collision geometry will be destroyed. This function will destroy all joints associated with this body.

See also

NewtonCreateBody

NewtonBodySetUserData

void NewtonBodySetUserData(
const NewtonBody* bodyPtr,
void* userDataPtr)
Store a user defined data value with the body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
void *userDataPtr | - | pointer to the user defined user data value.

Return

Nothing.

Remarks

The application can store a user defined value with the Body. This value can be the pointer to a structure containing some application data for special effect. if the application allocate some resource to store the user data, the application can register a joint destructor to get rid of the allocated resource when the body is destroyed

See also

NewtonBodyGetUserData, NewtonBodySetDestructorCallback

NewtonBodyGetUserData

void* NewtonBodyGetUserData(const NewtonBody* bodyPtr)
Retrieve a user defined data value stored with the body.

Parameters

const NewtonBody *bodyPtr - pointer to the body.

Return

The user defined data.

Remarks

The application can store a user defined value with a rigid body. This value can be the pointer to a structure which is the graphical representation of the rigid body.

See also

NewtonBodySetUserData

NewtonBodyGetWorld

NewtonWorld* NewtonBodyGetWorld(const NewtonBody* bodyPtr)
Retrieve get the pointer to the world from the body.

Parameters

const NewtonBody *bodyPtr - pointer to the body.

Return

the world that own this body.

Remarks

The application can use this function to determine what world own this body. If the application have to get the world from a joint, it can do so by getting one of the bodies attached to the joint and getting the world from that body.

NewtonBodySetTransformCallback

void NewtonBodySetTransformCallback(
const NewtonBody* bodyPtr,
NewtonSetTransform callback)
Assign a transformation event function to the body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
NewtonSetTransform callback | - | pointer to a function callback in used to update the transformation matrix of the visual object that represents the rigid body.

Return

Nothing.

Remarks

The function NewtonSetTransform callback is called by the Newton engine every time a visual object that represents the rigid body has changed. The application can obtain the pointer user data value that points to the visual object. The Newton engine does not call the NewtonSetTransform callback function for bodies that are inactive or have reached a state of stable equilibrium.

Remarks

The matrix should be organized in row-major order (this is the way directX stores matrices). If you are using OpenGL matrices (column-major) you will need to transpose the matrices into a local array, before you pass them to Newton.

See also

NewtonBodyGetUserData, NewtonBodyGetUserData

NewtonBodySetAutoactiveCallback

void NewtonBodySetAutoactiveCallback(
const NewtonBody* bodyPtr,
NewtonBodyActivationState callback)
Assign an activation/deativation callback function.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
NewtonBodyActivationStatem callback | - | pointer to a function callback is used to be called when the body is about to be activated or deactivated.

Return

Nothing.

Remarks

this function sets an activation and deactivation callback with the body. The application can use this method to implement advanced scene management control.

NewtonBodySetForceAndTorqueCallback

void NewtonBodySetForceAndTorqueCallback(
const NewtonBody* bodyPtr,
NewtonApplyForceAndTorque callback)
Assign an event function for applying external force and torque to a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
NewtonApplyForceAndTorque callback | - | pointer to a function callback used to apply force and torque to a rigid body.

Return

Nothing.

Remarks

Before the NewtonApplyForceAndTorque callback is called for a body, Newton first clears the net force and net torque for the body.

Remarks

The function NewtonApplyForceAndTorque callback is called by the Newton Engine every time an active body is going to be simulated. The Newton Engine does not call the NewtonApplyForceAndTorque callback function for bodies that are inactive or have reached a state of stable equilibrium.

See also

NewtonBodyGetUserData, NewtonBodyGetUserData, NewtonBodyGetForceAndTorqueCallback

NewtonBodyGetForceAndTorqueCallback

NewtonApplyForceAndTorque NewtonBodyGetForceAndTorqueCallback(const NewtonBody* bodyPtr)
Return the pointer to the current force and torque call back function.

Parameters

const NewtonBody *bodyPtr - pointer to the body.

Return

pointer to the force call back.

Remarks

This function can be used to concatenate different force calculation components making more modular the design of function components dedicated to apply special effect. For example a body may have a basic force a force that only apply the effect of gravity, but that application can place a region in where there can be a fluid volume, or another gravity field. we this function the application can read the correct function and save into a local variable, and set a new one. this new function will firs call the save function pointer and upon return apply the correct effect. this similar to the concept of virtual methods on objected oriented languages.

Remarks

The function NewtonApplyForceAndTorque callback is called by the Newton Engine every time an active body is going to be simulated. The Newton Engine does not call the NewtonApplyForceAndTorque callback function for bodies that are inactive or have reached a state of stable equilibrium.

See also

NewtonBodyGetUserData, NewtonBodyGetUserData, NewtonBodySetForceAndTorqueCallback

NewtonBodySetDestructorCallback

void NewtonBodySetDestructorCallback(
const NewtonBody* bodyPtr,
NewtonBodyDestructor callback)
Assign an event function to be called when this body is about to be destroyed.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body to be destroyed.
NewtonBodyDestructor callback | - | pointer to a function callback.

Return

Nothing.

Remarks

This function NewtonBodyDestructor callback acts like a destruction function in CPP. This function is called when the body and all data joints associated with the body are about to be destroyed. The application could use this function to destroy or release any resource associated with this body. The application should not make reference to this body after this function returns.

Remarks

The destruction of a body will destroy all joints associated with the body.

See also

NewtonBodyGetUserData, NewtonBodyGetUserData

NewtonBodySetMassMatrix

void NewtonBodySetMassMatrix(
const NewtonBody* bodyPtr,
dFloat mass,
dFloat Ixx,
dFloat Iyy,
dFloat Izz)
Set the mass matrix of a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
dFloat mass | - | mass value.
dFloat Ixx | - | moment of inertia of the first principal axis of inertia of the body.
dFloat Iyy | - | moment of inertia of the first principal axis of inertia of the body.
dFloat Izz | - | moment of inertia of the first principal axis of inertia of the body.

Return

Nothing.

Remarks

Newton algorithms have no restriction on the values for the mass, but due to floating point dynamic range (24 bit precision) it is best if the ratio between the heaviest and the lightest body in the scene is limited to 200. There are no special utility functions in Newton to calculate the moment of inertia of common primitives. The application should specify the inertial values, keeping in mind that realistic inertia values are necessary for realistic physics behavior.

See also

NewtonConvexCollisionCalculateInertialMatrix, NewtonBodyGetMassMatrix, NewtonBodyGetInvMass

NewtonBodyGetMassMatrix

void NewtonBodyGetMassMatrix(
const NewtonBody* bodyPtr,
dFloat* mass,
dFloat* Ixx,
dFloat* Iyy,
dFloat* Izz)
Get the mass matrix of a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
dFloat *mass | - | pointer to a variable that will hold the mass value of the body.
dFloat *Ixx | - | pointer to a variable that will hold the moment of inertia of the first principal axis of inertia of the body.
dFloat *Iyy | - | pointer to a variable that will hold the moment of inertia of the first principal axis of inertia of the body.
dFloat *Izz | - | pointer to a variable that will hold the moment of inertia of the first principal axis of inertia of the body.

Return

Nothing.

See also

NewtonBodySetMassMatrix, NewtonBodyGetInvMass

NewtonBodyGetInvMass

void NewtonBodyGetInvMass(
const NewtonBody* bodyPtr,
dFloat* invMass,
dFloat* invIxx,
dFloat* invIyy,
dFloat* invIzz)
Get the inverse mass matrix of a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
dFloat *invMass | - | pointer to a variable that will hold the mass inverse value of the body.
dFloat *invIxx | - | pointer to a variable that will hold the moment of inertia inverse of the first principal axis of inertia of the body.
dFloat *invIyy | - | pointer to a variable that will hold the moment of inertia inverse of the first principal axis of inertia of the body.
dFloat *invIzz | - | pointer to a variable that will hold the moment of inertia inverse of the first principal axis of inertia of the body.

Return

Nothing.

See also

NewtonBodySetMassMatrix, NewtonBodyGetMassMatrix

NewtonBodySetMatrix

void NewtonBodySetMatrix(
const NewtonBody* bodyPtr,
const dFloat* matrixPtr)
Set the transformation matrix of a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *matrixPtr | - | pointer to an array of 16 floats containing the global matrix of the rigid body.

Return

Nothing.

Remarks

The matrix should be arranged in row-major order (this is the way directX stores matrices). If you are using OpenGL matrices (column-major) you will need to transpose you matrices into a local array, before passing them to Newton.

See also

NewtonBodyGetMatrix, NewtonBodySetMatrixRecursive

NewtonBodySetMatrixRecursive

void NewtonBodySetMatrixRecursive(
const NewtonBody* bodyPtr,
const dFloat* matrixPtr)
Apply hierarchical transformation to a body.

Parameters

const NewtonWorld *newtonWorld | - | pointer to the Newton world.
const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *matrixPtr | - | pointer to an array of 16 floats containing the global matrix of the rigid body.

Return

Nothing.

Remarks

This function applies the transformation matrix to the body and also applies the appropriate transformation matrix to set of articulated bodies. If the body is in contact with another body the other body is not transformed.

Remarks

this funtion should not be used to transform set of articulated bodies that are connected to a static body. doing so will result in umprediactable results. Think for example moving a chain attached to a ceiling from one place to another, to do that in real life a person first need to desconect the chain (destroy the joint), move the chain (apply teh tranfomation to the entire chain), the reconect it in the new position (recreate the joint again).

Remarks

this function will set to zero the linear and angular velocity of all bodies that are part of the set of articulated body array.

Remarks

The matrix should be arranged in row-major order (this is the way directX stores matrices). If you are using OpenGL matrices (column-major) you will need to transpose you matrices into a local array, before passing them to Newton.

See also

NewtonBodySetMatrix

NewtonBodyGetMatrix

void NewtonBodyGetMatrix(
const NewtonBody* bodyPtr,
dFloat* matrixPtr)
Get the transformation matrix of a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *matrixPtr | - | pointer to an array of 16 floats that will hold the global matrix of the rigid body.

Return

Nothing.

Remarks

The matrix should be arranged in row-major order (this is the way directX stores matrices). If you are using OpenGL matrices (column-major) you will need to transpose you matrices into a local array, before passing them to Newton.

See also

NewtonBodySetMatrix

NewtonBodySetForce

void NewtonBodySetForce(
const NewtonBody* bodyPtr,
const dFloat* forcePtr)
Set the net force applied to a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *forcePtr | - | pointer to an array of 3 floats containing the net force to be applied to the body.

Return

Nothing.

Remarks

This function is only effective when called from NewtonApplyForceAndTorque callback

See also

NewtonBodyAddForce, NewtonBodyGetForce

NewtonBodyAddForce

void NewtonBodyAddForce(
const NewtonBody* bodyPtr,
const dFloat* forcePtr)
Add the net force applied to a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body to be destroyed.
const dFloat *forcePtr | - | pointer to an array of 3 floats containing the net force to be applied to the body.

Return

Nothing.

Remarks

This function is only effective when called from NewtonApplyForceAndTorque callback

See also

NewtonBodySetForce, NewtonBodyGetForce

NewtonBodyGetForce

void NewtonBodyGetForce(
const NewtonBody* bodyPtr,
dFloat* vectorPtr)
Get the net force applied to a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *forcePtr | - | pointer to an array of 3 floats to hold the net force of the body.

Return

Nothing.

Remarks

This function is only effective when called from NewtonApplyForceAndTorque callback

See also

NewtonBodyAddForce, NewtonBodyGetForce

NewtonBodySetTorque

void NewtonBodySetTorque(
const NewtonBody* bodyPtr,
const dFloat* forcePtr)
Set the net torque applied to a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *torquePtr | - | pointer to an array of 3 floats containing the net torque to be applied to the body.

Return

Nothing.

Remarks

This function is only effective when called from NewtonApplyForceAndTorque callback

See also

NewtonBodyAddTorque, NewtonBodyGetTorque

NewtonBodySetCentreOfMass

void NewtonBodySetCentreOfMass(
const NewtonBody* bodyPtr,
const dFloat* comPtr)
Set the relative position of the center of mass of a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *comPtr | - | pointer to an array of 3 floats containing the relative offset of the centre of mass of the body.

Return

Nothing.

Remarks

This funtion can be used to set the relative offset of the centre of mass of a rigid body. when a rigid body is created the centre of mass is set the the point c(0, 0, 0), and normally this is the best setting for a rigid body. However the are situations in which and object does not have simetry or simple some kind of special effect is desired, and this origin need to be changed.

Remarks

Care must be taken when ofsseting the centre of mass of a body. The applycation must make sure that the external torques resulting from forces applied at at point relative to the center of mass are calculared apropriatly. this could be done Transform and Torque callback funtion as teh follow psudo code fragment shows:

Matrix matrix; Vector centre;

NewtonGatMetrix(body, matrix) NewtonGetCentreOfMass(body, centre);

for global space torque. Vector localForce (fx, fy, fz); Vector localPosition (x, y, z);

Vector localTroque (crossproduct ((localPosition - centre). localForce); Vector globalTroque (matrix.RotateVector (localTroque));

for global space torque.
Vector globalCentre (matrix.TranformVector (centre));
Vector globalPosition (x, y, z);
Vector globalForce (fx, fy, fz);

Vector globalTroque (crossproduct ((globalPosition - globalCentre). globalForce);

See also

NewtonConvexCollisionCalculateInertialMatrix, NewtonBodyGetCentreOfMass

NewtonBodyAddTorque

void NewtonBodyAddTorque(
const NewtonBody* bodyPtr,
const dFloat* forcePtr)
Add the net torque applied to a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *torquePtr | - | pointer to an array of 3 floats containing the net torque to be applied to the body.

Return

Nothing.

Remarks

This function is only effective when called from NewtonApplyForceAndTorque callback

See also

NewtonBodySetTorque, NewtonBodyGetTorque

NewtonBodyGetTorque

void NewtonBodyGetTorque(
const NewtonBody* bodyPtr,
dFloat* vectorPtr)
Get the net torque applied to a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const dFloat *torquePtr | - | pointer to an array of 3 floats to hold the net torque of the body.

Return

Nothing.

Remarks

This function is only effective when called from NewtonApplyForceAndTorque callback

See also

NewtonBodyAddTorque, NewtonBodyGetTorque

NewtonBodyGetCentreOfMass

void NewtonBodyGetCentreOfMass(
const NewtonBody* bodyPtr,
dFloat* comPtr)
Get the relative position of the center of mass of a rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
dFloat *comPtr | - | pointer to an array of 3 floats to hold the relative offset of the centre of mass of the body.

Return

Nothing.

Remarks

This function can be used to set the relative offset of the center of mass of a rigid body. when a rigid body is crated the center of mass is set the the point c(0, 0, 0), and normally this is the best setting for a rigid body. However the are situations in which and object does not have simetry or simple some kind of special effect is desired, and this origin need to be changed.

Remarks

This function can be used in conjunction with NewtonConvexCollisionCalculateInertialMatrix

See also

NewtonConvexCollisionCalculateInertialMatrix, NewtonBodySetCentreOfMass

NewtonBodyAddBuoyancyForce

void NewtonBodyAddBuoyancyForce(
const NewtonBody* bodyPtr,
dFloat fluidDensity,
dFloat fluidLinearViscosity,
dFloat fluidAngularViscosity,
const dFloat* gravityVector,
NewtonGetBuoyancyPlane buoyancyPlane,
void *context)
Add buoyancy force and torque for bodies immersed in a fluid.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
dFloat fluidDensity | - | fluid density.
dFloat fluidLinearViscosity | - | fluid linear viscosity (resistance to linear tranlation).
dFloat fluidAngularViscosity | - | fluid angular viscosity (resistance to rotation).
const dFloat *gravityVector | - | pointer to an array of floats containing the gravity vector.
NewtonGetBuoyancyPlane *buoyancyPlane | - | pointer to an array of at least 4 floats containing the plane equation of the surface of the fluid. This parameter can be NULL

Return

Nothing.

Remarks

This function is only effective when called from NewtonApplyForceAndTorque callback

Remarks

This function adds buoyancy force and torque to a body when it is immersed in a fluid. The force is calculated according to Archimedes’ Buoyancy Principle. When the parameter buoyancyPlane is set to NULL, the body is considered to completely immersed in the fluid. This can be used to simulate boats and lighter than air vehicles etc..

Remarks

If buoyancyPlane return 0 buoyancy calculation for this collision primitive is inghnored, this coudl be used to filter bouyancy calculation of compound collision geometry with diffrents IDs.

See also

NewtonConvexCollisionCalculateVolume

NewtonBodySetCollision

void NewtonBodySetCollision(
const NewtonBody* bodyPtr,
const NewtonCollision* collisionPtr)
Assign a collision primitive to the body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
const collisionPtr *collisionPtr | - | pointer to the new collision geometry.

Return

Nothing.

Remarks

This function replaces a collision geometry of a body with the new collision geometry. This function increments the reference count of the collision geometry and decrements the reference count of the old collision geometry. If the reference count of the old collision geometry reaches zero, the old collision geometry is destroyed. This function can be used to swap the collision geometry of bodies at runtime.

See also

NewtonCreateBody, NewtonBodyGetCollision

NewtonBodyCoriolisForcesMode

void NewtonBodyCoriolisForcesMode(
const NewtonBody* bodyPtr,
int mode)
Enable or disable Coriolis and gyroscopic force calculation for this body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
int mode | - | force mode zero indicate not gyroscopic force calculation.

Return

Nothing.

Remarks

Gyroscopic forces internal forces generated as a result of an asymmetric tensor. They are a pure mathematical consequence that the physics have to comply in order to agree with the math. As Gyroscopic forces are not real forces but the result of net unbalance of the changing inertia tensor or a rigid body when its angular velocity is measured on a reference frame different than the body’s own. Gyroscopic forces are extremely non linear by nature, therefore a first order implicit integrator will have a extremely hard time at dealing with this kind of forces, however because the fact that they are not real forces they do not make much difference in the outcome of the integration. Fortunately due to the fact that the magnitude of gyroscopic forces is proportional to the unbalance of the inertia tensor, it is possible to disregard the effect of this forces by assuming their inertial tensor is symmetric for the purpose of this calculation. For most cases an ordinary person is not capable to distinguish the motion of a body subject to gyroscopic forces and one that is not, especially when the motion is constrained. Because of this fact gyroscopic force are turned off by default in Newton, however there are cases when the desire effect is precisely to simulate these forces like a spinning top, or the design of a space navigational system, etc. The most important feature of gyroscopic forces is that they make the rigid body to process.

NewtonBodyGetCollision

NewtonCollision* NewtonBodyGetCollision(const NewtonBody* bodyPtr)
Get the collision primitive of a body.

Parameters

const NewtonBody *bodyPtr - pointer to the body.

Return

Pointer to body collision geometry.

Remarks

This function does not increment the reference count of the collision geometry.

See also

NewtonCreateBody, NewtonBodySetCollision

NewtonBodySetMaterialGroupID

void NewtonBodySetMaterialGroupID(
const NewtonBody* bodyPtr,
int id)
Assign a material group id to the body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
int id | - | id of a previously created material group.

Return

Nothing.

Remarks

When the application creates a body, the default material group, defaultGroupId, is applied by default.

See also

NewtonBodyGetMaterialGroupID, NewtonMaterialCreateGroupID, NewtonMaterialGetDefaultGroupID

NewtonBodyGetMaterialGroupID

int NewtonBodyGetMaterialGroupID(const NewtonBody* bodyPtr)
Get the material group id of the body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
int id | - | id of a previously created material group.

Return

Nothing.

See also

NewtonBodySetMaterialGroupID

NewtonBodySetContinuousCollisionMode

void NewtonBodySetContinuousCollisionMode(
const NewtonBody* bodyPtr,
unsigned state)
Set the continuous collision state mode for this rigid body.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
int state | - | collision state. 1 indicates this body may tunnel through other objects while moving at high speed. 0 ignore high speed collision checks.

Return

Nothing.

Remarks

continue collision mode enable allow the engine to predict colliding contact on rigid bodies Moving at high speed of subject to strong forces.

Remarks

continue collision mode does not prevent rigid bodies from interpenetration instead it prevent bodies from passing trough each others by extrapolating contact points when the bodies normal contact calculation determine the bodies are not colliding.

Remarks

for performance reason the bodies angular velocities is only use on the broad face of the collision, but not on the contact calculation.

Remarks

continue collision does not perform back tracking to determine time of contact, instead it extrapolate contact by incrementally extruding the collision geometries of the two colliding bodies along the linear velocity of the bodies during the time step, if during the extrusion colliding contact are found, a collision is declared and the normal contact resolution is called.

Remarks

for continue collision to be active the continue collision mode must on the material pair of the colliding bodies as well as on at least one of the two colliding bodies.

Remarks

Because there is penalty of about 40% to 80% depending of the shape complexity of the collision geometry, this feature is set off by default. It is the job of the application to determine what bodies need this feature on. Good guidelines are: very small objects, and bodies that move a height speed.

See also

NewtonBodyGetContinuousCollisionMode, NewtonBodySetContinuousCollisionMode

NewtonBodyGetContinuousCollisionMode

Get the continuous collision state mode for this rigid body.

Parameters

const NewtonBody *bodyPtr - pointer to the body.

Return

Nothing.

Remarks

Remark: Because there is there is penalty of about 3 to 5 depending of the shape complexity of the collision geometry, this feature is set off by default. It is the job of the application to determine what bodies need this feature on. Good guidelines are: very small objects, and bodies that move a height speed.

Remark

this feature is currently disabled:

See also

NewtonBodySetContinuousCollisionMode, NewtonBodySetContinuousCollisionMode

NewtonBodySetJointRecursiveCollision

void NewtonBodySetJointRecursiveCollision(
const NewtonBody* bodyPtr,
unsigned state)
Set the collision state flag of this body when the body is connected to another body by a hierarchy of joints.

Parameters

const NewtonBody *bodyPtr | - | pointer to the body.
int state | - | collision state. 1 indicates this body will collide with any linked body. 0 disable collision with body connected to this one by joints.

Return

Nothing.

Remarks

sometimes when making complicated arrangements of linked bodies it is possible the collision geometry of these bodies is in the way of the joints work space. This could be a problem for the normal operation of the joints. When this situation happens the application can determine which bodies are the problem and disable collision for those bodies while they are linked by joints. For the collision to be disable for a pair of body, both bodies must have the collision disabled. If the joints connecting the bodies are destroyed these bodies become collidable automatically. This feature can also be achieved by making special material for the whole configuration of jointed bodies, however it is a lot easier just to set collision disable for jointed bodies.

See also

NewtonBodySetMaterialGroupID

NewtonBodyGetJointRecursiveCollision

Get the collision state flag when the body is joint.

Parameters

const NewtonBody *bodyPtr - pointer to the body.

Return

return the collision state flag for this body.

See also

NewtonBodySetMaterialGroupID

NewtonBodySetAutoFreeze

void NewtonBodySetAutoFreeze(
const NewtonBody* bodyPtr,
int state)
Set the auto-activation mode for this body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
int state | - | active mode: 1 = auto-activation on (controlled by Newton). 0 = auto-activation off (controlled by the application).

Return

Nothing.

Remarks

Bodies are created with auto-activation on by default.

Remarks

Autoactivation enabled is the default state for the majority of bodies in a large scene. However, for player control, ai control or some other special circumstance, the application may want to control the activation/deactivation of the body. In that case, the application may call NewtonBodySetAutoFreeze (body, 0) followed by NewtonWorldUnfreezeBody(world, body), this will make the body active forever.

See also

NewtonWorldFreezeBody, NewtonWorldUnfreezeBody, NewtonBodyGetAutoFreeze, NewtonBodySetFreezeTreshold

NewtonBodyGetAutoFreeze

int NewtonBodyGetAutoFreeze(const NewtonBody* bodyPtr)
Get the auto-activation state of the body.

Parameters

const NewtonBody *bodyPtr - is the pointer to the body.

Return

Autoactivation state: 1 = auto-activation on. 0 = auto-activation off.

See also

NewtonBodySetAutoFreeze, NewtonBodyGetSleepingState

NewtonBodyGetSleepingState

int NewtonBodyGetSleepingState(const NewtonBody* bodyPtr)
Return the sleep mode of a rigid body.

Parameters

const NewtonBody *bodyPtr - is the pointer to the body.

Return

Autoactivation state: 1 = auto-activation on. 0 = auto-activation off.

See also

NewtonBodySetAutoFreeze

NewtonBodySetFreezeTreshold

void NewtonBodySetFreezeTreshold(
const NewtonBody* bodyPtr,
dFloat freezeSpeedMag2,
dFloat freezeOmegaMag2,
int framesCount)
Set the minimum values for velocity of a body that will be considered at rest.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
dFloat freezeSpeedMag2 | - | magnitude squared of the velocity threshold.
dFloat freezeOmegaMag2 | - | magnitude squared of angular velocity threshold.
int framesCount | - | number of frames the body velocity and angular will not excide freezeSpeedMag and freezeOmegaMag.

Remarks

Ideally, a body should be deactivated when it reaches a state of stable equilibrium. However, because of floating point inaccuracy, discrete time step simulation and other factors it is virtually impossible for a body to reach that state in a real-time simulation. Therefore, in the Newton World, a body is considered to be in stable equilibrium when its velocity and angular velocity fall below some threshold for a consecutive number of frames.

Remarks

The default and minimum values for the thresholds is 0.01 for speed and 10 for frames count. These values are tuned for single objects colliding under the influence of gravity. It is possible that for complex configuration of bodies like multiples pendulums, rag dolls, etc. these values may need to be increased. This is because joints have the property that they add a small amount of energy to the system in order to reduce the separation error. This may cause the bodies reach a state of unstable equilibrium. That is, when a body oscillates between two different positions because the energy added to the body is equal to the energy dissipated by the integrator. This is a situation that is hard to predict, and the best solution is to tweak these values for specific cases.

See also

NewtonBodySetAutoFreeze, NewtonBodyGetFreezeTreshold

NewtonBodyGetFreezeTreshold

void NewtonBodyGetFreezeTreshold(
const NewtonBody* bodyPtr,
dFloat* freezeSpeedMag2,
dFloat* freezeOmegaMag2)
Get the minimum values for velocity of a body the will be considered at rest.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
dFloat freezeSpeedMag2 | - | point the to a dFloat to hold the velocity threshold
dFloat freezeOmegaMag2 | - | point the to a dFloat to hold the angular velocity threshold

See also

NewtonBodySetFreezeTreshold

NewtonBodyGetAABB

void NewtonBodyGetAABB(
const NewtonBody* bodyPtr,
dFloat* p0,
dFloat* p1)
Get the world axis aligned bounding box (AABB) of the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
dFloat *p0 | - | pointer to an array of at least three floats to hold minimum value for the AABB.
dFloat *p1 | - | pointer to an array of at least three floats to hold maximum value for the AABB.

NewtonBodySetVelocity

void NewtonBodySetVelocity(
const NewtonBody* bodyPtr,
const dFloat* velocity)
Set the global linear velocity of the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
const dFloat *velocity | - | pointer to an array of at least three floats containing the velocity vector.

See also

NewtonBodyGetVelocity

NewtonBodyGetVelocity

void NewtonBodyGetVelocity(
const NewtonBody* bodyPtr,
dFloat* velocity)
Get the global linear velocity of the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
const dFloat *velocity | - | pointer to an array of at least three floats to hold the velocity vector.

See also

NewtonBodySetVelocity

NewtonBodySetOmega

void NewtonBodySetOmega(
const NewtonBody* bodyPtr,
const dFloat* omega)
Set the global angular velocity of the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
const dFloat *omega | - | pointer to an array of at least three floats containing the angular velocity vector.

See also

NewtonBodyGetOmega

NewtonBodyGetOmega

void NewtonBodyGetOmega(
const NewtonBody* bodyPtr,
dFloat* omega)
Get the global angular velocity of the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body
dFloat *omega | - | pointer to an array of at least three floats to hold the angular velocity vector.

See also

NewtonBodySetOmega

NewtonBodySetLinearDamping

void NewtonBodySetLinearDamping(
const NewtonBody* bodyPtr,
dFloat linearDamp)
Apply the linear viscous damping coefficient to the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
dFloat linearDamp | - | linear damping coefficient.

Remarks

the default value of linearDamp is clamped to a value between 0.0 and 1.0; the default value is 0.1, There is a non zero implicit attenuation value of 0.0001 assume by the integrator.

Remarks

The dampening viscous friction force is added to the external force applied to the body every frame before going to the solver-integrator. This force is proportional to the square of the magnitude of the velocity to the body in the opposite direction of the velocity of the body. An application can set linearDamp to zero when the application takes control of the external forces and torque applied to the body, should the application desire to have absolute control of the forces over that body. However, it is recommended that the linearDamp coefficient is set to a non-zero value for the majority of background bodies. This saves the application from having to control these forces and also prevents the integrator from adding very large velocities to a body.

See also

NewtonBodyGetLinearDamping

NewtonBodyGetLinearDamping

Get the linear viscous damping of the body.

Parameters

const NewtonBody *bodyPtr - is the pointer to the body.

Return

The linear damping coefficient.

See also

NewtonBodySetLinearDamping

NewtonBodySetAngularDamping

Apply the angular viscous damping coefficient to the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
dFloat *angularDamp | - | pointer to an array of at least three floats containing the angular damping coefficients for the principal axis of the body.

Remarks

the default value of angularDamp is clamped to a value between 0.0 and 1.0; the default value is 0.1, There is a non zero implicit attenuation value of 0.0001 assumed by the integrator.

Remarks

The dampening viscous friction torque is added to the external torque applied to the body every frame before going to the solver-integrator. This torque is proportional to the square of the magnitude of the angular velocity to the body in the opposite direction of the angular velocity of the body. An application can set angularDamp to zero when the to take control of the external forces and torque applied to the body, should the application desire to have absolute control of the forces over that body. However, it is recomended that the linearDamp coefficient be set to a non-zero value for the majority of background bodies. This saves the application from needing to control these forces and also prevents the integrator from adding very large velocities to a body.

See also

NewtonBodyGetAngularDamping

NewtonBodyGetAngularDamping

void NewtonBodyGetAngularDamping(
const NewtonBody* bodyPtr,
dFloat* angularDamp)
Get the linear viscous damping of the body.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
dFloat *angularDamp | - | pointer to an array of at least three floats to hold the angular damping coefficient for the principal axis of the body.

See also

NewtonBodySetAngularDamping

NewtonBodyForEachPolygonDo

void NewtonBodyForEachPolygonDo(
const NewtonBody* bodyPtr,
NewtonCollisionIterator callback)
Iterate thought polygon of the collision geometry of a body calling the function callback.

Parameters

const NewtonBody *bodyPtr | - | is the pointer to the body.
NewtonCollisionIterator callback | - | application define callback

Return

nothing

Remarks

This function can be called by the application in order to show the collision geometry. The application should provide a pointer to the function NewtonCollisionIterator, Newton will convert the collision geometry into a polygonal mesh, and will call callback for every polygon of the mesh

Remarks

this function affect severely the performance of Newton. The application should call this function only for debugging purpose

Remarks

This function will ignore user define collision mesh See also: NewtonWorldForEachBodyDo

NewtonAddBodyImpulse

void NewtonAddBodyImpulse(
const NewtonBody* bodyPtr,
const dFloat* pointDeltaVeloc,
const dFloat* pointPosit)
Add an impulse to a specific point on a body.

Parameters

const NewtonWorld *newtonWorld | - | pointer to the Newton world.
const NewtonBody *bodyPtr | - | is the pointer to the body.
const dFloat pointDeltaVeloc | - | pointer to an array of at least three floats containing the desired change in velocity to point pointPosit.
const dFloat pointPosit | - | pointer to an array of at least three floats containing the center of the impulse in global space.

Return

Nothing.

Remarks

This function will activate the body.

Remarks

pointPosit and pointDeltaVeloc must be specified in global space.

Remarks

pointDeltaVeloc represent a change in velocity. For example, a value of pointDeltaVeloc of (1, 0, 0) changes the velocity of bodyPtr in such a way that the velocity of point pointDeltaVeloc will increase by (1, 0, 0)

Remarks

Because pointDeltaVeloc represents a change in velocity, this function must be used with care. Repeated calls to this function will result in an increase of the velocity of the body and may cause to integrator to lose stability.

Ball and Socket joint interface

NewtonConstraintCreateBall

NewtonJoint* NewtonConstraintCreateBall(
const NewtonWorld* newtonWorld,
const dFloat* pivotPoint,
const NewtonBody* childBody,
const NewtonBody* parentBody)
Create a ball an socket joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *pivotPoint | - | is origin of ball and socket in global space.
const NewtonBody *childBody | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.
const NewtonBody *parentBody | - | is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body.

Return

Pointer to the ball and socket joint.

Remarks

This function creates a ball and socket and add it to the world. By default joint disables collision with the linked bodies.

NewtonBallSetConeLimits

void NewtonBallSetConeLimits(
const NewtonJoint* ball,
const dFloat* pin,
dFloat maxConeAngle,
dFloat maxTwistAngle)
Set the ball and socket cone and twist limits.

Parameters

const NewtonJoint *ball | - | is the pointer to a ball and socket joint.
const NewtonCollision *pin | - | pointer to a unit vector defining the cone axis in global space.
const dFloat maxConeAngle | - | max angle in radians the attached body is allow to swing relative to the pin axis, a value of zero will disable this limits.
const dFloat maxTwistAngle | - | max angle in radians the attached body is allow to twist relative to the pin axis, a value of zero will disable this limits.

Remarks

limits are disabled at creation time. A value of zero for maxConeAngle disable the cone limit, a value of zero for maxTwistAngle disable the twist limit all non-zero value for maxConeAngle are clamped between 5 degree and 175 degres

See also

NewtonConstraintCreateBall

NewtonBallSetUserCallback

void NewtonBallSetUserCallback(
const NewtonJoint* ball,
NewtonBallCallBack callback)
Set an update call back to be called when either of the two bodies linked by the joint is active.

Parameters

const NewtonJoint *ball | - | pointer to the joint.
NewtonBallCallBack callback | - | pointer to the joint function call back.

Return

nothing.

Remarks

if the application wants to have some feedback from the joint simulation, the application can register a function update callback to be called every time any of the bodies linked by this joint is active. This is useful to provide special effects like particles, sound or even to simulate breakable moving parts.

See also

NewtonJointSetUserData

NewtonBallGetJointAngle

Get the relative joint angle between the two bodies.

Parameters

const NewtonJoint *ball | - | pointer to the joint.
dFloat *angle | - | pointer to an array of a least three floats to hold the joint relative Euler angles.

Return

nothing.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play a bell sound when the joint angle passes some max value.

See also

NewtonBallSetUserCallback

NewtonBallGetJointOmega

void NewtonBallGetJointOmega(
const NewtonJoint* ball,
dFloat* omega)
Get the relative joint angular velocity between the two bodies.

Parameters

const NewtonJoint *ball | - | pointer to the joint.
dFloat *omega | - | pointer to an array of a least three floats to hold the joint relative angular velocity.

Return

nothing.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play the creaky noise of a hanging lamp.

See also

NewtonBallSetUserCallback

NewtonBallGetJointForce

void NewtonBallGetJointForce(
const NewtonJoint* ball,
dFloat* force)
Get the total force asserted over the joint pivot point, to maintain the constraint.

Parameters

const NewtonJoint *ball | - | pointer to the joint.
dFloat *force | - | pointer to an array of a least three floats to hold the force value of the joint.

Return

nothing.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can destroy the joint if the force exceeds some predefined value.

See also

NewtonBallSetUserCallback

Hinge joint interface

NewtonConstraintCreateHinge

NewtonJoint* NewtonConstraintCreateHinge(
const NewtonWorld* newtonWorld,
const dFloat* pivotPoint,
const dFloat* pinDir,
const NewtonBody* childBody,
const NewtonBody* parentBody)
Create a hinge joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *pivotPoint | - | is origin of the hinge in global space.
const NewtonCollision *pinDir | - | is the line of action of the hinge in global space.
const NewtonBody *childBody | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.
const NewtonBody *parentBody | - | is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body.

Return

Pointer to the hinge joint.

Remarks

This function creates a hinge and add it to the world. By default joint disables collision with the linked bodies.

NewtonHingeSetUserCallback

void NewtonHingeSetUserCallback(
const NewtonJoint* Hinge,
NewtonHingeCallBack callback)
Set an update call back to be called when either of the two body linked by the joint is active.

Parameters

const NewtonJoint *Hinge | - | pointer to the joint.
NewtonHingeCallBack callback | - | pointer to the joint function call back.

Return

nothing.

Remarks

if the application wants to have some feedback from the joint simulation, the application can register a function update callback to be call every time any of the bodies linked by this joint is active. This is useful to provide special effects like particles, sound or even to simulate breakable moving parts.

See also

NewtonJointGetUserData, NewtonJointSetUserData

NewtonHingeGetJointAngle

Get the relative joint angle between the two bodies.

Parameters

const NewtonJoint *Hinge - pointer to the joint.

Return

the joint angle relative to the hinge pin.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play a bell sound when the joint angle passes some max value.

See also

NewtonHingeSetUserCallback

NewtonHingeGetJointOmega

dFloat NewtonHingeGetJointOmega(const NewtonJoint* Hinge)
Get the relative joint angular velocity between the two bodies.

Parameters

const NewtonJoint *Hinge - pointer to the joint.

Return

the joint angular velocity relative to the pin axis.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play the creaky noise of a hanging lamp.

See also

NewtonHingeSetUserCallback

NewtonHingeGetJointForce

void NewtonHingeGetJointForce(
const NewtonJoint* Hinge,
dFloat* force)
Calculate the angular acceleration needed to stop the hinge at the desired angle.

Parameters

const NewtonJoint *Hinge | - | pointer to the joint.
NewtonHingeSliderUpdateDesc *desc | - | is the pointer to and the Hinge or slide structure.
dFloat angle | - | is the desired hinge stop angle

Return

the relative angular acceleration needed to stop the hinge.

Remarks

this function can only be called from a NewtonHingeCallBack and it can be used by the application to implement hinge limits.

See also

NewtonHingeSetUserCallback

NewtonHingeGetJointForce

void NewtonHingeGetJointForce(
const NewtonJoint* Hinge,
dFloat* force)
Get the total force asserted over the joint pivot point, to maintain the constraint.

Parameters

const NewtonJoint *Hinge | - | pointer to the joint.
dFloat *force | - | pointer to an array of a least three floats to hold the force value of the joint.

Return

nothing.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can destroy the joint if the force exceeds some predefined value.

See also

NewtonHingeSetUserCallback

Slider joint interface

NewtonConstraintCreateSlider

NewtonJoint* NewtonConstraintCreateSlider(
const NewtonWorld* newtonWorld,
const dFloat* pivotPoint,
const dFloat* pinDir,
const NewtonBody* childBody,
const NewtonBody* parentBody)
Create a slider joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *pivotPoint | - | is origin of the slider in global space.
const NewtonCollision *pinDir | - | is the line of action of the slider in global space.
const NewtonBody *childBody | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.
const NewtonBody *parentBody | - | is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body.

Return

Pointer to the slider joint.

Remarks

This function creates a slider and add it to the world. By default joint disables collision with the linked bodies.

NewtonSliderSetUserCallback

void NewtonSliderSetUserCallback(
const NewtonJoint* Slider,
NewtonSliderCallBack callback)
Set an update call back to be called when either of the two body linked by the joint is active.

Parameters

const NewtonJoint *Slider | - | pointer to the joint.
NewtonSliderCallBack callback | - | pointer to the joint function call back.

Return

nothing.

Remarks

if the application wants to have some feedback from the joint simulation, the application can register a function update callback to be call every time any of the bodies linked by this joint is active. This is useful to provide special effects like particles, sound or even to simulate breakable moving parts.

See also

NewtonJointGetUserData, NewtonJointSetUserData

NewtonSliderGetJointPosit

Get the relative joint angle between the two bodies.

Parameters

const NewtonJoint *Slider - pointer to the joint.

Return

the joint angle relative to the hinge pin.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play a bell sound when the joint angle passes some max value.

See also

NewtonSliderSetUserCallback

NewtonSliderGetJointVeloc

dFloat NewtonSliderGetJointVeloc(const NewtonJoint* Slider)
Get the relative joint angular velocity between the two bodies.

Parameters

const NewtonJoint *Slider - pointer to the joint.

Return

the joint angular velocity relative to the pin axis.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play the creaky noise of a hanging lamp.

See also

NewtonSliderSetUserCallback

NewtonSliderGetJointForce

void NewtonSliderGetJointForce(
const NewtonJoint* Slider,
dFloat* force)
Calculate the angular acceleration needed to stop the slider at the desired angle.

Parameters

const NewtonJoint *slider | - | pointer to the joint.
NewtonSliderSliderUpdateDesc *desc | - | is the pointer to the Slider or slide structure.
dFloat distance | - | desired stop distance relative to the pivot point

Return

the relative linear acceleration needed to stop the slider.

Remarks

this function can only be called from a NewtonSliderCallBack and it can be used by the application to implement slider limits.

See also

NewtonSliderSetUserCallback

NewtonSliderGetJointForce

void NewtonSliderGetJointForce(
const NewtonJoint* Slider,
dFloat* force)
Get the total force asserted over the joint pivot point, to maintain the constraint.

Parameters

const NewtonJoint *Slider | - | pointer to the joint.
dFloat *force | - | pointer to an array of a least three floats to hold the force value of the joint.

Return

nothing.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can destroy the joint if the force exceeds some predefined value.

See also

NewtonSliderSetUserCallback

Corkscrew joint interface

NewtonConstraintCreateCorkscrew

NewtonJoint* NewtonConstraintCreateCorkscrew(
const NewtonWorld* newtonWorld,
const dFloat* pivotPoint,
const dFloat* pinDir,
const NewtonBody* childBody,
const NewtonBody* parentBody)
Create a corkscrew joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *pivotPoint | - | is origin of the corkscrew in global space.
const NewtonCollision *pinDir | - | is the line of action of the corkscrew in global space.
const NewtonBody *childBody | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.
const NewtonBody *parentBody | - | is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body.

Return

Pointer to the corkscrew joint.

Remarks

This function creates a corkscrew and add it to the world. By default joint disables collision with the linked bodies.

NewtonCorkscrewSetUserCallback

void NewtonCorkscrewSetUserCallback(
const NewtonJoint* Corkscrew,
NewtonCorkscrewCallBack callback)
Set an update call back to be called when either of the two body linked by the joint is active.

Parameters

const NewtonJoint *Corkscrew | - | pointer to the joint.
NewtonCorkscrewCallBack callback | - | pointer to the joint function call back.

Return

nothing.

Remarks

if the application wants to have some feedback from the joint simulation, the application can register a function update callback to be call every time any of the bodies linked by this joint is active. This is useful to provide special effects like particles, sound or even to simulate breakable moving parts.

Remarks

the function NewtonCorkscrewCallBack callback should return a bit field code. if the application does not want to set the joint acceleration the return code is zero if the application only wants to change the joint linear acceleration the return code is 1 if the application only wants to change the joint angular acceleration the return code is 2 if the application only wants to change the joint angular and linear acceleration the return code is 3

See also

NewtonJointGetUserData, NewtonJointSetUserData

NewtonCorkscrewGetJointPosit

Get the relative joint angle between the two bodies.

Parameters

const NewtonJoint *Corkscrew - pointer to the joint.

Return

the joint angle relative to the hinge pin.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play a bell sound when the joint angle passes some max value.

See also

NewtonCorkscrewSetUserCallback

NewtonCorkscrewGetJointVeloc

dFloat NewtonCorkscrewGetJointVeloc(const NewtonJoint* Corkscrew)
Get the relative joint angular velocity between the two bodies.

Parameters

const NewtonJoint *Corkscrew - pointer to the joint.

Return

the joint angular velocity relative to the pin axis.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play the creaky noise of a hanging lamp.

See also

NewtonCorkscrewSetUserCallback

NewtonCorkscrewGetJointAngle

Get the relative joint angle between the two bodies.

Parameters

const NewtonJoint *Corkscrew - pointer to the joint.

Return

the joint angle relative to the corkscrew pin.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play a bell sound when the joint angle passes some max value.

See also

NewtonCorkscrewSetUserCallback

NewtonCorkscrewGetJointOmega

dFloat NewtonCorkscrewGetJointOmega(const NewtonJoint* Corkscrew)
Get the relative joint angular velocity between the two bodies.

Parameters

const NewtonJoint *Corkscrew - pointer to the joint.

Return

the joint angular velocity relative to the pin axis.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play the creaky noise of a hanging lamp.

See also

NewtonCorkscrewSetUserCallback

NewtonCorkscrewCalculateStopAlpha

Calculate the angular acceleration needed to stop the corkscrew at the desired angle.

Parameters

const NewtonJoint *Corkscrew | - | pointer to the joint.
NewtonCorkscrewSliderUpdateDesc *desc | - | is the pointer to the Corkscrew or slide structure.
dFloat angle | - | is the desired corkscrew stop angle

Return

the relative angular acceleration needed to stop the corkscrew.

Remarks

this function can only be called from a NewtonCorkscrewCallBack and it can be used by the application to implement corkscrew limits.

See also

NewtonCorkscrewSetUserCallback

NewtonCorkscrewGetJointForce

void NewtonCorkscrewGetJointForce(
const NewtonJoint* Corkscrew,
dFloat* force)
Calculate the angular acceleration needed to stop the corkscrew at the desired angle.

Parameters

const NewtonJoint *corkscrew | - | pointer to the joint.
NewtonCorkscrewCorkscrewUpdateDesc *desc | - | is the pointer to the Corkscrew or slide structure.
dFloat distance | - | desired stop distance relative to the pivot point

Return

the relative linear acceleration needed to stop the corkscrew.

Remarks

this function can only be called from a NewtonCorkscrewCallBack and it can be used by the application to implement corkscrew limits.

See also

NewtonCorkscrewSetUserCallback

NewtonCorkscrewGetJointForce

void NewtonCorkscrewGetJointForce(
const NewtonJoint* Corkscrew,
dFloat* force)
Get the total force asserted over the joint pivot point, to maintain the constraint.

Parameters

const NewtonJoint *Corkscrew | - | pointer to the joint.
dFloat *force | - | pointer to an array of a least three floats to hold the force value of the joint.

Return

nothing.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can destroy the joint if the force exceeds some predefined value.

See also

NewtonCorkscrewSetUserCallback

Universal joint interface

NewtonConstraintCreateUniversal

NewtonJoint* NewtonConstraintCreateUniversal(
const NewtonWorld* newtonWorld,
const dFloat* pivotPoint,
const dFloat* pinDir0,
const dFloat* pinDir1,
const NewtonBody* childBody,
const NewtonBody* parentBody)
Create a universal joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *pivotPoint | - | is origin of the universal joint in global space.
const NewtonCollision *pinDir0 | - | first axis of rotation fixed on childBody body and perpendicular to pinDir1.
const NewtonCollision *pinDir1 | - | second axis of rotation fixed on parentBody body and perpendicular to pinDir0.
const NewtonBody *childBody | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.
const NewtonBody *parentBody | - | is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body.

Return

Pointer to the universal joint.

Remarks

This function creates a universal joint and add it to the world. By default joint disables collision with the linked bodies.

Remark

a universal joint is a constraint that restricts twp rigid bodies to be connected to a point fixed on both bodies, while and allowing one body to spin around a fix axis in is own frame, and the other body to spin around another axis fixes on it own frame. Both axis must be mutually perpendicular.

NewtonUniversalSetUserCallback

void NewtonUniversalSetUserCallback(
const NewtonJoint* Universal,
NewtonUniversalCallBack callback)
Set an update call back to be called when either of the two body linked by the joint is active.

Parameters

const NewtonJoint *Universal | - | pointer to the joint.
NewtonUniversalCallBack callback | - | pointer to the joint function call back.

Return

nothing.

Remarks

if the application wants to have some feedback from the joint simulation, the application can register a function update callback to be called every time any of the bodies linked by this joint is active. This is useful to provide special effects like particles, sound or even to simulate breakable moving parts.

Remarks

the function NewtonUniversalCallBack callback should return a bit field code. if the application does not want to set the joint acceleration the retur code is zero if the application only wants to change the joint linear acceleration the return code is 1 if the application only wants to change the joint angular acceleration the return code is 2 if the application only wants to change the joint angular and linear acceleration the return code is 3

See also

NewtonJointGetUserData, NewtonJointSetUserData

NewtonUniversalGetJointAngle0

dFloat NewtonUniversalGetJointAngle0(const NewtonJoint* Universal)
Get the relative joint angle between the two bodies.

Parameters

const NewtonJoint *Universal - pointer to the joint.

Return

the joint angle relative to the universal pin0.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play a bell sound when the joint angle passes some max value.

See also

NewtonUniversalSetUserCallback

NewtonUniversalGetJointAngle1

dFloat NewtonUniversalGetJointAngle1(const NewtonJoint* Universal)
Get the relative joint angle between the two bodies.

Parameters

const NewtonJoint *Universal - pointer to the joint.

Return

the joint angle relative to the universal pin1.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play a bell sound when the joint angle passes some max value.

See also

NewtonUniversalSetUserCallback

NewtonUniversalGetJointOmega0

dFloat NewtonUniversalGetJointOmega0(const NewtonJoint* Universal)
Get the relative joint angular velocity between the two bodies.

Parameters

const NewtonJoint *Universal - pointer to the joint.

Return

the joint angular velocity relative to the pin0 axis.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play the creaky noise of a hanging lamp.

See also

NewtonUniversalSetUserCallback

NewtonUniversalGetJointOmega1

dFloat NewtonUniversalGetJointOmega1(const NewtonJoint* Universal)
Get the relative joint angular velocity between the two bodies.

Parameters

const NewtonJoint *Universal - pointer to the joint.

Return

the joint angular velocity relative to the pin1 axis.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can play the creaky noise of a hanging lamp.

See also

NewtonUniversalSetUserCallback

NewtonUniversalCalculateStopAlpha0

dFloat NewtonUniversalCalculateStopAlpha0(
const NewtonJoint* universal,
const NewtonHingeSliderUpdateDesc* desc,
dFloat angle)
Calculate the angular acceleration needed to stop the universal at the desired angle.

Parameters

const NewtonJoint *Universal | - | pointer to the joint.
NewtonUniversalSliderUpdateDesc *desc | - | is the pointer to the Universal or slide structure.
dFloat angle | - | is the desired universal stop angle rotation around pin0

Return

the relative angular acceleration needed to stop the universal.

Remarks

this function can only be called from a NewtonUniversalCallBack and it can be used by the application to implement universal limits.

See also

NewtonUniversalSetUserCallback

NewtonUniversalCalculateStopAlpha1

dFloat NewtonUniversalCalculateStopAlpha1(
const NewtonJoint* universal,
const NewtonHingeSliderUpdateDesc* desc,
dFloat angle)
Calculate the angular acceleration needed to stop the universal at the desired angle.

Parameters

const NewtonJoint *Universal | - | pointer to the joint.
NewtonUniversalSliderUpdateDesc *desc | - | is the pointer to and the Universal or slide structure.
dFloat angle | - | is the desired universal stop angle rotation around pin1

Return

the relative angular acceleration needed to stop the universal.

Remarks

this function can only be called from a NewtonUniversalCallBack and it can be used by the application to implement universal limits.

See also

NewtonUniversalSetUserCallback

NewtonUniversalGetJointForce

void NewtonUniversalGetJointForce(
const NewtonJoint* Universal,
dFloat* force)
Get the total force asserted over the joint pivot point, to maintain the constraint.

Parameters

const NewtonJoint *Universal | - | pointer to the joint.
dFloat *force | - | pointer to an array of a least three floats to hold the force value of the joint.

Return

nothing.

Remarks

this function can be used during a function update call back to provide the application with some special effect. for example the application can destroy the joint if the force exceeds some predefined value.

See also

NewtonUniversalSetUserCallback

UpVector joint Interface

NewtonConstraintCreateUpVector

Create a UpVector joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonCollision *pinDir | - | is the aligning vector.
const NewtonBody *body | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.

Return

Pointer to the up vector joint.

Remarks

This function creates an up vector joint. An up vector joint is a constraint that allows a body to translate freely in 3d space, but it only allows the body to rotate around the pin direction vector. This could be use by the application to control a character with physics and collision.

Remark

Since the UpVector joint is a unary constraint, there is not need to have user callback or user data assigned to it. The application can simple hold to the joint handle and update the pin on the force callback function of the rigid body owning the joint.

NewtonUpVectorGetPin

void NewtonUpVectorGetPin(
const NewtonJoint* upVector,
dFloat *pin)
Get the up vector pin of this joint in global space.

Parameters

const NewtonJoint *upVector | - | pointer to the joint.
dFloat *pin | - | pointer to an array of a least three floats to hold the up vector direction in global space.

Return

nothing.

Remarks

the application ca call this function to read the up vector, this is useful to animate the up vector. if the application is going to animated the up vector, it must do so by applying only small rotation, too large rotation can cause vibration of the joint.

See also

NewtonUpVectorSetUserCallback, NewtonUpVectorSetPin

NewtonUpVectorSetPin

void NewtonUpVectorSetPin(
const NewtonJoint* upVector,
const dFloat *pin)
Set the up vector pin of this joint in global space.

Parameters

const NewtonJoint *upVector | - | pointer to the joint.
dFloat *pin | - | pointer to an array of a least three floats containing the up vector direction in global space.

Return

nothing.

Remarks

the application ca call this function to change the joint up vector, this is useful to animate the up vector. if the application is going to animated the up vector, it must do so by applying only small rotation, too large rotation can cause vibration of the joint.

See also

NewtonUpVectorSetUserCallback, NewtonUpVectorGetPin

User defined joint interface

NewtonConstraintCreateUserJoint

NewtonJoint* NewtonConstraintCreateUserJoint(
const NewtonWorld* newtonWorld,
int maxDOF,
NewtonUserBilateralCallBack callback,
const NewtonBody* childBody,
const NewtonBody* parentBody)
Create a user define bilateral joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
in*t maxDOF | - | is the maximum number of degree of freedom controlled by this joint.
NewtonUpVectorCallBack callback | - | pointer to the joint function call back.
const NewtonBody *childBody | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.
const NewtonBody *parentBody | - | is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body.

Remark

Bilateral joint are constraints that can have up to 6 degree of freedoms, 3 linear and 3 angular. By restricting the motion along any number of these degree of freedom a very large number of useful joint between two rigid bodies can be accomplished. Some of the degree of freedoms restriction makes no sense, and also some combinations are so rare that only make sense to a very specific application, the Newton engine implements the more commons combinations like, hinges, ball and socket, etc. However if and application is in the situation that any of the provided joints can achieve the desired effect, then the application can design it own joint.

Remark

User defined joint is a very advance feature that should be look at, only for very especial situations. The designer must be a person with a very good understanding of constrained dynamics, and it may be the case that many trial have to be made before a good result can be accomplished.

Remark

maxDOF is and upper bound as to how many degrees of freedoms the joint can control, usually this value can be 6 for bilateral joints, but it can be higher for special joints like vehicles where by the used of friction clamping the number of rows can be higher. In general the application should determine maxDof correctly, passing an unnecessary excessive value will lead to performance decreased.

NewtonUserJointAddLinearRow

void NewtonUserJointAddLinearRow(
const NewtonJoint* joint,
const dFloat *pivot0,
const dFloat *pivot1,
const dFloat *dir)
Add a linear restricted degree of freedom.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
const dFloat *pivot0 | - | pointer of a vector in global space fixed on body zero.
const dFloat *pivot1 | - | pointer of a vector in global space fixed on body one.
const dFloat *pin | - | pointer of a unit vector in global space along which the relative position, velocity and acceleration between the bodies will be driven to zero.

Remark

A linear contraint row calculates the Jacobian derivatives and relative acceleration required to enforce the constraint condition at the attachment point and the pin direction considered fixed to both bodies.

Remark

The acceleration is calculated such that the relative linear motion between the two points is zero, the application can afterward override this value to create motors.

Remark

after this function is call and internal DOF index will point to the current row entry in the constraint matrix.

Remark

This function call only be called from inside a NewtonUserBilateralCallBack callback.

See also

NewtonUserJointAddAngularRow,

NewtonUserJointAddAngularRow

void NewtonUserJointAddAngularRow(
const NewtonJoint* joint,
dFloat relativeAngleError,
const dFloat *pin)
Add an angular restricted degree of freedom.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat relativeAngleError | - | relative angle error between both bodies around pin axis.
const dFloat *pin | - | pointer of a unit vector in global space along which the relative position, velocity and acceleration between the bodies will be driven to zero.

Remark

An angular contraint row calculates the Jacobian derivatives and relative acceleration required to enforce the constraint condition at pin direction considered fixed to both bodies.

Remark

The acceleration is calculated such that the relative angular motion between the two points is zero, The application can afterward override this value to create motors.

Remark

After this function is called and internal DOF index will point to the current row entry in the constraint matrix.

Remark

This function call only be called from inside a NewtonUserBilateralCallBack callback.

Remark

This function is of not practical to enforce hard constraints, but it is very useful for making angular motors.

See also

NewtonUserJointAddLinearRow, NewtonUserJointAddIndependentAngularRow

NewtonUserJointAddGeneralRow

void NewtonUserJointAddGeneralRow(
const NewtonJoint* joint,
const dFloat *jacobian0,
const dFloat *jacobian1)
set the general linear and angular Jacobian for the desired degree of freedom

Parameters

const NewtonJoint *joint | - | pointer to the joint.
const dFloat *jacobian0 | - | pointer of a set of six values defining the linear and angular Jacobian for body0.
const dFloat *jacobian1 | - | pointer of a set of six values defining the linear and angular Jacobian for body1.

Remark

In general this function must be used for very special effects and in combination with other joints. it is expected that the user have a knowledge of Constrained dynamics to make a good used of this function. Must typical application of this function are the creation of synchronization or control joints like gears, pulleys, worm gear and some other mechanical control.

Remark

this function set the relative acceleration for this degree of freedom to zero. It is the application responsibility to set the relative acceleration after a call to this function

See also

NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow

NewtonUserJointSetRowMaximumFriction

void NewtonUserJointSetRowMaximumFriction(
const NewtonJoint* joint,
dFloat friction)
Set the maximum friction value the solver is allow to apply to the joint row.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat friction | - | maximum friction value for this row. It must be a positive value between 0.0 and INFINITY.

Remark

This function will override the default friction values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. friction value is context sensitive, if for linear constraint friction is a Max friction force, for angular constraint friction is a max friction is a Max friction torque.

See also

NewtonUserJointSetRowMinimumFriction, NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow

NewtonUserJointSetRowMinimumFriction

void NewtonUserJointSetRowMinimumFriction(
const NewtonJoint* joint,
dFloat friction)
Set the minimum friction value the solver is allow to apply to the joint row.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat friction | - | friction value for this row. It must be a negative value between 0.0 and -INFINITY.

Remark

This function will override the default friction values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. friction value is context sensitive, if for linear constraint friction is a Min friction force, for angular constraint friction is a friction is a Min friction torque.

See also

NewtonUserJointSetRowMaximumFriction, NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow

NewtonUserJointSetRowAcceleration

void NewtonUserJointSetRowAcceleration(
const NewtonJoint* joint,
dFloat acceleration)
Set the value for the desired acceleration for the current constraint row.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat acceleration | - | desired acceleration value for this row.

Remark

This function will override the default acceleration values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. friction value is context sensitive, if for linear constraint acceleration is a linear acceleration, for angular constraint acceleration is an angular acceleration.

See also

NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow

NewtonUserJointSetRowSpringDamperAcceleration

void NewtonUserJointSetRowSpringDamperAcceleration(
const NewtonJoint* joint,
dFloat springK,
dFloat springD)
Calculates the row acceleration to satisfy the specified the spring damper system.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat springK | - | desired spring stiffness, it must be a positive value.
dFloat springD | - | desired spring damper, it must be a positive value.

Remark

This function will override the default acceleration values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. friction value is context sensitive, if for linear constraint acceleration is a linear acceleration, for angular constraint acceleration is an angular acceleration.

Remark

the acceleration calculated by this function represent the mass, spring system of the form

a = -ks * x - kd * v.

Remark

for this function to take place the joint stiffness must be set to a values lower than 1.0

See also

NewtonUserJointSetRowAcceleration, NewtonUserJointSetRowStiffness

NewtonUserJointSetRowStiffness

void NewtonUserJointSetRowStiffness(
const NewtonJoint* joint,
dFloat stiffness)
Set the maximum percentage of the constraint force that will be applied to the constraint row.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat stiffness | - | row stiffness, it must be a values between 0.0 and 1.0, the default is 0.9.

Remark

This function will override the default stiffness value set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. the row stiffness is the percentage of the constraint force that will be applied to the rigid bodies. Ideally the value should be 1.0 (100% stiff) but dues to numerical integration error this could be the joint a little unstable, and lower values are preferred.

See also

NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow, NewtonUserJointSetRowSpringDamperAcceleration

NewtonUserJointGetRowForce

dFloat NewtonUserJointGetRowForce(
const NewtonJoint* joint,
int row)
Return the magnitude previews force or torque value calculated by the solver for this contraint row.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
int row | - | index to the constraint row.

Remark

This function can be call for any of the previews row for this particular joint, The application must keep track of the meaning of the row.

Remark

This function can be used to produce special effects like breakable or malleable joints, fro example a hinge can turn into ball and sockect after the force in some of the row excide certain high value.

Joint common function s

NewtonJointSetUserData

void NewtonJointSetUserData(
const NewtonJoint* joint,
void* userData)
Store a user defined data value with the joint.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
void *userDataPtr | - | pointer to the user defined user data value.

Return

Nothing.

Remarks

The application can store a user defined value with the Joint. This value can be the pointer to a structure containing some application data for special effect. if the application allocate some resource to store the user data, the application can register a joint destructor to get rid of the allocated resource when the Joint is destroyed

See also

NewtonConstraintCreateJoint, NewtonJointSetDestructor

NewtonJointGetUserData

void* NewtonJointGetUserData(const NewtonJoint* joint)
Retrieve a user defined data value stored with the joint.

Parameters

const NewtonJoint *joint - pointer to the joint.

Return

The user defined data.

Remarks

The application can store a user defined value with a joint. This value can be the pointer to a structure to store some game play data for special effect.

See also

NewtonJointSetUserData

NewtonJointSetCollisionState

void NewtonJointSetCollisionState(
const NewtonJoint* joint,
int state)
Enable or disable collision between the two bodies linked by this joint. The default state is collision disable when the joint is created.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
int state | - | collision state, zero mean disable collision, non zero enable collision between linked bodies.

Return

nothing.

Remarks

usually when two bodies are linked by a joint, the application wants collision between this two bodies to be disabled. This is the default behavior of joints when they are created, however when this behavior is not desired the application can change it by setting collision on. If the application decides to enable collision between jointed bodies, the application should make sure the collision geometry do not collide in the work space of the joint.

Remarks

if the joint is destroyed the collision state of the two bodies linked by this joint is determined by the material pair assigned to each body.

See also

NewtonJointGetCollisionState, NewtonBodySetJointRecursiveCollision

NewtonJointGetCollisionState

int NewtonJointGetCollisionState(const NewtonJoint* joint)
Get the collision state of the two bodies linked by the joint.

Parameters

const NewtonJoint *joint - pointer to the joint.

Return

the collision state.

Remarks

usually when two bodies are linked by a joint, the application wants collision between this two bodies to be disabled. This is the default behavior of joints when they are created, however when this behavior is not desired the application can change it by setting collision on. If the application decides to enable collision between jointed bodies, the application should make sure the collision geometry do not collide in the work space of the joint.

See also

NewtonJointSetCollisionState

NewtonJointSetStiffness

void NewtonJointSetStiffness(
const NewtonJoint* joint,
dFloat stiffness)
Set the strength coeficient to be applied to the joint reaction forces.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat stiffness | - | stiffness coeficient, a value between 0, and 1.0, the default value for most joint is 0.9

Return

nothing.

Remarks

Constraint keep bodies together by calculating the exact force necessary to cancel the relative acceleration between one or more common points fixed in the two bodies. The problem is that when the bodies drift apart due to numerical integration inaccuracies, the reaction force work to pull eliminated the error but at the expense of adding extra energy to the system, does violating the rule that constraint forces must be work less. This is a inevitable situation and the only think we can do is to minimize the effect of the extra energy by dampening the force by some amount. In essence the stiffness coefficient tell Newton calculate the precise reaction force by only apply a fraction of it to the joint point. And value of 1.0 will apply the exact force, and a value of zero will apply only 10 percent.

Remark

The stiffness is set to a all around value that work well for most situation, however the application can play with these parameter to make finals adjustment. A high value will make the joint stronger but more prompt to vibration of instability; a low value will make the joint more stable but weaker.

See also

NewtonJointGetStiffness

NewtonJointGetStiffness

dFloat NewtonJointGetStiffness(const NewtonJoint* joint)
Get the strength coefficient bing applied to the joint reaction forces.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
dFloat stiffness | - | stiffness coeficient, a value between 0, and 1.0, the default value for most joint is 0.9

Return

stiffness coeficient.

Remarks

Constraint keep bodies together by calculating the exact force necessary to cancel the relative acceleration between one or more common points fixed in the two bodies. The problem is that when the bodies drift apart due to numerical integration inaccuracies, the reaction force work to pull eliminated the error but at the expense of adding extra energy to the system, does violating the rule that constraint forces must be work less. This is a inevitable situation and the only think we can do is to minimize the effect of the extra energy by dampening the force by some amount. In essence the stiffness coefficient tell Newton calculate the precise reaction force by only apply a fraction of it to the joint point. And value of 1.0 will apply the exact force, and a value of zero will apply only 10 percent.

Remark

The stiffness is set to a all around value that work well for most situation, however the application can play with these parameter to make finals adjustment. A high value will make the joint stronger but more prompt to vibration of instability; a low value will make the joint more stable but weaker.

See also

NewtonJointSetStiffness

NewtonJointSetDestructor

void NewtonJointSetDestructor(
const NewtonJoint* joint,
NewtonConstraintDestructor destructor)
Register a destructor callback to be called when the joint is about to be destroyed.

Parameters

const NewtonJoint *joint | - | pointer to the joint.
NewtonJointCallBack destructor | - | pointer to the joint destructor callback.

Return

nothing.

Remarks

If application stores any resource with the joint, or the application wants to be notified when the joint is about to be destroyed. The application can register a destructor call back with the joint.

See also

NewtonJointSetUserData

NewtonDestroyJoint

void NewtonDestroyJoint(
const NewtonWorld* newtonWorld,
const NewtonJoint* joint)
destroy a joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the body.
const NewtonJoint *joint | - | pointer to joint to be destroyed

Return

nothing

Remarks

The application can call this function when it wants to destroy a joint. This function can be used by the application to simulate breakable joints

See also

NewtonConstraintCreateJoint, NewtonConstraintCreateHinge, NewtonConstraintCreateSlider

Rag doll joint container Interface

NewtonCreateRagDoll

NewtonRagDoll* NewtonCreateRagDoll(const NewtonWorld* newtonWorld)
Create an empty rag doll container.

Parameters

const NewtonWorld *newtonWorld - is the pointer to the Newton world.

Return

handle to an empty rag doll container.

Remarks

A rag doll container is the encapsulation of a group of ball and socket joints, under a common object. It provides common functional shared by all joints in the tree like structure. The rag doll object job is to simplify some of the common task that the programmer encounters when it tries to make a rag doll model by connecting joints. It also has some limitations, for example the hierarchy of joints is made of Ball and socket joints, it only support tree like structures of joints, the joints can not by detached from the array once they are added to the rag doll. Rag doll joints are good to make articulated creatures, like humans, monsters, horses, etc. They are good to simulate effects like death of a character in a game.

See also

NewtonDestroyRagDoll

NewtonDestroyRagDoll

void NewtonDestroyRagDoll(
const NewtonWorld* newtonWorld,
const NewtonRagDoll* ragDoll)
Destroy a ragdoll containers and all it components.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const NewtonRagDoll *ragDoll | - | handle to a rag doll container.

Return

nothing

See also

NewtonCreateRagDoll

NewtonRagDollBegin

void NewtonRagDollBegin(const NewtonRagDoll* ragDoll)
Prepare a rag doll object to accept bones and making the skeleton.

Parameters

const NewtonRagDoll *ragDoll - handle to a rag doll container.

Return

nothing

Remarks

This function will clean up the rag doll container of any previously added bone. After the constructions process of the rag doll is completed the application should call NewtonRagDollEnd, not doing so will result in unpredictable results.

See also

NewtonRagDollEnd, NewtonRagDollAddBone, SetExtForceAndTorqueCallback, SetTransformCallback

NewtonRagDollEnd

void NewtonRagDollEnd(const NewtonRagDoll* ragDoll)
Finalized the rag doll construction process.

Parameters

const NewtonRagDoll *ragDoll - handle to a rag doll container.

Return

nothing

Remarks

This function should be called after the constructions process of the rag doll in completed. calling this function without first calling NewtonRagDollBegin will produce unpredictable results.

See also

NewtonRagDollBegin

NewtonRagDollAddBone

NewtonRagDollBone* NewtonRagDollAddBone(
const NewtonRagDoll* ragDoll,
const NewtonRagDollBone* parent,
void *userData,
dFloat mass,
const dFloat* matrix,
const NewtonCollision* boneCollision,
const dFloat* size)
Add a bone to a rag doll objects.

Parameters

const NewtonRagDoll *ragDoll | - | handle to a rag doll container.
const NewtonRagDollBone *parent | - | handle to the bone parent for this bone. If this is the root bone the parent should be NULL.
void *userData | - | user data value. The application can use this parameter to store the pointer on index into the graphical part representing this bone.
dFloat mass | - | mass of this body part.
const dFloat *matrix | - | pointer to a 4x4 transformation matrix in the local space of the bone. The matrix should be expressed relative to the parent bone.
const NewtonCollision *boneCollision | - | bone collision geometry.
const dFloat size | - | pointer to an array of three dFloat specifying the size of this body part. The first component of the array is interpreted as the length of the bone.

Return

the handle to a Rag doll bone

Remarks

The user data value of a rag doll rigid body is set to the NewtonRagDollBone, Unpredictable result will happens if the application set the user data of a rag doll node rigid body.

Remarks

this function can only be called from inside of a NewtonRagDollBegin/NewtonRagDollEnd pair.

See also

NewtonRagDollBegin

NewtonRagDollBoneGetUserData

void* NewtonRagDollBoneGetUserData(const NewtonRagDollBone* bone)
Retrieve a user defined data value stored with the rag doll bone.

Parameters

const NewtonRagDollBone *bone - pointer to the bone.

Return

The user defined data.

Remarks

The application can store a user defined value with a rigid body. This value can be the pointer to a structure which is the graphical representation of the bone.

See also

NewtonRagDollAddBone

NewtonRagDollSetTransformCallback

void NewtonRagDollSetTransformCallback(
const NewtonRagDoll* ragDoll,
NewtonSetRagDollTransform callback)
Assign a transformation event function to a rag doll object.

Parameters

const NewtonRagDoll *ragDoll | - | handle to a rag doll container.
NewtonSetRagDollTransform callback | - | pointer to a function callback is used to update the transformation matrix of the visual object that represents the rag doll.

Return

Nothing.

Remarks

The function NewtonSetRagDollTransform callback is called by the Newton engine every time a visual object that represent a bone of a rag doll has changed. The application can obtain the pointer user data value that points to the visual object. The Newton engine does not call the NewtonSetRagDollTransform callback function for bones that are inactive or have reached a state of stable equilibrium.

Remarks

The user data value of a rag doll rigid body is set to the NewtonRagDollBone, Unpredictable result will happens if the application set the user data of a rag doll node rigid body. The application can get the pointer to the application graphical data by retrieving the user data stored with the NewtonRagDollBone.

Remarks

The matrix should be organized in row-major order (this is the way directX stores matrices). If you are using OpenGL matrices (column-major) you will need to transpose the matrices into a local array, before you pass them to Newton.

Remarks

this function can only be called from inside of a NewtonRagDollBegin/NewtonRagDollEnd pair.

See also

NewtonRagDollBegin, NewtonRagDollAddBone

NewtonRagDollSetForceAndTorqueCallback

void NewtonRagDollSetForceAndTorqueCallback(
const NewtonRagDoll* ragDoll,
NewtonApplyForceAndTorque callback)
Assign an event function for applying external force and torque to a Rag doll.

Parameters

const NewtonRagDoll *ragDoll | - | handle to a rag doll container.
NewtonApplyForceAndTorque callback | - | pointer to a function callback used to apply force and torque to a rigid body bone.

Return

Nothing.

Remarks

this function can be seen as a utility function that will call NewtonBodySetForceAndTorqueCallback for every bone of a rag doll object.

Remarks

The user data value of a rag doll rigid body is set to the NewtonRagDollBone, unpredictable result will happens if the application set the user data of a rag doll node rigid body. The application can get the pointer to the application graphical data by retrieving the user data stored with the NewtonRagDollBone.

Remarks

Before the NewtonApplyForceAndTorque callback is called for a body, Newton first clears the net force and net torque for the body.

Remarks

The function NewtonApplyForceAndTorque callback is called by the Newton Engine every time an active body is going to be simulated. The Newton Engine does not call the NewtonApplyForceAndTorque callback function for bodies that are inactive or have reached a state of stable equilibrium.

See also

NewtonRagDollBegin, NewtonRagDollAddBone

NewtonRagDollBoneSetID

Set an id for this particular bone.

Parameters

const NewtonRagDollBone *bone | - | handle to the bone.
int id | - | identifier for this bone.

Return

Nothing.

Remarks

during the construction, the application has the option to set an identifier for each bone. It is good idea to make this identifier unique for the rag doll.

See also

NewtonRagDollAddBone, NewtonRagDollFindBone

NewtonRagDollFindBone

NewtonRagDollBone* NewtonRagDollFindBone(
const NewtonRagDoll* ragDoll,
int id)
Find the first bone with this id in this rag doll.

Parameters

const NewtonRagDoll *ragDoll | - | handle to a rag doll container.
int id | - | identifier for this bone.

Return

the handle to the bone with this identifier. NULL if no bone in the rag doll has this id

Remarks

during the construction, the application has the option to set an identifier for each bone. It is good idea to make this identifier unique for the rag doll. the application can use this id to find particular bones in the rag doll body. This is useful for authoring tolls.

See also

NewtonRagDollBoneSetID

NewtonRagDollBoneGetBody

NewtonBody* NewtonRagDollBoneGetBody(const NewtonRagDollBone* bone)
Retrieve the rigid body assigned to this bone.

Parameters

const NewtonRagDollBone *bone - handle to the bone.

Return

The rigid body assigned to this bone

Remarks

this function can be used to customized some of the properties of the rigid body assigned to the bone. the application should not override the pointer to TransformCallback or ApplyForceAndTorque of a rigid body assigned to a Rag doll bone. It should call the functions NewtonRagDollSetTransformCallback and NewtonRagDollSetForceAndTorqueCallback instead.

See also

NewtonRagDollAddBone, NewtonRagDollSetTransformCallback, NewtonRagDollSetForceAndTorqueCallback

NewtonRagDollBoneSetLimits

void NewtonRagDollBoneSetLimits(
const NewtonRagDollBone* bone,
const dFloat* coneDir,
dFloat minConeAngle,
dFloat maxConeAngle,
dFloat maxTwistAngle,
const dFloat* lateralConeDir,
dFloat negativeBilateralConeAngle,
dFloat positiveBilateralConeAngle)
Set the stop limits for this bone.

Parameters

const NewtonRagDollBone *bone | - | handle to this particular bone. If this parameter is the root bone, then the limits do not have any effect.
const dFloat *coneDir | - | pointer to an array of tree dFloat specifying the direction in global space of the cone limits for this bone.
dFloat minConeAngle | - | minimum value of the cone of the cone limit.
dFloat maxConeAngle | - | maximum value of the cone of the cone limit.
dFloat maxTwistAngle | - | maximum and minimum that this bone is allow to spin around the coneDir.
const dFloat *lateralConeDir | - | this parameter is ignored in this release.
dFloat negativeBilateralConeAngle | - | this parameter is ignored in this release.
dFloat negativeBilateralConeAngle | - | this parameter is ignored in this release.

Remarks

This function set a cone fixed on the frame of the parent of this bone and defining the work space of the bone.

See also

NewtonRagDollBegin

NewtonRagDollBoneGetLocalMatrix

void NewtonRagDollBoneGetLocalMatrix(
const NewtonRagDollBone* bone,
dFloat* matrixPtr)
Get the transformation matrix for this bone in the local space of the bone.

Parameters

const NewtonRagDollBone *bone | - | handle to this particular bone. If this parameter is the root bone, then the limits do not have any effect.
dFloat *matrix | - | pointer to a 4x4 transformation matrix to receive the transformation matrix for this bone.

Remarks

the application can call this function from a NewtonSetRagDollTransform to get the transformation matrix for the graphical representation of the bone in local space.

See also

NewtonRagDollSetTransformCallback

NewtonRagDollBoneGetGlobalMatrix

void NewtonRagDollBoneGetGlobalMatrix(
const NewtonRagDollBone* bone,
dFloat* matrixPtr)
Get the transformation matrix for this bone in the global space of the bone.

Parameters

const NewtonRagDollBone *bone | - | handle to this particular bone. If this parameter is the root bone, then the limits do not have any effect.
dFloat *matrix | - | pointer to a 4x4 transformation matrix to receive the transformation matrix for this bone.

Remarks

the application can call this function from a NewtonSetRagDollTransform to get the transformation matrix for the graphical representation of the bone in global space.

See also

NewtonRagDollSetTransformCallback

Vehicle constraint interface

NewtonConstraintCreateVehicle

NewtonJoint* NewtonConstraintCreateVehicle(
const NewtonWorld* newtonWorld,
const dFloat* upDir,
const NewtonBody* body)
Create and empty vehicle joint.

Parameters

const NewtonWorld *newtonWorld | - | is the pointer to the Newton world.
const dFloat *upDir | - | is the unit vector defined by the tires pivot points, usually the opposite direction to the gravity vector.
const NewtonBody *body | - | is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass.

Return

Pointer to the vehicle joint.

Remarks

This joint provides basics functionality for simulating real-time simplistic vehicle dynamics. The joint is not meant to be and accurate and realistic representation of a real vehicle, that is out of the scope of a real-time physics engine. The vehicle is made out of a main rigid body visible to the application and attached to it a set of tires not visible to the application directly as rigid bodies. The tires are connected to the body via rigid wheel joints providing the ability for the tire to spin, have suspension, and turn. The internal vehicle mechanics like transmission, power transfer shaft, suspension mechanism, doors etc. It only models the vehicle body mounted on a set of wheels, with suspension and the ability to roll.

NewtonVehicleSetTireCallback

void NewtonVehicleSetTireCallback(
const NewtonJoint* vehicle,
NewtonVehicleTireUpdate update)
Store a function callback pointer for vehicle update.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
NewtonVehicleTireUpdate update | - | pointer to the callback function.

Return

nothing

Remarks

The only way to control a vehicle is by implementing the vehicle update callback. The application should iterate through each tire applying tire dynamics to each one.

See also

NewtonVehicleGetFirstTireID, NewtonVehicleGetNextTireID

NewtonVehicleAddTire

void* NewtonVehicleAddTire(
const NewtonJoint* vehicle,
const dFloat* localMatrix,
const dFloat* pin,
dFloat mass,
dFloat width,
dFloat radius,
dFloat suspesionShock,
dFloat suspesionSpring,
dFloat suspesionLength,
void* userData,
int collisionID)
Add a new tire to the vehicle container.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
const dFloat *localMatrix | - | pointer to an array of 16 floats containing the offset of the tire relative to the vehicle body.
const dFloat pin | - | pointer to an array of 3 floats containing the rotation axis of the tire, in the space of the tire.
dFloat mass | - | tire mass, must be much smaller than the vehicle body. ratio of 50:1 to 100:1 are the recommended values.
dFloat width | - | width of the tire, must be smaller than the tire radius.
dFloat radius | - | tire radius.
dFloat suspesionShock | - | parametrized damping constant for a spring, mass, damper system. A value of one corresponds to a critically damped system.
dFloat suspesionSpring | - | parametrized spring constant for a spring, mass, damper system. A value of one corresponds to a critically damped system.
dFloat suspesionLength | - | distance from the tire set position to the upper stop on the vehicle body frame. The total suspension length is twice that.
void *userData | - | pointer to a user define data value. Usually used to store the pointer to the graphical representation of the tire.
int collisionID | - | the collision ID use by the application to identify the tire contacts in a contact callback function.

Return

the tire ID.

Remarks

After the application creates the vehicle joint, it must add the tires. Tires are added one at a time at the graphics set position and with the appropriate. the application should calculate the correct tire parameters, like tire mass, position, width height, spring and damper constants.

See also

NewtonVehicleRemoveTire

NewtonVehicleReset

void NewtonVehicleReset(const NewtonJoint* vehicle)
Reset all tires velocities to zero.

Parameters

const NewtonJoint *vehicle - pointer to the vehicle joint.

Return

nothing.

This function is useful for reposition the vehicle.

NewtonVehicleRemoveTire

void NewtonVehicleRemoveTire(
const NewtonJoint* vehicle,
void* tireId)
Detach and destroy a tire from the vehicle.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | tire index to be destroyed.

Return

nothing.

NewtonVehicleGetFirstTireID

void* NewtonVehicleGetFirstTireID(const NewtonJoint* vehicle)
Get the index of the first tire of the vehicle tire set.

Parameters

const NewtonJoint *vehicle - pointer to the vehicle joint.

Return

tire index.

Remarks

This function is usually used from inside the vehicle update callback. It is used to iterate through the tire set applying the tire dynamics.

See also

NewtonVehicleGetNextTireID

NewtonVehicleGetNextTireID

void* NewtonVehicleGetNextTireID(
const NewtonJoint* vehicle,
void* tireId)
Get the index of the next tire on the tire set.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

Next tire index, or zero if index tireId was pointing to the last tire in the set.

Remarks

This function is usually used from inside a tire update callback. It is used to iterate through the tire set applying the tire dynamics.

See also

NewtonVehicleGetFirstTireID

NewtonVehicleGetTireUserData

Retrieve the pointer to the tire user data.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

tire user data.

Remarks

This function is usually used from the vehicle update callback or from transformation callback of the vehicle body, It can used do set the transformation matrix of the tire graphical representation.

NewtonVehicleGetTireMatrix

void NewtonVehicleGetTireMatrix(
const NewtonJoint* vehicle,
void* tireId,
dFloat* matrix)
Retrieve the transformation matrix of the tire in global space.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat matrix | - | pointer to an array of 16 floats containing the global matrix of the tire.

Return

nothing

Remarks

This function is usually used from the tire update callback or from transformation callback of the vehicle body, It can be used to set the transformation of the tire graphical representation.

NewtonVehicleGetTireSteerAngle

dFloat NewtonVehicleGetTireSteerAngle(
const NewtonJoint* vehicle,
void* tireId)
Get the tire steering angle.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

steering angle.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleSetTireSteerAngle

void NewtonVehicleSetTireSteerAngle(
const NewtonJoint* vehicle,
void* tireId,
dFloat angle)
Set the tire steering angle.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat angle | - | new steering angle.

Return

nothing.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleSetTireTorque

void NewtonVehicleSetTireTorque(
const NewtonJoint* vehicle,
void* tireId,
dFloat torque)
Set the tire torque.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat torque | - | new torque value.

Return

nothing.

Remarks

This function is useful to simulate normal vehicles with wheels that propel by applying torque to a the tire axis in order to move.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleGetTireOmega

dFloat NewtonVehicleGetTireOmega(
const NewtonJoint* vehicle,
void* tireId)
Retrieve the tire angular velocity.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

angular velocity.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleGetTireNormalLoad

dFloat NewtonVehicleGetTireNormalLoad(
const NewtonJoint* vehicle,
void* tireId)
Return the part of the vehicle weight supported by this tire.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

magnitude of the vehicle weight supported by this tire.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleTireSetBrakeAcceleration

void NewtonVehicleTireSetBrakeAcceleration(
const NewtonJoint* vehicle,
void* tireId,
dFloat acceleration,
dFloat maxFrictionTorque)
Apply the acceleration and max friction torque to a tire axis.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat acceleration | - | desire tire acceleration.
dFloat maxFrictionTorque | - | maximum friction torque the tire brake, or tire motor can withstand.

Return

noting.

Remarks

This is a multipurpose function. The more common use is to apply hand or soft brakes to a vehicle. To apply brakes the application may use the function NewtonVehicleTireSetBrakeAcceleration to determine the exact acceleration needed to stop the tire from continue to spin in one frame. To simulated the variable brakes strength the application can use a nominal maximum friction torque (just like in real life any device will withstand a max value) and modulate this value with an analog control. For hand brakes the application set the control to the maximum and for soft brakes it can just modulate the variable friction. Another use for this function is to simulate rolling friction, For this effect the application apply the acceleration to stop but with a friction value set to a minimum non zero fixed value. Note that brakes and tire torque are not mutually exclusive, the application can apply then simultaneously. As a matter of fact doing so is quite a satisfying test showing how the vehicles rocks forth and back due to the engine torque, while the tire prevent it from moving. Another use for this function is the simulation of track based vehicles. For this the application apply an arbitrary fix acceleration to the tires on each side of the vehicle. A function as simple as A = Ad minus Ks x Omega can do the trick, where Ad is the desire acceleration controlled by the application joystick, Ks is some viscous velocity damping, and omega is the current tire angular velocity reported by the function NewtonVehicleGetTireOmega. To make the vehicle take turns the application can elaborate the equation like A = Ad + At minus Ks x Omega where At is the differential acceleration supplied by the steering control, for the tires on the right side At is positive while for tires of the left side At is negative.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

See also

NewtonVehicleTireCalculateMaxBrakeAcceleration, NewtonVehicleGetTireOmega

NewtonVehicleTireCalculateMaxBrakeAcceleration

dFloat NewtonVehicleTireCalculateMaxBrakeAcceleration(
const NewtonJoint* vehicle,
void* tireId)
Calculate the exact acceleration needed to be applied to a tire axis in order to bring it to full stop in one time step.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

exact acceleration for full stop of the tire.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

See also

NewtonVehicleTireSetBrakeAcceleration

NewtonVehicleGetTireLateralSpeed

dFloat NewtonVehicleGetTireLateralSpeed(
const NewtonJoint* vehicle,
void* tireId)
Return the tire speed along the tire pin axis.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

tire lateral speed.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleGetTireLongitudinalSpeed

dFloat NewtonVehicleGetTireLongitudinalSpeed(
const NewtonJoint* vehicle,
void* tireId)
Return the tire speed along the axis perpendicular to the tire pin axis and the vehicle upvector.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

tire longitudinal speed.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleSetTireMaxSideSleepSpeed

void NewtonVehicleSetTireMaxSideSleepSpeed(
const NewtonJoint* vehicle,
void* tireId,
dFloat speed)
Set the maximum side slip velocity for the tire to be considered to lose grip.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat speed | - | maximum side speed before the vehicle is considered to loose side grip.

Return

nothing.

Remarks

Tire operation involve a mix of elastic distortion and sliding friction. To have and idea how to code a convincing approximation of a real tire we must run some experiment and make some reflection upon the result. First we will run a static test: keeping a tire at equilibrium applying a constant load and without rolling, we will apply a lateral force perpendicular to the tire plane and applied at the tire center. If we run this experiment we will find that the tire will deflect in response to the lateral force. If we increase the magnitude of the lateral force, the magnitude of the deflection is proportional to the magnitude of the lateral force, until the tire begins to slide. This show that when a tire is not moving it behaves like a spring (elastic distortion). If we repeat this experiment but this time increasing the tire load, but still not moving the tire, we will see that the max deflection is proportional to the magnitude of the tire load. This indicates the tire behavior is proportional to two variables, the lateral force and the tire load. (Fortunately the side force in practice is a linear function of the tire load so this keeps the model simple) Now we will run the first experiment but this time we will rotate the tire with a constant angular velocity (think of those tune up machines at check up stations.) With the tire rolling at constant angular velocity if we apply a lateral force we will see that as the tire deflect, the part of the tire in contact with the floor keeps rolling and another part take its place, but this part also start to deflect, allowing the tire to move sideways with a velocity proportional to the tire rolling angular velocity. Notice that the tire does this without sliding as the part of it in contact with the floor never loses grip. Now if we increase the lateral force we will find that the lateral speed of the tire will also increase. This suggests that the side speed of the tire is proportional to the lateral force and also proportional to the rolling angular velocity. This is the tire elastic properties give then some kind of damping property when they are rolling. There is not known macroscopic mathematical model that can explain this behavior. The best we can do is to write the values of the experiment and use then to interpolate and extrapolate intermediate values. One thing we know is that the tires operates within some limits, and we can use those parameters to treat then as a constraint optimization problem, which is the Newton approach. When the tire is rolling and side slipping is not that the tire lost grip, nor that the tire is generating some force. It is rather that the tire have the capacity to absorb some of the lateral force by sliding and convert it to side velocity, this means that for the tire to loose grip a stronger force is necessary. In another word at rest a tire will lose grip under a much lower lateral force than if the tire was rolling. In Newton this behavior is treaded as a constrain optimization problem by asking the application how much side slip velocity is the tire allow to have before it is considered to lose grip, and how much of the lateral forces generated by the rigid body dynamics will be adsorbed by the tire at a given speed. It is the application responsibility to set these parameters as close to the real tire as it chooses. This approach allows for a very wide range of behaviors form arcade, to toy cars to very realistic.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

See also

NewtonVehicleSetTireSideSleepCoeficient

NewtonVehicleSetTireSideSleepCoeficient

void NewtonVehicleSetTireSideSleepCoeficient(
const NewtonJoint* vehicle,
void* tireId,
dFloat coeficient)
Set the coefficient that tell the engine how much of the lateral force can be absorbed by the tire.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat coeficient | - | side slip coeficient.

Return

nothing.

Remarks

See description of side slip on function NewtonVehicleSetTireMaxSideSleepSpeed

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

See also

NewtonVehicleSetTireMaxSideSleepSpeed

NewtonVehicleSetTireMaxLongitudinalSlideSpeed

void NewtonVehicleSetTireMaxLongitudinalSlideSpeed(
const NewtonJoint* vehicle,
void* tireId,
dFloat speed)
Set the maximum side slide velocity for the tire to be considered to lose traction.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat speed | - | maximum side speed before the vehicle is considered to loose side traction.

Return

nothing.

Remarks

The explanation of longitudinal slide is similar to the side slip, however it is not so critical to achieve realistic behavior. See description of side slip on function NewtonVehicleSetTireMaxSideSleepSpeed

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

See also

NewtonVehicleSetTireLongitudinalSlideCoeficient

NewtonVehicleSetTireLongitudinalSlideCoeficient

void NewtonVehicleSetTireLongitudinalSlideCoeficient(
const NewtonJoint* vehicle,
void* tireId,
dFloat coeficient)
Set the coefficient that tell the engine how much of the longitudinal force can be absorbed by the tire.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.
dFloat coefficient | - | longitudinal slide coefficient.

Return

nothing.

Remarks

The explanation of longitudinal slide is similar to the side slip, however it is not so critical to achieve realistic behavior. See description of side slip on function NewtonVehicleSetTireMaxSideSleepSpeed

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

See also

NewtonVehicleSetTireMaxLongitudinalSlideSpeed

NewtonVehicleTireIsAirBorne

int NewtonVehicleTireIsAirBorne(
const NewtonJoint* vehicle,
void* tireId)
Return a boolean value that tells the application if this tire is touching the ground.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

airborne state 1 on the air, 0 on the ground.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleTireLostSideGrip

int NewtonVehicleTireLostSideGrip(
const NewtonJoint* vehicle,
void* tireId)
Return a boolean value that tell the application if this tire lost side grip..

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

Grip state.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.

NewtonVehicleTireLostTraction

int NewtonVehicleTireLostTraction(
const NewtonJoint* vehicle,
void* tireId)
Return a boolean value that tell the application if this tire lost longitudinal traction.

Parameters

const NewtonJoint *vehicle | - | pointer to the vehicle joint.
void *tireId | - | index to current tire.

Return

traction state.

Remarks

The vehicle joint provides a rich set of interface functions to the application. Which function to use is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved.

Remarks

The parameters applied to a tire are reset to default values each time the update function is called. So the application should set the desired value in each simulation frame.

Remarks

This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics.


Introduction to Newton Game Dynamics

Tutorial 1: Getting started

This tutorial covers how to integrate Newton with your graphic engine.

Unpack the SDK, if you have not done it yet.

Open Visual studio and find the project Tutorials.dsw and double click on it.

Select the subproject Tutorial 1 getting started and make it the active project.

Select the file Tutorial.cpp and double click to open it in the editor.

At the beginning of the file and you will find the include section.

Add the line:

#include “newton.h”

#include "tutorial.h"
#include "HiResTimer.h"
#include "RenderPrimitive.h"
#include "Newton.h"

Find the main function on that file.

The first thing is the initialization of the graphic engine. In this case we encapsulated all Opengl initialization into one single function call. This represents your engine initialization of all major systems.

// Initialize opengl
InitOpenGl (argc, argv, "Newton Getting Started", DrawScene, NULL, Keyboard);

Next you will see another call to initialize the scene.

// Create the physics scene. This represents your engine scene initialization
InitScene();

Finally there is the opengl main loop call. This represents your game engine main loop.

Now find the function InitScene. This is where all the initialization of the physics engine happens.

For this tutorial we want to make the simplest possible physics scene, we are going to create a rigid body box, suspended and spinning on the vacuum.

You will see

// Create the newton world
nWorld = NewtonCreate
(NULL, NULL);

This makes and instance of the Newton world, and initializes all its internal structures. Ignore the two arguments for now, as they will be explained in the next tutorial. We hold the handle to the Newton world in a global variable.

Since it is not possible to get out of the opengl loop, we need to register an event to terminate the Newton world and all allocated recourses. This is what the line

onexit (Cleanup) does.

Next we need to create a rigid body, but for that we need to have the collision geometry first. (Rigid bodies must have collision geometry at all times).

So we create a box collision of the size of the graphical box.

// Create the collision shape
collision = NewtonCreateBox (nWorld, box.m_x * 2.0f, box.m_y * 2.0f, box.m_z * 2.0f, NULL);

The first argument to that call is the Newton world, followed by the box size. The last argument is the pointer to a transformation matrix used to offset the collision geometry from the origin of the rigid body. When Null the box is placed at the origin of the Body.

Now we create the rigid body and save into a global variable.

// Create the ridid body
ribidBodyBox = NewtonCreateBody (nWorld, collision);

After you are done using the collision object you must release it. Collision objects are the only objects in Newton that used reference count. This is done because other rigid bodies can share collision geometry. For example you can make several boxes of the same size and all of them may have the same collision geometry.

// Get rid of the collision
NewtonReleaseCollision (nWorld, collision);

When Newton creates a rigid body the mass is set to infinity, making the body static. We need to tell Newton we want this body to be dynamic. This is done by calling

// set the body mass and inertia
NewtonBodySetMassMatrix (ribidBodyBox, 1.0f, 1.0f, 1.0f, 1.0f);

Do not worry about the mass and inertia values, as they will be covered in the Dealing with Mass and Inertia tutorial.

We also need to position this body in the world

// Set the transformation matrix
dMatrix matrix (box.GetMatrix());
matrix.m_posit.m_x = 0.0f;
matrix.m_posit.m_y = 1.0f;
matrix.m_posit.m_z = 0.0f;

NewtonBodySetMatrix (ribidBodyBox, &matrix[0][0]);

There will be no forces or torques applied to this body. We just apply an initial angular velocity.

// Animate the body by setting the angular velocity
dVector omega (1.0f, 1.0f, 1.0f);
NewtonBodySetOmega (ribidBodyBox, &omega[0]);

That’s all for initialization, Now the main simulation loop.

Every frame OpenGl or your engine will make a call to the main simulation loop. For this tutorial this is the function DrawScene.

Notice that we need to get the elapse time since the last update. This is done by the utility function.

// get the time step
timeStep = timer.GetElapsedSeconds();

Next we call the NewtonUpdate to advance the world by this amount of time.

// update the Newton physics world
NewtonUpdate (nWorld, timeStep);

Now we need to retrieve the transformation matrices of bodies whose position changed during the world update call. For this example we are lucky we only have one body.

// get the matrix from the rigid body
dMatrix matrix;
NewtonBodyGetMatrix(ribidBodyBox, &matrix[0][0]);

Now we need to apply the transform to the graphical body.

// Set the matrix of the visual body
box.SetMatrix (matrix);

Finally we render the scene

// Render the object
glPushMatrix();
box.Render();
glPopMatrix();

And that covers the main loop.

The last thing is termination of the application. This happens when you hit the escape key or if you click on the close window button. Either case the function exit(0) is called.

This function will call all termination events in reverse order. In our case we only have the Cleanup function that will destroy the Newton world.

To navigate the demo use the keyboard keys w, s, a, d,

To change direction press the mouse button and move the mouse

This finishes this tutorial.


Tutorial 2: Using Callbacks

In Tutorial one we learned how to plug Newton into the graphic engine. We also manage to simulate a single rigid body, but what if we have a scene with thousands of physics entities. Scenes like this are very possible due the fact there is a lot of coherence in a physics environment. The action tends to be localized around the player and most of the objects in the scene are just sitting there waiting for the player of some other event to activate them.

The approach of tutorial one will require the application to re-define lots of its architecture in order to figure out what had changed after a physics updated call. It will probably have to modify its own data structure to keep shortcuts to bodies and joints.

Newton was designed to be as less intrusive as possible to the application. It was made to handle data sets of the order of several thousand bodies, without putting the burden of having to maintain these arrays onto the application. Newton uses an even driven paradigm to programming. When the application creates an object, it has the option of register a user data value and also some function pointers callbacks. Newton uses this function to communicate with the application every time some type of information has changed.

For this type of scenes we will also need some kind of graphic system to take care of the number of graphic objects in the scene. We will use a simple link list, we will add new objects to the end of the list and remove objects form the beginning.

Open up the project Tutorial 2 Using Callbacks, and open the file tutorial.cpp.

Find the function InitScene.

The first thing you will notice is that the function NewtonCreate is now passing two arguments. These are the pointers to the memory allocation and de-allocation functions

// Create the newton world
nWorld = NewtonCreate
(PhysicsAlloc, PhysicsFree);

Newton will call these functions whenever it needs memory and whenever some piece of memory needs to be freed. The application does not have to worry about memory be aligned; Newton takes care of that internally.

The allocation functions pass the memory size as an argument. The application can use this value to monitor how much memory the physics engine is using. Newton uses the concept of singleton internally, so it is possible that not all memory is de-allocated when the Newton world is destroyed. It is guarantied that all memory is de-allocated when the application terminates.

Next you will find that the pointer to the rigid body box now is a local variable. In fact there aren’t any pointers to any Newton object, except for world. It is difficult for beginner programmers to get used to not store the data with the application, but in time you will feel more comfortable with it.

We are going to abuse the capability of Newton for scene management. We will save the Graphic object as the rigid body user data. And we will also add a destructor callback with the rigid body.

// Store the graphic object with the rigid body.
NewtonBodySetUserData (floorBody, floor);

// Set a destructor for this rigid body
NewtonBodySetDestructorCallback (floorBody, PhysicsBodyDestructor);

The following lines are similar to tutorial one, except that we are adding 100 stacks of 10 bodies each of boxes (1000 boxes).

Note: if you do not have a high-end system you can just reduce any of the loop iteration indexes to something more manageable to you system.

Another thing different also is that we assign a force and torque callback as well as a transform call back function.

// Set the transform call back function
NewtonBodySetTransformCallback (boxBody, PhysicsSetTransform);

// Set the force and torque call back function
NewtonBodySetForceAndTorqueCallback (boxBody, PhysicsApplyForceAndTorque);

With this the application main render loop now do not have to worry about looping trough the array of object to determine when an object has changed position.

The rest of the code is the same as tutorial one.

When a body is about to be destroyed, it also destroys the graphic companion.

There are more objects in Newton that use the same callback mechanism: the materials, the joints, some special collisions geometry, the Newton world, and the iterator functions. We cannot cover all of then in one simple tutorial. But we will make a reference when any of these objects is introduced for the first time in a tutorial.

This is all for this tutorial.


Tutorial 3: Using Collision Tree part A

In Tutorial two we managed to create a small scene with few objects bouncing over a large background box. The problem with that demo was that we made everything using collision primitives. Modeling the world with collision primitives is not practical nor it is efficient. For that Newton provides two special kinds of collision primitives: User defined collision and Collision Trees.

These collision geometries are not as flexible as boxes, and sphere; because forces and velocity cannot affect them, however they can be moved by the application by directly manipulating the body transformation matrix. When these primitives are assigned to a rigid body, they nullify the mass property. The benefit these collision geometries provide to the application is that they can have any arbitrary shape or form. They can be made out of an unlimited number of polygons, therefore making them ideal to represent the static background collision geometry of the level.

User defined collision will be covered in the Advanced Collision tutorial. For now we will just say this collision geometry is useful for meshes with a known access pattern, like height maps or procedural geometries. For most geometry, collision tree is the best choice.

Open the project Tutorial 3 Using Collision Tree A. Find the function InitScene() the only difference between this function and the equivalent on the previous tutorial, is that now we load a pre made level geometry for the static background geometry. This done by the code fragment:

// Load level geometry and add it to the display list
level = new LevelPrimitive ("data\\level.dat", nWorld);

The rest of this file remained the same as before.

Open the file LevelPrimitive.cpp; this file implements all the functionality for loading and creating the background geometry.

The first thing done in the constructor of this class is

// Create the collision tree geometry
collision = NewtonCreateTreeCollision(nWorld, LevelCollisionCallback);

The second argument to this call is another Newton callback event function, which allows the application to extract and modify information stored in the user id with each face of the collision geometry. A common use for this callback is for debugging purpose by showing the outline of the geometry colliding with some other body. However the more advanced purpose for this function in to simulate special effects like: per surface material properties on the level geometry, conditional collision like surfaces that are collideable but break after impact (breaking glass), even modifiable surface material like dry surface that became wet after some event, or even special effect surfaces like conveyor belt. The possibilities are only limited by the expertise and creativity of the user.

Note: If your application is not going to modify per polygon attribute at run time.

You can still use the call back for debugging purpose, but you can gain a little bit of performance by just passing the null pointer to the Level collision call back for final release.

The next call is the

// prepare to create collsion geometry
NewtonTreeCollisionBeginBuild(collision);

This prepares the collision tree to begin to accept faces. Only one collision tree can be built at any one time, not doing so will create unpredictable results.

Next the data file is opened and an openly display list for fast rendering is created. The function iterate trough every face of the level geometry adding them to the collision tree and to the openly display list.

//
Open the level data
file = fopen (name, "rb");

m_list
= glGenLists(1);
glNewList (m_list, GL_COMPILE);

for
(fscanf (file, "%d", &count); count; fscanf (file,
"%d", &count)) {
// read the face
for (i = 0; i
< count; i ++) {
fscanf (file, "%(%f %f %f%)",
&point[i].m_x, &point[i].m_y, &point[i].m_z);
}
//
add this face to the collsion
tree
NewtonTreeCollisionAddFace(collision, count, &point[0].m_x,
sizeof (dVector), 1);

// add this face to the display
list
glBegin(GL_POLYGON);

// calculate the
normal
dVector normal ((point[1] - point[0]) * (point[2] –
point[0]));
normal = normal.Scale (1.0f / sqrtf (normal %
normal));
glNormal3f(normal.m_x, normal.m_y, normal.m_z);

    // submit the
face
for (i = 0; i < count; i ++) {
glVertex3f(point[i].m_x,
point[i].m_y, point[i].m_z);
}
// end the
list
glEnd();
}
glEndList ();

The line

// Add this face to the collision tree
NewtonTreeCollisionAddFace(collision, count, &point[0].m_x, sizeof (dVector), 1);

adds each face to the collision tree. Notice that the last parameter to this function is set to one. This is the user data that will be stored with the face in the tree. This parameter should be read from the data file and it should be associated with the type of surface of the level geometry. Usually an authoring tool specifies this, but since this is a very simple tutorial we will set to a hard coded value.

After all the faces are added to collision then the function call

// Finalize the collision tree build
NewtonTreeCollisionEndBuild(collision, 1);

tells Newton to compile the collision geometry. When the last parameter is set to zero, the tree compiler will make the collision tree out of the same geometry. This is fast and could be used for testing purposes. However for final versions this parameter should always be set to one. The memory saving can by for 200% to 1200%, and runtime performance gain can be as high as 5 time faster, depending on how much redundancy information is in the original data. The optimizer does not change the topology of the mesh it only extract redundant information.

The rest of the code create the rigid body just like we did before

//
Release the collision tree (release the app from book keeping Newton
objects
NewtonReleaseCollision (nWorld, collision);

// set
the global position of this body
NewtonBodySetMatrix (level,
&m_matrix[0][0]);

dVector boxP0;
dVector boxP1;
// get the position of the aabb of this
geometry
NewtonCollisionCalculateAABB (collision, &m_matrix[0][0],
&boxP0.m_x, &boxP1.m_x);

// Add some extra padding
the world size
boxP0.m_x -= 10.0f;
boxP0.m_y -=
10.0f;
boxP0.m_z -= 10.0f;
boxP1.m_x += 10.0f;
boxP1.m_y +=
10.0f;
boxP1.m_z += 10.0f;

// set the world
size
NewtonSetWorldSize (nWorld, &boxP0.m_x, &boxP1.m_x);

The only interesting thing here is that we use the side of the Level geometry to set the side of the Newton world.

Note: It is a good idea to simplify collision geometry as much as possible. Highly tessellated collision geometry for background geometry may look good but they do not improve much collision resolution, they however impose a costly burden on the constraint solver part of the engine. Newton is very good at optimizing the geometry and preprocessing contacts, but if you add too complex curve surfaces then you will have problems with performance and accuracy.

This is all for this tutorial.


Tutorial 4 Introduction to materials

So far we have been making rigid bodies with default physics properties, but this is not the way rigid bodies behave in the real world. Even though a real-time physics engine is only a very crude approximation or the real world, we still want to see macroscopic physical behavior like: elasticity, realistic friction, sound effects, particles effects, and even non realistic effects.

Newton’s answer for rigid body custom physics behavior is the material graph.

The material graph is an undirected graph, were the nodes are the material ID and the edges are the material interactions.

Material IDs are unique identifiers Newton uses to represent real like materials like: wood, concrete, metal etc. The material interactions are objects that store the definitions for the behavior of any two material IDs when they come into contact.

In this tutorial we are going to create a material graph consisting of tree different simple materials and one special material used to assist in controlling a small ball character.

Open the project tutorial4_IntroductionToMaterials.

Open the file Tutorial.cpp a go to function InitScene().

The first thing we need to do after the Newton world is created is to create the material graph for the entire scene. This is important because materials are expensive to make and they cannot be destroyed individually. So the application should decide early in the project how many materials are going to be used.

// set up all material and material interactions
SetupMaterials (nWorld);

Next we create our first controllable player character.

// Create a ball controlable by the player
AddBallCharacter ();

Open the file Materials.cpp
You will see four global variables used as material Ids

int woodID;
int metalID;
int levelID;
int
characterID;

Next there is a data structure the application can use to store the resources needed to provide feedback when two rigid bodies come into contact.

// structure used to hold game play especial
effects
struct SpecialEffectStruct
{
void
*soundHandle;
void *particleHandle;

// create the
resources for this materials effect here
void Init (char*
effectName)
{
}

// destroy all resources for this
material interaction here
void Detroy ()
{
}

//
play the impact sound
void PlayImpactSound (float
volume)
{
}

// play scratch sound
void
PlayScratchSound (float volume)
{
}

NewtonBody*
m_body0;
NewtonBody* m_body1;
dVector m_position;
float
m_contactMaxNormalSpeed;
float m_contactMaxTangentSpeed;
};

There is one instance of this structure for every different special effect the application wants to define.

// structures use to hold different materials interaction
SpecialEffectStruct wood_wood;
SpecialEffectStruct wood_metal;
SpecialEffectStruct wood_level;
SpecialEffectStruct metal_metal;
SpecialEffectStruct metal_level;
...

Find the function SetupMaterials. First all SpecialEffect instances are initialized

// initialize the material intaration here
wood_wood.Init ("wood_wood");
wood_metal.Init ("wood_metal");
wood_level.Init ("wood_level");
metal_metal.Init ("metal_metal");
metal_level.Init ("metal_level");

Next the application gets the default ID and sets the default physics behavior for the pair default ID – default ID

// get the default material ID
defaultID = NewtonMaterialGetDefaultGroupID (nWorld);

// Set default material properties
NewtonMaterialSetDefaultSoftness (nWorld, defaultID, defaultID, 0.05f);
NewtonMaterialSetDefaultElasticity (nWorld, defaultID, defaultID, 0.4f);
NewtonMaterialSetDefaultCollidable (nWorld, defaultID, defaultID, 1);
NewtonMaterialSetDefaultFriction (nWorld, defaultID, defaultID, 1.0f, 0.5f);
NewtonMaterialSetCollisionCallback (nWorld, woodID, woodID, &wood_wood, GenericContactBegin, GenericContactProcess, GenericContactEnd);

It is important that the application set the properties for the default-default material interactions. This is because when new materials are created, all possible permutations of the new IDs with existing ones get their properties from the default-default pair.

Now the application creates all Material IDs that will be used with this level

// create all materials ID
woodID = NewtonMaterialCreateGroupID(nWorld);
metalID = NewtonMaterialCreateGroupID(nWorld);
levelID = NewtonMaterialCreateGroupID(nWorld);
characterID = NewtonMaterialCreateGroupID(nWorld);

Then what follows is the tedious process of setting the individual material interactions for every combination of any two materials

// set the material properties for wood on wood
NewtonMaterialSetDefaultElasticity (nWorld, woodID, woodID, 0.3f);
NewtonMaterialSetDefaultFriction (nWorld, woodID, woodID, 1.1f, 0.7f);
NewtonMaterialSetCollisionCallback (nWorld, woodID, woodID, &wood_wood, GenericContactBegin, GenericContactProcess, GenericContactEnd);

Notice that almost all material interactions use the same tree material call back but with different user data. This is very common for setting background rigid bodies. Must of the time the application is only interested in visual reaction like friction or bounciness or particle effects, or audio effects like playing different sounds when two bodies collide or slide against each other. However some times it is necessary to customize and make decisions about how the application wants the collision of two bodies to be processed. This is the case of the ball character.

// set the material properties for character on level
NewtonMaterialSetDefaultElasticity (nWorld, levelID, characterID, 0.4f);
NewtonMaterialSetDefaultFriction (nWorld, levelID, characterID, 0.8f, 0.8f);
NewtonMaterialSetCollisionCallback (nWorld, levelID, characterID, &metal_level, GenericContactBegin, CharacterContactProcess, GenericContactEnd);

This material uses a different contact call back CharacterContactProcess. This function in turn calls the same default contact callback, but upon return it aligns the contact normal with the ball linear velocity vector, this rotation improves significantly the kinetic friction behavior of the ball with the background geometry.

Materials are not only limited to provide contact physics behaviors; they can be used to provide game logic and game play content. You can use materials in combination with static rigid bodies (bodies with infinite mass) to provided trigger volumes, like water pools, antigravity rooms. Also they can be used to create special effects like sliding surfaces or to create sensor areas for special bodies. These are advanced uses that will be covered in subsequent tutorials. We just wanted to emphasize the power of materials.

Now open the file Tutorial.cpp and find the function AddBallCharacter ().

This function creates a ball and assigns a special force and torque call back function.

Also, since this is going to be a player character, the auto disable functionality is turned off and the body is activated.

The function BallCharacterApplyForceAndTorque is very simple

It has two modes of operations:

In normal mode it applies a torque the ball making to roll, in fly mode it apply a force to the center of the ball. The force and torque are aligned to the camera heading.

To control the ball:

w, s, a, d move ball

space switch to fly mode.

Mouse left button down and drag change the camera orientation.

This is all for this tutorial.


Tutorial 5 Using joints

Constraints or joints are objects that connect two rigid bodies by canceling one or more degree of freedom between them. In this tutorial we are going to demonstrate how to use the different types of constraint provided with the Newton API. Newton possesses a very rich set of joints. It will be too much work to cover each one of them in a simple tutorial. We will only show four of the most commonly used joints: ball and socket, hinge, corkscrew and slider. The application should be able to determine how to implement its own features using other joints by comparing them to any of these four.

Open the project tutorial5_UsingJoints. The project is almost exactly the same as tutorial4_IntroductionToMaterials but it will add some extra functionality.

Open the file Tutorial.cpp a go to function InitScene().

After the ball character is created, it will add three different set of rigid bodies each one linked by one or more different joints.

// Add some joint configurations
AddRope (nWorld);
AddRollingBeats (nWorld);
AddDoubleSwingDoors (nWorld);

Open the file JointsTutorial.cpp

Find the function AddRope. This function will create a short rope made by connecting a few skinny rectangular rods with ball and socket joints.

For a rope to behave realistically the pieces should have an accurate moment of inertia.

// Calculate an accurate moment of inertia
mass =
2.0f;
Ixx = 0.7f * mass * (size.m_y * size.m_y + size.m_z *
size.m_z) / 12.0f;
Iyy = 0.7f * mass * (size.m_x * size.m_x +
size.m_z * size.m_z) / 12.0f;
Izz = 0.7f * mass * (size.m_x *
size.m_x + size.m_y * size.m_y) / 12.0f;

Then we find the position for the first piece in global space

// Set position for this root in global space
dMatrix
location (GetIdentityMatrix());
Location.m_posit.m_y = 11.5f;
Location.m_posit.m_z = -5.0f;

Next we create a common collision geometry to be shared by each rope segment

// Create a collision primitive to be shared by all links
collision = NewtonCreateBox (nWorld, size.m_x, size.m_y, size.m_z, NULL);

The following loop will create each rope piece and set it initial condition and parameter

for (i = 0; i < 6; i ++) {
// create the a graphic character (use a box as our body
box = new BoxPrimitive (location, size);

//create the rigid body
link1 = NewtonCreateBody (nWorld, collision);

// Set Material Id for this object
NewtonBodySetMaterialGroupID (link1, woodID);

// Save the pointer to the graphic object with the body.
NewtonBodySetUserData (link1, box);

// Set a destructor for this rigid body
NewtonBodySetDestructorCallback (link1, PhysicsBodyDestructor);

// Set the transform call back function
NewtonBodySetTransformCallback (link1, PhysicsSetTransform);

// Set the force and torque call back function
NewtonBodySetForceAndTorqueCallback (link1, hysicsApplyForceAndTorque);

// Set the mass matrix
NewtonBodySetMassMatrix (link1, mass, Ixx, Iyy, Izz);

// Set the matrix for both the rigid body and the graphic body
NewtonBodySetMatrix (link1, &location [0][0]);
PhysicsSetTransform (link1, &location [0][0]);

Then each two rope pieces are connected by a ball and socket joint. The first piece is an exception as it is connected to the world.

dVector pivot (location.m_posit);
pivot.m_y += size.m_y * 0.5f;

// Connect these two bodies by a ball and sockect joint
joint = NewtonConstraintCreateBall (nWorld, &pivot.m_x, link1, link0);

Each segment of the rope is only allowed to spin 10 degrees around the segment axis.

This will make the rope to looks mare realistic.

The ball and socket joint can set also a cone limit. But it won’t be used with this particular configuration. A value of zero for cone limit disables the joint limit altogether

// Set a twist angle to prevent the links to spin unrealistically
dVector pin (location.m_up.Scale (-1.0f));
NewtonBallSetConeLimits (joint, &pin.m_x, 0.0f, 10.0f * 3.1416f / 180.0f);

The rest prepares the loop for creating the next rope segment

link0 = link1;
Location.m_posit.m_y -= size.m_y;
}

Finally after the entire rope is completed, we release the collision geometry. That completes the rope setup

// Release the collision geometry when not need it
NewtonReleaseCollision (nWorld, collision);

Now find the function DoubleDoorUserCallback. This function creates a double wing door with two wood planks and two hinges. Setting up the bodies is almost the same as the previous function; so don’t have to explain it again.

The code fragment:

dVector pivot (location.m_posit);
dVector pin (location.m_up);
pivot.m_x += size.m_x * 0.5f;
// Connect these two bodies by a ball and sockect joint
joint = NewtonConstraintCreateHinge (nWorld, &pivot.m_x, &pin.m_x, link1, NULL);

// Set limit to the door
NewtonHingeSetUserCallback (joint, DoubleDoorUserCallback);

Create a hinge and set a function callback to update the hinge acceleration. The function

DoubleDoorUserCallback is called for every update to the hinge axis acceleration. Here the application can perform several things like: making a motor, setting joint limits, or making a hinge with friction (rusty hinge)

The third function, AddRollingBeats, follows the same procedure as DoubleDoorUserCallback except that it plugs a sliding joint and a corkscrew joint.

The only thing worth noticing here is that these joints, in addition to have their own update callback, they also keep their own private data and function destructor.

Also notice that the corkscrew joint controls two degrees of freedom, one rotational (a motor) and one linear with limits.

This concludes this tutorial.


Tutorial 6 Utilities functions

Many factors are involved when adopting a third party library into a project as opposed to implementing an in-house one. The developer should make a thorough evaluation of the pros and cons of taking that step because, in the case of serious projects, a wrong choice could translate into lost time, budgets overrun, mediocre turnout of features do to mediocre technology, etc. In many cases depending on the scope of the project this could turn into lost of millions of dollars.

A physics library is certainly not exempt from this process. Among the things the person evaluating the technology should take into consideration are:

-The application will delegate a lot of its own functionality to a black box API and in some case functionality will be duplicated if the third party API does not support a particular feature or does not have and interface for it.

-The API should be evaluated with a fine comb. The developer should test the existing functionality and make their decision base on that, she or he should not move forward counting on the promise of further features with new releases. New Features should be welcome but they should not be mandatory for the completion of the project at hand.

-What extra functionality can be extracted from the new API, given the fact that a great part of the project will be trusted to this black box piece of software? It is possible that the API can do everything it needs to do physically, but it does not provide the ability to be extended resulting in functionality duplication and hacked integrations.

-The API should have good technical support from the creator. This factor should be considered but it should not be the deciding one. The creator of the API should be considered as a last resource for resolving some technical problems not as the main source of information.

The Newton technical development team has realized that this extra functionality is very important when it comes to choose a physics engine, and also realized these features are very helpful to the developer. In this tutorial we will expose some of these extra features:

-Ray Casting

-Iterators functions

-Debug display

-Auto Sleep notification

Ray Casting:

Ray casting is by far the most important and practical of these features. As we mention before it has nothing to do with the physics part of the engine, but it uses the internal data structures of the engine to provide the application with an efficient and general purpose ray casting interface. The applications of ray casting in a project are enormous. Among them we can mention: Object picking, object placement, Line of sight for target shooting, assist in various AI algorithms, and many more.

In the tutorial we will demonstrate two uses for ray casting: Object placement and Object picking.

Open the file tutorial7_UtilityFuntionality\totorial7.cpp find the function InitScene

The very first few lines of this function create a big flat box to serve as the floor for this tutorial. Then after the floor creation the line

// position the camera relative to the floor
cameraEyepoint.m_y = FindFloor (cameraEyepoint.m_x, cameraEyepoint.m_z) + 10.0f;

position the camera eye point 10 meters above the floor.

Find the function FindFloor on the same file. This is the first and one of the simplest uses of the ray cast function. The goal it to shoot a vertical ray from some point up in the space to some point below and return the elevation of the closest static body in the scene.

For that we will shoot a ray for a point 1000 meters up and 1000 meters down, call the ray cast and collect the parametric intersection of the ray with the closet static body in the scene.

The ray cast function does not implement any predefined filtering technique based on bits field or objects list or anything like that. Instead it lets the application decide how rigid bodies will be filtered when the engine is scanning the scene along the ray from begin to end. The application does that by writing a special call back function that will be called each time the engine encounters a rigid body on its way.

In this case that function is RayCastPlacement. It is extremely simple, each time it is called it checks if the rigid body is static, if it is then checks if the parametric intersection is smaller than the previous one, and if it is, then saves the intersection parameter and returns that parameter to let Newton know that it should not check bodies beyond that point.

Upon return the floor is the interpolated value between the upper and lower points.

After this the function InitScene continues to populate the scene with some objects.

For this tutorial we will place two building structures by calling two similar functions.

CreateBuildingStruture_1 ();
CreateBuildingStruture_2 ();

Both functions are very similar so we well describe the first one.

Find the function CreateBuildingStruture_1 on the same file;

In this function we will place a parking lot type of structure in the scene. For that it is very important the initial position of the components touch each other starting from the ground and continuing building up. Once again we need to know the exact elevation of the floor to start building the structure.

Then the function set two different mass values 1kg and 200kg (the reason for the high mass ratios will be explained later) and what follows is a loop building a 10 story high structure by placing 4 lightweight support columns and a heavy platform of top in each iteration.

The second application for ray casting is object picking. First we need to define what objects picking is and how it is done.

Object picking is the act of pointing to a body on the screen and finding out what rigid body was rendered at that pixel position. This is done by knowing the fact that a pixel on the near clipping plane and a pixel on the far clipping plane with the same screen coordinate maps to a straight line on three the dimensional space. To do this we take the point at the mouse position, and set the near clipping coordinate z to zero. Then we invert transform this point by the view port matrix, the projection matrix, and the view matrix of the graphic API. We do the same for the second point except now we set z value to 1 for the far clipping plane.

Once we do that we have the two points defining the line on three d space. We should mention now that this is not an internal part of the physics engine it is just an explanation of how to obtain the point from the screen space and convert it to a line in tree d space. Must graphics engines provide this functionality as a built in feature. Next we collect all of the rigid bodies intersected by the ray going from the origin to the end of the line.

Next we store two values, the parametric intersection and the position of the point relative to the hit rigid body.

Next, as long as the mouse button is depressed we want to apply a force to the body at the hit point, that will tend to drive to zero the distance from that point in the body space and the same point on the line at the new mouse position. For that we use a penalty force.

To do all this we need to modify the mouse routine function which is found in the keyboard function. The big if-else statement is the part implementing the mouse position collection and doing the data manipulation. The important part is the implementation of the RayCastFilter callback function. This function is similar to the find floor except that it collects the closest dynamic body and also the pointer to the rigid body.

The object pick effect is done by implementing a new apply force and torque PhysicsApplyPickForce function callback which is set to the hit body when it is picked and reset back to the standard apply gravity when the body is let loose.

Iterators functions:

The Newton engine was designed with an event driven user interface. However there are situation in which an application needs to iterate through all the object is the scene collecting information about each object for many different purposes. These situations are rare but inevitable nevertheless. Examples of these cases are setting global state for all objects in the scene at the hit of a button, or displaying debug information for objects in global manner, and other application dependent uses.

The Newton engine comes with two kind or Iterators, one for rigid bodies and the second is almost exclusive for debugging the collision geometry in the scene. The second iterator comes handy when the behavior of some objects is the scene is odd, or when making complex collision objects. The first one can be used for a variety of purposes.

In this tutorial we use the Body Set globally the state of auto sleeping for each body, and also to display the collision geometry of each body on the scene.

It is important to emphasize that iterators are helper functions designed to assist the application in debugging and balancing the physics scene. These functions are by not mean efficient and the application should not rely on them for runtime functionality as they will severally degrade the performance of the engine.

Find The function Keyboard(), and you will see that two new interface keys had been added. F1 and F2

The Key F1 will toggle a global auto sleep flag and call the Iterator function NewtonWorldForEachBodyDo passing the pointer to the function callback ToggleAutoSleep

The function ToggleAutoSleep will be called for each body in the scene changing the state of the body from sleeping to awake, or vise versa depending on the global auto sleep flag, the function also forces the body to wake up state.

The second key F2 toggles a global debug flag to indicate the main render loop if it has to render the debug geometry of each collision geometry in the scene. If you look at the end of the function DrawScene, the if statement will call the DebugShowCollision

The function Debug collision implements two nested loops, one the outer one iterates through each body on the scene passing the callback DebugShowBodyCollision

And the DebugShowBodyCollision iterate through each collision geometry in the scene by calling DebugShowGeometryCollision. It should be pointed out that these functions are not meant to be efficient and they will render all the bodies on the scene, therefore they can degrade performance significantly on large scene. The application should implement more efficient versions of these functions by adding some kind of filtering.

Active Bodies Tracking

The third facture we are going to used is the Activation Deactivation Notification callback.

This is all for this tutorial


Tutorial 7 Character Controller

This is our first advanced tutorial. We will use several features in cooperation to create a character that will be controlled by forces and torque, and at the same time it will stay in an upright position.

The elements we are going to use are: compound collision primitive with identification, especial joint called up vector, and special force and torque. This is a technical demo and therefore it will focus in showing the minimum amount of code needed to get the character running, features like: jumping, moving up and down ramps and stairs, crouching etc. are left to the application to implement.

The framework for this tutorial is taken from tutorial Introduction to Materials.

Open project Tutorial6_CharaterController in the function InitScene() you will see that the ball character is replaced by the call to

// Create a ball controllable by the player
AddCharacter (nWorld);

Open the file and find the function AddCharacter this function creates a rigid body with a compound collision geometry.

The collision geometry is made out tree spheres and one skinny rod used to sense the floor under the character. Each part of the collision geometry has a generic ID that will be used later on by the contact callback in order to determine what part of the body produced the collision.

// Place a sphere at the center
collisionParts[count]
= NewtonCreateSphere (nWorld, size.m_x * 0.75f, NULL);
// set a
identifier for this collsion
NewtonConvexCollisionSetUserID
(collisionParts[count], SPHERE_COLLISION);
count ++;

//
place a sphere on the upper half
offsetMatrix.m_posit.m_y =
size.m_y * 0.25f;
collisionParts[count] = NewtonCreateSphere
(nWorld, size.m_x * 0.75f, &offsetMatrix[0][0]);
// set a
identifier for this collsion
NewtonConvexCollisionSetUserID
(collisionParts[count], SPHERE_COLLISION);
count ++;

//
place a sphere on the lower half
offsetMatrix.m_posit.m_y =
-size.m_y * 0.25f;
collisionParts[count] = NewtonCreateSphere
(nWorld, size.m_x * 0.75f, &offsetMatrix[0][0]);
// set a
identifier for this collision
NewtonConvexCollisionSetUserID
(collisionParts[count], SPHERE_COLLISION);
count ++;

// use
a long box rod for support on the ground
offsetMatrix.m_posit.m_y
= -size.m_y * 0.25f;
collisionParts[count] = NewtonCreateBox
(nWorld, 0.05f, size.m_y, 0.05f, &offsetMatrix[0][0]);
// set
a identifier for this collsion
NewtonConvexCollisionSetUserID
(collisionParts[count], BOX_COLLISION);
count ++;

// create
the compound collision
collision = NewtonCreateCompoundCollision
(nWorld, count, collisionParts);

The rest of this function follows the same model of all other rigid body creation, with the exception that this rigid body is constrained to the world by an up vector joint. This joint will allow the rigid body to translate in all three directions but it only allows rotation about the joint pin axis.

// Add an up vector constraint to help in keeping the
body upright
NewtonJoint* upVector;
dVector upDirection (0.0f,
1.0f, 0.0f);
upVector = NewtonConstraintCreateUpVector (nWorld,
&upDirection.m_x, chrBody);

The function CharacterApplyForceAndTorque applies a torque and a force to the body. This function uses information set up by the camera and keyboard in order to push and steer the body to the direction and orientation desired by the player.

The last interesting part of this project is the function callback CharacterContactProcess in the file materials.cpp

Here after the contact is processed by the base process contact call back, the function finds out which one of the bodies belongs to the character.

// Apply the default behavio
GenericContactProcess (material, contact);

// Get the spherical body, it is the body with non zero mass
// This is a quit and dirty way to determine the player body, but it no safe,
//it only work in this case because one of the two bodies is the terrain which we now have //infinite mass.

// A better way to do this is by getting the user data and finding some object identifier // stored with the user data.

body = g_currectEffect->m_body0;
NewtonBodyGetMassMatrix (g_currectEffect->m_body0, &mass, &Ixx, &Iyy, &Izz);
if (mass == 0.0f) {
body = g_currectEffect->m_body1;
NewtonBodyGetMassMatrix (g_currectEffect->m_body1, &mass, &Ixx, &Iyy, &Izz);
}

Then once we have the character rigid body we ask Newton what part of the body is generating this contact

// Get the collision ID
collisionID = NewtonMaterialGetBodyCollisionID(material, body);

If the contact was produced by one of the spheres then we tell Newton not to use friction with it, this will allow the body to slide without rolling when it hit a wall or vertical obstacles.

if (collisionID == SPHERE_COLLISION) {
// disable fiction calculation for sphere collision
NewtonMaterialSetContactFrictionState (material, 0, 0);
NewtonMaterialSetContactFrictionState (material, 0, 1);

If the contact was produced by the skinny rod then we align the tangent surface direction with the linear velocity vector of the body.

This is all for this tutorial


Credits

 We want to express our thanks to the people that helped us with the beta testing of the Newton physics engine. With their demos, suggestions and feedback we were able to find bugs faster, improve the engine interface and provide better engine functionality.

Special thanks to (in alphabetical order):

Bill Merrill
Bruno Cesteiro
Chris Leathley
Jon Walton
Sascha Willems
Thomas Oppl
Tim FitzRandolph
Tomasz Zielinski
Truevision3D, LLC

We really appreciate your time and dedication.

The assets used in the SDK tutorials were provide by Bruno Cesteiro.